#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail

if [[ -z "$JOB_TYPE" ]]; then
    exit 0
fi

SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"

source $SCRIPT_ROOT/../lib/common.sh

ORIGIN_ORG="eks-distro-pr-bot"
UPSTREAM_ORG="aws"

MAIN_BRANCH="${PULL_BASE_REF:-main}"

cd ${SCRIPT_ROOT}/../../
git config --global push.default current
git config user.name "EKS Distro PR Bot"
git config user.email "aws-model-rocket-bots+eksdistroprbot@amazon.com"
git config remote.origin.url >&- || git remote add origin git@github.com:${ORIGIN_ORG}/eks-distro.git
git config remote.upstream.url >&- || git remote add upstream https://github.com/${UPSTREAM_ORG}/eks-distro.git

build::common::echo_and_run git status

# Files have already changed, stash to perform rebase
build::common::echo_and_run git stash
build::common::echo_and_run retry git fetch upstream

build::common::echo_and_run git checkout $MAIN_BRANCH
# there will be conflicts before we are on the bots fork at this point
# -Xtheirs instructs git to favor the changes from the current branch
build::common::echo_and_run git rebase -Xtheirs upstream/$MAIN_BRANCH

if [ "$(git stash list)" != "" ]; then
    build::common::echo_and_run git stash pop
    build::common::echo_and_run git status
fi

function pr:create()
{
    local -r pr_title="$1"
    local -r commit_message="$2"
    local -r pr_branch="$3"
    local -r pr_body="$4"

    git diff --staged
    local -r files_added=$(git diff --staged --name-only)
    if [ "$files_added" = "" ]; then
        return 0
    fi

    git checkout -B $pr_branch
    git commit -m "$commit_message" || true

    if [ "$JOB_TYPE" != "periodic" ]; then
        return 0
    fi

    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'

    gh auth login --with-token < /secrets/github-secrets/token
    local -r pr_exists=$(gh pr list | grep -c "$pr_branch" || true)
    if [ $pr_exists -eq 0 ]; then
        echo "Creating PR $pr_title"
        gh pr create --title "$pr_title" --body "$pr_body" --base $MAIN_BRANCH
    fi
}

function pr::create::pr_body(){
    pr_body=""
    case $1 in
    attribution)
        pr_body=$(cat <<'EOF'
This PR updates the ATTRIBUTION.txt files across all dependency projects if there have been changes.

These 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!
EOF
)
        ;;
    checksums)
        pr_body=$(cat <<'EOF'
This PR updates the CHECKSUMS files across all dependency projects if there have been changes.

These 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!
EOF
)
        ;;
    makehelp)
        pr_body=$(cat <<'EOF'
This PR updates the Help.mk files across all dependency projects if there have been changes.
EOF
)
        ;;
    go-mod)
        pr_body=$(cat <<'EOF'
This PR updates the checked in go.mod and go.sum files across all dependency projects to support automated vulnerability scanning.
EOF
)
        ;;
    *)
        echo "Invalid argument: $1"
        exit 1
        ;;
    esac
    PROW_BUCKET_NAME=$(echo $JOB_SPEC | jq -r ".decoration_config.gcs_configuration.bucket" | awk -F// '{print $NF}')
    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")

    printf "$full_pr_body"
}

function pr::create::attribution() {
    local -r pr_title="Update ATTRIBUTION.txt files"
    local -r commit_message="[PR BOT] Update ATTRIBUTION.txt files"
    local -r pr_branch="attribution-files-update-$MAIN_BRANCH"
    local -r pr_body=$(pr::create::pr_body "attribution")

    pr:create "$pr_title" "$commit_message" "$pr_branch" "$pr_body"
}

function pr::create::checksums() {
    local -r pr_title="Update CHECKSUMS files"
    local -r commit_message="[PR BOT] Update CHECKSUMS files"
    local -r pr_branch="checksums-files-update-$MAIN_BRANCH"
    local -r pr_body=$(pr::create::pr_body "checksums")

    pr:create "$pr_title" "$commit_message" "$pr_branch" "$pr_body"
}

function pr::create::help() {
    local -r pr_title="Update Makefile generated help"
    local -r commit_message="[PR BOT] Update Help.mk files"
    local -r pr_branch="help-makefiles-update-$MAIN_BRANCH"
    local -r pr_body=$(pr::create::pr_body "makehelp")

    pr:create "$pr_title" "$commit_message" "$pr_branch" "$pr_body"
}

function pr::create::go-mod() {
    local -r pr_title="Update go.mod files"
    local -r commit_message="[PR BOT] Update go.mod files"
    local -r pr_branch="go-mod-update-$MAIN_BRANCH"
    local -r pr_body=$(pr::create::pr_body "go-mod")

    pr:create "$pr_title" "$commit_message" "$pr_branch" "$pr_body"
}

function pr::file:add() {
    local -r file="$1"

    if git check-ignore -q $FILE; then
        continue
    fi

    local -r diff="$(git diff --ignore-blank-lines --ignore-all-space $FILE)"
    if [[ -z $diff ]]; then
        continue
    fi

    git add $file
}

echo "Adding Checksum files"
# Add checksum files
for FILE in $(find . -type f -name CHECKSUMS); do
    pr::file:add $FILE
done

# This file is being added as it may have been updated by the last lines of ./build/lib/update_go_versions.sh,
# which replaces the go version in this script with the go version(s) in the builder base if they are newer
# when running `make update-checksum-files`
git add ./build/lib/install_go_versions.sh

# stash attribution and help.mk files
git stash --keep-index

pr::create::checksums

git checkout $MAIN_BRANCH

if [ "$(git stash list)" != "" ]; then
    build::common::echo_and_run git stash pop
    build::common::echo_and_run git status
fi

echo "Adding ATTRIBUTION files"
# Add attribution files
for FILE in $(find . -type f \( -name "*ATTRIBUTION.txt" ! -path "*/_output/*" \)); do
    pr::file:add $FILE
done

# stash help.mk files
git stash --keep-index

pr::create::attribution

git checkout $MAIN_BRANCH

if [ "$(git stash list)" != "" ]; then
    build::common::echo_and_run git stash pop
    build::common::echo_and_run git status
fi

echo "Adding Help.mk files"

# Add help.mk/Makefile files
for FILE in $(find . -type f \( -name Help.mk -o -name Makefile \)); do
    pr::file:add $FILE
done

# stash go.sum files
git stash --keep-index

pr::create::help

git checkout $MAIN_BRANCH

if [ "$(git stash list)" != "" ]; then
    build::common::echo_and_run git stash pop
    build::common::echo_and_run git status
fi

echo "Adding go.mod and go.sum files"
# Add go.mod files
for FILE in $(find . -type f \( -name go.sum -o -name go.mod \)); do
    git check-ignore -q $FILE || git add $FILE
done

pr::create::go-mod


#!/usr/bin/env bash
# Copyright 2020 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o errexit
set -o nounset
set -o pipefail
shopt -s globstar

PROJECT="$1"
TARGET="$2"

MAKE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)"
PROJECT_ROOT=$MAKE_ROOT/$PROJECT

OUTPUT_DIR=$MAKE_ROOT/_output
mkdir -p $OUTPUT_DIR
touch $OUTPUT_DIR/total_summary.txt

function build::attribution::generate(){
    make -C $PROJECT_ROOT $TARGET

    if ls $PROJECT_ROOT/_output/**/summary.txt 1> /dev/null 2>&1; then
        for summary in $PROJECT_ROOT/_output/**/summary.txt; do
            sed -i "s/+.*=/ =/g" $summary
            awk -F" => " '{ count[$1]+=$2} END { for (item in count) printf("%s => %d\n", item, count[item]) }' \
                $summary $OUTPUT_DIR/total_summary.txt | sort > $OUTPUT_DIR/total_summary.tmp && mv $OUTPUT_DIR/total_summary.tmp $OUTPUT_DIR/total_summary.txt
        done
    fi
}

# Some projects have specific folders for different kubernetes release
# dynamically find all versions to avoid having to update with every release
RELEASE_FOLDER=$(find $PROJECT_ROOT -type d -name "1-*")

if [ -z "${RELEASE_FOLDER}" ]; then
    build::attribution::generate
else
    LAST_GIT_TAG=""
    LAST_RELEASE_BRANCH=""
    for release in $(cat $MAKE_ROOT/release/SUPPORTED_RELEASE_BRANCHES) ; do
        export RELEASE_BRANCH="$release"

        GIT_TAG="$(cat $PROJECT_ROOT/$release/GIT_TAG)"
        if [ "$GIT_TAG" != "$LAST_GIT_TAG" ] || [ $TARGET == "update-go-mods" ]; then
            # clean before regenerating to ensure there are no intermediate files left around
            make -C $PROJECT_ROOT clean clean-go-cache
            build::attribution::generate $release
        else
            # if the git_tags match across release branches, save the output state to avoid
            # rebuilding/regenerating
            if [[ $TARGET == *"checksums"* ]]; then
                echo "Copying $LAST_RELEASE_BRANCH CHECKSUMS to $release"
                mkdir -p $PROJECT_ROOT/_output/$release
                sed "s/$LAST_RELEASE_BRANCH/$release/" $PROJECT_ROOT/$LAST_RELEASE_BRANCH/CHECKSUMS > $PROJECT_ROOT/$release/CHECKSUMS
            fi

            if [[ $TARGET == *"attribution"* ]]; then
                echo "Copying $LAST_RELEASE_BRANCH ATTRIBUTION to $release"
                mkdir -p $PROJECT_ROOT/_output/$release
                cp -rf $PROJECT_ROOT/$LAST_RELEASE_BRANCH/*TTRIBUTION.txt $PROJECT_ROOT/$release
            fi
        fi
        LAST_GIT_TAG="$GIT_TAG"
        LAST_RELEASE_BRANCH="$release"
    done
fi

make -C $PROJECT_ROOT clean clean-go-cache


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Generates release on GitHub.
# IMPORTANT!! GIT_TAG for release must already exist.
set -e
set -o pipefail
set -x

GIT_TAG="${1?...}"
CHANGELOG_FILEPATH="${2?...}"
INDEX_FILEPATH="${3?...}"

# Removes the first three lines to get rid of H1 headers and an empty line and the
# changelog highlights from the changelog and first four lines from the index.md
# including the additional information and the empty line for the github release
# docs
# The H1 headers are larger than the release titles on GitHub, and it
# looks confusing with them.
releaseNotes="$(sed '1,3d' "$CHANGELOG_FILEPATH")

$(sed '1,4d' "$INDEX_FILEPATH")"

gh release create "$GIT_TAG" --title "EKS Distro $GIT_TAG Release" --notes "$releaseNotes" --repo "aws/eks-distro"


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -o pipefail
set -x

PR_BRANCH="${1?...}"
PR_TITLE="${2?...}"

echo "pushing..."
git push origin "${PR_BRANCH}"
echo "pushed!"

PR_REPO="eks-distro"

GITHUB_USERNAME_REGEX="s/(https:\/\/|git@)github\.com(\/|:)(.*)\/${PR_REPO}.git/\3/p"
GITHUB_USERNAME=$(git remote get-url origin | sed -n -E "$GITHUB_USERNAME_REGEX")
if [ -z "$GITHUB_USERNAME" ]
then
echo "Failed to parse Github username! Ensure you have a remote 'origin' set." && return 1
fi

pr_arguments=(
  --head "${GITHUB_USERNAME}:${PR_BRANCH}"
  --repo "aws/${PR_REPO}"
  --title "${PR_TITLE}"
  --web
  --body "By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice."
)

gh pr create "${pr_arguments[@]}"


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -x

BASE_DIRECTORY=$(git rev-parse --show-toplevel)
RELEASE_BRANCH=$(cat "${BASE_DIRECTORY}"/release/DEFAULT_RELEASE_BRANCH)
RELEASE_ENVIRONMENT=${RELEASE_ENVIRONMENT:-production}
RELEASE=$(cat "${BASE_DIRECTORY}"/release/"${RELEASE_BRANCH}"/"${RELEASE_ENVIRONMENT}"/RELEASE)
RELEASE_TAG="eks-${RELEASE_BRANCH}-${RELEASE}"

RELEASE_CRD="https://distro.eks.amazonaws.com/kubernetes-${RELEASE_BRANCH}/kubernetes-${RELEASE_BRANCH}-eks-${RELEASE}.yaml"
ECR_BASE="public.ecr.aws/eks-distro"

RELEASE_GIT_TAG=$(cat "${BASE_DIRECTORY}"/projects/kubernetes/release/${RELEASE_BRANCH}/GIT_TAG)

while read -r image_uri; do
  docker pull "$image_uri"
done < <(curl "${RELEASE_CRD}" | sed -n -e "s|^.*uri: \\($ECR_BASE\\)|\1|p")

# These are not in the CRD
docker pull "${ECR_BASE}/kubernetes/kube-proxy-base:${RELEASE_GIT_TAG}-${RELEASE_TAG}"
docker pull "${ECR_BASE}/kubernetes/go-runner:${RELEASE_GIT_TAG}-${RELEASE_TAG}"


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -eo pipefail
BASEDIR=$(dirname "$0")
cd ${BASEDIR}

function install_ecr_public {
    if [ ! -f ~/.aws/models/ecr-public/2020-10-30/service-2.json ]
    then
        echo "Installing ECR Public plugin"
        aws configure add-model \
          --service-model file://ecr-public-2020-10-30.api.json \
          --service-name ecr-public
    fi
}

function create_ecr_public_policy {
    POLICY_NAME=ECRPublicAccess
    if aws iam list-policies \
         --query "Policies[?PolicyName=='${POLICY_NAME}'].[PolicyName]" \
         --output text | grep "${POLICY_NAME}" >/dev/null
    then
        return
    fi
    echo "Creating ECR Public policy"
    aws iam create-policy \
      --policy-name ${POLICY_NAME} \
      --policy-document \
      file://ecr-public-policy.json
}

function login_ecr_public {
    # Token expires after 12 hours
    TOKEN=$(aws --region us-east-1 ecr-public get-authorization-token \
        --output=text \
        --query 'authorizationData.authorizationToken')

    DOCKER_CONFIG=${DOCKER_CONFIG:-"~/.docker"}
    if command -v docker &> /dev/null && docker info > /dev/null 2>&1; then
        echo $TOKEN | \
            base64 --decode | \
            cut -d: -f2 | \
            docker login -u AWS --password-stdin https://public.ecr.aws
    else
        mkdir -p $DOCKER_CONFIG
        if [ ! -f $DOCKER_CONFIG/config.json ]; then
            echo '{}' > $DOCKER_CONFIG/config.json
        fi
        # Gross, abominable hack until ecr-credential-helper supports public ECR
        # See https://github.com/awslabs/amazon-ecr-credential-helper/issues/248
        cat $DOCKER_CONFIG/config.json | \
            jq --arg TOKEN $TOKEN '.auths."public.ecr.aws".auth = $TOKEN' > $DOCKER_CONFIG/config.json.new
        cp $DOCKER_CONFIG/config.json.new $DOCKER_CONFIG/config.json
    fi
}

function create_private_repository {
    local -r repository_name="${1?First argument is repository name}"
    aws ecr describe-repositories \
      --query "repositories[*].repositoryName" \
      --output text \
      --repository-name $repository_name 2>/dev/null ||
    aws ecr create-repository \
      --repository-name $repository_name \
      --image-scanning-configuration scanOnPush=true
}

function create_public_repository {
    local -r repository_name="${1?First argument should be repository name}"
    local -r file_prefix="$(echo $repository_name | awk -F/ '{print $(NF)}')"
    local -r input="create-public-repo-input.json"
    # Yes, they put a _space_ in "ARM 64"
    cat << EOF > $input
{
    "repositoryName": "$repository_name",
    "catalogData": {
        "description": "Development $(cat image-docs/${file_prefix}-description)",
        "architectures": [
            "x86-64",
            "ARM 64"
        ],
        "operatingSystems": [
            "linux"
        ],
	"aboutText": "Development $(awk '{printf "%s\\n", $0}' image-docs/${file_prefix}-about.md)",
	"usageText": "$(awk '{printf "%s\\n", $0}' image-docs/${file_prefix}-usage.md)"
    }
}
EOF
    aws ecr-public describe-repositories \
      --query "repositories[*].repositoryName" \
      --output text \
      --repository-name $repository_name 2>/dev/null ||
    aws ecr-public create-repository \
      --repository-name $repository_name \
      --cli-input-json file://$input
    rm -f $input
}

function create_all_private_repositories {
    create_private_repository "coredns/coredns"
    create_private_repository "etcd-io/etcd"
    create_private_repository "kubernetes-csi/external-attacher"
    create_private_repository "kubernetes-csi/external-provisioner"
    create_private_repository "kubernetes-csi/external-resizer"
    create_private_repository "kubernetes-csi/external-snapshotter/csi-snapshotter"
    create_private_repository "kubernetes-csi/external-snapshotter/snapshot-controller"
    create_private_repository "kubernetes-csi/external-snapshotter/snapshot-validation-webhook"
    create_private_repository "kubernetes-csi/livenessprobe"
    create_private_repository "kubernetes-csi/node-driver-registrar"
    create_private_repository "kubernetes-sigs/aws-iam-authenticator"
    create_private_repository "kubernetes-sigs/metrics-server"
    create_private_repository "kubernetes/go-runner"
    create_private_repository "kubernetes/kube-apiserver"
    create_private_repository "kubernetes/kube-controller-manager"
    create_private_repository "kubernetes/kube-proxy"
    create_private_repository "kubernetes/kube-proxy-base"
    create_private_repository "kubernetes/kube-scheduler"
    create_private_repository "kubernetes/pause"
}

function create_all_public_repositories {
    create_public_repository "coredns/coredns"
    create_public_repository "etcd-io/etcd"
    create_public_repository "kubernetes-csi/external-attacher"
    create_public_repository "kubernetes-csi/external-provisioner"
    create_public_repository "kubernetes-csi/external-resizer"
    create_public_repository "kubernetes-csi/external-snapshotter/csi-snapshotter"
    create_public_repository "kubernetes-csi/external-snapshotter/snapshot-controller"
    create_public_repository "kubernetes-csi/external-snapshotter/snapshot-validation-webhook"
    create_public_repository "kubernetes-csi/livenessprobe"
    create_public_repository "kubernetes-csi/node-driver-registrar"
    create_public_repository "kubernetes-sigs/aws-iam-authenticator"
    create_public_repository "kubernetes-sigs/metrics-server"
    create_public_repository "kubernetes/go-runner"
    create_public_repository "kubernetes/kube-apiserver"
    create_public_repository "kubernetes/kube-controller-manager"
    create_public_repository "kubernetes/kube-proxy"
    create_public_repository "kubernetes/kube-proxy-base"
    create_public_repository "kubernetes/kube-scheduler"
    create_public_repository "kubernetes/pause"
}

function update_public_repository {
    local -r repository_name="${1?First argument is repository_name}"
    local -r file_prefix="$(echo $repository_name | awk -F/ '{print $(NF)}')"
    # requires CLI v2
    aws ecr-public put-repository-catalog-data \
        --repository-name $repository_name \
        --catalog-data operatingSystems=Linux,logoImageBlob=$(cat eks-distro-img-large.png |base64)
    local -r input="update-public-repo-input.json"
    cat << EOF > base-$input
{
    "repositoryName": "$repository_name",
    "catalogData": {
        "architectures": [
            "x86-64",
            "ARM 64"
        ],
        "operatingSystems": [
            "Linux"
        ]
    }
}
EOF
    jq --arg about "$(<image-docs/${file_prefix}-about.md)" '.catalogData.aboutText=$about' base-${input} > about-$input
    jq --arg usage "$(<image-docs/${file_prefix}-usage.md)" '.catalogData.usageText=$usage' about-${input} > $input
    aws ecr-public put-repository-catalog-data \
      --cli-input-json file://$input
    rm base-$input about-${input} ${input}
}

function delete_public_repository {
    local -r repository_name="${1?First argument is repository name}"
    if ! aws ecr-public describe-repositories \
           --query "repositories[*].repositoryName" \
           --repository-name $repository_name 2>/dev/null
    then
        return
    fi
    REGISTRY_ID=$(aws ecr-public describe-registries --query registries[0].registryId --output text)
    for digest in $(aws ecr-public describe-images --registry-id  $REGISTRY_ID --repository-name $repository_name --query imageDetails[*].imageDigest --output text); do
        aws ecr-public batch-delete-image --registry-id  $REGISTRY_ID --repository-name $repository_name --image-ids imageDigest=$digest
    done
    aws ecr-public delete-repository --registry-id  $REGISTRY_ID --repository-name $repository_name
}

function retag_private_image {
    local -r repository_name="${1?First argument is repository name}"
    local -r image_tag="${2?Second argument is image tag}"
    local -r new_tag="${3?Third argument is new tag}"
    MANIFEST=$(aws ecr batch-get-image --repository-name ${repository_name} --image-ids imageTag=${image_tag} --query 'images[].imageManifest' --output text)
    aws ecr put-image --repository-name ${repository_name} --image-tag ${new_tag} --image-manifest "$MANIFEST"
}

COMMAND="${1}"
shift
case "${COMMAND}" in
install-ecr-public)
  install_ecr_public
  ;;
create-ecr-public-policy)
  export AWS_DEFAULT_REGION=us-east-1
  export AWS_REGION=us-east-1
  create_ecr_public_policy
  ;;
login-ecr-public)
  export AWS_DEFAULT_REGION=us-east-1
  export AWS_REGION=us-east-1
  login_ecr_public
  ;;
create-public-repository)
  export AWS_DEFAULT_REGION=us-east-1
  export AWS_REGION=us-east-1
  create_public_repository ${1}
  ;;
create-all-private-repositories)
  create_all_private_repositories
  ;;
create-all-public-repositories)
  export AWS_DEFAULT_REGION=us-east-1
  export AWS_REGION=us-east-1
  create_all_public_repositories
  ;;
create-private-repository)
  create_private_repository ${*}
  ;;
update-public-metadata)
  export AWS_DEFAULT_REGION=us-east-1
  export AWS_REGION=us-east-1
  update_public_repository ${*}
  ;;
delete-public-repository)
  export AWS_DEFAULT_REGION=us-east-1
  export AWS_REGION=us-east-1
  delete_public_repository ${*}
  ;;
retag-private-image)
  retag_private_image ${*}
  ;;
*)
  echo "Please specify a supported command"
  exit 1
  ;;
esac


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

readonly ECR_REPOS=(
    coredns/coredns
    etcd-io/etcd
    kubernetes-csi/external-attacher
    kubernetes-csi/external-provisioner
    kubernetes-csi/external-resizer
    kubernetes-csi/external-snapshotter/csi-snapshotter
    kubernetes-csi/external-snapshotter/snapshot-controller
    kubernetes-csi/external-snapshotter/snapshot-validation-webhook
    kubernetes-csi/livenessprobe
    kubernetes-csi/node-driver-registrar
    kubernetes-sigs/aws-iam-authenticator
    kubernetes-sigs/metrics-server
    kubernetes/go-runner
    kubernetes/kube-apiserver
    kubernetes/kube-controller-manager
    kubernetes/kube-proxy
    kubernetes/kube-proxy-base
    kubernetes/kube-scheduler
    kubernetes/pause
)
for image in "${ECR_REPOS[@]}"; do
    aws ecr describe-repositories --repository-name $image 2>/dev/null ||
    aws ecr create-repository \
        --repository-name $image \
        --image-scanning-configuration  scanOnPush=true || true
done


#!/usr/bin/env bash -xe
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

./ecr-command.sh install-ecr-public
./ecr-command.sh create-ecr-public-policy
./ecr-command.sh login-ecr-public

./ecr-command.sh delete-public-repository test-repository
./ecr-command.sh create-public-repository test-repository
./ecr-command.sh update-public-metadata test-repository
./ecr-command.sh delete-public-repository test-repository

./ecr-command.sh create-private-repository test-repository
#./ecr-command.sh retag-private-image test-repository scratch 1.0 2.0


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -eo pipefail

BASEDIR=$(dirname "$0")
source ${BASEDIR}/set_environment.sh
$PREFLIGHT_CHECK_PASSED || exit 1

function retry {
  local n=1
  local max=120
  local delay=5
  while true; do
    "$@" && break || {
      if [[ $n -lt $max ]]; then
        ((n++))
        echo "Command failed. Attempt $n/$max:"
        sleep $delay;
      else
        fail "The command has failed after $n attempts."
      fi
    }
  done
}

function k {
    retry kubectl --context $KOPS_CLUSTER_NAME "$@"
}

# Add IAM configmap
echo 'Waiting for cluster to come up...'
k apply -f ./${KOPS_CLUSTER_NAME}/aws-iam-authenticator.yaml

# kops installs an older metrics server
# than we ship with EKS-D, along with an older clusterrole def. The 0.6 version
# of metrics requires a slightly different rbac setup.
k apply -f metrics-server-0.6-clusterrole.yaml

# kops doesnt support setting these cilium values
# session affinity for conformance tess
# kube-proxy disabled to make sure we are validating our kube-proxy
k -n kube-system patch cm/cilium-config --type merge -p '{"data":{"enable-session-affinity":"true"}}'
k -n kube-system rollout restart deployment/cilium-operator
k -n kube-system rollout status deployment/cilium-operator --timeout=30s
k -n kube-system delete pods -lk8s-app=cilium

set -x
${KOPS} validate cluster --wait 15m

# --set ipam.mode="kubernetes"


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -o errexit
set -o nounset
set -o pipefail
set -x

if [ "$TEST_ROLE_ARN" == "" ]; then
    echo "Empty TEST_ROLE_ARN, this script must be run in a codebuild job with a test role arn provided"
    exit 1
fi

BASEDIR=$(dirname "$0")

cat << EOF > config
[profile conformance-test]
role_arn=$TEST_ROLE_ARN
region=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-west-2}}
credential_source=EcsContainer
EOF

export AWS_CONFIG_FILE=$(pwd)/config
export AWS_PROFILE=conformance-test
DEFAULT_KOPS_ZONE_NAME="prod-build-pdx.kops-ci.model-rocket.aws.dev"
KOPS_ZONE_NAME=${KOPS_ZONE_NAME:-"${DEFAULT_KOPS_ZONE_NAME}"}
export NODE_ARCHITECTURE=${NODE_ARCHITECTURE:-amd64}
export KOPS_CLUSTER_NAME=${RELEASE_BRANCH}-${NODE_ARCHITECTURE}-$(git rev-parse --short HEAD).$(echo $RANDOM | md5sum | head -c 4).${KOPS_ZONE_NAME}
${BASEDIR}/run_all.sh


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -eo pipefail

BASEDIR=$(dirname "$0")
source ${BASEDIR}/set_environment.sh
$PREFLIGHT_CHECK_PASSED || exit 1

ADDITIONAL_ARGS=""
if [ -n "$NODE_INSTANCE_PROFILE" ]; then
    ADDITIONAL_ARGS="--lifecycle-overrides IAMRole=ExistsAndWarnIfChanges,IAMRolePolicy=ExistsAndWarnIfChanges,IAMInstanceProfileRole=ExistsAndWarnIfChanges"
fi

${KOPS} update cluster --admin --name ${KOPS_CLUSTER_NAME} --yes $ADDITIONAL_ARGS


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -eo pipefail

BASEDIR=$(dirname "$0")
source ${BASEDIR}/set_environment.sh
$PREFLIGHT_CHECK_PASSED || exit 1

# Create the bucket if it doesn't exist
_bucket_name=$(aws s3api list-buckets  --query "Buckets[?Name=='$BUCKET_NAME'].Name | [0]" --out text)
if [ $_bucket_name == "None" ]; then
    echo "Creating kOps state store: $KOPS_STATE_STORE"
    if [ "$AWS_DEFAULT_REGION" == "us-east-1" ]; then
        aws s3api create-bucket --bucket $BUCKET_NAME
    else
        aws s3api create-bucket --bucket $BUCKET_NAME --create-bucket-configuration LocationConstraint=$AWS_DEFAULT_REGION
    fi
else
    echo "Using kOps state store: $KOPS_STATE_STORE"
fi

mkdir -p ./${KOPS_CLUSTER_NAME}
echo "Creating ./${KOPS_CLUSTER_NAME}/aws-iam-authenticator.yaml"
cat << EOF > ./${KOPS_CLUSTER_NAME}/aws-iam-authenticator.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: aws-iam-authenticator
  namespace: kube-system
  labels:
    k8s-app: aws-iam-authenticator
data:
  config.yaml: |
    clusterID: $KOPS_CLUSTER_NAME
EOF

echo "Creating ${KOPS_CLUSTER_NAME}.yaml"
${KOPS} toolbox template --template ${BASEDIR}/eks-d.tpl --values ./${KOPS_CLUSTER_NAME}/values.yaml > "./${KOPS_CLUSTER_NAME}/${KOPS_CLUSTER_NAME}.yaml"

echo "Creating cluster configuration"
${KOPS} create -f "./${KOPS_CLUSTER_NAME}/${KOPS_CLUSTER_NAME}.yaml"

echo "Creating cluster ssh key"
SSH_FILE=${SSH_KEY_PATH:-$HOME/.ssh/id_rsa}
if [ ! -f "$SSH_FILE" ]
then
  ssh-keygen -t rsa -b 4096 -f "$SSH_FILE"
fi
export SSH_KEY_PATH="$SSH_FILE"
${KOPS} create secret --name $KOPS_CLUSTER_NAME sshpublickey admin -i "${SSH_KEY_PATH}.pub"
echo
echo "# Creating ./${KOPS_CLUSTER_NAME}/env.sh"
echo "export AWS_DEFAULT_REGION=$AWS_DEFAULT_REGION" | tee ./${KOPS_CLUSTER_NAME}/env.sh
echo "export AWS_REGION=$AWS_DEFAULT_REGION" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh
echo "export KOPS_CLUSTER_NAME=$KOPS_CLUSTER_NAME" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh
echo "export KOPS_STATE_STORE=$KOPS_STATE_STORE" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh
echo "export KOPS_BASE_URL=$KOPS_BASE_URL" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh
if [ -n "$CONTROL_PLANE_INSTANCE_PROFILE" ]; then
    echo "export CONTROL_PLANE_INSTANCE_PROFILE=$CONTROL_PLANE_INSTANCE_PROFILE" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh
fi
if [ -n "$NODE_INSTANCE_PROFILE" ]; then
    echo "export NODE_INSTANCE_PROFILE=$NODE_INSTANCE_PROFILE" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh
fi
if [ -n "$NODE_INSTANCE_TYPE" ]; then
    echo "export NODE_INSTANCE_TYPE=$NODE_INSTANCE_TYPE" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh
fi
if [ -n "$NODE_ARCHITECTURE" ]; then
    echo "export NODE_ARCHITECTURE=$NODE_ARCHITECTURE" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh
fi
if [ -n "$ARTIFACT_BUCKET" ]; then
    echo "export ARTIFACT_BUCKET=$ARTIFACT_BUCKET" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh
fi
if [ -n "$IMAGE_REPO" ]; then
    echo "export IMAGE_REPO=$IMAGE_REPO" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh
fi


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Create a unique s3 bucket name
export 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)}
echo export KOPS_STATE_STORE="${KOPS_STATE_STORE}"


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -eo pipefail

BASEDIR=$(dirname "$0")
source ${BASEDIR}/set_environment.sh
$PREFLIGHT_CHECK_PASSED || exit 1

mkdir -p "./${KOPS_CLUSTER_NAME}"
if [ -f "./${KOPS_CLUSTER_NAME}/values.yaml" ]; then
    echo -e "Error the ./${KOPS_CLUSTER_NAME}/values.yaml file already exists."
    echo -e "Delete the cluster and cluster store before creating a new cluster"
    exit 1
fi

function get_container_yaml() {
    REPOSITORY_NAME="${1}"
    RELEASE="${2}"
    VERSION="$(get_project_version $REPOSITORY_NAME)"

    if  [[ $REPOSITORY_NAME == "kubernetes-csi/external-snapshotter" ]]
    then
        REPOSITORY_NAME="kubernetes-csi/external-snapshotter/csi-snapshotter"
    fi

    if  [[ $REPOSITORY_NAME == "kubernetes/cloud-provider-aws" ]]
    then
        REPOSITORY_NAME="kubernetes/cloud-provider-aws/cloud-controller-manager"
    fi

    echo "    repository: ${IMAGE_REPO}/${REPOSITORY_NAME}
    tag: ${VERSION}-eks-${RELEASE_BRANCH}-${RELEASE}"
}

function get_project_version(){
    REPOSITORY_NAME="${1}"
    if  [[ $REPOSITORY_NAME == kubernetes/* ]] && [[ $REPOSITORY_NAME != "kubernetes/cloud-provider-aws" ]]
    then
        REPOSITORY_NAME="kubernetes/kubernetes"
    fi

    TAG_FILE=${BASEDIR}/../../projects/${REPOSITORY_NAME}/GIT_TAG
    if [ -f "$TAG_FILE" ]; then
        VERSION=$(cat ${BASEDIR}/../../projects/${REPOSITORY_NAME}/GIT_TAG)
    else
        VERSION=$(cat ${BASEDIR}/../../projects/${REPOSITORY_NAME}/${RELEASE_BRANCH}/GIT_TAG)
    fi

    echo $VERSION
}

# Get latest ubuntu ami based on desired release and arch
UBUNTU_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)

echo "Creating ./${KOPS_CLUSTER_NAME}/values.yaml"
cat << EOF > ./${KOPS_CLUSTER_NAME}/values.yaml
kubernetesVersion: ${ARTIFACT_URL}/kubernetes/${KUBERNETES_VERSION}
clusterName: $KOPS_CLUSTER_NAME
configBase: $KOPS_STATE_STORE/$KOPS_CLUSTER_NAME
awsRegion: $AWS_DEFAULT_REGION
controlPlaneInstanceProfileArn: $CONTROL_PLANE_INSTANCE_PROFILE
nodeInstanceProfileArn: $NODE_INSTANCE_PROFILE
instanceType: $NODE_INSTANCE_TYPE
architecture: $NODE_ARCHITECTURE
ubuntuAmi: $UBUNTU_AMI
ipv6: $IPV6
pause:
$(get_container_yaml kubernetes/pause $RELEASE)
kube_apiserver:
$(get_container_yaml kubernetes/kube-apiserver $RELEASE)
kube_controller_manager:
$(get_container_yaml kubernetes/kube-controller-manager $RELEASE)
kube_scheduler:
$(get_container_yaml kubernetes/kube-scheduler $RELEASE)
kube_proxy:
$(get_container_yaml kubernetes/kube-proxy $RELEASE)
metrics_server:
$(get_container_yaml kubernetes-sigs/metrics-server $RELEASE)
awsiamauth:
$(get_container_yaml kubernetes-sigs/aws-iam-authenticator $RELEASE)
coredns:
$(get_container_yaml coredns/coredns $RELEASE)
node_driver_registrar:
$(get_container_yaml kubernetes-csi/node-driver-registrar $RELEASE)
csi_resizer:
$(get_container_yaml kubernetes-csi/external-resizer $RELEASE)
csi_attacher:
$(get_container_yaml kubernetes-csi/external-attacher $RELEASE)
csi_snapshotter:
$(get_container_yaml kubernetes-csi/external-snapshotter $RELEASE)
csi_provisioner:
$(get_container_yaml kubernetes-csi/external-provisioner $RELEASE)
csi_livenessprobe:
$(get_container_yaml kubernetes-csi/livenessprobe $RELEASE)
etcd:
$(get_container_yaml etcd-io/etcd $RELEASE)
cloud_controller_manager:
$(get_container_yaml kubernetes/cloud-provider-aws $RELEASE)
EOF


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -eo pipefail

BASEDIR=$(dirname "$0")
source ${BASEDIR}/set_environment.sh
$PREFLIGHT_CHECK_PASSED || exit 1

echo "Deleting cluster $KOPS_STATE_STORE ${KOPS_CLUSTER_NAME}"
set -x
${KOPS} delete cluster --state "${KOPS_STATE_STORE}" --name "${KOPS_CLUSTER_NAME}" --yes
set +x


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -eo pipefail

BASEDIR=$(dirname "$0")
source ${BASEDIR}/set_environment.sh
$PREFLIGHT_CHECK_PASSED || exit 1

echo "Deleting kops store $KOPS_STATE_STORE"
set -x
aws s3 rm --recursive "${KOPS_STATE_STORE}/${KOPS_CLUSTER_NAME}" || true
if [ -n "${KOPS_CLUSTER_NAME}" ]
then
  rm -rf "./${KOPS_CLUSTER_NAME}"
fi


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -eo pipefail

BASEDIR=$(dirname "$0")
source ${BASEDIR}/set_environment.sh
$PREFLIGHT_CHECK_PASSED || exit 1

export LOG_DUMP_SAVE_SERVICES="kops-configuration containerd protokube"
export KUBERNETES_PROVIDER="none" # the script from upstream doesnt seem to handle aws exactly right
export LOG_DUMP_SSH_KEY="~/.ssh/id_rsa"
export LOG_DUMP_SSH_USER="ubuntu"
export LOG_DUMP_EXTRA_FILES="cloud-init-output.log cloud-init.log kube-proxy.log containers/*"
export LOG_DUMP_SYSTEMD_JOURNAL=true
ARTIFACTS=${ARTIFACTS:-"./_artifacts"}

function log_dump_custom_get_instances() {
    local -r type=$1
    local filter=''
    if [ $type == "control_plane" ]; then
        filter="Name=tag:k8s.io/role/master,Values=1"
    else
        filter="Name=tag:k8s.io/role/node,Values=1"
    fi
    nodes=$(aws ec2 describe-instances \
        --filters "Name=tag:KubernetesCluster,Values=${KOPS_CLUSTER_NAME}" "$filter" \
        --query "Reservations[*].Instances[*].PublicDnsName" --output text)

    # Container logs are symlinks and need a slightly different chmod
    # log-dump-ssh comes the upstream log-dump.sh script
    for node in $nodes ; do log-dump-ssh $node "sudo chmod a+r /var/log/containers/*" || true ; done

    echo "$nodes"
}
export -f log_dump_custom_get_instances

# fix protocol error: filename does not match request
# this seems to happen for the symlink'd files
function scp() {
    command scp -T "$@"
}
export -f scp

source ./log-dump/log-dump.sh $ARTIFACTS


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -euo pipefail

REPOSITORY_NAME="${1}"
QUERY='[.imageDetails[] | select(.imageTags != null)] | sort_by(.imagePushedAt)|reverse|first|.imageTags[0]'
TAG=$(aws --region us-east-1 ecr-public  describe-images \
          --repository-name "${REPOSITORY_NAME}" | \
          jq -r "${QUERY}")
echo ${TAG}


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#            http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -eo pipefail

BASEDIR=$(dirname "$0")
source ${BASEDIR}/set_environment.sh
# Ignoring preflight check failures since we only need the env vars set

if [ "$(uname)" == "Darwin" ]
then
    OS="darwin"
    ARCH="amd64"
else
    OS="linux"
    ARCH="amd64"
fi

mkdir -p ${BASEDIR}/bin

if [ ! -x ${KOPS} ]
then
    echo "Determine kops version"
    echo "Download kops"
    KOPS_URL="https://eks-d-postsubmit-artifacts.s3.us-west-2.amazonaws.com/kops/${KOPS_VERSION}/${OS}/${ARCH}/kops"
    set -x
    curl -L -o ${KOPS} "${KOPS_URL}"
    chmod 755 ${KOPS}
    set +x
fi

if ! command -v kubectl &> /dev/null
then
    echo "kubectl could not be found. Downloading..."
    KUBECTL_VERSION=$(cat ${BASEDIR}/../../projects/kubernetes/kubernetes/${RELEASE_BRANCH}/GIT_TAG)
    KUBECTL_PATH=${BASEDIR}/bin/kubectl
    COUNT=0
    while [ ! "$(${KUBECTL_PATH} version)" ]; do
        sleep 5
        COUNT=$(expr $COUNT + 1)
        if [ $COUNT -gt 120 ]
        then
            echo "Failed to download kubectl"
            exit 1
        fi
        set -x
        curl -sSL "${ARTIFACT_URL}/kubernetes/${KUBECTL_VERSION}/bin/${OS}/${ARCH}/kubectl" -o ${KUBECTL_PATH}
        chmod +x ${KUBECTL_PATH}
        set +x
    done
fi

if ! command -v helm &> /dev/null
then
    curl -s https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | HELM_INSTALL_DIR=${BASEDIR}/bin bash
fi

if ! command -v sonobuoy &> /dev/null
then
    echo "Download sonobuoy"
    SONOBUOY=https://github.com/vmware-tanzu/sonobuoy/releases/download/v0.56.2/sonobuoy_0.56.2_${OS}_${ARCH}.tar.gz
    wget -qO- ${SONOBUOY} |tar -xz sonobuoy
    chmod 755 sonobuoy
    mv sonobuoy ./bin
fi

echo "$(which kops): $(kops version)"
echo "$(which kubectl): $(kubectl version --client=true --short)"
echo "$(which helm): $(helm version --short)"
echo "$(which sonobuoy): $(sonobuoy version --short)"

exit 0


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

if [ "$AWS_ROLE_ARN" == "" ]; then
    echo "Empty AWS_ROLE_ARN, this script must be run in a postsubmit pod with IAM Roles for Service Accounts"
    exit 1
fi

if [ "$TEST_ROLE_ARN" == "" ]; then
    echo "Empty AWS_ROLE_ARN, this script must be run in a postsubmit pod with IAM Roles for Service Accounts"
    exit 1
fi

BASEDIR=$(dirname "$0")

cat << EOF > config
[default]
output=json
region=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-west-2}}
role_arn=$AWS_ROLE_ARN
web_identity_token_file=/var/run/secrets/eks.amazonaws.com/serviceaccount/token

[profile conformance-test]
role_arn=$TEST_ROLE_ARN
region=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-west-2}}
source_profile=default
EOF
export AWS_CONFIG_FILE=$(pwd)/config
export AWS_PROFILE=conformance-test
unset AWS_ROLE_ARN AWS_WEB_IDENTITY_TOKEN_FILE
DEFAULT_KOPS_ZONE_NAME="prod-build-pdx.kops-ci.model-rocket.aws.dev"
KOPS_ZONE_NAME=${KOPS_ZONE_NAME:-"${DEFAULT_KOPS_ZONE_NAME}"}
export NODE_ARCHITECTURE=${NODE_ARCHITECTURE:-amd64}
export KOPS_CLUSTER_NAME=${RELEASE_BRANCH}-${NODE_ARCHITECTURE}-$(git rev-parse --short HEAD).$(echo $RANDOM | md5sum | head -c 4).${KOPS_ZONE_NAME}
${BASEDIR}/run_all.sh


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -exo pipefail
BASEDIR=$(dirname "$0")
cd ${BASEDIR}

function cleanup()
{
  echo 'Deleting...'
  ./gather_logs.sh || true
  ./delete_cluster.sh
  ./delete_store.sh
}

function cleanup_and_error()
{
  cleanup
  exit 255;
}

echo "This script will create a cluster, run tests and tear it down"
source ./set_environment.sh
$PREFLIGHT_CHECK_PASSED || exit 1
./install_requirements.sh
if [[ "${KOPS_STATE_STORE}" != "" ]]; then
  for cluster_name in $(aws s3 ls ${KOPS_STATE_STORE}); do
    if [[ "${cluster_name}" == "${RELEASE_BRANCH}-${NODE_ARCHITECTURE}-"* ]]; then
      # Only delete if older than a day, get timestamp from config file in s3
      cluster_fqdn="$(echo ${cluster_name}|tr -d "/")"
      config=$(aws s3 ls ${KOPS_STATE_STORE}/${cluster_fqdn}/config)
      createDate=$(echo $config | awk {'print $1" "$2'})
      createDate=$(date -d"$createDate" +%s)
      olderThan=$(date --date "1 day ago" +%s)
      if [[ $createDate -lt $olderThan ]]; then
        echo "Deleting cluster ${cluster_fqdn}"
        ${KOPS} delete cluster --state "${KOPS_STATE_STORE}" --name ${cluster_fqdn} --yes
        aws s3 rm --recursive "${KOPS_STATE_STORE}/${cluster_name}"
      fi
    fi
  done
fi
trap cleanup_and_error SIGINT SIGTERM ERR
./create_values_yaml.sh
./create_configuration.sh
./create_cluster.sh
./set_nodeport_access.sh
./cluster_wait.sh
./validate_dns.sh
./run_tests.sh
./validate_eks.sh
./run_sonobuoy.sh

# avoid trying to clean up twice
trap '' SIGINT SIGTERM ERR

cleanup


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -eo pipefail
BASEDIR=$(dirname "$0")
echo "This script will create a cluster"
cd "$BASEDIR"
source ./set_environment.sh
$PREFLIGHT_CHECK_PASSED || exit 1
./install_requirements.sh
./create_values_yaml.sh
./create_configuration.sh
./create_cluster.sh
echo
echo "Run ./cluster_wait.sh"


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -eo pipefail

BASEDIR=$(dirname "$0")
source ${BASEDIR}/set_environment.sh
$PREFLIGHT_CHECK_PASSED || exit 1

CONFORMANCE_IMAGE=registry.k8s.io/conformance:${KUBERNETES_VERSION}
echo "Testing cluster ${KOPS_CLUSTER_NAME}"

COUNT=0
while ! sonobuoy --context ${KOPS_CLUSTER_NAME} run --mode=certified-conformance --wait --kube-conformance-image ${CONFORMANCE_IMAGE}
do
  sonobuoy --context ${KOPS_CLUSTER_NAME} delete --all --wait||true
  sleep 5
  COUNT=$(expr $COUNT + 1)
  if [ $COUNT -gt 3 ]
  then
    echo "Failed to run sonobuoy"
    exit 1
  fi
  echo 'Waiting for the cluster to be ready...'
done

results=''
function save_results() {
  local run=$1

  results=$(sonobuoy --context ${KOPS_CLUSTER_NAME} retrieve)
  mv $results "./${KOPS_CLUSTER_NAME}/$results"
  results="./${KOPS_CLUSTER_NAME}/$results"
  mkdir -p ./${KOPS_CLUSTER_NAME}/results
  tar xzf $results -C ./${KOPS_CLUSTER_NAME}/results
  if [ -w /logs/artifacts ]
  then
    mkdir -p /logs/artifacts/$NODE_ARCHITECTURE-$run
    cp ./${KOPS_CLUSTER_NAME}/results/plugins/e2e/results/global/* /logs/artifacts/$NODE_ARCHITECTURE-$run
  fi

  sonobuoy results --plugin e2e ${results}
  if sonobuoy results --plugin e2e ${results} | grep 'Status: passed'; then
    return 0
  else
    return 1
  fi
}

COUNT=1
while ! save_results $COUNT; do
  # retry failed conformance tests up to 3 times
  echo "Rerunning failed conformace tests"
  COUNT=$(expr $COUNT + 1)
  if [ $COUNT -gt 4 ]; then
    echo "Conformance test still failing after reruns"
    exit 1
  fi
  sonobuoy --context ${KOPS_CLUSTER_NAME} delete --all --wait
  sonobuoy --context ${KOPS_CLUSTER_NAME} run --rerun-failed ${results} --wait --kube-conformance-image ${CONFORMANCE_IMAGE}
done


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -eo pipefail

BASEDIR=$(dirname "$0")
source ${BASEDIR}/set_environment.sh
$PREFLIGHT_CHECK_PASSED || exit 1

function fail {
  echo $1 >&2
  exit 1
}

function retry {
  local n=1
  local max=5
  local delay=1
  while true; do
    "$@" && break || {
      if [[ $n -lt $max ]]; then
        ((n++))
        echo "Command failed. Attempt $n/$max:"
        sleep $delay;
      else
        fail "The command has failed after $n attempts."
      fi
    }
  done
}

function k {
    retry kubectl --context ${KOPS_CLUSTER_NAME} "$@"
}

function node_driver_registrar_expect {
    echo "node_driver_registrar_expect"
    k logs --selector app=csi-mockplugin --container node-driver-registrar  | \
        grep "Registration Server started at: /registration/io.kubernetes.storage.mock-reg.sock"
}

function liveness_probe_expect {
    echo "liveness_probe_expect"
    k logs --selector app=csi-mockplugin --container liveness-probe | \
        grep "io.kubernetes.storage.mock"
}

function provisioning_expect {
    echo "provisioning_expect"
    [ $(k get events --field-selector involvedObject.name=example-pvc,reason=ProvisioningSucceeded | wc -l) -ge 1 ]
}

function attach_expect {
    echo "attach_expect"
    k logs --selector app=csi-mockplugin --container csi-attacher | \
        grep "Fully attached"
}

function resize_expect {
    echo "resize_expect"
    [ $(k get events --field-selector involvedObject.name=example-pvc,reason=VolumeResizeSuccessful | wc -l) -ge 1 ]
}

function validate_csi {
    # Launch mock csi driver and validate all sidecars launch and trigger specific
    # events and/or log messages
    # Not a full suite but at least verifies all containers launch and
    # executes some of the flows

    ${KOPS} toolbox template --template ${BASEDIR}/tests/csi/deploy/csi-mock-driver-deployment.yaml.tpl \
        --values ./${KOPS_CLUSTER_NAME}/values.yaml > "./${KOPS_CLUSTER_NAME}/csi-mock-driver-deployment.yaml"

    k apply -f ${BASEDIR}/tests/csi/deploy/csi-mock-driver-rbac.yaml

    k apply -f "./${KOPS_CLUSTER_NAME}/csi-mock-driver-deployment.yaml"

    k wait deploy/csi-mockplugin --for condition=available --timeout=5m

    retry node_driver_registrar_expect
    retry liveness_probe_expect

    k apply -f "tests/csi/pvc-test.yaml"
    retry provisioning_expect

    k apply -f tests/csi/pod-test.yaml
    k wait pod/web-server --for condition=ready --timeout=5m
    retry attach_expect

    k patch pvc example-pvc -p '{"spec":{"resources":{"requests":{"storage": "2Mi"}}}}'
    retry resize_expect

}

function etcd_expect {
    echo "etcd_expect"
    [ $(k exec etcd0  -- etcdctl --endpoints=http://etcd0:2379 member list | wc -l) = 3 ]
}

function validate_etcd {
    # Not a full suite
    # Launch a 3 node etcd cluster using etcd images to validate they launch correctly

    ${KOPS} toolbox template --template ${BASEDIR}/tests/etcd/deploy/etcd.yaml.tpl \
        --values ./${KOPS_CLUSTER_NAME}/values.yaml > "./${KOPS_CLUSTER_NAME}/etcd.yaml"

    k apply -f "./${KOPS_CLUSTER_NAME}/etcd.yaml"
    k wait pod/etcd0 --for condition=ready --timeout=5m
    k wait pod/etcd1 --for condition=ready --timeout=5m
    k wait pod/etcd2 --for condition=ready --timeout=5m
    retry etcd_expect

}

validate_csi
validate_etcd


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

BASE_DIRECTORY=$(git rev-parse --show-toplevel)
export DEFAULT_RELEASE_BRANCH=$(cat ${BASE_DIRECTORY}/release/DEFAULT_RELEASE_BRANCH)
export RELEASE_BRANCH=${RELEASE_BRANCH:-"${DEFAULT_RELEASE_BRANCH}"}
RELEASE_ENVIRONMENT=${RELEASE_ENVIRONMENT:-development}
export DEFAULT_RELEASE=$(cat ${BASE_DIRECTORY}/release/${RELEASE_BRANCH}/${RELEASE_ENVIRONMENT}/RELEASE)
export RELEASE=${RELEASE:-${DEFAULT_RELEASE}}
export ARTIFACT_BASE_URL="https://distro.eks.amazonaws.com"
export NODE_INSTANCE_TYPE=${NODE_INSTANCE_TYPE:-t3.medium}
export NODE_ARCHITECTURE=${NODE_ARCHITECTURE:-amd64}
export UBUNTU_RELEASE=${UBUNTU_RELEASE:-focal-20.04}
export IPV6=${IPV6:-false}
export KOPS_VERSION="1.26.3"

if [ -n "$ARTIFACT_BUCKET" ]; then
    export ARTIFACT_BASE_URL="https://$ARTIFACT_BUCKET.s3.amazonaws.com"
fi

if [ "${PREFLIGHT_CHECK_PASSED:-false}" != "true" ]
then
    PREFLIGHT_CHECK_PASSED=true
    GOOD="\xE2\x9C\x94"
    BAD="\xE2\x9D\x8C"
    export AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION:-${AWS_REGION}}
    export AWS_REGION="${AWS_DEFAULT_REGION}"
    if [ -z "$AWS_DEFAULT_REGION" ]; then
        PREFLIGHT_CHECK_PASSED=false
        echo -e "${BAD} AWS_REGION must be set and exported"
    else
        echo -e "${GOOD} AWS_REGION=${AWS_REGION}"
    fi

    if ! aws sts get-caller-identity --query Account --output text >/dev/null 2>/dev/null
    then
        PREFLIGHT_CHECK_PASSED=false
        echo -e "${BAD} AWS CLI failed to authenticate"
    else
        echo -e "${GOOD} AWS CLI authenticated"
    fi

    if [ -z "$KOPS_STATE_STORE" ]; then
        PREFLIGHT_CHECK_PASSED=false
        echo -e "${BAD} KOPS_STATE_STORE must be set and exported"
    else
        echo -e "${GOOD} KOPS_STATE_STORE=${KOPS_STATE_STORE}"
    fi
    if [[ "${KOPS_STATE_STORE}" != s3://* ]]
    then
        export KOPS_STATE_STORE="s3://${KOPS_STATE_STORE}"
    fi
    export BUCKET_NAME=${KOPS_STATE_STORE#"s3://"}

    if [ -z "$KOPS_CLUSTER_NAME" ]; then
        PREFLIGHT_CHECK_PASSED=false
        echo -e "${BAD} KOPS_CLUSTER_NAME must be set and exported"
    else
        echo -e "${GOOD} KOPS_CLUSTER_NAME=${KOPS_CLUSTER_NAME}"
    fi
fi
export PREFLIGHT_CHECK_PASSED

export KUBERNETES_VERSION=$(cat ../../projects/kubernetes/kubernetes/${RELEASE_BRANCH}/GIT_TAG)
export IMAGE_REPO=${IMAGE_REPO:-public.ecr.aws/eks-distro}
export ARTIFACT_URL=${ARTIFACT_URL:-$ARTIFACT_BASE_URL/kubernetes-${RELEASE_BRANCH}/releases/${RELEASE}/artifacts}
export CNI_VERSION=$(cat ../../projects/containernetworking/plugins/${RELEASE_BRANCH}/GIT_TAG)
export CNI_VERSION_URL=${ARTIFACT_URL}/plugins/${CNI_VERSION}/cni-plugins-linux-${NODE_ARCHITECTURE}-${CNI_VERSION}.tar.gz
export CNI_ASSET_HASH_STRING=${CNI_ASSET_HASH_STRING:-sha256:$(curl -s ${CNI_VERSION_URL}.sha256 | cut -f1 -d' ')}
export KOPS_BASE_URL=https://eks-d-postsubmit-artifacts.s3.amazonaws.com/kops/$KOPS_VERSION
export KOPS=bin/kops
mkdir -p bin
export PATH=`pwd`/bin:${PATH}


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -eo pipefail

BASEDIR=$(dirname "$0")
source ${BASEDIR}/set_environment.sh
$PREFLIGHT_CHECK_PASSED || exit 1

#
# NodePort setting
#
export KOPS_FEATURE_FLAGS=SpecOverrideFlag
${KOPS} edit cluster --name "${KOPS_CLUSTER_NAME}" --set 'cluster.spec.nodePortAccess=0.0.0.0/0'

ADDITIONAL_ARGS=""
if [ -n "$NODE_INSTANCE_PROFILE" ]; then
    ADDITIONAL_ARGS="--lifecycle-overrides IAMRole=ExistsAndWarnIfChanges,IAMRolePolicy=ExistsAndWarnIfChanges,IAMInstanceProfileRole=ExistsAndWarnIfChanges"
fi

${KOPS} update cluster --yes $ADDITIONAL_ARGS


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# In prow we have occasional dns issues after a cluster has been created
# Wait for 60 seconds giving both dns pods a chance to get the latest
# ip for the api server.  Printing out the results to potentially
# make debugging easier

set -eo pipefail
BASEDIR=$(dirname "$0")
cd "$BASEDIR"
source ./set_environment.sh
$PREFLIGHT_CHECK_PASSED || exit 1

APISERVER="api.$KOPS_CLUSTER_NAME"
SUCCESS_COUNT=0
while [ $SUCCESS_COUNT -lt 8 ]
do
  API_SERVER_IP=$(dig +short $APISERVER)
  if [ -z "$API_SERVER_IP" ]; then
    echo "$APISERVER did not resolve!"
    SUCCESS_COUNT=0
  else
    echo "$APISERVER resolves to $API_SERVER_IP"
    SUCCESS_COUNT=$((SUCCESS_COUNT+1))
  fi

  sleep 5s
done

kubectl --context ${KOPS_CLUSTER_NAME} config set-cluster ${KOPS_CLUSTER_NAME} \
    --insecure-skip-tls-verify=true --server=https://${API_SERVER_IP}


#!/usr/bin/env bash
# Copyright 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.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

kubectl --context $KOPS_CLUSTER_NAME get po --all-namespaces -o json | jq -r '.items[].spec.containers[].image' | sort -u