#!/bin/bash
# Runs "npm package" in all modules. This will produce a "dist/" directory in each module.
# Then, calls pack-collect.sh to merge all outputs into a root ./pack directory, which is
# later read by bundle-beta.sh.
set -eu
export PATH=$PWD/node_modules/.bin:$PATH
export NODE_OPTIONS="--max-old-space-size=8192 ${NODE_OPTIONS:-}"
root=$PWD

# Get version and changelog file name (these require that .versionrc.json would have been generated)
version=$(node -p "require('./scripts/resolve-version').version")
changelog_file=$(node -p "require('./scripts/resolve-version').changelogFile")
marker=$(node -p "require('./scripts/resolve-version').marker")

PACMAK=${PACMAK:-jsii-pacmak}
ROSETTA=${ROSETTA:-jsii-rosetta}
TMPDIR=${TMPDIR:-$(dirname $(mktemp -u))}
distdir="$PWD/dist"
rm -fr ${distdir}
mkdir -p ${distdir}

if ${CHECK_PREREQS:-true}; then
  /bin/bash ./scripts/check-pack-prerequisites.sh
fi

# Split out jsii and non-jsii packages. Jsii packages will be built all at once.
# Non-jsii packages will be run individually.
echo "Collecting package list..." >&2
scripts/list-packages $TMPDIR/jsii.txt $TMPDIR/nonjsii.txt

# Return lerna scopes from a package list
function lerna_scopes() {
  while [[ "${1:-}" != "" ]]; do
    echo "--scope $1 "
    shift
  done
}

scripts/run-rosetta.sh --infuse --pkgs-from $TMPDIR/jsii.txt

# Execute any pre-package steps for the jsii modules here:
echo "Running aws-cdk-lib pre-package"
npx lerna run --scope aws-cdk-lib package -- --pre-only

# Jsii packaging (all at once using jsii-pacmak)
echo "Packaging jsii modules" >&2
$PACMAK \
  --verbose \
  $(cat $TMPDIR/jsii.txt)

# Execute any post-package steps for the jsii modules here:
echo "Running aws-cdk-lib post-package"
npx lerna run --scope aws-cdk-lib package -- --post-only

# Non-jsii packaging, which means running 'package' in every individual
# module
echo "Packaging non-jsii modules" >&2
npx lerna run $(lerna_scopes $(cat $TMPDIR/nonjsii.txt)) --sort --concurrency=1 --stream package

# Finally rsync all 'dist' directories together into a global 'dist' directory
for dir in $(find packages -name dist | grep -v node_modules | grep -v run-wrappers); do
  echo "Merging ${dir} into ${distdir}" >&2
  rsync -a $dir/ ${distdir}/
done

# Record the dependency order of NPM packages into a file
# (This file will be opportunistically used during publishing)
#
# Manually sort 'aws-cdk' to the end, as the 'cdk init' command has implicit dependencies
# on other packages (that should not appear in 'package.json' and so
# there is no way to tell lerna about these).
for dir in $(lerna ls --toposort -p | grep -v packages/aws-cdk) $PWD/packages/aws-cdk; do
  (cd $dir/dist/js && ls >> ${distdir}/js/npm-publish-order.txt) || true
done

# Remove a JSII aggregate POM that may have snuk past
rm -rf dist/java/software/amazon/jsii

# Get commit from CodePipeline (or git, if we are in CodeBuild)
# If CODEBUILD_RESOLVED_SOURCE_VERSION is not defined (i.e. local
# build or CodePipeline build), use the HEAD commit hash).
commit="${CODEBUILD_RESOLVED_SOURCE_VERSION:-}"
if [ -z "${commit}" ]; then
  commit="$(git rev-parse --verify HEAD)"
fi

cat > ${distdir}/build.json <<HERE
{
  "name": "aws-cdk",
  "version": "${version}",
  "commit": "${commit}"
}
HERE

# copy CHANGELOG.md and RELEASE_NOTES.md to dist/ for github releases
cp ${changelog_file} ${distdir}/CHANGELOG.md
# Release notes are not available for bump candidate builds.
if ! ${BUMP_CANDIDATE:-false}; then
  cp RELEASE_NOTES.md ${distdir}/RELEASE_NOTES.md
fi

# defensive: make sure our artifacts don't use the version marker (this means
# that "pack" will always fails when building in a dev environment)
# when we get to 10.0.0, we can fix this...
if find dist/ | grep -F "${marker}"; then
  echo "ERROR: build artifacts use the version marker '${marker}' instead of a real version."
  echo "This is expected for builds in a development environment but should not happen in CI builds!"
  exit 1
fi


#!/bin/bash
#
# Run our integration tests in regression mode against the
# candidate version of the framework, which is the one we just packed.
#
set -euo pipefail
integdir=$(cd $(dirname $0) && pwd)

source ${integdir}/test-cli-regression.bash

run_regression_against_framework_version CANDIDATE_VERSION


#!/bin/bash
#
# Run our integration tests in regression mode against the
# previous version of the framework, relative to the version being packed now.
#
set -euo pipefail
integdir=$(cd $(dirname $0) && pwd)

source ${integdir}/test-cli-regression.bash

run_regression_against_framework_version PREVIOUS_VERSION


#!/bin/bash
set -euo pipefail
scriptdir=$(cd $(dirname $0) && pwd)

echo '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
echo 'CLI Integration Tests'
echo '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'

current_version=$(node -p "require('${scriptdir}/../../../package.json').version")

# This allows injecting different versions, not just the current one.
# Useful when testing.
export VERSION_UNDER_TEST=${VERSION_UNDER_TEST:-${current_version}}

cd $scriptdir

# Install these dependencies that the tests (written in Jest) need.
# Only if we're not running from the repo, because if we are the
# dependencies have already been installed by the containing 'aws-cdk' package's
# package.json.
if ! npx --no-install jest --version; then
  echo 'Looks like we need to install jest first. Hold on.' >& 2
  npm install --prefix . jest aws-sdk
fi

npx jest --runInBand --verbose "$@"


#!/bin/bash
# executes markdownlint on all RFCs
# --fix to fix errors
set -euo pipefail
linters=$PWD/tools/linters

npm install --prefix $linters
find . -type f -name '*.md' -not -path '*/node_modules/*' -not -path '*/.github/*' |\
  xargs -I'{}' $linters/node_modules/.bin/markdownlint -c $linters/markdownlint.json $@ '{}'


#!/bin/bash
set -euo pipefail
(cd tools/rfc-render && npm install)
node tools/rfc-render/inject-table.js README.md


# Source this file to activate auto completion for zsh using the bash
# compatibility helper.  Make sure to run `compinit` before, which should be
# given usually.
#
# % source /path/to/zsh_complete.sh
#
# Typically that would be called somewhere in your .zshrc.
#
# Note, the overwrite of _bash_complete() is to export COMP_LINE and COMP_POINT
# That is only required for zsh <= edab1d3dbe61da7efe5f1ac0e40444b2ec9b9570
#
# https://github.com/zsh-users/zsh/commit/edab1d3dbe61da7efe5f1ac0e40444b2ec9b9570
#
# zsh releases prior to that version do not export the required env variables!

autoload -Uz bashcompinit
bashcompinit -i

_bash_complete() {
  local ret=1
  local -a suf matches
  local -x COMP_POINT COMP_CWORD
  local -a COMP_WORDS COMPREPLY BASH_VERSINFO
  local -x COMP_LINE="$words"
  local -A savejobstates savejobtexts

  (( COMP_POINT = 1 + ${#${(j. .)words[1,CURRENT]}} + $#QIPREFIX + $#IPREFIX + $#PREFIX ))
  (( COMP_CWORD = CURRENT - 1))
  COMP_WORDS=( $words )
  BASH_VERSINFO=( 2 05b 0 1 release )

  savejobstates=( ${(kv)jobstates} )
  savejobtexts=( ${(kv)jobtexts} )

  [[ ${argv[${argv[(I)nospace]:-0}-1]} = -o ]] && suf=( -S '' )

  matches=( ${(f)"$(compgen $@ -- ${words[CURRENT]})"} )

  if [[ -n $matches ]]; then
    if [[ ${argv[${argv[(I)filenames]:-0}-1]} = -o ]]; then
      compset -P '*/' && matches=( ${matches##*/} )
      compset -S '/*' && matches=( ${matches%%/*} )
      compadd -Q -f "${suf[@]}" -a matches && ret=0
    else
      compadd -Q "${suf[@]}" -a matches && ret=0
    fi
  fi

  if (( ret )); then
    if [[ ${argv[${argv[(I)default]:-0}-1]} = -o ]]; then
      _default "${suf[@]}" && ret=0
    elif [[ ${argv[${argv[(I)dirnames]:-0}-1]} = -o ]]; then
      _directories "${suf[@]}" && ret=0
    fi
  fi

  return ret
}

complete -C aws_completer aws


#!/usr/bin/env bash

# Cleanup EKS cluster used for integration test.

source ./integration/eks-test/scripts/eks-common.sh

# Delete service and namespace from export and import cluster
$KUBECTL_BIN config use-context $EXPORT_CLS
$KUBECTL_BIN delete svc $SERVICE -n $NAMESPACE

# Verfication to check if there are hanging ServiceExport or ServiceImport CRDs and clears the finalizers to allow cleanup process to continue
for CRD in $($KUBECTL_BIN get crd -n $NAMESPACE | grep multicluster | cut -d " " -f 1 | xargs); do
    $KUBECTL_BIN patch crd -n $NAMESPACE $CRD --type merge -p '{"metadata":{"finalizers": [null]}}';
    $KUBECTL_BIN delete crd $CRD -n $NAMESPACE # CRD needs to be explictly deleted in order to ensure zero resources are hanging for future tests
done

$KUBECTL_BIN delete namespaces $NAMESPACE

# IAM Service Account needs to be explictly deleted, as not doing so creates hanging service accounts that cause permissions issues in future tests
eksctl delete iamserviceaccount \
    --name cloud-map-mcs-controller-manager \
    --namespace $MCS_NAMESPACE \
    --cluster $EXPORT_CLS \
    --wait

$KUBECTL_BIN config use-context $IMPORT_CLS
$KUBECTL_BIN delete pod $CLIENT_POD -n $NAMESPACE
$KUBECTL_BIN delete namespaces $NAMESPACE
eksctl delete iamserviceaccount \
    --name cloud-map-mcs-controller-manager \
    --namespace $MCS_NAMESPACE \
    --cluster $IMPORT_CLS \
    --wait

$KUBECTL_BIN config use-context $EXPORT_CLS
$KUBECTL_BIN delete -k "github.com/aws/aws-cloud-map-mcs-controller-for-k8s/config/controller_install_latest"
$KUBECTL_BIN config use-context $IMPORT_CLS
$KUBECTL_BIN delete -k "github.com/aws/aws-cloud-map-mcs-controller-for-k8s/config/controller_install_latest"

echo "EKS clusters cleaned!"

# ./integration/shared/scripts/cleanup-cloudmap.sh
go run ./integration/janitor/runner/main.go "$NAMESPACE" "$CLUSTERID1" "$CLUSTERSETID1"
go run ./integration/janitor/runner/main.go "$NAMESPACE" "$CLUSTERID2" "$CLUSTERSETID1"


#!/usr/bin/env bash

export KIND_BIN='./bin/kind'
export KUBECTL_BIN='kubectl'
export LOGS='./integration/eks-test/testlog'
export CONFIGS='./integration/eks-test/configs'
export SCENARIOS='./integration/shared/scenarios'
export NAMESPACE='aws-cloud-map-mcs-eks-e2e'
export MCS_NAMESPACE='cloud-map-mcs-system'
export SERVICE='nginx-hello'
export SERVICE_TYPE='ClusterSetIP'
export CLIENT_POD='client-hello'
export ENDPT_PORT=80
export SERVICE_PORT=80 # from nginx-service.yaml
export EXPORT_CLS='cls1'
export IMPORT_CLS='cls2'
export CLUSTERID1='eks-e2e-clusterid-1'
export CLUSTERID2='eks-e2e-clusterid-2'
export CLUSTERSETID1='eks-e2e-clustersetid-1'
export EXPECTED_ENDPOINT_COUNT=3
export UPDATED_ENDPOINT_COUNT=4


#!/usr/bin/env bash

# Testing service consumption with client-hello pod

echo "verifying cross-cluster service consumption..."

# Install curl if not installed
$KUBECTL_BIN exec $CLIENT_POD -n $NAMESPACE /bin/sh -- curl --version &>/dev/null
exit_code=$?
if [ "$exit_code" -eq 126 ]; then
    echo "curl not installed, installing..."
    $KUBECTL_BIN exec $CLIENT_POD -n $NAMESPACE /bin/sh -- apk add curl
fi

# Perform an nslookup to cluster-local CoreDNS
echo "performing nslookup..."
$KUBECTL_BIN exec -it $CLIENT_POD -n $NAMESPACE /bin/sh -- nslookup $SERVICE.$NAMESPACE.svc.clusterset.local
exit_code=$?

if [ "$exit_code" -ne 0 ]; then
    echo "ERROR: Unable to nslookup service $SERVICE.$NAMESPACE.svc.clusterset.local"
    exit $exit_code
fi
sleep 5

# Call to DNS server, if unable to reach, importing cluster is not able to properly consume service
echo "performing curl..."
$KUBECTL_BIN exec -it $CLIENT_POD -n $NAMESPACE /bin/sh -- curl $SERVICE.$NAMESPACE.svc.clusterset.local
exit_code=$?

if [ "$exit_code" -ne 0 ]; then
    echo "ERROR: Unable to reach service $SERVICE.$NAMESPACE.svc.clusterset.local"
    exit $exit_code
fi

echo "confirmed service consumption"
exit 0


#!/usr/bin/env bash

# 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

source ./integration/eks-test/scripts/eks-common.sh

# Checking expected endpoints number in exporting cluster
$KUBECTL_BIN config use-context $EXPORT_CLS
if ! endpts=$(./integration/shared/scripts/poll-endpoints.sh "$EXPECTED_ENDPOINT_COUNT"); then
    exit $?
fi

# Runner to verify expected endpoints are exported to Cloud Map
go run $SCENARIOS/runner/main.go $NAMESPACE $SERVICE $CLUSTERID1 $CLUSTERSETID1 $ENDPT_PORT $SERVICE_PORT $SERVICE_TYPE "$endpts"
exit_code=$?

# Check imported endpoints in importing cluster
if [ "$exit_code" -eq 0 ] ; then
  $KUBECTL_BIN config use-context $IMPORT_CLS
  ./integration/shared/scripts/test-import.sh "$EXPECTED_ENDPOINT_COUNT" "$endpts"
  exit_code=$?
fi

# Verifying that importing cluster is properly consuming services
if [ "$exit_code" -eq 0 ] ; then
  ./integration/eks-test/scripts/eks-DNS-test.sh
  exit_code=$?
fi

echo "sleeping..."
sleep 2

# Scaling and verifying deployment
if [ "$exit_code" -eq 0 ] ; then
  $KUBECTL_BIN config use-context $EXPORT_CLS
  deployment=$($KUBECTL_BIN get deployment --namespace "$NAMESPACE" -o json | jq -r '.items[0].metadata.name')

  echo "scaling the deployment $deployment to $UPDATED_ENDPOINT_COUNT"
  $KUBECTL_BIN scale deployment/"$deployment" --replicas="$UPDATED_ENDPOINT_COUNT" --namespace "$NAMESPACE"
  exit_code=$?
fi

if [ "$exit_code" -eq 0 ] ; then
  if ! updated_endpoints=$(./integration/shared/scripts/poll-endpoints.sh "$UPDATED_ENDPOINT_COUNT") ; then
    exit $?
  fi
fi

if [ "$exit_code" -eq 0 ] ; then
  go run $SCENARIOS/runner/main.go $NAMESPACE $SERVICE $CLUSTERID1 $CLUSTERSETID1 $ENDPT_PORT $SERVICE_PORT $SERVICE_TYPE "$updated_endpoints"
  exit_code=$?
fi

if [ "$exit_code" -eq 0 ] ; then
  $KUBECTL_BIN config use-context $IMPORT_CLS
  ./integration/shared/scripts/test-import.sh "$UPDATED_ENDPOINT_COUNT" "$updated_endpoints"
  exit_code=$?
fi

if [ "$exit_code" -eq 0 ] ; then
  ./integration/eks-test/scripts/eks-DNS-test.sh
  exit_code=$?
fi

# Dump logs
mkdir -p "$LOGS"
$KUBECTL_BIN config use-context $EXPORT_CLS
$KUBECTL_BIN logs -l control-plane=controller-manager -c manager --namespace $MCS_NAMESPACE &> "$LOGS/ctl-1.log"
$KUBECTL_BIN config use-context $IMPORT_CLS
$KUBECTL_BIN logs -l control-plane=controller-manager -c manager --namespace $MCS_NAMESPACE &> "$LOGS/ctl-2.log"
echo "dumped logs"

exit $exit_code


#!/usr/bin/env bash

# Adding IAM service accounts
$KUBECTL_BIN config use-context $1
$KUBECTL_BIN create namespace $MCS_NAMESPACE
eksctl create iamserviceaccount \
--cluster $1 \
--namespace $MCS_NAMESPACE \
--name cloud-map-mcs-controller-manager \
--attach-policy-arn arn:aws:iam::aws:policy/AWSCloudMapFullAccess \
--override-existing-serviceaccounts \
--approve

# Installing controller
$KUBECTL_BIN config use-context $1
$KUBECTL_BIN apply -k "github.com/aws/aws-cloud-map-mcs-controller-for-k8s/config/controller_install_latest"


#!/usr/bin/env bash

source ./integration/eks-test/scripts/eks-common.sh

# Call helper for service account and controller installation
./integration/eks-test/scripts/eks-setup-helper.sh $EXPORT_CLS
./integration/eks-test/scripts/eks-setup-helper.sh $IMPORT_CLS

# Apply ClusterProperties
$KUBECTL_BIN config use-context $EXPORT_CLS
$KUBECTL_BIN apply -f "$CONFIGS/e2e-clusterproperty-1.yaml"

$KUBECTL_BIN config use-context $IMPORT_CLS
$KUBECTL_BIN apply -f "$CONFIGS/e2e-clusterproperty-2.yaml"

# Installing service
$KUBECTL_BIN config use-context $EXPORT_CLS
$KUBECTL_BIN create namespace $NAMESPACE
$KUBECTL_BIN apply -f "$CONFIGS/nginx-deployment.yaml"
$KUBECTL_BIN apply -f "$CONFIGS/nginx-service.yaml"

$KUBECTL_BIN config use-context $IMPORT_CLS
$KUBECTL_BIN create namespace $NAMESPACE

# Creating service export
$KUBECTL_BIN config use-context $EXPORT_CLS
$KUBECTL_BIN apply -f "$CONFIGS/nginx-serviceexport.yaml"

# Create client-hello pod
$KUBECTL_BIN config use-context $IMPORT_CLS
$KUBECTL_BIN apply -f "$CONFIGS/client-hello.yaml"
sleep 15


#!/usr/bin/env bash

# Deletes Kind cluster used for integration test.

set -eo pipefail
source ./integration/kind-test/scripts/common.sh

$KIND_BIN delete cluster --name "$KIND_SHORT"

./integration/shared/scripts/cleanup-cloudmap.sh


#!/usr/bin/env bash

export KIND_BIN='./bin/kind'
export KUBECTL_BIN='kubectl'
export LOGS='./integration/kind-test/testlog'
export KIND_CONFIGS='./integration/kind-test/configs'
export SHARED_CONFIGS='./integration/shared/configs'
export SCENARIOS='./integration/shared/scenarios'
export NAMESPACE='aws-cloud-map-mcs-e2e'
export ENDPT_PORT=80
export SERVICE_PORT=80
export CLUSTERIP_SERVICE='e2e-clusterset-ip-service'
export HEADLESS_SERVICE='e2e-headless-service'
export KIND_SHORT='cloud-map-e2e'
export CLUSTER='kind-cloud-map-e2e'
export CLUSTERID1='kind-e2e-clusterid-1'
export CLUSTERSETID1='kind-e2e-clustersetid-1'
export IMAGE='kindest/node:v1.21.12@sha256:f316b33dd88f8196379f38feb80545ef3ed44d9197dca1bfd48bcb1583210207'
export EXPECTED_ENDPOINT_COUNT=5
export UPDATED_ENDPOINT_COUNT=6


#!/usr/bin/env bash

# Testing service consumption with dnsutils pod

deployment=$1

echo "performing curl to $SERVICE.$NAMESPACE.svc.clusterset.local"
http_code=$($KUBECTL_BIN exec deployment/$deployment --namespace "$NAMESPACE" -- curl -s -o /dev/null -w "%{http_code}" $SERVICE.$NAMESPACE.svc.clusterset.local)
exit_code=$?

if [ "$exit_code" -ne 0 ]; then
    echo "ERROR: Unable to curl $SERVICE.$NAMESPACE.svc.clusterset.local"
    exit $exit_code
fi

if [ "$http_code" -ne "200" ]; then
    echo "ERROR: curl $SERVICE.$NAMESPACE.svc.clusterset.local failed with $http_code"
    exit 1
fi

exit 0


#!/usr/bin/env bash

# If the IP Type env var is not set, default it to IPv4
if [[ -z "${ADDRESS_TYPE}" ]]; then
  ADDRESS_TYPE="IPv4"
fi

# Helper function to verify DNS results
checkDNS() {
    dns_addresses_count=$(echo "$1" | wc -l | xargs)

    if [ "$SERVICE_TYPE" = "Headless" ]; then
        if [ "$dns_addresses_count" -ne "$expected_endpoint_count" ]; then
            echo "ERROR: Found $dns_addresses_count endpoints, expected $expected_endpoint_count endpoints"
            exit 1
        fi
    fi

    if [ "$SERVICE_TYPE" = "ClusterSetIP" ]; then
        if [ "$dns_addresses_count" -ne 1 ]; then
            echo "ERROR: Found $dns_addresses_count endpoints, expected 1 endpoint"
            exit 1
        fi
    fi
}

# Testing service consumption with dnsutils pod

echo "verifying dns resolution..."

expected_endpoint_count=$1

# Install dnsutils pod
$KUBECTL_BIN apply -f "$KIND_CONFIGS/dnsutils-pod.yaml"
$KUBECTL_BIN wait --for=condition=ready pod/dnsutils # wait until pod is deployed

# Perform a dig to cluster-local CoreDNS
# TODO: parse dig outputs for more precise verification - check specifics IPs?
if [[ $ADDRESS_TYPE == "IPv4" ]]; then
    echo "performing dig for A records for IPv4..."
    addresses=$($KUBECTL_BIN exec dnsutils -- dig +all +ans $SERVICE.$NAMESPACE.svc.clusterset.local +short)
    exit_code=$?
    echo "$addresses"
elif [[ $ADDRESS_TYPE == "IPv6" ]]; then
    echo "performing dig for AAAA records for IPv6..."
    addresses=$($KUBECTL_BIN exec dnsutils -- dig AAAA +all +ans $SERVICE.$NAMESPACE.svc.clusterset.local +short)
    exit_code=$?
    echo "$addresses"
else
    echo "ADDRESS_TYPE invalid"
    exit 1
fi

if [ "$exit_code" -ne 0 ]; then
    echo "ERROR: Unable to dig service $SERVICE.$NAMESPACE.svc.clusterset.local"
    exit $exit_code
fi

# verify DNS results
checkDNS "$addresses"

echo "performing dig for SRV records..."
addresses=$($KUBECTL_BIN exec dnsutils -- dig +all +ans $SERVICE.$NAMESPACE.svc.clusterset.local. SRV +short)
exit_code=$?
echo "$addresses"

if [ "$exit_code" -ne 0 ]; then
    echo "ERROR: Unable to dig service $SERVICE.$NAMESPACE.svc.clusterset.local"
    exit $exit_code
fi

# verify DNS results
checkDNS "$addresses"

echo "confirmed dns resolution"
exit 0


#!/usr/bin/env bash

# Ensure jq is available to parse json output. Installs jq on debian/ubuntu

if ! which -s jq ; then
  echo "jq not found, attempting to install"
  if ! sudo apt-get install -y jq ; then
    echo "failed to install jq, ensure it is available before running tests"
    exit 1
  fi
fi

exit 0


#!/usr/bin/env bash

# Helper to run test and passing different Service names

source ./integration/kind-test/scripts/common.sh

# create test namespace
$KUBECTL_BIN create namespace "$NAMESPACE"

# If the IP Type env var is not set, default it to IPV4
if [[ -z "${ADDRESS_TYPE}" ]]; then
  ADDRESS_TYPE="IPv4"
fi

# ClusterIP service test
./integration/kind-test/scripts/run-tests.sh "$CLUSTERIP_SERVICE" "ClusterSetIP" $ADDRESS_TYPE
exit_code=$?
if [ "$exit_code" -ne 0 ] ; then
    echo "ERROR: Testing $CLUSTERIP_SERVICE failed"
    exit $exit_code
fi

sleep 5

# Headless service test
./integration/kind-test/scripts/run-tests.sh "$HEADLESS_SERVICE" "Headless" $ADDRESS_TYPE
exit_code=$?
if [ "$exit_code" -ne 0 ] ; then
    echo "ERROR: Testing $HEADLESS_SERVICE failed"
    exit $exit_code
fi


#!/usr/bin/env bash

# Runs the AWS Cloud Map MCS Controller for K8s as a background process and tests services have been exported

source ./integration/kind-test/scripts/common.sh
export SERVICE=$1
export SERVICE_TYPE=$2
export IP_TYPE=$3

# Deploy pods
$KUBECTL_BIN apply -f "$KIND_CONFIGS/e2e-deployment.yaml"
# Get deployment
deployment=$($KUBECTL_BIN get deployment --namespace "$NAMESPACE" -o json | jq -r '.items[0].metadata.name')

printf "\n***Testing Service: $SERVICE***\n"

$KUBECTL_BIN apply -f "$KIND_CONFIGS/$SERVICE.yaml"

if ! endpts=$(./integration/shared/scripts/poll-endpoints.sh "$EXPECTED_ENDPOINT_COUNT") ; then
  exit $?
fi

mkdir -p "$LOGS"
./bin/manager --zap-devel=true --zap-time-encoding=rfc3339 &> "$LOGS/ctl.log" &
CTL_PID=$!
echo "controller PID:$CTL_PID"

go run $SCENARIOS/runner/main.go $NAMESPACE $SERVICE $CLUSTERID1 $CLUSTERSETID1 $ENDPT_PORT $SERVICE_PORT $SERVICE_TYPE $IP_TYPE "$endpts"
exit_code=$?

if [ "$exit_code" -eq 0 ] ; then
  ./integration/shared/scripts/test-import.sh "$EXPECTED_ENDPOINT_COUNT" "$endpts"
  exit_code=$?
fi

if [ "$exit_code" -eq 0 ] ; then
  ./integration/kind-test/scripts/dns-test.sh "$EXPECTED_ENDPOINT_COUNT"
  exit_code=$?
fi

if [ "$exit_code" -eq 0 ] ; then
  ./integration/kind-test/scripts/curl-test.sh "$deployment"
  exit_code=$?
fi

echo "sleeping..."
sleep 2

if [ "$exit_code" -eq 0 ] ; then
  echo "scaling the deployment $deployment to $UPDATED_ENDPOINT_COUNT"
  $KUBECTL_BIN scale deployment/"$deployment" --replicas="$UPDATED_ENDPOINT_COUNT" --namespace "$NAMESPACE"
  exit_code=$?
fi

if [ "$exit_code" -eq 0 ] ; then
  if ! updated_endpoints=$(./integration/shared/scripts/poll-endpoints.sh "$UPDATED_ENDPOINT_COUNT") ; then
    exit $?
  fi
fi

if [ "$exit_code" -eq 0 ] ; then
  go run $SCENARIOS/runner/main.go $NAMESPACE $SERVICE $CLUSTERID1 $CLUSTERSETID1 $ENDPT_PORT $SERVICE_PORT $SERVICE_TYPE $IP_TYPE "$updated_endpoints"
  exit_code=$?
fi

if [ "$exit_code" -eq 0 ] ; then
  ./integration/shared/scripts/test-import.sh "$UPDATED_ENDPOINT_COUNT" "$updated_endpoints"
  exit_code=$?
fi

if [ "$exit_code" -eq 0 ] ; then
  ./integration/kind-test/scripts/dns-test.sh "$UPDATED_ENDPOINT_COUNT"
  exit_code=$?
fi

echo "Test Successful. Cleaning up..."

# Remove the deployment and delete service (should also delete ServiceExport)
if [ "$exit_code" -eq 0 ] ; then
  $KUBECTL_BIN delete -f "$KIND_CONFIGS/e2e-deployment.yaml"
  $KUBECTL_BIN delete Service $SERVICE -n $NAMESPACE
  # TODO: verify service export is not found
  # TODO: verify cloudmap resources are cleaned up
fi

echo "killing controller PID:$CTL_PID"
kill $CTL_PID
exit $exit_code


#!/usr/bin/env bash

# Builds the AWS Cloud Map MCS Controller for K8s, provisions a Kubernetes clusters with Kind,
# installs Cloud Map CRDs and controller into the cluster and applies export and deployment configs.

set -e

source ./integration/kind-test/scripts/common.sh

./integration/kind-test/scripts/ensure-jq.sh

# If the IP Type env var is not set, default it to IPv4
if [[ -z "${ADDRESS_TYPE}" ]]; then
  ADDRESS_TYPE="IPv4"
fi

echo "ADDRESS_TYPE: $ADDRESS_TYPE"
if [[ $ADDRESS_TYPE == "IPv4" ]]; then
  $KIND_BIN create cluster --name "$KIND_SHORT" --image "$IMAGE"
elif [[ $ADDRESS_TYPE == "IPv6" ]]; then
  $KIND_BIN create cluster --name "$KIND_SHORT" --image "$IMAGE" --config=./integration/kind-test/configs/ipv6.yaml
else
  echo "ADDRESS_TYPE invalid"
fi

$KUBECTL_BIN config use-context "$CLUSTER"
make install

# Install CoreDNS plugin
$KUBECTL_BIN apply -f "$SHARED_CONFIGS/coredns-clusterrole.yaml"
$KUBECTL_BIN apply -f "$SHARED_CONFIGS/coredns-configmap.yaml"
$KUBECTL_BIN apply -f "$KIND_CONFIGS/coredns-deployment.yaml"

# Add ClusterId and ClusterSetId
$KUBECTL_BIN apply -f "$KIND_CONFIGS/e2e-clusterproperty.yaml"


#!/usr/bin/env bash

# Deletes all AWS Cloud Map resources used for integration test.

set -eo pipefail

go run ./integration/janitor/runner/main.go "$NAMESPACE" "$CLUSTERID1" "$CLUSTERSETID1"


#!/usr/bin/env bash

# Poll for endpoints to become active

set -e

endpt_count=0
poll_count=0
while ((endpt_count < $1))
do
  if ((poll_count++ > 30)) ; then
    echo "timed out polling for endpoints" >&2
    exit 1
  fi

  sleep 2
  if ! addresses=$($KUBECTL_BIN get endpointslices -o json --namespace "$NAMESPACE" | \
    jq --arg SERVICE "$SERVICE" '.items[] | select(.metadata.ownerReferences[].name==$SERVICE) | .endpoints[].addresses[0]' 2> /dev/null)
  then
    # no endpoints ready
    continue
  fi

  endpt_count=$(echo "$addresses" | wc -l | xargs)
done

echo "$addresses" | tr -d '"' | paste -sd "," -
echo "matched number of endpoints to expected count" >&2
exit 0


#!/usr/bin/env bash

# Test service imports were created during e2e test

set -e

expected_endpoint_count=$1
endpoints=$2
echo "checking service imports..."

import_count=0
poll_count=0
while ((import_count < expected_endpoint_count))
do
  sleep 1
  if ((poll_count++ > 30)) ; then
    echo "timed out polling for import endpoints"
    exit 1
  fi

  imports=$($KUBECTL_BIN get endpointslices -o json --namespace $NAMESPACE | \
    jq '.items[] | select(.metadata.ownerReferences[].name | startswith("imported")) | .endpoints[].addresses[0]')
  echo "import endpoint list from kubectl:"
  echo "$imports"

  import_count=$(echo "$imports" | wc -l | xargs)
done

echo "$imports" | tr -d '"' | while read -r import; do
  echo "checking import: $import"
  if ! echo "$endpoints" | grep -q "$import" ; then
    echo "exported endpoint not found: $import"
    exit 1
  fi
done

if [ $? -ne 0 ]; then
    exit $?
fi

echo "matched all imports to exported endpoints"
exit 0


#!/bin/sh
set -e

/usr/local/bin/dockerd \
	--host=unix:///var/run/docker.sock \
	--host=tcp://127.0.0.1:2375 \
	--storage-driver=overlay2 &>/var/log/docker.log &

tries=0
d_timeout=60
until docker info >/dev/null 2>&1
do
	if [ "$tries" -gt "$d_timeout" ]; then
                cat /var/log/docker.log
		echo 'Timed out trying to connect to internal docker host.' >&2
		exit 1
	fi
        tries=$(( $tries + 1 ))
	sleep 1
done

eval "$@"


#!/bin/bash

function allOSRealPath() {
    if isOSWindows
    then
        path=""
        case $1 in
            .* ) path="$PWD/${1#./}" ;;
            /* ) path="$1" ;;
            *  ) path="/$1" ;;
        esac

        echo "/$path" | sed -e 's/\\/\//g' -e 's/://' -e 's/./\U&/3'
    else
        case $1 in
            /* ) echo "$1"; exit;;
            *  ) echo "$PWD/${1#./}"; exit;;
        esac
    fi
}

function isOSWindows() {
    if [ $OSTYPE == "msys" ]
    then
        return 0
    else
        return 1
    fi
}

function usage {
    echo "usage: codebuild_build.sh [-i image_name] [-a artifact_output_directory] [options]"
    echo "Required:"
    echo "  -i        Used to specify the customer build container image."
    echo "  -a        Used to specify an artifact output directory."
    echo "Options:"
    echo "  -l IMAGE  Used to override the default local agent image."
    echo "  -r        Used to specify a report output directory."
    echo "  -s        Used to specify source information. Defaults to the current working directory for primary source."
    echo "               * First (-s) is for primary source"
    echo "               * Use additional (-s) in <sourceIdentifier>:<sourceLocation> format for secondary source"
    echo "               * For sourceIdentifier, use a value that is fewer than 128 characters and contains only alphanumeric characters and underscores"
    echo "  -c        Use the AWS configuration and credentials from your local host. This includes ~/.aws and any AWS_* environment variables."
    echo "  -p        Used to specify the AWS CLI Profile."
    echo "  -b FILE   Used to specify a buildspec override file. Defaults to buildspec.yml in the source directory."
    echo "  -m        Used to mount the source directory to the customer build container directly."
    echo "  -d        Used to run the build container in docker privileged mode."
    echo "  -e FILE   Used to specify a file containing environment variables."
    echo "            (-e) File format expectations:"
    echo "               * Each line is in VAR=VAL format"
    echo "               * Lines beginning with # are processed as comments and ignored"
    echo "               * Blank lines are ignored"
    echo "               * File can be of type .env or .txt"
    echo "               * There is no special handling of quotation marks, meaning they will be part of the VAL"
    exit 1
}

image_flag=false
artifact_flag=false
awsconfig_flag=false
mount_src_dir_flag=false
docker_privileged_mode_flag=false

while getopts "cmdi:a:r:s:b:e:l:p:h" opt; do
    case $opt in
        i  ) image_flag=true; image_name=$OPTARG;;
        a  ) artifact_flag=true; artifact_dir=$OPTARG;;
        r  ) report_dir=$OPTARG;;
        b  ) buildspec=$OPTARG;;
        c  ) awsconfig_flag=true;;
        m  ) mount_src_dir_flag=true;;
        d  ) docker_privileged_mode_flag=true;;
        s  ) source_dirs+=("$OPTARG");;
        e  ) environment_variable_file=$OPTARG;;
        l  ) local_agent_image=$OPTARG;;
        p  ) aws_profile=$OPTARG;;
        h  ) usage; exit;;
        \? ) echo "Unknown option: -$OPTARG" >&2; exit 1;;
        :  ) echo "Missing option argument for -$OPTARG" >&2; exit 1;;
        *  ) echo "Invalid option: -$OPTARG" >&2; exit 1;;
    esac
done

if  ! $image_flag
then
    echo "The image name flag (-i) must be included for a build to run" >&2
fi

if  ! $artifact_flag
then
    echo "The artifact directory (-a) must be included for a build to run" >&2
fi

if  ! $image_flag ||  ! $artifact_flag
then
    exit 1
fi

docker_command="docker run -it "
if isOSWindows
then
    docker_command+="-v //var/run/docker.sock:/var/run/docker.sock -e "
else
    docker_command+="-v /var/run/docker.sock:/var/run/docker.sock -e "
fi

docker_command+="\"IMAGE_NAME=$image_name\" -e \
    \"ARTIFACTS=$(allOSRealPath "$artifact_dir")\""

if [ -n "$report_dir" ]
then
    docker_command+=" -e \"REPORTS=$(allOSRealPath "$report_dir")\""
fi

if [ -z "$source_dirs" ]
then
    docker_command+=" -e \"SOURCE=$(allOSRealPath "$PWD")\""
else
    for index in "${!source_dirs[@]}"; do
        if [ $index -eq 0 ]
        then
            docker_command+=" -e \"SOURCE=$(allOSRealPath "${source_dirs[$index]}")\""
        else
            identifier=${source_dirs[$index]%%:*}
            src_dir=$(allOSRealPath "${source_dirs[$index]#*:}")

            docker_command+=" -e \"SECONDARY_SOURCE_$index=$identifier:$src_dir\""
        fi
    done
fi

if [ -n "$buildspec" ]
then
    docker_command+=" -e \"BUILDSPEC=$(allOSRealPath "$buildspec")\""
fi

if [ -n "$environment_variable_file" ]
then
    environment_variable_file_path=$(allOSRealPath "$environment_variable_file")
    environment_variable_file_dir=$(dirname "$environment_variable_file_path")
    environment_variable_file_basename=$(basename "$environment_variable_file")
    docker_command+=" -v \"$environment_variable_file_dir:/LocalBuild/envFile/\" -e \"ENV_VAR_FILE=$environment_variable_file_basename\""
fi

if [ -n "$local_agent_image" ]
then
    docker_command+=" -e \"LOCAL_AGENT_IMAGE_NAME=$local_agent_image\""
fi

if $awsconfig_flag
then
    if [ -d "$HOME/.aws" ]
    then
        configuration_file_path=$(allOSRealPath "$HOME/.aws")
        docker_command+=" -e \"AWS_CONFIGURATION=$configuration_file_path\""
    else
        docker_command+=" -e \"AWS_CONFIGURATION=NONE\""
    fi

    if [ -n "$aws_profile" ]
    then
        docker_command+=" -e \"AWS_PROFILE=$aws_profile\""
    fi

    docker_command+="$(env | grep ^AWS_ | while read -r line; do echo " -e \"$line\""; done )"
fi

if $mount_src_dir_flag
then
    docker_command+=" -e \"MOUNT_SOURCE_DIRECTORY=TRUE\""
fi

if $docker_privileged_mode_flag
then
    docker_command+=" -e \"DOCKER_PRIVILEGED_MODE=TRUE\""
fi

if isOSWindows
then
    docker_command+=" -e \"INITIATOR=$USERNAME\""
else
    docker_command+=" -e \"INITIATOR=$USER\""
fi

if [ -n "$local_agent_image" ]
then
    docker_command+=" $local_agent_image"
else
    docker_command+=" public.ecr.aws/codebuild/local-builds:latest"
fi

# Note we do not expose the AWS_SECRET_ACCESS_KEY or the AWS_SESSION_TOKEN
exposed_command=$docker_command
secure_variables=( "AWS_SECRET_ACCESS_KEY=" "AWS_SESSION_TOKEN=")
for variable in "${secure_variables[@]}"
do
    exposed_command="$(echo $exposed_command | sed "s/\($variable\)[^ ]*/\1********\"/")"
done

echo "Build Command:"
echo ""
echo $exposed_command
echo ""

eval $docker_command


#!/usr/bin/expect -f

set timeout 1800
set cmd [lindex $argv 0]
set licenses [lindex $argv 1]

spawn {*}$cmd
expect {
    "Do you accept the license '*'*" {
        exp_send "y\r"
        exp_continue
    }
    "Accept? (y/N): " {
        exp_send "y\r"
        exp_continue
    }
    "Review licenses that have not been accepted (y/N)? " {
        exp_send "y\r"
        exp_continue
    }
    eof
}

lassign [wait] pid spawnid os_error waitvalue

if {$os_error == 0} {
    exit $waitvalue
} else {
    exit 1
}


#!/usr/bin/expect -f

set timeout 1800
set cmd [lindex $argv 0]
set licenses [lindex $argv 1]

spawn {*}$cmd
expect {
  "Do you accept the license '*'*" {
        exp_send "y\r"
        exp_continue
  }
  eof
}


#!/bin/sh
set -e

/usr/local/bin/dockerd \
	--host=unix:///var/run/docker.sock \
	--host=tcp://127.0.0.1:2375 \
	--storage-driver=overlay &>/var/log/docker.log &

tries=0
d_timeout=60
until docker info >/dev/null 2>&1
do
	if [ "$tries" -gt "$d_timeout" ]; then
                cat /var/log/docker.log
		echo 'Timed out trying to connect to internal docker host.' >&2
		exit 1
	fi
        tries=$(( $tries + 1 ))
	sleep 1
done

eval "$@"


#!/usr/bin/expect -f

set timeout 1800
set cmd [lindex $argv 0]
set licenses [lindex $argv 1]

spawn {*}$cmd
expect {
    "Do you accept the license '*'*" {
        exp_send "y\r"
        exp_continue
    }
    "Accept? (y/N): " {
        exp_send "y\r"
        exp_continue
    }
    "Review licenses that have not been accepted (y/N)? " {
        exp_send "y\r"
        exp_continue
    }
    eof
}


#!/bin/sh
set -e

/usr/local/bin/dind docker daemon \
	--host=unix:///var/run/docker.sock \
	--host=tcp://0.0.0.0:2375 \
	--storage-driver=overlay &>/var/log/docker.log &

tries=0
d_timeout=60
until docker info >/dev/null 2>&1
do
	if [ "$tries" -gt "$d_timeout" ]; then
                cat /var/log/docker.log
		echo 'Timed out trying to connect to internal docker host.' >&2
		exit 1
	fi
        tries=$(( $tries + 1 ))
	sleep 1
done

eval "$@"


#!/bin/sh
set -e

/usr/local/bin/dockerd \
	--host=unix:///var/run/docker.sock \
	--host=tcp://0.0.0.0:2375 \
	--storage-driver=overlay &>/var/log/docker.log &

tries=0
d_timeout=60
until docker info >/dev/null 2>&1
do
	if [ "$tries" -gt "$d_timeout" ]; then
                cat /var/log/docker.log
		echo 'Timed out trying to connect to internal docker host.' >&2
		exit 1
	fi
        tries=$(( $tries + 1 ))
	sleep 1
done

eval "$@"


#!/bin/bash

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "AfterAllowTraffic" >> $SCRIPT_DIR/../../../../../executed_proof_file


#!/bin/bash

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "AfterBlockTraffic" >> $SCRIPT_DIR/../../../../../executed_proof_file


#!/bin/bash

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "AfterInstall" >> $SCRIPT_DIR/../../../../../executed_proof_file


#!/bin/bash

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "ApplicationStart" >> $SCRIPT_DIR/../../../../../executed_proof_file


#!/bin/bash

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "ApplicationStop" >> $SCRIPT_DIR/../../../../../executed_proof_file


#!/bin/bash

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "BeforeAllowTraffic" >> $SCRIPT_DIR/../../../../../executed_proof_file


#!/bin/bash

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "BeforeBlockTraffic" >> $SCRIPT_DIR/../../../../../executed_proof_file


#!/bin/bash

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "BeforeInstall" >> $SCRIPT_DIR/../../../../../executed_proof_file


#!/bin/bash

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "ValidateService" >> $SCRIPT_DIR/../../../../../executed_proof_file


#!/bin/bash

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "CustomEvent" >> $SCRIPT_DIR/../../../../../executed_proof_file


#!/bin/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. A copy of the License is located at
#
#      http://www.apache.org/licenses/LICENSE-2.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, express or implied. See the License for the specific language governing permissions
#  and limitations under the License.
#-----------------------------------------------------------------------------------------------------------------------

#
# This assumes all of the OS-level configuration has been completed and git repo has already been cloned
#
# This script should be run from the repo's deployment directory
# cd deployment
# ./build-s3-dist.sh solution-name
#
# Paramenters:
#  - solution-name: name of the solution for consistency

# Check to see if input has been provided:
if [ -z "$1" ]; then
    echo "Please provide the trademark approved solution name for the open source package."
    echo "For example: ./build-s3-dist.sh trademarked-solution-name"
    exit 1
fi

# Get reference for all important folders
source_template_dir="$PWD"
dist_dir="$source_template_dir/open-source"
dist_template_dir="$dist_dir/deployment"
source_dir="$source_template_dir/../source"

echo "------------------------------------------------------------------------------"
echo "[Init] Clean old open-source folder"
echo "------------------------------------------------------------------------------"
echo "rm -rf $dist_dir"
rm -rf $dist_dir
echo "mkdir -p $dist_dir"
mkdir -p $dist_dir
echo "mkdir -p $dist_template_dir"
mkdir -p $dist_template_dir

echo "------------------------------------------------------------------------------"
echo "[Packing] Templates"
echo "------------------------------------------------------------------------------"
echo "cp $source_template_dir/*.template $dist_template_dir/"
cp $source_template_dir/*.template $dist_template_dir/
echo "copy yaml templates and rename"
cp $source_template_dir/*.yaml $dist_template_dir/
cd $dist_template_dir
# Rename all *.yaml to *.template
for f in *.yaml; do
    mv -- "$f" "${f%.yaml}.template"
done

echo "------------------------------------------------------------------------------"
echo "[Packing] Build Script"
echo "------------------------------------------------------------------------------"
echo "cp $source_template_dir/build-s3-dist.sh $dist_template_dir"
cp $source_template_dir/build-s3-dist.sh $dist_template_dir
echo "cp $source_template_dir/run-unit-tests.sh $dist_template_dir"
cp $source_template_dir/run-unit-tests.sh $dist_template_dir

echo "------------------------------------------------------------------------------"
echo "[Packing] Source Folder"
echo "------------------------------------------------------------------------------"
echo "cp -r $source_dir $dist_dir"
cp -r $source_dir $dist_dir
echo "cp $source_template_dir/../LICENSE.txt $dist_dir"
cp $source_template_dir/../LICENSE.txt $dist_dir
echo "cp $source_template_dir/../NOTICE.txt $dist_dir"
cp $source_template_dir/../NOTICE.txt $dist_dir
echo "cp $source_template_dir/../README.md $dist_dir"
cp $source_template_dir/../README.md $dist_dir
echo "cp $source_template_dir/../CODE_OF_CONDUCT.md $dist_dir"
cp $source_template_dir/../CODE_OF_CONDUCT.md $dist_dir
echo "cp $source_template_dir/../CONTRIBUTING.md $dist_dir"
cp $source_template_dir/../CONTRIBUTING.md $dist_dir
echo "cp $source_template_dir/../CHANGELOG.md $dist_dir"
cp $source_template_dir/../CHANGELOG.md $dist_dir

echo "------------------------------------------------------------------------------"
echo "[Packing] Clean dist, node_modules and bower_components folders"
echo "------------------------------------------------------------------------------"
echo "find $dist_dir -iname "node_modules" -type d -exec rm -r "{}" \; 2> /dev/null"
find $dist_dir -iname "node_modules" -type d -exec rm -r "{}" \; 2> /dev/null
echo "find $dist_dir -iname "tests" -type d -exec rm -r "{}" \; 2> /dev/null"
find $dist_dir -iname "tests" -type d -exec rm -r "{}" \; 2> /dev/null
echo "find $dist_dir -iname "dist" -type d -exec rm -r "{}" \; 2> /dev/null"
find $dist_dir -iname "dist" -type d -exec rm -r "{}" \; 2> /dev/null
echo "find $dist_dir -iname "bower_components" -type d -exec rm -r "{}" \; 2> /dev/null"
find $dist_dir -iname "bower_components" -type d -exec rm -r "{}" \; 2> /dev/null
echo "find ../ -type f -name 'package-lock.json' -delete"
find $dist_dir -type f -name 'package-lock.json' -delete

echo "------------------------------------------------------------------------------"
echo "[Packing] Create GitHub (open-source) zip file"
echo "------------------------------------------------------------------------------"
echo "cd $dist_dir"
cd $dist_dir
echo "zip -q -r9 ../$1.zip *"
zip -q -r9 ../$1.zip *
echo "Clean up open-source folder"
echo "rm -rf *"
rm -rf *
echo "mv ../$1.zip ."
mv ../$1.zip .
echo "Completed building $1.zip dist"


#!/bin/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. A copy of the License is located at
#
#      http://www.apache.org/licenses/LICENSE-2.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, express or implied. See the License for the specific language governing permissions
#  and limitations under the License.
#-----------------------------------------------------------------------------------------------------------------------

#
# This assumes all of the OS-level configuration has been completed and git repo has already been cloned
#
# This script should be run from the repo's deployment directory
# cd deployment
# ./build-s3-dist.sh source-bucket-base-name solution-name version-code
#
# Paramenters:
#  - source-bucket-base-name: Name for the S3 bucket location where the template will source the Lambda
#    code from. The template will append '-[region_name]' to this bucket name.
#    For example: ./build-s3-dist.sh solutions my-solution v1.0.0
#    The template will then expect the source code to be located in the solutions-[region_name] bucket
#
#  - solution-name: name of the solution for consistency
#
#  - version-code: version of the package

# Check to see if input has been provided:
if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ] || [ -z "$4" ] || [ -z "$5" ] || [ -z "$6" ]; then
    echo "Please provide the base source bucket name, trademark approved solution name and version where the lambda code will eventually reside."
    echo "For example: ./build-s3-dist.sh solutions trademarked-solution-name v1.0.0"
    exit 1
fi

# Get reference for all important folders
template_dir="$PWD"
template_dist_dir="$template_dir/global-s3-assets"
build_dist_dir="$template_dir/regional-s3-assets"
source_dir="$template_dir/../source"

echo "------------------------------------------------------------------------------"
echo "[Init] Clean old dist, node_modules and bower_components folders"
echo "------------------------------------------------------------------------------"
echo "rm -rf $template_dist_dir"
rm -rf $template_dist_dir
echo "mkdir -p $template_dist_dir"
mkdir -p $template_dist_dir
echo "rm -rf $build_dist_dir"
rm -rf $build_dist_dir
echo "mkdir -p $build_dist_dir"
mkdir -p $build_dist_dir

echo "------------------------------------------------------------------------------"
echo "[Rebuild] Bundle Application"
echo "------------------------------------------------------------------------------"
repositoryRegion=''

if [ -n "$6" ]; then
    repositoryRegion="-R $6"
fi

repositoryUri="$5"
cd "$source_dir/packages/services/simulation-launcher/src/containers/jmeter/infrastructure"
./deploy.bash -b -r $repositoryUri $repositoryRegion

cd $source_dir
rush bundle

echo "------------------------------------------------------------------------------"
echo "[Packing] Templates"
echo "------------------------------------------------------------------------------"

# copy all the cfn templates in the source/infrastructure dir
cp $source_dir/infrastructure/cfn-*.yaml $template_dist_dir/
# copy all the cfn templates in source/infrastructure/cloudformation dir
cp $source_dir/infrastructure/cloudformation/cfn-*.yaml $template_dist_dir/
# copy all the cfn templates in source/infrastructure/lambdaLayers/openssl/infrastructure
cp $source_dir/infrastructure/lambdaLayers/openssl/infrastructure/cfn-*.yml $template_dist_dir/
# copy all the cfn templates ending in yml in source/package/*/infrastructure
cp $source_dir/packages/services/*/infrastructure/cfn-*.yml $template_dist_dir/
# copy all the cfn templates ending in yaml in source/package/*/infrastructure
cp $source_dir/packages/services/*/infrastructure/cfn-*.yaml $template_dist_dir/
# copy all cfn template snippets
cp -a $source_dir/infrastructure/cloudformation/snippets/ $template_dist_dir/snippets/
# copy all cfn templates in libraries/core
cp $source_dir/packages/libraries/core/*/infrastructure/cfn-*.yaml $template_dist_dir/

cd $template_dist_dir
# Rename all *.yaml to *.template
for f in *.yaml; do
    mv -- "$f" "${f%.yaml}.template"
done

# Rename all *.yml to *.template
for f in *.yml; do
    mv -- "$f" "${f%.yml}.template"
done

# remove non-release templates
rm $template_dist_dir/cfn-auth-jwt.template
rm $template_dist_dir/cfn-auth-devicecert.template

# override the S3 Code Uri and TemplateURL for the cfn templates to point to a S3 location
for f in *.template; do
    if [ -f "../transforms/${f%.*}.yaml" ]; then
        yq w -i -s "../transforms/${f%.*}.yaml" "$f"
    fi
done

cd ..
echo "Updating code source bucket in template with $1"
replace="s/%%BUCKET_NAME%%/$1/g"
echo "sed -i '' -e $replace $template_dist_dir/*.template"
sed -i '' -e $replace $template_dist_dir/*.template
replace="s/%%SOLUTION_NAME%%/$2/g"
echo "sed -i '' -e $replace $template_dist_dir/*.template"
sed -i '' -e $replace $template_dist_dir/*.template
replace="s/%%VERSION%%/$3/g"
echo "sed -i '' -e $replace $template_dist_dir/*.template"
sed -i '' -e $replace $template_dist_dir/*.template

replace="s/%%TEMPLATE_BUCKET_NAME%%/$4/g"
sed -i '' -e $replace $template_dist_dir/*.template

echo "------------------------------------------------------------------------------"
echo "[Rebuild] Package Dists"
echo "------------------------------------------------------------------------------"

# Copy and rename dists
cd $build_dist_dir
cp $source_dir/packages/libraries/core/deployment-helper/bundle.zip $build_dist_dir/cdf-deployment-helper.zip
cp $source_dir/infrastructure/lambdaLayers/openssl/build/build.zip $build_dist_dir/cdf-openssl-layer.zip
cp $source_dir/packages/services/assetlibrary/bundle.zip $build_dist_dir/cdf-assetLibrary.zip
cp $source_dir/packages/services/assetlibraryhistory/bundle.zip $build_dist_dir/cdf-assetLibrary-history.zip
cp $source_dir/packages/services/assetlibrary-export/bundle.zip $build_dist_dir/cdf-assetLibrary-export.zip
cp $source_dir/packages/services/provisioning/bundle.zip $build_dist_dir/cdf-provisioning.zip
cp $source_dir/packages/services/commands/bundle.zip $build_dist_dir/cdf-commands.zip
cp $source_dir/packages/services/device-monitoring/bundle.zip $build_dist_dir/cdf-device-monitoring.zip
cp $source_dir/packages/services/events-processor/bundle.zip $build_dist_dir/cdf-events-processor.zip
cp $source_dir/packages/services/events-alerts/bundle.zip $build_dist_dir/cdf-events-alerts.zip
cp $source_dir/packages/services/bulkcerts/bundle.zip $build_dist_dir/cdf-bulkcerts.zip
cp $source_dir/packages/services/certificateactivator/bundle.zip $build_dist_dir/cdf-certificate-activator.zip
cp $source_dir/packages/services/certificatevendor/bundle.zip $build_dist_dir/cdf-certificate-vendor.zip
cp $source_dir/packages/services/simulation-launcher/bundle.zip $build_dist_dir/cdf-simulation-launcher.zip
cp $source_dir/packages/services/simulation-manager/bundle.zip $build_dist_dir/cdf-simulation-manager.zip
cp $source_dir/packages/services/device-patcher/bundle.zip $build_dist_dir/cdf-device-patcher.zip
cp $source_dir/packages/services/greengrass2-provisioning/bundle.zip $build_dist_dir/cdf-greengrass2-provisioning.zip
cp $source_dir/packages/services/greengrass2-installer-config-generators/bundle.zip $build_dist_dir/cdf-greengrass2-installer-config-generators.zip


#!/bin/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. A copy of the License is located at
#
#      http://www.apache.org/licenses/LICENSE-2.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, express or implied. See the License for the specific language governing permissions
#  and limitations under the License.
#-----------------------------------------------------------------------------------------------------------------------

#
# This assumes all of the OS-level configuration has been completed and git repo has already been cloned
#
# This script should be run from the repo's deployment directory
# cd deployment
# ./run-unit-tests.sh
#

# Get reference for all important folders
template_dir="$PWD"
source_dir="$template_dir/../source"

# note:  pnpm@3.5.7 has broken tsc
echo installing rush
npm i -g @microsoft/rush

echo installing jq...
curl -s -qL -o /usr/bin/jq https://stedolan.github.io/jq/download/linux64/jq
chmod +x /usr/bin/jq

echo installing yq
curl -s -qL -o /usr/bin/yq https://github.com/mikefarah/yq/releases/download/3.4.0/yq_linux_amd64
chmod +x /usr/bin/yq

aws --version
yq --version
jq --version
docker --version


#!/bin/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. A copy of the License is located at
#
#      http://www.apache.org/licenses/LICENSE-2.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, express or implied. See the License for the specific language governing permissions
#  and limitations under the License.
#-----------------------------------------------------------------------------------------------------------------------

#
# This assumes all of the OS-level configuration has been completed and git repo has already been cloned
#
# This script should be run from the repo's deployment directory
# cd deployment
# ./build-s3-dist.sh source-bucket-base-name solution-name version-code
#
# Parameters:
#  - source-bucket-base-name: Name for the S3 bucket location where the template will source the Lambda
#    code from. The template will append '-[region_name]' to this bucket name.
#    For example: ./build-s3-dist.sh solutions my-solution v1.0.0
#    The template will then expect the source code to be located in the solutions-[region_name] bucket
#
#  - solution-name: name of the solution for consistency
#
#  - version-code: version of the package

# Check to see if input has been provided:
if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ] || [ -z "$4" ] ; then
    echo "Please provide the base source bucket name, trademark approved solution name and version where the lambda code will eventually reside."
    echo "For example: ./build-s3-dist.sh solutions trademarked-solution-name v1.0.0"
    exit 1
fi

# Get reference for all important folders
template_dir="$PWD"
template_dist_dir="$template_dir/global-s3-assets"
build_dist_dir="$template_dir/regional-s3-assets"
source_dir="$template_dir/../source"

echo "------------------------------------------------------------------------------"
echo "[Init] Clean old dist, node_modules and bower_components folders"
echo "------------------------------------------------------------------------------"
echo "rm -rf $template_dist_dir"
rm -rf $template_dist_dir
echo "mkdir -p $template_dist_dir"
mkdir -p $template_dist_dir
echo "rm -rf $build_dist_dir"
rm -rf $build_dist_dir
echo "mkdir -p $build_dist_dir"
mkdir -p $build_dist_dir

echo "------------------------------------------------------------------------------"
echo "[Packing] Templates"
echo "------------------------------------------------------------------------------"

# copy all the cfn templates in the source/infrastructure dir
cp $source_dir/infrastructure/cfn-sample-tenant-component.yaml $template_dist_dir/
# copy all the cfn templates in source/infrastructure/lambdaLayers/openssl/infrastructure
cp $source_dir/infrastructure/lambdaLayers/openssl/infrastructure/cfn-*.yml $template_dist_dir/
# copy all the cfn templates ending in yml in source/package/*/infrastructure
cp $source_dir/packages/services/*/infrastructure/cfn-command-and-control.yml $template_dist_dir/
# copy all cfn template snippets
cp -a $source_dir/infrastructure/cloudformation/snippets/ $template_dist_dir/snippets/
# copy all cfn templates in libraries/core
cp $source_dir/packages/libraries/core/*/infrastructure/cfn-deployment-helper.yaml $template_dist_dir/

cd "$template_dist_dir"
# Rename all *.yaml to *.template
for f in *.yaml; do
    mv -- "$f" "${f%.yaml}.template"
done

# Rename all *.yml to *.template
for f in *.yml; do
    mv -- "$f" "${f%.yml}.template"
done

# remove non-release templates
rm "$template_dist_dir"/cfn-auth-jwt.template
rm "$template_dist_dir"/cfn-auth-devicecert.template
rm "$template_dist_dir"/cfn-cdf-core*
rm "$template_dist_dir"/cfn-bastion-host.template

# override the S3 Code Uri and TemplateURL for the cfn templates to point to a S3 location
for f in *.template; do
    if [ -f "../transforms/${f%.*}.yaml" ]; then
      # Below only works in yq version 3.4.1
      yq w -i -s "../transforms/${f%.*}.yaml" "$f"
    fi
done

cd ..
echo "Updating code source bucket in template with $1"
replace="s/%%BUCKET_NAME%%/$1/g"
echo "sed -i '' -e $replace $template_dist_dir/*.template"
sed -i '' -e $replace $template_dist_dir/*.template
replace="s/%%SOLUTION_NAME%%/$2/g"
echo "sed -i '' -e $replace $template_dist_dir/*.template"
sed -i '' -e $replace $template_dist_dir/*.template
replace="s/%%VERSION%%/$3/g"
echo "sed -i '' -e $replace $template_dist_dir/*.template"
sed -i '' -e $replace $template_dist_dir/*.template

replace="s/%%TEMPLATE_BUCKET_NAME%%/$4/g"
sed -i '' -e $replace $template_dist_dir/*.template

echo "------------------------------------------------------------------------------"
echo "[Rebuild] Package Dists"
echo "------------------------------------------------------------------------------"

# Copy and rename dists
cd $build_dist_dir
cp $source_dir/packages/libraries/core/deployment-helper/bundle.zip $build_dist_dir/cdf-deployment-helper.zip
cp $source_dir/infrastructure/lambdaLayers/openssl/build/build.zip $build_dist_dir/cdf-openssl-layer.zip
cp $source_dir/packages/services/provisioning/bundle.zip $build_dist_dir/cdf-provisioning.zip
cp $source_dir/packages/services/command-and-control/bundle.zip $build_dist_dir/cdf-command-and-control.zip


#!/bin/sh

# Export the sheets/tabs of cdf-core-hla.drawio as PNG files for embedding in readme and documentation
# files. This script assumes that the draw.io executable is installed locally and available on the PATH.
# See https://github.com/jgraph/drawio-desktop/ for draw.io installers.
#
# Unused HLA diagrams in cdf-core-hla.drawio (tab index, CDF module name):
# 5 Commands (deprecated)
# 11 Certificate Renewer

draw.io --export --format png --page-index 0 --output "./cdf-core-hla-lifecycle.png" cdf-core-hla.drawio
cp cdf-core-hla.drawio.license "./cdf-core-hla-lifecycle.png.license"
draw.io --export --format png --page-index 1 --output "./cdf-core-hla-HLA.png" cdf-core-hla.drawio
cp cdf-core-hla.drawio.license "./cdf-core-hla-HLA.png.license"
draw.io --export --format png --page-index 2 --output "./cdf-core-hla-hla-aws.png" cdf-core-hla.drawio
cp cdf-core-hla.drawio.license "./cdf-core-hla-hla-aws.png.license"
draw.io --export --format png --page-index 3 --output "../../packages/services/assetlibrary/docs/images/cdf-core-hla-Asset Library.png" cdf-core-hla.drawio
cp cdf-core-hla.drawio.license "../../packages/services/assetlibrary/docs/images/cdf-core-hla-Asset Library.png.license"
draw.io --export --format png --page-index 4 --output "../../packages/services/bulkcerts/docs/images/bulkcerts.hla.png" cdf-core-hla.drawio
cp cdf-core-hla.drawio.license "../../packages/services/bulkcerts/docs/images/bulkcerts.hla.png.license"
draw.io --export --format png --page-index 6 --output "../../packages/services/device-patcher/docs/images/device-patcher-hla.png" cdf-core-hla.drawio
cp cdf-core-hla.drawio.license "../../packages/services/device-patcher/docs/images/device-patcher-hla.png.license"
draw.io --export --format png --page-index 7 --output "../../packages/services/greengrass2-provisioning/docs/images/greengrass2-hla.png" cdf-core-hla.drawio
cp cdf-core-hla.drawio.license "../../packages/services/greengrass2-provisioning/docs/images/greengrass2-hla.png.license"
draw.io --export --format png --page-index 8 --output "../../packages/services/provisioning/docs/images/provisioning.hla.png" cdf-core-hla.drawio
cp cdf-core-hla.drawio.license "../../packages/services/provisioning/docs/images/provisioning.hla.png.license"
draw.io --export --format png --page-index 9 --output "../../packages/services/certificateactivator/docs/images/certificateactivator-hla.png" cdf-core-hla.drawio
cp cdf-core-hla.drawio.license "../../packages/services/certificateactivator/docs/images/certificateactivator-hla.png.license"
draw.io --export --format png --page-index 10 --output "../../packages/services/certificatevendor/docs/images/certificatevendor-hla.png" cdf-core-hla.drawio
cp cdf-core-hla.drawio.license "../../packages/services/certificatevendor/docs/images/certificatevendor-hla.png.license"


#!/bin/sh
#-----------------------------------------------------------------------------------------------------------------------
#   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. A copy of the License is located at
#
#      http://www.apache.org/licenses/LICENSE-2.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, express or implied. See the License for the specific language governing permissions
#  and limitations under the License.
#-----------------------------------------------------------------------------------------------------------------------

export JMETER_VERSION="5.4.3"
export AWSCLI_VERSION="1.16.278"
export JMETER_PLUGINS_MANAGER_VERSION="1.3"
export CMDRUNNER_VERSION="2.2"
export JSON_LIB_VERSION="2.4"
export JSON_LIB_FULL_VERSION="${JSON_LIB_VERSION}-jdk15"

export JMETER_HOME=/opt/apache-jmeter-${JMETER_VERSION}
export JMETER_BIN=${JMETER_HOME}/bin
export PATH=$PATH:$JMETER_BIN
export JMETER_DOWNLOAD_URL=https://archive.apache.org/dist/jmeter/binaries/apache-jmeter-${JMETER_VERSION}.tgz
export RESULTS_LOG=results.jtl
export PATH=/root/.local/bin:$PATH

# install aws cli
apk add --update \
    python \
    python-dev \
    py-pip \
    build-base \
    && pip install awscli==$AWSCLI_VERSION --upgrade --user \
    && apk --purge -v del py-pip \
    && rm -rf /var/cache/apk/*

# Install jmeter
apk update \
	&& apk upgrade \
	&& apk add ca-certificates \
	&& update-ca-certificates \
	&& apk add --update openjdk8-jre tzdata curl unzip bash \
	&& apk add --no-cache nss \
	&& rm -rf /var/cache/apk/* \
	&& mkdir -p /tmp/dependencies  \
	&& curl -L --silent ${JMETER_DOWNLOAD_URL} >  /tmp/dependencies/apache-jmeter-${JMETER_VERSION}.tgz  \
	&& mkdir -p /opt  \
	&& tar -xzf /tmp/dependencies/apache-jmeter-${JMETER_VERSION}.tgz -C /opt  \
	&& rm -rf /tmp/dependencies

# Install jmeter plugins
cd /tmp/ \
 && 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 \
 && 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 \
 && 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 \
 && 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 \
 && java -cp ${JMETER_HOME}/lib/ext/jmeter-plugins-manager-${JMETER_PLUGINS_MANAGER_VERSION}.jar org.jmeterplugins.repository.PluginManagerCMDInstaller \
 && PluginsManagerCMD.sh install \
blazemeter-debugger=0.6,\
bzm-hls=2.0,\
bzm-http2=1.4.1,\
bzm-parallel=0.9,\
bzm-random-csv=0.6,\
bzm-rte=2.2,\
bzm-siebel=0.1.0-beta,\
custom-soap=1.3.3,\
jmeter.backendlistener.elasticsearch=2.6.9,\
jmeter.backendlistener.kafka=1.0.0,\
jmeter.pack-listener=1.7,\
jpgc-autostop=0.1,\
jpgc-casutg=2.9,\
jpgc-cmd=2.2,\
jpgc-csl=0.1,\
jpgc-csvars=0.1,\
jpgc-dbmon=0.1,\
jpgc-directory-listing=0.3,\
jpgc-dummy=0.4,\
jpgc-ffw=2.0,\
jpgc-fifo=0.2,\
jpgc-filterresults=2.2,\
jpgc-functions=2.1,\
jpgc-ggl=2.0,\
jpgc-graphs-additional=2.0,\
jpgc-graphs-basic=2.0,\
jpgc-graphs-composite=2.0,\
jpgc-graphs-dist=2.0,\
jpgc-graphs-vs=2.0,\
jpgc-hadoop=2.0,\
jpgc-httpraw=0.1,\
jpgc-jms=0.2,\
jpgc-jmxmon=0.2,\
jpgc-json=2.7,\
jpgc-lockfile=0.1,\
jpgc-mergeresults=2.1,\
jpgc-pde=0.1,\
jpgc-perfmon=2.1,\
jpgc-plancheck=2.4,\
jpgc-prmctl=0.4,\
jpgc-redis=0.3,\
jpgc-rotating-listener=0.2,\
jpgc-sense=3.5,\
jpgc-standard=2.0,\
jpgc-sts=2.4,\
jpgc-synthesis=2.2,\
jpgc-tst=2.5,\
jpgc-udp=0.4,\
jpgc-webdriver=3.1,\
jpgc-wsc=0.7,\
jpgc-xml=0.1,\
jpgc-xmpp=1.5.1,\
kafkameter=0.2.0,\
netflix-cassandra=0.2-SNAPSHOT,\
ssh-sampler=1.1.1-SNAPSHOT,\
tilln-iso8583=1.0,\
tilln-sshmon=1.2,\
tilln-wssecurity=1.7,\
websocket-sampler=1.0.2-SNAPSHOT,\
websocket-samplers=1.2.2 \
 && jmeter --version \
 && PluginsManagerCMD.sh status \
 && chmod +x ${JMETER_HOME}/bin/*.sh \
 && rm -fr /tmp/*

##### # node setup

export VERSION=v8.16.2
export NPM_VERSION=6

apk add --no-cache curl make gcc g++ python linux-headers binutils-gold gnupg libstdc++ && \
  for server in ipv4.pool.sks-keyservers.net keyserver.pgp.com ha.pool.sks-keyservers.net; do \
    gpg --keyserver $server --recv-keys \
      4ED778F539E3634C779C87C6D7062848A1AB005C \
      B9E2F5981AA6E0CD28160D9FF13993A75599653C \
      94AE36675C464D64BAFA68DD7434390BDBE9B9C5 \
      B9AE9905FFD7803F25714661B63B535A4C206CA9 \
      77984A986EBC2AA786BC0F66B01FBB92821C587A \
      71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 \
      FD3A5288F042B6850C66B31F09FE44734EB7990E \
      8FCCA13FEF1D0C2E91008E09770F7A9A5AE15600 \
      C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8 \
      DD8F2338BAE7501E3DD5AC78C273792F7D83545D \
      A48C2BEE680E841632CD4E44F07496B3EB3C1762 && break; \
  done && \
  curl -sfSLO https://nodejs.org/dist/${VERSION}/node-${VERSION}.tar.xz && \
  curl -sfSL https://nodejs.org/dist/${VERSION}/SHASUMS256.txt.asc | gpg -d -o SHASUMS256.txt && \
  grep " node-${VERSION}.tar.xz\$" SHASUMS256.txt | sha256sum -c | grep ': OK$' && \
  tar -xf node-${VERSION}.tar.xz && \
  cd node-${VERSION} && \
  ./configure --prefix=/usr ${CONFIG_FLAGS} && \
  make -j$(getconf _NPROCESSORS_ONLN) && \
  make install && \
  cd / && \
  if [ -z "$CONFIG_FLAGS" ]; then \
    if [ -n "$NPM_VERSION" ]; then \
      npm install -g npm@${NPM_VERSION}; \
    fi; \
    find /usr/lib/node_modules/npm -name test -o -name .bin -type d | xargs rm -rf; \
    if [ -n "$YARN_VERSION" ]; then \
      for server in ipv4.pool.sks-keyservers.net keyserver.pgp.com ha.pool.sks-keyservers.net; do \
        gpg --keyserver $server --recv-keys \
          6A010C5166006599AA17F08146C2130DFD2497F5 && break; \
      done && \
      curl -sfSL -O https://yarnpkg.com/${YARN_VERSION}.tar.gz -O https://yarnpkg.com/${YARN_VERSION}.tar.gz.asc && \
      gpg --batch --verify ${YARN_VERSION}.tar.gz.asc ${YARN_VERSION}.tar.gz && \
      mkdir /usr/local/share/yarn && \
      tar -xf ${YARN_VERSION}.tar.gz -C /usr/local/share/yarn --strip 1 && \
      ln -s /usr/local/share/yarn/bin/yarn /usr/local/bin/ && \
      ln -s /usr/local/share/yarn/bin/yarnpkg /usr/local/bin/ && \
      rm ${YARN_VERSION}.tar.gz*; \
    fi; \
  fi && \
  apk del curl make gcc g++ python linux-headers binutils-gold gnupg ${DEL_PKGS} && \
  rm -rf ${RM_DIRS} /node-${VERSION}* /SHASUMS256.txt /tmp/* /var/cache/apk/* \
    /usr/share/man/* /usr/share/doc /root/.npm /root/.node-gyp /root/.config \
    /usr/lib/node_modules/npm/man /usr/lib/node_modules/npm/doc /usr/lib/node_modules/npm/html /usr/lib/node_modules/npm/scripts && \
  { rm -rf /root/.gnupg || true; }


#!/bin/sh
#-----------------------------------------------------------------------------------------------------------------------
#   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. A copy of the License is located at
#
#      http://www.apache.org/licenses/LICENSE-2.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, express or implied. See the License for the specific language governing permissions
#  and limitations under the License.
#-----------------------------------------------------------------------------------------------------------------------
set -x

freeMem=`awk '/MemFree/ { print int($2/1024) }' /proc/meminfo`
s=$(($freeMem/10*8))
x=$(($freeMem/10*8))
n=$(($freeMem/10*2))
export JVM_ARGS="-Xmn${n}m -Xms${s}m -Xmx${x}m"

echo "START Running Jmeter on `date`"
echo "JVM_ARGS=${JVM_ARGS}"
echo "jmeter args=$@"

# empty the logs directory, or jmeter may fail
rm -rf /opt/jmeter/*.log /opt/jmeter/*.jtl

rm -rf "$JMETER_BIN/cdf"
mkdir -p "$JMETER_BIN/cdf"

# download the test plan and properties from S3
aws s3 cp "s3://$BUCKET/$TEST_PLAN" "$JMETER_BIN/cdf/plan.jmx"
aws s3 cp "s3://$BUCKET/$EXTERNAL_PROPERTIES" "$JMETER_BIN/cdf/config.properties"

# launch jmeter
set +e
cd /opt/jmeter
jmeter -n $JMETER_FLAGS \
  -p "$JMETER_BIN/cdf/config.properties" \
  -l results.jtl \
  -j logfile.txt \
  -t "$JMETER_BIN/cdf/plan.jmx" \
  || true

# need to wait for jmeter to finish writing to the logs once it shuts down
sleep 5

# upload logs and results to s3
aws s3 cp logfile.txt "s3://$BUCKET/$UPLOAD_DIR"logfile.txt
aws s3 cp results.jtl "s3://$BUCKET/$UPLOAD_DIR"results.jtl

echo "Logs...."
cat logfile.txt

echo "Results..."
cat results.jtl


#!/bin/bash

if [[ "$1" == "implementation" ]]; then
  mkdir -p runtimes/java/src/main/dafny-generated
  for directory in runtimes/java/temp/AwsCryptographyDbEncryptionSdkDynamoDbMiddlewareInternal-java/*; do
    mv "$directory" "runtimes/java/src/main/dafny-generated/"
  done
  exit 0
elif [[ "$1" == "test" ]]; then
  # With the runAllTests flag, dafny generates an entry point for the tests that we want,
  # so we copy all files to the test destination.
  mkdir -p runtimes/java/src/test/dafny-generated
  for allFiles in runtimes/java/temp-tests/AwsCryptographyDbEncryptionSdkDynamoDbMiddlewareInternalTests-java/*; do
    mv "$allFiles" "runtimes/java/src/test/dafny-generated/"
  done
  exit 0
else
  echo "makefile_helper needs either implementation or test argument"
  echo "i.e: ./runtimes/java/makefile_helper.sh test"
  exit 1
fi


#!/usr/bin/env bash

dotnet build AWS.Deploy.sln --configuration Release

dotnet test AWS.Deploy.sln --no-build


#!/bin/bash
# Minimal wrapper script for upstream requirements install and freeze.
# We do this here rather than as tox commands because tox does not support output redirection.
if [ -z ${1} ]; then
    exit 1
fi

pip install -r requirements.txt
pip install -r dev_requirements/test-requirements.txt
pip freeze > ${1}


#!/bin/bash
# Verify that tests can be successfully run from the source build.
#
#NOTE: Humans should not run this file directly. If you want to run this check, use the
#   tox to run the "sourcebuildcheck" test environment.

WORKINGDIR=${1}
DISTDIR=${2}

echo "Performing source build check"
echo "Using working directory ${WORKINGDIR}"
echo "Using dist directory ${DISTDIR}"

echo "Locating the source build and copying it into the working directory."
DISTFILE=$(ls ${DISTDIR}/dynamodb-encryption-sdk-*.tar.gz | tail -1)
echo "Found source build at ${DISTFILE}"
cp ${DISTFILE} ${WORKINGDIR}

echo "Extracting the source build."
cd ${WORKINGDIR}
NEWDISTFILE=$(ls dynamodb-encryption-sdk-*.tar.gz | tail -1)
echo "Using distfile ${NEWDISTFILE}"
tar xzvf ${NEWDISTFILE}
rm ${NEWDISTFILE}
EXTRACTEDDIR=$(ls | tail -1)
cd ${EXTRACTEDDIR}

echo "Installing requirements from extracted source build."
pip install -r dev_requirements/test-requirements.txt
pip install -e .

echo "Running tests from extracted source build."
pytest --cov dynamodb_encryption_sdk -m "local and not slow and not veryslow and not nope"


#!/bin/bash
set -e

defaultVersion=4.1-jdk8

versions=( 4.0-jdk7 4.1-jdk8 )
url='git://github.com/aws/aws-eb-glassfish'

echo '# maintainer: Amazon Web Services <https://aws.amazon.com/contact-us/> (@aws)'

for version in "${versions[@]}"; do
	commit="$(git log -1 --format='format:%H' -- "$version")"

	glassfishVersion="${version%%-*}"
	jdkVersion="${version#*-}" # "jdk7"

	versionAliases=( $glassfishVersion-$jdkVersion $glassfishVersion) # 4.0-jdk7 4.0

	if [ "$glassfishVersion-$jdkVersion" = "$defaultVersion" ]; then
		versionAliases+=( latest )
	fi

	echo
	for va in "${versionAliases[@]}"; do
		echo "$va: ${url}@${commit} $version"
	done
done


#!/bin/sh

PID_FILE=$GLASSFISH_HOME/glassfish/domains/domain1/config/pid

# when deploying a directory, Glassfish expect all submodules to be extracted
# which is usually not the case for EARs
# zip app back into a bundle and let Glassfish handle it
rm -f /var/app/Dockerfile
rm -f /var/app/Dockerrun.aws.json
zip /var/app.zip -r .

asadmin start-domain
asadmin deploy --contextroot / --name current-app /var/app.zip

inotifywait -qq -e delete_self $PID_FILE


#!/bin/sh

PID_FILE=$GLASSFISH_HOME/glassfish/domains/domain1/config/pid

# when deploying a directory, Glassfish expect all submodules to be extracted
# which is usually not the case for EARs
# zip app back into a bundle and let Glassfish handle it
rm -f /var/app/Dockerfile
rm -f /var/app/Dockerrun.aws.json
zip -r /var/app.zip .

asadmin start-domain
asadmin deploy --contextroot / --name current-app /var/app.zip

inotifywait -qq -e delete_self $PID_FILE


#!/bin/bash

cd /var/app

. bin/activate

# Django support
if cat requirements.txt | grep -q -i Django && [ -z "$WSGI_PATH" ]; then
	WSGI_PATH=`find /var/app | egrep '/var/app/[^/]+/wsgi.py'`
fi

# Flask support
if cat requirements.txt | grep -q -i Flask && [ -z "$WSGI_MODULE" ]; then
	WSGI_MODULE=application:app
fi

[ -n "$WSGI_MODULE" ] && UWSGI_MODULE="--module $WSGI_MODULE"

# defaulting to application.py if not explicitly set
[ -z "$WSGI_PATH" ] && WSGI_PATH=application.py

uwsgi --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


#!/bin/bash

# Copyright 2019 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.

# Reads authorized keys blob $3 and prints verified, unexpired keys
# Openssl to use provided as $1
# Signer public key file path provided as $2

# Runs our full suite of integration tests against all known instance types

# Basic string concat w/ newline
concat () {
    printf "%s\n%s" "${1}" "${2}"
}

TOPDIR=$(dirname "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)")

if [ $# -lt 8 ] ; then
    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]"
    exit 1
fi

types_specified=0

while getopts ":r:a:k:s:g:d:p:t:u:l:i:" opt ; do
    case "${opt}" in
        r)
            region="${OPTARG}"
            ;;
        a)
            ami_id="${OPTARG}"
            ;;
        k)
            key_name="${OPTARG}"
            ;;
        s)
            subnet_id="${OPTARG}"
            ;;
        g)
            security_group_id="${OPTARG}"
            ;;
        d)
            output_directory="${OPTARG}"
            ;;
        p)
            private_key="${OPTARG}"
            ;;
        t)
            IFS=',' read -r -a instance_types <<< "${OPTARG}"
            types_specified=1
            ;;
        u)
            osuser="${OPTARG}"
            ;;
        l)
            distro="${OPTARG}"
            ;;
        i)
            package_path="${OPTARG}"
            ;;
        *)
            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]"
            exit 1
            ;;
    esac
done

# Ensure we have config for this distro
if [ ! -f "${TOPDIR}/integration-test/config/${distro}" ] ; then
    echo "Unsupported distro ${distro} will not be tested"
    exit 1
fi

source "${TOPDIR}/integration-test/config/${distro}"

package_name="${package_path##*/}"

if [ -z "${output_directory}" ] ; then
    timestamp=$(/bin/date -u "+%Y-%m-%d_%H:%M:%S")
    # TODO: Better autogenerated directory.  Include AMI/test name?
    output_directory="/tmp/eic_integ_test_${timestamp}"
    echo "No output directory set.  Creating & using ${output_directory}"
    mkdir "${output_directory}"
fi

# Fetch information about the subnet (AZ, etc)
subnet_output=$(aws ec2 describe-subnets --subnet-ids "${subnet_id}")
subnet_status=$?
if [ "${subnet_status}" -ne 0 ] ; then
    echo "Failed to query subnet information:"
    echo "${subnet_output}"
    exit "${subnet_status}"
fi

zone=$(echo "${subnet_output}" | grep "\"AvailabilityZone\"" | cut -d '"' -f 4)

if [ $types_specified -eq 0 ] ; then
    echo "Instance types not specified.  Will test all supported in this subnet."
    instance_types=$("${TOPDIR}/bin/integration-test/get_zone_instance_types.sh" "${region}" "${zone}")
    IFS=$'\n' read -d '' -r -a instance_types <<< "${instance_types}"
fi

overall_exit=0
for instance_type in "${instance_types[@]}" ; do
    echo "Testing ${instance_type}"
    mkdir "${output_directory}/${instance_type}"
    output=""
    instance_exit=0
    # Run instance
    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}")
    launch_status=$?
    if [ "${launch_status}" -ne 0 ] ; then
        output=$(concat "${output}" "${launch_output}")
        instance_exit=1
    else
        instance_id=$launch_output
        public_ip=$(aws ec2 describe-instances --instance-ids "${instance_id}" | grep "PublicIp" | cut -d '"' -f 4 | uniq)
        # scp the package file to the instance and install it
        output=$(concat "${output}" "scping package file to instance")
        scp_out=$(scp -i "${private_key}" -o StrictHostKeyChecking=no "${package_path}" "${osuser}@${public_ip}:/tmp/${package_name}" 2>&1)
        install_status=$?
        output=$(concat "${output}" "${scp_out}")
        if [ "${install_status}" -eq 0 ] ; then
            # FIXME: Ubuntu AMIs fail here due to dpkg lock contention
            ssh -i "${private_key}" -o StrictHostKeyChecking=no "${osuser}@${public_ip}" "${INSTALL} /tmp/${package_name}" 1>/dev/null 2>&1
            install_status=$?
            output=$(concat "${output}" "${scp_out}")
        else
            output=$(concat "${output}" "Failed to scp package to instance.")
            instance_exit=1
        fi
        if [ "${install_status}" -ne 0 ] ; then
            output=$(concat "${output}" "Failed to install EIC package on instance.")
            instance_exit=1
        else
            # Run the actual tests
            "${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}"
            test_exit=$?
            if [ "${test_exit}" -ne 0 ] ; then
                overall_exit=1
            else
                rmdir "${output_directory}/${instance_type}"
            fi
        fi
        # Terminate the instance
        aws ec2 terminate-instances --instance-ids "${instance_id}" 1>/dev/null
    fi
    if [ "${instance_exit}" -ne 0 ] ; then
        echo "Could not run tests on instance."
        echo "${output}" > "${output_directory}/${instance_type}/setup"
        overall_exit=1
    fi
done

if [ "${overall_exit}" -ne 0 ] ; then
    echo "Some instance types failed.  Please check the contents of ${output_directory} for details."
else
    echo "All instance types passed!  Removing failed output directory since it is empty."
    rmdir "${output_directory}"
fi

exit "${overall_exit}"


#!/bin/bash

# Copyright 2019 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.

# Reads authorized keys blob $3 and prints verified, unexpired keys
# Openssl to use provided as $1
# Signer public key file path provided as $2

# XXX: This script builds a local 3.0 (native) package for testing purposes.
# Any actual patches should be developed and submitted using apt-source and Quilt.

# Note: this will only work on a system with dpkg build tools installed (ie, Debian & its derivatives)
# It is also strongly recommended you install devtools (dch, etc) to assist with package building
# You are *REQUIRED* to have debhelper and devscripts installed!

if [ $# -ne 2 ] ; then
    echo "Usage: make_deb.sh [version] [release]"
    echo "    ie, make_deb.sh [1.1] [1]"
    exit 1
fi

md5 () {
    echo -n "${1}" | md5sum | sed 's/\s.*$//'
}

sha1 () {
    echo -n "${1}" | sha1sum | sed 's/\s.*$//'
}

sha256 () {
    echo -n "${1}" | sha256sum | sed 's/\s.*$//'
}

TOPDIR=$(dirname "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )")

version=$1
release=$2
pkgdir="${TOPDIR}/ec2-instance-connect-${version}-${release}"

# Copy source files
mkdir "${pkgdir}"
mkdir -p "${pkgdir}/ec2-instance-connect"
cp "${TOPDIR}"/src/bin/* "${pkgdir}/ec2-instance-connect/"
# Dump /bin, /usr/bin, etc from binary paths names since we want to use $PATH on Ubuntu/etc
sed -i "s%/usr/bin/%%g" "${pkgdir}"/ec2-instance-connect/*
sed -i "s%^/bin/%%g" "${pkgdir}"/ec2-instance-connect/*
sed -i "s%\([^\#][^\!]\)/bin/%\1%g" "${pkgdir}"/ec2-instance-connect/*

mkdir "${pkgdir}/debian"
cp -r "${TOPDIR}"/debian/* "${pkgdir}/debian/"
sed -i "s/\!VERSION\!/${version}-${release}/" "${pkgdir}/debian/control"

# Do the actual packaging
return_dir=$(pwd)
cd "${pkgdir}" || exit 1
debuild

# Clean up
cd "${return_dir}" || exit 1
rm -rf "${pkgdir}"


#!/bin/bash

# Copyright 2019 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.

# Reads authorized keys blob $3 and prints verified, unexpired keys
# Openssl to use provided as $1
# Signer public key file path provided as $2

# Note: this will only work on a system with rpm build tools installed (ie, RHEL & its derivatives)

if [ $# -ne 2 ] ; then
    echo "Usage: make_rpm.sh [version] [release]"
    echo "    ie, make_rpm.sh [1.1] [1]"
    exit 1
fi

TOPDIR=$(dirname "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )")
BUILDDIR="${TOPDIR}/rpmbuild"
mkdir -p "${BUILDDIR}"

version="${1}"
release="${2}"

mkdir -p "${BUILDDIR}"/{BUILD,RPMS,SOURCES,SPECS,SRPMS,ec2-instance-connect-"${version}",tmp}
mkdir -p "${BUILDDIR}/ec2-instance-connect-${version}/opt/aws/bin"
cp "${TOPDIR}"/rpmsrc/SPECS/generic.spec "${BUILDDIR}/SPECS/ec2-instance-connect.spec"
cp "${TOPDIR}"/src/bin/* "${BUILDDIR}/ec2-instance-connect-${version}/opt/aws/bin/"
cp "${TOPDIR}"/rpmsrc/.rpmmacros "${BUILDDIR}/"

/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"

# Trick rpmbuild into thinking this is homedir to read .rpmmacros
REALHOME="${HOME}"
export HOME="${BUILDDIR}"

function cleanup {
    export HOME="${REALHOME}"
    rm -rf "${BUILDDIR}"/{BUILD,SOURCES,tmp}
    rm -rf "${BUILDDIR}/BUILDROOT" # In case we got far enough for this to exist
    rm -rf "${BUILDDIR}/ec2-instance-connect-${version}"
}
trap cleanup EXIT

ls "${BUILDDIR}/SOURCES"

cd "${BUILDDIR}" || exit 1 # Will ensure some paths are set correctly in rpmbuild

# Compress the scripts
tar -czf "${BUILDDIR}/SOURCES/ec2-instance-connect-${version}.tar.gz" "ec2-instance-connect-${version}/"

# Fill in the placeholders
sed -i "s/\!VERSION\!/${version}/" "${BUILDDIR}/SPECS/ec2-instance-connect.spec"
sed -i "s/\!RELEASE\!/${release}/" "${BUILDDIR}/SPECS/ec2-instance-connect.spec"

# Build the package
rpmbuild -ba "${BUILDDIR}/SPECS/ec2-instance-connect.spec"

cp "${BUILDDIR}/RPMS/noarch/ec2-instance-connect-${version}-${release}.noarch.rpm" "${TOPDIR}/"


#!/bin/bash

# Copyright 2019 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.

# Reads authorized keys blob $3 and prints verified, unexpired keys
# Openssl to use provided as $1
# Signer public key file path provided as $2

TOPDIR=$(dirname "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )")

verrel="$(cat "${TOPDIR}/VERSION")"
version="${verrel%-*}"
pkgver="ec2-instance-connect-${version}"

mkdir -p "${TOPDIR}/${pkgver}/opt/aws/bin"
cp "${TOPDIR}"/src/bin/* "${TOPDIR}/${pkgver}/opt/aws/bin/"
if [ $# -eq 1 ] ; then # TODO: better check.  Low-priority.
    /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"
fi
tar -czf "${TOPDIR}/${pkgver}.tar.gz" -C "${TOPDIR}" "${pkgver}/"
rm -rf "${TOPDIR:?}/${pkgver:?}"/*
rmdir "${TOPDIR}/${pkgver}"


#!/bin/bash

# Copyright 2019 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.

# Reads authorized keys blob $3 and prints verified, unexpired keys
# Openssl to use provided as $1
# Signer public key file path provided as $2

# Script to run our entire unit test suite.
# Iterates over the contents of test/input/direct and test/input/unsigned and validates we get the matching contents of unit-test/expected-output

OPENSSL="/usr/bin/openssl"
TOPDIR=$(dirname "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)")

tmpdir=$(mktemp -d /dev/shm/tmp-XXXXXXXX)
trap 'rm -rf "${tmpdir}"' EXIT

# Generate test certificates
"${TOPDIR}/bin/unit-test/setup_certificates.sh" "${OPENSSL}" "${tmpdir}"
# Combine unittest & intermediate into the trust chain for the actual AuthorizedKeysCommand
cat "${tmpdir}/unittest.pem" "${tmpdir}/intermediate.pem" "${tmpdir}/ca.pem" > "${tmpdir}/chain.pem"

intermediate_fingerprint="$(openssl x509 -noout -fingerprint -sha1 -inform pem -in "${tmpdir}/intermediate.pem" | sed -n 's/SHA1 Fingerprint=\(.*\)/\1/p' | tr -d ':')"
unittest_fingerprint="$(openssl x509 -noout -fingerprint -sha1 -inform pem -in "${tmpdir}"/unittest.pem | sed -n 's/SHA1 Fingerprint=\(.*\)/\1/p' | tr -d ':')"

# Generate OCSP for those certificates
"${TOPDIR}/bin/unit-test/generate_ocsp.sh" "${OPENSSL}" "${tmpdir}/intermediate.crt" "${tmpdir}/ca" "${tmpdir}/${intermediate_fingerprint}"
"${TOPDIR}/bin/unit-test/generate_ocsp.sh" "${OPENSSL}" "${tmpdir}/unittest.crt" "${tmpdir}/intermediate" "${tmpdir}/${unittest_fingerprint}"

exit_status=0

# Direct input tests
for testfile in "${TOPDIR}"/unit-test/input/direct/* ; do
    filename="${testfile##*/}"
    "${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}"
    result="${?}"
    if [ "${result}" -ne 0 ] ; then
        exit_status=1
    fi
done

# Tests that require signing input data
for testdir in "${TOPDIR}"/unit-test/input/unsigned/* ; do
    # Generate signatures for key blobs
    filename="${testdir##*/}"
    if [ "$("${TOPDIR}/bin/unit-test/sign_data.sh" "${OPENSSL}" "${tmpdir}/unittest.key" "${testdir}" "${tmpdir}/${filename}")" ] ; then
        echo "Unable to run test ${filename}: signature generation failed"
    else
        # Run the actual test
        "${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}"
        result="${?}"
        if [ "${result}" -ne 0 ] ; then
            exit_status=1
        fi
    fi
done

rm -rf "${tmpdir:?}"

exit "${exit_status}"


#!/bin/bash

# Copyright 2019 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.

# Reads authorized keys blob $3 and prints verified, unexpired keys
# Openssl to use provided as $1
# Signer public key file path provided as $2

# Load the list of instance types supported in a given zone.
# XXX: The mechanism for this is based on reserved instances. This may not be exhaustive in every zone.

region=$1
zone=$2

raw=$(aws ec2 describe-reserved-instances-offerings --filters "Name=availability-zone,Values=$zone" --region "${region}")
types=$(echo "{$raw}" | grep "InstanceType" | cut -d '"' -f 4)
echo "${types}"


#!/bin/bash

# Copyright 2019 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.

# Reads authorized keys blob $3 and prints verified, unexpired keys
# Openssl to use provided as $1
# Signer public key file path provided as $2

# Attempts to launch an instance to the given specification
# Outputs instance ID on success or where it failed otherwise

while getopts ":t:r:a:k:s:g:n:o:p:" opt ; do
    case "${opt}" in
        t)
            instance_type="${OPTARG}"
            ;;
        r)
            region="${OPTARG}"
            ;;
        a)
            ami_id="${OPTARG}"
            ;;
        k)
            key_name="${OPTARG}"
            ;;
        s)
            subnet_id="${OPTARG}"
            ;;
        g)
            security_group_id="${OPTARG}"
            ;;
        n)
            name_tag="${OPTARG}"
            ;;
        o)
            osuser="${OPTARG}"
            ;;
        p)
            private_key="${OPTARG}"
            ;;
        *)
            echo "Usage: $0 -t instance-type -r aws-region -a ami -k ec2-key-pair -s subnet -g security-group -n name-tag-value"
            exit 1
            ;;
    esac
done

launch_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}\"}]}]")
launch_code=$?
if [ "${launch_code}" -ne 0 ] ; then
    echo "Instance launch failed!"
    exit "${launch_code}"
fi

instance_id=$(echo "${launch_output}" | grep \"InstanceId\" | cut -d '"' -f 4)
running=0
try="0"
# Wait up to 5 minutes for the instance to come up, checking every 5 seconds
while [ $try -lt 60 ] ; do
    aws ec2 describe-instances --instance-ids "${instance_id}" | grep "Name" | grep -q "running"
    launch_code=$?
    if [ "${launch_code}" -eq 0 ] ; then
        try="60"
        running=1
    else
        try=$((try+1))
        sleep 5
    fi
done
if [ $running -eq 0 ] ; then
    echo "Timed out waiting for instance to enter 'running' state"
    exit 1
fi

# Wait a bit extra to let sshd come up
ssh_try="0"
public_ip=$(aws ec2 describe-instances --instance-ids "${instance_id}" | grep "PublicIp" | cut -d '"' -f 4 | uniq)
while [ $ssh_try -lt 30 ] ; do
    ssh -q -i "${private_key}" -o StrictHostKeyChecking=no "${osuser}@${public_ip}" exit 2>&1
    launch_code="${?}"
    if [ "${launch_code}" -eq 0 ] ; then
        # Everything's ready
        echo "${instance_id}"
        exit 0
    fi
    ssh_try=$((ssh_try+1))
    sleep 10
done
echo "Timed out waiting for sshd to start on instance (or keypair is misconfigured)"
exit 1


#!/bin/bash

# Copyright 2019 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.

# Reads authorized keys blob $3 and prints verified, unexpired keys
# Openssl to use provided as $1
# Signer public key file path provided as $2

TOPDIR=$(dirname "$( cd "$( dirname "$( dirname "${BASH_SOURCE[0]}" )" )" && pwd)")

while getopts ":i:p:k:u:z:o:l:f:" opt ; do
    case "${opt}" in
        i)
            instance_id="${OPTARG}"
            ;;
        p)
            public_ip="${OPTARG}"
            ;;
        k)
            keypath="${OPTARG}"
            ;;
        u)
            osuser="${OPTARG}"
            ;;
        z)
            zone="${OPTARG}"
            ;;
        o)
            output_directory="${OPTARG}"
            ;;
        l)
            distro="${OPTARG}"
            ;;
        f)
            package_path="${OPTARG}"
            ;;
        *)
            ;;
    esac
done

overall_success=0
for testscript in "${TOPDIR}"/integration-test/test/* ; do
    filename="${testscript##*/}"
    test_output=$($testscript -i "${instance_id}" -p "${public_ip}" -z "${zone}" -u "${osuser}" -k "${keypath}" -l "${distro}" -t "${package_path}")
    test_exit="${?}"
    if [ "${test_exit}" -ne 0 ] ; then
        echo "${test_output}" > "${output_directory}/${filename}"
        echo "Test ${filename} FAILED"
        overall_success=1
    else
        echo "Test ${filename} PASSED"
    fi
done

exit "${overall_success}"


#!/bin/bash

# Copyright 2019 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.

# Reads authorized keys blob $3 and prints verified, unexpired keys
# Openssl to use provided as $1
# Signer public key file path provided as $2

# Unit test helper to generate an OCSP response in the desired location

if [ -z "${1}" ] ; then
    echo "No openssl provided"
    exit 1
fi

if [ -z "${2}" ] ; then
    echo "No certificate file provided"
    exit 2
fi

if [ -z "${3}" ] ; then
    echo "No CA filepath provided (do not include file extension - this path will be used with .crt, .key, and .cdb.index)"
    exit 3
fi

if [ -z "${4}" ] ; then
    echo "No output file specified"
    exit 4
fi

tmpfile=$(mktemp /dev/shm/tmp-XXXXXXXX)

# Generate the OCSP request

"${1}" ocsp -no_nonce -issuer "${3}.crt" -cert "${2}" -VAfile "${3}".crt -reqout "${tmpfile}"

# Generate the response
# 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.
"${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

# Drop the request, we don't need it anymore
rm -f "${tmpfile}"