#!/usr/bin/env bash

echo 'Listing available android sdks for installation'
$ANDROID_HOME/tools/bin/sdkmanager --list | grep system-images

emulatorImage='system-images;android-28;google_apis;x86_64'
avdName='Pixel_9.0'

echo ''
echo "Installing emulator image ${emulatorImage}"
echo "y" | $ANDROID_HOME/tools/bin/sdkmanager --install $emulatorImage

echo ''
echo "Creating android emulator with name ${avdName}"
echo "no" | $ANDROID_HOME/tools/bin/avdmanager create avd -n $avdName -k $emulatorImage --force

echo ''
echo 'Listing active android emulators'
$ANDROID_HOME/emulator/emulator -list-avds

echo ''
echo "Starting emulator in background thread"
nohup $ANDROID_HOME/emulator/emulator -avd $avdName -gpu auto -no-snapshot > /dev/null 2>&1 &

echo ''
echo 'Waiting for emulator to boot up...'
$ANDROID_HOME/platform-tools/adb wait-for-device shell 'while [[ -z $(getprop sys.boot_completed | tr -d '\r') ]]; do sleep 1; done; input keyevent 82'
echo ''
echo "Emulator started"

$ANDROID_HOME/platform-tools/adb devices


#!/usr/bin/env bash

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

# make sure we have correct version of code generator
cd $GOPATH/src/k8s.io/code-generator/

# https://stackoverflow.com/a/6245587/697126
currentbranch=$(git branch | grep \* | cut -d ' ' -f2)

if [[ $currentbranch != "release-1.14" ]]
then
  git fetch --all
  git checkout -t origin/release-1.14
else
  echo "on correct branch"
fi


#!/bin/bash

# Adapted for this project from cert-manager
# License: https://github.com/jetstack/cert-manager/blob/master/LICENSE
# Script: https://github.com/jetstack/cert-manager/blob/master/hack/update-deploy-gen.sh
set -euo pipefail
IFS=$'\n\t'

SCRIPT_ROOT=$(dirname "${BASH_SOURCE}")
REPO_ROOT="${SCRIPT_ROOT}/.."

gen() {
	OUTPUT=$1
    VALUES_PATH=""
	TMP_OUTPUT=$(mktemp)
	mkdir -p "$(dirname ${OUTPUT})"
    VALUES=${2:-}
    if [[ ! -z "$VALUES" ]]; then
        VALUES_PATH="--values=${SCRIPT_ROOT}/deploy/values/${VALUES}.yaml"
    fi
    helm template \
        "${REPO_ROOT}/charts/azure-k8s-metrics-adapter/" \
        --namespace "custom-metrics" \
        --name "azure-k8s-metrics-adapter" \
        --set "fullnameOverride=azure-k8s-metrics-adapter" \
		--set "createNamespaceResource=true" > "${TMP_OUTPUT}" \
        ${VALUES_PATH}

	mv "${TMP_OUTPUT}" "${OUTPUT}"
}

# Additional deployment files can be generated here with the following format:
#   gen /path/to/deployment-file.yaml [values.yaml file name in deploy/values]
#   gen ${REPO_ROOT}/deploy/adapter.yaml the-values
gen "${REPO_ROOT}/deploy/adapter.yaml"


#!/usr/bin/env bash

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

GOPATH="${GOPATH:-$HOME/go}"

DIVIDER="============================================================"

echo "Checking for a current cluster context"
kubectl config current-context

echo; echo "Checking that cluster nodes are ready"
JSONPATH='{range .items[*]}{@.metadata.name}{"\t"}Ready={@.status.conditions[?(@.type=="Ready")].status}{"\n"}{end}'
kubectl get nodes -o jsonpath="$JSONPATH"
if kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=False"; then
    exit 1
fi

echo; echo "Checking helm and tiller install"
helm version

echo; echo "Checking for other pre-reqs"
which jq        # Used to format some command output
which docker

# If the script fails on error here, the deployment won't be cleaned up properly
set +o errexit

echo; echo "Running deployment scripts"
cd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/hack/e2e-scripts
chmod +x *.sh

TEST_FAILED=0

./deploy-adapter-with-sp.sh
if [[ $? = 0 ]]; then
    echo "Testing Queue (Azure Monitor) metrics"
    ./configure-queue-metrics.sh
    ./gen-and-check-queue-messages.sh
    if [[ $? = 0 ]];
        then echo $DIVIDER; echo "PASS"; echo $DIVIDER
        else echo $DIVIDER; echo "FAIL"; echo $DIVIDER; TEST_FAILED=1;
    fi

    ./run-queue-consumer.sh

    echo "Testing Topic Subscriptions metrics"
    ./configure-topic-subscriptions-metrics.sh
    ./gen-and-check-topic-subscriptions-messages.sh
    if [[ $? = 0 ]];
        then echo $DIVIDER; echo "PASS"; echo $DIVIDER
        else echo $DIVIDER; echo "FAIL"; echo $DIVIDER; TEST_FAILED=1;
    fi

    ./run-topic-consumer.sh
else
    echo $DIVIDER; echo "FAIL"; echo $DIVIDER; TEST_FAILED=1;
fi

echo "Removing adapter deployment"
helm delete --purge adapter

if [[ $TEST_FAILED == 1 ]]; then
    echo $DIVIDER; echo "FAIL"; echo $DIVIDER;
    exit 1
fi


#!/usr/bin/env bash

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

CGO_ENABLED=0 go test $(go list ./... | grep -v -e '/client/' -e '/samples/' -e '/apis/')


#!/usr/bin/env bash

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

SCRIPT_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
CODEGEN_PKG=${CODEGEN_PKG:-$(cd "${SCRIPT_ROOT}"; ls -d -1 ./vendor/k8s.io/code-generator 2>/dev/null || echo ../code-generator)}
chmod +x ${CODEGEN_PKG}/generate-groups.sh

"${CODEGEN_PKG}"/generate-groups.sh all \
    github.com/Azure/azure-k8s-metrics-adapter/pkg/client \
    github.com/Azure/azure-k8s-metrics-adapter/pkg/apis \
    metrics:v1alpha2 \
    --go-header-file "${SCRIPT_ROOT}"/hack/boilerplate.go.txt


#!/usr/bin/env bash
#
# Modified under license:
#
# Copyright 2017 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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

PROJECT_ROOT=$(dirname "${BASH_SOURCE}")/..

DIFFROOT="${PROJECT_ROOT}/pkg/apis"
TMP_DIFFROOT="${PROJECT_ROOT}/_tmp/pkg/apis"
_tmp="${PROJECT_ROOT}/_tmp"

cleanup() {
  rm -rf "${_tmp}"
}
trap "cleanup" EXIT SIGINT

cleanup

mkdir -p "${TMP_DIFFROOT}"
cp -a "${DIFFROOT}"/* "${TMP_DIFFROOT}"

"${PROJECT_ROOT}/hack/update-codegen.sh"
echo "diffing ${DIFFROOT} against freshly generated codegen"
ret=0
diff -Naupr "${DIFFROOT}" "${TMP_DIFFROOT}" || ret=$?
cp -a "${TMP_DIFFROOT}"/* "${DIFFROOT}"
if [[ $ret -eq 0 ]]
then
  echo "${DIFFROOT} up to date."
else
  echo "${DIFFROOT} is out of date. Please run hack/update-codegen.sh"
  exit 1
fi


#!/bin/bash

# Adapted for this project from cert-manager
# License: https://github.com/jetstack/cert-manager/blob/master/LICENSE
# Script: https://github.com/jetstack/cert-manager/blob/master/hack/verify-deploy-gen.sh

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

SCRIPT_ROOT=$(dirname "${BASH_SOURCE}")/..

DIFFROOT="${SCRIPT_ROOT}/deploy"
TMP_DIFFROOT="${SCRIPT_ROOT}/_tmp/deploy/manifests"
_tmp="${SCRIPT_ROOT}/_tmp"

cleanup() {
  rm -rf "${_tmp}"
}
trap "cleanup" EXIT SIGINT

cleanup

mkdir -p "${TMP_DIFFROOT}"
cp -a "${DIFFROOT}"/* "${TMP_DIFFROOT}"

"${SCRIPT_ROOT}/hack/gen-deploy.sh"
echo "diffing ${DIFFROOT} against freshly deploy-gen"
ret=0
diff -Naupr "${DIFFROOT}" "${TMP_DIFFROOT}" || ret=$?
cp -a "${TMP_DIFFROOT}"/* "${DIFFROOT}"
if [[ $ret -eq 0 ]]
then
  echo "${DIFFROOT} up to date."
else
  echo "${DIFFROOT} is out of date. Please run hack/gen-deploy.sh"
  exit 1
fi


#!/bin/bash

set -o nounset
set -o errexit

GOPATH="${GOPATH:-$HOME/go}"
SERVICEBUS_QUEUE_NAME="${SERVICEBUS_QUEUE_NAME:-externalq}"

echo; echo "Configuring external metric (queuemessages)..."
cd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/servicebus-queue/
cp deploy/externalmetric.yaml deploy/externalmetric.yaml.copy

sed -i 's|sb-external-ns|'${SERVICEBUS_NAMESPACE}'|g' deploy/externalmetric.yaml
sed -i 's|sb-external-example|'${SERVICEBUS_RESOURCE_GROUP}'|g' deploy/externalmetric.yaml
sed -i 's|externalq|'${SERVICEBUS_QUEUE_NAME}'|g' deploy/externalmetric.yaml

AGGREGATE_TYPE=( "average" "maximum" "minimum" "total" )
# supported aggregates https://github.com/Azure/azure-sdk-for-go/blob/0acfc1d1083d148a606d380143176e218d437728/services/preview/monitor/mgmt/2018-03-01/insights/models.go#L38
for AGGREGATE in "${AGGREGATE_TYPE[@]}"
do
    filePath="deploy/${AGGREGATE}.externalmetric.yaml"
    echo "Creating ${AGGREGATE} external metric with file: $filePath"
    cp deploy/externalmetric.yaml $filePath

    # give a name to the external metric
    sed -i 's|queuemessages|queuemessages-'${AGGREGATE}'|g' $filePath

    # specify the aggregate type
    sed -i 's|Total|'${AGGREGATE}'|g' $filePath

    kubectl apply -f $filePath
done

rm deploy/*externalmetric.yaml; mv deploy/externalmetric.yaml.copy deploy/externalmetric.yaml


#!/bin/bash

set -o nounset
set -o errexit

GOPATH="${GOPATH:-$HOME/go}"
SERVICEBUS_TOPIC_NAME="${SERVICEBUS_TOPIC_NAME:-example-topic}"
SERVICEBUS_SUBSCRIPTION_NAME="${SERVICEBUS_SUBSCRIPTION_NAME:-externalsub}"

echo; echo "Configuring external metric (subscriptionmessages)..."
cd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/resources/externalmetric-examples/
cp servicebussubscription-example.yaml servicebussubscription-example.yaml.copy

sed -i 's|sb-external-ns|'${SERVICEBUS_NAMESPACE}'|g' servicebussubscription-example.yaml
sed -i 's|sb-external-example|'${SERVICEBUS_RESOURCE_GROUP}'|g' servicebussubscription-example.yaml
sed -i 's|example-topic|'${SERVICEBUS_TOPIC_NAME}'|g' servicebussubscription-example.yaml
sed -i 's|example-sub|'${SERVICEBUS_SUBSCRIPTION_NAME}'|g' servicebussubscription-example.yaml
kubectl apply -f servicebussubscription-example.yaml

rm servicebussubscription-example.yaml; mv servicebussubscription-example.yaml.copy servicebussubscription-example.yaml


#!/bin/bash

set -o nounset
set -o errexit

GOPATH="${GOPATH:-$HOME/go}"

echo; echo "Deploying metrics adapter..."
cd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter
# If SP values are set via env vars, use them; otherwise, just use values file
if [[ -v SP_CLIENT_ID ]]; then
    helm install --name adapter \
        --set azureAuthentication.tenantID=$SP_TENANT_ID \
        --set azureAuthentication.clientID=$SP_CLIENT_ID \
        --set azureAuthentication.clientSecret=$SP_CLIENT_SECRET \
        -f ./local-dev-values.yaml \
        ./charts/azure-k8s-metrics-adapter
else
    helm install --name adapter \
        -f ./local-dev-values.yaml \
        ./charts/azure-k8s-metrics-adapter
fi

echo; echo "Waiting for deployment to be available..."
START=`date +%s`

kubectl get deploy/adapter-azure-k8s-metrics-adapter
while [[ ! `kubectl get deploy/adapter-azure-k8s-metrics-adapter -o jsonpath="{@.status.availableReplicas}"` = 1 ]] && \
        [[ $(( $(date +%s) - 55 )) -lt $START ]]; do
    sleep 5
    kubectl get deploy/adapter-azure-k8s-metrics-adapter --no-headers
done

if [[ ! `kubectl get deploy/adapter-azure-k8s-metrics-adapter -o jsonpath="{@.status.availableReplicas}"` = 1 ]]; then
    echo; echo "Deployment failed, output debug information"
    kubectl describe deploy/adapter-azure-k8s-metrics-adapter
    echo
    kubectl logs deploy/adapter-azure-k8s-metrics-adapter
    exit 1
fi


#!/bin/bash

set -o nounset
set -o errexit

GOPATH="${GOPATH:-$HOME/go}"
SERVICEBUS_QUEUE_NAME="${SERVICEBUS_QUEUE_NAME:-externalq}"

cd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/servicebus-queue/

echo; echo "Building producer and consumer..."
make

echo; echo "Creating random number for producer..."
NUM=$(( ($RANDOM % 30 )  + 1 ))

echo; echo "Sending $NUM messages..."
./bin/producer 0 $NUM $SERVICEBUS_QUEUE_NAME> /dev/null

echo; echo "Checking metrics endpoint for 4 minutes..."

MSGCOUNT=$(kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1/namespaces/default/queuemessages-total" | jq .items[0].value)
START=`date +%s`

while [[ ! "$MSGCOUNT" = "\"$NUM\"" ]] && [[ $(( $(date +%s) - 225 )) -lt $START ]]; do
  sleep 15
  MSGCOUNT=$(kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1/namespaces/default/queuemessages-total" | jq .items[0].value)
  echo "Endpoint returned $MSGCOUNT messages"
done

AGGREGATE_TYPE=( "average" "maximum" "minimum" "total" )
for AGGREGATE in "${AGGREGATE_TYPE[@]}"
do
    METRIC_NAME="queuemessages-${AGGREGATE}"
    VALUE=$(kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1/namespaces/default/${METRIC_NAME}" | jq .items[0].value)
    if [[ ! "$VALUE" = "\"$NUM\"" ]]; then
        echo "Timed out, message aggregate type: ${AGGREGATE} value: ${VALUE} not equal to number of messages sent ($NUM)"
        exit 1
    else
        echo "message aggregate type: ${AGGREGATE} value: ${VALUE} is equal to number of messages sent ($NUM), metrics adapter working correctly"
    fi
done


#!/bin/bash

set -o nounset
set -o errexit

GOPATH="${GOPATH:-$HOME/go}"
SERVICEBUS_TOPIC_NAME="${SERVICEBUS_TOPIC_NAME:-example-topic}"
SERVICEBUS_SUBSCRIPTION_NAME="${SERVICEBUS_SUBSCRIPTION_NAME:-externalsub}"

cd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/servicebus-topic/

echo; echo "Building producer and consumer..."
make

echo; echo "Creating random number for producer script..."
NUM=$(( ($RANDOM % 30 )  + 1 ))

echo; echo "Sending $NUM messages..."
./bin/producer 0 $NUM $SERVICEBUS_TOPIC_NAME $SERVICEBUS_SUBSCRIPTION_NAME > /dev/null

echo; echo "Checking metrics endpoint for 4 minutes..."

MSGCOUNT=$(kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1/namespaces/default/example-external-metric-service-bus-subscription" | jq .items[0].value)
START=`date +%s`

while [[ ! "$MSGCOUNT" = "\"$NUM\"" ]] && [[ $(( $(date +%s) - 225 )) -lt $START ]]; do
  sleep 15
  MSGCOUNT=$(kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1/namespaces/default/example-external-metric-service-bus-subscription" | jq .items[0].value)
  echo "Endpoint returned $MSGCOUNT messages"
done

if [[ ! "$MSGCOUNT" = "\"$NUM\"" ]]; then
    echo "Timed out, message count ($MSGCOUNT) not equal to number of messages sent ($NUM)"
    exit 1
else
    echo "Message count equal to number of messages sent, metrics adapter working correctly"
fi


#!/bin/bash

set -o nounset

GOPATH="${GOPATH:-$HOME/go}"
SERVICEBUS_QUEUE_NAME="${SERVICEBUS_QUEUE_NAME:-externalq}"

echo; echo "Running queue consumer to clear queue"
cd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/servicebus-queue/

timeout 30 ./bin/consumer $SERVICEBUS_QUEUE_NAME> /dev/null

# Exit status 124 just means timeout completed, which is what we expect
if [[ $? = 124 ]]; then
    echo "Consumer timed out as expected"
    exit 0
fi


#!/bin/bash

set -o nounset

GOPATH="${GOPATH:-$HOME/go}"

SERVICEBUS_TOPIC_NAME="${SERVICEBUS_TOPIC_NAME:-example-topic}"
SERVICEBUS_SUBSCRIPTION_NAME="${SERVICEBUS_SUBSCRIPTION_NAME:-externalsub}"

echo; echo "Running consumer to clear topic"
cd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/servicebus-topic/

timeout 30 ./bin/consumer $SERVICEBUS_TOPIC_NAME $SERVICEBUS_SUBSCRIPTION_NAME> /dev/null

# Exit status 124 just means timeout completed, which is what we expect
if [[ $? = 124 ]]; then
    echo "Consumer timed out as expected"
    exit 0
fi


#go test -run=none -file bench_test.go -test.bench . -cpuprofile=bench_test.out

go test -c
./go-restful.test -test.run=none -test.cpuprofile=tmp.prof -test.bench=BenchmarkMany
./go-restful.test -test.run=none -test.cpuprofile=curly.prof -test.bench=BenchmarkManyCurly

#go tool pprof go-restful.test tmp.prof
go tool pprof go-restful.test curly.prof


go test -coverprofile=coverage.out
go tool cover -html=coverage.out


go get github.com/golang/protobuf/protoc-gen-go

protoc \
--go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. *.proto


#!/usr/bin/env bash

set -e
echo "" > coverage.txt

for d in $(go list ./... | grep -v vendor); do
    echo -e "TESTS FOR: for \033[0;35m${d}\033[0m"
    go test -race -v -coverprofile=profile.coverage.out -covermode=atomic $d
    if [ -f profile.coverage.out ]; then
        cat profile.coverage.out >> coverage.txt
        rm profile.coverage.out
    fi
    echo ""
done


#!/bin/bash
set -e
set -x

if [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then
    mkdir -p /tmp/build-golang/src/github.com/json-iterator
    ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go
fi
export GOPATH=/tmp/build-golang
go get -u github.com/golang/dep/cmd/dep
cd /tmp/build-golang/src/github.com/json-iterator/go
exec $GOPATH/bin/dep ensure -update


#!/usr/bin/env bash

set -e
echo "" > coverage.txt

for d in $(go list ./... | grep -v vendor); do
    go test -coverprofile=profile.out -coverpkg=github.com/json-iterator/go $d
    if [ -f profile.out ]; then
        cat profile.out >> coverage.txt
        rm profile.out
    fi
done


#!/usr/bin/env bash

set -e
echo "" > coverage.txt

for d in $(go list ./... | grep -v vendor); do
    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/concurrent $d
    if [ -f profile.out ]; then
        cat profile.out >> coverage.txt
        rm profile.out
    fi
done


#!/usr/bin/env bash

set -e
echo "" > coverage.txt

for d in $(go list github.com/modern-go/reflect2-tests/... | grep -v vendor); do
    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/reflect2 $d
    if [ -f profile.out ]; then
        cat profile.out >> coverage.txt
        rm profile.out
    fi
done


#!/usr/bin/env bash
# Copyright 2009 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

# This script runs or (given -n) prints suggested commands to generate files for
# the Architecture/OS specified by the GOARCH and GOOS environment variables.
# See README.md for more information about how the build system works.

GOOSARCH="${GOOS}_${GOARCH}"

# defaults
mksyscall="go run mksyscall.go"
mkerrors="./mkerrors.sh"
zerrors="zerrors_$GOOSARCH.go"
mksysctl=""
zsysctl="zsysctl_$GOOSARCH.go"
mksysnum=
mktypes=
mkasm=
run="sh"
cmd=""

case "$1" in
-syscalls)
	for i in zsyscall*go
	do
		# Run the command line that appears in the first line
		# of the generated file to regenerate it.
		sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i
		rm _$i
	done
	exit 0
	;;
-n)
	run="cat"
	cmd="echo"
	shift
esac

case "$#" in
0)
	;;
*)
	echo 'usage: mkall.sh [-n]' 1>&2
	exit 2
esac

if [[ "$GOOS" = "linux" ]]; then
	# Use the Docker-based build system
	# Files generated through docker (use $cmd so you can Ctl-C the build or run)
	$cmd docker build --tag generate:$GOOS $GOOS
	$cmd docker run --interactive --tty --volume $(dirname "$(readlink -f "$0")"):/build generate:$GOOS
	exit
fi

GOOSARCH_in=syscall_$GOOSARCH.go
case "$GOOSARCH" in
_* | *_ | _)
	echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2
	exit 1
	;;
aix_ppc)
	mkerrors="$mkerrors -maix32"
	mksyscall="go run mksyscall_aix_ppc.go -aix"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
aix_ppc64)
	mkerrors="$mkerrors -maix64"
	mksyscall="go run mksyscall_aix_ppc64.go -aix"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
darwin_386)
	mkerrors="$mkerrors -m32"
	mksyscall="go run mksyscall.go -l32"
	mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	mkasm="go run mkasm_darwin.go"
	;;
darwin_amd64)
	mkerrors="$mkerrors -m64"
	mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	mkasm="go run mkasm_darwin.go"
	;;
darwin_arm)
	mkerrors="$mkerrors"
	mksyscall="go run mksyscall.go -l32"
	mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	mkasm="go run mkasm_darwin.go"
	;;
darwin_arm64)
	mkerrors="$mkerrors -m64"
	mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	mkasm="go run mkasm_darwin.go"
	;;
dragonfly_amd64)
	mkerrors="$mkerrors -m64"
	mksyscall="go run mksyscall.go -dragonfly"
	mksysnum="go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
freebsd_386)
	mkerrors="$mkerrors -m32"
	mksyscall="go run mksyscall.go -l32"
	mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
freebsd_amd64)
	mkerrors="$mkerrors -m64"
	mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
freebsd_arm)
	mkerrors="$mkerrors"
	mksyscall="go run mksyscall.go -l32 -arm"
	mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
freebsd_arm64)
	mkerrors="$mkerrors -m64"
	mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
netbsd_386)
	mkerrors="$mkerrors -m32"
	mksyscall="go run mksyscall.go -l32 -netbsd"
	mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
netbsd_amd64)
	mkerrors="$mkerrors -m64"
	mksyscall="go run mksyscall.go -netbsd"
	mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
netbsd_arm)
	mkerrors="$mkerrors"
	mksyscall="go run mksyscall.go -l32 -netbsd -arm"
	mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
netbsd_arm64)
	mkerrors="$mkerrors -m64"
	mksyscall="go run mksyscall.go -netbsd"
	mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
openbsd_386)
	mkerrors="$mkerrors -m32"
	mksyscall="go run mksyscall.go -l32 -openbsd"
	mksysctl="go run mksysctl_openbsd.go"
	mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
openbsd_amd64)
	mkerrors="$mkerrors -m64"
	mksyscall="go run mksyscall.go -openbsd"
	mksysctl="go run mksysctl_openbsd.go"
	mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
openbsd_arm)
	mkerrors="$mkerrors"
	mksyscall="go run mksyscall.go -l32 -openbsd -arm"
	mksysctl="go run mksysctl_openbsd.go"
	mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
openbsd_arm64)
	mkerrors="$mkerrors -m64"
	mksyscall="go run mksyscall.go -openbsd"
	mksysctl="go run mksysctl_openbsd.go"
	mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
solaris_amd64)
	mksyscall="go run mksyscall_solaris.go"
	mkerrors="$mkerrors -m64"
	mksysnum=
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
*)
	echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2
	exit 1
	;;
esac

(
	if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi
	case "$GOOS" in
	*)
		syscall_goos="syscall_$GOOS.go"
		case "$GOOS" in
		darwin | dragonfly | freebsd | netbsd | openbsd)
			syscall_goos="syscall_bsd.go $syscall_goos"
			;;
		esac
		if [ -n "$mksyscall" ]; then
			if [ "$GOOSARCH" == "aix_ppc64" ]; then
				# aix/ppc64 script generates files instead of writing to stdin.
				echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_"$GOOSARCH"_gccgo.go && gofmt -w zsyscall_"$GOOSARCH"_gc.go " ;
			elif [ "$GOOS" == "darwin" ]; then
			        # pre-1.12, direct syscalls
			        echo "$mksyscall -tags $GOOS,$GOARCH,!go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.1_11.go";
			        # 1.12 and later, syscalls via libSystem
				echo "$mksyscall -tags $GOOS,$GOARCH,go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go";
			else
				echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go";
			fi
		fi
	esac
	if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi
	if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi
	if [ -n "$mktypes" ]; then echo "$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go"; fi
	if [ -n "$mkasm" ]; then echo "$mkasm $GOARCH"; fi
) | $run


#!/usr/bin/env bash
# Copyright 2009 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

# Generate Go code listing errors and other #defined constant
# values (ENAMETOOLONG etc.), by asking the preprocessor
# about the definitions.

unset LANG
export LC_ALL=C
export LC_CTYPE=C

if test -z "$GOARCH" -o -z "$GOOS"; then
	echo 1>&2 "GOARCH or GOOS not defined in environment"
	exit 1
fi

# Check that we are using the new build system if we should
if [[ "$GOOS" = "linux" ]] && [[ "$GOLANG_SYS_BUILD" != "docker" ]]; then
	echo 1>&2 "In the Docker based build system, mkerrors should not be called directly."
	echo 1>&2 "See README.md"
	exit 1
fi

if [[ "$GOOS" = "aix" ]]; then
	CC=${CC:-gcc}
else
	CC=${CC:-cc}
fi

if [[ "$GOOS" = "solaris" ]]; then
	# Assumes GNU versions of utilities in PATH.
	export PATH=/usr/gnu/bin:$PATH
fi

uname=$(uname)

includes_AIX='
#include <net/if.h>
#include <net/netopt.h>
#include <netinet/ip_mroute.h>
#include <sys/protosw.h>
#include <sys/stropts.h>
#include <sys/mman.h>
#include <sys/poll.h>
#include <sys/termio.h>
#include <termios.h>
#include <fcntl.h>

#define AF_LOCAL AF_UNIX
'

includes_Darwin='
#define _DARWIN_C_SOURCE
#define KERNEL
#define _DARWIN_USE_64_BIT_INODE
#include <stdint.h>
#include <sys/attr.h>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/ptrace.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#include <sys/xattr.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <termios.h>
'

includes_DragonFly='
#include <sys/types.h>
#include <sys/event.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <termios.h>
#include <netinet/ip.h>
#include <net/ip_mroute/ip_mroute.h>
'

includes_FreeBSD='
#include <sys/capsicum.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <termios.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
#include <sys/extattr.h>

#if __FreeBSD__ >= 10
#define IFT_CARP	0xf8	// IFT_CARP is deprecated in FreeBSD 10
#undef SIOCAIFADDR
#define SIOCAIFADDR	_IOW(105, 26, struct oifaliasreq)	// ifaliasreq contains if_data
#undef SIOCSIFPHYADDR
#define SIOCSIFPHYADDR	_IOW(105, 70, struct oifaliasreq)	// ifaliasreq contains if_data
#endif
'

includes_Linux='
#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#ifndef __LP64__
#define _FILE_OFFSET_BITS 64
#endif
#define _GNU_SOURCE

// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of
// these structures. We just include them copied from <bits/termios.h>.
#if defined(__powerpc__)
struct sgttyb {
        char    sg_ispeed;
        char    sg_ospeed;
        char    sg_erase;
        char    sg_kill;
        short   sg_flags;
};

struct tchars {
        char    t_intrc;
        char    t_quitc;
        char    t_startc;
        char    t_stopc;
        char    t_eofc;
        char    t_brkc;
};

struct ltchars {
        char    t_suspc;
        char    t_dsuspc;
        char    t_rprntc;
        char    t_flushc;
        char    t_werasc;
        char    t_lnextc;
};
#endif

#include <bits/sockaddr.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/signalfd.h>
#include <sys/socket.h>
#include <sys/xattr.h>
#include <linux/bpf.h>
#include <linux/errqueue.h>
#include <linux/if.h>
#include <linux/if_alg.h>
#include <linux/if_arp.h>
#include <linux/if_ether.h>
#include <linux/if_ppp.h>
#include <linux/if_tun.h>
#include <linux/if_packet.h>
#include <linux/if_addr.h>
#include <linux/falloc.h>
#include <linux/fanotify.h>
#include <linux/filter.h>
#include <linux/fs.h>
#include <linux/kexec.h>
#include <linux/keyctl.h>
#include <linux/magic.h>
#include <linux/memfd.h>
#include <linux/module.h>
#include <linux/netfilter/nfnetlink.h>
#include <linux/netlink.h>
#include <linux/net_namespace.h>
#include <linux/perf_event.h>
#include <linux/random.h>
#include <linux/reboot.h>
#include <linux/rtnetlink.h>
#include <linux/ptrace.h>
#include <linux/sched.h>
#include <linux/seccomp.h>
#include <linux/sockios.h>
#include <linux/wait.h>
#include <linux/icmpv6.h>
#include <linux/serial.h>
#include <linux/can.h>
#include <linux/vm_sockets.h>
#include <linux/taskstats.h>
#include <linux/genetlink.h>
#include <linux/watchdog.h>
#include <linux/hdreg.h>
#include <linux/rtc.h>
#include <linux/if_xdp.h>
#include <linux/cryptouser.h>
#include <mtd/ubi-user.h>
#include <net/route.h>

#if defined(__sparc__)
// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the
// definition in glibc. As only the error constants are needed here, include the
// generic termibits.h (which is included by termbits.h on sparc).
#include <asm-generic/termbits.h>
#else
#include <asm/termbits.h>
#endif

#ifndef MSG_FASTOPEN
#define MSG_FASTOPEN    0x20000000
#endif

#ifndef PTRACE_GETREGS
#define PTRACE_GETREGS	0xc
#endif

#ifndef PTRACE_SETREGS
#define PTRACE_SETREGS	0xd
#endif

#ifndef SOL_NETLINK
#define SOL_NETLINK	270
#endif

#ifdef SOL_BLUETOOTH
// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h
// but it is already in bluetooth_linux.go
#undef SOL_BLUETOOTH
#endif

// Certain constants are missing from the fs/crypto UAPI
#define FS_KEY_DESC_PREFIX              "fscrypt:"
#define FS_KEY_DESC_PREFIX_SIZE         8
#define FS_MAX_KEY_SIZE                 64
'

includes_NetBSD='
#include <sys/types.h>
#include <sys/param.h>
#include <sys/event.h>
#include <sys/extattr.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/termios.h>
#include <sys/ttycom.h>
#include <sys/wait.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
#include <netinet/if_ether.h>

// Needed since <sys/param.h> refers to it...
#define schedppq 1
'

includes_OpenBSD='
#include <sys/types.h>
#include <sys/param.h>
#include <sys/event.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/termios.h>
#include <sys/ttycom.h>
#include <sys/unistd.h>
#include <sys/wait.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/if_var.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
#include <netinet/if_ether.h>
#include <net/if_bridge.h>

// We keep some constants not supported in OpenBSD 5.5 and beyond for
// the promise of compatibility.
#define EMUL_ENABLED		0x1
#define EMUL_NATIVE		0x2
#define IPV6_FAITH		0x1d
#define IPV6_OPTIONS		0x1
#define IPV6_RTHDR_STRICT	0x1
#define IPV6_SOCKOPT_RESERVED1	0x3
#define SIOCGIFGENERIC		0xc020693a
#define SIOCSIFGENERIC		0x80206939
#define WALTSIG			0x4
'

includes_SunOS='
#include <limits.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <sys/mkdev.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <termios.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
'

includes='
#include <sys/types.h>
#include <sys/file.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/tcp.h>
#include <errno.h>
#include <sys/signal.h>
#include <signal.h>
#include <sys/resource.h>
#include <time.h>
'
ccflags="$@"

# Write go tool cgo -godefs input.
(
	echo package unix
	echo
	echo '/*'
	indirect="includes_$(uname)"
	echo "${!indirect} $includes"
	echo '*/'
	echo 'import "C"'
	echo 'import "syscall"'
	echo
	echo 'const ('

	# The gcc command line prints all the #defines
	# it encounters while processing the input
	echo "${!indirect} $includes" | $CC -x c - -E -dM $ccflags |
	awk '
		$1 != "#define" || $2 ~ /\(/ || $3 == "" {next}

		$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers
		$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}
		$2 ~ /^(SCM_SRCRT)$/ {next}
		$2 ~ /^(MAP_FAILED)$/ {next}
		$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.

		$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||
		$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}

		$2 !~ /^ECCAPBITS/ &&
		$2 !~ /^ETH_/ &&
		$2 !~ /^EPROC_/ &&
		$2 !~ /^EQUIV_/ &&
		$2 !~ /^EXPR_/ &&
		$2 ~ /^E[A-Z0-9_]+$/ ||
		$2 ~ /^B[0-9_]+$/ ||
		$2 ~ /^(OLD|NEW)DEV$/ ||
		$2 == "BOTHER" ||
		$2 ~ /^CI?BAUD(EX)?$/ ||
		$2 == "IBSHIFT" ||
		$2 ~ /^V[A-Z0-9]+$/ ||
		$2 ~ /^CS[A-Z0-9]/ ||
		$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||
		$2 ~ /^IGN/ ||
		$2 ~ /^IX(ON|ANY|OFF)$/ ||
		$2 ~ /^IN(LCR|PCK)$/ ||
		$2 !~ "X86_CR3_PCID_NOFLUSH" &&
		$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||
		$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||
		$2 == "BRKINT" ||
		$2 == "HUPCL" ||
		$2 == "PENDIN" ||
		$2 == "TOSTOP" ||
		$2 == "XCASE" ||
		$2 == "ALTWERASE" ||
		$2 == "NOKERNINFO" ||
		$2 ~ /^PAR/ ||
		$2 ~ /^SIG[^_]/ ||
		$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||
		$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||
		$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||
		$2 ~ /^O?XTABS$/ ||
		$2 ~ /^TC[IO](ON|OFF)$/ ||
		$2 ~ /^IN_/ ||
		$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||
		$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|MCAST|EVFILT|NOTE|EV|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||
		$2 ~ /^TP_STATUS_/ ||
		$2 ~ /^FALLOC_/ ||
		$2 == "ICMPV6_FILTER" ||
		$2 == "SOMAXCONN" ||
		$2 == "NAME_MAX" ||
		$2 == "IFNAMSIZ" ||
		$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||
		$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||
		$2 ~ /^HW_MACHINE$/ ||
		$2 ~ /^SYSCTL_VERS/ ||
		$2 !~ "MNT_BITS" &&
		$2 ~ /^(MS|MNT|UMOUNT)_/ ||
		$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||
		$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT)_/ ||
		$2 ~ /^KEXEC_/ ||
		$2 ~ /^LINUX_REBOOT_CMD_/ ||
		$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||
		$2 ~ /^MODULE_INIT_/ ||
		$2 !~ "NLA_TYPE_MASK" &&
		$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||
		$2 ~ /^SIOC/ ||
		$2 ~ /^TIOC/ ||
		$2 ~ /^TCGET/ ||
		$2 ~ /^TCSET/ ||
		$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||
		$2 !~ "RTF_BITS" &&
		$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||
		$2 ~ /^BIOC/ ||
		$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||
		$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||
		$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||
		$2 ~ /^CLONE_[A-Z_]+/ ||
		$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&
		$2 ~ /^(BPF|DLT)_/ ||
		$2 ~ /^(CLOCK|TIMER)_/ ||
		$2 ~ /^CAN_/ ||
		$2 ~ /^CAP_/ ||
		$2 ~ /^ALG_/ ||
		$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE|IOC_(GET|SET)_ENCRYPTION)/ ||
		$2 ~ /^GRND_/ ||
		$2 ~ /^RND/ ||
		$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||
		$2 ~ /^KEYCTL_/ ||
		$2 ~ /^PERF_EVENT_IOC_/ ||
		$2 ~ /^SECCOMP_MODE_/ ||
		$2 ~ /^SPLICE_/ ||
		$2 ~ /^SYNC_FILE_RANGE_/ ||
		$2 !~ /^AUDIT_RECORD_MAGIC/ &&
		$2 !~ /IOC_MAGIC/ &&
		$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||
		$2 ~ /^(VM|VMADDR)_/ ||
		$2 ~ /^IOCTL_VM_SOCKETS_/ ||
		$2 ~ /^(TASKSTATS|TS)_/ ||
		$2 ~ /^CGROUPSTATS_/ ||
		$2 ~ /^GENL_/ ||
		$2 ~ /^STATX_/ ||
		$2 ~ /^RENAME/ ||
		$2 ~ /^UBI_IOC[A-Z]/ ||
		$2 ~ /^UTIME_/ ||
		$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||
		$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||
		$2 ~ /^FSOPT_/ ||
		$2 ~ /^WDIOC_/ ||
		$2 ~ /^NFN/ ||
		$2 ~ /^XDP_/ ||
		$2 ~ /^(HDIO|WIN|SMART)_/ ||
		$2 ~ /^CRYPTO_/ ||
		$2 !~ "WMESGLEN" &&
		$2 ~ /^W[A-Z0-9]+$/ ||
		$2 ~/^PPPIOC/ ||
		$2 ~ /^FAN_|FANOTIFY_/ ||
		$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf("\t%s = C.%s\n", $2, $2)}
		$2 ~ /^__WCOREFLAG$/ {next}
		$2 ~ /^__W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", substr($2,3), $2)}

		{next}
	' | sort

	echo ')'
) >_const.go

# Pull out the error names for later.
errors=$(
	echo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |
	sort
)

# Pull out the signal names for later.
signals=$(
	echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |
	egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |
	sort
)

# Again, writing regexps to a file.
echo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print "^\t" $2 "[ \t]*=" }' |
	sort >_error.grep
echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' |
	egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |
	sort >_signal.grep

echo '// mkerrors.sh' "$@"
echo '// Code generated by the command above; see README.md. DO NOT EDIT.'
echo
echo "// +build ${GOARCH},${GOOS}"
echo
go tool cgo -godefs -- "$@" _const.go >_error.out
cat _error.out | grep -vf _error.grep | grep -vf _signal.grep
echo
echo '// Errors'
echo 'const ('
cat _error.out | grep -f _error.grep | sed 's/=\(.*\)/= syscall.Errno(\1)/'
echo ')'

echo
echo '// Signals'
echo 'const ('
cat _error.out | grep -f _signal.grep | sed 's/=\(.*\)/= syscall.Signal(\1)/'
echo ')'

# Run C program to print error and syscall strings.
(
	echo -E "
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <string.h>
#include <signal.h>

#define nelem(x) (sizeof(x)/sizeof((x)[0]))

enum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below

struct tuple {
	int num;
	const char *name;
};

struct tuple errors[] = {
"
	for i in $errors
	do
		echo -E '	{'$i', "'$i'" },'
	done

	echo -E "
};

struct tuple signals[] = {
"
	for i in $signals
	do
		echo -E '	{'$i', "'$i'" },'
	done

	# Use -E because on some systems bash builtin interprets \n itself.
	echo -E '
};

static int
tuplecmp(const void *a, const void *b)
{
	return ((struct tuple *)a)->num - ((struct tuple *)b)->num;
}

int
main(void)
{
	int i, e;
	char buf[1024], *p;

	printf("\n\n// Error table\n");
	printf("var errorList = [...]struct {\n");
	printf("\tnum  syscall.Errno\n");
	printf("\tname string\n");
	printf("\tdesc string\n");
	printf("} {\n");
	qsort(errors, nelem(errors), sizeof errors[0], tuplecmp);
	for(i=0; i<nelem(errors); i++) {
		e = errors[i].num;
		if(i > 0 && errors[i-1].num == e)
			continue;
		strcpy(buf, strerror(e));
		// lowercase first letter: Bad -> bad, but STREAM -> STREAM.
		if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)
			buf[0] += a - A;
		printf("\t{ %d, \"%s\", \"%s\" },\n", e, errors[i].name, buf);
	}
	printf("}\n\n");

	printf("\n\n// Signal table\n");
	printf("var signalList = [...]struct {\n");
	printf("\tnum  syscall.Signal\n");
	printf("\tname string\n");
	printf("\tdesc string\n");
	printf("} {\n");
	qsort(signals, nelem(signals), sizeof signals[0], tuplecmp);
	for(i=0; i<nelem(signals); i++) {
		e = signals[i].num;
		if(i > 0 && signals[i-1].num == e)
			continue;
		strcpy(buf, strsignal(e));
		// lowercase first letter: Bad -> bad, but STREAM -> STREAM.
		if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)
			buf[0] += a - A;
		// cut trailing : number.
		p = strrchr(buf, ":"[0]);
		if(p)
			*p = '\0';
		printf("\t{ %d, \"%s\", \"%s\" },\n", e, signals[i].name, buf);
	}
	printf("}\n\n");

	return 0;
}

'
) >_errors.c

$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out


#!/bin/bash -e
#
# This script rebuilds the generated code for the protocol buffers.
# To run this you will need protoc and goprotobuf installed;
# see https://github.com/golang/protobuf for instructions.

PKG=google.golang.org/appengine

function die() {
	echo 1>&2 $*
	exit 1
}

# Sanity check that the right tools are accessible.
for tool in go protoc protoc-gen-go; do
	q=$(which $tool) || die "didn't find $tool"
	echo 1>&2 "$tool: $q"
done

echo -n 1>&2 "finding package dir... "
pkgdir=$(go list -f '{{.Dir}}' $PKG)
echo 1>&2 $pkgdir
base=$(echo $pkgdir | sed "s,/$PKG\$,,")
echo 1>&2 "base: $base"
cd $base

# Run protoc once per package.
for dir in $(find $PKG/internal -name '*.proto' | xargs dirname | sort | uniq); do
	echo 1>&2 "* $dir"
	protoc --go_out=. $dir/*.proto
done

for f in $(find $PKG/internal -name '*.pb.go'); do
  # Remove proto.RegisterEnum calls.
  # These cause duplicate registration panics when these packages
  # are used on classic App Engine. proto.RegisterEnum only affects
  # parsing the text format; we don't care about that.
  # https://code.google.com/p/googleappengine/issues/detail?id=11670#c17
  sed -i '/proto.RegisterEnum/d' $f
done


#!/usr/bin/env bash

# This script serves as an example to demonstrate how to generate the gRPC-Go
# interface and the related messages from .proto file.
#
# It assumes the installation of i) Google proto buffer compiler at
# https://github.com/google/protobuf (after v2.6.1) and ii) the Go codegen
# plugin at https://github.com/golang/protobuf (after 2015-02-20). If you have
# not, please install them first.
#
# We recommend running this script at $GOPATH/src.
#
# If this is not what you need, feel free to make your own scripts. Again, this
# script is for demonstration purpose.
#
proto=$1
protoc --go_out=plugins=grpc:. $proto


#!/bin/bash

TMP=$(mktemp -d /tmp/sdk.XXX) \
&& curl -o $TMP.zip "https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_linux_amd64-1.9.68.zip" \
&& unzip -q $TMP.zip -d $TMP \
&& export PATH="$PATH:$TMP/go_appengine"


#!/bin/bash

if [[ `uname -a` = *"Darwin"* ]]; then
  echo "It seems you are running on Mac. This script does not work on Mac. See https://github.com/grpc/grpc-go/issues/2047"
  exit 1
fi

set -ex  # Exit on error; debugging enabled.
set -o pipefail  # Fail a pipe if any sub-command fails.

die() {
  echo "$@" >&2
  exit 1
}

fail_on_output() {
  tee /dev/stderr | (! read)
}

# Check to make sure it's safe to modify the user's git repo.
git status --porcelain | fail_on_output

# Undo any edits made by this script.
cleanup() {
  git reset --hard HEAD
}
trap cleanup EXIT

PATH="${GOPATH}/bin:${GOROOT}/bin:${PATH}"

if [[ "$1" = "-install" ]]; then
  # Check for module support
  if go help mod >& /dev/null; then
    go install \
      golang.org/x/lint/golint \
      golang.org/x/tools/cmd/goimports \
      honnef.co/go/tools/cmd/staticcheck \
      github.com/client9/misspell/cmd/misspell \
      github.com/golang/protobuf/protoc-gen-go
  else
    # Ye olde `go get` incantation.
    # Note: this gets the latest version of all tools (vs. the pinned versions
    # with Go modules).
    go get -u \
      golang.org/x/lint/golint \
      golang.org/x/tools/cmd/goimports \
      honnef.co/go/tools/cmd/staticcheck \
      github.com/client9/misspell/cmd/misspell \
      github.com/golang/protobuf/protoc-gen-go
  fi
  if [[ -z "${VET_SKIP_PROTO}" ]]; then
    if [[ "${TRAVIS}" = "true" ]]; then
      PROTOBUF_VERSION=3.3.0
      PROTOC_FILENAME=protoc-${PROTOBUF_VERSION}-linux-x86_64.zip
      pushd /home/travis
      wget https://github.com/google/protobuf/releases/download/v${PROTOBUF_VERSION}/${PROTOC_FILENAME}
      unzip ${PROTOC_FILENAME}
      bin/protoc --version
      popd
    elif ! which protoc > /dev/null; then
      die "Please install protoc into your path"
    fi
  fi
  exit 0
elif [[ "$#" -ne 0 ]]; then
  die "Unknown argument(s): $*"
fi

# - Ensure all source files contain a copyright message.
git ls-files "*.go" | xargs grep -L "\(Copyright [0-9]\{4,\} gRPC authors\)\|DO NOT EDIT" 2>&1 | fail_on_output

# - Make sure all tests in grpc and grpc/test use leakcheck via Teardown.
(! grep 'func Test[^(]' *_test.go)
(! grep 'func Test[^(]' test/*.go)

# - Do not import math/rand for real library code.  Use internal/grpcrand for
#   thread safety.
git ls-files "*.go" | xargs grep -l '"math/rand"' 2>&1 | (! grep -v '^examples\|^stress\|grpcrand\|wrr_test')

# - Ensure all ptypes proto packages are renamed when importing.
git ls-files "*.go" | (! xargs grep "\(import \|^\s*\)\"github.com/golang/protobuf/ptypes/")

# - Check imports that are illegal in appengine (until Go 1.11).
# TODO: Remove when we drop Go 1.10 support
go list -f {{.Dir}} ./... | xargs go run test/go_vet/vet.go

# - gofmt, goimports, golint (with exceptions for generated code), go vet.
gofmt -s -d -l . 2>&1 | fail_on_output
goimports -l . 2>&1 | (! grep -vE "(_mock|\.pb)\.go:") | fail_on_output
golint ./... 2>&1 | (! grep -vE "(_mock|\.pb)\.go:")
go vet -all .

# - Check that generated proto files are up to date.
if [[ -z "${VET_SKIP_PROTO}" ]]; then
  PATH="/home/travis/bin:${PATH}" make proto && \
    git status --porcelain 2>&1 | fail_on_output || \
    (git status; git --no-pager diff; exit 1)
fi

# - Check that our module is tidy.
if go help mod >& /dev/null; then
  go mod tidy && \
    git status --porcelain 2>&1 | fail_on_output || \
    (git status; git --no-pager diff; exit 1)
fi

# - Collection of static analysis checks
# TODO(menghanl): fix errors in transport_test.
staticcheck -go 1.9 -checks 'inherit,-ST1015' -ignore '
google.golang.org/grpc/balancer.go:SA1019
google.golang.org/grpc/balancer/roundrobin/roundrobin_test.go:SA1019
google.golang.org/grpc/balancer/xds/edsbalancer/balancergroup.go:SA1019
google.golang.org/grpc/balancer/xds/xds.go:SA1019
google.golang.org/grpc/balancer_conn_wrappers.go:SA1019
google.golang.org/grpc/balancer_test.go:SA1019
google.golang.org/grpc/benchmark/benchmain/main.go:SA1019
google.golang.org/grpc/benchmark/worker/benchmark_client.go:SA1019
google.golang.org/grpc/clientconn.go:S1024
google.golang.org/grpc/clientconn_state_transition_test.go:SA1019
google.golang.org/grpc/clientconn_test.go:SA1019
google.golang.org/grpc/internal/transport/handler_server.go:SA1019
google.golang.org/grpc/internal/transport/handler_server_test.go:SA1019
google.golang.org/grpc/resolver/dns/dns_resolver.go:SA1019
google.golang.org/grpc/stats/stats_test.go:SA1019
google.golang.org/grpc/test/channelz_test.go:SA1019
google.golang.org/grpc/test/end2end_test.go:SA1019
google.golang.org/grpc/test/healthcheck_test.go:SA1019
' ./...
misspell -error .


#!/bin/bash
# Copyright 2018 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -eux -o pipefail

TMP=$(mktemp -d)

function finish {
  rm -rf "$TMP"
}
trap finish EXIT

pushd "$TMP"
mkdir -p grpc/binarylog/grpc_binarylog_v1
curl https://raw.githubusercontent.com/grpc/grpc-proto/master/grpc/binlog/v1/binarylog.proto > grpc/binarylog/grpc_binarylog_v1/binarylog.proto

protoc --go_out=plugins=grpc,paths=source_relative:. -I. grpc/binarylog/grpc_binarylog_v1/*.proto
popd
rm -f ./grpc_binarylog_v1/*.pb.go
cp "$TMP"/grpc/binarylog/grpc_binarylog_v1/*.pb.go ../../binarylog/grpc_binarylog_v1/


#!/usr/bin/env bash

# Copyright 2017 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

# gencerts.sh generates the certificates for the webhook tests.
#
# It is not expected to be run often (there is no go generate rule), and mainly
# exists for documentation purposes.

CN_BASE="webhook_tests"

cat > server.conf << EOF
[req]
req_extensions = v3_req
distinguished_name = req_distinguished_name
[req_distinguished_name]
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth, serverAuth
subjectAltName = @alt_names
[alt_names]
IP.1 = 127.0.0.1
EOF

cat > client.conf << EOF
[req]
req_extensions = v3_req
distinguished_name = req_distinguished_name
[req_distinguished_name]
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth, serverAuth
subjectAltName = @alt_names
[alt_names]
IP.1 = 127.0.0.1
EOF

# Create a certificate authority
openssl genrsa -out caKey.pem 2048
openssl req -x509 -new -nodes -key caKey.pem -days 100000 -out caCert.pem -subj "/CN=${CN_BASE}_ca"

# Create a second certificate authority
openssl genrsa -out badCAKey.pem 2048
openssl req -x509 -new -nodes -key badCAKey.pem -days 100000 -out badCACert.pem -subj "/CN=${CN_BASE}_ca"

# Create a server certiticate
openssl genrsa -out serverKey.pem 2048
openssl req -new -key serverKey.pem -out server.csr -subj "/CN=${CN_BASE}_server" -config server.conf
openssl x509 -req -in server.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out serverCert.pem -days 100000 -extensions v3_req -extfile server.conf

# Create a client certiticate
openssl genrsa -out clientKey.pem 2048
openssl req -new -key clientKey.pem -out client.csr -subj "/CN=${CN_BASE}_client" -config client.conf
openssl x509 -req -in client.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out clientCert.pem -days 100000 -extensions v3_req -extfile client.conf

outfile=certs_test.go

cat > $outfile << EOF
/*
Copyright 2017 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// This file was generated using openssl by the gencerts.sh script
// and holds raw certificates for the webhook tests.

package webhook
EOF

for file in caKey caCert badCAKey badCACert serverKey serverCert clientKey clientCert; do
	data=$(cat ${file}.pem)
	echo "" >> $outfile
	echo "var $file = []byte(\`$data\`)" >> $outfile
done

# Clean up after we're done.
rm ./*.pem
rm ./*.csr
rm ./*.srl
rm ./*.conf


#!/usr/bin/env bash

# Copyright 2016 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

# gencerts.sh generates the certificates for the webhook authz plugin tests.
#
# It is not expected to be run often (there is no go generate rule), and mainly
# exists for documentation purposes.

cat > server.conf << EOF
[req]
req_extensions = v3_req
distinguished_name = req_distinguished_name
[req_distinguished_name]
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
IP.1 = 127.0.0.1
EOF

cat > client.conf << EOF
[req]
req_extensions = v3_req
distinguished_name = req_distinguished_name
[req_distinguished_name]
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth
EOF

# Create a certificate authority
openssl genrsa -out caKey.pem 2048
openssl req -x509 -new -nodes -key caKey.pem -days 100000 -out caCert.pem -subj "/CN=webhook_authz_ca"

# Create a second certificate authority
openssl genrsa -out badCAKey.pem 2048
openssl req -x509 -new -nodes -key badCAKey.pem -days 100000 -out badCACert.pem -subj "/CN=webhook_authz_ca"

# Create a server certiticate
openssl genrsa -out serverKey.pem 2048
openssl req -new -key serverKey.pem -out server.csr -subj "/CN=webhook_authz_server" -config server.conf
openssl x509 -req -in server.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out serverCert.pem -days 100000 -extensions v3_req -extfile server.conf

# Create a client certiticate
openssl genrsa -out clientKey.pem 2048
openssl req -new -key clientKey.pem -out client.csr -subj "/CN=webhook_authz_client" -config client.conf
openssl x509 -req -in client.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out clientCert.pem -days 100000 -extensions v3_req -extfile client.conf

outfile=certs_test.go

cat > $outfile << EOF
/*
Copyright 2016 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// This file was generated using openssl by the gencerts.sh script
// and holds raw certificates for the webhook tests.

package webhook
EOF

for file in caKey caCert badCAKey badCACert serverKey serverCert clientKey clientCert; do
	data=$(cat ${file}.pem)
	echo "" >> $outfile
	echo "var $file = []byte(\`$data\`)" >> $outfile
done

# Clean up after we're done.
rm ./*.pem
rm ./*.csr
rm ./*.srl
rm ./*.conf


#!/usr/bin/env bash

# Copyright 2017 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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

# generate-groups generates everything for a project with external types only, e.g. a project based
# on CustomResourceDefinitions.

if [ "$#" -lt 4 ] || [ "${1}" == "--help" ]; then
  cat <<EOF
Usage: $(basename "$0") <generators> <output-package> <apis-package> <groups-versions> ...

  <generators>        the generators comma separated to run (deepcopy,defaulter,client,lister,informer) or "all".
  <output-package>    the output package name (e.g. github.com/example/project/pkg/generated).
  <apis-package>      the external types dir (e.g. github.com/example/api or github.com/example/project/pkg/apis).
  <groups-versions>   the groups and their versions in the format "groupA:v1,v2 groupB:v1 groupC:v2", relative
                      to <api-package>.
  ...                 arbitrary flags passed to all generator binaries.

Examples:
  $(basename "$0") all             github.com/example/project/pkg/client github.com/example/project/pkg/apis "foo:v1 bar:v1alpha1,v1beta1"
  $(basename "$0") deepcopy,client github.com/example/project/pkg/client github.com/example/project/pkg/apis "foo:v1 bar:v1alpha1,v1beta1"
EOF
  exit 0
fi

GENS="$1"
OUTPUT_PKG="$2"
APIS_PKG="$3"
GROUPS_WITH_VERSIONS="$4"
shift 4

(
  # To support running this script from anywhere, we have to first cd into this directory
  # so we can install the tools.
  cd "$(dirname "${0}")"
  go install ./cmd/{defaulter-gen,client-gen,lister-gen,informer-gen,deepcopy-gen}
)

function codegen::join() { local IFS="$1"; shift; echo "$*"; }

# enumerate group versions
FQ_APIS=() # e.g. k8s.io/api/apps/v1
for GVs in ${GROUPS_WITH_VERSIONS}; do
  IFS=: read -r G Vs <<<"${GVs}"

  # enumerate versions
  for V in ${Vs//,/ }; do
    FQ_APIS+=("${APIS_PKG}/${G}/${V}")
  done
done

if [ "${GENS}" = "all" ] || grep -qw "deepcopy" <<<"${GENS}"; then
  echo "Generating deepcopy funcs"
  "${GOPATH}/bin/deepcopy-gen" --input-dirs "$(codegen::join , "${FQ_APIS[@]}")" -O zz_generated.deepcopy --bounding-dirs "${APIS_PKG}" "$@"
fi

if [ "${GENS}" = "all" ] || grep -qw "client" <<<"${GENS}"; then
  echo "Generating clientset for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}"
  "${GOPATH}/bin/client-gen" --clientset-name "${CLIENTSET_NAME_VERSIONED:-versioned}" --input-base "" --input "$(codegen::join , "${FQ_APIS[@]}")" --output-package "${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}" "$@"
fi

if [ "${GENS}" = "all" ] || grep -qw "lister" <<<"${GENS}"; then
  echo "Generating listers for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/listers"
  "${GOPATH}/bin/lister-gen" --input-dirs "$(codegen::join , "${FQ_APIS[@]}")" --output-package "${OUTPUT_PKG}/listers" "$@"
fi

if [ "${GENS}" = "all" ] || grep -qw "informer" <<<"${GENS}"; then
  echo "Generating informers for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/informers"
  "${GOPATH}/bin/informer-gen" \
           --input-dirs "$(codegen::join , "${FQ_APIS[@]}")" \
           --versioned-clientset-package "${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}/${CLIENTSET_NAME_VERSIONED:-versioned}" \
           --listers-package "${OUTPUT_PKG}/listers" \
           --output-package "${OUTPUT_PKG}/informers" \
           "$@"
fi


#!/usr/bin/env bash

# Copyright 2017 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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

# generate-internal-groups generates everything for a project with internal types, e.g. an
# user-provided API server based on k8s.io/apiserver.

if [ "$#" -lt 5 ] || [ "${1}" == "--help" ]; then
  cat <<EOF
Usage: $(basename "$0") <generators> <output-package> <internal-apis-package> <extensiona-apis-package> <groups-versions> ...

  <generators>        the generators comma separated to run (deepcopy,defaulter,conversion,client,lister,informer) or "all".
  <output-package>    the output package name (e.g. github.com/example/project/pkg/generated).
  <int-apis-package>  the internal types dir (e.g. github.com/example/project/pkg/apis).
  <ext-apis-package>  the external types dir (e.g. github.com/example/project/pkg/apis or githubcom/example/apis).
  <groups-versions>   the groups and their versions in the format "groupA:v1,v2 groupB:v1 groupC:v2", relative
                      to <api-package>.
  ...                 arbitrary flags passed to all generator binaries.

Examples:
  $(basename "$0") all                           github.com/example/project/pkg/client github.com/example/project/pkg/apis github.com/example/project/pkg/apis "foo:v1 bar:v1alpha1,v1beta1"
  $(basename "$0") deepcopy,defaulter,conversion github.com/example/project/pkg/client github.com/example/project/pkg/apis github.com/example/project/apis     "foo:v1 bar:v1alpha1,v1beta1"
EOF
  exit 0
fi

GENS="$1"
OUTPUT_PKG="$2"
INT_APIS_PKG="$3"
EXT_APIS_PKG="$4"
GROUPS_WITH_VERSIONS="$5"
shift 5

go install ./"$(dirname "${0}")"/cmd/{defaulter-gen,conversion-gen,client-gen,lister-gen,informer-gen,deepcopy-gen}
function codegen::join() { local IFS="$1"; shift; echo "$*"; }

# enumerate group versions
ALL_FQ_APIS=() # e.g. k8s.io/kubernetes/pkg/apis/apps k8s.io/api/apps/v1
INT_FQ_APIS=() # e.g. k8s.io/kubernetes/pkg/apis/apps
EXT_FQ_APIS=() # e.g. k8s.io/api/apps/v1
for GVs in ${GROUPS_WITH_VERSIONS}; do
  IFS=: read -r G Vs <<<"${GVs}"

  if [ -n "${INT_APIS_PKG}" ]; then
    ALL_FQ_APIS+=("${INT_APIS_PKG}/${G}")
    INT_FQ_APIS+=("${INT_APIS_PKG}/${G}")
  fi

  # enumerate versions
  for V in ${Vs//,/ }; do
    ALL_FQ_APIS+=("${EXT_APIS_PKG}/${G}/${V}")
    EXT_FQ_APIS+=("${EXT_APIS_PKG}/${G}/${V}")
  done
done

if [ "${GENS}" = "all" ] || grep -qw "deepcopy" <<<"${GENS}"; then
  echo "Generating deepcopy funcs"
  "${GOPATH}/bin/deepcopy-gen" --input-dirs "$(codegen::join , "${ALL_FQ_APIS[@]}")" -O zz_generated.deepcopy --bounding-dirs "${INT_APIS_PKG},${EXT_APIS_PKG}" "$@"
fi

if [ "${GENS}" = "all" ] || grep -qw "defaulter" <<<"${GENS}"; then
  echo "Generating defaulters"
  "${GOPATH}/bin/defaulter-gen"  --input-dirs "$(codegen::join , "${EXT_FQ_APIS[@]}")" -O zz_generated.defaults "$@"
fi

if [ "${GENS}" = "all" ] || grep -qw "conversion" <<<"${GENS}"; then
  echo "Generating conversions"
  "${GOPATH}/bin/conversion-gen" --input-dirs "$(codegen::join , "${ALL_FQ_APIS[@]}")" -O zz_generated.conversion "$@"
fi

if [ "${GENS}" = "all" ] || grep -qw "client" <<<"${GENS}"; then
  echo "Generating clientset for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}"
  if [ -n "${INT_APIS_PKG}" ]; then
    IFS=" " read -r -a APIS <<< "$(printf '%s/ ' "${INT_FQ_APIS[@]}")"
    "${GOPATH}/bin/client-gen" --clientset-name "${CLIENTSET_NAME_INTERNAL:-internalversion}" --input-base "" --input "$(codegen::join , "${APIS[@]}")" --output-package "${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}" "$@"
  fi
  "${GOPATH}/bin/client-gen" --clientset-name "${CLIENTSET_NAME_VERSIONED:-versioned}" --input-base "" --input "$(codegen::join , "${EXT_FQ_APIS[@]}")" --output-package "${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}" "$@"
fi

if [ "${GENS}" = "all" ] || grep -qw "lister" <<<"${GENS}"; then
  echo "Generating listers for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/listers"
  "${GOPATH}/bin/lister-gen" --input-dirs "$(codegen::join , "${ALL_FQ_APIS[@]}")" --output-package "${OUTPUT_PKG}/listers" "$@"
fi

if [ "${GENS}" = "all" ] || grep -qw "informer" <<<"${GENS}"; then
  echo "Generating informers for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/informers"
  "${GOPATH}/bin/informer-gen" \
           --input-dirs "$(codegen::join , "${ALL_FQ_APIS[@]}")" \
           --versioned-clientset-package "${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}/${CLIENTSET_NAME_VERSIONED:-versioned}" \
           --internal-clientset-package "${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}/${CLIENTSET_NAME_INTERNAL:-internalversion}" \
           --listers-package "${OUTPUT_PKG}/listers" \
           --output-package "${OUTPUT_PKG}/informers" \
           "$@"
fi


#/bin/bash

# ========================================================================
# Copyright 2014 Microsoft Corporation

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========================================================================

npm install express socket.io flavored-path cli


#!/bin/bash

# ========================================================================
# Copyright 2014 Microsoft Corporation

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========================================================================

# This script is provided as a shorcut to starting the demo server.
# It essentially just loads up your kubernetes config and pulls some configuration variables from there.
# In the future this script may need adjusting as paths to the config scripts change.

if [ -z $KUBERNETES_PROVIDER ]; then
	export KUBERNETES_PROVIDER=azure;
fi

export KUBERNETES_PATH=../kubernetes

source $KUBERNETES_PATH/release/${KUBERNETES_PROVIDER}/config.sh
source $KUBERNETES_PATH/cluster/${KUBERNETES_PROVIDER}/config-default.sh

./index.js \
	-s ${AZ_CS}.cloudapp.net \
	-m ${NUM_MINIONS} \
	-k ${KUBERNETES_PATH} \
	$@


#!/bin/sh -eu

tmpfile=$(mktemp)
trap "rm -f $tmpfile" EXIT

run_test() {
  tfile="$1.avro"
  efile="$2.json"
  cfile="$2.csv"
  shift; shift
  set +e
  options="$@"

  echo "Running: ./avro2json $options ../tests/${tfile}"
  ./avro2json $options "../tests/${tfile}" > $tmpfile
  if ! diff -a $tmpfile "../tests/${efile}"; then
    exit 1
  fi

  if [ -f ../tests/$cfile ]; then
    ./avro2json $options --csv "../tests/${tfile}" > $tmpfile
    if ! diff -a $tmpfile "../tests/${cfile}"; then
      exit 1
    fi
  fi
}

run_test file1 file1
run_test file1 file1-p --prune
run_test reals reals
run_test decimals decimals
run_test decimals decimals-l --logical-types
run_test decimals-bytes decimals-bytes
run_test decimals-bytes decimals-bytes-l --logical-types
run_test columns columns-1 --columns 1
run_test columns columns-2 --columns 2
run_test columns columns-3 --columns 1,4
run_test columns columns-4 --columns 4,1
run_test dates dates-l --logical-types
run_test datetimes datetimes-l --logical-types


#!/bin/bash

cd /home/

git clone https://github.com/Azure/azure-kusto-demos.git

cp /home/config/EventHubsConfig.json /home/azure-kusto-demos/eventhub-python/github-events-demo/config/

cd /home/azure-kusto-demos/eventhub-python/github-events-demo/

python crawl_send_eventhub.py &> "../../../config/$(date +"%Y_%m_%d_%I_%M_%p").log"


job_name='yem0825-cdtest'
# list run and cancel run
run_list=$(databricks runs list | grep $job_name)
while IFS='  ' read id name status result url
do
echo "run_id - $id $name $status"
if [ "$status" != 'TERMINATED' ]
then
   databricks runs cancel --run-id $id
   echo "cancel run_id - $id"
fi
done <<< "$run_list"

# create a job with the job-meta.json
job_meta_file="./job_meta_simple_test.json"
job_id=$(databricks jobs create --json-file "$job_meta_file" | python -c "import sys, json; print(json.load(sys.stdin)['job_id'])")
echo "create job $job_name $job_id"

# load notbook arguments
notebook_param_file="./notebook_params_simple_test.json"
notebook_params=$(<$notebook_param_file)

# create a run with the job
run_id=$(databricks jobs run-now --job-id $job_id --notebook-params  "$notebook_params"  | python -c "import sys, json; print(json.load(sys.stdin)['run_id'])")
echo "run job $job_id with run_id $run_id"


#!/bin/sh
# Copyright The OpenTelemetry Authors
# SPDX-License-Identifier: Apache-2.0

# This script is used to generate protobuf files for all services.
# Useful to ensure code can compile without Docker, and provide hints for IDEs.
# Several dev tools including: cargo, protoc, python grpcio-tools, and rebar3 may be required to run this script.

base_dir=$(pwd)

gen_proto_dotnet() {
  echo "Generating .NET protobuf files for $1"
  cd "$base_dir"/src/"$1" || return
  mkdir -p ./src/protos/
  cp -r "$base_dir"/pb/ ./src/protos/
  cd "$base_dir" || return
}

gen_proto_elixir() {
  echo "Generating Elixir protobuf files for $1"
  cd "$base_dir"/src/"$1" || return
  mkdir -p proto
  cp "$base_dir"/pb/demo.proto ./proto/demo.proto
  rebar3 grpc_regen
  cd "$base_dir" || return
}

gen_proto_go() {
  echo "Generating Go protobuf files for $1"
  cd "$base_dir"/src/"$1" || return
  protoc -I ../../pb ./../../pb/demo.proto --go_out=./ --go-grpc_out=./
  cd "$base_dir" || return
}

gen_proto_js() {
  echo "Generating Javascript protobuf files for $1"
  cd "$base_dir"/src/"$1" || return
  cp "$base_dir"/pb/demo.proto .
  cd "$base_dir" || return
}

gen_proto_python() {
  echo "Generating Python protobuf files for $1"
  cd "$base_dir"/src/"$1" || return
  python3 -m grpc_tools.protoc -I=../../pb --python_out=./ --grpc_python_out=./ ./../../pb/demo.proto
  cd "$base_dir" || return
}

gen_proto_rust() {
  echo "Generating Rust protobuf files for $1"
  cd "$base_dir"/src/"$1" || return
  mkdir -p proto
  cp "$base_dir"/pb/demo.proto proto/demo.proto
  cargo build
  cd "$base_dir" || return
}

gen_proto_ts() {
  echo "Generating Typescript protobuf files for $1"
  cd "$base_dir"/src/"$1" || return
  cp -r "$base_dir"/pb .
  mkdir -p ./protos
  protoc -I ./pb  --plugin=./node_modules/.bin/protoc-gen-ts_proto --ts_proto_opt=esModuleInterop=true --ts_proto_out=./protos --ts_proto_opt=outputServices=grpc-js demo.proto
  cd "$base_dir" || return
}

gen_proto_go accountingservice
# gen_proto_java adservice
gen_proto_dotnet cartservice
gen_proto_go checkoutservice
# gen_proto_cpp currencyservice
# gen_proto_ruby emailservice
gen_proto_elixir featureflagservice
gen_proto_ts frontend
gen_proto_js paymentservice
gen_proto_go productcatalogservice
# gen_proto_php quoteservice
gen_proto_python recommendationservice
gen_proto_rust shippingservice


if [ -z "$1" ]; then
    echo "Usage: pull_hdfs [path_to_hdfs_git_root]"
    exit 1;
fi
if [ ! -d "$1" ]; then
    echo "$1 is not a directory"
fi
if [ ! -d "$1/hadoop-hdfs-project" ]; then
    echo "$1 is not the root of a hadoop git checkout"
fi

HADOOP_ROOT=$1
echo HADOOP_ROOT=$HADOOP_ROOT
OUT=$(readlink -m `dirname $0`)
echo OUT=$OUT
TS=$OUT/imported_timestamp

    cd $HADOOP_ROOT &&
    mvn -pl :hadoop-hdfs-native-client -Pnative compile -Dnative_make_args="copy_hadoop_files"
    (date > $TS; git rev-parse --abbrev-ref HEAD >> $TS; git log -n 1 >> $TS;  \
        echo "diffs: --------------" >> $TS; git diff HEAD >> $TS; \
        echo "       --------------" >> $TS)
    cd $OUT &&
    #Delete everything except for pull_hdfs.sh and imported_timestamp
    find . ! -name 'pull_hdfs.sh' ! -name 'imported_timestamp' ! -name '.' ! -name '..' -exec rm -rf {} + &&
    cp -R $HADOOP_ROOT/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfspp . &&
    cp -R $HADOOP_ROOT/hadoop-hdfs-project/hadoop-hdfs-native-client/target/main/native/libhdfspp/extern libhdfspp/ &&
    cd libhdfspp &&
	tar -czf ../libhdfspp.tar.gz * &&
	cd .. &&
	rm -rf libhdfspp &&
	date >> $TS


find test -name "*.json" -exec bash -c 'jq . {} > {}.tmp && mv {}.tmp {}' \;


#!/bin/bash

sudo apt-get update

# install apache
sudo apt-get -y install apache2

# restart Apache
sudo service apache2 restart


#!/bin/bash

sudo apt-get install -f

sudo apt-get update

# install apache
sudo apt-get -y install apache2

# restart Apache
sudo apachectl restart


#!/bin/bash

/usr/bin/yes | sudo apt-get update
/usr/bin/yes | sudo apt install python-pip
/usr/bin/yes | sudo pip install --upgrade pip
sudo pip install azure-cli
az login --msi
az storage account create -n $1 -g $2 -l $3 --sku Premium_LRS


#!/bin/bash

sudo apt-get update

# install apache
sudo apt-get -y install apache2

# restart Apache
sudo apachectl restart


#!/bin/bash

sudo apt-get update
sudo apt-get install -y openjdk-8-jdk maven git


#############################################
# Define colored output func
function title {
    LGREEN='\033[1;32m'
    CLEAR='\033[0m'

    echo -e ${LGREEN}$1${CLEAR}
}

#############################################

set -e

title 'Generating tasks list'
java -jar ./ci/java-test-collector-1.0-SNAPSHOT.jar ./

title 'Building docker image'
image=azuresdk-java:java-$TRAVIS_BUILD_NUMBER
docker build -t $image -f ci/Dockerfile .

title 'Pushing docker image'
image=azuresdk-java:java-$TRAVIS_BUILD_NUMBER
docker login azureclidev.azurecr.io -u $AZURESDKDEV_ACR_SP_USERNAME -p $AZURESDK_ACR_SP_PASSWORD
docker tag azuresdk-java:java-$TRAVIS_BUILD_NUMBER azureclidev.azurecr.io/azuresdk-java:java-$TRAVIS_BUILD_NUMBER
docker tag azuresdk-java:java-$TRAVIS_BUILD_NUMBER azureclidev.azurecr.io/azuresdk-java:java-latest
docker push azureclidev.azurecr.io/azuresdk-java:java-$TRAVIS_BUILD_NUMBER
docker push azureclidev.azurecr.io/azuresdk-java:java-latest


#!/usr/bin/env bash

set -e
# ###########################################
# Define colored output func
function title {
    LGREEN='\033[1;32m'
    CLEAR='\033[0m'

    echo -e ${LGREEN}$1${CLEAR}
}

#############################################
LOG_PARAMS='-Dorg.slf4j.simpleLogger.defaultLogLevel=error -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn --batch-mode' ;
if [ ${TRAVIS_JDK_VERSION} = "oraclejdk8" ]; then
    title 'Running checkstyle:check'
    mvn checkstyle:check ;
fi
title 'Running mvn -pl !azure-samples package javadoc:aggregate -DskipTests=true $LOG_PARAMS'
mvn -q -pl !azure-samples package javadoc:aggregate -DskipTests=true $LOG_PARAMS ;
echo '==> Starting mvn test ===' ;
mvn test -q -Dsurefire.rerunFailingTestsCount=3 $LOG_PARAMS -Dparallel=classes -DthreadCount=2 -DforkCount=1C ;


#!/usr/bin/env bash

echo "Current limits :"
ulimit -a

ulimit -n

ulimit

echo "Setting new limits"
ulimit -S unlimited
ulimit -H unlimited

ulimit -n 65535

echo "updated limits"
ulimit

ulimit -n

ulimit -a


#!/bin/sh

set -e
base=`dirname {BASH_SOURCE[0]}`
rootdir="$( cd "$base" && pwd )"
netstd14="netstandard1.4"
netstd16="netstandard1.6"
#netcore11='netcoreapp1.1'
netcore20='netcoreapp2.0'
ubuntu1404="ubuntu.14.04-x64"
nugetOrgSource="https://api.nuget.org/v3/index.json"

dotnet --info

getBuildTools() {
    copyFromRootDir="."
    printf "Updating Build tools .....\n"

    if [ ! -d ./tools/SdkBuildTools ]; then
        mkdir ./tools/SdkBuildTools
    fi
    if [ ! -d ./tools/SdkBuildTools/targets ]; then
        mkdir ./tools/SdkBuildTools/targets
    fi

    if [ ! -d ./tools/SdkBuildTools/targets/core ]; then
        mkdir ./tools/SdkBuildTools/targets/core
    fi

    if [ ! -d ./tools/SdkBuildTools/tasks ]; then
        mkdir ./tools/SdkBuildTools/tasks
    fi

    if [ ! -d ./tools/SdkBuildTools/tasks/net46 ]; then
        mkdir ./tools/SdkBuildTools/tasks/net46
    fi

    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/additional.targets ./tools/SdkBuildTools/targets/additional.targets
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/common.Build.props ./tools/SdkBuildTools/targets/common.Build.props
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/common.NugetPackage.props ./tools/SdkBuildTools/targets/common.NugetPackage.props
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/common.targets ./tools/SdkBuildTools/targets/common.targets
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/signing.targets ./tools/SdkBuildTools/targets/signing.targets
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/ideCmd.targets ./tools/SdkBuildTools/targets/ideCmd.targets
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/utility.targets ./tools/SdkBuildTools/targets/utility.targets
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/core/_AzSdk.props ./tools/SdkBuildTools/targets/core/_AzSdk.props
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/core/_build.proj ./tools/SdkBuildTools/targets/core/_build.proj
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/core/_Directory.Build.props ./tools/SdkBuildTools/targets/core/_Directory.Build.props
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/core/_Directory.Build.targets ./tools/SdkBuildTools/targets/core/_Directory.Build.targets
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/core/_test.props ./tools/SdkBuildTools/targets/core/_test.props
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/common.tasks ./tools/SdkBuildTools/tasks/common.tasks
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/Microsoft.Azure.Sdk.Build.Tasks.dll ./tools/SdkBuildTools/tasks/net46/Microsoft.Azure.Sdk.Build.Tasks.dll
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/Microsoft.Build.dll ./tools/SdkBuildTools/tasks/net46/Microsoft.Build.dll
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/Microsoft.Build.Framework.dll ./tools/SdkBuildTools/tasks/net46/Microsoft.Build.Framework.dll
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/Microsoft.Build.Tasks.Core.dll ./tools/SdkBuildTools/tasks/net46/Microsoft.Build.Tasks.Core.dll
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/Microsoft.Build.Utilities.Core.dll ./tools/SdkBuildTools/tasks/net46Microsoft.Build.Utilities.Core.dll
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/System.Collections.Immutable.dll ./tools/SdkBuildTools/tasks/net46/System.Collections.Immutable.dll
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/System.Reflection.Metadata.dll ./tools/SdkBuildTools/tasks/net46/System.Reflection.Metadata.dll
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/System.Runtime.InteropServices.RuntimeInformation.dll ./tools/SdkBuildTools/tasks/net46/System.Runtime.InteropServices.RuntimeInformation.dll
    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/System.Threading.Thread.dll ./tools/SdkBuildTools/tasks/net46/System.Threading.Thread.dll
}

getBuildTools
echo Restoring... $ubuntu1404
dotnet restore Fluent.Tests.sln -r $ubuntu1404
echo Building... $netcore20

dotnet build src/ResourceManagement/ResourceManager/Microsoft.Azure.Management.ResourceManager.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/Storage/Microsoft.Azure.Management.Storage.Fluent.csproj -f $netstd14

dotnet build src/ResourceManagement/Graph.RBAC/Microsoft.Azure.Management.Graph.RBAC.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/Network/Microsoft.Azure.Management.Network.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/AppService/Microsoft.Azure.Management.AppService.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/Cdn/Microsoft.Azure.Management.Cdn.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/Compute/Microsoft.Azure.Management.Compute.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/ContainerRegistry/Microsoft.Azure.Management.ContainerRegistry.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/Dns/Microsoft.Azure.Management.Dns.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/CosmosDB/Microsoft.Azure.Management.CosmosDB.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/KeyVault/Microsoft.Azure.Management.KeyVault.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/PrivateDns/Microsoft.Azure.Management.PrivateDns.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/RedisCache/Microsoft.Azure.Management.Redis.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/Search/Microsoft.Azure.Management.Search.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/ServiceBus/Microsoft.Azure.Management.ServiceBus.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/Sql/Microsoft.Azure.Management.Sql.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/TrafficManager/Microsoft.Azure.Management.TrafficManager.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/ContainerService/Microsoft.Azure.Management.ContainerService.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/ContainerInstance/Microsoft.Azure.Management.ContainerInstance.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/Locks/Microsoft.Azure.Management.Locks.Fluent.csproj -f $netstd14
dotnet build src/ResourceManagement/Azure.Fluent/Microsoft.Azure.Management.Fluent.csproj -f $netstd14
dotnet build Samples/Samples.csproj  -f $netstd16
dotnet build Tests/Fluent.Tests/Fluent.Tests.csproj -f $netcore20
dotnet build Tests/Samples.Tests/Samples.Tests.csproj -f $netcore20

echo Running Fluent Tests
cd $rootdir/Tests/Fluent.Tests
dotnet test Fluent.Tests.csproj -f $netcore20

echo Running Samples Tests
cd $rootdir/Tests/Samples.Tests
dotnet test Samples.Tests.csproj -f $netcore20


#############################################
# Define colored output func
function title {
    LGREEN='\033[1;32m'
    CLEAR='\033[0m'

    echo -e ${LGREEN}$1${CLEAR}
}

#############################################

title 'Generating tasks list'
./ci/get_tasks_list.sh

title 'Building docker image'
image=azuresdk-net:net-$TRAVIS_BUILD_NUMBER
docker build -t $image -f ci/Dockerfile .

title 'Pushing docker image'
docker login azureclidev.azurecr.io -u $AZURESDKDEV_ACR_SP_USERNAME -p $AZURESDK_ACR_SP_PASSWORD
docker tag azuresdk-net:net-$TRAVIS_BUILD_NUMBER azureclidev.azurecr.io/azuresdk-net:net-$TRAVIS_BUILD_NUMBER
docker tag azuresdk-net:net-$TRAVIS_BUILD_NUMBER azureclidev.azurecr.io/azuresdk-net:net-latest
docker push azureclidev.azurecr.io/azuresdk-net:net-$TRAVIS_BUILD_NUMBER
docker push azureclidev.azurecr.io/azuresdk-net:net-latest


#!/bin/bash
set -e
base=`dirname {BASH_SOURCE[0]}`
rootdir="$( cd "$base" && pwd )"

echo $rootdir

sampleTestPath=/azure-libraries-for-net/Tests/Samples.Tests/
fluentTestPath=/azure-libraries-for-net/Tests/Fluent.Tests/

cd $rootdir/Tests/Samples.Tests/

dotnet test -t --no-build > $rootdir/ci/tasklist

echo "[" > $rootdir/ci/app/test_index
while read line; do
    testcase="$( echo "$line" | cut -d '=' -f 1 )"
    if [[ $testcase == Samples* ]] ; then
        testname="$(echo "$testcase" | rev | cut -d'.' -f1 | rev)"
        recordpath="$(echo "$testcase" | rev | cut -d'.' -f2-7 | rev)"
        sed -e "s;%testcase%;${testcase};g" -e "s|%testpath%|${sampleTestPath}|g" -e "s|%recordpath%|${recordpath}|g" -e "s|%testname%|${testname}|g" $rootdir/ci/task_template > $rootdir/ci/file.out
        task=$(cat $rootdir/ci/file.out)
        echo $task, >> $rootdir/ci/app/test_index
    fi
done < $rootdir/ci/tasklist

cd $rootdir/Tests/Fluent.Tests/

dotnet test -t --no-build > $rootdir/ci/tasklist

while read line; do
    testcase="$( echo "$line" | cut -d '=' -f 1 )"
    if [[ $testcase == Fluent* ]] ; then
        testname="$(echo "$testcase" | rev | cut -d'.' -f1 | rev)"
        recordpath="$(echo "$testcase" | rev | cut -d'.' -f2-7 | rev)"
        sed -e "s/%testcase%/${testcase}/g" -e "s|%testpath%|${fluentTestPath}|g" -e "s|%recordpath%|${recordpath}|g" -e "s|%testname%|${testname}|g" $rootdir/ci/task_template > $rootdir/ci/file.out
        task=$(cat $rootdir/ci/file.out)
        echo $task, >> $rootdir/ci/app/test_index
    fi
done < $rootdir/ci/tasklist

#sed -i '$ s|.$||' ./app/test_index

truncate -s-2 $rootdir/ci/app/test_index

#sed -i '$! { P; D; }; s|.$||' ./app/test_index

echo "]" >> $rootdir/ci/app/test_index


#!/bin/bash

/usr/bin/yes | sudo apt-get update
/usr/bin/yes | sudo apt install python-pip
/usr/bin/yes | sudo pip install --upgrade pip
sudo pip install azure-cli
az login --identity -u $1
az storage account create -n $2 -g $3 -l $4 --sku Premium_LRS


#!/bin/bash

sudo apt-get install -f

sudo apt-get update

# install apache
sudo apt-get -y install apache2

# restart Apache
sudo service apache2 restart


ï»¿#!/bin/bash

# install DotNet
curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg

sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-xenial-prod xenial main" > /etc/apt/sources.list.d/dotnetdev.list'
sudo apt-get update
sudo apt-get install -y dotnet-sdk-2.1.3

# install Git
sudo apt-get update
sudo apt-get install -y git

# Refresh environment
source /etc/environment


#!/bin/bash
#V-SHISAV@MICROSOFT.COM

#HOW TO PARSE THE ARGUMENTS.. SOURCE - http://stackoverflow.com/questions/4882349/parsing-shell-script-arguments

while echo $1 | grep ^- > /dev/null; do
    eval $( echo $1 | sed 's/-//g' | tr -d '\012')=$2
    shift
    shift
done

newUser=$newUser
newPassword=$newPassword

AddUser()
{
	if [ -e /etc/debian_version ]; then
		echo -e $newPassword'\n'$newPassword | adduser --gecos "" --force-badname -q $newUser
		isUserAdded=$?
	elif [ -e /etc/redhat-release ]; then
		#encryptedPass=$(perl -e 'print crypt($ARGV[0], "password")' $newPassword)
		#adduser $newUser -c "AutomationUser" -m -p $encryptedPass
		adduser $newUser -c "AutomationUser" -m
		isUserAdded=$?
		if [ $isUserAdded = "0" ]; then
			echo User added $newUser
			echo -e $newPassword'\n'$newPassword | passwd $newUser
			isUserAdded=$?
		fi

	elif [ -e /etc/SuSE-release ]; then
		useradd $newUser -c "AutomationUser" -m
		isUserAdded=$?
		if [ $isUserAdded = "0" ]; then
			echo User added $newUser
			echo -e $newPassword'\n'$newPassword | passwd $newUser
			isUserAdded=$?
		fi
	fi

	if [ $isUserAdded = "0" ]; then
	    echo "AUTOMATION_USER_ADDED"
	else
	    echo "AUTOMATION_USER_ADD_FAILED"
	fi

}
AddUser
exit 0


#!/bin/bash

while echo $1 | grep ^- > /dev/null; do
    eval $( echo $1 | sed 's/-//g' | tr -d '\012')=$2
    shift
    shift
done

newUser=$newUser
newPassword=$newPassword

AddUser()
{
	egrep "^$newUser" /etc/passwd >/dev/null
    if [ $? -eq 0 ]; then
        echo "$newUser exists!"
        userdel -r $newUser
    fi
	if [ -e /etc/debian_version ]; then
		echo -e $newPassword'\n'$newPassword | adduser --gecos "" --force-badname -q $newUser
		isUserAdded=$?
	elif [ -e /etc/redhat-release ]; then
		adduser $newUser -c "AutomationUser" -m
		isUserAdded=$?
		if [ $isUserAdded = "0" ]; then
			echo User added $newUser
			echo -e $newPassword'\n'$newPassword | passwd $newUser
			isUserAdded=$?
		fi

	elif [ -e /etc/SuSE-release ]; then
		useradd $newUser -c "AutomationUser" -m
		isUserAdded=$?
		if [ $isUserAdded = "0" ]; then
			echo User added $newUser
			echo -e $newPassword'\n'$newPassword | passwd $newUser
			isUserAdded=$?
		fi
	elif [ -e /etc/os-release ]; then
		tmp=`cat /etc/os-release`
		if [[ "$tmp" == *coreos* ]]; then
			useradd $newUser -c "AutomationUser" -m
			isUserAdded=$?
			if [ $isUserAdded = "0" ]; then
				echo User added $newUser
				echo $newUser:$newPassword | chpasswd
				isUserAdded=$?
			fi
		fi
	fi

	if [ $isUserAdded = "0" ]; then
        echo "$newUser ALL=(ALL) ALL" > /etc/sudoers.d/$newUser
		chmod 0440 /etc/sudoers.d/$newUser
	    echo "AUTOMATION_USER_ADDED"
	else
	    echo "AUTOMATION_USER_ADD_FAILED"
	fi

}
AddUser
exit 0


#!/bin/bash
############################################################################
#
# Linux on Hyper-V and Azure Test Code, ver. 1.0.0
# Copyright (c) Microsoft Corporation
#
# All rights reserved.
# Licensed under the Apache License, Version 2.0 (the ""License"");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#     http://www.apache.org/licenses/LICENSE-2.0
#
# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR
# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
#
# See the Apache Version 2.0 License for specific language governing
# permissions and limitations under the License.
#
############################################################################

ICA_TESTRUNNING="TestRunning"      # The test is running
ICA_TESTCOMPLETED="TestCompleted"  # The test completed successfully
ICA_TESTABORTED="TestAborted"      # Error during setup of test
ICA_TESTFAILED="TestFailed"        # Error during running of test

username=$1
CONSTANTS_FILE="constants.sh"
StateFile="/home/$username/state.txt"
SummaryFile="/home/$username/summary.log"

LogMsg()
{
    echo `date "+%a %b %d %T %Y"` : ${1}    # To add the timestamp to the log file
}

UpdateTestState()
{
    echo $1 > $StateFile
}

#
# Create the state.txt file so ICA knows we are running
#
LogMsg "Updating test case state to running"
UpdateTestState $ICA_TESTRUNNING

#
# Source the constants.sh file to pickup definitions from
# the ICA automation
#
if [ -e ./$CONSTANTS_FILE ]; then
    LogMsg "CONSTANTS FILE: $(cat $CONSTANTS_FILE)"
    source $CONSTANTS_FILE
else
    echo "Warn : no ${CONSTANTS_FILE} found"
fi

if [ -e $SummaryFile ]; then
    LogMsg "Cleaning up previous copies of summary.log"
    rm -f $SummaryFile
fi

#
# Create and delete testfile for Trim test
#
LogMsg "Running TRIM test on /mnt/data to Create 5Gb TEST FILE"
cd /mnt/data;
df -hT | grep /mnt/data
LogMsg "Creating 5GB test file in /mnt/data"
dd if=/dev/zero of=testfile.txt bs=5G count=1
if [ $? -ne 0 ]; then
    LogMsg "Error in creating test file.."
    echo "Creating test file: Failed" >> $SummaryFile
    UpdateTestState $ICA_TESTFAILED
    exit 80
fi
LogMsg "Test file is created on /mnt/data and Waiting for Active pages update."
sleep 300
ls -l
df -hT | grep /mnt/data
LogMsg "Calculate Active pages on TRIM test once test file is created."
#
# Let ICA know we completed successfully
#
LogMsg "Updating test case state to completed"
UpdateTestState $ICA_TESTCOMPLETED

exit 0


#!/bin/bash
############################################################################
#
# Linux on Hyper-V and Azure Test Code, ver. 1.0.0
# Copyright (c) Microsoft Corporation
#
# All rights reserved.
# Licensed under the Apache License, Version 2.0 (the ""License"");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#     http://www.apache.org/licenses/LICENSE-2.0
#
# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR
# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
#
# See the Apache Version 2.0 License for specific language governing
# permissions and limitations under the License.
#
############################################################################

ICA_TESTRUNNING="TestRunning"      # The test is running
ICA_TESTCOMPLETED="TestCompleted"  # The test completed successfully
ICA_TESTABORTED="TestAborted"      # Error during setup of test
ICA_TESTFAILED="TestFailed"        # Error during running of test

username=$1
CONSTANTS_FILE="constants.sh"
StateFile="/home/$username/state.txt"
SummaryFile="/home/$username/summary.log"
s
LogMsg()
{
    echo `date "+%a %b %d %T %Y"` : ${1}    # To add the timestamp to the log file
}

UpdateTestState()
{
    echo $1 > $StateFile
}

#
# Create the state.txt file so ICA knows we are running
#
LogMsg "Updating test case state to running"
UpdateTestState $ICA_TESTRUNNING

#
# Source the constants.sh file to pickup definitions from
# the ICA automation
#
if [ -e ./$CONSTANTS_FILE ]; then
    LogMsg "CONSTANTS FILE: $(cat $CONSTANTS_FILE)"
    source $CONSTANTS_FILE
else
    echo "Warn : no ${CONSTANTS_FILE} found"
fi

if [ -e $SummaryFile ]; then
    LogMsg "Cleaning up previous copies of summary.log"
    rm -f $SummaryFile
fi

#
# Verify test file and delete testfile for Trim test
#
LogMsg "Running TRIM test on /mnt/data to Verify created TEST FILE and delete"
cd /mnt/data;
ls -l
df -hT | grep /mnt/data
LogMsg "Deleting 5GB test file in /mnt/data"
rm -f testfile.txt
if [[ $? -eq 0 ]]; then
    LogMsg "Test file is deleted successfully.."
    echo "Test file is deleted successfully.." >> $SummaryFile
else
    LogMsg "Error in deleting test file.."
    echo "Deleting test file: Failed" >> $SummaryFile
    UpdateTestState $ICA_TESTFAILED
    exit 80
fi
LogMsg "Waiting for Clear Allocated memory by TRIM."
sleep 600
ls -l
df -hT | grep /mnt/data
#
# Let ICA know we completed successfully
#
LogMsg "Updating test case state to completed"
UpdateTestState $ICA_TESTCOMPLETED

exit 0


#!/bin/bash
############################################################################
#
# Linux on Hyper-V and Azure Test Code, ver. 1.0.0
# Copyright (c) Microsoft Corporation
#
# All rights reserved.
# Licensed under the Apache License, Version 2.0 (the ""License"");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#     http://www.apache.org/licenses/LICENSE-2.0
#
# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR
# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
#
# See the Apache Version 2.0 License for specific language governing
# permissions and limitations under the License.
#
############################################################################

ICA_TESTRUNNING="TestRunning"      # The test is running
ICA_TESTCOMPLETED="TestCompleted"  # The test completed successfully
ICA_TESTABORTED="TestAborted"      # Error during setup of test
ICA_TESTFAILED="TestFailed"        # Error during running of test

username=$1
CONSTANTS_FILE="constants.sh"
StateFile="/home/$username/state.txt"
SummaryFile="/home/$username/summary.log"

LogMsg()
{
    echo `date "+%a %b %d %T %Y"` : ${1}    # To add the timestamp to the log file
}

UpdateTestState()
{
    #echo $1 > ~/state.txt
	echo $1 > $StateFile
}

SetValue()
{
    OLD_VALUE=$(cat $1)
    LogMsg "$1 's old value is $OLD_VALUE"
    if [ "$OLD_VALUE" -ne "$2" ]; then
        LogMsg "Changing $1 to $2"
        echo $2 > $1
    fi
}

#
# Create the state.txt file so ICA knows we are running
#
LogMsg "Updating test case state to running"
UpdateTestState $ICA_TESTRUNNING

#
# Source the constants.sh file to pickup definitions from
# the ICA automation
#
if [ -e ./$CONSTANTS_FILE ]; then
    LogMsg "CONSTANTS FILE: $(cat $CONSTANTS_FILE)"
    source $CONSTANTS_FILE
else
    echo "Warn : no ${CONSTANTS_FILE} found"
fi

if [ -e $SummaryFile ]; then
    LogMsg "Cleaning up previous copies of summary.log"
    rm -f $SummaryFile
fi

#DATA_DISK=sdb
DATA_DISK=$DATA_DISK
if ! fdisk -l | grep "Disk /dev/$DATA_DISK"; then
    LogMsg "The /dev/$DATA_DISK not found"
    echo "The /dev/$DATA_DISK not found" >> $SummaryFile
    LogMsg "aborting the test."
    UpdateTestState $ICA_TESTABORTED
    exit 30
fi

SetValue /sys/module/scsi_mod/parameters/scsi_logging_level 63
SetValue /sys/block/$DATA_DISK/device/timeout 180

echo "Test data disk : /dev/$DATA_DISK" >> $SummaryFile
DATA_PARTITION=/dev/${DATA_DISK}1

# Create data partition
df -hT | grep $DATA_PARTITION && umount $DATA_PARTITION
[ -b $DATA_PARTITION ] && (echo p; echo d; echo p; echo w) | fdisk /dev/$DATA_DISK
(echo n; echo p; echo 1; echo; echo; echo w) | fdisk /dev/$DATA_DISK
if [ $? -ne 0 ]; then
    LogMsg "Error in creating data partition.."
    echo "Creating data partition : Failed" >> $SummaryFile
    UpdateTestState $ICA_TESTFAILED
    exit 80
fi
LogMsg "$DATA_PARTITION data partition is created successfully..."

# Format DATA_PARTITION
LogMsg "File System type is $trimParam"
if [ "$trimParam" == "BTRFS" ]
then
    LogMsg "Formatting $DATA_PARTITION with BTRFS FS"
    mkfs.btrfs -f $DATA_PARTITION || mkfs.btrfs $DATA_PARTITION
elif [ "$trimParam" == "XFS" ]
then
    LogMsg "Formatting $DATA_PARTITION with XFS FS"
    mkfs.xfs -f $DATA_PARTITION || mkfs.xfs $DATA_PARTITION
elif [ "$trimParam" == "EXT4" ]
then
    if grep -q "SUSE Linux Enterprise Server 11" /etc/*-release
    then
        LogMsg "Formatting $DATA_PARTITION with ext3 FS"
        mkfs.ext3 -E lazy_itable_init=0 $DATA_PARTITION
    else
        LogMsg "Formatting $DATA_PARTITION with ext4 FS"
        mkfs.ext4 -E lazy_itable_init=0 $DATA_PARTITION
    fi
else
    echo "Please pass valid File System type"
    exit 80
fi
if [ $? -ne 0 ]; then
    LogMsg "Error in creating file system.."
    echo "Creating file system : Failed" >> $SummaryFile
    UpdateTestState $ICA_TESTFAILED
    exit 80
fi
LogMsg "$DATA_PARTITION is formatted successfully..."

find /sys/devices -name 'provisioning_mode' -exec sh -c 'echo -n unmap > $1' -- {} \;

# mount DATA_PARTITION
[ ! -d /mnt/data ] && mkdir /mnt/data
LogMsg "Mounting $DATA_PARTITION with discard option"
mount -o discard $DATA_PARTITION /mnt/data || mount $DATA_PARTITION /mnt/data
if [ $? -eq 0 ]; then
    LogMsg "Drive mounted successfully..."
else
    LogMsg "Error in mounting drive..."
    echo "Drive mount : Failed" >> $SummaryFile
    UpdateTestState $ICA_TESTFAILED
    exit 70
fi

if ! grep -q "SUSE Linux Enterprise Server 11" /etc/*-release
then
    LogMsg "Re-mounting / with discard option"
    mount -o remount,discard /
fi

#Block size details
LogMsg "Block size used for TRIM test :"
blockdev --getbsz /dev/sdb1

#
# Let ICA know we completed successfully
#
LogMsg "Updating test case state to completed"
UpdateTestState $ICA_TESTCOMPLETED

exit 0