diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c1a5ea6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +# Maven +target/ +!.mvn/wrapper/maven-wrapper.jar + +# Jenv +.java-version + +# Eclipse +.settings/ +.classpath +.project + +# IntelliJ IDEA +.idea +*.iml + +# Visual Studio Code +.factorypath + +# Branch switching +generated/ + +# Mac OS +*.DS_Store diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..1ef8d69 --- /dev/null +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or 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. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.4"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + " .jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..1914b84 Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..23fdba0 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.4/maven-wrapper-0.5.4.jar diff --git a/README.md b/README.md index 847260c..8f916c7 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,113 @@ -## My Project +# Introduction +This is a modified version of the [spring-petclinic-microservices](https://github.com/spring-petclinic/spring-petclinic-microservices) Spring Boot sample application. +Our modifications focus on showcasing the capabilities of Application Signals within a Spring Boot environment. +If your interest lies in exploring the broader aspects of the Spring Boot stack, we recommend visiting the original repository at [spring-petclinic-microservices](https://github.com/spring-petclinic/spring-petclinic-microservices). -TODO: Fill this README out! +In the following, we will focus on how customers can set up the current sample application to explore the features of Application Signals. -Be sure to: +# Prerequisite +* A Linux or Mac machine with x86-64 (AMD64) architecture is required for building Docker images for the sample application. +* Docker is installed and running on the machine. +* AWS CLI 2.x is installed. For more information about installing the AWS CLI, see [Install or update the latest version of the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html). +* kubectl is installed - https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html +* eksctl is installed - https://docs.aws.amazon.com/eks/latest/userguide/eksctl.html +* jq is installed - https://jqlang.github.io/jq/download/ -* Change the title in this README -* Edit your repository description on GitHub +# EKS demo -## Security +## Build the sample application images and push to ECR +1. Build container images for each micro-service application -See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. +``` +./mvnw clean install -P buildDocker +``` -## License +2. Create an ECR repo for each micro service and push the images to the relevant repos. Replace the aws account id and the AWS Region. + +``` +export ACCOUNT='111122223333' +export REGION='us-east-1' +./push-ecr.sh +``` -This project is licensed under the Apache-2.0 License. +## Try Application Signals with the sample application +1. Create an EKS cluster, enable Application Signals, and deploy the sample application to your EKS cluster. Replace `new-cluster-name` with the name that you want to use for the new cluster. Replace `region-name` with the same region in previous section "**Build the sample application images and push to ECR**". + +``` +cd scripts/eks/appsignals/one-step && ./setup.sh new-cluster-name region-name +``` + +2. Clean up all the resources. Replace `new-cluster-name` and `region-name` with the same values that you use in previous step. + +``` +cd scripts/eks/appsignals/one-step && ./cleanup.sh new-cluster-name region-name +``` + + +# EC2 Demo +The following instructions describe how to set up the pet clinic sample application on EC2 instances. You can run these steps in your personal AWS account to follow along. + +1. Clone this repository and run `./mvnw clean install` +2. Set up an S3 bucket in your account and put the created JAR files into it +3. Set up a VPC with a public subnet and a security group accepting all traffic. +4. Set up 5 EC2 instances all with the following configuration: + - Running on Amazon Linux + - Instance type t2.small or larger + - A key-pair you save to your computer + - Use the VPC, public subnet, and security group created in step 1 + - Enable auto-assign public IP + - An IAM instance profile with the following permissions: + - AmazonDynamoDBFullAccess + - AmazonKinesisFullAccess + - AmazonS3FullAccess + - AmazonSQSFullAccess +5. Rename your instances as follows to follow along with the instructions: + - setup + - pet-clinic-frontend + - vets + - customers + - visits +6. Connect to the EC2 instance named setup and run the following commands to start the config, discovery, and admin services: + +``` +sudo yum install java-1.8.0 +aws s3 sync s3:// . +screen -S config +java -jar spring-petclinic-config... +``` +Leave the config service `screen` session by inputting `ctrl+a, d`. +``` +clear +screen -S discovery +java -jar spring-petclinic-discovery... +``` +Leave the discovery service `screen` session by inputting `ctrl+a, d`. +``` +clear +screen -S admin +java -jar spring-petclinic-admin... +``` +Leave the admin service `screen` session by inputting `ctrl+a, d`. +Feel free to end your connection to the EC2 instance, the screens will continue running. + +7. Connect to the EC2 instance named pet-clinic-frontend and run the following commands to start the api-gateway service. Make sure to replace the private IP in the export commands. +``` +sudo yum install java-1.8.0 +aws s3 sync s3:// . +export CONFIG_SERVER_URL=http://:8888 +export DISCOVERY_SERVER_URL=http://:8761/eureka +screen -S frontend +java -jar spring-petclinic-api-gateway... +``` +Leave the api-gateway service `screen` session by inputting `ctrl+a, d`. +Feel free to end your connection to the EC2 instance, the screen will continue running the service + +8. Repeat step 7 for the remaining EC2 instances (vets, customers, visits) + +9. Visit the sample application by going to http://:8080 + +10. Interact with the application to ensure you've properly set up the backend services. Note that each service takes a few seconds to come up. + + +To enable Application Signals on the sample application, please refer to [this user guide](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Signals-Enable-EC2.html). diff --git a/THIRD_PARTY_LICENSES b/THIRD_PARTY_LICENSES new file mode 100644 index 0000000..5196242 --- /dev/null +++ b/THIRD_PARTY_LICENSES @@ -0,0 +1,219 @@ +** spring-petclinic-microservices; version 2.6.7 -- https://github.com/spring-petclinic/spring-petclinic-microservices/tree/master + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +* For spring-petclinic-microservices see also this required NOTICE: + /* + * Copyright 2002-2021 the original author or 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. + */ diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..b8d72fb --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,34 @@ +FROM public.ecr.aws/amazoncorretto/amazoncorretto:11 as builder +WORKDIR /application +ARG ARTIFACT_NAME +COPY ${ARTIFACT_NAME}.jar application.jar +RUN java -Djarmode=layertools -jar application.jar extract + +# Install wget +RUN yum install -y wget tar gzip && yum clean all + +# Download dockerize and cache that layer +ARG DOCKERIZE_VERSION +RUN wget -O dockerize.tar.gz https://github.com/jwilder/dockerize/releases/download/${DOCKERIZE_VERSION}/dockerize-alpine-linux-amd64-${DOCKERIZE_VERSION}.tar.gz +RUN tar xzf dockerize.tar.gz +RUN chmod +x dockerize + + +FROM public.ecr.aws/amazoncorretto/amazoncorretto:11 +USER 1000 + +WORKDIR /application + +# Dockerize +COPY --from=builder /application/dockerize ./ + +ARG EXPOSED_PORT +EXPOSE ${EXPOSED_PORT} + +ENV SPRING_PROFILES_ACTIVE docker + +COPY --from=builder /application/dependencies/ ./ +COPY --from=builder /application/spring-boot-loader/ ./ +COPY --from=builder /application/snapshot-dependencies/ ./ +COPY --from=builder /application/application/ ./ +ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"] diff --git a/mvnw b/mvnw new file mode 100755 index 0000000..35ff643 --- /dev/null +++ b/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.4/maven-wrapper-0.5.4.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.4/maven-wrapper-0.5.4.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..dae46d4 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.4/maven-wrapper-0.5.4.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.4/maven-wrapper-0.5.4.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..fc45017 --- /dev/null +++ b/pom.xml @@ -0,0 +1,164 @@ + + +4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.7 + + +org.springframework.samples +spring-petclinic-microservices +2.6.7 +${project.artifactId} +pom + + + spring-petclinic-admin-server + spring-petclinic-customers-service + spring-petclinic-vets-service + spring-petclinic-visits-service + spring-petclinic-config-server + spring-petclinic-discovery-server + spring-petclinic-api-gateway + + + + 1.8 + 3.17.1 + + 2.6.0 + 2021.0.2 + 2.3.10 + + springcommunity + 9090 + ${basedir} + v0.6.1 + 1.2.0 + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + de.codecentric + chaos-monkey-spring-boot + ${chaos-monkey-spring-boot.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + + + springboot + + + + src/main/resources/application.yml + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + build-info + + + + ${project.build.sourceEncoding} + ${project.reporting.outputEncoding} + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + + + pl.project13.maven + git-commit-id-plugin + + + + revision + + + + + true + yyyy-MM-dd'T'HH:mm:ssZ + true + ${project.build.outputDirectory}/git.properties + false + false + + + + + + + + buildDocker + + + + + com.spotify + docker-maven-plugin + ${docker.plugin.version} + + + install + + build + + + + + ${docker.image.prefix}/${project.artifactId} + ${docker.image.dockerfile.dir} + docker-hub + https://index.docker.io/v1/ + + + / + ${project.build.directory} + ${project.build.finalName}.jar + + + + ${project.build.finalName} + ${docker.image.exposed.port} + ${docker.image.dockerize.version} + + + + + + + + + + diff --git a/push-ecr.sh b/push-ecr.sh new file mode 100755 index 0000000..a85ea73 --- /dev/null +++ b/push-ecr.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +export REPOSITORY_PREFIX=${ACCOUNT}.dkr.ecr.${REGION}.amazonaws.com + +aws ecr get-login-password --region ${REGION} | docker login --username AWS --password-stdin ${REPOSITORY_PREFIX} + +aws ecr create-repository --repository-name springcommunity/spring-petclinic-api-gateway --region ${REGION} || true +docker tag springcommunity/spring-petclinic-api-gateway:latest ${REPOSITORY_PREFIX}/springcommunity/spring-petclinic-api-gateway:latest +docker push ${REPOSITORY_PREFIX}/springcommunity/spring-petclinic-api-gateway:latest + +aws ecr create-repository --repository-name springcommunity/spring-petclinic-discovery-server --region ${REGION} || true +docker tag springcommunity/spring-petclinic-discovery-server:latest ${REPOSITORY_PREFIX}/springcommunity/spring-petclinic-discovery-server:latest +docker push ${REPOSITORY_PREFIX}/springcommunity/spring-petclinic-discovery-server:latest + +aws ecr create-repository --repository-name springcommunity/spring-petclinic-config-server --region ${REGION} || true +docker tag springcommunity/spring-petclinic-config-server:latest ${REPOSITORY_PREFIX}/springcommunity/spring-petclinic-config-server:latest +docker push ${REPOSITORY_PREFIX}/springcommunity/spring-petclinic-config-server:latest + +aws ecr create-repository --repository-name springcommunity/spring-petclinic-visits-service --region ${REGION} || true +docker tag springcommunity/spring-petclinic-visits-service:latest ${REPOSITORY_PREFIX}/springcommunity/spring-petclinic-visits-service:latest +docker push ${REPOSITORY_PREFIX}/springcommunity/spring-petclinic-visits-service:latest + +aws ecr create-repository --repository-name springcommunity/spring-petclinic-vets-service --region ${REGION} || true +docker tag springcommunity/spring-petclinic-vets-service:latest ${REPOSITORY_PREFIX}/springcommunity/spring-petclinic-vets-service:latest +docker push ${REPOSITORY_PREFIX}/springcommunity/spring-petclinic-vets-service:latest + +aws ecr create-repository --repository-name springcommunity/spring-petclinic-customers-service --region ${REGION} || true +docker tag springcommunity/spring-petclinic-customers-service:latest ${REPOSITORY_PREFIX}/springcommunity/spring-petclinic-customers-service:latest +docker push ${REPOSITORY_PREFIX}/springcommunity/spring-petclinic-customers-service:latest + +aws ecr create-repository --repository-name springcommunity/spring-petclinic-admin-server --region ${REGION} || true +docker tag springcommunity/spring-petclinic-admin-server:latest ${REPOSITORY_PREFIX}/springcommunity/spring-petclinic-admin-server:latest +docker push ${REPOSITORY_PREFIX}/springcommunity/spring-petclinic-admin-server:latest + diff --git a/scripts/eks/appsignals/canaries/policies/canary_policy.json b/scripts/eks/appsignals/canaries/policies/canary_policy.json new file mode 100644 index 0000000..bcb1884 --- /dev/null +++ b/scripts/eks/appsignals/canaries/policies/canary_policy.json @@ -0,0 +1,55 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "s3:PutObject", + "s3:GetObject" + ], + "Resource": [ + "arn:aws:s3:::cw-syn-results-petclinic-*-*/*" + ] + }, + { + "Effect": "Allow", + "Action": [ + "s3:GetBucketLocation" + ], + "Resource": [ + "arn:aws:s3:::cwn-syn-results-petclinic-*-*" + ] + }, + { + "Effect": "Allow", + "Action": [ + "logs:CreateLogStream", + "logs:PutLogEvents", + "logs:CreateLogGroup" + ], + "Resource": [ + "arn:aws:logs:*:*:log-group:/aws/lambda/cwsyn-*" + ] + }, + { + "Effect": "Allow", + "Action": [ + "s3:ListAllMyBuckets", + "xray:PutTraceSegments" + ], + "Resource": [ + "*" + ] + }, + { + "Effect": "Allow", + "Resource": "*", + "Action": "cloudwatch:PutMetricData", + "Condition": { + "StringEquals": { + "cloudwatch:namespace": "CloudWatchSynthetics" + } + } + } + ] +} \ No newline at end of file diff --git a/scripts/eks/appsignals/canaries/policies/canary_role.json b/scripts/eks/appsignals/canaries/policies/canary_role.json new file mode 100644 index 0000000..72a13c3 --- /dev/null +++ b/scripts/eks/appsignals/canaries/policies/canary_role.json @@ -0,0 +1,12 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": { + "Service": "lambda.amazonaws.com" + }, + "Action": "sts:AssumeRole" + } + ] +} \ No newline at end of file diff --git a/scripts/eks/appsignals/canaries/scripts/pc-add-visit.js b/scripts/eks/appsignals/canaries/scripts/pc-add-visit.js new file mode 100644 index 0000000..4ec0417 --- /dev/null +++ b/scripts/eks/appsignals/canaries/scripts/pc-add-visit.js @@ -0,0 +1,46 @@ +const synthetics = require('Synthetics'); +const log = require('SyntheticsLogger'); +const syntheticsConfiguration = synthetics.getConfiguration(); + +const flowBuilderBlueprint = async function () { + let url = process.env.URL + "/#!/owners/details/1"; + + syntheticsConfiguration.setConfig({ + includeRequestHeaders: true, // Enable if headers should be displayed in HAR + includeResponseHeaders: true, // Enable if headers should be displayed in HAR + restrictedHeaders: [], // Value of these headers will be redacted from logs and reports + restrictedUrlParameters: [] // Values of these url parameters will be redacted from logs and reports + }); + let page = await synthetics.getPage(); + + // Navigate to the initial url + await synthetics.executeStep('navigateToUrl', async function (timeoutInMillis = 120000) { + await page.goto(url, {waitUntil: ['load', 'networkidle0'], timeout: timeoutInMillis}); + }); + + // Execute customer steps + await synthetics.executeStep('click', async function () { + await page.waitForSelector("body > div > div > div > ui-view > owner-details > table:nth-child(4) > tbody > tr:nth-child(1) > td:nth-child(2) > table > tbody > tr > td:nth-child(2) > a", { timeout: 30000 }); + await Promise.all([ + page.click("body > div > div > div > ui-view > owner-details > table:nth-child(4) > tbody > tr:nth-child(1) > td:nth-child(2) > table > tbody > tr > td:nth-child(2) > a"), + page.waitForNavigation({ timeout: 30000 }) + ]); + }); + await synthetics.executeStep('input', async function () { + await page.waitFor(12000); + await page.type("body > div > div > div > ui-view > visits > form > div:nth-child(2) > textarea", "i\'m going to visit"); + }); + await synthetics.executeStep('click', async function () { + await page.waitForSelector("body > div > div > div > ui-view > visits > form > div:nth-child(3) > button", { timeout: 120000 }); + await Promise.all([ + page.click("body > div > div > div > ui-view > visits > form > div:nth-child(3) > button"), + page.waitForNavigation({ timeout: 30000 }) + ]); + }); + + +}; + +exports.handler = async () => { + return await flowBuilderBlueprint(); +}; \ No newline at end of file diff --git a/scripts/eks/appsignals/canaries/scripts/pc-create-owners.js b/scripts/eks/appsignals/canaries/scripts/pc-create-owners.js new file mode 100644 index 0000000..22d2b95 --- /dev/null +++ b/scripts/eks/appsignals/canaries/scripts/pc-create-owners.js @@ -0,0 +1,81 @@ +const synthetics = require('Synthetics'); +const log = require('SyntheticsLogger'); +const syntheticsConfiguration = synthetics.getConfiguration(); + +const flowBuilderBlueprint = async function () { + let url = process.env.URL + "/#!/owners/new"; + + syntheticsConfiguration.setConfig({ + includeRequestHeaders: true, // Enable if headers should be displayed in HAR + includeResponseHeaders: true, // Enable if headers should be displayed in HAR + restrictedHeaders: [], // Value of these headers will be redacted from logs and reports + restrictedUrlParameters: [] // Values of these url parameters will be redacted from logs and reports + }); + let page = await synthetics.getPage(); + const currentTime = new Date().toLocaleTimeString() + const firstName = "firstName" + currentTime; + const lastName = "lastName" + currentTime; + + // Navigate to the initial url + await synthetics.executeStep('navigateToUrl', async function (timeoutInMillis = 120000) { + await page.goto(url, {waitUntil: ['load', 'networkidle0'], timeout: timeoutInMillis}); + }); + + // Execute customer steps + await synthetics.executeStep('input', async function () { + await page.type("body > div > div > div > ui-view > owner-form > form > div:nth-child(1) > input", firstName); + }); + await synthetics.executeStep('input', async function () { + await page.type("body > div > div > div > ui-view > owner-form > form > div:nth-child(2) > input", lastName); + }); + await synthetics.executeStep('input', async function () { + await page.type("body > div > div > div > ui-view > owner-form > form > div:nth-child(3) > input", "address"); + }); + await synthetics.executeStep('input', async function () { + await page.type("body > div > div > div > ui-view > owner-form > form > div:nth-child(4) > input", "city"); + }); + await synthetics.executeStep('input', async function () { + await page.type("body > div > div > div > ui-view > owner-form > form > div:nth-child(5) > input", "408098080808"); + }); + await synthetics.executeStep('click', async function () { + await page.waitForSelector("body > div > div > div > ui-view > owner-form > form > div:nth-child(6) > button", { timeout: 30000 }); + await Promise.all([ + page.click("body > div > div > div > ui-view > owner-form > form > div:nth-child(6) > button"), + page.waitForNavigation({ timeout: 30000 }) + ]); + }); + await synthetics.executeStep('input', async function () { + await page.type("body > div > div > div > ui-view > owner-list > form > div > input", "FirstName"); + }); + await synthetics.executeStep('click', async function () { + await page.waitForSelector("body > div > div > div > ui-view > owner-list > table > tbody > tr:nth-child(1) > td:nth-child(1) > a", { timeout: 30000 }); + await Promise.all([ + page.click("body > div > div > div > ui-view > owner-list > table > tbody > tr:nth-child(1) > td:nth-child(1) > a"), + page.waitForNavigation({ timeout: 30000 }) + ]); + }); + await synthetics.executeStep('click', async function () { + await page.waitForSelector("body > div > div > div > ui-view > owner-details > table:nth-child(2) > tbody > tr:nth-child(5) > td:nth-child(2) > a", { timeout: 30000 }); + await Promise.all([ + page.click("body > div > div > div > ui-view > owner-details > table:nth-child(2) > tbody > tr:nth-child(5) > td:nth-child(2) > a"), + page.waitForNavigation({ timeout: 30000 }) + ]); + }); + await synthetics.executeStep('input', async function () { + await page.type("body > div > div > div > ui-view > pet-form > form > div:nth-child(2) > div > input", lastName); + }); + await synthetics.executeStep('input', async function () { + await page.type("body > div > div > div > ui-view > pet-form > form > div:nth-child(3) > div > input", "08082022"); + }); + await synthetics.executeStep('click', async function () { + await page.waitForSelector("body > div > div > div > ui-view > pet-form > form > div:nth-child(5) > div > button", { timeout: 120000 }); + await Promise.all([ + await page.click("body > div > div > div > ui-view > pet-form > form > div:nth-child(5) > div > button"), + page.waitForNavigation({ timeout: 30000 }) + ]); + }); +}; + +exports.handler = async () => { + return await flowBuilderBlueprint(); +}; \ No newline at end of file diff --git a/scripts/eks/appsignals/canaries/scripts/pc-visit-pet.js b/scripts/eks/appsignals/canaries/scripts/pc-visit-pet.js new file mode 100644 index 0000000..d6b41e8 --- /dev/null +++ b/scripts/eks/appsignals/canaries/scripts/pc-visit-pet.js @@ -0,0 +1,35 @@ +const synthetics = require('Synthetics'); +const log = require('SyntheticsLogger'); +const syntheticsConfiguration = synthetics.getConfiguration(); + +const flowBuilderBlueprint = async function () { + let url = process.env.URL + "/#!/owners/1/pets/1"; + + syntheticsConfiguration.setConfig({ + includeRequestHeaders: true, // Enable if headers should be displayed in HAR + includeResponseHeaders: true, // Enable if headers should be displayed in HAR + restrictedHeaders: [], // Value of these headers will be redacted from logs and reports + restrictedUrlParameters: [] // Values of these url parameters will be redacted from logs and reports + }); + let page = await synthetics.getPage(); + + // Navigate to the initial url + await synthetics.executeStep('navigateToUrl', async function (timeoutInMillis = 120000) { + await page.goto(url, {waitUntil: ['load', 'networkidle0'], timeout: timeoutInMillis}); + }); + + // Execute customer steps + await synthetics.executeStep('click', async function () { + await page.waitForSelector("body > div > div > div > ui-view > pet-form > form > div:nth-child(5) > div > button", { timeout: 120000 }); + await Promise.all([ + page.click("body > div > div > div > ui-view > pet-form > form > div:nth-child(5) > div > button"), + page.waitForNavigation({ timeout: 30000 }) + ]); + }); + + +}; + +exports.handler = async () => { + return await flowBuilderBlueprint(); +}; \ No newline at end of file diff --git a/scripts/eks/appsignals/canaries/scripts/pc-visit-vet.js b/scripts/eks/appsignals/canaries/scripts/pc-visit-vet.js new file mode 100644 index 0000000..1216171 --- /dev/null +++ b/scripts/eks/appsignals/canaries/scripts/pc-visit-vet.js @@ -0,0 +1,24 @@ +const synthetics = require('Synthetics'); +const log = require('SyntheticsLogger'); +const syntheticsConfiguration = synthetics.getConfiguration(); + +const flowBuilderBlueprint = async function () { + let url = process.env.URL + "/#!/vets"; + + syntheticsConfiguration.setConfig({ + includeRequestHeaders: true, // Enable if headers should be displayed in HAR + includeResponseHeaders: true, // Enable if headers should be displayed in HAR + restrictedHeaders: [], // Value of these headers will be redacted from logs and reports + restrictedUrlParameters: [] // Values of these url parameters will be redacted from logs and reports + }); + let page = await synthetics.getPage(); + + // Navigate to the initial url + await synthetics.executeStep('navigateToUrl', async function (timeoutInMillis = 120000) { + await page.goto(url, {waitUntil: ['load', 'networkidle0'], timeout: timeoutInMillis}); + }); +}; + +exports.handler = async () => { + return await flowBuilderBlueprint(); +}; \ No newline at end of file diff --git a/scripts/eks/appsignals/canaries/scripts/pet-clinic-traffic.js b/scripts/eks/appsignals/canaries/scripts/pet-clinic-traffic.js new file mode 100644 index 0000000..dd615bb --- /dev/null +++ b/scripts/eks/appsignals/canaries/scripts/pet-clinic-traffic.js @@ -0,0 +1,39 @@ +const synthetics = require('Synthetics'); +const log = require('SyntheticsLogger'); +const syntheticsConfiguration = synthetics.getConfiguration(); + +const flowBuilderBlueprint = async function () { + let url = process.env.URL + "/#!/welcome"; + + syntheticsConfiguration.setConfig({ + includeRequestHeaders: true, // Enable if headers should be displayed in HAR + includeResponseHeaders: true, // Enable if headers should be displayed in HAR + restrictedHeaders: [], // Value of these headers will be redacted from logs and reports + restrictedUrlParameters: [] // Values of these url parameters will be redacted from logs and reports + }); + let page = await synthetics.getPage(); + + // Navigate to the initial url + await synthetics.executeStep('navigateToUrl', async function (timeoutInMillis = 120000) { + await page.goto(url, {waitUntil: ['load', 'networkidle0'], timeout: timeoutInMillis}); + }); + + // Execute customer steps + await synthetics.executeStep('click', async function () { + await page.waitForSelector("#main-navbar > ul > li.dropdown > a", { timeout: 120000 }); + await page.click("#main-navbar > ul > li.dropdown > a"); + }); + await synthetics.executeStep('click', async function () { + await page.waitForSelector("#main-navbar > ul > li.dropdown.open > ul > li:nth-child(2) > a", { timeout: 30000 }); + await Promise.all([ + page.click("#main-navbar > ul > li.dropdown.open > ul > li:nth-child(2) > a"), + page.waitForNavigation({ timeout: 30000 }) + ]); + }); + + +}; + +exports.handler = async () => { + return await flowBuilderBlueprint(); +}; \ No newline at end of file diff --git a/scripts/eks/appsignals/clean-app-signals.sh b/scripts/eks/appsignals/clean-app-signals.sh new file mode 100755 index 0000000..2daf1f7 --- /dev/null +++ b/scripts/eks/appsignals/clean-app-signals.sh @@ -0,0 +1,25 @@ +#!/bin/bash +# set -x + +# change the directory to the script location so that the relative path can work +cd "$(dirname "$0")" + +# Set variables with provided arguments +CLUSTER_NAME=$1 +REGION=$2 +NAMESPACE=${3:-default} + +# Check if the current context points to the new cluster in the correct region +kub_config=$(kubectl config current-context) +if [[ $kub_config != *"$CLUSTER_NAME"* ]] || [[ $kub_config != *"$REGION"* ]]; then + echo "Your current cluster context is not set to $CLUSTER_NAME $REGION. Please switch to the correct context first before running this script" + exit 1 +fi + +echo "Deleting amazon-cloudwatch-observability addon" +aws eks delete-addon --cluster-name $CLUSTER_NAME --addon-name amazon-cloudwatch-observability --region $REGION + +echo "Deleting ServiceAccount" +eksctl delete iamserviceaccount --cluster $CLUSTER_NAME --region $REGION --name cloudwatch-agent --namespace amazon-cloudwatch + +aws logs delete-log-group --log-group-name '/aws/appsignals/eks' --region $REGION diff --git a/scripts/eks/appsignals/cleanup-slo.sh b/scripts/eks/appsignals/cleanup-slo.sh new file mode 100755 index 0000000..14dd9d9 --- /dev/null +++ b/scripts/eks/appsignals/cleanup-slo.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +# change the directory to the script location so that the relative path can work +cd "$(dirname "$0")" + +REGION=$1 + +echo "Deleting Service Level Objectives" + +err=0 +trap 'err=1' ERR + +aws cloudwatch delete-service-level-objective --cli-input-json file://slo/inputRequest/DeleteServiceLevelObjective/deleteSlo1.json --region $REGION --no-cli-pager +aws cloudwatch delete-service-level-objective --cli-input-json file://slo/inputRequest/DeleteServiceLevelObjective/deleteSlo2.json --region $REGION --no-cli-pager +aws cloudwatch delete-service-level-objective --cli-input-json file://slo/inputRequest/DeleteServiceLevelObjective/deleteSlo3.json --region $REGION --no-cli-pager +aws cloudwatch delete-service-level-objective --cli-input-json file://slo/inputRequest/DeleteServiceLevelObjective/deleteSlo4.json --region $REGION --no-cli-pager + +exit $err diff --git a/scripts/eks/appsignals/create-canaries.sh b/scripts/eks/appsignals/create-canaries.sh new file mode 100755 index 0000000..8cc111e --- /dev/null +++ b/scripts/eks/appsignals/create-canaries.sh @@ -0,0 +1,202 @@ +#!/usr/bin/env bash + +############################################################################## +# +# Use this script to create canaries or clean them up for the Pet Clinic +# sample app. +# +############################################################################## + +cd "$(dirname "$0")" + +# Set variables with provided arguments or default values +REGION=${1:-"us-west-2"} +OPERATION=${2:-"create"} # Specify 'create' to set up canaries or 'delete' to clean up canaries + +ACCOUNT_ID=$(aws sts get-caller-identity | jq -r '.Account') +if [ -z "$ACCOUNT_ID" ]; then + echo "Fail to get account id. Account id is empty. Exit the script" + exit 8 +fi +ROLE_PATH="/service-role/" +ROLE_NAME="CloudWatchSyntheticsRole-PetClinic-$ACCOUNT_ID-$REGION" +POLICY_NAME="CloudWatchSyntheticsPolicy-PetClinic-$ACCOUNT_ID-$REGION" +POLICY_ARN="arn:aws:iam::$ACCOUNT_ID:policy/service-role/$POLICY_NAME" +CODE_BUCKET="aws-synthetics-code-petclinic-$ACCOUNT_ID-$REGION" +ARTIFACT_BUCKET="cw-syn-results-petclinic-$ACCOUNT_ID-$REGION" + +setup() { + echo "Setting up the canary execution role" + res=$(aws iam get-role --role-name $ROLE_NAME --region $REGION 2>&1;) + if ! grep -q "The role with name "$ROLE_NAME" cannot be found" <<< "$res"; then + echo "Role "$ROLE_NAME" exist. Update it." + aws iam update-assume-role-policy --role-name $ROLE_NAME --policy-document file://canaries/policies/canary_role.json --no-cli-pager + else + echo "Start creating IAM role $ROLE_NAME" + aws iam create-role --path $ROLE_PATH --role-name $ROLE_NAME --assume-role-policy-document file://canaries/policies/canary_role.json --no-cli-pager + fi + + res=$(aws iam get-policy --policy-arn $POLICY_ARN --region $REGION 2>&1;) + if ! grep -q "Policy "$POLICY_ARN" was not found" <<< "$res"; then + echo "Policy "$POLICY_ARN" exist. Update it." + policy_pre_version_id=$(echo $res | jq -r '.Policy.DefaultVersionId') + res=$(aws iam create-policy-version --policy-arn $POLICY_ARN --policy-document file://canaries/policies/canary_policy.json --set-as-default --no-cli-pager) + echo $res | jq + if ! grep -q "VersionId" <<< "$res"; then + echo "Fail to create new IAM policy version. Exit the script." + exit 9 + fi + echo "Deleting old policy version $policy_pre_version_id" + aws iam delete-policy-version --policy-arn $POLICY_ARN --version-id $policy_pre_version_id --no-cli-pager + else + echo "creating IAM policy" + aws iam create-policy --path $ROLE_PATH --policy-name $POLICY_NAME --policy-document file://canaries/policies/canary_policy.json --no-cli-pager + fi + aws iam attach-role-policy --role-name $ROLE_NAME --policy-arn $POLICY_ARN + + echo "Setting up S3 code buckets" + res=$(aws s3api head-bucket --bucket $CODE_BUCKET --region $REGION 2>&1) + if [ -z "$res" ]; then + echo "Bucket $CODE_BUCKET is already created." + else + echo "Creating S3 code bucket $CODE_BUCKET" + aws s3 mb s3://$CODE_BUCKET --region $REGION + fi + + res=$(aws s3api head-bucket --bucket $ARTIFACT_BUCKET --region $REGION 2>&1) + if [ -z "$res" ]; then + echo "Bucket $CODE_BUCKET is already created." + else + echo "Creating S3 artifact bucket $ARTIFACT_BUCKET" + aws s3 mb s3://$ARTIFACT_BUCKET --region $REGION + fi +} + +cleanup() { + echo "Cleaning up canary execution role" + aws iam detach-role-policy --role-name $ROLE_NAME --policy-arn $POLICY_ARN + aws iam delete-role --role-name $ROLE_NAME + other_policy_versions=($(aws iam list-policy-versions --policy-arn $POLICY_ARN | jq -r '.Versions[]|select(.IsDefaultVersion==false)|.VersionId')) + for other_policy_version in "${other_policy_versions[@]}" + do + aws iam delete-policy-version --policy-arn $POLICY_ARN --version-id $other_policy_version + done + aws iam delete-policy --policy-arn $POLICY_ARN + + echo "Cleaning up S3 code buckets" + aws s3 rm s3://$CODE_BUCKET --recursive --region $REGION + aws s3 rm s3://$ARTIFACT_BUCKET --recursive --region $REGION + aws s3api delete-bucket --bucket $CODE_BUCKET --region $REGION + aws s3api delete-bucket --bucket $ARTIFACT_BUCKET --region $REGION +} + +delete_canaries() { + for canary_name in ${canaries[@]}; do + echo "Deleting canary $canary_name" + canary_id=$(aws synthetics get-canary --name $canary_name --region $REGION | jq -r '.Canary.Id') + aws synthetics delete-canary --name $canary_name --delete-lambda --region $REGION + aws logs delete-log-group --log-group-name "/aws/lambda/cwsyn-${canary_name}-${canary_id}" --region $REGION + done +} + +stop_canaries() { + for canary_name in ${canaries[@]}; do + echo "Stopping canary $canary_name" + aws synthetics stop-canary --name $canary_name --region $REGION + done +} + +upload_canary_script() { + canary_name=$1 + mkdir -p nodejs/node_modules + cp "canaries/scripts/$canary_name.js" "nodejs/node_modules/$canary_name.js" + zip -r $canary_name.zip nodejs + + echo "Uploading canary script for canary $canary_name to S3" + aws s3api put-object --bucket $CODE_BUCKET --key $canary_name --body "$canary_name.zip" | jq + rm -rf nodejs $canary_name.zip +} + +create_canary() { + canary_name=$1 + canary_execution_role_arn=$(aws iam get-role --role-name $ROLE_NAME | jq -r '.Role.Arn') + if [ -z "$canary_execution_role_arn" ]; then + echo "Fail to get canary execution role arn. Exit the script" + exit 1 + fi + + ENDPOINT=${3:-"http://"$(kubectl get svc -n ingress-nginx | grep "ingress-nginx" | awk '{print $4}')} + if [ -z "$ENDPOINT" ]; then + echo "Fail to get a valid endpoint. Endpoint is empty. Exit the script" + exit 6 + elif [[ "$ENDPOINT" == 'http://' ]]; then + echo "Fail to get a valid endpoint. Endpoint is http:// Exit the script" + exit 7 + fi + echo "ENDPOINT is $ENDPOINT" + + echo "Creating/updating canary $canary_name" + res=$(aws synthetics get-canary --name $canary_name --region $REGION 2>&1) + [[ $(grep "Canary not found" <<< "$res") ]] && operation="create-canary" || operation="update-canary" + aws synthetics $operation \ + --name $canary_name \ + --artifact-s3-location "s3://$ARTIFACT_BUCKET" \ + --code Handler="$canary_name.handler",S3Bucket="$CODE_BUCKET",S3Key="$canary_name" \ + --execution-role-arn $canary_execution_role_arn \ + --runtime-version "syn-nodejs-puppeteer-4.0" \ + --schedule Expression="rate(1 minute)" \ + --run-config ActiveTracing=true,EnvironmentVariables={URL=$ENDPOINT} \ + --region $REGION \ + --no-cli-pager \ + | jq +} + +create_canaries() { + for canary_name in ${canaries[@]}; do + upload_canary_script $canary_name + create_canary $canary_name + done +} + +start_canaries() { + for canary_name in ${canaries[@]}; do + res=$(set -x; aws synthetics get-canary --name $canary_name --region $REGION 2>&1; set +x;) + if (grep -q '"State": "RUNNING"' <<< "$res") then + echo "Canary $canary_name is already running. Skip the starting step" + else + echo "Starting canary $canary_name" + aws synthetics start-canary --name $canary_name --region $REGION + fi + done +} + +# Print out the values +echo "REGION is $REGION" +echo "OPERATION is $OPERATION" +echo "ACCOUNT_ID is $ACCOUNT_ID" + +declare -a canaries=( + "pc-add-visit" + "pc-create-owners" + "pc-visit-pet" + "pc-visit-vet" + "pet-clinic-traffic" +) + +if [ $OPERATION = "create" ]; then + setup + create_canaries + echo "Waiting a minute for canaries to finish creating or updating." + sleep 60 + echo "Done waiting. Starting canaries." + start_canaries +elif [ $OPERATION = "delete" ]; then + stop_canaries + echo "Waiting a minute for canaries to finish stopping." + sleep 60 + echo "Done waiting. Deleting canaries." + delete_canaries + cleanup +else + echo "Unknown operation $OPERATION" +fi diff --git a/scripts/eks/appsignals/create-cluster.sh b/scripts/eks/appsignals/create-cluster.sh new file mode 100755 index 0000000..4e17a95 --- /dev/null +++ b/scripts/eks/appsignals/create-cluster.sh @@ -0,0 +1,43 @@ +#!/bin/bash + +# Optional inputs with default values +cluster_name=$1 +region=$2 + +usage() { + echo "Usage: $0 [cluster_name] [region]" + echo "cluster_name: the name of the EKS cluster" + echo "region: the AWS region to create the cluster" + exit 1 +} + +# If --help is provided as an argument, print the usage +for arg in "$@" +do + if [[ "$arg" == "--help" ]]; then + usage + exit 0 + fi +done + +check_cluster_exists() { + cluster_exists=$(aws eks describe-cluster --name $cluster_name --region $region --query 'cluster.[name]' --output text 2>/dev/null) + + if [[ "$cluster_exists" == "$cluster_name" ]]; then + echo "Error: Cluster $cluster_name already exists in region $region" + exit 1 + fi +} + +create_cluster() { + eksctl create cluster --name $cluster_name --region $region --nodes=2 + if [[ $? -eq 0 ]]; then + echo "Cluster $cluster_name has been created successfully in region $region" + else + echo "Error: Failed to create cluster $cluster_name in region $region" + exit 1 + fi +} + +check_cluster_exists +create_cluster diff --git a/scripts/eks/appsignals/create-slo.sh b/scripts/eks/appsignals/create-slo.sh new file mode 100755 index 0000000..f1a644f --- /dev/null +++ b/scripts/eks/appsignals/create-slo.sh @@ -0,0 +1,156 @@ +#!/bin/bash + +# change the directory to the script location so that the relative path can work +cd "$(dirname "$0")" + +CLUSTER_NAME=$1 +REGION=$2 +SERVICE_NAME="pet-clinic-frontend" + +check_if_step_failed_and_exit() { + if [ $? -ne 0 ]; then + echo $1 + exit 1 + fi +} + +check_if_loop_failed_and_exit() { + if [ $1 -ne 0 ]; then + echo $2 + exit 1 + fi +} + +# Add model to aws cli for new aws cloudwatch commands. It is not required after SDK is released +aws configure add-model --service-model file://slo/monitoring-2010-08-01.normal.json --service-name cloudwatch +check_if_step_failed_and_exit "There was an error adding the model to aws cli, exiting" + +# SLR could be created via console or API. So EnableTopologyDiscovery API is called to enroll topology discovery. +aws cloudwatch enable-topology-discovery --region $REGION +check_if_step_failed_and_exit "There was an error enabling topology discovery, exiting" + +# Pause for synthetics canaries to generate traffic +echo "Wait 10 minutes for canaries to generate traffic" +sleep 600 + +echo "Creating Service Level Objectives" + +# List services +end_time=$(date +%s) +end_time_as_int=$((end_time)) +# Start time is 24 hours ago +start_time_as_int=$((end_time-86400)) +LIST_SERVICES_REQUEST="slo/inputRequest/ListServices/listServices.json" +# Replace startTime and endTime in the request template with correct timestamps +LIST_SERVICES_REQUEST_WITH_CORRECT_INPUT=$(sed -e "s|\"StartTime\": .*|\"StartTime\": $start_time_as_int,|" -e "s|\"EndTime\": .*|\"EndTime\": $end_time_as_int|" "$LIST_SERVICES_REQUEST") + +# Get attribute reference id +REFERENCE_ID=$(aws cloudwatch list-services \ + --cli-input-json "$LIST_SERVICES_REQUEST_WITH_CORRECT_INPUT" \ + --output text --query "AttributeSets[?contains(Attributes[?Name=='EKS.Cluster'].Value, '$CLUSTER_NAME')].ReferenceId" \ + --region $REGION) +echo "Reference_Id" +echo "$REFERENCE_ID" + +# Use reference id to retrieve the service arn +SERVICE_ARN_THROUGH_ATTRIBUTES_SET=$(aws cloudwatch list-services \ + --cli-input-json "$LIST_SERVICES_REQUEST_WITH_CORRECT_INPUT" \ + --output text --query "ServiceSummaries[?AttributesReferenceId=='$REFERENCE_ID' && Name=='$SERVICE_NAME'].Id" \ + --region $REGION) + +echo SERVICE_ARN_THROUGH_ATTRIBUTES_SET +echo "$SERVICE_ARN_THROUGH_ATTRIBUTES_SET" + +SERVICE_ARN_THROUGH_ATTRIBUTES=$(aws cloudwatch list-services \ + --cli-input-json "$LIST_SERVICES_REQUEST_WITH_CORRECT_INPUT" \ + --output text --query "ServiceSummaries[?Name=='$SERVICE_NAME'].Id" \ + --region $REGION) + +echo SERVICE_ARN_THROUGH_ATTRIBUTES +echo "$SERVICE_ARN_THROUGH_ATTRIBUTES" + +if [ "$SERVICE_ARN_THROUGH_ATTRIBUTES_SET" = "" ]; then + SERVICE_ARN="$SERVICE_ARN_THROUGH_ATTRIBUTES" +else + SERVICE_ARN="$SERVICE_ARN_THROUGH_ATTRIBUTES_SET" +fi + +echo $SERVICE_ARN +if [ "$SERVICE_ARN" = "" ]; then + echo "The SERVICE_ARN should not be null, exiting" + exit 1 +fi + +# Create SLOs + +CREATE_SLO_REQUEST_1="slo/inputRequest/CreateServiceLevelObjective/getOwner99Availability.json" +# Update service arn in the request +CREATE_SLO_REQUEST_WITH_CORRECT_SERVICE_ARN_1=$(sed "s|\"ServiceId\": .*|\"ServiceId\": \"$SERVICE_ARN\",|" "$CREATE_SLO_REQUEST_1") +err=0 +for i in {1..5} +do + output=$(aws cloudwatch create-service-level-objective --cli-input-json "$CREATE_SLO_REQUEST_WITH_CORRECT_SERVICE_ARN_1" --no-cli-pager --region $REGION 2>&1) + err=$? + if echo "$output" | grep 'InvalidParameterValue'; then + echo "Error creating SLO. Retrying attempt: $i" + sleep 120 + continue + fi + break +done +check_if_loop_failed_and_exit $err "There was an error updating the service arn, exiting" +echo "$output" + +CREATE_SLO_REQUEST_2="slo/inputRequest/CreateServiceLevelObjective/getOwnerP99Latency.json" +# Update service arn in the request +CREATE_SLO_REQUEST_WITH_CORRECT_SERVICE_ARN_2=$(sed "s|\"ServiceId\": .*|\"ServiceId\": \"$SERVICE_ARN\",|" "$CREATE_SLO_REQUEST_2") +err=0 +for i in {1..5} +do + output=$(aws cloudwatch create-service-level-objective --cli-input-json "$CREATE_SLO_REQUEST_WITH_CORRECT_SERVICE_ARN_2" --no-cli-pager --region $REGION 2>&1) + err=$? + if echo "$output" | grep 'InvalidParameterValue'; then + echo "Error creating SLO. Retrying attempt: $i" + sleep 120 + continue + fi + break +done +check_if_loop_failed_and_exit $err "There was an error updating the service arn, exiting" +echo "$output" + +CREATE_SLO_REQUEST_3="slo/inputRequest/CreateServiceLevelObjective/postOwner99Availability.json" +# Update service arn in the request +CREATE_SLO_REQUEST_WITH_CORRECT_SERVICE_ARN_3=$(sed "s|\"ServiceId\": .*|\"ServiceId\": \"$SERVICE_ARN\",|" "$CREATE_SLO_REQUEST_3") +err=0 +for i in {1..5} +do + output=$(aws cloudwatch create-service-level-objective --cli-input-json "$CREATE_SLO_REQUEST_WITH_CORRECT_SERVICE_ARN_3" --no-cli-pager --region $REGION 2>&1) + err=$? + if echo "$output" | grep 'InvalidParameterValue'; then + echo "Error creating SLO. Retrying attempt: $i" + sleep 120 + continue + fi + break +done +check_if_loop_failed_and_exit $err "There was an error updating the service arn, exiting" +echo "$output" + +CREATE_SLO_REQUEST_4="slo/inputRequest/CreateServiceLevelObjective/postOwnerP99Latency.json" +# Update service arn in the request +CREATE_SLO_REQUEST_WITH_CORRECT_SERVICE_ARN_4=$(sed "s|\"ServiceId\": .*|\"ServiceId\": \"$SERVICE_ARN\",|" "$CREATE_SLO_REQUEST_4") +err=0 +for i in {1..5} +do + output=$(aws cloudwatch create-service-level-objective --cli-input-json "$CREATE_SLO_REQUEST_WITH_CORRECT_SERVICE_ARN_4" --no-cli-pager --region $REGION 2>&1) + err=$? + if echo "$output" | grep 'InvalidParameterValue'; then + echo "Error creating SLO. Retrying attempt: $i" + sleep 120 + continue + fi + break +done +check_if_loop_failed_and_exit $err "There was an error updating the service arn, exiting" +echo "$output" diff --git a/scripts/eks/appsignals/deploy-sample-app.sh b/scripts/eks/appsignals/deploy-sample-app.sh new file mode 100755 index 0000000..525cd88 --- /dev/null +++ b/scripts/eks/appsignals/deploy-sample-app.sh @@ -0,0 +1,71 @@ +#!/bin/bash +# set -x + +# change the directory to the script location so that the relative path can work +cd "$(dirname "$0")" + +# Set variables with provided arguments or default values +CLUSTER_NAME=$1 +REGION=$2 +NAMESPACE=${3:-default} +OPERATION=${4:-"apply"} + +# Check if the current context points to the new cluster in the correct region +kub_config=$(kubectl config current-context) +if [[ $kub_config != *"$CLUSTER_NAME"* ]] || [[ $kub_config != *"$REGION"* ]]; then + echo "Your current cluster context is not set to $CLUSTER_NAME $REGION. Please switch to the correct context first before running this script" + exit 1 +fi + +err=0 +trap 'err=1' ERR +if [[ $OPERATION == "apply" ]]; then + echo "Creating ServiceAccount" + eksctl create iamserviceaccount \ + --name visits-service-account \ + --namespace ${NAMESPACE} \ + --cluster ${CLUSTER_NAME} \ + --region ${REGION} \ + --attach-policy-arn arn:aws:iam::aws:policy/AmazonSQSFullAccess \ + --attach-policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess \ + --attach-policy-arn arn:aws:iam::aws:policy/AmazonKinesisFullAccess \ + --attach-policy-arn arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess \ + --approve \ + --override-existing-serviceaccounts +else + echo "Deleting ServiceAccount" + eksctl delete iamserviceaccount \ + --name visits-service-account \ + --namespace ${NAMESPACE} \ + --cluster ${CLUSTER_NAME} \ + --region ${REGION} +fi + +ACCOUNT=$(aws sts get-caller-identity | jq -r '.Account') + +for config in $(ls ./sample-app/*.yaml) +do + sed "s/111122223333.dkr.ecr.us-west-2/$ACCOUNT.dkr.ecr.$REGION/g" $config | kubectl ${OPERATION} --namespace=$NAMESPACE -f - +done + +if [[ $OPERATION == "apply" ]]; then + # Apply k8s nginx configuration + kubectl apply -f ./sample-app/k8s-nginx-ingress/namespace.yaml + kubectl apply -f ./sample-app/k8s-nginx-ingress/ + + # Wait a few seconds for services to start + sleep 30 + + # Save the endpoint URL to a variable + endpoint=$(kubectl get svc -n ingress-nginx | grep "ingress-nginx" | awk '{print $4}') + + # Print the endpoint + echo "Visit the following URL to see the sample app running: $endpoint" + + # Replace the old endpoint in the jmx file + sed '/PETCLINC_HOST<\/stringProp>/{n;s|.*|'${endpoint}'|;}' ./sample-app/test/petclinic_test_plan.jmx > tmp.jmx + mv tmp.jmx ./sample-app/test/petclinic_test_plan.jmx +else + kubectl delete -f ./sample-app/k8s-nginx-ingress/ +fi +exit $err diff --git a/scripts/eks/appsignals/enable-app-signals.sh b/scripts/eks/appsignals/enable-app-signals.sh new file mode 100755 index 0000000..288b726 --- /dev/null +++ b/scripts/eks/appsignals/enable-app-signals.sh @@ -0,0 +1,124 @@ +#!/usr/bin/env bash + +cd "$(dirname "$0")" + +CLUSTER_NAME=$1 +REGION=$2 +NAMESPACE=${3:-default} +echo "Enabling Application Signals for EKS Cluster ${CLUSTER_NAME} in ${REGION} for namespace ${NAMESPACE}" + +# Check if the current context points to the new cluster in the correct region +kub_config=$(kubectl config current-context) +if [[ $kub_config != *"$CLUSTER_NAME"* ]] || [[ $kub_config != *"$REGION"* ]]; then + echo "Your current cluster context is not set to $CLUSTER_NAME $REGION. Please switch to the correct context first before running this script" + exit 1 +fi + +check_if_step_failed_and_exit() { + if [ $? -ne 0 ]; then + echo $1 + exit 1 + fi +} + +check_if_loop_failed_and_exit() { + if [ $1 -ne 0 ]; then + echo $2 + exit 1 + fi +} + +# Create service linked role in the account +aws iam create-service-linked-role --aws-service-name application-signals.cloudwatch.amazonaws.com + +# Enable OIDC to allow IAM role authN/Z with service account +eksctl utils associate-iam-oidc-provider --cluster ${CLUSTER_NAME} --region ${REGION} --approve +check_if_step_failed_and_exit "There was an error enabling the OIDC, exiting" + +# Create Service Account with the proper IAM permissions +echo "Creating ServiceAccount" +eksctl create iamserviceaccount \ + --name cloudwatch-agent \ + --namespace amazon-cloudwatch \ + --cluster ${CLUSTER_NAME} \ + --region ${REGION} \ + --attach-policy-arn arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess \ + --attach-policy-arn arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy \ + --approve \ + --override-existing-serviceaccounts +check_if_step_failed_and_exit "There was an error creating the ServiceAccount, exiting" + + +# Install amazon-cloudwatch-observability addon +echo "Checking amazon-cloudwatch-observability add-on" +result=$(aws eks describe-addon --addon-name amazon-cloudwatch-observability --cluster-name ${CLUSTER_NAME} --region ${REGION} 2>&1) +echo "${result}" + +if [[ "${result}" == *"No addon: "* ]]; then + echo "Installing amazon-cloudwatch-observability add-on" + aws eks create-addon \ + --cluster-name ${CLUSTER_NAME} \ + --addon-name amazon-cloudwatch-observability \ + --addon-version v1.2.0-eksbuild.1 \ + --region ${REGION} + # wait until the amazon-cloudwatch-observability add-on is active + # Fetch the initial status + status=$(aws eks describe-addon --cluster-name ${CLUSTER_NAME} --addon-name amazon-cloudwatch-observability --region ${REGION} | grep '"status":' | awk -F '"' '{print $4}') + + # Loop until status becomes "ACTIVE" + while [[ "$status" != "ACTIVE" ]]; do + echo "Current status: $status" + if [[ "$status" == "CREATE_FAILED" ]]; then + echo "Create amazon-cloudwatch-observability add-on failed!" + exit 1 + fi + echo "Waiting for addon to become ACTIVE..." + sleep 20 # wait for 20 seconds before checking again + status=$(aws eks describe-addon --cluster-name ${CLUSTER_NAME} --addon-name amazon-cloudwatch-observability --region ${REGION} | grep '"status":' | awk -F '"' '{print $4}') + done + + echo "EKS amazon-cloudwatch-observability add-on is now ACTIVE" +else + addon_version=$(echo "${result}" | grep "addonVersion" | awk -F '"' '{print $4}') + if [[ "$addon_version" < "v1.2.0" ]]; then + read -p "Do you want to update the add-on version to v1.2.0, current version $addon_version? (yes/no): " choice + + if [ "$choice" == "yes" ]; then + aws eks update-addon \ + --cluster-name ${CLUSTER_NAME} \ + --addon-name amazon-cloudwatch-observability \ + --addon-version v1.2.0-eksbuild.1 \ + --region ${REGION} + # wait until the amazon-cloudwatch-observability add-on is active + echo "Waiting for addon to become ACTIVE..." + sleep 5 + status=$(aws eks describe-addon --cluster-name ${CLUSTER_NAME} --addon-name amazon-cloudwatch-observability --region ${REGION} | grep '"status":' | awk -F '"' '{print $4}') + + # Loop until status becomes "ACTIVE" + while [[ "$status" != "ACTIVE" ]]; do + echo "Current status: $status" + if [[ "$status" == "UPDATE_FAILED" ]]; then + echo "Update amazon-cloudwatch-observability add-on failed!" + exit 1 + fi + echo "Waiting for addon to become ACTIVE..." + sleep 20 # wait for 20 seconds before checking again + status=$(aws eks describe-addon --cluster-name ${CLUSTER_NAME} --addon-name amazon-cloudwatch-observability --region ${REGION} | grep '"status":' | awk -F '"' '{print $4}') + done + + echo "EKS amazon-cloudwatch-observability add-on is now ACTIVE" + else + echo "Aborted upgrading EKS amazon-cloudwatch-observability add-on." + fi + else + echo "EKS amazon-cloudwatch-observability add-on has been installed" + fi +fi + +if [ -z "${REGION}" ] +then + echo "Region set to us-west-2" + REGION="us-west-2" +fi + +check_if_step_failed_and_exit "There was an error enabling application signals, exiting" diff --git a/scripts/eks/appsignals/one-step/cleanup.sh b/scripts/eks/appsignals/one-step/cleanup.sh new file mode 100755 index 0000000..8b87ee2 --- /dev/null +++ b/scripts/eks/appsignals/one-step/cleanup.sh @@ -0,0 +1,68 @@ +#!/bin/bash +# set -x + +# change the directory to the script location so that the relative path can work +cd "$(dirname "$0")" + +# Set variables with provided arguments +CLUSTER_NAME=$1 +REGION=$2 +NAMESPACE=${3:-default} + +# Get the kubectl config in JSON format +kubectl_config=$(kubectl config view --output=json) + +# Extract the context with the specified cluster name and region +desired_context=$(echo "$kubectl_config" | jq -r --arg CLUSTER_NAME "$CLUSTER_NAME" --arg REGION "$REGION" '.contexts[] | select(.name | contains($CLUSTER_NAME) and contains($REGION))') + +# Check if the desired context exists +if [ -n "$desired_context" ]; then + context_name=$(echo "$desired_context" | jq -r '.name') + echo "Setting current context to: $context_name" + kubectl config use-context "$context_name" +else + echo "Desired context not found. Exit the script" + exit 1 +fi + +check_if_step_failed_and_exit() { + if [ $? -ne 0 ]; then + echo $1 + exit 1 + fi +} + +check_if_step_failed() { + if [ $? -ne 0 ]; then + echo $1 + fi +} + +echo "Deleting SLO" +../cleanup-slo.sh $REGION +check_if_step_failed_and_exit "There was an error deleting the SLOs. Please make sure they are deleted properly before proceeding with the following steps" + +echo "Deleting canaries" +../create-canaries.sh $REGION delete +check_if_step_failed_and_exit "There was an error deleting the canaries. Please make sure they are deleted properly before proceeding with the following steps" + +../deploy-sample-app.sh $CLUSTER_NAME $REGION $NAMESPACE delete +check_if_step_failed_and_exit "There was an error deleting the sample apps. Please make sure they are deleted properly before proceeding with the following steps" + +eksctl delete cluster --name $CLUSTER_NAME --region $REGION +check_if_step_failed "There was an error deleting the cluster $CLUSTER_NAME." + +aws logs delete-log-group --log-group-name '/aws/appsignals/eks' --region $REGION +check_if_step_failed "There was an error deleting the log group /aws/appsignals/eks." + +# remove the sqs queue +aws sqs delete-queue --region $REGION --queue-url $(aws sqs get-queue-url --region $REGION --queue-name apm_test --query 'QueueUrl' --output text) +check_if_step_failed "There was an error deleting the sqs." + +# delete the kinesis stream +aws kinesis delete-stream --stream-name apm_test --region $REGION +check_if_step_failed "There was an error deleting the kinesis stream." + +# remove DDB table +aws dynamodb delete-table --table-name apm_test --region $REGION +check_if_step_failed "There was an error deleting the dynamodb table." diff --git a/scripts/eks/appsignals/one-step/setup.sh b/scripts/eks/appsignals/one-step/setup.sh new file mode 100755 index 0000000..b462b02 --- /dev/null +++ b/scripts/eks/appsignals/one-step/setup.sh @@ -0,0 +1,66 @@ +#!/bin/bash +# set -x + +# change the directory to the script location so that the relative path can work +cd "$(dirname "$0")" + +# check aws cli version to make sure it's recent enough +# Get the AWS CLI version +version=$(aws --version 2>&1 | cut -d/ -f2 | cut -d' ' -f1) + +# Use sort -V (version sort) to compare the version numbers +min_version="2.13.0" +if [[ $(echo -e "$min_version\n$version" | sort -V | head -n1) == "$version" && "$min_version" != "$version" ]]; then + echo "Your AWS CLI version is lower than 2.13.0. Please upgrade your AWS CLI version: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html" + exit 1 +fi + +# Continue with the rest of your script here +echo "AWS CLI version is acceptable, continuing..." + +# Set variables with provided arguments or default values +CLUSTER_NAME=$1 +REGION=$2 +NAMESPACE=${3:-default} + +check_if_step_failed_and_exit() { + if [ $? -ne 0 ]; then + echo $1 + exit 1 + fi +} + +# create cluster +../create-cluster.sh $CLUSTER_NAME $REGION +check_if_step_failed_and_exit "There was an error creating cluster $CLUSTER_NAME in region $REGION, exiting" + +# enable application signals auto-instrumentation +../enable-app-signals.sh $CLUSTER_NAME $REGION $NAMESPACE +check_if_step_failed_and_exit "There was an error enabling app signals with namespace $NAMESPACE, exiting" + +# deploy sample application +../deploy-sample-app.sh $CLUSTER_NAME $REGION $NAMESPACE +check_if_step_failed_and_exit "There was an error deploying the sample app, exiting" + +# create canaries +../create-canaries.sh $REGION +check_if_step_failed_and_exit "There was an error creating the canaries, exiting" + +# create slo +../create-slo.sh $CLUSTER_NAME $REGION +check_if_step_failed_and_exit "There was an error creating the SLOs, exiting" + +# Check if the current context points to the new cluster in the correct region +kub_config=$(kubectl config current-context) +if [[ $kub_config != *"$CLUSTER_NAME"* ]] || [[ $kub_config != *"$REGION"* ]]; then + echo "Your current cluster context is not set to $CLUSTER_NAME in $REGION. To get the endpoint of the sample app update your context then run + kubectl get svc -n ingress-nginx | grep \"ingress-nginx\" | awk '{print \$4}'" + exit 1 +fi + + +# Save the endpoint URL to a variable +endpoint=$(kubectl get svc -n ingress-nginx | grep "ingress-nginx" | awk '{print $4}') + +# Print the endpoint +echo "Visit the following URL to see the sample app running: $endpoint" diff --git a/scripts/eks/appsignals/sample-app/admin-server-deployment.yaml b/scripts/eks/appsignals/sample-app/admin-server-deployment.yaml new file mode 100644 index 0000000..f736fd5 --- /dev/null +++ b/scripts/eks/appsignals/sample-app/admin-server-deployment.yaml @@ -0,0 +1,42 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: admin-server + name: admin-server +spec: + replicas: 1 + selector: + matchLabels: + io.kompose.service: admin-server + strategy: {} + template: + metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: admin-server + spec: + containers: + - command: + - ./dockerize + - -wait=tcp://discovery-server:8761 + - -timeout=60s + - -- + - java + - org.springframework.boot.loader.JarLauncher + image: 111122223333.dkr.ecr.us-west-2.amazonaws.com/springcommunity/spring-petclinic-admin-server:latest + securityContext: + runAsNonRoot: true + allowPrivilegeEscalation: false + name: admin-server + ports: + - containerPort: 9090 + restartPolicy: Always +status: {} diff --git a/scripts/eks/appsignals/sample-app/admin-server-service.yaml b/scripts/eks/appsignals/sample-app/admin-server-service.yaml new file mode 100644 index 0000000..89fadda --- /dev/null +++ b/scripts/eks/appsignals/sample-app/admin-server-service.yaml @@ -0,0 +1,19 @@ +apiVersion: v1 +kind: Service +metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: admin-server + name: admin-server +spec: + ports: + - name: "9090" + port: 9090 + targetPort: 9090 + selector: + io.kompose.service: admin-server +status: + loadBalancer: {} diff --git a/scripts/eks/appsignals/sample-app/api-gateway-deployment.yaml b/scripts/eks/appsignals/sample-app/api-gateway-deployment.yaml new file mode 100644 index 0000000..a73ac21 --- /dev/null +++ b/scripts/eks/appsignals/sample-app/api-gateway-deployment.yaml @@ -0,0 +1,45 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: pet-clinic-frontend + name: pet-clinic-frontend +spec: + replicas: 2 + selector: + matchLabels: + io.kompose.service: pet-clinic-frontend + strategy: {} + template: + metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: pet-clinic-frontend + annotations: + sidecar.opentelemetry.io/inject-java: "true" + instrumentation.opentelemetry.io/inject-java: "true" + spec: + containers: + - command: + - ./dockerize + - -wait=tcp://discovery-server:8761 + - -timeout=60s + - -- + - java + - org.springframework.boot.loader.JarLauncher + image: 111122223333.dkr.ecr.us-west-2.amazonaws.com/springcommunity/spring-petclinic-api-gateway:latest + securityContext: + runAsNonRoot: true + allowPrivilegeEscalation: false + name: api-gateway + ports: + - containerPort: 8080 + restartPolicy: Always +status: {} diff --git a/scripts/eks/appsignals/sample-app/api-gateway-service.yaml b/scripts/eks/appsignals/sample-app/api-gateway-service.yaml new file mode 100644 index 0000000..57fafe5 --- /dev/null +++ b/scripts/eks/appsignals/sample-app/api-gateway-service.yaml @@ -0,0 +1,19 @@ +apiVersion: v1 +kind: Service +metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: pet-clinic-frontend + name: pet-clinic-frontend +spec: + ports: + - name: "8080" + port: 8080 + targetPort: 8080 + selector: + io.kompose.service: pet-clinic-frontend +status: + loadBalancer: {} diff --git a/scripts/eks/appsignals/sample-app/config-server-deployment.yaml b/scripts/eks/appsignals/sample-app/config-server-deployment.yaml new file mode 100644 index 0000000..0561957 --- /dev/null +++ b/scripts/eks/appsignals/sample-app/config-server-deployment.yaml @@ -0,0 +1,35 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: config-server + name: config-server +spec: + replicas: 1 + selector: + matchLabels: + io.kompose.service: config-server + strategy: {} + template: + metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: config-server + spec: + containers: + - image: 111122223333.dkr.ecr.us-west-2.amazonaws.com/springcommunity/spring-petclinic-config-server:latest + securityContext: + runAsNonRoot: true + allowPrivilegeEscalation: false + name: config-server + ports: + - containerPort: 8888 + restartPolicy: Always +status: {} diff --git a/scripts/eks/appsignals/sample-app/config-server-service.yaml b/scripts/eks/appsignals/sample-app/config-server-service.yaml new file mode 100644 index 0000000..4154248 --- /dev/null +++ b/scripts/eks/appsignals/sample-app/config-server-service.yaml @@ -0,0 +1,19 @@ +apiVersion: v1 +kind: Service +metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: config-server + name: config-server +spec: + ports: + - name: "8888" + port: 8888 + targetPort: 8888 + selector: + io.kompose.service: config-server +status: + loadBalancer: {} diff --git a/scripts/eks/appsignals/sample-app/customers-service-deployment.yaml b/scripts/eks/appsignals/sample-app/customers-service-deployment.yaml new file mode 100644 index 0000000..f0c5838 --- /dev/null +++ b/scripts/eks/appsignals/sample-app/customers-service-deployment.yaml @@ -0,0 +1,46 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: customers-service + name: customers-service +spec: + replicas: 2 + selector: + matchLabels: + io.kompose.service: customers-service + strategy: {} + template: + metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: customers-service + annotations: + sidecar.opentelemetry.io/inject-java: "true" + instrumentation.opentelemetry.io/inject-java: "true" + spec: + serviceAccountName: visits-service-account + containers: + - command: + - ./dockerize + - -wait=tcp://discovery-server:8761 + - -timeout=60s + - -- + - java + - org.springframework.boot.loader.JarLauncher + image: 111122223333.dkr.ecr.us-west-2.amazonaws.com/springcommunity/spring-petclinic-customers-service:latest + securityContext: + runAsNonRoot: true + allowPrivilegeEscalation: false + name: customers-service + ports: + - containerPort: 8081 + restartPolicy: Always +status: {} diff --git a/scripts/eks/appsignals/sample-app/customers-service-service.yaml b/scripts/eks/appsignals/sample-app/customers-service-service.yaml new file mode 100644 index 0000000..949bcc8 --- /dev/null +++ b/scripts/eks/appsignals/sample-app/customers-service-service.yaml @@ -0,0 +1,19 @@ +apiVersion: v1 +kind: Service +metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: customers-service + name: customers-service +spec: + ports: + - name: "8081" + port: 8081 + targetPort: 8081 + selector: + io.kompose.service: customers-service +status: + loadBalancer: {} diff --git a/scripts/eks/appsignals/sample-app/discovery-server-deployment.yaml b/scripts/eks/appsignals/sample-app/discovery-server-deployment.yaml new file mode 100644 index 0000000..64b1df5 --- /dev/null +++ b/scripts/eks/appsignals/sample-app/discovery-server-deployment.yaml @@ -0,0 +1,42 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: discovery-server + name: discovery-server +spec: + replicas: 1 + selector: + matchLabels: + io.kompose.service: discovery-server + strategy: {} + template: + metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: discovery-server + spec: + containers: + - command: + - ./dockerize + - -wait=tcp://config-server:8888 + - -timeout=60s + - -- + - java + - org.springframework.boot.loader.JarLauncher + image: 111122223333.dkr.ecr.us-west-2.amazonaws.com/springcommunity/spring-petclinic-discovery-server:latest + securityContext: + runAsNonRoot: true + allowPrivilegeEscalation: false + name: discovery-server + ports: + - containerPort: 8761 + restartPolicy: Always +status: {} diff --git a/scripts/eks/appsignals/sample-app/discovery-server-service.yaml b/scripts/eks/appsignals/sample-app/discovery-server-service.yaml new file mode 100644 index 0000000..cc7cbbc --- /dev/null +++ b/scripts/eks/appsignals/sample-app/discovery-server-service.yaml @@ -0,0 +1,19 @@ +apiVersion: v1 +kind: Service +metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: discovery-server + name: discovery-server +spec: + ports: + - name: "8761" + port: 8761 + targetPort: 8761 + selector: + io.kompose.service: discovery-server +status: + loadBalancer: {} diff --git a/scripts/eks/appsignals/sample-app/k8s-nginx-ingress/namespace.yaml b/scripts/eks/appsignals/sample-app/k8s-nginx-ingress/namespace.yaml new file mode 100644 index 0000000..bc9ce85 --- /dev/null +++ b/scripts/eks/appsignals/sample-app/k8s-nginx-ingress/namespace.yaml @@ -0,0 +1,4 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: ingress-nginx \ No newline at end of file diff --git a/scripts/eks/appsignals/sample-app/k8s-nginx-ingress/nginx-alb.yaml b/scripts/eks/appsignals/sample-app/k8s-nginx-ingress/nginx-alb.yaml new file mode 100644 index 0000000..c8a36a1 --- /dev/null +++ b/scripts/eks/appsignals/sample-app/k8s-nginx-ingress/nginx-alb.yaml @@ -0,0 +1,27 @@ +apiVersion: v1 +kind: Service +metadata: + name: ingress-nginx + namespace: ingress-nginx + annotations: + prometheus.io/port: '9113' + prometheus.io/scrape: 'true' + prometheus.io/scheme: http +spec: + type: LoadBalancer + ports: + - name: http + port: 80 + targetPort: 80 + nodePort: 32080 + protocol: TCP + - name: https + port: 443 + targetPort: 443 + nodePort: 32081 + protocol: TCP + - name: prometheus + port: 9113 + targetPort: 9113 + selector: + app: ingress-nginx diff --git a/scripts/eks/appsignals/sample-app/k8s-nginx-ingress/nginx-ingress.yaml b/scripts/eks/appsignals/sample-app/k8s-nginx-ingress/nginx-ingress.yaml new file mode 100644 index 0000000..15ab6bf --- /dev/null +++ b/scripts/eks/appsignals/sample-app/k8s-nginx-ingress/nginx-ingress.yaml @@ -0,0 +1,346 @@ +--- + +apiVersion: apps/v1 +kind: Deployment +metadata: + name: default-http-backend + labels: + app: default-http-backend + namespace: ingress-nginx +spec: + replicas: 1 + selector: + matchLabels: + app: default-http-backend + template: + metadata: + labels: + app: default-http-backend + spec: + terminationGracePeriodSeconds: 60 + containers: + - name: default-http-backend + # Any image is permissible as long as: + # 1. It serves a 404 page at / + # 2. It serves 200 on a /healthz endpoint + image: gcr.io/google_containers/defaultbackend:1.4 + livenessProbe: + httpGet: + path: /healthz + port: 8080 + scheme: HTTP + initialDelaySeconds: 30 + timeoutSeconds: 5 + ports: + - containerPort: 8080 + resources: + limits: + cpu: 10m + memory: 20Mi + requests: + cpu: 10m + memory: 20Mi +--- + +apiVersion: v1 +kind: Service +metadata: + name: default-http-backend + namespace: ingress-nginx + labels: + app: default-http-backend +spec: + ports: + - port: 80 + targetPort: 8080 + selector: + app: default-http-backend +--- + +kind: ConfigMap +apiVersion: v1 +metadata: + name: nginx-configuration + namespace: ingress-nginx + labels: + app: ingress-nginx +data: + allow-snippet-annotations: "true" + enable-opentelemetry: "true" + opentelemetry-operation-name: HTTP $request_method $service_name + opentelemetry-trust-incoming-span: "true" + otel-sampler: AlwaysOn + otel-sampler-parent-based: "true" + otel-sampler-ratio: "1.0" + otel-service-name: nginx-proxy + otlp-collector-host: "cloudwatch-agent.amazon-cloudwatch" + otlp-collector-port: "4315" +--- + +kind: ConfigMap +apiVersion: v1 +metadata: + name: tcp-services + namespace: ingress-nginx +--- + +kind: ConfigMap +apiVersion: v1 +metadata: + name: udp-services + namespace: ingress-nginx +--- + +apiVersion: v1 +kind: ServiceAccount +metadata: + name: nginx-ingress-serviceaccount + namespace: ingress-nginx + +--- + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: nginx-ingress-clusterrole +rules: + - apiGroups: + - "" + resources: + - configmaps + - endpoints + - nodes + - pods + - secrets + verbs: + - list + - watch + - update + - apiGroups: + - "" + resources: + - nodes + verbs: + - get + - apiGroups: + - "" + resources: + - services + verbs: + - get + - list + - watch + - apiGroups: + - "networking.k8s.io" + - "extensions" + resources: + - ingresses + verbs: + - get + - list + - watch + - apiGroups: + - "" + resources: + - events + verbs: + - create + - patch + - apiGroups: + - "networking.k8s.io" + - "extensions" + resources: + - ingresses/status + verbs: + - update + - apiGroups: + - "discovery.k8s.io" + resources: + - "endpointslices" + verbs: + - list + - watch + - apiGroups: + - "coordination.k8s.io" + resources: + - "leases" + verbs: + - get + - list + - create + - update + +--- + +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: nginx-ingress-role + namespace: ingress-nginx +rules: + - apiGroups: + - "" + resources: + - configmaps + - pods + - secrets + - namespaces + verbs: + - get + - apiGroups: + - "" + resources: + - configmaps + resourceNames: + # Defaults to "-" + # Here: "-" + # This has to be adapted if you change either parameter + # when launching the nginx-ingress-controller. + - "ingress-controller-leader-nginx" + - "ingress-controller-leader" + verbs: + - get + - update + - apiGroups: + - "" + resources: + - configmaps + verbs: + - create + - apiGroups: + - "" + resources: + - endpoints + verbs: + - get + +--- + +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: nginx-ingress-role-nisa-binding + namespace: ingress-nginx +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: nginx-ingress-role +subjects: + - kind: ServiceAccount + name: nginx-ingress-serviceaccount + namespace: ingress-nginx + +--- + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: nginx-ingress-clusterrole-nisa-binding +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: nginx-ingress-clusterrole +subjects: + - kind: ServiceAccount + name: nginx-ingress-serviceaccount + namespace: ingress-nginx +--- + +apiVersion: apps/v1 +kind: Deployment +metadata: + name: nginx-ingress-controller + namespace: ingress-nginx + annotations: + prometheus.io/port: '9113' + prometheus.io/scrape: 'true' +spec: + replicas: 1 + selector: + matchLabels: + app: ingress-nginx + template: + metadata: + labels: + app: ingress-nginx + annotations: + prometheus.io/port: '9113' + prometheus.io/scrape: 'true' + prometheus.io/scheme: http + spec: + serviceAccountName: nginx-ingress-serviceaccount + containers: + - name: nginx-ingress-controller + image: registry.k8s.io/ingress-nginx/controller:v1.9.4 + args: + - /nginx-ingress-controller + - --default-backend-service=$(POD_NAMESPACE)/default-http-backend + - --configmap=$(POD_NAMESPACE)/nginx-configuration + - --tcp-services-configmap=$(POD_NAMESPACE)/tcp-services + - --udp-services-configmap=$(POD_NAMESPACE)/udp-services + - --publish-service=$(POD_NAMESPACE)/ingress-nginx + - --annotations-prefix=nginx.ingress.kubernetes.io + securityContext: + capabilities: + drop: + - ALL + add: + - NET_BIND_SERVICE + runAsUser: 101 + env: + - name: POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: LD_PRELOAD + value: /usr/local/lib/libmimalloc.so + ports: + - name: http + containerPort: 80 + - name: https + containerPort: 443 + - containerPort: 8443 + name: webhook + protocol: TCP + - name: prometheus + containerPort: 9113 + livenessProbe: + failureThreshold: 3 + httpGet: + path: /healthz + port: 10254 + scheme: HTTP + initialDelaySeconds: 10 + periodSeconds: 10 + successThreshold: 1 + timeoutSeconds: 1 + readinessProbe: + failureThreshold: 3 + httpGet: + path: /healthz + port: 10254 + scheme: HTTP + periodSeconds: 10 + successThreshold: 1 + timeoutSeconds: 1 + volumeMounts: + - mountPath: /modules_mount + name: modules + initContainers: + - command: + - /init_module + image: registry.k8s.io/ingress-nginx/opentelemetry:v20230721-3e2062ee5 + imagePullPolicy: IfNotPresent + name: opentelemetry + securityContext: + allowPrivilegeEscalation: false + volumeMounts: + - mountPath: /modules_mount + name: modules + volumes: + - emptyDir: {} + name: modules diff --git a/scripts/eks/appsignals/sample-app/k8s-nginx-ingress/petclinc-nginx-ingress.yaml b/scripts/eks/appsignals/sample-app/k8s-nginx-ingress/petclinc-nginx-ingress.yaml new file mode 100644 index 0000000..23ddc0f --- /dev/null +++ b/scripts/eks/appsignals/sample-app/k8s-nginx-ingress/petclinc-nginx-ingress.yaml @@ -0,0 +1,40 @@ +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: petclinic-nginx-ingress + annotations: + kubernetes.io/ingress.class: nginx + nginx.ingress.kubernetes.io/ssl-redirect: "false" + nginx.ingress.kubernetes.io/enable-opentelemetry: "true" +spec: + rules: + - http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: pet-clinic-frontend + port: + number: 8080 + - path: / + pathType: Prefix + backend: + service: + name: customers-service + port: + number: 8081 + - path: / + pathType: Prefix + backend: + service: + name: vets-service + port: + number: 8083 + - path: / + pathType: Prefix + backend: + service: + name: visits-service + port: + number: 8082 diff --git a/scripts/eks/appsignals/sample-app/test/petclinic_test_plan.jmx b/scripts/eks/appsignals/sample-app/test/petclinic_test_plan.jmx new file mode 100644 index 0000000..8674ad1 --- /dev/null +++ b/scripts/eks/appsignals/sample-app/test/petclinic_test_plan.jmx @@ -0,0 +1,568 @@ + + + + + + false + true + false + + + + PETCLINC_HOST + k8s-ingressn-ingressn-193e15626c-4c39ac279c55df38.elb.us-west-2.amazonaws.com + = + + + PETCLINIC_PORT + 80 + = + + + + + + + + + + + ${PETCLINC_HOST} + ${PETCLINIC_PORT} + + + + 6 + + + + + + + + Accept + application/json, text/plain, */* + + + Content-Type + application/json;charset=UTF-8 + + + Accept-Encoding + gzip, deflate, br + + + + + + + + 1 + 0 + 0 + 300 + 30 + + + + false + -1 + + continue + + + + PET_TYPE + + 1 + 6 + + false + + + + 300 + 100.0 + + + + + + + + + + + /api/customer/owners + GET + true + false + true + false + + + + + + + + 200 + + + Assertion.response_code + false + 8 + + + + + true + + + + false + { + "firstName":"Firstname", + "lastName":"Lastname", + "address":"Adress", + "city":"City", + "telephone":"0000000000" +} + = + + + + + + + + /api/customer/owners + POST + true + false + true + false + + + + + + + + 201 + + + Assertion.response_code + false + 8 + + + + OWNER_ID + $.id + + + + + + + + + + + + + /api/gateway/owners/1 + GET + true + false + true + false + + + + + + + + 200 + + + Assertion.response_code + false + 8 + + + + + true + + + + false + { + "id":"${OWNER_ID}", + "firstName":"Firstname", + "lastName":"Lastname${OWNER_ID}", + "address":"Adress${OWNER_ID}", + "city":"City${OWNER_ID}", + "telephone":"1111111111" +} + = + + + + + + + + /api/customer/owners/1 + PUT + true + false + true + false + + + + + + + + 204 + + + Assertion.response_code + false + 8 + + + + + true + + + + false + { + "name":"Pet", + "birthDate":"2018-12-31T23:00:00.000Z", + "typeId":"${PET_TYPE}" +} + = + + + + + + + + /api/customer/owners/1/pets + POST + true + false + true + false + + + + + + + + 201 + + + Assertion.response_code + false + 8 + + + + PET_ID + $.id + + + + + + 1 + + + + true + + + + false + { + "name":"Pet", + "birthDate":"2018-12-31T23:00:00.000Z", + "typeId":"${PET_TYPE}" +} + = + + + + + + + + /api/customer/owners/1/pets + POST + true + false + true + false + + + + + + + + 201 + + + Assertion.response_code + false + 8 + + + + + + true + + + + false + { + "id": ${PET_ID}, + "name":"Pet${OWNER_ID}", + "birthDate":"2018-12-31T23:00:00.000Z", + "typeId":"${PET_TYPE}" +} + = + + + + + + + + /api/customer/owners/1/pets/1 + PUT + true + false + true + false + + + + + + + + 204 + + + Assertion.response_code + false + 8 + + + + + true + + + + false + { + "date":"2019-03-15", + "description":"Visit" +} + = + + + + + + + + /api/visit/owners/1/pets/1/visits + POST + true + false + true + false + + + + + + + + 201 + + + Assertion.response_code + false + 8 + + + + + 1 + + + + true + + + + false + { + "date":"2019-03-15", + "description":"Visit" +} + = + + + + + + + + /api/visit/owners/1/pets/1/visits + POST + true + false + true + false + + + + + + + + 201 + + + Assertion.response_code + false + 8 + + + + + + + + + + + + + /api/vet/vets + GET + true + false + true + false + + + + + + + + 200 + + + Assertion.response_code + false + 8 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + true + false + false + false + true + 0 + true + true + true + true + true + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + true + false + false + false + true + 0 + true + true + true + true + true + true + + + + + + + + + diff --git a/scripts/eks/appsignals/sample-app/vets-service-deployment.yaml b/scripts/eks/appsignals/sample-app/vets-service-deployment.yaml new file mode 100644 index 0000000..53d4791 --- /dev/null +++ b/scripts/eks/appsignals/sample-app/vets-service-deployment.yaml @@ -0,0 +1,46 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: vets-service + name: vets-service +spec: + replicas: 1 + selector: + matchLabels: + io.kompose.service: vets-service + strategy: {} + template: + metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: vets-service + annotations: + sidecar.opentelemetry.io/inject-java: "true" + instrumentation.opentelemetry.io/inject-java: "true" + spec: + serviceAccountName: visits-service-account + containers: + - command: + - ./dockerize + - -wait=tcp://discovery-server:8761 + - -timeout=60s + - -- + - java + - org.springframework.boot.loader.JarLauncher + image: 111122223333.dkr.ecr.us-west-2.amazonaws.com/springcommunity/spring-petclinic-vets-service:latest + securityContext: + runAsNonRoot: true + allowPrivilegeEscalation: false + name: vets-service + ports: + - containerPort: 8083 + restartPolicy: Always +status: {} diff --git a/scripts/eks/appsignals/sample-app/vets-service-service.yaml b/scripts/eks/appsignals/sample-app/vets-service-service.yaml new file mode 100644 index 0000000..c810bc8 --- /dev/null +++ b/scripts/eks/appsignals/sample-app/vets-service-service.yaml @@ -0,0 +1,19 @@ +apiVersion: v1 +kind: Service +metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: vets-service + name: vets-service +spec: + ports: + - name: "8083" + port: 8083 + targetPort: 8083 + selector: + io.kompose.service: vets-service +status: + loadBalancer: {} diff --git a/scripts/eks/appsignals/sample-app/visits-service-deployment.yaml b/scripts/eks/appsignals/sample-app/visits-service-deployment.yaml new file mode 100644 index 0000000..47d0804 --- /dev/null +++ b/scripts/eks/appsignals/sample-app/visits-service-deployment.yaml @@ -0,0 +1,49 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: visits-service + name: visits-service +spec: + replicas: 3 + selector: + matchLabels: + io.kompose.service: visits-service + strategy: {} + template: + metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: visits-service + annotations: + sidecar.opentelemetry.io/inject-java: "true" + instrumentation.opentelemetry.io/inject-java: "true" + spec: + serviceAccountName: visits-service-account + containers: + - command: + - ./dockerize + - -wait=tcp://discovery-server:8761 + - -timeout=60s + - -- + - java + - org.springframework.boot.loader.JarLauncher + env: + - name: OTEL_INSTRUMENTATION_AWS_SDK_EXPERIMENTAL_SPAN_ATTRIBUTES + value: "true" + image: 111122223333.dkr.ecr.us-west-2.amazonaws.com/springcommunity/spring-petclinic-visits-service:latest + securityContext: + runAsNonRoot: true + allowPrivilegeEscalation: false + name: visits-service + ports: + - containerPort: 8082 + restartPolicy: Always +status: {} diff --git a/scripts/eks/appsignals/sample-app/visits-service-service.yaml b/scripts/eks/appsignals/sample-app/visits-service-service.yaml new file mode 100644 index 0000000..2676d72 --- /dev/null +++ b/scripts/eks/appsignals/sample-app/visits-service-service.yaml @@ -0,0 +1,19 @@ +apiVersion: v1 +kind: Service +metadata: + annotations: + kompose.cmd: kompose convert -f ../docker-compose-eks.yml + kompose.version: 1.27.0 (b0ed6a2c9) + creationTimestamp: null + labels: + io.kompose.service: visits-service + name: visits-service +spec: + ports: + - name: "8082" + port: 8082 + targetPort: 8082 + selector: + io.kompose.service: visits-service +status: + loadBalancer: {} diff --git a/scripts/eks/appsignals/slo/inputRequest/CreateServiceLevelObjective/getOwner99Availability.json b/scripts/eks/appsignals/slo/inputRequest/CreateServiceLevelObjective/getOwner99Availability.json new file mode 100644 index 0000000..afafd8a --- /dev/null +++ b/scripts/eks/appsignals/slo/inputRequest/CreateServiceLevelObjective/getOwner99Availability.json @@ -0,0 +1,24 @@ +{ + "Name": "Availability for Searching an Owner", + "Description": "Availability larger than 99 for Get Owner operation", + "SliConfig": { + "StandardMetricsConfig": { + "ServiceId": "arn:aws:cloudwatch:us-west-2:285432994731:service/pet-clinic-frontend-7f6e6c088de97979c1ed9b1897ff45051aed6bc13440e4786e4fc7f755ae1c23", + "OperationName": "GET /api/customer/owners", + "MetricName": "AVAILABILITY", + "PeriodSeconds": 60 + }, + "MetricThreshold": 99.0, + "ComparisonOperator": "GreaterThan" + }, + "Goal": { + "Interval": { + "RollingInterval": { + "Duration": 1, + "DurationUnit": "DAY" + } + }, + "AttainmentGoal": 99.9, + "WarningThreshold": 60.0 + } +} diff --git a/scripts/eks/appsignals/slo/inputRequest/CreateServiceLevelObjective/getOwnerP99Latency.json b/scripts/eks/appsignals/slo/inputRequest/CreateServiceLevelObjective/getOwnerP99Latency.json new file mode 100644 index 0000000..48d0b8f --- /dev/null +++ b/scripts/eks/appsignals/slo/inputRequest/CreateServiceLevelObjective/getOwnerP99Latency.json @@ -0,0 +1,25 @@ +{ + "Name": "Latency for Searching an Owner", + "Description": "Latency P99 less than 200 ms for Get Owner operation", + "SliConfig": { + "StandardMetricsConfig": { + "ServiceId": "arn:aws:cloudwatch:us-west-2:285432994731:service/pet-clinic-frontend-7f6e6c088de97979c1ed9b1897ff45051aed6bc13440e4786e4fc7f755ae1c23", + "OperationName": "GET /api/customer/owners", + "MetricName": "LATENCY", + "Statistic": "p99", + "PeriodSeconds": 60 + }, + "MetricThreshold": 200.0, + "ComparisonOperator": "LessThan" + }, + "Goal": { + "Interval": { + "RollingInterval": { + "Duration": 1, + "DurationUnit": "DAY" + } + }, + "AttainmentGoal": 99.9, + "WarningThreshold": 60.0 + } +} diff --git a/scripts/eks/appsignals/slo/inputRequest/CreateServiceLevelObjective/postOwner99Availability.json b/scripts/eks/appsignals/slo/inputRequest/CreateServiceLevelObjective/postOwner99Availability.json new file mode 100644 index 0000000..6e982ad --- /dev/null +++ b/scripts/eks/appsignals/slo/inputRequest/CreateServiceLevelObjective/postOwner99Availability.json @@ -0,0 +1,24 @@ +{ + "Name": "Availability for Registering an Owner", + "Description": "Availability larger than 99 for Post Owner operation", + "SliConfig": { + "StandardMetricsConfig": { + "ServiceId": "arn:aws:cloudwatch:us-west-2:285432994731:service/pet-clinic-frontend-7f6e6c088de97979c1ed9b1897ff45051aed6bc13440e4786e4fc7f755ae1c23", + "OperationName": "POST /api/customer/owners", + "MetricName": "AVAILABILITY", + "PeriodSeconds": 60 + }, + "MetricThreshold": 99.0, + "ComparisonOperator": "GreaterThan" + }, + "Goal": { + "Interval": { + "RollingInterval": { + "Duration": 1, + "DurationUnit": "DAY" + } + }, + "AttainmentGoal": 99.9, + "WarningThreshold": 60.0 + } +} diff --git a/scripts/eks/appsignals/slo/inputRequest/CreateServiceLevelObjective/postOwnerP99Latency.json b/scripts/eks/appsignals/slo/inputRequest/CreateServiceLevelObjective/postOwnerP99Latency.json new file mode 100644 index 0000000..8cf63ce --- /dev/null +++ b/scripts/eks/appsignals/slo/inputRequest/CreateServiceLevelObjective/postOwnerP99Latency.json @@ -0,0 +1,25 @@ +{ + "Name": "Latency for Registering an Owner", + "Description": "Latency P99 less than 2000 ms for Post Owner operation", + "SliConfig": { + "StandardMetricsConfig": { + "ServiceId": "arn:aws:cloudwatch:us-west-2:285432994731:service/pet-clinic-frontend-7f6e6c088de97979c1ed9b1897ff45051aed6bc13440e4786e4fc7f755ae1c23", + "OperationName": "POST /api/customer/owners", + "MetricName": "LATENCY", + "Statistic": "p99", + "PeriodSeconds": 60 + }, + "MetricThreshold": 2000.0, + "ComparisonOperator": "LessThan" + }, + "Goal": { + "Interval": { + "RollingInterval": { + "Duration": 1, + "DurationUnit": "DAY" + } + }, + "AttainmentGoal": 99.9, + "WarningThreshold": 60.0 + } +} diff --git a/scripts/eks/appsignals/slo/inputRequest/DeleteServiceLevelObjective/deleteSlo1.json b/scripts/eks/appsignals/slo/inputRequest/DeleteServiceLevelObjective/deleteSlo1.json new file mode 100644 index 0000000..f4342b9 --- /dev/null +++ b/scripts/eks/appsignals/slo/inputRequest/DeleteServiceLevelObjective/deleteSlo1.json @@ -0,0 +1,3 @@ +{ + "Name": "Availability for Searching an Owner" +} diff --git a/scripts/eks/appsignals/slo/inputRequest/DeleteServiceLevelObjective/deleteSlo2.json b/scripts/eks/appsignals/slo/inputRequest/DeleteServiceLevelObjective/deleteSlo2.json new file mode 100644 index 0000000..ac58666 --- /dev/null +++ b/scripts/eks/appsignals/slo/inputRequest/DeleteServiceLevelObjective/deleteSlo2.json @@ -0,0 +1,3 @@ +{ + "Name": "Latency for Searching an Owner" +} diff --git a/scripts/eks/appsignals/slo/inputRequest/DeleteServiceLevelObjective/deleteSlo3.json b/scripts/eks/appsignals/slo/inputRequest/DeleteServiceLevelObjective/deleteSlo3.json new file mode 100644 index 0000000..f188b62 --- /dev/null +++ b/scripts/eks/appsignals/slo/inputRequest/DeleteServiceLevelObjective/deleteSlo3.json @@ -0,0 +1,3 @@ +{ + "Name": "Availability for Registering an Owner" +} diff --git a/scripts/eks/appsignals/slo/inputRequest/DeleteServiceLevelObjective/deleteSlo4.json b/scripts/eks/appsignals/slo/inputRequest/DeleteServiceLevelObjective/deleteSlo4.json new file mode 100644 index 0000000..a0eec9b --- /dev/null +++ b/scripts/eks/appsignals/slo/inputRequest/DeleteServiceLevelObjective/deleteSlo4.json @@ -0,0 +1,3 @@ +{ + "Name": "Latency for Registering an Owner" +} diff --git a/scripts/eks/appsignals/slo/inputRequest/ListServices/listServices.json b/scripts/eks/appsignals/slo/inputRequest/ListServices/listServices.json new file mode 100644 index 0000000..fc6e324 --- /dev/null +++ b/scripts/eks/appsignals/slo/inputRequest/ListServices/listServices.json @@ -0,0 +1,4 @@ +{ + "StartTime": 1, + "EndTime": 1 +} \ No newline at end of file diff --git a/scripts/eks/appsignals/slo/monitoring-2010-08-01.normal.json b/scripts/eks/appsignals/slo/monitoring-2010-08-01.normal.json new file mode 100644 index 0000000..4c1faa2 --- /dev/null +++ b/scripts/eks/appsignals/slo/monitoring-2010-08-01.normal.json @@ -0,0 +1,6502 @@ +{ + "version":"2.0", + "metadata":{ + "apiVersion":"2010-08-01", + "endpointPrefix":"monitoring", + "protocol":"query", + "serviceAbbreviation":"CloudWatch", + "serviceFullName":"Amazon CloudWatch", + "serviceId":"CloudWatch", + "signatureVersion":"v4", + "uid":"monitoring-2010-08-01", + "xmlNamespace":"http://monitoring.amazonaws.com/doc/2010-08-01/" + }, + "operations":{ + "BatchGetServiceLevelIndicatorReport":{ + "name":"BatchGetServiceLevelIndicatorReport", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"BatchGetServiceLevelIndicatorReportInput"}, + "output":{ + "shape":"BatchGetServiceLevelIndicatorReportOutput", + "resultWrapper":"BatchGetServiceLevelIndicatorReportResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"} + ], + "internalonly":true + }, + "BatchGetServiceLevelObjectiveBudgetReport":{ + "name":"BatchGetServiceLevelObjectiveBudgetReport", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"BatchGetServiceLevelObjectiveBudgetReportInput"}, + "output":{ + "shape":"BatchGetServiceLevelObjectiveBudgetReportOutput", + "resultWrapper":"BatchGetServiceLevelObjectiveBudgetReportResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"} + ], + "internalonly":true + }, + "CreateServiceLevelObjective":{ + "name":"CreateServiceLevelObjective", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"CreateServiceLevelObjectiveInput"}, + "output":{ + "shape":"CreateServiceLevelObjectiveOutput", + "resultWrapper":"CreateServiceLevelObjectiveResult" + }, + "errors":[ + {"shape":"ServiceQuotaExceededException"}, + {"shape":"ConflictException"}, + {"shape":"InvalidParameterValueException"} + ], + "internalonly":true + }, + "DeleteAlarmTemplate":{ + "name":"DeleteAlarmTemplate", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DeleteAlarmTemplateInput"}, + "errors":[ + {"shape":"ResourceNotFoundException"}, + {"shape":"ConflictException"} + ], + "internalonly":true + }, + "DeleteAlarms":{ + "name":"DeleteAlarms", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DeleteAlarmsInput"}, + "errors":[ + {"shape":"ResourceNotFound"} + ], + "documentation":"

Deletes the specified alarms. You can delete up to 100 alarms in one operation. However, this total can include no more than one composite alarm. For example, you could delete 99 metric alarms and one composite alarms with one operation, but you can't delete two composite alarms with one operation.

If you specify an incorrect alarm name or make any other error in the operation, no alarms are deleted. To confirm that alarms were deleted successfully, you can use the DescribeAlarms operation after using DeleteAlarms.

It is possible to create a loop or cycle of composite alarms, where composite alarm A depends on composite alarm B, and composite alarm B also depends on composite alarm A. In this scenario, you can't delete any composite alarm that is part of the cycle because there is always still a composite alarm that depends on that alarm that you want to delete.

To get out of such a situation, you must break the cycle by changing the rule of one of the composite alarms in the cycle to remove a dependency that creates the cycle. The simplest change to make to break a cycle is to change the AlarmRule of one of the alarms to false.

Additionally, the evaluation of composite alarms stops if CloudWatch detects a cycle in the evaluation path.

" + }, + "DeleteAlarmsAccount":{ + "name":"DeleteAlarmsAccount", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DeleteAlarmsAccountInput"}, + "output":{ + "shape":"DeleteAlarmsAccountOutput", + "resultWrapper":"DeleteAlarmsAccountResult" + }, + "internalonly":true + }, + "DeleteAnomalyDetector":{ + "name":"DeleteAnomalyDetector", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DeleteAnomalyDetectorInput"}, + "output":{ + "shape":"DeleteAnomalyDetectorOutput", + "resultWrapper":"DeleteAnomalyDetectorResult" + }, + "errors":[ + {"shape":"ResourceNotFoundException"}, + {"shape":"InternalServiceFault"}, + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"}, + {"shape":"InvalidParameterCombinationException"} + ], + "documentation":"

Deletes the specified anomaly detection model from your account. For more information about how to delete an anomaly detection model, see Deleting an anomaly detection model in the CloudWatch User Guide.

" + }, + "DeleteDashboards":{ + "name":"DeleteDashboards", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DeleteDashboardsInput"}, + "output":{ + "shape":"DeleteDashboardsOutput", + "resultWrapper":"DeleteDashboardsResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"DashboardNotFoundError"}, + {"shape":"InternalServiceFault"} + ], + "documentation":"

Deletes all dashboards that you specify. You can specify up to 100 dashboards to delete. If there is an error during this call, no dashboards are deleted.

" + }, + "DeleteDashboardsForAccount":{ + "name":"DeleteDashboardsForAccount", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DeleteDashboardsForAccountInput"}, + "output":{ + "shape":"DeleteDashboardsForAccountOutput", + "resultWrapper":"DeleteDashboardsForAccountResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"DashboardNotFoundError"}, + {"shape":"InternalServiceFault"} + ], + "internalonly":true + }, + "DeleteInsightRules":{ + "name":"DeleteInsightRules", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DeleteInsightRulesInput"}, + "output":{ + "shape":"DeleteInsightRulesOutput", + "resultWrapper":"DeleteInsightRulesResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"} + ], + "documentation":"

Permanently deletes the specified Contributor Insights rules.

If you create a rule, delete it, and then re-create it with the same name, historical data from the first time the rule was created might not be available.

" + }, + "DeleteMetricStream":{ + "name":"DeleteMetricStream", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DeleteMetricStreamInput"}, + "output":{ + "shape":"DeleteMetricStreamOutput", + "resultWrapper":"DeleteMetricStreamResult" + }, + "errors":[ + {"shape":"InternalServiceFault"}, + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"} + ], + "documentation":"

Permanently deletes the metric stream that you specify.

" + }, + "DeleteServiceLevelObjective":{ + "name":"DeleteServiceLevelObjective", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DeleteServiceLevelObjectiveInput"}, + "output":{ + "shape":"DeleteServiceLevelObjectiveOutput", + "resultWrapper":"DeleteServiceLevelObjectiveResult" + }, + "errors":[ + {"shape":"ResourceNotFoundException"}, + {"shape":"InvalidParameterValueException"} + ], + "internalonly":true + }, + "DescribeAlarmHistory":{ + "name":"DescribeAlarmHistory", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DescribeAlarmHistoryInput"}, + "output":{ + "shape":"DescribeAlarmHistoryOutput", + "resultWrapper":"DescribeAlarmHistoryResult" + }, + "errors":[ + {"shape":"InvalidNextToken"} + ], + "documentation":"

Retrieves the history for the specified alarm. You can filter the results by date range or item type. If an alarm name is not specified, the histories for either all metric alarms or all composite alarms are returned.

CloudWatch retains the history of an alarm even if you delete the alarm.

To use this operation and return information about a composite alarm, you must be signed on with the cloudwatch:DescribeAlarmHistory permission that is scoped to *. You can't return information about composite alarms if your cloudwatch:DescribeAlarmHistory permission has a narrower scope.

" + }, + "DescribeAlarmTemplateHistory":{ + "name":"DescribeAlarmTemplateHistory", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DescribeAlarmTemplateHistoryInput"}, + "output":{ + "shape":"DescribeAlarmTemplateHistoryOutput", + "resultWrapper":"DescribeAlarmTemplateHistoryResult" + }, + "errors":[ + {"shape":"InvalidNextToken"} + ], + "internalonly":true + }, + "DescribeAlarms":{ + "name":"DescribeAlarms", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DescribeAlarmsInput"}, + "output":{ + "shape":"DescribeAlarmsOutput", + "resultWrapper":"DescribeAlarmsResult" + }, + "errors":[ + {"shape":"InvalidNextToken"} + ], + "documentation":"

Retrieves the specified alarms. You can filter the results by specifying a prefix for the alarm name, the alarm state, or a prefix for any action.

To use this operation and return information about composite alarms, you must be signed on with the cloudwatch:DescribeAlarms permission that is scoped to *. You can't return information about composite alarms if your cloudwatch:DescribeAlarms permission has a narrower scope.

" + }, + "DescribeAlarmsForActionInternal":{ + "name":"DescribeAlarmsForActionInternal", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DescribeAlarmsForActionInternalInput"}, + "output":{ + "shape":"DescribeAlarmsForActionInternalOutput", + "resultWrapper":"DescribeAlarmsForActionInternalResult" + }, + "errors":[ + {"shape":"InvalidNextToken"} + ], + "internalonly":true + }, + "DescribeAlarmsForMetric":{ + "name":"DescribeAlarmsForMetric", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DescribeAlarmsForMetricInput"}, + "output":{ + "shape":"DescribeAlarmsForMetricOutput", + "resultWrapper":"DescribeAlarmsForMetricResult" + }, + "documentation":"

Retrieves the alarms for the specified metric. To filter the results, specify a statistic, period, or unit.

This operation retrieves only standard alarms that are based on the specified metric. It does not return alarms based on math expressions that use the specified metric, or composite alarms that use the specified metric.

" + }, + "DescribeAnomalyDetectors":{ + "name":"DescribeAnomalyDetectors", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DescribeAnomalyDetectorsInput"}, + "output":{ + "shape":"DescribeAnomalyDetectorsOutput", + "resultWrapper":"DescribeAnomalyDetectorsResult" + }, + "errors":[ + {"shape":"InvalidNextToken"}, + {"shape":"InternalServiceFault"}, + {"shape":"InvalidParameterValueException"}, + {"shape":"InvalidParameterCombinationException"} + ], + "documentation":"

Lists the anomaly detection models that you have created in your account. For single metric anomaly detectors, you can list all of the models in your account or filter the results to only the models that are related to a certain namespace, metric name, or metric dimension. For metric math anomaly detectors, you can list them by adding METRIC_MATH to the AnomalyDetectorTypes array. This will return all metric math anomaly detectors in your account.

" + }, + "DescribeInsightRules":{ + "name":"DescribeInsightRules", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DescribeInsightRulesInput"}, + "output":{ + "shape":"DescribeInsightRulesOutput", + "resultWrapper":"DescribeInsightRulesResult" + }, + "errors":[ + {"shape":"InvalidNextToken"} + ], + "documentation":"

Returns a list of all the Contributor Insights rules in your account.

For more information about Contributor Insights, see Using Contributor Insights to Analyze High-Cardinality Data.

" + }, + "DescribeMetricStreams":{ + "name":"DescribeMetricStreams", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DescribeMetricStreamsInput"}, + "output":{ + "shape":"DescribeMetricStreamsOutput", + "resultWrapper":"DescribeMetricStreamsResult" + }, + "errors":[ + {"shape":"InvalidNextToken"}, + {"shape":"InternalServiceFault"}, + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"}, + {"shape":"InvalidParameterCombinationException"} + ], + "internalonly":true + }, + "DescribeResourceCreationIds":{ + "name":"DescribeResourceCreationIds", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DescribeResourceCreationIdsInput"}, + "output":{ + "shape":"DescribeResourceCreationIdsOutput", + "resultWrapper":"DescribeResourceCreationIdsResult" + }, + "internalonly":true + }, + "DisableAlarmActions":{ + "name":"DisableAlarmActions", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DisableAlarmActionsInput"}, + "documentation":"

Disables the actions for the specified alarms. When an alarm's actions are disabled, the alarm actions do not execute when the alarm state changes.

" + }, + "DisableInsightRules":{ + "name":"DisableInsightRules", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"DisableInsightRulesInput"}, + "output":{ + "shape":"DisableInsightRulesOutput", + "resultWrapper":"DisableInsightRulesResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"} + ], + "documentation":"

Disables the specified Contributor Insights rules. When rules are disabled, they do not analyze log groups and do not incur costs.

" + }, + "EnableAlarmActions":{ + "name":"EnableAlarmActions", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"EnableAlarmActionsInput"}, + "documentation":"

Enables the actions for the specified alarms.

" + }, + "EnableInsightRules":{ + "name":"EnableInsightRules", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"EnableInsightRulesInput"}, + "output":{ + "shape":"EnableInsightRulesOutput", + "resultWrapper":"EnableInsightRulesResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"}, + {"shape":"LimitExceededException"} + ], + "documentation":"

Enables the specified Contributor Insights rules. When rules are enabled, they immediately begin analyzing log data.

" + }, + "EnableTopologyDiscovery":{ + "name":"EnableTopologyDiscovery", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"EnableTopologyDiscoveryInput"}, + "output":{ + "shape":"EnableTopologyDiscoveryOutput", + "resultWrapper":"EnableTopologyDiscoveryResult" + }, + "internalonly":true + }, + "GetAlarmTemplate":{ + "name":"GetAlarmTemplate", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"GetAlarmTemplateInput"}, + "output":{ + "shape":"GetAlarmTemplateOutput", + "resultWrapper":"GetAlarmTemplateResult" + }, + "errors":[ + {"shape":"ResourceNotFoundException"} + ], + "internalonly":true + }, + "GetDashboard":{ + "name":"GetDashboard", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"GetDashboardInput"}, + "output":{ + "shape":"GetDashboardOutput", + "resultWrapper":"GetDashboardResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"DashboardNotFoundError"}, + {"shape":"InternalServiceFault"} + ], + "documentation":"

Displays the details of the dashboard that you specify.

To copy an existing dashboard, use GetDashboard, and then use the data returned within DashboardBody as the template for the new dashboard when you call PutDashboard to create the copy.

" + }, + "GetDashboardForAccount":{ + "name":"GetDashboardForAccount", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"GetDashboardForAccountInput"}, + "output":{ + "shape":"GetDashboardForAccountOutput", + "resultWrapper":"GetDashboardForAccountResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"DashboardNotFoundError"}, + {"shape":"InternalServiceFault"} + ], + "internalonly":true + }, + "GetEntities":{ + "name":"GetEntities", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"GetEntitiesInput"}, + "output":{ + "shape":"GetEntitiesOutput", + "resultWrapper":"GetEntitiesResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"InternalServiceFault"}, + {"shape":"InvalidNextToken"} + ], + "internalonly":true + }, + "GetInsightRuleContributors":{ + "name":"GetInsightRuleContributors", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"GetInsightRuleContributorsInput"}, + "output":{ + "shape":"GetInsightRuleContributorsOutput", + "resultWrapper":"GetInsightRuleContributorsResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"}, + {"shape":"ResourceNotFoundException"}, + {"shape":"PreconditionNotMetException"}, + {"shape":"InvalidNextToken"} + ], + "internalonly":true + }, + "GetInsightRuleReport":{ + "name":"GetInsightRuleReport", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"GetInsightRuleReportInput"}, + "output":{ + "shape":"GetInsightRuleReportOutput", + "resultWrapper":"GetInsightRuleReportResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"}, + {"shape":"ResourceNotFoundException"} + ], + "documentation":"

This operation returns the time series data collected by a Contributor Insights rule. The data includes the identity and number of contributors to the log group.

You can also optionally return one or more statistics about each data point in the time series. These statistics can include the following:

  • UniqueContributors -- the number of unique contributors for each data point.

  • MaxContributorValue -- the value of the top contributor for each data point. The identity of the contributor might change for each data point in the graph.

    If this rule aggregates by COUNT, the top contributor for each data point is the contributor with the most occurrences in that period. If the rule aggregates by SUM, the top contributor is the contributor with the highest sum in the log field specified by the rule's Value, during that period.

  • SampleCount -- the number of data points matched by the rule.

  • Sum -- the sum of the values from all contributors during the time period represented by that data point.

  • Minimum -- the minimum value from a single observation during the time period represented by that data point.

  • Maximum -- the maximum value from a single observation during the time period represented by that data point.

  • Average -- the average value from all contributors during the time period represented by that data point.

" + }, + "GetMetricData":{ + "name":"GetMetricData", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"GetMetricDataInput"}, + "output":{ + "shape":"GetMetricDataOutput", + "resultWrapper":"GetMetricDataResult" + }, + "errors":[ + {"shape":"InvalidNextToken"} + ], + "documentation":"

You can use the GetMetricData API to retrieve CloudWatch metric values. The operation can also include a CloudWatch Metrics Insights query, and one or more metric math functions.

A GetMetricData operation that does not include a query can retrieve as many as 500 different metrics in a single request, with a total of as many as 100,800 data points. You can also optionally perform metric math expressions on the values of the returned statistics, to create new time series that represent new insights into your data. For example, using Lambda metrics, you could divide the Errors metric by the Invocations metric to get an error rate time series. For more information about metric math expressions, see Metric Math Syntax and Functions in the Amazon CloudWatch User Guide.

If you include a Metrics Insights query, each GetMetricData operation can include only one query. But the same GetMetricData operation can also retrieve other metrics. Metrics Insights queries can query only the most recent three hours of metric data. For more information about Metrics Insights, see Query your metrics with CloudWatch Metrics Insights.

Calls to the GetMetricData API have a different pricing structure than calls to GetMetricStatistics. For more information about pricing, see Amazon CloudWatch Pricing.

Amazon CloudWatch retains metric data as follows:

  • Data points with a period of less than 60 seconds are available for 3 hours. These data points are high-resolution metrics and are available only for custom metrics that have been defined with a StorageResolution of 1.

  • Data points with a period of 60 seconds (1-minute) are available for 15 days.

  • Data points with a period of 300 seconds (5-minute) are available for 63 days.

  • Data points with a period of 3600 seconds (1 hour) are available for 455 days (15 months).

Data points that are initially published with a shorter period are aggregated together for long-term storage. For example, if you collect data using a period of 1 minute, the data remains available for 15 days with 1-minute resolution. After 15 days, this data is still available, but is aggregated and retrievable only with a resolution of 5 minutes. After 63 days, the data is further aggregated and is available with a resolution of 1 hour.

If you omit Unit in your request, all data that was collected with any unit is returned, along with the corresponding units that were specified when the data was reported to CloudWatch. If you specify a unit, the operation returns only data that was collected with that unit specified. If you specify a unit that does not match the data collected, the results of the operation are null. CloudWatch does not perform unit conversions.

Using Metrics Insights queries with metric math

You can't mix a Metric Insights query and metric math syntax in the same expression, but you can reference results from a Metrics Insights query within other Metric math expressions. A Metrics Insights query without a GROUP BY clause returns a single time-series (TS), and can be used as input for a metric math expression that expects a single time series. A Metrics Insights query with a GROUP BY clause returns an array of time-series (TS[]), and can be used as input for a metric math expression that expects an array of time series.

" + }, + "GetMetricStatistics":{ + "name":"GetMetricStatistics", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"GetMetricStatisticsInput"}, + "output":{ + "shape":"GetMetricStatisticsOutput", + "resultWrapper":"GetMetricStatisticsResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"}, + {"shape":"InvalidParameterCombinationException"}, + {"shape":"InternalServiceFault"} + ], + "documentation":"

Gets statistics for the specified metric.

The maximum number of data points returned from a single call is 1,440. If you request more than 1,440 data points, CloudWatch returns an error. To reduce the number of data points, you can narrow the specified time range and make multiple requests across adjacent time ranges, or you can increase the specified period. Data points are not returned in chronological order.

CloudWatch aggregates data points based on the length of the period that you specify. For example, if you request statistics with a one-hour period, CloudWatch aggregates all data points with time stamps that fall within each one-hour period. Therefore, the number of values aggregated by CloudWatch is larger than the number of data points returned.

CloudWatch needs raw data points to calculate percentile statistics. If you publish data using a statistic set instead, you can only retrieve percentile statistics for this data if one of the following conditions is true:

  • The SampleCount value of the statistic set is 1.

  • The Min and the Max values of the statistic set are equal.

Percentile statistics are not available for metrics when any of the metric values are negative numbers.

Amazon CloudWatch retains metric data as follows:

  • Data points with a period of less than 60 seconds are available for 3 hours. These data points are high-resolution metrics and are available only for custom metrics that have been defined with a StorageResolution of 1.

  • Data points with a period of 60 seconds (1-minute) are available for 15 days.

  • Data points with a period of 300 seconds (5-minute) are available for 63 days.

  • Data points with a period of 3600 seconds (1 hour) are available for 455 days (15 months).

Data points that are initially published with a shorter period are aggregated together for long-term storage. For example, if you collect data using a period of 1 minute, the data remains available for 15 days with 1-minute resolution. After 15 days, this data is still available, but is aggregated and retrievable only with a resolution of 5 minutes. After 63 days, the data is further aggregated and is available with a resolution of 1 hour.

CloudWatch started retaining 5-minute and 1-hour metric data as of July 9, 2016.

For information about metrics and dimensions supported by Amazon Web Services services, see the Amazon CloudWatch Metrics and Dimensions Reference in the Amazon CloudWatch User Guide.

" + }, + "GetMetricStream":{ + "name":"GetMetricStream", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"GetMetricStreamInput"}, + "output":{ + "shape":"GetMetricStreamOutput", + "resultWrapper":"GetMetricStreamResult" + }, + "errors":[ + {"shape":"ResourceNotFoundException"}, + {"shape":"InternalServiceFault"}, + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"}, + {"shape":"InvalidParameterCombinationException"} + ], + "documentation":"

Returns information about the metric stream that you specify.

" + }, + "GetMetricWidgetImage":{ + "name":"GetMetricWidgetImage", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"GetMetricWidgetImageInput"}, + "output":{ + "shape":"GetMetricWidgetImageOutput", + "resultWrapper":"GetMetricWidgetImageResult" + }, + "documentation":"

You can use the GetMetricWidgetImage API to retrieve a snapshot graph of one or more Amazon CloudWatch metrics as a bitmap image. You can then embed this image into your services and products, such as wiki pages, reports, and documents. You could also retrieve images regularly, such as every minute, and create your own custom live dashboard.

The graph you retrieve can include all CloudWatch metric graph features, including metric math and horizontal and vertical annotations.

There is a limit of 20 transactions per second for this API. Each GetMetricWidgetImage action has the following limits:

  • As many as 100 metrics in the graph.

  • Up to 100 KB uncompressed payload.

" + }, + "GetService":{ + "name":"GetService", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"GetServiceInput"}, + "output":{ + "shape":"GetServiceOutput", + "resultWrapper":"GetServiceResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"} + ], + "internalonly":true + }, + "GetServiceData":{ + "name":"GetServiceData", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"GetServiceDataInput"}, + "output":{ + "shape":"GetServiceDataOutput", + "resultWrapper":"GetServiceDataResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"} + ], + "internalonly":true + }, + "GetServiceLevelIndicatorReport":{ + "name":"GetServiceLevelIndicatorReport", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"GetServiceLevelIndicatorReportInput"}, + "output":{ + "shape":"GetServiceLevelIndicatorReportOutput", + "resultWrapper":"GetServiceLevelIndicatorReportResult" + }, + "errors":[ + {"shape":"ResourceNotFoundException"}, + {"shape":"InvalidParameterValueException"} + ], + "internalonly":true + }, + "GetServiceLevelObjective":{ + "name":"GetServiceLevelObjective", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"GetServiceLevelObjectiveInput"}, + "output":{ + "shape":"GetServiceLevelObjectiveOutput", + "resultWrapper":"GetServiceLevelObjectiveResult" + }, + "errors":[ + {"shape":"ResourceNotFoundException"}, + {"shape":"InvalidParameterValueException"} + ], + "internalonly":true + }, + "GetTopologyDiscoveryStatus":{ + "name":"GetTopologyDiscoveryStatus", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"GetTopologyDiscoveryStatusInput"}, + "output":{ + "shape":"GetTopologyDiscoveryStatusOutput", + "resultWrapper":"GetTopologyDiscoveryStatusResult" + }, + "internalonly":true + }, + "GetTopologyMap":{ + "name":"GetTopologyMap", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"GetTopologyMapInput"}, + "output":{ + "shape":"GetTopologyMapOutput", + "resultWrapper":"GetTopologyMapResult" + }, + "internalonly":true + }, + "ListAlarmTemplates":{ + "name":"ListAlarmTemplates", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"ListAlarmTemplatesInput"}, + "output":{ + "shape":"ListAlarmTemplatesOutput", + "resultWrapper":"ListAlarmTemplatesResult" + }, + "errors":[ + {"shape":"InvalidNextToken"} + ], + "internalonly":true + }, + "ListDashboards":{ + "name":"ListDashboards", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"ListDashboardsInput"}, + "output":{ + "shape":"ListDashboardsOutput", + "resultWrapper":"ListDashboardsResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"InternalServiceFault"} + ], + "documentation":"

Returns a list of the dashboards for your account. If you include DashboardNamePrefix, only those dashboards with names starting with the prefix are listed. Otherwise, all dashboards in your account are listed.

ListDashboards returns up to 1000 results on one page. If there are more than 1000 dashboards, you can call ListDashboards again and include the value you received for NextToken in the first call, to receive the next 1000 results.

" + }, + "ListDashboardsForAccount":{ + "name":"ListDashboardsForAccount", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"ListDashboardsForAccountInput"}, + "output":{ + "shape":"ListDashboardsForAccountOutput", + "resultWrapper":"ListDashboardsForAccountResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"InternalServiceFault"} + ], + "internalonly":true + }, + "ListHostInfo":{ + "name":"ListHostInfo", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "output":{ + "shape":"ListHostInfoOutput", + "resultWrapper":"ListHostInfoResult" + }, + "errors":[ + {"shape":"InternalServiceFault"} + ], + "internalonly":true + }, + "ListInsightRuleVendedResources":{ + "name":"ListInsightRuleVendedResources", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"ListInsightRuleVendedResourcesInput"}, + "output":{ + "shape":"ListInsightRuleVendedResourcesOutput", + "resultWrapper":"ListInsightRuleVendedResourcesResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"}, + {"shape":"InvalidNextToken"} + ], + "internalonly":true + }, + "ListManagedInsightRules":{ + "name":"ListManagedInsightRules", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"ListManagedInsightRulesInput"}, + "output":{ + "shape":"ListManagedInsightRulesOutput", + "resultWrapper":"ListManagedInsightRulesResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"}, + {"shape":"InvalidNextToken"} + ], + "documentation":"

Returns a list that contains the number of managed Contributor Insights rules in your account.

", + "internalonly":true + }, + "ListMetricStreams":{ + "name":"ListMetricStreams", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"ListMetricStreamsInput"}, + "output":{ + "shape":"ListMetricStreamsOutput", + "resultWrapper":"ListMetricStreamsResult" + }, + "errors":[ + {"shape":"InvalidNextToken"}, + {"shape":"InternalServiceFault"}, + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"} + ], + "documentation":"

Returns a list of metric streams in this account.

" + }, + "ListMetrics":{ + "name":"ListMetrics", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"ListMetricsInput"}, + "output":{ + "shape":"ListMetricsOutput", + "resultWrapper":"ListMetricsResult" + }, + "errors":[ + {"shape":"InternalServiceFault"}, + {"shape":"InvalidParameterValueException"} + ], + "documentation":"

List the specified metrics. You can use the returned metrics with GetMetricData or GetMetricStatistics to get statistical data.

Up to 500 results are returned for any one call. To retrieve additional results, use the returned token with subsequent calls.

After you create a metric, allow up to 15 minutes for the metric to appear. To see metric statistics sooner, use GetMetricData or GetMetricStatistics.

If you are using CloudWatch cross-account observability, you can use this operation in a monitoring account and view metrics from the linked source accounts. For more information, see CloudWatch cross-account observability.

ListMetrics doesn't return information about metrics if those metrics haven't reported data in the past two weeks. To retrieve those metrics, use GetMetricData or GetMetricStatistics.

" + }, + "ListServiceLevelObjectives":{ + "name":"ListServiceLevelObjectives", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"ListServiceLevelObjectivesInput"}, + "output":{ + "shape":"ListServiceLevelObjectivesOutput", + "resultWrapper":"ListServiceLevelObjectivesResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"} + ], + "internalonly":true + }, + "ListServices":{ + "name":"ListServices", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"ListServicesInput"}, + "output":{ + "shape":"ListServicesOutput", + "resultWrapper":"ListServicesResult" + }, + "internalonly":true + }, + "ListTagsForResource":{ + "name":"ListTagsForResource", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"ListTagsForResourceInput"}, + "output":{ + "shape":"ListTagsForResourceOutput", + "resultWrapper":"ListTagsForResourceResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"ResourceNotFoundException"}, + {"shape":"InternalServiceFault"} + ], + "documentation":"

Displays the tags associated with a CloudWatch resource. Currently, alarms and Contributor Insights rules support tagging.

" + }, + "PutAlarmTemplate":{ + "name":"PutAlarmTemplate", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"PutAlarmTemplateInput"}, + "errors":[ + {"shape":"LimitExceededFault"}, + {"shape":"ConflictException"} + ], + "internalonly":true + }, + "PutAnomalyDetector":{ + "name":"PutAnomalyDetector", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"PutAnomalyDetectorInput"}, + "output":{ + "shape":"PutAnomalyDetectorOutput", + "resultWrapper":"PutAnomalyDetectorResult" + }, + "errors":[ + {"shape":"LimitExceededException"}, + {"shape":"InternalServiceFault"}, + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"}, + {"shape":"InvalidParameterCombinationException"} + ], + "documentation":"

Creates an anomaly detection model for a CloudWatch metric. You can use the model to display a band of expected normal values when the metric is graphed.

For more information, see CloudWatch Anomaly Detection.

" + }, + "PutCompositeAlarm":{ + "name":"PutCompositeAlarm", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"PutCompositeAlarmInput"}, + "errors":[ + {"shape":"LimitExceededFault"} + ], + "documentation":"

Creates or updates a composite alarm. When you create a composite alarm, you specify a rule expression for the alarm that takes into account the alarm states of other alarms that you have created. The composite alarm goes into ALARM state only if all conditions of the rule are met.

The alarms specified in a composite alarm's rule expression can include metric alarms and other composite alarms. The rule expression of a composite alarm can include as many as 100 underlying alarms. Any single alarm can be included in the rule expressions of as many as 150 composite alarms.

Using composite alarms can reduce alarm noise. You can create multiple metric alarms, and also create a composite alarm and set up alerts only for the composite alarm. For example, you could create a composite alarm that goes into ALARM state only when more than one of the underlying metric alarms are in ALARM state.

Currently, the only alarm actions that can be taken by composite alarms are notifying SNS topics.

It is possible to create a loop or cycle of composite alarms, where composite alarm A depends on composite alarm B, and composite alarm B also depends on composite alarm A. In this scenario, you can't delete any composite alarm that is part of the cycle because there is always still a composite alarm that depends on that alarm that you want to delete.

To get out of such a situation, you must break the cycle by changing the rule of one of the composite alarms in the cycle to remove a dependency that creates the cycle. The simplest change to make to break a cycle is to change the AlarmRule of one of the alarms to false.

Additionally, the evaluation of composite alarms stops if CloudWatch detects a cycle in the evaluation path.

When this operation creates an alarm, the alarm state is immediately set to INSUFFICIENT_DATA. The alarm is then evaluated and its state is set appropriately. Any actions associated with the new state are then executed. For a composite alarm, this initial time after creation is the only time that the alarm can be in INSUFFICIENT_DATA state.

When you update an existing alarm, its state is left unchanged, but the update completely overwrites the previous configuration of the alarm.

To use this operation, you must be signed on with the cloudwatch:PutCompositeAlarm permission that is scoped to *. You can't create a composite alarms if your cloudwatch:PutCompositeAlarm permission has a narrower scope.

If you are an IAM user, you must have iam:CreateServiceLinkedRole to create a composite alarm that has Systems Manager OpsItem actions.

" + }, + "PutDashboard":{ + "name":"PutDashboard", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"PutDashboardInput"}, + "output":{ + "shape":"PutDashboardOutput", + "resultWrapper":"PutDashboardResult" + }, + "errors":[ + {"shape":"DashboardInvalidInputError"}, + {"shape":"InternalServiceFault"} + ], + "documentation":"

Creates a dashboard if it does not already exist, or updates an existing dashboard. If you update a dashboard, the entire contents are replaced with what you specify here.

All dashboards in your account are global, not region-specific.

A simple way to create a dashboard using PutDashboard is to copy an existing dashboard. To copy an existing dashboard using the console, you can load the dashboard and then use the View/edit source command in the Actions menu to display the JSON block for that dashboard. Another way to copy a dashboard is to use GetDashboard, and then use the data returned within DashboardBody as the template for the new dashboard when you call PutDashboard.

When you create a dashboard with PutDashboard, a good practice is to add a text widget at the top of the dashboard with a message that the dashboard was created by script and should not be changed in the console. This message could also point console users to the location of the DashboardBody script or the CloudFormation template used to create the dashboard.

" + }, + "PutDashboardForAccount":{ + "name":"PutDashboardForAccount", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"PutDashboardForAccountInput"}, + "output":{ + "shape":"PutDashboardForAccountOutput", + "resultWrapper":"PutDashboardForAccountResult" + }, + "errors":[ + {"shape":"DashboardInvalidInputError"}, + {"shape":"InternalServiceFault"} + ], + "internalonly":true + }, + "PutInsightRule":{ + "name":"PutInsightRule", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"PutInsightRuleInput"}, + "output":{ + "shape":"PutInsightRuleOutput", + "resultWrapper":"PutInsightRuleResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"}, + {"shape":"LimitExceededException"} + ], + "documentation":"

Creates a Contributor Insights rule. Rules evaluate log events in a CloudWatch Logs log group, enabling you to find contributor data for the log events in that log group. For more information, see Using Contributor Insights to Analyze High-Cardinality Data.

If you create a rule, delete it, and then re-create it with the same name, historical data from the first time the rule was created might not be available.

" + }, + "PutManagedInsightRules":{ + "name":"PutManagedInsightRules", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"PutManagedInsightRulesInput"}, + "output":{ + "shape":"PutManagedInsightRulesOutput", + "resultWrapper":"PutManagedInsightRulesResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"} + ], + "documentation":"

Creates a managed Contributor Insights rule for a specified Amazon Web Services resource. When you enable a managed rule, you create a Contributor Insights rule that collects data from Amazon Web Services services. You cannot edit these rules with PutInsightRule. The rules can be enabled, disabled, and deleted using EnableInsightRules, DisableInsightRules, and DeleteInsightRules. If a previously created managed rule is currently disabled, a subsequent call to this API will re-enable it. Use ListManagedInsightRules to describe all available rules.

", + "internalonly":true + }, + "PutMetricAlarm":{ + "name":"PutMetricAlarm", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"PutMetricAlarmInput"}, + "errors":[ + {"shape":"LimitExceededFault"} + ], + "documentation":"

Creates or updates an alarm and associates it with the specified metric, metric math expression, anomaly detection model, or Metrics Insights query. For more information about using a Metrics Insights query for an alarm, see Create alarms on Metrics Insights queries.

Alarms based on anomaly detection models cannot have Auto Scaling actions.

When this operation creates an alarm, the alarm state is immediately set to INSUFFICIENT_DATA. The alarm is then evaluated and its state is set appropriately. Any actions associated with the new state are then executed.

When you update an existing alarm, its state is left unchanged, but the update completely overwrites the previous configuration of the alarm.

If you are an IAM user, you must have Amazon EC2 permissions for some alarm operations:

  • The iam:CreateServiceLinkedRole permission for all alarms with EC2 actions

  • The iam:CreateServiceLinkedRole permissions to create an alarm with Systems Manager OpsItem or response plan actions.

The first time you create an alarm in the Amazon Web Services Management Console, the CLI, or by using the PutMetricAlarm API, CloudWatch creates the necessary service-linked role for you. The service-linked roles are called AWSServiceRoleForCloudWatchEvents and AWSServiceRoleForCloudWatchAlarms_ActionSSM. For more information, see Amazon Web Services service-linked role.

Each PutMetricAlarm action has a maximum uncompressed payload of 120 KB.

Cross-account alarms

You can set an alarm on metrics in the current account, or in another account. To create a cross-account alarm that watches a metric in a different account, you must have completed the following pre-requisites:

  • The account where the metrics are located (the sharing account) must already have a sharing role named CloudWatch-CrossAccountSharingRole. If it does not already have this role, you must create it using the instructions in Set up a sharing account in Cross-account cross-Region CloudWatch console. The policy for that role must grant access to the ID of the account where you are creating the alarm.

  • The account where you are creating the alarm (the monitoring account) must already have a service-linked role named AWSServiceRoleForCloudWatchCrossAccount to allow CloudWatch to assume the sharing role in the sharing account. If it does not, you must create it following the directions in Set up a monitoring account in Cross-account cross-Region CloudWatch console.

" + }, + "PutMetricData":{ + "name":"PutMetricData", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"PutMetricDataInput"}, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"}, + {"shape":"InvalidParameterCombinationException"}, + {"shape":"InternalServiceFault"} + ], + "documentation":"

Publishes metric data points to Amazon CloudWatch. CloudWatch associates the data points with the specified metric. If the specified metric does not exist, CloudWatch creates the metric. When CloudWatch creates a metric, it can take up to fifteen minutes for the metric to appear in calls to ListMetrics.

You can publish either individual data points in the Value field, or arrays of values and the number of times each value occurred during the period by using the Values and Counts fields in the MetricDatum structure. Using the Values and Counts method enables you to publish up to 150 values per metric with one PutMetricData request, and supports retrieving percentile statistics on this data.

Each PutMetricData request is limited to 1 MB in size for HTTP POST requests. You can send a payload compressed by gzip. Each request is also limited to no more than 1000 different metrics.

Although the Value parameter accepts numbers of type Double, CloudWatch rejects values that are either too small or too large. Values must be in the range of -2^360 to 2^360. In addition, special values (for example, NaN, +Infinity, -Infinity) are not supported.

You can use up to 30 dimensions per metric to further clarify what data the metric collects. Each dimension consists of a Name and Value pair. For more information about specifying dimensions, see Publishing Metrics in the Amazon CloudWatch User Guide.

You specify the time stamp to be associated with each data point. You can specify time stamps that are as much as two weeks before the current date, and as much as 2 hours after the current day and time.

Data points with time stamps from 24 hours ago or longer can take at least 48 hours to become available for GetMetricData or GetMetricStatistics from the time they are submitted. Data points with time stamps between 3 and 24 hours ago can take as much as 2 hours to become available for for GetMetricData or GetMetricStatistics.

CloudWatch needs raw data points to calculate percentile statistics. If you publish data using a statistic set instead, you can only retrieve percentile statistics for this data if one of the following conditions is true:

  • The SampleCount value of the statistic set is 1 and Min, Max, and Sum are all equal.

  • The Min and Max are equal, and Sum is equal to Min multiplied by SampleCount.

" + }, + "PutMetricDataBatch":{ + "name":"PutMetricDataBatch", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"PutMetricDataBatchInput"}, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"}, + {"shape":"InvalidParameterCombinationException"}, + {"shape":"InternalServiceFault"} + ], + "internalonly":true + }, + "PutMetricStream":{ + "name":"PutMetricStream", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"PutMetricStreamInput"}, + "output":{ + "shape":"PutMetricStreamOutput", + "resultWrapper":"PutMetricStreamResult" + }, + "errors":[ + {"shape":"ConcurrentModificationException"}, + {"shape":"InternalServiceFault"}, + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"}, + {"shape":"InvalidParameterCombinationException"} + ], + "documentation":"

Creates or updates a metric stream. Metric streams can automatically stream CloudWatch metrics to Amazon Web Services destinations, including Amazon S3, and to many third-party solutions.

For more information, see Using Metric Streams.

To create a metric stream, you must be signed in to an account that has the iam:PassRole permission and either the CloudWatchFullAccess policy or the cloudwatch:PutMetricStream permission.

When you create or update a metric stream, you choose one of the following:

  • Stream metrics from all metric namespaces in the account.

  • Stream metrics from all metric namespaces in the account, except for the namespaces that you list in ExcludeFilters.

  • Stream metrics from only the metric namespaces that you list in IncludeFilters.

By default, a metric stream always sends the MAX, MIN, SUM, and SAMPLECOUNT statistics for each metric that is streamed. You can use the StatisticsConfigurations parameter to have the metric stream send additional statistics in the stream. Streaming additional statistics incurs additional costs. For more information, see Amazon CloudWatch Pricing.

When you use PutMetricStream to create a new metric stream, the stream is created in the running state. If you use it to update an existing stream, the state of the stream is not changed.

If you are using CloudWatch cross-account observability and you create a metric stream in a monitoring account, you can choose whether to include metrics from source accounts in the stream. For more information, see CloudWatch cross-account observability.

" + }, + "PutVendedInsightRuleContributions":{ + "name":"PutVendedInsightRuleContributions", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"PutVendedInsightRuleContributionsInput"}, + "output":{ + "shape":"PutVendedInsightRuleContributionsOutput", + "resultWrapper":"PutVendedInsightRuleContributionsResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"} + ], + "internalonly":true + }, + "RemoveActionInternal":{ + "name":"RemoveActionInternal", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"RemoveActionInternalInput"}, + "output":{ + "shape":"RemoveActionInternalOutput", + "resultWrapper":"RemoveActionInternalResult" + }, + "internalonly":true + }, + "SetAlarmState":{ + "name":"SetAlarmState", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"SetAlarmStateInput"}, + "errors":[ + {"shape":"ResourceNotFound"}, + {"shape":"InvalidFormatFault"} + ], + "documentation":"

Temporarily sets the state of an alarm for testing purposes. When the updated state differs from the previous value, the action configured for the appropriate state is invoked. For example, if your alarm is configured to send an Amazon SNS message when an alarm is triggered, temporarily changing the alarm state to ALARM sends an SNS message.

Metric alarms returns to their actual state quickly, often within seconds. Because the metric alarm state change happens quickly, it is typically only visible in the alarm's History tab in the Amazon CloudWatch console or through DescribeAlarmHistory.

If you use SetAlarmState on a composite alarm, the composite alarm is not guaranteed to return to its actual state. It returns to its actual state only once any of its children alarms change state. It is also reevaluated if you update its configuration.

If an alarm triggers EC2 Auto Scaling policies or application Auto Scaling policies, you must include information in the StateReasonData parameter to enable the policy to take the correct action.

" + }, + "StartMetricStreams":{ + "name":"StartMetricStreams", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"StartMetricStreamsInput"}, + "output":{ + "shape":"StartMetricStreamsOutput", + "resultWrapper":"StartMetricStreamsResult" + }, + "errors":[ + {"shape":"InternalServiceFault"}, + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"} + ], + "documentation":"

Starts the streaming of metrics for one or more of your metric streams.

" + }, + "StopMetricStreams":{ + "name":"StopMetricStreams", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"StopMetricStreamsInput"}, + "output":{ + "shape":"StopMetricStreamsOutput", + "resultWrapper":"StopMetricStreamsResult" + }, + "errors":[ + {"shape":"InternalServiceFault"}, + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"} + ], + "documentation":"

Stops the streaming of metrics for one or more of your metric streams.

" + }, + "TagResource":{ + "name":"TagResource", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"TagResourceInput"}, + "output":{ + "shape":"TagResourceOutput", + "resultWrapper":"TagResourceResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"ResourceNotFoundException"}, + {"shape":"ConcurrentModificationException"}, + {"shape":"InternalServiceFault"} + ], + "documentation":"

Assigns one or more tags (key-value pairs) to the specified CloudWatch resource. Currently, the only CloudWatch resources that can be tagged are alarms and Contributor Insights rules.

Tags can help you organize and categorize your resources. You can also use them to scope user permissions by granting a user permission to access or change only resources with certain tag values.

Tags don't have any semantic meaning to Amazon Web Services and are interpreted strictly as strings of characters.

You can use the TagResource action with an alarm that already has tags. If you specify a new tag key for the alarm, this tag is appended to the list of tags associated with the alarm. If you specify a tag key that is already associated with the alarm, the new tag value that you specify replaces the previous value for that tag.

You can associate as many as 50 tags with a CloudWatch resource.

" + }, + "UntagResource":{ + "name":"UntagResource", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"UntagResourceInput"}, + "output":{ + "shape":"UntagResourceOutput", + "resultWrapper":"UntagResourceResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"ResourceNotFoundException"}, + {"shape":"ConcurrentModificationException"}, + {"shape":"InternalServiceFault"} + ], + "documentation":"

Removes one or more tags from the specified resource.

" + }, + "UpdateInsightRulesTtl":{ + "name":"UpdateInsightRulesTtl", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"UpdateInsightRulesTtlInput"}, + "output":{ + "shape":"UpdateInsightRulesTtlOutput", + "resultWrapper":"UpdateInsightRulesTtlResult" + }, + "errors":[ + {"shape":"InvalidParameterValueException"}, + {"shape":"MissingRequiredParameterException"} + ], + "internalonly":true + }, + "UpdateMetricStreamSegmentationData":{ + "name":"UpdateMetricStreamSegmentationData", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"UpdateMetricStreamSegmentationDataInput"}, + "output":{ + "shape":"UpdateMetricStreamSegmentationDataOutput", + "resultWrapper":"UpdateMetricStreamSegmentationDataResult" + }, + "internalonly":true + }, + "UpdateServiceLevelObjective":{ + "name":"UpdateServiceLevelObjective", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"UpdateServiceLevelObjectiveInput"}, + "output":{ + "shape":"UpdateServiceLevelObjectiveOutput", + "resultWrapper":"UpdateServiceLevelObjectiveResult" + }, + "errors":[ + {"shape":"ServiceQuotaExceededException"}, + {"shape":"ResourceNotFoundException"}, + {"shape":"InvalidParameterValueException"} + ], + "internalonly":true + }, + "VerifyResourcesExistForTagris":{ + "name":"VerifyResourcesExistForTagris", + "http":{ + "method":"POST", + "requestUri":"/" + }, + "input":{"shape":"TagrisVerifyResourcesExistInput"}, + "output":{ + "shape":"TagrisVerifyResourcesExistOutput", + "resultWrapper":"VerifyResourcesExistForTagrisResult" + }, + "errors":[ + {"shape":"TagrisAccessDeniedException"}, + {"shape":"TagrisInternalServiceException"}, + {"shape":"TagrisInvalidArnException"}, + {"shape":"TagrisInvalidParameterException"}, + {"shape":"TagrisPartialResourcesExistResultsException"}, + {"shape":"TagrisThrottledException"} + ], + "internalonly":true + } + }, + "shapes":{ + "AWSAccountId":{ + "type":"string", + "max":63, + "min":1 + }, + "AccountId":{ + "type":"string", + "max":255, + "min":1 + }, + "ActionPrefix":{ + "type":"string", + "max":1024, + "min":1 + }, + "ActionsEnabled":{"type":"boolean"}, + "ActionsSuppressedBy":{ + "type":"string", + "enum":[ + "WaitPeriod", + "ExtensionPeriod", + "Alarm" + ] + }, + "ActionsSuppressedReason":{ + "type":"string", + "max":1024, + "min":0 + }, + "AggregatedNode":{ + "type":"structure", + "required":[ + "Id", + "StatisticReferences" + ], + "members":{ + "Id":{"shape":"AggregatedNodeId"}, + "StatisticReferences":{"shape":"StatisticReferences"} + } + }, + "AggregatedNodeId":{"type":"string"}, + "AggregatedNodeIds":{ + "type":"list", + "member":{"shape":"AggregatedNodeId"} + }, + "AggregatedNodes":{ + "type":"list", + "member":{"shape":"AggregatedNode"} + }, + "AlarmArn":{ + "type":"string", + "max":1600, + "min":1 + }, + "AlarmDescription":{ + "type":"string", + "max":1024, + "min":0 + }, + "AlarmHistoryItem":{ + "type":"structure", + "members":{ + "AlarmName":{ + "shape":"AlarmName", + "documentation":"

The descriptive name for the alarm.

" + }, + "AlarmType":{ + "shape":"AlarmType", + "documentation":"

The type of alarm, either metric alarm or composite alarm.

" + }, + "Timestamp":{ + "shape":"Timestamp", + "documentation":"

The time stamp for the alarm history item.

" + }, + "HistoryItemType":{ + "shape":"HistoryItemType", + "documentation":"

The type of alarm history item.

" + }, + "HistorySummary":{ + "shape":"HistorySummary", + "documentation":"

A summary of the alarm history, in text format.

" + }, + "HistoryData":{ + "shape":"HistoryData", + "documentation":"

Data about the alarm, in JSON format.

" + }, + "ResourceArn":{ + "shape":"AmazonResourceName", + "internalonly":true + }, + "AlarmManagerArn":{ + "shape":"AmazonResourceName", + "internalonly":true + } + }, + "documentation":"

Represents the history of a specific alarm.

" + }, + "AlarmHistoryItems":{ + "type":"list", + "member":{"shape":"AlarmHistoryItem"} + }, + "AlarmName":{ + "type":"string", + "max":255, + "min":1 + }, + "AlarmNamePrefix":{ + "type":"string", + "max":255, + "min":1 + }, + "AlarmNames":{ + "type":"list", + "member":{"shape":"AlarmName"}, + "max":100 + }, + "AlarmRule":{ + "type":"string", + "max":10240, + "min":1 + }, + "AlarmTemplateDescription":{ + "type":"string", + "max":1024, + "min":0 + }, + "AlarmTemplateEntries":{ + "type":"list", + "member":{"shape":"AlarmTemplateEntry"}, + "internalonly":true + }, + "AlarmTemplateEntry":{ + "type":"structure", + "members":{ + "Name":{"shape":"AlarmTemplateName"}, + "Arn":{"shape":"AmazonResourceName"}, + "ResourceType":{"shape":"AlarmTemplateResourceType"}, + "ResourceTag":{"shape":"Tag"} + }, + "internalonly":true + }, + "AlarmTemplateHistoryItem":{ + "type":"structure", + "members":{ + "Name":{"shape":"AlarmTemplateName"}, + "Arn":{"shape":"AmazonResourceName"}, + "HistoryItemType":{"shape":"HistoryItemType"}, + "HistorySummary":{"shape":"HistorySummary"}, + "HistoryData":{"shape":"HistoryData"}, + "Timestamp":{"shape":"Timestamp"} + }, + "internalonly":true + }, + "AlarmTemplateHistoryItems":{ + "type":"list", + "member":{"shape":"AlarmTemplateHistoryItem"}, + "internalonly":true + }, + "AlarmTemplateName":{ + "type":"string", + "max":255, + "min":1 + }, + "AlarmTemplateNamePrefix":{ + "type":"string", + "max":100, + "min":1 + }, + "AlarmTemplateResourceType":{ + "type":"string", + "max":255, + "min":1 + }, + "AlarmTemplateState":{ + "type":"string", + "enum":[ + "ACTIVE", + "INACTIVE", + "CREATE_IN_PROGRESS", + "UPDATE_IN_PROGRESS", + "DELETE_IN_PROGRESS" + ] + }, + "AlarmTemplateStateReason":{ + "type":"string", + "max":1023, + "min":0 + }, + "AlarmType":{ + "type":"string", + "enum":[ + "CompositeAlarm", + "MetricAlarm" + ] + }, + "AlarmTypes":{ + "type":"list", + "member":{"shape":"AlarmType"} + }, + "AmazonResourceName":{ + "type":"string", + "max":1024, + "min":1 + }, + "AmpQueue":{"type":"string"}, + "AmpQueues":{ + "type":"list", + "member":{"shape":"AmpQueue"} + }, + "AnomalyDetector":{ + "type":"structure", + "members":{ + "Namespace":{ + "shape":"Namespace", + "documentation":"

The namespace of the metric associated with the anomaly detection model.

", + "deprecated":true, + "deprecatedMessage":"Use SingleMetricAnomalyDetector.Namespace property." + }, + "MetricName":{ + "shape":"MetricName", + "documentation":"

The name of the metric associated with the anomaly detection model.

", + "deprecated":true, + "deprecatedMessage":"Use SingleMetricAnomalyDetector.MetricName property." + }, + "Dimensions":{ + "shape":"Dimensions", + "documentation":"

The metric dimensions associated with the anomaly detection model.

", + "deprecated":true, + "deprecatedMessage":"Use SingleMetricAnomalyDetector.Dimensions property." + }, + "Stat":{ + "shape":"AnomalyDetectorMetricStat", + "documentation":"

The statistic associated with the anomaly detection model.

", + "deprecated":true, + "deprecatedMessage":"Use SingleMetricAnomalyDetector.Stat property." + }, + "Configuration":{ + "shape":"AnomalyDetectorConfiguration", + "documentation":"

The configuration specifies details about how the anomaly detection model is to be trained, including time ranges to exclude from use for training the model, and the time zone to use for the metric.

" + }, + "StateValue":{ + "shape":"AnomalyDetectorStateValue", + "documentation":"

The current status of the anomaly detector's training. The possible values are TRAINED | PENDING_TRAINING | TRAINED_INSUFFICIENT_DATA

" + }, + "SingleMetricAnomalyDetector":{ + "shape":"SingleMetricAnomalyDetector", + "documentation":"

The CloudWatch metric and statistic for this anomaly detector.

" + }, + "MetricMathAnomalyDetector":{ + "shape":"MetricMathAnomalyDetector", + "documentation":"

The CloudWatch metric math expression for this anomaly detector.

" + } + }, + "documentation":"

An anomaly detection model associated with a particular CloudWatch metric, statistic, or metric math expression. You can use the model to display a band of expected, normal values when the metric is graphed.

" + }, + "AnomalyDetectorConfiguration":{ + "type":"structure", + "members":{ + "ExcludedTimeRanges":{ + "shape":"AnomalyDetectorExcludedTimeRanges", + "documentation":"

An array of time ranges to exclude from use when the anomaly detection model is trained. Use this to make sure that events that could cause unusual values for the metric, such as deployments, aren't used when CloudWatch creates the model.

" + }, + "MetricTimezone":{ + "shape":"AnomalyDetectorMetricTimezone", + "documentation":"

The time zone to use for the metric. This is useful to enable the model to automatically account for daylight savings time changes if the metric is sensitive to such time changes.

To specify a time zone, use the name of the time zone as specified in the standard tz database. For more information, see tz database.

" + } + }, + "documentation":"

The configuration specifies details about how the anomaly detection model is to be trained, including time ranges to exclude from use for training the model and the time zone to use for the metric.

" + }, + "AnomalyDetectorExcludedTimeRanges":{ + "type":"list", + "member":{"shape":"Range"} + }, + "AnomalyDetectorMetricStat":{ + "type":"string", + "max":50, + "pattern":"(SampleCount|Average|Sum|Minimum|Maximum|IQM|(p|tc|tm|ts|wm)(\\d{1,2}(\\.\\d{0,10})?|100)|[ou]\\d+(\\.\\d*)?)(_E|_L|_H)?|(TM|TC|TS|WM)\\(((((\\d{1,2})(\\.\\d{0,10})?|100(\\.0{0,10})?)%)?:((\\d{1,2})(\\.\\d{0,10})?|100(\\.0{0,10})?)%|((\\d{1,2})(\\.\\d{0,10})?|100(\\.0{0,10})?)%:(((\\d{1,2})(\\.\\d{0,10})?|100(\\.0{0,10})?)%)?)\\)|(TM|TC|TS|WM|PR)\\(((\\d+(\\.\\d{0,10})?|(\\d+(\\.\\d{0,10})?[Ee][+-]?\\d+)):((\\d+(\\.\\d{0,10})?|(\\d+(\\.\\d{0,10})?[Ee][+-]?\\d+)))?|((\\d+(\\.\\d{0,10})?|(\\d+(\\.\\d{0,10})?[Ee][+-]?\\d+)))?:(\\d+(\\.\\d{0,10})?|(\\d+(\\.\\d{0,10})?[Ee][+-]?\\d+)))\\)" + }, + "AnomalyDetectorMetricTimezone":{ + "type":"string", + "max":50, + "pattern":".*" + }, + "AnomalyDetectorSearchTerm":{ + "type":"structure", + "members":{ + "SingleMetricSearchTerm":{"shape":"SingleMetricSearchTerm"}, + "MetricMathSearchTerm":{"shape":"MetricMathSearchTerm"} + }, + "internalonly":true + }, + "AnomalyDetectorSearchTerms":{ + "type":"list", + "member":{"shape":"AnomalyDetectorSearchTerm"}, + "internalonly":true, + "max":2 + }, + "AnomalyDetectorStateValue":{ + "type":"string", + "enum":[ + "PENDING_TRAINING", + "TRAINED_INSUFFICIENT_DATA", + "TRAINED" + ] + }, + "AnomalyDetectorType":{ + "type":"string", + "enum":[ + "SINGLE_METRIC", + "METRIC_MATH" + ] + }, + "AnomalyDetectorTypes":{ + "type":"list", + "member":{"shape":"AnomalyDetectorType"}, + "max":2 + }, + "AnomalyDetectors":{ + "type":"list", + "member":{"shape":"AnomalyDetector"} + }, + "AppMonitorArn":{"type":"string"}, + "AppMonitorArns":{ + "type":"list", + "member":{"shape":"AppMonitorArn"} + }, + "AttainmentGoal":{ + "type":"double", + "box":true + }, + "Attribute":{ + "type":"structure", + "members":{ + "Name":{"shape":"AttributeName"}, + "Value":{"shape":"AttributeValue"} + } + }, + "AttributeName":{"type":"string"}, + "AttributeSet":{ + "type":"structure", + "required":["Attributes"], + "members":{ + "ReferenceId":{"shape":"AttributeSetReferenceId"}, + "Attributes":{"shape":"Attributes"} + } + }, + "AttributeSetReferenceId":{"type":"string"}, + "AttributeSets":{ + "type":"list", + "member":{"shape":"AttributeSet"} + }, + "AttributeValue":{"type":"string"}, + "Attributes":{ + "type":"list", + "member":{"shape":"Attribute"} + }, + "AttributesMap":{ + "type":"map", + "key":{"shape":"AttributesMapKey"}, + "value":{"shape":"AttributesMapValue"} + }, + "AttributesMapKey":{"type":"string"}, + "AttributesMapValue":{"type":"string"}, + "AutoDecompose":{"type":"boolean"}, + "AwsQueryErrorMessage":{"type":"string"}, + "BatchFailures":{ + "type":"list", + "member":{"shape":"PartialFailure"} + }, + "BatchGetServiceLevelIndicatorReportInput":{ + "type":"structure", + "required":["Requests"], + "members":{ + "Requests":{"shape":"GetServiceLevelIndicatorReportInputs"} + } + }, + "BatchGetServiceLevelIndicatorReportOutput":{ + "type":"structure", + "required":[ + "Reports", + "Errors" + ], + "members":{ + "Reports":{"shape":"ServiceLevelIndicatorReports"}, + "Errors":{"shape":"ServiceLevelIndicatorReportErrors"} + } + }, + "BatchGetServiceLevelObjectiveBudgetReportInput":{ + "type":"structure", + "required":["Requests"], + "members":{ + "Requests":{"shape":"ServiceLevelObjectiveBudgetReportInputs"} + } + }, + "BatchGetServiceLevelObjectiveBudgetReportOutput":{ + "type":"structure", + "required":[ + "Reports", + "Errors" + ], + "members":{ + "Reports":{"shape":"ServiceLevelObjectiveBudgetReports"}, + "Errors":{"shape":"ServiceLevelObjectiveBudgetReportErrors"} + } + }, + "CalendarInterval":{ + "type":"structure", + "required":[ + "StartTime", + "DurationUnit", + "Duration" + ], + "members":{ + "StartTime":{"shape":"Timestamp"}, + "DurationUnit":{"shape":"DurationUnit"}, + "Duration":{"shape":"CalendarIntervalDuration"} + } + }, + "CalendarIntervalDuration":{ + "type":"integer", + "box":true + }, + "CanaryArn":{"type":"string"}, + "CanaryArns":{ + "type":"list", + "member":{"shape":"CanaryArn"} + }, + "ComparisonOperator":{ + "type":"string", + "enum":[ + "GreaterThanOrEqualToThreshold", + "GreaterThanThreshold", + "LessThanThreshold", + "LessThanOrEqualToThreshold", + "LessThanLowerOrGreaterThanUpperThreshold", + "LessThanLowerThreshold", + "GreaterThanUpperThreshold" + ] + }, + "CompositeAlarm":{ + "type":"structure", + "members":{ + "ActionsEnabled":{ + "shape":"ActionsEnabled", + "documentation":"

Indicates whether actions should be executed during any changes to the alarm state.

" + }, + "AlarmActions":{ + "shape":"ResourceList", + "documentation":"

The actions to execute when this alarm transitions to the ALARM state from any other state. Each action is specified as an Amazon Resource Name (ARN).

" + }, + "AlarmArn":{ + "shape":"AlarmArn", + "documentation":"

The Amazon Resource Name (ARN) of the alarm.

" + }, + "AlarmConfigurationUpdatedTimestamp":{ + "shape":"Timestamp", + "documentation":"

The time stamp of the last update to the alarm configuration.

" + }, + "AlarmDescription":{ + "shape":"AlarmDescription", + "documentation":"

The description of the alarm.

" + }, + "AlarmName":{ + "shape":"AlarmName", + "documentation":"

The name of the alarm.

" + }, + "AlarmRule":{ + "shape":"AlarmRule", + "documentation":"

The rule that this alarm uses to evaluate its alarm state.

" + }, + "CreationId":{ + "shape":"CreationId", + "internalonly":true + }, + "InsufficientDataActions":{ + "shape":"ResourceList", + "documentation":"

The actions to execute when this alarm transitions to the INSUFFICIENT_DATA state from any other state. Each action is specified as an Amazon Resource Name (ARN).

" + }, + "OKActions":{ + "shape":"ResourceList", + "documentation":"

The actions to execute when this alarm transitions to the OK state from any other state. Each action is specified as an Amazon Resource Name (ARN).

" + }, + "StateReason":{ + "shape":"StateReason", + "documentation":"

An explanation for the alarm state, in text format.

" + }, + "StateReasonData":{ + "shape":"StateReasonData", + "documentation":"

An explanation for the alarm state, in JSON format.

" + }, + "StateUpdatedTimestamp":{ + "shape":"Timestamp", + "documentation":"

Tracks the timestamp of any state update, even if StateValue doesn't change.

" + }, + "StateValue":{ + "shape":"StateValue", + "documentation":"

The state value for the alarm.

" + }, + "StateTransitionedTimestamp":{ + "shape":"Timestamp", + "documentation":"

The timestamp of the last change to the alarm's StateValue.

" + }, + "ActionsSuppressedBy":{ + "shape":"ActionsSuppressedBy", + "documentation":"

When the value is ALARM, it means that the actions are suppressed because the suppressor alarm is in ALARM When the value is WaitPeriod, it means that the actions are suppressed because the composite alarm is waiting for the suppressor alarm to go into into the ALARM state. The maximum waiting time is as specified in ActionsSuppressorWaitPeriod. After this time, the composite alarm performs its actions. When the value is ExtensionPeriod, it means that the actions are suppressed because the composite alarm is waiting after the suppressor alarm went out of the ALARM state. The maximum waiting time is as specified in ActionsSuppressorExtensionPeriod. After this time, the composite alarm performs its actions.

" + }, + "ActionsSuppressedReason":{ + "shape":"ActionsSuppressedReason", + "documentation":"

Captures the reason for action suppression.

" + }, + "ActionsSuppressor":{ + "shape":"AlarmArn", + "documentation":"

Actions will be suppressed if the suppressor alarm is in the ALARM state. ActionsSuppressor can be an AlarmName or an Amazon Resource Name (ARN) from an existing alarm.

" + }, + "ActionsSuppressorWaitPeriod":{ + "shape":"SuppressorPeriod", + "documentation":"

The maximum time in seconds that the composite alarm waits for the suppressor alarm to go into the ALARM state. After this time, the composite alarm performs its actions.

WaitPeriod is required only when ActionsSuppressor is specified.

" + }, + "ActionsSuppressorExtensionPeriod":{ + "shape":"SuppressorPeriod", + "documentation":"

The maximum time in seconds that the composite alarm waits after suppressor alarm goes out of the ALARM state. After this time, the composite alarm performs its actions.

ExtensionPeriod is required only when ActionsSuppressor is specified.

" + } + }, + "documentation":"

The details about a composite alarm.

", + "xmlOrder":[ + "ActionsEnabled", + "AlarmActions", + "AlarmArn", + "AlarmConfigurationUpdatedTimestamp", + "AlarmDescription", + "AlarmName", + "AlarmRule", + "CreationId", + "InsufficientDataActions", + "OKActions", + "StateReason", + "StateReasonData", + "StateUpdatedTimestamp", + "StateValue", + "StateTransitionedTimestamp", + "ActionsSuppressedBy", + "ActionsSuppressedReason", + "ActionsSuppressor", + "ActionsSuppressorWaitPeriod", + "ActionsSuppressorExtensionPeriod" + ] + }, + "CompositeAlarms":{ + "type":"list", + "member":{"shape":"CompositeAlarm"} + }, + "ConcurrentModificationException":{ + "type":"structure", + "members":{ + }, + "documentation":"

More than one process tried to modify a resource at the same time.

", + "error":{ + "code":"ConcurrentModificationException", + "httpStatusCode":429, + "senderFault":true + }, + "exception":true + }, + "ConflictException":{ + "type":"structure", + "members":{ + }, + "error":{ + "code":"ConflictException", + "httpStatusCode":409, + "senderFault":true + }, + "exception":true + }, + "CountOnlyRequest":{"type":"boolean"}, + "Counts":{ + "type":"list", + "member":{"shape":"DatapointValue"} + }, + "CreateServiceLevelObjectiveInput":{ + "type":"structure", + "required":[ + "Name", + "SliConfig" + ], + "members":{ + "Name":{"shape":"ServiceLevelObjectiveName"}, + "Description":{"shape":"ServiceLevelObjectiveDescription"}, + "SliConfig":{"shape":"ServiceLevelIndicatorConfig"}, + "Goal":{"shape":"Goal"}, + "PayerToken":{ + "shape":"PayerToken", + "internalonly":true + }, + "Tags":{"shape":"TagList"}, + "InternalId":{ + "shape":"ServiceLevelObjectiveInternalId", + "internalonly":true + } + } + }, + "CreateServiceLevelObjectiveOutput":{ + "type":"structure", + "required":["Slo"], + "members":{ + "Slo":{"shape":"ServiceLevelObjective"} + } + }, + "CreationId":{"type":"string"}, + "CreationIdItem":{ + "type":"structure", + "members":{ + "Arn":{"shape":"AmazonResourceName"}, + "CreationId":{"shape":"CreationId"} + } + }, + "CreationIdItems":{ + "type":"list", + "member":{"shape":"CreationIdItem"} + }, + "CustomMetrics":{ + "type":"structure", + "required":["Metrics"], + "members":{ + "Metrics":{"shape":"MetricDataQueries"} + } + }, + "CustomMetricsConfig":{ + "type":"structure", + "required":["Metrics"], + "members":{ + "Metrics":{"shape":"MetricDataQueries"} + } + }, + "DashboardArn":{"type":"string"}, + "DashboardBody":{"type":"string"}, + "DashboardEntries":{ + "type":"list", + "member":{"shape":"DashboardEntry"} + }, + "DashboardEntry":{ + "type":"structure", + "members":{ + "DashboardName":{ + "shape":"DashboardName", + "documentation":"

The name of the dashboard.

" + }, + "DashboardArn":{ + "shape":"DashboardArn", + "documentation":"

The Amazon Resource Name (ARN) of the dashboard.

" + }, + "LastModified":{ + "shape":"LastModified", + "documentation":"

The time stamp of when the dashboard was last modified, either by an API call or through the console. This number is expressed as the number of milliseconds since Jan 1, 1970 00:00:00 UTC.

" + }, + "Size":{ + "shape":"Size", + "documentation":"

The size of the dashboard, in bytes.

" + } + }, + "documentation":"

Represents a specific dashboard.

" + }, + "DashboardErrorMessage":{"type":"string"}, + "DashboardInvalidInputError":{ + "type":"structure", + "members":{ + "message":{"shape":"DashboardErrorMessage"}, + "dashboardValidationMessages":{"shape":"DashboardValidationMessages"} + }, + "documentation":"

Some part of the dashboard data is invalid.

", + "error":{ + "code":"InvalidParameterInput", + "httpStatusCode":400, + "senderFault":true + }, + "exception":true + }, + "DashboardMaxResults":{"type":"integer"}, + "DashboardName":{"type":"string"}, + "DashboardNamePrefix":{"type":"string"}, + "DashboardNames":{ + "type":"list", + "member":{"shape":"DashboardName"} + }, + "DashboardNotFoundError":{ + "type":"structure", + "members":{ + "message":{"shape":"DashboardErrorMessage"} + }, + "documentation":"

The specified dashboard does not exist.

", + "error":{ + "code":"ResourceNotFound", + "httpStatusCode":404, + "senderFault":true + }, + "exception":true + }, + "DashboardValidationMessage":{ + "type":"structure", + "members":{ + "DataPath":{ + "shape":"DataPath", + "documentation":"

The data path related to the message.

" + }, + "Message":{ + "shape":"Message", + "documentation":"

A message describing the error or warning.

" + } + }, + "documentation":"

An error or warning for the operation.

" + }, + "DashboardValidationMessages":{ + "type":"list", + "member":{"shape":"DashboardValidationMessage"} + }, + "Data":{ + "type":"list", + "member":{"shape":"Datum"} + }, + "DataPath":{"type":"string"}, + "DataSource":{ + "type":"string", + "enum":[ + "SERVICE_OPERATION", + "SERVICE_DEPENDENCY", + "CLIENT", + "CANARY" + ] + }, + "Datapoint":{ + "type":"structure", + "members":{ + "Timestamp":{ + "shape":"Timestamp", + "documentation":"

The time stamp used for the data point.

" + }, + "SampleCount":{ + "shape":"DatapointValue", + "documentation":"

The number of metric values that contributed to the aggregate value of this data point.

" + }, + "Average":{ + "shape":"DatapointValue", + "documentation":"

The average of the metric values that correspond to the data point.

" + }, + "Sum":{ + "shape":"DatapointValue", + "documentation":"

The sum of the metric values for the data point.

" + }, + "Minimum":{ + "shape":"DatapointValue", + "documentation":"

The minimum metric value for the data point.

" + }, + "Maximum":{ + "shape":"DatapointValue", + "documentation":"

The maximum metric value for the data point.

" + }, + "Unit":{ + "shape":"StandardUnit", + "documentation":"

The standard unit for the data point.

" + }, + "ExtendedStatistics":{ + "shape":"DatapointValueMap", + "documentation":"

The percentile statistic for the data point.

" + } + }, + "documentation":"

Encapsulates the statistical data that CloudWatch computes from metric data.

", + "xmlOrder":[ + "Timestamp", + "SampleCount", + "Average", + "Sum", + "Minimum", + "Maximum", + "Unit", + "ExtendedStatistics" + ] + }, + "DatapointValue":{"type":"double"}, + "DatapointValueMap":{ + "type":"map", + "key":{"shape":"ExtendedStatistic"}, + "value":{"shape":"DatapointValue"} + }, + "DatapointValues":{ + "type":"list", + "member":{"shape":"DatapointValue"} + }, + "Datapoints":{ + "type":"list", + "member":{"shape":"Datapoint"} + }, + "DatapointsToAlarm":{ + "type":"integer", + "min":1 + }, + "DatastoreEndpoint":{"type":"string"}, + "DatastoreEndpoints":{ + "type":"list", + "member":{"shape":"DatastoreEndpoint"} + }, + "Datum":{ + "type":"structure", + "members":{ + "Id":{"shape":"TriageDatumId"}, + "Stat":{"shape":"TriageStatistic"}, + "Unit":{"shape":"Unit"}, + "Value":{"shape":"TriageDatumValue"}, + "Error":{"shape":"TriageError"} + } + }, + "DeleteAlarmTemplateInput":{ + "type":"structure", + "required":["Name"], + "members":{ + "Name":{"shape":"AlarmTemplateName"} + } + }, + "DeleteAlarmsAccountInput":{ + "type":"structure", + "required":["AWSAccountId"], + "members":{ + "AWSAccountId":{"shape":"AWSAccountId"} + } + }, + "DeleteAlarmsAccountOutput":{ + "type":"structure", + "members":{ + "IsAccountDeleted":{"shape":"IsAccountDeleted"} + } + }, + "DeleteAlarmsInput":{ + "type":"structure", + "required":["AlarmNames"], + "members":{ + "AlarmNames":{ + "shape":"AlarmNames", + "documentation":"

The alarms to be deleted. Do not enclose the alarm names in quote marks.

" + } + } + }, + "DeleteAnomalyDetectorInput":{ + "type":"structure", + "members":{ + "Namespace":{ + "shape":"Namespace", + "documentation":"

The namespace associated with the anomaly detection model to delete.

", + "deprecated":true, + "deprecatedMessage":"Use SingleMetricAnomalyDetector." + }, + "MetricName":{ + "shape":"MetricName", + "documentation":"

The metric name associated with the anomaly detection model to delete.

", + "deprecated":true, + "deprecatedMessage":"Use SingleMetricAnomalyDetector." + }, + "Dimensions":{ + "shape":"Dimensions", + "documentation":"

The metric dimensions associated with the anomaly detection model to delete.

", + "deprecated":true, + "deprecatedMessage":"Use SingleMetricAnomalyDetector." + }, + "Stat":{ + "shape":"AnomalyDetectorMetricStat", + "documentation":"

The statistic associated with the anomaly detection model to delete.

", + "deprecated":true, + "deprecatedMessage":"Use SingleMetricAnomalyDetector." + }, + "SingleMetricAnomalyDetector":{ + "shape":"SingleMetricAnomalyDetector", + "documentation":"

A single metric anomaly detector to be deleted.

When using SingleMetricAnomalyDetector, you cannot include the following parameters in the same operation:

  • Dimensions,

  • MetricName

  • Namespace

  • Stat

  • the MetricMathAnomalyDetector parameters of DeleteAnomalyDetectorInput

Instead, specify the single metric anomaly detector attributes as part of the SingleMetricAnomalyDetector property.

" + }, + "MetricMathAnomalyDetector":{ + "shape":"MetricMathAnomalyDetector", + "documentation":"

The metric math anomaly detector to be deleted.

When using MetricMathAnomalyDetector, you cannot include following parameters in the same operation:

  • Dimensions,

  • MetricName

  • Namespace

  • Stat

  • the SingleMetricAnomalyDetector parameters of DeleteAnomalyDetectorInput

Instead, specify the metric math anomaly detector attributes as part of the MetricMathAnomalyDetector property.

" + } + } + }, + "DeleteAnomalyDetectorOutput":{ + "type":"structure", + "members":{ + } + }, + "DeleteDashboardsForAccountInput":{ + "type":"structure", + "required":[ + "AccountId", + "DashboardNames" + ], + "members":{ + "AccountId":{"shape":"AccountId"}, + "DashboardNames":{"shape":"DashboardNames"} + } + }, + "DeleteDashboardsForAccountOutput":{ + "type":"structure", + "members":{ + } + }, + "DeleteDashboardsInput":{ + "type":"structure", + "required":["DashboardNames"], + "members":{ + "DashboardNames":{ + "shape":"DashboardNames", + "documentation":"

The dashboards to be deleted. This parameter is required.

" + } + } + }, + "DeleteDashboardsOutput":{ + "type":"structure", + "members":{ + } + }, + "DeleteEmptyMonitors":{"type":"boolean"}, + "DeleteInsightRulesInput":{ + "type":"structure", + "required":["RuleNames"], + "members":{ + "RuleNames":{ + "shape":"InsightRuleNames", + "documentation":"

An array of the rule names to delete. If you need to find out the names of your rules, use DescribeInsightRules.

" + } + } + }, + "DeleteInsightRulesOutput":{ + "type":"structure", + "members":{ + "Failures":{ + "shape":"BatchFailures", + "documentation":"

An array listing the rules that could not be deleted. You cannot delete built-in rules.

" + } + } + }, + "DeleteMetricStreamInput":{ + "type":"structure", + "required":["Name"], + "members":{ + "Name":{ + "shape":"MetricStreamName", + "documentation":"

The name of the metric stream to delete.

" + } + } + }, + "DeleteMetricStreamOutput":{ + "type":"structure", + "members":{ + } + }, + "DeleteServiceLevelObjectiveInput":{ + "type":"structure", + "required":["Name"], + "members":{ + "Name":{"shape":"ServiceLevelObjectiveName"}, + "PayerToken":{ + "shape":"PayerToken", + "internalonly":true + } + } + }, + "DeleteServiceLevelObjectiveOutput":{ + "type":"structure", + "members":{ + } + }, + "DeletedAlarm":{ + "type":"structure", + "required":[ + "AlarmName", + "AlarmCreationId" + ], + "members":{ + "AlarmName":{"shape":"AlarmName"}, + "AlarmCreationId":{"shape":"CreationId"} + } + }, + "DeletedAlarms":{ + "type":"list", + "member":{"shape":"DeletedAlarm"} + }, + "Dependencies":{ + "type":"list", + "member":{"shape":"Dependency"} + }, + "Dependency":{ + "type":"structure", + "required":[ + "DependencyName", + "DependencyTarget" + ], + "members":{ + "DependencyName":{"shape":"DependencyName"}, + "DependencyTarget":{"shape":"DependencyTarget"}, + "OperationPaths":{"shape":"OperationPaths"} + } + }, + "DependencyName":{"type":"string"}, + "DependencyTarget":{"type":"string"}, + "DescribeAlarmHistoryInput":{ + "type":"structure", + "members":{ + "AlarmName":{ + "shape":"AlarmName", + "documentation":"

The name of the alarm.

" + }, + "AlarmTypes":{ + "shape":"AlarmTypes", + "documentation":"

Use this parameter to specify whether you want the operation to return metric alarms or composite alarms. If you omit this parameter, only metric alarms are returned.

" + }, + "HistoryItemType":{ + "shape":"HistoryItemType", + "documentation":"

The type of alarm histories to retrieve.

" + }, + "StartDate":{ + "shape":"Timestamp", + "documentation":"

The starting date to retrieve alarm history.

" + }, + "EndDate":{ + "shape":"Timestamp", + "documentation":"

The ending date to retrieve alarm history.

" + }, + "MaxRecords":{ + "shape":"MaxRecords", + "documentation":"

The maximum number of alarm history records to retrieve.

" + }, + "NextToken":{ + "shape":"NextToken", + "documentation":"

The token returned by a previous call to indicate that there is more data available.

" + }, + "ScanBy":{ + "shape":"ScanBy", + "documentation":"

Specified whether to return the newest or oldest alarm history first. Specify TimestampDescending to have the newest event history returned first, and specify TimestampAscending to have the oldest history returned first.

" + } + } + }, + "DescribeAlarmHistoryOutput":{ + "type":"structure", + "members":{ + "AlarmHistoryItems":{ + "shape":"AlarmHistoryItems", + "documentation":"

The alarm histories, in JSON format.

" + }, + "NextToken":{ + "shape":"NextToken", + "documentation":"

The token that marks the start of the next batch of returned results.

" + } + } + }, + "DescribeAlarmTemplateHistoryInput":{ + "type":"structure", + "required":["Name"], + "members":{ + "Name":{"shape":"AlarmTemplateName"}, + "HistoryItemType":{"shape":"HistoryItemType"}, + "StartDate":{"shape":"Timestamp"}, + "EndDate":{"shape":"Timestamp"}, + "MaxRecords":{"shape":"MaxRecords"}, + "NextToken":{"shape":"NextToken"} + } + }, + "DescribeAlarmTemplateHistoryOutput":{ + "type":"structure", + "members":{ + "HistoryItems":{"shape":"AlarmTemplateHistoryItems"}, + "NextToken":{"shape":"NextToken"} + } + }, + "DescribeAlarmsForActionInternalInput":{ + "type":"structure", + "members":{ + "AWSAccountId":{"shape":"AWSAccountId"}, + "AlarmActionArn":{"shape":"ResourceName"}, + "MaxRecords":{"shape":"MaxRecords"}, + "NextToken":{"shape":"NextToken"} + } + }, + "DescribeAlarmsForActionInternalOutput":{ + "type":"structure", + "members":{ + "CreationIdItems":{"shape":"CreationIdItems"}, + "NextToken":{"shape":"NextToken"} + } + }, + "DescribeAlarmsForMetricInput":{ + "type":"structure", + "required":[ + "MetricName", + "Namespace" + ], + "members":{ + "MetricName":{ + "shape":"MetricName", + "documentation":"

The name of the metric.

" + }, + "Namespace":{ + "shape":"Namespace", + "documentation":"

The namespace of the metric.

" + }, + "Statistic":{ + "shape":"Statistic", + "documentation":"

The statistic for the metric, other than percentiles. For percentile statistics, use ExtendedStatistics.

" + }, + "ExtendedStatistic":{ + "shape":"ExtendedStatistic", + "documentation":"

The percentile statistic for the metric. Specify a value between p0.0 and p100.

" + }, + "Dimensions":{ + "shape":"Dimensions", + "documentation":"

The dimensions associated with the metric. If the metric has any associated dimensions, you must specify them in order for the call to succeed.

" + }, + "Period":{ + "shape":"Period", + "documentation":"

The period, in seconds, over which the statistic is applied.

" + }, + "Unit":{ + "shape":"StandardUnit", + "documentation":"

The unit for the metric.

" + } + } + }, + "DescribeAlarmsForMetricOutput":{ + "type":"structure", + "members":{ + "MetricAlarms":{ + "shape":"MetricAlarms", + "documentation":"

The information for each alarm with the specified metric.

" + } + } + }, + "DescribeAlarmsInput":{ + "type":"structure", + "members":{ + "AlarmNames":{ + "shape":"AlarmNames", + "documentation":"

The names of the alarms to retrieve information about.

" + }, + "AlarmNamePrefix":{ + "shape":"AlarmNamePrefix", + "documentation":"

An alarm name prefix. If you specify this parameter, you receive information about all alarms that have names that start with this prefix.

If this parameter is specified, you cannot specify AlarmNames.

" + }, + "AlarmTypes":{ + "shape":"AlarmTypes", + "documentation":"

Use this parameter to specify whether you want the operation to return metric alarms or composite alarms. If you omit this parameter, only metric alarms are returned.

" + }, + "ChildrenOfAlarmName":{ + "shape":"AlarmName", + "documentation":"

If you use this parameter and specify the name of a composite alarm, the operation returns information about the \"children\" alarms of the alarm you specify. These are the metric alarms and composite alarms referenced in the AlarmRule field of the composite alarm that you specify in ChildrenOfAlarmName. Information about the composite alarm that you name in ChildrenOfAlarmName is not returned.

If you specify ChildrenOfAlarmName, you cannot specify any other parameters in the request except for MaxRecords and NextToken. If you do so, you receive a validation error.

Only the Alarm Name, ARN, StateValue (OK/ALARM/INSUFFICIENT_DATA), and StateUpdatedTimestamp information are returned by this operation when you use this parameter. To get complete information about these alarms, perform another DescribeAlarms operation and specify the parent alarm names in the AlarmNames parameter.

" + }, + "ParentsOfAlarmName":{ + "shape":"AlarmName", + "documentation":"

If you use this parameter and specify the name of a metric or composite alarm, the operation returns information about the \"parent\" alarms of the alarm you specify. These are the composite alarms that have AlarmRule parameters that reference the alarm named in ParentsOfAlarmName. Information about the alarm that you specify in ParentsOfAlarmName is not returned.

If you specify ParentsOfAlarmName, you cannot specify any other parameters in the request except for MaxRecords and NextToken. If you do so, you receive a validation error.

Only the Alarm Name and ARN are returned by this operation when you use this parameter. To get complete information about these alarms, perform another DescribeAlarms operation and specify the parent alarm names in the AlarmNames parameter.

" + }, + "StateValue":{ + "shape":"StateValue", + "documentation":"

Specify this parameter to receive information only about alarms that are currently in the state that you specify.

" + }, + "ActionPrefix":{ + "shape":"ActionPrefix", + "documentation":"

Use this parameter to filter the results of the operation to only those alarms that use a certain alarm action. For example, you could specify the ARN of an SNS topic to find all alarms that send notifications to that topic.

" + }, + "MaxRecords":{ + "shape":"MaxRecords", + "documentation":"

The maximum number of alarm descriptions to retrieve.

" + }, + "NextToken":{ + "shape":"NextToken", + "documentation":"

The token returned by a previous call to indicate that there is more data available.

" + } + } + }, + "DescribeAlarmsOutput":{ + "type":"structure", + "members":{ + "CompositeAlarms":{ + "shape":"CompositeAlarms", + "documentation":"

The information about any composite alarms returned by the operation.

" + }, + "MetricAlarms":{ + "shape":"MetricAlarms", + "documentation":"

The information about any metric alarms returned by the operation.

" + }, + "NextToken":{ + "shape":"NextToken", + "documentation":"

The token that marks the start of the next batch of returned results.

" + } + } + }, + "DescribeAnomalyDetectorsInput":{ + "type":"structure", + "members":{ + "NextToken":{ + "shape":"NextToken", + "documentation":"

Use the token returned by the previous operation to request the next page of results.

" + }, + "MaxResults":{ + "shape":"MaxReturnedResultsCount", + "documentation":"

The maximum number of results to return in one operation. The maximum value that you can specify is 100.

To retrieve the remaining results, make another call with the returned NextToken value.

" + }, + "Namespace":{ + "shape":"Namespace", + "documentation":"

Limits the results to only the anomaly detection models that are associated with the specified namespace.

" + }, + "MetricName":{ + "shape":"MetricName", + "documentation":"

Limits the results to only the anomaly detection models that are associated with the specified metric name. If there are multiple metrics with this name in different namespaces that have anomaly detection models, they're all returned.

" + }, + "Dimensions":{ + "shape":"Dimensions", + "documentation":"

Limits the results to only the anomaly detection models that are associated with the specified metric dimensions. If there are multiple metrics that have these dimensions and have anomaly detection models associated, they're all returned.

" + }, + "AnomalyDetectorTypes":{ + "shape":"AnomalyDetectorTypes", + "documentation":"

The anomaly detector types to request when using DescribeAnomalyDetectorsInput. If empty, defaults to SINGLE_METRIC.

" + }, + "AnomalyDetectorSearchTerms":{ + "shape":"AnomalyDetectorSearchTerms", + "internalonly":true + } + } + }, + "DescribeAnomalyDetectorsOutput":{ + "type":"structure", + "members":{ + "AnomalyDetectors":{ + "shape":"AnomalyDetectors", + "documentation":"

The list of anomaly detection models returned by the operation.

" + }, + "NextToken":{ + "shape":"NextToken", + "documentation":"

A token that you can use in a subsequent operation to retrieve the next set of results.

" + } + } + }, + "DescribeInsightRulesInput":{ + "type":"structure", + "members":{ + "NextToken":{ + "shape":"NextToken", + "documentation":"

Include this value, if it was returned by the previous operation, to get the next set of rules.

" + }, + "MaxResults":{ + "shape":"InsightRuleMaxResults", + "documentation":"

The maximum number of results to return in one operation. If you omit this parameter, the default of 500 is used.

" + } + } + }, + "DescribeInsightRulesOutput":{ + "type":"structure", + "members":{ + "NextToken":{ + "shape":"NextToken", + "documentation":"

If this parameter is present, it is a token that marks the start of the next batch of returned results.

" + }, + "InsightRules":{ + "shape":"InsightRules", + "documentation":"

The rules returned by the operation.

" + } + } + }, + "DescribeMetricStreamsInput":{ + "type":"structure", + "required":[ + "Segment", + "TotalSegments" + ], + "members":{ + "Segment":{"shape":"MetricStreamSegment"}, + "TotalSegments":{"shape":"MetricStreamTotalSegments"}, + "MaxResults":{"shape":"DescribeMetricStreamsMaxResults"}, + "NextToken":{"shape":"NextToken"} + } + }, + "DescribeMetricStreamsMaxResults":{"type":"integer"}, + "DescribeMetricStreamsOutput":{ + "type":"structure", + "members":{ + "MetricStreams":{"shape":"MetricStreams"}, + "NextToken":{"shape":"NextToken"} + } + }, + "DescribeResourceCreationIdsInput":{ + "type":"structure", + "members":{ + "ResourceIdentifiers":{"shape":"ResourceIdentifiers"} + } + }, + "DescribeResourceCreationIdsOutput":{ + "type":"structure", + "members":{ + "CreationIdItems":{"shape":"CreationIdItems"} + } + }, + "DestinationNodeId":{"type":"string"}, + "Dimension":{ + "type":"structure", + "required":[ + "Name", + "Value" + ], + "members":{ + "Name":{ + "shape":"DimensionName", + "documentation":"

The name of the dimension. Dimension names must contain only ASCII characters, must include at least one non-whitespace character, and cannot start with a colon (:). ASCII control characters are not supported as part of dimension names.

" + }, + "Value":{ + "shape":"DimensionValue", + "documentation":"

The value of the dimension. Dimension values must contain only ASCII characters and must include at least one non-whitespace character. ASCII control characters are not supported as part of dimension values.

" + } + }, + "documentation":"

A dimension is a name/value pair that is part of the identity of a metric. Because dimensions are part of the unique identifier for a metric, whenever you add a unique name/value pair to one of your metrics, you are creating a new variation of that metric. For example, many Amazon EC2 metrics publish InstanceId as a dimension name, and the actual instance ID as the value for that dimension.

You can assign up to 30 dimensions to a metric.

", + "xmlOrder":[ + "Name", + "Value" + ] + }, + "DimensionFilter":{ + "type":"structure", + "required":["Name"], + "members":{ + "Name":{ + "shape":"DimensionName", + "documentation":"

The dimension name to be matched.

" + }, + "Value":{ + "shape":"DimensionValue", + "documentation":"

The value of the dimension to be matched.

" + } + }, + "documentation":"

Represents filters for a dimension.

" + }, + "DimensionFilters":{ + "type":"list", + "member":{"shape":"DimensionFilter"}, + "max":10 + }, + "DimensionName":{ + "type":"string", + "max":255, + "min":1 + }, + "DimensionValue":{ + "type":"string", + "max":1024, + "min":1 + }, + "Dimensions":{ + "type":"list", + "member":{"shape":"Dimension"}, + "max":30 + }, + "DisableAlarmActionsInput":{ + "type":"structure", + "required":["AlarmNames"], + "members":{ + "AlarmNames":{ + "shape":"AlarmNames", + "documentation":"

The names of the alarms.

" + } + } + }, + "DisableInsightRulesInput":{ + "type":"structure", + "required":["RuleNames"], + "members":{ + "RuleNames":{ + "shape":"InsightRuleNames", + "documentation":"

An array of the rule names to disable. If you need to find out the names of your rules, use DescribeInsightRules.

" + } + } + }, + "DisableInsightRulesOutput":{ + "type":"structure", + "members":{ + "Failures":{ + "shape":"BatchFailures", + "documentation":"

An array listing the rules that could not be disabled. You cannot disable built-in rules.

" + } + } + }, + "DurationUnit":{ + "type":"string", + "enum":[ + "HOUR", + "DAY", + "WEEK", + "MONTH", + "YEAR" + ] + }, + "EdgeId":{"type":"string"}, + "EnableAlarmActionsInput":{ + "type":"structure", + "required":["AlarmNames"], + "members":{ + "AlarmNames":{ + "shape":"AlarmNames", + "documentation":"

The names of the alarms.

" + } + } + }, + "EnableInsightRulesInput":{ + "type":"structure", + "required":["RuleNames"], + "members":{ + "RuleNames":{ + "shape":"InsightRuleNames", + "documentation":"

An array of the rule names to enable. If you need to find out the names of your rules, use DescribeInsightRules.

" + } + } + }, + "EnableInsightRulesOutput":{ + "type":"structure", + "members":{ + "Failures":{ + "shape":"BatchFailures", + "documentation":"

An array listing the rules that could not be enabled. You cannot disable or enable built-in rules.

" + } + } + }, + "EnableTopologyDiscoveryInput":{ + "type":"structure", + "members":{ + } + }, + "EnableTopologyDiscoveryOutput":{ + "type":"structure", + "members":{ + } + }, + "EndTimeAttainment":{ + "type":"double", + "box":true + }, + "EndTimeBudgetSecondsRemaining":{ + "type":"integer", + "box":true + }, + "Entities":{ + "type":"list", + "member":{"shape":"Entity"} + }, + "Entity":{ + "type":"structure", + "members":{ + "URI":{"shape":"URI"}, + "MetricTemplate":{"shape":"MetricTemplate"}, + "Labels":{"shape":"EntityLabels"} + } + }, + "EntityLabel":{ + "type":"structure", + "required":["Key"], + "members":{ + "Key":{"shape":"LabelKey"}, + "Value":{"shape":"LabelValue"} + } + }, + "EntityLabels":{ + "type":"list", + "member":{"shape":"EntityLabel"} + }, + "ErrorMessage":{ + "type":"string", + "max":255, + "min":1 + }, + "EvaluateLowSampleCountPercentile":{ + "type":"string", + "max":255, + "min":1 + }, + "EvaluationPeriods":{ + "type":"integer", + "min":1 + }, + "EvaluationState":{ + "type":"string", + "enum":["PARTIAL_DATA"] + }, + "ExceptionType":{"type":"string"}, + "ExpressionFunctionOccurrences":{ + "type":"map", + "key":{"shape":"ExpressionFunctionOccurrences_Name"}, + "value":{"shape":"ExpressionFunctionOccurrences_Count"} + }, + "ExpressionFunctionOccurrences_Count":{"type":"integer"}, + "ExpressionFunctionOccurrences_Name":{"type":"string"}, + "ExtendedStatistic":{"type":"string"}, + "ExtendedStatistics":{ + "type":"list", + "member":{"shape":"ExtendedStatistic"}, + "max":10, + "min":1 + }, + "FailureCode":{"type":"string"}, + "FailureDescription":{"type":"string"}, + "FailureResource":{"type":"string"}, + "FaultDescription":{"type":"string"}, + "FetchedTimeSeriesCount":{"type":"integer"}, + "Filter":{ + "type":"structure", + "required":[ + "FilterName", + "FilterOperation", + "FilterValue" + ], + "members":{ + "FilterName":{"shape":"TriageFilterName"}, + "FilterOperation":{"shape":"FilterOperation"}, + "FilterValue":{"shape":"FilterValue"} + } + }, + "FilterOperation":{ + "type":"string", + "enum":["EQUALS"] + }, + "FilterValue":{"type":"string"}, + "Filters":{ + "type":"list", + "member":{"shape":"Filter"} + }, + "GetAlarmTemplateInput":{ + "type":"structure", + "required":["Name"], + "members":{ + "Name":{"shape":"AlarmTemplateName"} + } + }, + "GetAlarmTemplateOutput":{ + "type":"structure", + "members":{ + "Name":{"shape":"AlarmTemplateName"}, + "Description":{"shape":"AlarmTemplateDescription"}, + "Arn":{"shape":"AmazonResourceName"}, + "MetricAlarmConfigurations":{"shape":"MetricAlarmConfigurations"}, + "ResourceType":{"shape":"AlarmTemplateResourceType"}, + "ResourceTag":{"shape":"Tag"}, + "CreationId":{ + "shape":"CreationId", + "internalonly":true + }, + "State":{"shape":"AlarmTemplateState"}, + "StateReason":{"shape":"AlarmTemplateStateReason"} + } + }, + "GetDashboardForAccountInput":{ + "type":"structure", + "required":[ + "AccountId", + "DashboardName" + ], + "members":{ + "AccountId":{"shape":"AccountId"}, + "DashboardName":{"shape":"DashboardName"} + } + }, + "GetDashboardForAccountOutput":{ + "type":"structure", + "members":{ + "DashboardArn":{"shape":"DashboardArn"}, + "DashboardBody":{"shape":"DashboardBody"}, + "DashboardName":{"shape":"DashboardName"} + } + }, + "GetDashboardInput":{ + "type":"structure", + "required":["DashboardName"], + "members":{ + "DashboardName":{ + "shape":"DashboardName", + "documentation":"

The name of the dashboard to be described.

" + } + } + }, + "GetDashboardOutput":{ + "type":"structure", + "members":{ + "DashboardArn":{ + "shape":"DashboardArn", + "documentation":"

The Amazon Resource Name (ARN) of the dashboard.

" + }, + "DashboardBody":{ + "shape":"DashboardBody", + "documentation":"

The detailed information about the dashboard, including what widgets are included and their location on the dashboard. For more information about the DashboardBody syntax, see Dashboard Body Structure and Syntax.

" + }, + "DashboardName":{ + "shape":"DashboardName", + "documentation":"

The name of the dashboard.

" + } + } + }, + "GetEntitiesAction":{ + "type":"string", + "enum":[ + "Select", + "Autocomplete" + ] + }, + "GetEntitiesInput":{ + "type":"structure", + "required":[ + "Action", + "Match" + ], + "members":{ + "Action":{"shape":"GetEntitiesAction"}, + "Match":{"shape":"Match"}, + "LabelSelectors":{"shape":"LabelSelectors"}, + "NextToken":{"shape":"NextToken"}, + "MaxResults":{ + "shape":"PrismaMaxResults", + "internalonly":true + } + } + }, + "GetEntitiesOutput":{ + "type":"structure", + "members":{ + "Entities":{"shape":"Entities"}, + "NextToken":{"shape":"NextToken"} + } + }, + "GetEntitiesResourceType":{ + "type":"string", + "pattern":"AWS::[a-zA-Z0-9]+::\\w+" + }, + "GetInsightRuleContributorsInput":{ + "type":"structure", + "required":[ + "RuleName", + "StartTime", + "EndTime" + ], + "members":{ + "TargetAccountId":{ + "shape":"AccountId", + "internalonly":true + }, + "RuleName":{"shape":"InsightRuleName"}, + "StartTime":{"shape":"Timestamp"}, + "EndTime":{"shape":"Timestamp"}, + "MaxResults":{"shape":"InsightRuleUnboundInteger"}, + "NextToken":{"shape":"NextToken"} + } + }, + "GetInsightRuleContributorsOutput":{ + "type":"structure", + "members":{ + "NextToken":{"shape":"NextToken"}, + "Contributors":{"shape":"InsightRuleListContributors"}, + "KeyLabels":{"shape":"InsightRuleContributorKeyLabels"} + } + }, + "GetInsightRuleReportInput":{ + "type":"structure", + "required":[ + "RuleName", + "StartTime", + "EndTime", + "Period" + ], + "members":{ + "TargetAccountId":{ + "shape":"AccountId", + "internalonly":true + }, + "RuleName":{ + "shape":"InsightRuleName", + "documentation":"

The name of the rule that you want to see data from.

" + }, + "StartTime":{ + "shape":"Timestamp", + "documentation":"

The start time of the data to use in the report. When used in a raw HTTP Query API, it is formatted as yyyy-MM-dd'T'HH:mm:ss. For example, 2019-07-01T23:59:59.

" + }, + "EndTime":{ + "shape":"Timestamp", + "documentation":"

The end time of the data to use in the report. When used in a raw HTTP Query API, it is formatted as yyyy-MM-dd'T'HH:mm:ss. For example, 2019-07-01T23:59:59.

" + }, + "Period":{ + "shape":"Period", + "documentation":"

The period, in seconds, to use for the statistics in the InsightRuleMetricDatapoint results.

" + }, + "MaxContributorCount":{ + "shape":"InsightRuleUnboundInteger", + "documentation":"

The maximum number of contributors to include in the report. The range is 1 to 100. If you omit this, the default of 10 is used.

" + }, + "Metrics":{ + "shape":"InsightRuleMetricList", + "documentation":"

Specifies which metrics to use for aggregation of contributor values for the report. You can specify one or more of the following metrics:

  • UniqueContributors -- the number of unique contributors for each data point.

  • MaxContributorValue -- the value of the top contributor for each data point. The identity of the contributor might change for each data point in the graph.

    If this rule aggregates by COUNT, the top contributor for each data point is the contributor with the most occurrences in that period. If the rule aggregates by SUM, the top contributor is the contributor with the highest sum in the log field specified by the rule's Value, during that period.

  • SampleCount -- the number of data points matched by the rule.

  • Sum -- the sum of the values from all contributors during the time period represented by that data point.

  • Minimum -- the minimum value from a single observation during the time period represented by that data point.

  • Maximum -- the maximum value from a single observation during the time period represented by that data point.

  • Average -- the average value from all contributors during the time period represented by that data point.

" + }, + "OrderBy":{ + "shape":"InsightRuleOrderBy", + "documentation":"

Determines what statistic to use to rank the contributors. Valid values are SUM and MAXIMUM.

" + } + } + }, + "GetInsightRuleReportOutput":{ + "type":"structure", + "members":{ + "KeyLabels":{ + "shape":"InsightRuleContributorKeyLabels", + "documentation":"

An array of the strings used as the keys for this rule. The keys are the dimensions used to classify contributors. If the rule contains more than one key, then each unique combination of values for the keys is counted as a unique contributor.

" + }, + "AggregationStatistic":{ + "shape":"InsightRuleAggregationStatistic", + "documentation":"

Specifies whether this rule aggregates contributor data by COUNT or SUM.

" + }, + "AggregateValue":{ + "shape":"InsightRuleUnboundDouble", + "documentation":"

The sum of the values from all individual contributors that match the rule.

" + }, + "ApproximateUniqueCount":{ + "shape":"InsightRuleUnboundLong", + "documentation":"

An approximate count of the unique contributors found by this rule in this time period.

" + }, + "Contributors":{ + "shape":"InsightRuleContributors", + "documentation":"

An array of the unique contributors found by this rule in this time period. If the rule contains multiple keys, each combination of values for the keys counts as a unique contributor.

" + }, + "MetricDatapoints":{ + "shape":"InsightRuleMetricDatapoints", + "documentation":"

A time series of metric data points that matches the time period in the rule request.

" + }, + "RuleAttributes":{ + "shape":"InsightRuleAttributes", + "internalonly":true + } + } + }, + "GetMetricDataEvaluationMetadata":{ + "type":"structure", + "members":{ + "FetchedTimeSeriesCount":{"shape":"FetchedTimeSeriesCount"}, + "ExpressionFunctionOccurrences":{"shape":"ExpressionFunctionOccurrences"} + } + }, + "GetMetricDataInput":{ + "type":"structure", + "required":[ + "MetricDataQueries", + "StartTime", + "EndTime" + ], + "members":{ + "MetricDataQueries":{ + "shape":"MetricDataQueries", + "documentation":"

The metric queries to be returned. A single GetMetricData call can include as many as 500 MetricDataQuery structures. Each of these structures can specify either a metric to retrieve, a Metrics Insights query, or a math expression to perform on retrieved data.

" + }, + "StartTime":{ + "shape":"Timestamp", + "documentation":"

The time stamp indicating the earliest data to be returned.

The value specified is inclusive; results include data points with the specified time stamp.

CloudWatch rounds the specified time stamp as follows:

  • Start time less than 15 days ago - Round down to the nearest whole minute. For example, 12:32:34 is rounded down to 12:32:00.

  • Start time between 15 and 63 days ago - Round down to the nearest 5-minute clock interval. For example, 12:32:34 is rounded down to 12:30:00.

  • Start time greater than 63 days ago - Round down to the nearest 1-hour clock interval. For example, 12:32:34 is rounded down to 12:00:00.

If you set Period to 5, 10, or 30, the start time of your request is rounded down to the nearest time that corresponds to even 5-, 10-, or 30-second divisions of a minute. For example, if you make a query at (HH:mm:ss) 01:05:23 for the previous 10-second period, the start time of your request is rounded down and you receive data from 01:05:10 to 01:05:20. If you make a query at 15:07:17 for the previous 5 minutes of data, using a period of 5 seconds, you receive data timestamped between 15:02:15 and 15:07:15.

For better performance, specify StartTime and EndTime values that align with the value of the metric's Period and sync up with the beginning and end of an hour. For example, if the Period of a metric is 5 minutes, specifying 12:05 or 12:30 as StartTime can get a faster response from CloudWatch than setting 12:07 or 12:29 as the StartTime.

" + }, + "EndTime":{ + "shape":"Timestamp", + "documentation":"

The time stamp indicating the latest data to be returned.

The value specified is exclusive; results include data points up to the specified time stamp.

For better performance, specify StartTime and EndTime values that align with the value of the metric's Period and sync up with the beginning and end of an hour. For example, if the Period of a metric is 5 minutes, specifying 12:05 or 12:30 as EndTime can get a faster response from CloudWatch than setting 12:07 or 12:29 as the EndTime.

" + }, + "NextToken":{ + "shape":"NextToken", + "documentation":"

Include this value, if it was returned by the previous GetMetricData operation, to get the next set of data points.

" + }, + "ReturnEvaluationMetadata":{ + "shape":"ReturnEvaluationMetadata", + "internalonly":true + }, + "ScanBy":{ + "shape":"ScanBy", + "documentation":"

The order in which data points should be returned. TimestampDescending returns the newest data first and paginates when the MaxDatapoints limit is reached. TimestampAscending returns the oldest data first and paginates when the MaxDatapoints limit is reached.

" + }, + "MaxDatapoints":{ + "shape":"GetMetricDataMaxDatapoints", + "documentation":"

The maximum number of data points the request should return before paginating. If you omit this, the default of 100,800 is used.

" + }, + "LabelOptions":{ + "shape":"LabelOptions", + "documentation":"

This structure includes the Timezone parameter, which you can use to specify your time zone so that the labels of returned data display the correct time for your time zone.

" + } + } + }, + "GetMetricDataLabelTimezone":{"type":"string"}, + "GetMetricDataMaxDatapoints":{"type":"integer"}, + "GetMetricDataOutput":{ + "type":"structure", + "members":{ + "EvaluationMetadata":{ + "shape":"GetMetricDataEvaluationMetadata", + "internalonly":true + }, + "MetricDataResults":{ + "shape":"MetricDataResults", + "documentation":"

The metrics that are returned, including the metric name, namespace, and dimensions.

" + }, + "NextToken":{ + "shape":"NextToken", + "documentation":"

A token that marks the next batch of returned results.

" + }, + "Messages":{ + "shape":"MetricDataResultMessages", + "documentation":"

Contains a message about this GetMetricData operation, if the operation results in such a message. An example of a message that might be returned is Maximum number of allowed metrics exceeded. If there is a message, as much of the operation as possible is still executed.

A message appears here only if it is related to the global GetMetricData operation. Any message about a specific metric returned by the operation appears in the MetricDataResult object returned for that metric.

" + } + } + }, + "GetMetricStatisticsInput":{ + "type":"structure", + "required":[ + "Namespace", + "MetricName", + "StartTime", + "EndTime", + "Period" + ], + "members":{ + "Namespace":{ + "shape":"Namespace", + "documentation":"

The namespace of the metric, with or without spaces.

" + }, + "MetricName":{ + "shape":"MetricName", + "documentation":"

The name of the metric, with or without spaces.

" + }, + "Dimensions":{ + "shape":"Dimensions", + "documentation":"

The dimensions. If the metric contains multiple dimensions, you must include a value for each dimension. CloudWatch treats each unique combination of dimensions as a separate metric. If a specific combination of dimensions was not published, you can't retrieve statistics for it. You must specify the same dimensions that were used when the metrics were created. For an example, see Dimension Combinations in the Amazon CloudWatch User Guide. For more information about specifying dimensions, see Publishing Metrics in the Amazon CloudWatch User Guide.

" + }, + "StartTime":{ + "shape":"Timestamp", + "documentation":"

The time stamp that determines the first data point to return. Start times are evaluated relative to the time that CloudWatch receives the request.

The value specified is inclusive; results include data points with the specified time stamp. In a raw HTTP query, the time stamp must be in ISO 8601 UTC format (for example, 2016-10-03T23:00:00Z).

CloudWatch rounds the specified time stamp as follows:

  • Start time less than 15 days ago - Round down to the nearest whole minute. For example, 12:32:34 is rounded down to 12:32:00.

  • Start time between 15 and 63 days ago - Round down to the nearest 5-minute clock interval. For example, 12:32:34 is rounded down to 12:30:00.

  • Start time greater than 63 days ago - Round down to the nearest 1-hour clock interval. For example, 12:32:34 is rounded down to 12:00:00.

If you set Period to 5, 10, or 30, the start time of your request is rounded down to the nearest time that corresponds to even 5-, 10-, or 30-second divisions of a minute. For example, if you make a query at (HH:mm:ss) 01:05:23 for the previous 10-second period, the start time of your request is rounded down and you receive data from 01:05:10 to 01:05:20. If you make a query at 15:07:17 for the previous 5 minutes of data, using a period of 5 seconds, you receive data timestamped between 15:02:15 and 15:07:15.

" + }, + "EndTime":{ + "shape":"Timestamp", + "documentation":"

The time stamp that determines the last data point to return.

The value specified is exclusive; results include data points up to the specified time stamp. In a raw HTTP query, the time stamp must be in ISO 8601 UTC format (for example, 2016-10-10T23:00:00Z).

" + }, + "Period":{ + "shape":"Period", + "documentation":"

The granularity, in seconds, of the returned data points. For metrics with regular resolution, a period can be as short as one minute (60 seconds) and must be a multiple of 60. For high-resolution metrics that are collected at intervals of less than one minute, the period can be 1, 5, 10, 30, 60, or any multiple of 60. High-resolution metrics are those metrics stored by a PutMetricData call that includes a StorageResolution of 1 second.

If the StartTime parameter specifies a time stamp that is greater than 3 hours ago, you must specify the period as follows or no data points in that time range is returned:

  • Start time between 3 hours and 15 days ago - Use a multiple of 60 seconds (1 minute).

  • Start time between 15 and 63 days ago - Use a multiple of 300 seconds (5 minutes).

  • Start time greater than 63 days ago - Use a multiple of 3600 seconds (1 hour).

" + }, + "Statistics":{ + "shape":"Statistics", + "documentation":"

The metric statistics, other than percentile. For percentile statistics, use ExtendedStatistics. When calling GetMetricStatistics, you must specify either Statistics or ExtendedStatistics, but not both.

" + }, + "ExtendedStatistics":{ + "shape":"ExtendedStatistics", + "documentation":"

The percentile statistics. Specify values between p0.0 and p100. When calling GetMetricStatistics, you must specify either Statistics or ExtendedStatistics, but not both. Percentile statistics are not available for metrics when any of the metric values are negative numbers.

" + }, + "Unit":{ + "shape":"StandardUnit", + "documentation":"

The unit for a given metric. If you omit Unit, all data that was collected with any unit is returned, along with the corresponding units that were specified when the data was reported to CloudWatch. If you specify a unit, the operation returns only data that was collected with that unit specified. If you specify a unit that does not match the data collected, the results of the operation are null. CloudWatch does not perform unit conversions.

" + } + } + }, + "GetMetricStatisticsOutput":{ + "type":"structure", + "members":{ + "Label":{ + "shape":"MetricLabel", + "documentation":"

A label for the specified metric.

" + }, + "Datapoints":{ + "shape":"Datapoints", + "documentation":"

The data points for the specified metric.

" + } + } + }, + "GetMetricStreamInput":{ + "type":"structure", + "required":["Name"], + "members":{ + "Name":{ + "shape":"MetricStreamName", + "documentation":"

The name of the metric stream to retrieve information about.

" + } + } + }, + "GetMetricStreamOutput":{ + "type":"structure", + "members":{ + "Arn":{ + "shape":"AmazonResourceName", + "documentation":"

The ARN of the metric stream.

" + }, + "Name":{ + "shape":"MetricStreamName", + "documentation":"

The name of the metric stream.

" + }, + "IncludeFilters":{ + "shape":"MetricStreamFilters", + "documentation":"

If this array of metric namespaces is present, then these namespaces are the only metric namespaces that are streamed by this metric stream.

" + }, + "ExcludeFilters":{ + "shape":"MetricStreamFilters", + "documentation":"

If this array of metric namespaces is present, then these namespaces are the only metric namespaces that are not streamed by this metric stream. In this case, all other metric namespaces in the account are streamed by this metric stream.

" + }, + "FirehoseArn":{ + "shape":"AmazonResourceName", + "documentation":"

The ARN of the Amazon Kinesis Data Firehose delivery stream that is used by this metric stream.

" + }, + "RoleArn":{ + "shape":"AmazonResourceName", + "documentation":"

The ARN of the IAM role that is used by this metric stream.

" + }, + "State":{ + "shape":"MetricStreamState", + "documentation":"

The state of the metric stream. The possible values are running and stopped.

" + }, + "CreationDate":{ + "shape":"Timestamp", + "documentation":"

The date that the metric stream was created.

" + }, + "LastUpdateDate":{ + "shape":"Timestamp", + "documentation":"

The date of the most recent update to the metric stream's configuration.

" + }, + "OutputFormat":{ + "shape":"MetricStreamOutputFormat", + "documentation":"

The output format for the stream. Valid values are json and opentelemetry0.7. For more information about metric stream output formats, see Metric streams output formats.

" + }, + "StatisticsConfigurations":{ + "shape":"MetricStreamStatisticsConfigurations", + "documentation":"

Each entry in this array displays information about one or more metrics that include additional statistics in the metric stream. For more information about the additional statistics, see CloudWatch statistics definitions.

" + }, + "IncludeLinkedAccountsMetrics":{ + "shape":"IncludeLinkedAccountsMetrics", + "documentation":"

If this is true and this metric stream is in a monitoring account, then the stream includes metrics from source accounts that the monitoring account is linked to.

" + } + } + }, + "GetMetricWidgetImageInput":{ + "type":"structure", + "required":["MetricWidget"], + "members":{ + "MetricWidget":{ + "shape":"MetricWidget", + "documentation":"

A JSON string that defines the bitmap graph to be retrieved. The string includes the metrics to include in the graph, statistics, annotations, title, axis limits, and so on. You can include only one MetricWidget parameter in each GetMetricWidgetImage call.

For more information about the syntax of MetricWidget see GetMetricWidgetImage: Metric Widget Structure and Syntax.

If any metric on the graph could not load all the requested data points, an orange triangle with an exclamation point appears next to the graph legend.

" + }, + "OutputFormat":{ + "shape":"OutputFormat", + "documentation":"

The format of the resulting image. Only PNG images are supported.

The default is png. If you specify png, the API returns an HTTP response with the content-type set to text/xml. The image data is in a MetricWidgetImage field. For example:

<GetMetricWidgetImageResponse xmlns=<URLstring>>

<GetMetricWidgetImageResult>

<MetricWidgetImage>

iVBORw0KGgoAAAANSUhEUgAAAlgAAAGQEAYAAAAip...

</MetricWidgetImage>

</GetMetricWidgetImageResult>

<ResponseMetadata>

<RequestId>6f0d4192-4d42-11e8-82c1-f539a07e0e3b</RequestId>

</ResponseMetadata>

</GetMetricWidgetImageResponse>

The image/png setting is intended only for custom HTTP requests. For most use cases, and all actions using an Amazon Web Services SDK, you should use png. If you specify image/png, the HTTP response has a content-type set to image/png, and the body of the response is a PNG image.

" + } + } + }, + "GetMetricWidgetImageOutput":{ + "type":"structure", + "members":{ + "MetricWidgetImage":{ + "shape":"MetricWidgetImage", + "documentation":"

The image of the graph, in the output format specified. The output is base64-encoded.

" + } + } + }, + "GetServiceDataInput":{ + "type":"structure", + "required":[ + "ServiceId", + "DataSource", + "StartTime", + "EndTime" + ], + "members":{ + "ServiceId":{"shape":"ServiceId"}, + "DataSource":{"shape":"DataSource"}, + "MaxResults":{"shape":"GetServiceDataMaxResults"}, + "NextToken":{"shape":"NextToken"}, + "StartTime":{"shape":"Timestamp"}, + "EndTime":{"shape":"Timestamp"}, + "DataGranularity":{"shape":"TriageAttributes"}, + "Filters":{"shape":"Filters"}, + "Sort":{"shape":"Sort"} + } + }, + "GetServiceDataMaxResults":{ + "type":"integer", + "box":true, + "max":1000, + "min":1 + }, + "GetServiceDataOutput":{ + "type":"structure", + "members":{ + "ServiceData":{"shape":"ServiceData"}, + "TotalCount":{"shape":"ServiceDataTotalCount"}, + "NextToken":{"shape":"NextToken"} + } + }, + "GetServiceInput":{ + "type":"structure", + "required":[ + "StartTime", + "EndTime", + "Id" + ], + "members":{ + "StartTime":{"shape":"Timestamp"}, + "EndTime":{"shape":"Timestamp"}, + "Id":{"shape":"ServiceId"}, + "NextToken":{"shape":"NextToken"} + } + }, + "GetServiceLevelIndicatorReportInput":{ + "type":"structure", + "required":[ + "StartTime", + "EndTime" + ], + "members":{ + "Id":{"shape":"ReferenceId"}, + "StartTime":{"shape":"Timestamp"}, + "EndTime":{"shape":"Timestamp"} + } + }, + "GetServiceLevelIndicatorReportInputs":{ + "type":"list", + "member":{"shape":"GetServiceLevelIndicatorReportInput"}, + "max":50, + "min":1 + }, + "GetServiceLevelIndicatorReportOutput":{ + "type":"structure", + "required":["SliReport"], + "members":{ + "SliReport":{"shape":"ServiceLevelIndicatorReport"} + } + }, + "GetServiceLevelObjectiveBudgetReportInput":{ + "type":"structure", + "required":[ + "Arn", + "StartTime", + "EndTime" + ], + "members":{ + "Arn":{"shape":"ServiceLevelObjectiveArn"}, + "StartTime":{"shape":"Timestamp"}, + "EndTime":{"shape":"Timestamp"} + } + }, + "GetServiceLevelObjectiveInput":{ + "type":"structure", + "required":["Arn"], + "members":{ + "Arn":{"shape":"ServiceLevelObjectiveArn"} + } + }, + "GetServiceLevelObjectiveOutput":{ + "type":"structure", + "required":["Slo"], + "members":{ + "Slo":{"shape":"ServiceLevelObjective"} + } + }, + "GetServiceOutput":{ + "type":"structure", + "required":[ + "Service", + "StartTime", + "EndTime" + ], + "members":{ + "Service":{"shape":"Service"}, + "StartTime":{"shape":"Timestamp"}, + "EndTime":{"shape":"Timestamp"}, + "NextToken":{"shape":"NextToken"} + } + }, + "GetTopologyDiscoveryStatusInput":{ + "type":"structure", + "members":{ + } + }, + "GetTopologyDiscoveryStatusOutput":{ + "type":"structure", + "required":["TopologyDiscoveryStatus"], + "members":{ + "TopologyDiscoveryStatus":{"shape":"TopologyDiscoveryStatus"} + } + }, + "GetTopologyMapInput":{ + "type":"structure", + "required":[ + "StartTime", + "EndTime" + ], + "members":{ + "StartTime":{"shape":"Timestamp"}, + "EndTime":{"shape":"Timestamp"}, + "NextToken":{"shape":"NextToken"} + } + }, + "GetTopologyMapOutput":{ + "type":"structure", + "required":[ + "StartTime", + "EndTime", + "TopologyNodes" + ], + "members":{ + "StartTime":{"shape":"Timestamp"}, + "EndTime":{"shape":"Timestamp"}, + "TopologyNodes":{"shape":"TopologyNodes"}, + "TopologyEdges":{"shape":"TopologyEdges"}, + "AggregatedNodes":{"shape":"AggregatedNodes"}, + "NextToken":{"shape":"NextToken"} + } + }, + "Goal":{ + "type":"structure", + "members":{ + "Interval":{"shape":"Interval"}, + "AttainmentGoal":{"shape":"AttainmentGoal"}, + "WarningThreshold":{"shape":"WarningThreshold"} + } + }, + "HistoryData":{ + "type":"string", + "max":4095, + "min":1 + }, + "HistoryItemType":{ + "type":"string", + "enum":[ + "ConfigurationUpdate", + "StateUpdate", + "Action" + ] + }, + "HistorySummary":{ + "type":"string", + "max":255, + "min":1 + }, + "HostName":{"type":"string"}, + "IncludeLinkedAccounts":{"type":"boolean"}, + "IncludeLinkedAccountsMetrics":{"type":"boolean"}, + "InsightRule":{ + "type":"structure", + "required":[ + "Name", + "State", + "Schema", + "Definition" + ], + "members":{ + "Name":{ + "shape":"InsightRuleName", + "documentation":"

The name of the rule.

" + }, + "State":{ + "shape":"InsightRuleState", + "documentation":"

Indicates whether the rule is enabled or disabled.

" + }, + "DisableAt":{"shape":"Timestamp"}, + "DeleteAt":{"shape":"Timestamp"}, + "Schema":{ + "shape":"InsightRuleSchema", + "documentation":"

For rules that you create, this is always {\"Name\": \"CloudWatchLogRule\", \"Version\": 1}. For managed rules, this is {\"Name\": \"ServiceLogRule\", \"Version\": 1}

" + }, + "Definition":{ + "shape":"InsightRuleDefinition", + "documentation":"

The definition of the rule, as a JSON object. The definition contains the keywords used to define contributors, the value to aggregate on if this rule returns a sum instead of a count, and the filters. For details on the valid syntax, see Contributor Insights Rule Syntax.

" + }, + "ManagedRule":{ + "shape":"InsightRuleIsManaged", + "documentation":"

An optional built-in rule that Amazon Web Services manages.

" + } + }, + "documentation":"

This structure contains the definition for a Contributor Insights rule. For more information about this rule, see Using Constributor Insights to analyze high-cardinality data in the Amazon CloudWatch User Guide.

" + }, + "InsightRuleAggregationStatistic":{"type":"string"}, + "InsightRuleAttribute":{ + "type":"string", + "enum":["PUBLISH_PER_CONTRIBUTOR_METRICS"] + }, + "InsightRuleAttributes":{ + "type":"list", + "member":{"shape":"InsightRuleAttribute"} + }, + "InsightRuleBinaryData":{"type":"blob"}, + "InsightRuleContributor":{ + "type":"structure", + "required":[ + "Keys", + "ApproximateAggregateValue", + "Datapoints" + ], + "members":{ + "Keys":{ + "shape":"InsightRuleContributorKeys", + "documentation":"

One of the log entry field keywords that is used to define contributors for this rule.

" + }, + "ApproximateAggregateValue":{ + "shape":"InsightRuleUnboundDouble", + "documentation":"

An approximation of the aggregate value that comes from this contributor.

" + }, + "Datapoints":{ + "shape":"InsightRuleContributorDatapoints", + "documentation":"

An array of the data points where this contributor is present. Only the data points when this contributor appeared are included in the array.

" + } + }, + "documentation":"

One of the unique contributors found by a Contributor Insights rule. If the rule contains multiple keys, then a unique contributor is a unique combination of values from all the keys in the rule.

If the rule contains a single key, then each unique contributor is each unique value for this key.

For more information, see GetInsightRuleReport.

" + }, + "InsightRuleContributorDatapoint":{ + "type":"structure", + "required":[ + "Timestamp", + "ApproximateValue" + ], + "members":{ + "Timestamp":{ + "shape":"Timestamp", + "documentation":"

The timestamp of the data point.

" + }, + "ApproximateValue":{ + "shape":"InsightRuleUnboundDouble", + "documentation":"

The approximate value that this contributor added during this timestamp.

" + } + }, + "documentation":"

One data point related to one contributor.

For more information, see GetInsightRuleReport and InsightRuleContributor.

" + }, + "InsightRuleContributorDatapoints":{ + "type":"list", + "member":{"shape":"InsightRuleContributorDatapoint"} + }, + "InsightRuleContributorKey":{"type":"string"}, + "InsightRuleContributorKeyLabel":{"type":"string"}, + "InsightRuleContributorKeyLabels":{ + "type":"list", + "member":{"shape":"InsightRuleContributorKeyLabel"} + }, + "InsightRuleContributorKeys":{ + "type":"list", + "member":{"shape":"InsightRuleContributorKey"} + }, + "InsightRuleContributors":{ + "type":"list", + "member":{"shape":"InsightRuleContributor"} + }, + "InsightRuleDefinition":{ + "type":"string", + "max":8192, + "min":1, + "pattern":"[\\x00-\\x7F]+" + }, + "InsightRuleIsManaged":{"type":"boolean"}, + "InsightRuleListContributor":{ + "type":"structure", + "required":[ + "Keys", + "Value" + ], + "members":{ + "Keys":{"shape":"InsightRuleContributorKeys"}, + "Value":{"shape":"InsightRuleUnboundDouble"} + }, + "internalonly":true + }, + "InsightRuleListContributors":{ + "type":"list", + "member":{"shape":"InsightRuleListContributor"}, + "internalonly":true + }, + "InsightRuleMaxResults":{ + "type":"integer", + "max":500, + "min":1 + }, + "InsightRuleMetricDatapoint":{ + "type":"structure", + "required":["Timestamp"], + "members":{ + "Timestamp":{ + "shape":"Timestamp", + "documentation":"

The timestamp of the data point.

" + }, + "UniqueContributors":{ + "shape":"InsightRuleUnboundDouble", + "documentation":"

The number of unique contributors who published data during this timestamp.

This statistic is returned only if you included it in the Metrics array in your request.

" + }, + "MaxContributorValue":{ + "shape":"InsightRuleUnboundDouble", + "documentation":"

The maximum value provided by one contributor during this timestamp. Each timestamp is evaluated separately, so the identity of the max contributor could be different for each timestamp.

This statistic is returned only if you included it in the Metrics array in your request.

" + }, + "SampleCount":{ + "shape":"InsightRuleUnboundDouble", + "documentation":"

The number of occurrences that matched the rule during this data point.

This statistic is returned only if you included it in the Metrics array in your request.

" + }, + "Average":{ + "shape":"InsightRuleUnboundDouble", + "documentation":"

The average value from all contributors during the time period represented by that data point.

This statistic is returned only if you included it in the Metrics array in your request.

" + }, + "Sum":{ + "shape":"InsightRuleUnboundDouble", + "documentation":"

The sum of the values from all contributors during the time period represented by that data point.

This statistic is returned only if you included it in the Metrics array in your request.

" + }, + "Minimum":{ + "shape":"InsightRuleUnboundDouble", + "documentation":"

The minimum value from a single contributor during the time period represented by that data point.

This statistic is returned only if you included it in the Metrics array in your request.

" + }, + "Maximum":{ + "shape":"InsightRuleUnboundDouble", + "documentation":"

The maximum value from a single occurence from a single contributor during the time period represented by that data point.

This statistic is returned only if you included it in the Metrics array in your request.

" + } + }, + "documentation":"

One data point from the metric time series returned in a Contributor Insights rule report.

For more information, see GetInsightRuleReport.

" + }, + "InsightRuleMetricDatapoints":{ + "type":"list", + "member":{"shape":"InsightRuleMetricDatapoint"} + }, + "InsightRuleMetricList":{ + "type":"list", + "member":{"shape":"InsightRuleMetricName"} + }, + "InsightRuleMetricName":{ + "type":"string", + "max":32, + "min":1, + "pattern":"[\\x20-\\x7E]+" + }, + "InsightRuleName":{ + "type":"string", + "max":128, + "min":1, + "pattern":"[\\x20-\\x7E]+" + }, + "InsightRuleNames":{ + "type":"list", + "member":{"shape":"InsightRuleName"} + }, + "InsightRuleOrderBy":{ + "type":"string", + "max":32, + "min":1, + "pattern":"[\\x20-\\x7E]+" + }, + "InsightRuleSchema":{"type":"string"}, + "InsightRuleState":{ + "type":"string", + "max":32, + "min":1, + "pattern":"[\\x20-\\x7E]+" + }, + "InsightRuleTtl":{ + "type":"structure", + "members":{ + "RuleName":{"shape":"InsightRuleName"}, + "DisableAt":{"shape":"Timestamp"}, + "DeleteAt":{"shape":"Timestamp"} + } + }, + "InsightRuleUnboundDouble":{"type":"double"}, + "InsightRuleUnboundInteger":{"type":"integer"}, + "InsightRuleUnboundLong":{"type":"long"}, + "InsightRules":{ + "type":"list", + "member":{"shape":"InsightRule"} + }, + "InsightRulesTtl":{ + "type":"list", + "member":{"shape":"InsightRuleTtl"} + }, + "InternalServiceFault":{ + "type":"structure", + "members":{ + "Message":{ + "shape":"FaultDescription", + "documentation":"

" + } + }, + "documentation":"

Request processing has failed due to some unknown error, exception, or failure.

", + "error":{ + "code":"InternalServiceError", + "httpStatusCode":500 + }, + "exception":true, + "xmlOrder":["Message"] + }, + "Interval":{ + "type":"structure", + "members":{ + "RollingInterval":{"shape":"RollingInterval"}, + "CalendarInterval":{"shape":"CalendarInterval"} + }, + "union":true + }, + "InvalidFormatFault":{ + "type":"structure", + "members":{ + "message":{ + "shape":"ErrorMessage", + "documentation":"

" + } + }, + "documentation":"

Data was not syntactically valid JSON.

", + "error":{ + "code":"InvalidFormat", + "httpStatusCode":400, + "senderFault":true + }, + "exception":true + }, + "InvalidNextToken":{ + "type":"structure", + "members":{ + "message":{ + "shape":"ErrorMessage", + "documentation":"

" + } + }, + "documentation":"

The next token specified is invalid.

", + "error":{ + "code":"InvalidNextToken", + "httpStatusCode":400, + "senderFault":true + }, + "exception":true + }, + "InvalidParameterCombinationException":{ + "type":"structure", + "members":{ + "message":{ + "shape":"AwsQueryErrorMessage", + "documentation":"

" + } + }, + "documentation":"

Parameters were used together that cannot be used together.

", + "error":{ + "code":"InvalidParameterCombination", + "httpStatusCode":400, + "senderFault":true + }, + "exception":true, + "synthetic":true + }, + "InvalidParameterValueException":{ + "type":"structure", + "members":{ + "message":{ + "shape":"AwsQueryErrorMessage", + "documentation":"

" + } + }, + "documentation":"

The value of an input parameter is bad or out-of-range.

", + "error":{ + "code":"InvalidParameterValue", + "httpStatusCode":400, + "senderFault":true + }, + "exception":true, + "synthetic":true + }, + "IsAccountDeleted":{"type":"boolean"}, + "LabelKey":{ + "type":"string", + "max":128, + "min":1 + }, + "LabelOptions":{ + "type":"structure", + "members":{ + "Timezone":{ + "shape":"GetMetricDataLabelTimezone", + "documentation":"

The time zone to use for metric data return in this operation. The format is + or - followed by four digits. The first two digits indicate the number of hours ahead or behind of UTC, and the final two digits are the number of minutes. For example, +0130 indicates a time zone that is 1 hour and 30 minutes ahead of UTC. The default is +0000.

" + } + }, + "documentation":"

This structure includes the Timezone parameter, which you can use to specify your time zone so that the labels that are associated with returned metrics display the correct time for your time zone.

The Timezone value affects a label only if you have a time-based dynamic expression in the label. For more information about dynamic expressions in labels, see Using Dynamic Labels.

" + }, + "LabelSelector":{ + "type":"string", + "max":128, + "min":1 + }, + "LabelSelectors":{ + "type":"list", + "member":{"shape":"LabelSelector"} + }, + "LabelValue":{ + "type":"string", + "max":256, + "min":0 + }, + "LastModified":{"type":"timestamp"}, + "LimitExceededException":{ + "type":"structure", + "members":{ + }, + "documentation":"

The operation exceeded one or more limits.

", + "error":{ + "code":"LimitExceededException", + "httpStatusCode":400, + "senderFault":true + }, + "exception":true + }, + "LimitExceededFault":{ + "type":"structure", + "members":{ + "message":{ + "shape":"ErrorMessage", + "documentation":"

" + } + }, + "documentation":"

The quota for alarms for this customer has already been reached.

", + "error":{ + "code":"LimitExceeded", + "httpStatusCode":400, + "senderFault":true + }, + "exception":true + }, + "ListAlarmTemplatesInput":{ + "type":"structure", + "members":{ + "NamePrefix":{"shape":"AlarmTemplateNamePrefix"}, + "ResourceType":{"shape":"AlarmTemplateResourceType"}, + "ResourceTag":{"shape":"Tag"}, + "NextToken":{"shape":"NextToken"}, + "MaxRecords":{"shape":"MaxRecords"} + } + }, + "ListAlarmTemplatesOutput":{ + "type":"structure", + "members":{ + "AlarmTemplateEntries":{"shape":"AlarmTemplateEntries"}, + "NextToken":{"shape":"NextToken"} + } + }, + "ListDashboardsForAccountInput":{ + "type":"structure", + "required":["AccountId"], + "members":{ + "AccountId":{"shape":"AccountId"}, + "DashboardNamePrefix":{"shape":"DashboardNamePrefix"}, + "NextToken":{"shape":"NextToken"}, + "MaxResults":{ + "shape":"DashboardMaxResults", + "internalonly":true + } + } + }, + "ListDashboardsForAccountOutput":{ + "type":"structure", + "members":{ + "DashboardEntries":{"shape":"DashboardEntries"}, + "NextToken":{"shape":"NextToken"} + } + }, + "ListDashboardsInput":{ + "type":"structure", + "members":{ + "DashboardNamePrefix":{ + "shape":"DashboardNamePrefix", + "documentation":"

If you specify this parameter, only the dashboards with names starting with the specified string are listed. The maximum length is 255, and valid characters are A-Z, a-z, 0-9, \".\", \"-\", and \"_\".

" + }, + "NextToken":{ + "shape":"NextToken", + "documentation":"

The token returned by a previous call to indicate that there is more data available.

" + }, + "MaxResults":{ + "shape":"DashboardMaxResults", + "internalonly":true + } + } + }, + "ListDashboardsOutput":{ + "type":"structure", + "members":{ + "DashboardEntries":{ + "shape":"DashboardEntries", + "documentation":"

The list of matching dashboards.

" + }, + "NextToken":{ + "shape":"NextToken", + "documentation":"

The token that marks the start of the next batch of returned results.

" + } + } + }, + "ListHostInfoOutput":{ + "type":"structure", + "members":{ + "HostName":{"shape":"HostName"}, + "StackName":{"shape":"StackName"}, + "Marketplace":{"shape":"Marketplace"}, + "Region":{"shape":"Region"}, + "SdbDatastoreEndpoints":{"shape":"SdbDatastoreEndpoints"}, + "DatastoreEndpoints":{"shape":"DatastoreEndpoints"}, + "AmpQueues":{"shape":"AmpQueues"} + } + }, + "ListInsightRuleVendedResourcesInput":{ + "type":"structure", + "required":["ResourceType"], + "members":{ + "ResourceType":{"shape":"VendedResourceType"}, + "NextToken":{"shape":"NextToken"}, + "MaxResults":{"shape":"InsightRuleMaxResults"} + } + }, + "ListInsightRuleVendedResourcesOutput":{ + "type":"structure", + "members":{ + "VendedResourceRuleMappings":{"shape":"VendedResourceRuleMappings"}, + "NextToken":{"shape":"NextToken"} + } + }, + "ListManagedInsightRulesInput":{ + "type":"structure", + "required":["ResourceARN"], + "members":{ + "TargetAccountId":{ + "shape":"AccountId", + "internalonly":true + }, + "ResourceARN":{ + "shape":"AmazonResourceName", + "documentation":"

The ARN of an Amazon Web Services resource that has managed Contributor Insights rules.

" + }, + "NextToken":{ + "shape":"NextToken", + "documentation":"

Include this value to get the next set of rules if the value was returned by the previous operation.

" + }, + "MaxResults":{ + "shape":"InsightRuleMaxResults", + "documentation":"

The maximum number of results to return in one operation. If you omit this parameter, the default number is used. The default number is 100.

" + } + } + }, + "ListManagedInsightRulesOutput":{ + "type":"structure", + "members":{ + "ManagedRules":{ + "shape":"ManagedRuleDescriptions", + "documentation":"

The managed rules that are available for the specified Amazon Web Services resource.

" + }, + "NextToken":{ + "shape":"NextToken", + "documentation":"

Include this value to get the next set of rules if the value was returned by the previous operation.

" + } + } + }, + "ListMetricStreamsInput":{ + "type":"structure", + "members":{ + "NextToken":{ + "shape":"NextToken", + "documentation":"

Include this value, if it was returned by the previous call, to get the next set of metric streams.

" + }, + "MaxResults":{ + "shape":"ListMetricStreamsMaxResults", + "documentation":"

The maximum number of results to return in one operation.

" + } + } + }, + "ListMetricStreamsMaxResults":{ + "type":"integer", + "max":500, + "min":1 + }, + "ListMetricStreamsOutput":{ + "type":"structure", + "members":{ + "NextToken":{ + "shape":"NextToken", + "documentation":"

The token that marks the start of the next batch of returned results. You can use this token in a subsequent operation to get the next batch of results.

" + }, + "Entries":{ + "shape":"MetricStreamEntries", + "documentation":"

The array of metric stream information.

" + } + } + }, + "ListMetricsInput":{ + "type":"structure", + "members":{ + "Namespace":{ + "shape":"Namespace", + "documentation":"

The metric namespace to filter against. Only the namespace that matches exactly will be returned.

" + }, + "MetricName":{ + "shape":"MetricName", + "documentation":"

The name of the metric to filter against. Only the metrics with names that match exactly will be returned.

" + }, + "Dimensions":{ + "shape":"DimensionFilters", + "documentation":"

The dimensions to filter against. Only the dimensions that match exactly will be returned.

" + }, + "NextToken":{ + "shape":"NextToken", + "documentation":"

The token returned by a previous call to indicate that there is more data available.

" + }, + "RecentlyActive":{ + "shape":"RecentlyActive", + "documentation":"

To filter the results to show only metrics that have had data points published in the past three hours, specify this parameter with a value of PT3H. This is the only valid value for this parameter.

The results that are returned are an approximation of the value you specify. There is a low probability that the returned results include metrics with last published data as much as 40 minutes more than the specified time interval.

" + }, + "TotalSegments":{ + "shape":"TotalSegments", + "internalonly":true + }, + "SegmentId":{ + "shape":"SegmentId", + "internalonly":true + }, + "CountOnlyRequest":{ + "shape":"CountOnlyRequest", + "internalonly":true + }, + "IncludeLinkedAccounts":{ + "shape":"IncludeLinkedAccounts", + "documentation":"

If you are using this operation in a monitoring account, specify true to include metrics from source accounts in the returned data.

The default is false.

" + }, + "OwningAccount":{ + "shape":"AccountId", + "documentation":"

When you use this operation in a monitoring account, use this field to return metrics only from one source account. To do so, specify that source account ID in this field, and also specify true for IncludeLinkedAccounts.

" + } + } + }, + "ListMetricsOutput":{ + "type":"structure", + "members":{ + "Metrics":{ + "shape":"Metrics", + "documentation":"

The metrics that match your request.

" + }, + "NextToken":{ + "shape":"NextToken", + "documentation":"

The token that marks the start of the next batch of returned results.

" + }, + "TotalMetricsCount":{ + "shape":"TotalMetricsCount", + "internalonly":true + }, + "OwningAccounts":{ + "shape":"OwningAccounts", + "documentation":"

If you are using this operation in a monitoring account, this array contains the account IDs of the source accounts where the metrics in the returned data are from.

This field is a 1:1 mapping between each metric that is returned and the ID of the owning account.

" + } + }, + "xmlOrder":[ + "Metrics", + "NextToken", + "TotalMetricsCount", + "OwningAccounts" + ] + }, + "ListServiceLevelObjectivesInput":{ + "type":"structure", + "members":{ + "ServiceId":{"shape":"ServiceId"}, + "OperationName":{"shape":"OperationName"}, + "MaxResults":{"shape":"ListServiceLevelObjectivesMaxResults"}, + "NextToken":{"shape":"NextToken"} + } + }, + "ListServiceLevelObjectivesMaxResults":{ + "type":"integer", + "box":true, + "max":50, + "min":1 + }, + "ListServiceLevelObjectivesOutput":{ + "type":"structure", + "members":{ + "SloSummaries":{"shape":"ServiceLevelObjectiveSummaries"}, + "NextToken":{"shape":"NextToken"} + } + }, + "ListServicesInput":{ + "type":"structure", + "required":[ + "StartTime", + "EndTime" + ], + "members":{ + "StartTime":{"shape":"Timestamp"}, + "EndTime":{"shape":"Timestamp"}, + "MaxResults":{"shape":"ListServicesMaxResults"}, + "NextToken":{"shape":"NextToken"} + } + }, + "ListServicesMaxResults":{ + "type":"integer", + "box":true, + "max":100, + "min":1 + }, + "ListServicesOutput":{ + "type":"structure", + "required":[ + "StartTime", + "EndTime", + "ServiceSummaries", + "AttributeSets" + ], + "members":{ + "StartTime":{"shape":"Timestamp"}, + "EndTime":{"shape":"Timestamp"}, + "ServiceSummaries":{"shape":"ServiceSummaries"}, + "AttributeSets":{"shape":"AttributeSets"}, + "NextToken":{"shape":"NextToken"} + } + }, + "ListTagsForResourceInput":{ + "type":"structure", + "required":["ResourceARN"], + "members":{ + "ResourceARN":{ + "shape":"AmazonResourceName", + "documentation":"

The ARN of the CloudWatch resource that you want to view tags for.

The ARN format of an alarm is arn:aws:cloudwatch:Region:account-id:alarm:alarm-name

The ARN format of a Contributor Insights rule is arn:aws:cloudwatch:Region:account-id:insight-rule:insight-rule-name

For more information about ARN format, see Resource Types Defined by Amazon CloudWatch in the Amazon Web Services General Reference.

" + } + } + }, + "ListTagsForResourceOutput":{ + "type":"structure", + "members":{ + "Tags":{ + "shape":"TagList", + "documentation":"

The list of tag keys and values associated with the resource you specified.

" + } + } + }, + "ManagedRule":{ + "type":"structure", + "required":[ + "TemplateName", + "ResourceARN" + ], + "members":{ + "TemplateName":{ + "shape":"TemplateName", + "documentation":"

The template name for the managed Contributor Insights rule, as returned by ListManagedInsightRules.

" + }, + "ResourceARN":{ + "shape":"AmazonResourceName", + "documentation":"

The ARN of an Amazon Web Services resource that has managed Contributor Insights rules.

" + }, + "Tags":{ + "shape":"TagList", + "documentation":"

A list of key-value pairs that you can associate with a managed Contributor Insights rule. You can associate as many as 50 tags with a rule. Tags can help you organize and categorize your resources. You also can use them to scope user permissions by granting a user permission to access or change only the resources that have certain tag values. To associate tags with a rule, you must have the cloudwatch:TagResource permission in addition to the cloudwatch:PutInsightRule permission. If you are using this operation to update an existing Contributor Insights rule, any tags that you specify in this parameter are ignored. To change the tags of an existing rule, use TagResource.

" + } + }, + "documentation":"

Contains the information that's required to enable a managed Contributor Insights rule for an Amazon Web Services resource.

" + }, + "ManagedRuleDescription":{ + "type":"structure", + "members":{ + "TemplateName":{ + "shape":"TemplateName", + "documentation":"

The template name for the managed rule. Used to enable managed rules using PutManagedInsightRules.

" + }, + "ResourceARN":{ + "shape":"AmazonResourceName", + "documentation":"

If a managed rule is enabled, this is the ARN for the related Amazon Web Services resource.

" + }, + "RuleState":{ + "shape":"ManagedRuleState", + "documentation":"

Describes the state of a managed rule. If present, it contains information about the Contributor Insights rule that contains information about the related Amazon Web Services resource.

" + } + }, + "documentation":"

Contains information about managed Contributor Insights rules, as returned by ListManagedInsightRules.

" + }, + "ManagedRuleDescriptions":{ + "type":"list", + "member":{"shape":"ManagedRuleDescription"} + }, + "ManagedRuleState":{ + "type":"structure", + "required":[ + "RuleName", + "State" + ], + "members":{ + "RuleName":{ + "shape":"InsightRuleName", + "documentation":"

The name of the Contributor Insights rule that contains data for the specified Amazon Web Services resource.

" + }, + "State":{ + "shape":"InsightRuleState", + "documentation":"

Indicates whether the rule is enabled or disabled.

" + } + }, + "documentation":"

The status of a managed Contributor Insights rule.

" + }, + "ManagedRules":{ + "type":"list", + "member":{"shape":"ManagedRule"} + }, + "Marketplace":{"type":"string"}, + "Match":{ + "type":"structure", + "required":["ResourceType"], + "members":{ + "ResourceType":{"shape":"GetEntitiesResourceType"}, + "Labels":{"shape":"EntityLabels"} + } + }, + "MaxRecords":{ + "type":"integer", + "max":100, + "min":1 + }, + "MaxReturnedResultsCount":{ + "type":"integer", + "min":1 + }, + "Message":{"type":"string"}, + "MessageData":{ + "type":"structure", + "members":{ + "Code":{ + "shape":"MessageDataCode", + "documentation":"

The error code or status code associated with the message.

" + }, + "Value":{ + "shape":"MessageDataValue", + "documentation":"

The message text.

" + } + }, + "documentation":"

A message returned by the GetMetricDataAPI, including a code and a description.

If a cross-Region GetMetricData operation fails with a code of Forbidden and a value of Authentication too complex to retrieve cross region data, you can correct the problem by running the GetMetricData operation in the same Region where the metric data is.

" + }, + "MessageDataCode":{"type":"string"}, + "MessageDataValue":{"type":"string"}, + "Metric":{ + "type":"structure", + "members":{ + "Namespace":{ + "shape":"Namespace", + "documentation":"

The namespace of the metric.

" + }, + "MetricName":{ + "shape":"MetricName", + "documentation":"

The name of the metric. This is a required field.

" + }, + "Dimensions":{ + "shape":"Dimensions", + "documentation":"

The dimensions for the metric.

" + } + }, + "documentation":"

Represents a specific metric.

", + "xmlOrder":[ + "Namespace", + "MetricName", + "Dimensions" + ] + }, + "MetricAlarm":{ + "type":"structure", + "members":{ + "AlarmName":{ + "shape":"AlarmName", + "documentation":"

The name of the alarm.

" + }, + "AlarmArn":{ + "shape":"AlarmArn", + "documentation":"

The Amazon Resource Name (ARN) of the alarm.

" + }, + "AlarmDescription":{ + "shape":"AlarmDescription", + "documentation":"

The description of the alarm.

" + }, + "AlarmConfigurationUpdatedTimestamp":{ + "shape":"Timestamp", + "documentation":"

The time stamp of the last update to the alarm configuration.

" + }, + "ActionsEnabled":{ + "shape":"ActionsEnabled", + "documentation":"

Indicates whether actions should be executed during any changes to the alarm state.

" + }, + "OKActions":{ + "shape":"ResourceList", + "documentation":"

The actions to execute when this alarm transitions to the OK state from any other state. Each action is specified as an Amazon Resource Name (ARN).

" + }, + "AlarmActions":{ + "shape":"ResourceList", + "documentation":"

The actions to execute when this alarm transitions to the ALARM state from any other state. Each action is specified as an Amazon Resource Name (ARN).

" + }, + "InsufficientDataActions":{ + "shape":"ResourceList", + "documentation":"

The actions to execute when this alarm transitions to the INSUFFICIENT_DATA state from any other state. Each action is specified as an Amazon Resource Name (ARN).

" + }, + "StateValue":{ + "shape":"StateValue", + "documentation":"

The state value for the alarm.

" + }, + "StateReason":{ + "shape":"StateReason", + "documentation":"

An explanation for the alarm state, in text format.

" + }, + "StateReasonData":{ + "shape":"StateReasonData", + "documentation":"

An explanation for the alarm state, in JSON format.

" + }, + "StateUpdatedTimestamp":{ + "shape":"Timestamp", + "documentation":"

The time stamp of the last update to the value of either the StateValue or EvaluationState parameters.

" + }, + "MetricName":{ + "shape":"MetricName", + "documentation":"

The name of the metric associated with the alarm, if this is an alarm based on a single metric.

" + }, + "Namespace":{ + "shape":"Namespace", + "documentation":"

The namespace of the metric associated with the alarm.

" + }, + "Statistic":{ + "shape":"Statistic", + "documentation":"

The statistic for the metric associated with the alarm, other than percentile. For percentile statistics, use ExtendedStatistic.

" + }, + "ExtendedStatistic":{ + "shape":"ExtendedStatistic", + "documentation":"

The percentile statistic for the metric associated with the alarm. Specify a value between p0.0 and p100.

" + }, + "Dimensions":{ + "shape":"Dimensions", + "documentation":"

The dimensions for the metric associated with the alarm.

" + }, + "Period":{ + "shape":"Period", + "documentation":"

The period, in seconds, over which the statistic is applied.

" + }, + "Unit":{ + "shape":"StandardUnit", + "documentation":"

The unit of the metric associated with the alarm.

" + }, + "EvaluationPeriods":{ + "shape":"EvaluationPeriods", + "documentation":"

The number of periods over which data is compared to the specified threshold.

" + }, + "DatapointsToAlarm":{ + "shape":"DatapointsToAlarm", + "documentation":"

The number of data points that must be breaching to trigger the alarm.

" + }, + "Threshold":{ + "shape":"Threshold", + "documentation":"

The value to compare with the specified statistic.

" + }, + "ComparisonOperator":{ + "shape":"ComparisonOperator", + "documentation":"

The arithmetic operation to use when comparing the specified statistic and threshold. The specified statistic value is used as the first operand.

" + }, + "TreatMissingData":{ + "shape":"TreatMissingData", + "documentation":"

Sets how this alarm is to handle missing data points. The valid values are breaching, notBreaching, ignore, and missing. For more information, see Configuring how CloudWatch alarms treat missing data.

If this parameter is omitted, the default behavior of missing is used.

" + }, + "EvaluateLowSampleCountPercentile":{ + "shape":"EvaluateLowSampleCountPercentile", + "documentation":"

Used only for alarms based on percentiles. If ignore, the alarm state does not change during periods with too few data points to be statistically significant. If evaluate or this parameter is not used, the alarm is always evaluated and possibly changes state no matter how many data points are available.

" + }, + "Metrics":{ + "shape":"MetricDataQueries", + "documentation":"

An array of MetricDataQuery structures, used in an alarm based on a metric math expression. Each structure either retrieves a metric or performs a math expression. One item in the Metrics array is the math expression that the alarm watches. This expression by designated by having ReturnData set to true.

" + }, + "CreationId":{ + "shape":"CreationId", + "internalonly":true + }, + "ThresholdMetricId":{ + "shape":"MetricId", + "documentation":"

In an alarm based on an anomaly detection model, this is the ID of the ANOMALY_DETECTION_BAND function used as the threshold for the alarm.

" + }, + "ResourceArn":{ + "shape":"AmazonResourceName", + "internalonly":true + }, + "AlarmManagerArn":{ + "shape":"AmazonResourceName", + "internalonly":true + }, + "EvaluationState":{ + "shape":"EvaluationState", + "documentation":"

If the value of this field is PARTIAL_DATA, the alarm is being evaluated based on only partial data. This happens if the query used for the alarm returns more than 10,000 metrics. For more information, see Create alarms on Metrics Insights queries.

", + "internalonly":true + }, + "StateTransitionedTimestamp":{ + "shape":"Timestamp", + "documentation":"

The date and time that the alarm's StateValue most recently changed.

" + } + }, + "documentation":"

The details about a metric alarm.

", + "xmlOrder":[ + "AlarmName", + "AlarmArn", + "AlarmDescription", + "AlarmConfigurationUpdatedTimestamp", + "ActionsEnabled", + "OKActions", + "AlarmActions", + "InsufficientDataActions", + "StateValue", + "StateReason", + "StateReasonData", + "StateUpdatedTimestamp", + "MetricName", + "Namespace", + "Statistic", + "Dimensions", + "Period", + "Unit", + "EvaluationPeriods", + "Threshold", + "ComparisonOperator", + "ExtendedStatistic", + "TreatMissingData", + "EvaluateLowSampleCountPercentile", + "DatapointsToAlarm", + "Metrics", + "CreationId", + "ThresholdMetricId", + "ResourceArn", + "AlarmManagerArn", + "EvaluationState", + "StateTransitionedTimestamp" + ] + }, + "MetricAlarmConfigurations":{ + "type":"list", + "member":{"shape":"MetricAlarm"}, + "internalonly":true, + "min":1 + }, + "MetricAlarms":{ + "type":"list", + "member":{"shape":"MetricAlarm"} + }, + "MetricData":{ + "type":"list", + "member":{"shape":"MetricDatum"} + }, + "MetricDataBatch":{ + "type":"structure", + "required":[ + "AccountId", + "Namespace", + "MetricData" + ], + "members":{ + "AccountId":{"shape":"AccountId"}, + "Namespace":{"shape":"Namespace"}, + "MetricData":{"shape":"MetricData"}, + "AutoDecompose":{"shape":"AutoDecompose"} + } + }, + "MetricDataBatches":{ + "type":"list", + "member":{"shape":"MetricDataBatch"} + }, + "MetricDataQueries":{ + "type":"list", + "member":{"shape":"MetricDataQuery"} + }, + "MetricDataQuery":{ + "type":"structure", + "required":["Id"], + "members":{ + "Id":{ + "shape":"MetricId", + "documentation":"

A short name used to tie this object to the results in the response. This name must be unique within a single call to GetMetricData. If you are performing math expressions on this set of data, this name represents that data and can serve as a variable in the mathematical expression. The valid characters are letters, numbers, and underscore. The first character must be a lowercase letter.

" + }, + "MetricStat":{ + "shape":"MetricStat", + "documentation":"

The metric to be returned, along with statistics, period, and units. Use this parameter only if this object is retrieving a metric and not performing a math expression on returned data.

Within one MetricDataQuery object, you must specify either Expression or MetricStat but not both.

" + }, + "Expression":{ + "shape":"MetricExpression", + "documentation":"

This field can contain either a Metrics Insights query, or a metric math expression to be performed on the returned data. For more information about Metrics Insights queries, see Metrics Insights query components and syntax in the Amazon CloudWatch User Guide.

A math expression can use the Id of the other metrics or queries to refer to those metrics, and can also use the Id of other expressions to use the result of those expressions. For more information about metric math expressions, see Metric Math Syntax and Functions in the Amazon CloudWatch User Guide.

Within each MetricDataQuery object, you must specify either Expression or MetricStat but not both.

" + }, + "Label":{ + "shape":"MetricLabel", + "documentation":"

A human-readable label for this metric or expression. This is especially useful if this is an expression, so that you know what the value represents. If the metric or expression is shown in a CloudWatch dashboard widget, the label is shown. If Label is omitted, CloudWatch generates a default.

You can put dynamic expressions into a label, so that it is more descriptive. For more information, see Using Dynamic Labels.

" + }, + "ReturnData":{ + "shape":"ReturnData", + "documentation":"

When used in GetMetricData, this option indicates whether to return the timestamps and raw data values of this metric. If you are performing this call just to do math expressions and do not also need the raw data returned, you can specify false. If you omit this, the default of true is used.

When used in PutMetricAlarm, specify true for the one expression result to use as the alarm. For all other metrics and expressions in the same PutMetricAlarm operation, specify ReturnData as False.

" + }, + "Period":{ + "shape":"Period", + "documentation":"

The granularity, in seconds, of the returned data points. For metrics with regular resolution, a period can be as short as one minute (60 seconds) and must be a multiple of 60. For high-resolution metrics that are collected at intervals of less than one minute, the period can be 1, 5, 10, 30, 60, or any multiple of 60. High-resolution metrics are those metrics stored by a PutMetricData operation that includes a StorageResolution of 1 second.

" + }, + "AccountId":{ + "shape":"AccountId", + "documentation":"

The ID of the account where the metrics are located.

If you are performing a GetMetricData operation in a monitoring account, use this to specify which account to retrieve this metric from.

If you are performing a PutMetricAlarm operation, use this to specify which account contains the metric that the alarm is watching.

" + } + }, + "documentation":"

This structure is used in both GetMetricData and PutMetricAlarm. The supported use of this structure is different for those two operations.

When used in GetMetricData, it indicates the metric data to return, and whether this call is just retrieving a batch set of data for one metric, or is performing a Metrics Insights query or a math expression. A single GetMetricData call can include up to 500 MetricDataQuery structures.

When used in PutMetricAlarm, it enables you to create an alarm based on a metric math expression. Each MetricDataQuery in the array specifies either a metric to retrieve, or a math expression to be performed on retrieved metrics. A single PutMetricAlarm call can include up to 20 MetricDataQuery structures in the array. The 20 structures can include as many as 10 structures that contain a MetricStat parameter to retrieve a metric, and as many as 10 structures that contain the Expression parameter to perform a math expression. Of those Expression structures, one must have true as the value for ReturnData. The result of this expression is the value the alarm watches.

Any expression used in a PutMetricAlarm operation must return a single time series. For more information, see Metric Math Syntax and Functions in the Amazon CloudWatch User Guide.

Some of the parameters of this structure also have different uses whether you are using this structure in a GetMetricData operation or a PutMetricAlarm operation. These differences are explained in the following parameter list.

" + }, + "MetricDataResult":{ + "type":"structure", + "members":{ + "Id":{ + "shape":"MetricId", + "documentation":"

The short name you specified to represent this metric.

" + }, + "Label":{ + "shape":"MetricLabel", + "documentation":"

The human-readable label associated with the data.

" + }, + "Timestamps":{ + "shape":"Timestamps", + "documentation":"

The timestamps for the data points, formatted in Unix timestamp format. The number of timestamps always matches the number of values and the value for Timestamps[x] is Values[x].

" + }, + "Values":{ + "shape":"DatapointValues", + "documentation":"

The data points for the metric corresponding to Timestamps. The number of values always matches the number of timestamps and the timestamp for Values[x] is Timestamps[x].

" + }, + "StatusCode":{ + "shape":"StatusCode", + "documentation":"

The status of the returned data. Complete indicates that all data points in the requested time range were returned. PartialData means that an incomplete set of data points were returned. You can use the NextToken value that was returned and repeat your request to get more data points. NextToken is not returned if you are performing a math expression. InternalError indicates that an error occurred. Retry your request using NextToken, if present.

" + }, + "Messages":{ + "shape":"MetricDataResultMessages", + "documentation":"

A list of messages with additional information about the data returned.

" + } + }, + "documentation":"

A GetMetricData call returns an array of MetricDataResult structures. Each of these structures includes the data points for that metric, along with the timestamps of those data points and other identifying information.

" + }, + "MetricDataResultMessages":{ + "type":"list", + "member":{"shape":"MessageData"} + }, + "MetricDataResults":{ + "type":"list", + "member":{"shape":"MetricDataResult"} + }, + "MetricDatum":{ + "type":"structure", + "required":["MetricName"], + "members":{ + "MetricName":{ + "shape":"MetricName", + "documentation":"

The name of the metric.

" + }, + "Dimensions":{ + "shape":"Dimensions", + "documentation":"

The dimensions associated with the metric.

" + }, + "Timestamp":{ + "shape":"Timestamp", + "documentation":"

The time the metric data was received, expressed as the number of milliseconds since Jan 1, 1970 00:00:00 UTC.

" + }, + "Value":{ + "shape":"DatapointValue", + "documentation":"

The value for the metric.

Although the parameter accepts numbers of type Double, CloudWatch rejects values that are either too small or too large. Values must be in the range of -2^360 to 2^360. In addition, special values (for example, NaN, +Infinity, -Infinity) are not supported.

" + }, + "StatisticValues":{ + "shape":"StatisticSet", + "documentation":"

The statistical values for the metric.

" + }, + "Values":{ + "shape":"Values", + "documentation":"

Array of numbers representing the values for the metric during the period. Each unique value is listed just once in this array, and the corresponding number in the Counts array specifies the number of times that value occurred during the period. You can include up to 150 unique values in each PutMetricData action that specifies a Values array.

Although the Values array accepts numbers of type Double, CloudWatch rejects values that are either too small or too large. Values must be in the range of -2^360 to 2^360. In addition, special values (for example, NaN, +Infinity, -Infinity) are not supported.

" + }, + "Counts":{ + "shape":"Counts", + "documentation":"

Array of numbers that is used along with the Values array. Each number in the Count array is the number of times the corresponding value in the Values array occurred during the period.

If you omit the Counts array, the default of 1 is used as the value for each count. If you include a Counts array, it must include the same amount of values as the Values array.

" + }, + "Unit":{ + "shape":"StandardUnit", + "documentation":"

When you are using a Put operation, this defines what unit you want to use when storing the metric.

In a Get operation, this displays the unit that is used for the metric.

" + }, + "StorageResolution":{ + "shape":"StorageResolution", + "documentation":"

Valid values are 1 and 60. Setting this to 1 specifies this metric as a high-resolution metric, so that CloudWatch stores the metric with sub-minute resolution down to one second. Setting this to 60 specifies this metric as a regular-resolution metric, which CloudWatch stores at 1-minute resolution. Currently, high resolution is available only for custom metrics. For more information about high-resolution metrics, see High-Resolution Metrics in the Amazon CloudWatch User Guide.

This field is optional, if you do not specify it the default of 60 is used.

" + } + }, + "documentation":"

Encapsulates the information sent to either create a metric or add new values to be aggregated into an existing metric.

" + }, + "MetricExpression":{ + "type":"string", + "max":2048, + "min":1 + }, + "MetricId":{ + "type":"string", + "max":255, + "min":1 + }, + "MetricLabel":{"type":"string"}, + "MetricMathAnomalyDetector":{ + "type":"structure", + "members":{ + "MetricDataQueries":{ + "shape":"MetricDataQueries", + "documentation":"

An array of metric data query structures that enables you to create an anomaly detector based on the result of a metric math expression. Each item in MetricDataQueries gets a metric or performs a math expression. One item in MetricDataQueries is the expression that provides the time series that the anomaly detector uses as input. Designate the expression by setting ReturnData to true for this object in the array. For all other expressions and metrics, set ReturnData to false. The designated expression must return a single time series.

" + } + }, + "documentation":"

Indicates the CloudWatch math expression that provides the time series the anomaly detector uses as input. The designated math expression must return a single time series.

" + }, + "MetricMathSearchTerm":{ + "type":"structure", + "members":{ + }, + "internalonly":true + }, + "MetricName":{ + "type":"string", + "max":255, + "min":1 + }, + "MetricReference":{ + "type":"structure", + "required":[ + "Namespace", + "Metrictype", + "MetricName" + ], + "members":{ + "Namespace":{"shape":"Namespace"}, + "Metrictype":{"shape":"MetricType"}, + "Dimensions":{"shape":"Dimensions"}, + "MetricName":{"shape":"MetricName"} + } + }, + "MetricReferences":{ + "type":"list", + "member":{"shape":"MetricReference"} + }, + "MetricStat":{ + "type":"structure", + "required":[ + "Metric", + "Period", + "Stat" + ], + "members":{ + "Metric":{ + "shape":"Metric", + "documentation":"

The metric to return, including the metric name, namespace, and dimensions.

" + }, + "Period":{ + "shape":"Period", + "documentation":"

The granularity, in seconds, of the returned data points. For metrics with regular resolution, a period can be as short as one minute (60 seconds) and must be a multiple of 60. For high-resolution metrics that are collected at intervals of less than one minute, the period can be 1, 5, 10, 30, 60, or any multiple of 60. High-resolution metrics are those metrics stored by a PutMetricData call that includes a StorageResolution of 1 second.

If the StartTime parameter specifies a time stamp that is greater than 3 hours ago, you must specify the period as follows or no data points in that time range is returned:

  • Start time between 3 hours and 15 days ago - Use a multiple of 60 seconds (1 minute).

  • Start time between 15 and 63 days ago - Use a multiple of 300 seconds (5 minutes).

  • Start time greater than 63 days ago - Use a multiple of 3600 seconds (1 hour).

" + }, + "Stat":{ + "shape":"Stat", + "documentation":"

The statistic to return. It can include any CloudWatch statistic or extended statistic.

" + }, + "Unit":{ + "shape":"StandardUnit", + "documentation":"

When you are using a Put operation, this defines what unit you want to use when storing the metric.

In a Get operation, if you omit Unit then all data that was collected with any unit is returned, along with the corresponding units that were specified when the data was reported to CloudWatch. If you specify a unit, the operation returns only data that was collected with that unit specified. If you specify a unit that does not match the data collected, the results of the operation are null. CloudWatch does not perform unit conversions.

" + } + }, + "documentation":"

This structure defines the metric to be returned, along with the statistics, period, and units.

" + }, + "MetricStream":{ + "type":"structure", + "members":{ + "Arn":{"shape":"AmazonResourceName"}, + "AccountId":{"shape":"MetricStreamAccountId"}, + "Name":{"shape":"MetricStreamName"}, + "IncludeFilters":{"shape":"MetricStreamFilters"}, + "ExcludeFilters":{"shape":"MetricStreamFilters"}, + "StatisticsConfigurations":{"shape":"MetricStreamStatisticsConfigurations"}, + "FirehoseArn":{"shape":"AmazonResourceName"}, + "RoleArn":{"shape":"AmazonResourceName"}, + "State":{"shape":"MetricStreamState"}, + "CreationDate":{"shape":"Timestamp"}, + "LastUpdateDate":{"shape":"Timestamp"}, + "FiltersVersion":{"shape":"MetricStreamFiltersVersion"}, + "ValidFromDate":{"shape":"Timestamp"}, + "SegmentationData":{"shape":"MetricStreamSegmentationData"}, + "OutputFormat":{"shape":"MetricStreamOutputFormat"}, + "IncludeLinkedAccountsMetrics":{"shape":"IncludeLinkedAccountsMetrics"}, + "IncludeLinkedAccountsMetricsLastUpdateDate":{"shape":"Timestamp"} + } + }, + "MetricStreamAccountId":{"type":"string"}, + "MetricStreamEntries":{ + "type":"list", + "member":{"shape":"MetricStreamEntry"} + }, + "MetricStreamEntry":{ + "type":"structure", + "members":{ + "Arn":{ + "shape":"AmazonResourceName", + "documentation":"

The ARN of the metric stream.

" + }, + "CreationDate":{ + "shape":"Timestamp", + "documentation":"

The date that the metric stream was originally created.

" + }, + "LastUpdateDate":{ + "shape":"Timestamp", + "documentation":"

The date that the configuration of this metric stream was most recently updated.

" + }, + "Name":{ + "shape":"MetricStreamName", + "documentation":"

The name of the metric stream.

" + }, + "FirehoseArn":{ + "shape":"AmazonResourceName", + "documentation":"

The ARN of the Kinesis Firehose devlivery stream that is used for this metric stream.

" + }, + "State":{ + "shape":"MetricStreamState", + "documentation":"

The current state of this stream. Valid values are running and stopped.

" + }, + "OutputFormat":{ + "shape":"MetricStreamOutputFormat", + "documentation":"

The output format of this metric stream. Valid values are json and opentelemetry0.7.

" + } + }, + "documentation":"

This structure contains the configuration information about one metric stream.

" + }, + "MetricStreamFilter":{ + "type":"structure", + "members":{ + "Namespace":{ + "shape":"Namespace", + "documentation":"

The name of the metric namespace for this filter.

The namespace can contain only ASCII printable characters (ASCII range 32 through 126). It must contain at least one non-whitespace character.

" + }, + "MetricNames":{ + "shape":"MetricStreamFilterMetricNames", + "documentation":"

The names of the metrics to either include or exclude from the metric stream.

If you omit this parameter, all metrics in the namespace are included or excluded, depending on whether this filter is specified as an exclude filter or an include filter.

Each metric name can contain only ASCII printable characters (ASCII range 32 through 126). Each metric name must contain at least one non-whitespace character.

" + } + }, + "documentation":"

This structure contains a metric namespace and optionally, a list of metric names, to either include in a metric stream or exclude from a metric stream.

A metric stream's filters can include up to 1000 total names. This limit applies to the sum of namespace names and metric names in the filters. For example, this could include 10 metric namespace filters with 99 metrics each, or 20 namespace filters with 49 metrics specified in each filter.

" + }, + "MetricStreamFilterMetricNames":{ + "type":"list", + "member":{"shape":"MetricName"} + }, + "MetricStreamFilters":{ + "type":"list", + "member":{"shape":"MetricStreamFilter"} + }, + "MetricStreamFiltersVersion":{"type":"string"}, + "MetricStreamName":{ + "type":"string", + "max":255, + "min":1 + }, + "MetricStreamNames":{ + "type":"list", + "member":{"shape":"MetricStreamName"} + }, + "MetricStreamOutputFormat":{ + "type":"string", + "enum":[ + "json", + "opentelemetry0.7" + ], + "max":255, + "min":1 + }, + "MetricStreamSegment":{ + "type":"integer", + "max":999999, + "min":0 + }, + "MetricStreamSegmentationData":{"type":"string"}, + "MetricStreamState":{"type":"string"}, + "MetricStreamStatistic":{"type":"string"}, + "MetricStreamStatisticsAdditionalStatistics":{ + "type":"list", + "member":{"shape":"MetricStreamStatistic"} + }, + "MetricStreamStatisticsConfiguration":{ + "type":"structure", + "required":[ + "IncludeMetrics", + "AdditionalStatistics" + ], + "members":{ + "IncludeMetrics":{ + "shape":"MetricStreamStatisticsIncludeMetrics", + "documentation":"

An array of metric name and namespace pairs that stream the additional statistics listed in the value of the AdditionalStatistics parameter. There can be as many as 100 pairs in the array.

All metrics that match the combination of metric name and namespace will be streamed with the additional statistics, no matter their dimensions.

" + }, + "AdditionalStatistics":{ + "shape":"MetricStreamStatisticsAdditionalStatistics", + "documentation":"

The list of additional statistics that are to be streamed for the metrics listed in the IncludeMetrics array in this structure. This list can include as many as 20 statistics.

If the OutputFormat for the stream is opentelemetry0.7, the only valid values are p?? percentile statistics such as p90, p99 and so on.

If the OutputFormat for the stream is json, the valid values include the abbreviations for all of the statistics listed in CloudWatch statistics definitions. For example, this includes tm98, wm90, PR(:300), and so on.

" + } + }, + "documentation":"

By default, a metric stream always sends the MAX, MIN, SUM, and SAMPLECOUNT statistics for each metric that is streamed. This structure contains information for one metric that includes additional statistics in the stream. For more information about statistics, see CloudWatch, listed in CloudWatch statistics definitions.

" + }, + "MetricStreamStatisticsConfigurations":{ + "type":"list", + "member":{"shape":"MetricStreamStatisticsConfiguration"} + }, + "MetricStreamStatisticsIncludeMetrics":{ + "type":"list", + "member":{"shape":"MetricStreamStatisticsMetric"} + }, + "MetricStreamStatisticsMetric":{ + "type":"structure", + "required":[ + "Namespace", + "MetricName" + ], + "members":{ + "Namespace":{ + "shape":"Namespace", + "documentation":"

The namespace of the metric.

" + }, + "MetricName":{ + "shape":"MetricName", + "documentation":"

The name of the metric.

" + } + }, + "documentation":"

This object contains the information for one metric that is to be streamed with additional statistics.

" + }, + "MetricStreamTotalSegments":{ + "type":"integer", + "max":1000000, + "min":1 + }, + "MetricStreams":{ + "type":"list", + "member":{"shape":"MetricStream"} + }, + "MetricTemplate":{ + "type":"structure", + "members":{ + "Namespace":{"shape":"Namespace"}, + "Dimensions":{"shape":"Dimensions"} + } + }, + "MetricType":{ + "type":"string", + "pattern":"[A-Za-z0-9 -]+" + }, + "MetricWidget":{"type":"string"}, + "MetricWidgetImage":{"type":"blob"}, + "Metrics":{ + "type":"list", + "member":{"shape":"Metric"} + }, + "MissingRequiredParameterException":{ + "type":"structure", + "members":{ + "message":{ + "shape":"AwsQueryErrorMessage", + "documentation":"

" + } + }, + "documentation":"

An input parameter that is required is missing.

", + "error":{ + "code":"MissingParameter", + "httpStatusCode":400, + "senderFault":true + }, + "exception":true, + "synthetic":true + }, + "Namespace":{ + "type":"string", + "max":255, + "min":1, + "pattern":"[^:].*" + }, + "NextToken":{"type":"string"}, + "NodeId":{"type":"string"}, + "NodeName":{"type":"string"}, + "NodeType":{"type":"string"}, + "Operation":{ + "type":"structure", + "required":[ + "OperationName", + "MetricReferences" + ], + "members":{ + "OperationName":{"shape":"OperationName"}, + "MetricReferences":{"shape":"MetricReferences"} + } + }, + "OperationName":{ + "type":"string", + "min":1 + }, + "OperationPath":{ + "type":"structure", + "required":[ + "ServiceOperationName", + "RemoteOperationName", + "MetricReferences" + ], + "members":{ + "ServiceOperationName":{"shape":"ServiceOperationName"}, + "RemoteOperationName":{"shape":"RemoteOperationName"}, + "MetricReferences":{"shape":"MetricReferences"} + } + }, + "OperationPaths":{ + "type":"list", + "member":{"shape":"OperationPath"} + }, + "Operations":{ + "type":"list", + "member":{"shape":"Operation"} + }, + "Order":{ + "type":"string", + "enum":[ + "ASC", + "DESC" + ] + }, + "OutputFormat":{"type":"string"}, + "OwningAccounts":{ + "type":"list", + "member":{"shape":"AccountId"} + }, + "PartialFailure":{ + "type":"structure", + "members":{ + "FailureResource":{ + "shape":"FailureResource", + "documentation":"

The specified rule that could not be deleted.

" + }, + "ExceptionType":{ + "shape":"ExceptionType", + "documentation":"

The type of error.

" + }, + "FailureCode":{ + "shape":"FailureCode", + "documentation":"

The code of the error.

" + }, + "FailureDescription":{ + "shape":"FailureDescription", + "documentation":"

A description of the error.

" + } + }, + "documentation":"

This array is empty if the API operation was successful for all the rules specified in the request. If the operation could not process one of the rules, the following data is returned for each of those rules.

" + }, + "PayerToken":{ + "type":"string", + "pattern":":[^:]*:[^:]*:[^:]*:[^:]*:.*" + }, + "Period":{ + "type":"integer", + "min":1 + }, + "PeriodSeconds":{ + "type":"integer", + "box":true + }, + "PreconditionNotMetException":{ + "type":"structure", + "members":{ + }, + "error":{ + "code":"PreconditionNotMet", + "httpStatusCode":400, + "senderFault":true + }, + "exception":true, + "internalonly":true + }, + "PrismaMaxResults":{"type":"integer"}, + "PutAlarmTemplateInput":{ + "type":"structure", + "required":[ + "Name", + "MetricAlarmConfigurations", + "ResourceType", + "ResourceTag" + ], + "members":{ + "Name":{"shape":"AlarmTemplateName"}, + "MetricAlarmConfigurations":{"shape":"MetricAlarmConfigurations"}, + "ResourceType":{"shape":"AlarmTemplateResourceType"}, + "ResourceTag":{"shape":"Tag"}, + "Tags":{"shape":"TagList"}, + "CreationId":{ + "shape":"CreationId", + "internalonly":true + }, + "Description":{"shape":"AlarmTemplateDescription"} + } + }, + "PutAnomalyDetectorInput":{ + "type":"structure", + "members":{ + "Namespace":{ + "shape":"Namespace", + "documentation":"

The namespace of the metric to create the anomaly detection model for.

", + "deprecated":true, + "deprecatedMessage":"Use SingleMetricAnomalyDetector." + }, + "MetricName":{ + "shape":"MetricName", + "documentation":"

The name of the metric to create the anomaly detection model for.

", + "deprecated":true, + "deprecatedMessage":"Use SingleMetricAnomalyDetector." + }, + "Dimensions":{ + "shape":"Dimensions", + "documentation":"

The metric dimensions to create the anomaly detection model for.

", + "deprecated":true, + "deprecatedMessage":"Use SingleMetricAnomalyDetector." + }, + "Stat":{ + "shape":"AnomalyDetectorMetricStat", + "documentation":"

The statistic to use for the metric and the anomaly detection model.

", + "deprecated":true, + "deprecatedMessage":"Use SingleMetricAnomalyDetector." + }, + "Configuration":{ + "shape":"AnomalyDetectorConfiguration", + "documentation":"

The configuration specifies details about how the anomaly detection model is to be trained, including time ranges to exclude when training and updating the model. You can specify as many as 10 time ranges.

The configuration can also include the time zone to use for the metric.

" + }, + "SingleMetricAnomalyDetector":{ + "shape":"SingleMetricAnomalyDetector", + "documentation":"

A single metric anomaly detector to be created.

When using SingleMetricAnomalyDetector, you cannot include the following parameters in the same operation:

  • Dimensions

  • MetricName

  • Namespace

  • Stat

  • the MetricMatchAnomalyDetector parameters of PutAnomalyDetectorInput

Instead, specify the single metric anomaly detector attributes as part of the property SingleMetricAnomalyDetector.

" + }, + "MetricMathAnomalyDetector":{ + "shape":"MetricMathAnomalyDetector", + "documentation":"

The metric math anomaly detector to be created.

When using MetricMathAnomalyDetector, you cannot include the following parameters in the same operation:

  • Dimensions

  • MetricName

  • Namespace

  • Stat

  • the SingleMetricAnomalyDetector parameters of PutAnomalyDetectorInput

Instead, specify the metric math anomaly detector attributes as part of the property MetricMathAnomalyDetector.

" + } + } + }, + "PutAnomalyDetectorOutput":{ + "type":"structure", + "members":{ + } + }, + "PutCompositeAlarmInput":{ + "type":"structure", + "required":[ + "AlarmName", + "AlarmRule" + ], + "members":{ + "ActionsEnabled":{ + "shape":"ActionsEnabled", + "documentation":"

Indicates whether actions should be executed during any changes to the alarm state of the composite alarm. The default is TRUE.

" + }, + "AlarmActions":{ + "shape":"ResourceList", + "documentation":"

The actions to execute when this alarm transitions to the ALARM state from any other state. Each action is specified as an Amazon Resource Name (ARN).

Valid Values: arn:aws:sns:region:account-id:sns-topic-name | arn:aws:ssm:region:account-id:opsitem:severity

" + }, + "AlarmDescription":{ + "shape":"AlarmDescription", + "documentation":"

The description for the composite alarm.

" + }, + "AlarmName":{ + "shape":"AlarmName", + "documentation":"

The name for the composite alarm. This name must be unique within the Region.

" + }, + "AlarmRule":{ + "shape":"AlarmRule", + "documentation":"

An expression that specifies which other alarms are to be evaluated to determine this composite alarm's state. For each alarm that you reference, you designate a function that specifies whether that alarm needs to be in ALARM state, OK state, or INSUFFICIENT_DATA state. You can use operators (AND, OR and NOT) to combine multiple functions in a single expression. You can use parenthesis to logically group the functions in your expression.

You can use either alarm names or ARNs to reference the other alarms that are to be evaluated.

Functions can include the following:

  • ALARM(\"alarm-name or alarm-ARN\") is TRUE if the named alarm is in ALARM state.

  • OK(\"alarm-name or alarm-ARN\") is TRUE if the named alarm is in OK state.

  • INSUFFICIENT_DATA(\"alarm-name or alarm-ARN\") is TRUE if the named alarm is in INSUFFICIENT_DATA state.

  • TRUE always evaluates to TRUE.

  • FALSE always evaluates to FALSE.

TRUE and FALSE are useful for testing a complex AlarmRule structure, and for testing your alarm actions.

Alarm names specified in AlarmRule can be surrounded with double-quotes (\"), but do not have to be.

The following are some examples of AlarmRule:

  • ALARM(CPUUtilizationTooHigh) AND ALARM(DiskReadOpsTooHigh) specifies that the composite alarm goes into ALARM state only if both CPUUtilizationTooHigh and DiskReadOpsTooHigh alarms are in ALARM state.

  • ALARM(CPUUtilizationTooHigh) AND NOT ALARM(DeploymentInProgress) specifies that the alarm goes to ALARM state if CPUUtilizationTooHigh is in ALARM state and DeploymentInProgress is not in ALARM state. This example reduces alarm noise during a known deployment window.

  • (ALARM(CPUUtilizationTooHigh) OR ALARM(DiskReadOpsTooHigh)) AND OK(NetworkOutTooHigh) goes into ALARM state if CPUUtilizationTooHigh OR DiskReadOpsTooHigh is in ALARM state, and if NetworkOutTooHigh is in OK state. This provides another example of using a composite alarm to prevent noise. This rule ensures that you are not notified with an alarm action on high CPU or disk usage if a known network problem is also occurring.

The AlarmRule can specify as many as 100 \"children\" alarms. The AlarmRule expression can have as many as 500 elements. Elements are child alarms, TRUE or FALSE statements, and parentheses.

" + }, + "CreationId":{ + "shape":"CreationId", + "internalonly":true + }, + "InsufficientDataActions":{ + "shape":"ResourceList", + "documentation":"

The actions to execute when this alarm transitions to the INSUFFICIENT_DATA state from any other state. Each action is specified as an Amazon Resource Name (ARN).

Valid Values: arn:aws:sns:region:account-id:sns-topic-name

" + }, + "OKActions":{ + "shape":"ResourceList", + "documentation":"

The actions to execute when this alarm transitions to an OK state from any other state. Each action is specified as an Amazon Resource Name (ARN).

Valid Values: arn:aws:sns:region:account-id:sns-topic-name

" + }, + "Tags":{ + "shape":"TagList", + "documentation":"

A list of key-value pairs to associate with the composite alarm. You can associate as many as 50 tags with an alarm.

Tags can help you organize and categorize your resources. You can also use them to scope user permissions, by granting a user permission to access or change only resources with certain tag values.

" + }, + "ActionsSuppressor":{ + "shape":"AlarmArn", + "documentation":"

Actions will be suppressed if the suppressor alarm is in the ALARM state. ActionsSuppressor can be an AlarmName or an Amazon Resource Name (ARN) from an existing alarm.

" + }, + "ActionsSuppressorWaitPeriod":{ + "shape":"SuppressorPeriod", + "documentation":"

The maximum time in seconds that the composite alarm waits for the suppressor alarm to go into the ALARM state. After this time, the composite alarm performs its actions.

WaitPeriod is required only when ActionsSuppressor is specified.

" + }, + "ActionsSuppressorExtensionPeriod":{ + "shape":"SuppressorPeriod", + "documentation":"

The maximum time in seconds that the composite alarm waits after suppressor alarm goes out of the ALARM state. After this time, the composite alarm performs its actions.

ExtensionPeriod is required only when ActionsSuppressor is specified.

" + } + } + }, + "PutDashboardForAccountInput":{ + "type":"structure", + "required":[ + "AccountId", + "DashboardName", + "DashboardBody" + ], + "members":{ + "AccountId":{"shape":"AccountId"}, + "DashboardName":{"shape":"DashboardName"}, + "DashboardBody":{"shape":"DashboardBody"} + } + }, + "PutDashboardForAccountOutput":{ + "type":"structure", + "members":{ + "DashboardValidationMessages":{"shape":"DashboardValidationMessages"} + } + }, + "PutDashboardInput":{ + "type":"structure", + "required":[ + "DashboardName", + "DashboardBody" + ], + "members":{ + "DashboardName":{ + "shape":"DashboardName", + "documentation":"

The name of the dashboard. If a dashboard with this name already exists, this call modifies that dashboard, replacing its current contents. Otherwise, a new dashboard is created. The maximum length is 255, and valid characters are A-Z, a-z, 0-9, \"-\", and \"_\". This parameter is required.

" + }, + "DashboardBody":{ + "shape":"DashboardBody", + "documentation":"

The detailed information about the dashboard in JSON format, including the widgets to include and their location on the dashboard. This parameter is required.

For more information about the syntax, see Dashboard Body Structure and Syntax.

" + } + } + }, + "PutDashboardOutput":{ + "type":"structure", + "members":{ + "DashboardValidationMessages":{ + "shape":"DashboardValidationMessages", + "documentation":"

If the input for PutDashboard was correct and the dashboard was successfully created or modified, this result is empty.

If this result includes only warning messages, then the input was valid enough for the dashboard to be created or modified, but some elements of the dashboard might not render.

If this result includes error messages, the input was not valid and the operation failed.

" + } + } + }, + "PutInsightRuleInput":{ + "type":"structure", + "required":[ + "RuleName", + "RuleDefinition" + ], + "members":{ + "RuleName":{ + "shape":"InsightRuleName", + "documentation":"

A unique name for the rule.

" + }, + "RuleState":{ + "shape":"InsightRuleState", + "documentation":"

The state of the rule. Valid values are ENABLED and DISABLED.

" + }, + "RuleDefinition":{ + "shape":"InsightRuleDefinition", + "documentation":"

The definition of the rule, as a JSON object. For details on the valid syntax, see Contributor Insights Rule Syntax.

" + }, + "Tags":{ + "shape":"TagList", + "documentation":"

A list of key-value pairs to associate with the Contributor Insights rule. You can associate as many as 50 tags with a rule.

Tags can help you organize and categorize your resources. You can also use them to scope user permissions, by granting a user permission to access or change only the resources that have certain tag values.

To be able to associate tags with a rule, you must have the cloudwatch:TagResource permission in addition to the cloudwatch:PutInsightRule permission.

If you are using this operation to update an existing Contributor Insights rule, any tags you specify in this parameter are ignored. To change the tags of an existing rule, use TagResource.

" + } + } + }, + "PutInsightRuleOutput":{ + "type":"structure", + "members":{ + } + }, + "PutManagedInsightRulesInput":{ + "type":"structure", + "required":["ManagedRules"], + "members":{ + "TargetAccountId":{ + "shape":"AccountId", + "internalonly":true + }, + "ManagedRules":{ + "shape":"ManagedRules", + "documentation":"

A list of ManagedRules to enable.

" + } + } + }, + "PutManagedInsightRulesOutput":{ + "type":"structure", + "members":{ + "Failures":{ + "shape":"BatchFailures", + "documentation":"

An array that lists the rules that could not be enabled.

" + } + } + }, + "PutMetricAlarmInput":{ + "type":"structure", + "required":[ + "AlarmName", + "EvaluationPeriods", + "ComparisonOperator" + ], + "members":{ + "AlarmName":{ + "shape":"AlarmName", + "documentation":"

The name for the alarm. This name must be unique within the Region.

The name must contain only UTF-8 characters, and can't contain ASCII control characters

" + }, + "AlarmDescription":{ + "shape":"AlarmDescription", + "documentation":"

The description for the alarm.

" + }, + "ActionsEnabled":{ + "shape":"ActionsEnabled", + "documentation":"

Indicates whether actions should be executed during any changes to the alarm state. The default is TRUE.

" + }, + "OKActions":{ + "shape":"ResourceList", + "documentation":"

The actions to execute when this alarm transitions to an OK state from any other state. Each action is specified as an Amazon Resource Name (ARN). Valid values:

EC2 actions:

  • arn:aws:automate:region:ec2:stop

  • arn:aws:automate:region:ec2:terminate

  • arn:aws:automate:region:ec2:reboot

  • arn:aws:automate:region:ec2:recover

  • arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Stop/1.0

  • arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Terminate/1.0

  • arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Reboot/1.0

  • arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Recover/1.0

Autoscaling action:

  • arn:aws:autoscaling:region:account-id:scalingPolicy:policy-id:autoScalingGroupName/group-friendly-name:policyName/policy-friendly-name

SNS notification action:

  • arn:aws:sns:region:account-id:sns-topic-name:autoScalingGroupName/group-friendly-name:policyName/policy-friendly-name

SSM integration actions:

  • arn:aws:ssm:region:account-id:opsitem:severity#CATEGORY=category-name

  • arn:aws:ssm-incidents::account-id:responseplan/response-plan-name

" + }, + "AlarmActions":{ + "shape":"ResourceList", + "documentation":"

The actions to execute when this alarm transitions to the ALARM state from any other state. Each action is specified as an Amazon Resource Name (ARN). Valid values:

EC2 actions:

  • arn:aws:automate:region:ec2:stop

  • arn:aws:automate:region:ec2:terminate

  • arn:aws:automate:region:ec2:reboot

  • arn:aws:automate:region:ec2:recover

  • arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Stop/1.0

  • arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Terminate/1.0

  • arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Reboot/1.0

  • arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Recover/1.0

Autoscaling action:

  • arn:aws:autoscaling:region:account-id:scalingPolicy:policy-id:autoScalingGroupName/group-friendly-name:policyName/policy-friendly-name

SNS notification action:

  • arn:aws:sns:region:account-id:sns-topic-name:autoScalingGroupName/group-friendly-name:policyName/policy-friendly-name

SSM integration actions:

  • arn:aws:ssm:region:account-id:opsitem:severity#CATEGORY=category-name

  • arn:aws:ssm-incidents::account-id:responseplan/response-plan-name

" + }, + "InsufficientDataActions":{ + "shape":"ResourceList", + "documentation":"

The actions to execute when this alarm transitions to the INSUFFICIENT_DATA state from any other state. Each action is specified as an Amazon Resource Name (ARN). Valid values:

EC2 actions:

  • arn:aws:automate:region:ec2:stop

  • arn:aws:automate:region:ec2:terminate

  • arn:aws:automate:region:ec2:reboot

  • arn:aws:automate:region:ec2:recover

  • arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Stop/1.0

  • arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Terminate/1.0

  • arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Reboot/1.0

  • arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Recover/1.0

Autoscaling action:

  • arn:aws:autoscaling:region:account-id:scalingPolicy:policy-id:autoScalingGroupName/group-friendly-name:policyName/policy-friendly-name

SNS notification action:

  • arn:aws:sns:region:account-id:sns-topic-name:autoScalingGroupName/group-friendly-name:policyName/policy-friendly-name

SSM integration actions:

  • arn:aws:ssm:region:account-id:opsitem:severity#CATEGORY=category-name

  • arn:aws:ssm-incidents::account-id:responseplan/response-plan-name

" + }, + "MetricName":{ + "shape":"MetricName", + "documentation":"

The name for the metric associated with the alarm. For each PutMetricAlarm operation, you must specify either MetricName or a Metrics array.

If you are creating an alarm based on a math expression, you cannot specify this parameter, or any of the Dimensions, Period, Namespace, Statistic, or ExtendedStatistic parameters. Instead, you specify all this information in the Metrics array.

" + }, + "Namespace":{ + "shape":"Namespace", + "documentation":"

The namespace for the metric associated specified in MetricName.

" + }, + "Statistic":{ + "shape":"Statistic", + "documentation":"

The statistic for the metric specified in MetricName, other than percentile. For percentile statistics, use ExtendedStatistic. When you call PutMetricAlarm and specify a MetricName, you must specify either Statistic or ExtendedStatistic, but not both.

" + }, + "ExtendedStatistic":{ + "shape":"ExtendedStatistic", + "documentation":"

The percentile statistic for the metric specified in MetricName. Specify a value between p0.0 and p100. When you call PutMetricAlarm and specify a MetricName, you must specify either Statistic or ExtendedStatistic, but not both.

" + }, + "Dimensions":{ + "shape":"Dimensions", + "documentation":"

The dimensions for the metric specified in MetricName.

" + }, + "Period":{ + "shape":"Period", + "documentation":"

The length, in seconds, used each time the metric specified in MetricName is evaluated. Valid values are 10, 30, and any multiple of 60.

Period is required for alarms based on static thresholds. If you are creating an alarm based on a metric math expression, you specify the period for each metric within the objects in the Metrics array.

Be sure to specify 10 or 30 only for metrics that are stored by a PutMetricData call with a StorageResolution of 1. If you specify a period of 10 or 30 for a metric that does not have sub-minute resolution, the alarm still attempts to gather data at the period rate that you specify. In this case, it does not receive data for the attempts that do not correspond to a one-minute data resolution, and the alarm might often lapse into INSUFFICENT_DATA status. Specifying 10 or 30 also sets this alarm as a high-resolution alarm, which has a higher charge than other alarms. For more information about pricing, see Amazon CloudWatch Pricing.

An alarm's total current evaluation period can be no longer than one day, so Period multiplied by EvaluationPeriods cannot be more than 86,400 seconds.

" + }, + "Unit":{ + "shape":"StandardUnit", + "documentation":"

The unit of measure for the statistic. For example, the units for the Amazon EC2 NetworkIn metric are Bytes because NetworkIn tracks the number of bytes that an instance receives on all network interfaces. You can also specify a unit when you create a custom metric. Units help provide conceptual meaning to your data. Metric data points that specify a unit of measure, such as Percent, are aggregated separately.

If you don't specify Unit, CloudWatch retrieves all unit types that have been published for the metric and attempts to evaluate the alarm. Usually, metrics are published with only one unit, so the alarm works as intended.

However, if the metric is published with multiple types of units and you don't specify a unit, the alarm's behavior is not defined and it behaves unpredictably.

We recommend omitting Unit so that you don't inadvertently specify an incorrect unit that is not published for this metric. Doing so causes the alarm to be stuck in the INSUFFICIENT DATA state.

" + }, + "EvaluationPeriods":{ + "shape":"EvaluationPeriods", + "documentation":"

The number of periods over which data is compared to the specified threshold. If you are setting an alarm that requires that a number of consecutive data points be breaching to trigger the alarm, this value specifies that number. If you are setting an \"M out of N\" alarm, this value is the N.

An alarm's total current evaluation period can be no longer than one day, so this number multiplied by Period cannot be more than 86,400 seconds.

" + }, + "DatapointsToAlarm":{ + "shape":"DatapointsToAlarm", + "documentation":"

The number of data points that must be breaching to trigger the alarm. This is used only if you are setting an \"M out of N\" alarm. In that case, this value is the M. For more information, see Evaluating an Alarm in the Amazon CloudWatch User Guide.

" + }, + "Threshold":{ + "shape":"Threshold", + "documentation":"

The value against which the specified statistic is compared.

This parameter is required for alarms based on static thresholds, but should not be used for alarms based on anomaly detection models.

" + }, + "ComparisonOperator":{ + "shape":"ComparisonOperator", + "documentation":"

The arithmetic operation to use when comparing the specified statistic and threshold. The specified statistic value is used as the first operand.

The values LessThanLowerOrGreaterThanUpperThreshold, LessThanLowerThreshold, and GreaterThanUpperThreshold are used only for alarms based on anomaly detection models.

" + }, + "TreatMissingData":{ + "shape":"TreatMissingData", + "documentation":"

Sets how this alarm is to handle missing data points. If TreatMissingData is omitted, the default behavior of missing is used. For more information, see Configuring How CloudWatch Alarms Treats Missing Data.

Valid Values: breaching | notBreaching | ignore | missing

Alarms that evaluate metrics in the AWS/DynamoDB namespace always ignore missing data even if you choose a different option for TreatMissingData. When an AWS/DynamoDB metric has missing data, alarms that evaluate that metric remain in their current state.

" + }, + "EvaluateLowSampleCountPercentile":{ + "shape":"EvaluateLowSampleCountPercentile", + "documentation":"

Used only for alarms based on percentiles. If you specify ignore, the alarm state does not change during periods with too few data points to be statistically significant. If you specify evaluate or omit this parameter, the alarm is always evaluated and possibly changes state no matter how many data points are available. For more information, see Percentile-Based CloudWatch Alarms and Low Data Samples.

Valid Values: evaluate | ignore

" + }, + "Metrics":{ + "shape":"MetricDataQueries", + "documentation":"

An array of MetricDataQuery structures that enable you to create an alarm based on the result of a metric math expression. For each PutMetricAlarm operation, you must specify either MetricName or a Metrics array.

Each item in the Metrics array either retrieves a metric or performs a math expression.

One item in the Metrics array is the expression that the alarm watches. You designate this expression by setting ReturnData to true for this object in the array. For more information, see MetricDataQuery.

If you use the Metrics parameter, you cannot include the MetricName, Dimensions, Period, Namespace, Statistic, or ExtendedStatistic parameters of PutMetricAlarm in the same operation. Instead, you retrieve the metrics you are using in your math expression as part of the Metrics array.

" + }, + "CreationId":{ + "shape":"CreationId", + "internalonly":true + }, + "Tags":{ + "shape":"TagList", + "documentation":"

A list of key-value pairs to associate with the alarm. You can associate as many as 50 tags with an alarm. To be able to associate tags with the alarm when you create the alarm, you must have the cloudwatch:TagResource permission.

Tags can help you organize and categorize your resources. You can also use them to scope user permissions by granting a user permission to access or change only resources with certain tag values.

If you are using this operation to update an existing alarm, any tags you specify in this parameter are ignored. To change the tags of an existing alarm, use TagResource or UntagResource.

" + }, + "ThresholdMetricId":{ + "shape":"MetricId", + "documentation":"

If this is an alarm based on an anomaly detection model, make this value match the ID of the ANOMALY_DETECTION_BAND function.

For an example of how to use this parameter, see the Anomaly Detection Model Alarm example on this page.

If your alarm uses this parameter, it cannot have Auto Scaling actions.

" + }, + "AlarmManagerArn":{ + "shape":"AmazonResourceName", + "internalonly":true + } + } + }, + "PutMetricDataBatchInput":{ + "type":"structure", + "required":["MetricDataBatches"], + "members":{ + "MetricDataBatches":{"shape":"MetricDataBatches"} + } + }, + "PutMetricDataInput":{ + "type":"structure", + "required":[ + "Namespace", + "MetricData" + ], + "members":{ + "Namespace":{ + "shape":"Namespace", + "documentation":"

The namespace for the metric data. You can use ASCII characters for the namespace, except for control characters which are not supported.

To avoid conflicts with Amazon Web Services service namespaces, you should not specify a namespace that begins with AWS/

" + }, + "MetricData":{ + "shape":"MetricData", + "documentation":"

The data for the metric. The array can include no more than 1000 metrics per call.

" + } + } + }, + "PutMetricStreamInput":{ + "type":"structure", + "required":[ + "Name", + "FirehoseArn", + "RoleArn", + "OutputFormat" + ], + "members":{ + "Name":{ + "shape":"MetricStreamName", + "documentation":"

If you are creating a new metric stream, this is the name for the new stream. The name must be different than the names of other metric streams in this account and Region.

If you are updating a metric stream, specify the name of that stream here.

Valid characters are A-Z, a-z, 0-9, \"-\" and \"_\".

" + }, + "IncludeFilters":{ + "shape":"MetricStreamFilters", + "documentation":"

If you specify this parameter, the stream sends only the metrics from the metric namespaces that you specify here.

You cannot include IncludeFilters and ExcludeFilters in the same operation.

" + }, + "ExcludeFilters":{ + "shape":"MetricStreamFilters", + "documentation":"

If you specify this parameter, the stream sends metrics from all metric namespaces except for the namespaces that you specify here.

You cannot include ExcludeFilters and IncludeFilters in the same operation.

" + }, + "FirehoseArn":{ + "shape":"AmazonResourceName", + "documentation":"

The ARN of the Amazon Kinesis Data Firehose delivery stream to use for this metric stream. This Amazon Kinesis Data Firehose delivery stream must already exist and must be in the same account as the metric stream.

" + }, + "RoleArn":{ + "shape":"AmazonResourceName", + "documentation":"

The ARN of an IAM role that this metric stream will use to access Amazon Kinesis Data Firehose resources. This IAM role must already exist and must be in the same account as the metric stream. This IAM role must include the following permissions:

  • firehose:PutRecord

  • firehose:PutRecordBatch

" + }, + "OutputFormat":{ + "shape":"MetricStreamOutputFormat", + "documentation":"

The output format for the stream. Valid values are json and opentelemetry0.7. For more information about metric stream output formats, see Metric streams output formats.

" + }, + "Tags":{ + "shape":"TagList", + "documentation":"

A list of key-value pairs to associate with the metric stream. You can associate as many as 50 tags with a metric stream.

Tags can help you organize and categorize your resources. You can also use them to scope user permissions by granting a user permission to access or change only resources with certain tag values.

You can use this parameter only when you are creating a new metric stream. If you are using this operation to update an existing metric stream, any tags you specify in this parameter are ignored. To change the tags of an existing metric stream, use TagResource or UntagResource.

" + }, + "StatisticsConfigurations":{ + "shape":"MetricStreamStatisticsConfigurations", + "documentation":"

By default, a metric stream always sends the MAX, MIN, SUM, and SAMPLECOUNT statistics for each metric that is streamed. You can use this parameter to have the metric stream also send additional statistics in the stream. This array can have up to 100 members.

For each entry in this array, you specify one or more metrics and the list of additional statistics to stream for those metrics. The additional statistics that you can stream depend on the stream's OutputFormat. If the OutputFormat is json, you can stream any additional statistic that is supported by CloudWatch, listed in CloudWatch statistics definitions. If the OutputFormat is opentelemetry0.7, you can stream percentile statistics such as p95, p99.9, and so on.

" + }, + "IncludeLinkedAccountsMetrics":{ + "shape":"IncludeLinkedAccountsMetrics", + "documentation":"

If you are creating a metric stream in a monitoring account, specify true to include metrics from source accounts in the metric stream.

" + } + } + }, + "PutMetricStreamOutput":{ + "type":"structure", + "members":{ + "Arn":{ + "shape":"AmazonResourceName", + "documentation":"

The ARN of the metric stream.

" + } + } + }, + "PutVendedInsightRuleContributionsInput":{ + "type":"structure", + "required":["BinaryContributionsData"], + "members":{ + "BinaryContributionsData":{"shape":"InsightRuleBinaryData"} + } + }, + "PutVendedInsightRuleContributionsOutput":{ + "type":"structure", + "members":{ + "Failures":{"shape":"BatchFailures"} + } + }, + "Range":{ + "type":"structure", + "required":[ + "StartTime", + "EndTime" + ], + "members":{ + "StartTime":{ + "shape":"Timestamp", + "documentation":"

The start time of the range to exclude. The format is yyyy-MM-dd'T'HH:mm:ss. For example, 2019-07-01T23:59:59.

" + }, + "EndTime":{ + "shape":"Timestamp", + "documentation":"

The end time of the range to exclude. The format is yyyy-MM-dd'T'HH:mm:ss. For example, 2019-07-01T23:59:59.

" + } + }, + "documentation":"

Specifies one range of days or times to exclude from use for training an anomaly detection model.

", + "xmlOrder":[ + "StartTime", + "EndTime" + ] + }, + "RecentlyActive":{ + "type":"string", + "enum":["PT3H"] + }, + "ReferenceId":{ + "type":"structure", + "members":{ + "ServiceId":{"shape":"ServiceId"}, + "ServiceOperationId":{"shape":"ServiceOperationId"}, + "SloName":{"shape":"ServiceLevelObjectiveName"} + }, + "union":true + }, + "Region":{"type":"string"}, + "RemoteOperationName":{"type":"string"}, + "RemoveActionInternalInput":{ + "type":"structure", + "required":[ + "AWSAccountId", + "ActionName" + ], + "members":{ + "AWSAccountId":{"shape":"AWSAccountId"}, + "ActionName":{"shape":"ResourceName"}, + "DeleteEmptyMonitors":{"shape":"DeleteEmptyMonitors"}, + "AlarmNames":{"shape":"AlarmNames"} + } + }, + "RemoveActionInternalOutput":{ + "type":"structure", + "required":["DeletedAlarms"], + "members":{ + "DeletedAlarms":{"shape":"DeletedAlarms"} + } + }, + "ResourceId":{"type":"string"}, + "ResourceIdentifier":{ + "type":"structure", + "required":["Arn"], + "members":{ + "Arn":{"shape":"AmazonResourceName"} + } + }, + "ResourceIdentifiers":{ + "type":"list", + "member":{"shape":"ResourceIdentifier"}, + "max":100, + "min":1 + }, + "ResourceList":{ + "type":"list", + "member":{"shape":"ResourceName"}, + "max":5 + }, + "ResourceName":{ + "type":"string", + "max":1024, + "min":1 + }, + "ResourceNotFound":{ + "type":"structure", + "members":{ + "message":{ + "shape":"ErrorMessage", + "documentation":"

" + } + }, + "documentation":"

The named resource does not exist.

", + "error":{ + "code":"ResourceNotFound", + "httpStatusCode":404, + "senderFault":true + }, + "exception":true + }, + "ResourceNotFoundException":{ + "type":"structure", + "members":{ + "ResourceType":{"shape":"ResourceType"}, + "ResourceId":{"shape":"ResourceId"} + }, + "documentation":"

The named resource does not exist.

", + "error":{ + "code":"ResourceNotFoundException", + "httpStatusCode":404, + "senderFault":true + }, + "exception":true + }, + "ResourceType":{"type":"string"}, + "ReturnData":{"type":"boolean"}, + "ReturnEvaluationMetadata":{"type":"boolean"}, + "RollingInterval":{ + "type":"structure", + "required":[ + "DurationUnit", + "Duration" + ], + "members":{ + "DurationUnit":{"shape":"DurationUnit"}, + "Duration":{"shape":"RollingIntervalDuration"} + } + }, + "RollingIntervalDuration":{ + "type":"integer", + "box":true + }, + "RuleTemplateProperties":{ + "type":"structure", + "members":{ + "TemplateName":{"shape":"TemplateName"} + }, + "internalonly":true + }, + "ScanBy":{ + "type":"string", + "enum":[ + "TimestampDescending", + "TimestampAscending" + ] + }, + "SdbDatastoreEndpoint":{"type":"string"}, + "SdbDatastoreEndpoints":{ + "type":"list", + "member":{"shape":"SdbDatastoreEndpoint"} + }, + "SegmentId":{ + "type":"integer", + "min":0 + }, + "Service":{ + "type":"structure", + "required":[ + "Name", + "Id", + "Attributes", + "Operations" + ], + "members":{ + "Name":{"shape":"ServiceName"}, + "Id":{"shape":"ServiceId"}, + "Attributes":{"shape":"Attributes"}, + "Operations":{"shape":"Operations"}, + "Dependencies":{"shape":"Dependencies"}, + "CanaryArns":{"shape":"CanaryArns"}, + "AppMonitorArns":{"shape":"AppMonitorArns"} + } + }, + "ServiceData":{ + "type":"list", + "member":{"shape":"ServiceDatum"} + }, + "ServiceDataTotalCount":{ + "type":"integer", + "box":true + }, + "ServiceDatum":{ + "type":"structure", + "members":{ + "Attributes":{"shape":"AttributesMap"}, + "MetricReferences":{"shape":"MetricReferences"}, + "SliReport":{"shape":"ServiceLevelIndicatorReport"}, + "Data":{"shape":"Data"} + } + }, + "ServiceId":{ + "type":"string", + "pattern":"arn:[^:]*:[^:]*:[^:]*:[^:]*:.*" + }, + "ServiceLevelIndicator":{ + "type":"structure", + "required":[ + "MetricThreshold", + "ComparisonOperator" + ], + "members":{ + "StandardMetrics":{"shape":"StandardMetrics"}, + "CustomMetrics":{"shape":"CustomMetrics"}, + "MetricThreshold":{"shape":"ServiceLevelIndicatorMetricThreshold"}, + "ComparisonOperator":{"shape":"ServiceLevelIndicatorComparisonOperator"} + } + }, + "ServiceLevelIndicatorComparisonOperator":{ + "type":"string", + "enum":[ + "GreaterThanOrEqualTo", + "GreaterThan", + "LessThan", + "LessThanOrEqualTo" + ] + }, + "ServiceLevelIndicatorConfig":{ + "type":"structure", + "required":[ + "MetricThreshold", + "ComparisonOperator" + ], + "members":{ + "StandardMetricsConfig":{"shape":"StandardMetricsConfig"}, + "CustomMetricsConfig":{"shape":"CustomMetricsConfig"}, + "MetricThreshold":{"shape":"ServiceLevelIndicatorMetricThreshold"}, + "ComparisonOperator":{"shape":"ServiceLevelIndicatorComparisonOperator"} + } + }, + "ServiceLevelIndicatorMetricThreshold":{ + "type":"double", + "box":true + }, + "ServiceLevelIndicatorReport":{ + "type":"structure", + "required":[ + "Id", + "StartTime", + "EndTime", + "SliStatus", + "TotalSloCount", + "OkSloCount", + "BreachedSloCount", + "BreachedSloNames" + ], + "members":{ + "Id":{"shape":"ReferenceId"}, + "StartTime":{"shape":"Timestamp"}, + "EndTime":{"shape":"Timestamp"}, + "SliStatus":{"shape":"ServiceLevelIndicatorStatus"}, + "TotalSloCount":{"shape":"ServiceLevelObjectiveCount"}, + "OkSloCount":{"shape":"ServiceLevelObjectiveCount"}, + "BreachedSloCount":{"shape":"ServiceLevelObjectiveCount"}, + "BreachedSloNames":{"shape":"ServiceLevelObjectiveNames"} + } + }, + "ServiceLevelIndicatorReportError":{ + "type":"structure", + "required":[ + "Id", + "SliReportErrorCode", + "SliReportErrorMessage" + ], + "members":{ + "Id":{"shape":"ReferenceId"}, + "SliReportErrorCode":{"shape":"ServiceLevelIndicatorReportErrorCode"}, + "SliReportErrorMessage":{"shape":"ServiceLevelIndicatorReportErrorMessage"} + } + }, + "ServiceLevelIndicatorReportErrorCode":{"type":"string"}, + "ServiceLevelIndicatorReportErrorMessage":{"type":"string"}, + "ServiceLevelIndicatorReportErrors":{ + "type":"list", + "member":{"shape":"ServiceLevelIndicatorReportError"}, + "max":50, + "min":0 + }, + "ServiceLevelIndicatorReports":{ + "type":"list", + "member":{"shape":"ServiceLevelIndicatorReport"}, + "max":50, + "min":0 + }, + "ServiceLevelIndicatorStatus":{ + "type":"string", + "enum":[ + "OK", + "BREACHED", + "INSUFFICIENT_DATA" + ] + }, + "ServiceLevelObjective":{ + "type":"structure", + "required":[ + "Arn", + "Name", + "CreatedTime", + "LastUpdatedTime", + "Sli", + "Goal" + ], + "members":{ + "Arn":{"shape":"ServiceLevelObjectiveArn"}, + "Name":{"shape":"ServiceLevelObjectiveName"}, + "Description":{"shape":"ServiceLevelObjectiveDescription"}, + "CreatedTime":{"shape":"Timestamp"}, + "LastUpdatedTime":{"shape":"Timestamp"}, + "Sli":{"shape":"ServiceLevelIndicator"}, + "Goal":{"shape":"Goal"}, + "Tags":{"shape":"TagList"} + } + }, + "ServiceLevelObjectiveArn":{ + "type":"string", + "max":2048, + "min":1, + "pattern":"arn:[^:]*:[^:]*:[^:]*:[^:]*:.*" + }, + "ServiceLevelObjectiveBudgetReport":{ + "type":"structure", + "required":[ + "Arn", + "Name", + "StartTime", + "EndTime", + "BudgetStatus", + "PeriodSeconds", + "TotalBudgetSeconds" + ], + "members":{ + "Arn":{"shape":"ServiceLevelObjectiveArn"}, + "Name":{"shape":"ServiceLevelObjectiveName"}, + "StartTime":{"shape":"Timestamp"}, + "EndTime":{"shape":"Timestamp"}, + "BudgetStatus":{"shape":"ServiceLevelObjectiveBudgetStatus"}, + "PeriodSeconds":{"shape":"PeriodSeconds"}, + "TotalBudgetSeconds":{"shape":"TotalBudgetSeconds"}, + "StartTimeBudgetSecondsRemaining":{"shape":"StartTimeBudgetSecondsRemaining"}, + "EndTimeBudgetSecondsRemaining":{"shape":"EndTimeBudgetSecondsRemaining"}, + "StartTimeAttainment":{"shape":"StartTimeAttainment"}, + "EndTimeAttainment":{"shape":"EndTimeAttainment"}, + "Sli":{"shape":"ServiceLevelIndicator"}, + "Goal":{"shape":"Goal"} + } + }, + "ServiceLevelObjectiveBudgetReportError":{ + "type":"structure", + "required":[ + "Name", + "Arn", + "SloBudgetReportErrorCode", + "SloBudgetReportErrorMessage" + ], + "members":{ + "Name":{"shape":"ServiceLevelObjectiveName"}, + "Arn":{"shape":"ServiceLevelObjectiveArn"}, + "SloBudgetReportErrorCode":{"shape":"ServiceLevelObjectiveBudgetReportErrorCode"}, + "SloBudgetReportErrorMessage":{"shape":"ServiceLevelObjectiveBudgetReportErrorMessage"} + } + }, + "ServiceLevelObjectiveBudgetReportErrorMessage":{"type":"string"}, + "ServiceLevelObjectiveBudgetReportErrors":{ + "type":"list", + "member":{"shape":"ServiceLevelObjectiveBudgetReportError"}, + "max":50, + "min":0 + }, + "ServiceLevelObjectiveBudgetReportInputs":{ + "type":"list", + "member":{"shape":"GetServiceLevelObjectiveBudgetReportInput"}, + "max":50, + "min":1 + }, + "ServiceLevelObjectiveBudgetReports":{ + "type":"list", + "member":{"shape":"ServiceLevelObjectiveBudgetReport"}, + "max":50, + "min":0 + }, + "ServiceLevelObjectiveBudgetStatus":{ + "type":"string", + "enum":[ + "OK", + "WARNING", + "BREACHED", + "INSUFFICIENT_DATA" + ] + }, + "ServiceLevelObjectiveCount":{ + "type":"integer", + "box":true + }, + "ServiceLevelObjectiveDescription":{ + "type":"string", + "min":1 + }, + "ServiceLevelObjectiveInternalId":{ + "type":"string", + "min":1 + }, + "ServiceLevelObjectiveName":{ + "type":"string", + "pattern":"[0-9A-Za-z][-._0-9A-Za-z ]{0,126}[0-9A-Za-z]" + }, + "ServiceLevelObjectiveNames":{ + "type":"list", + "member":{"shape":"ServiceLevelObjectiveName"}, + "max":10, + "min":0 + }, + "ServiceLevelObjectiveSummaries":{ + "type":"list", + "member":{"shape":"ServiceLevelObjectiveSummary"} + }, + "ServiceLevelObjectiveSummary":{ + "type":"structure", + "required":[ + "Arn", + "Name" + ], + "members":{ + "Arn":{"shape":"ServiceLevelObjectiveArn"}, + "Name":{"shape":"ServiceLevelObjectiveName"} + } + }, + "ServiceName":{ + "type":"string", + "pattern":"[A-Za-z0-9 -]+" + }, + "ServiceOperationId":{ + "type":"structure", + "required":[ + "ServiceId", + "OperationName" + ], + "members":{ + "ServiceId":{"shape":"ServiceId"}, + "OperationName":{"shape":"OperationName"} + } + }, + "ServiceOperationName":{"type":"string"}, + "ServiceQuotaExceededException":{ + "type":"structure", + "members":{ + }, + "error":{ + "code":"ServiceQuotaExceededException", + "httpStatusCode":400, + "senderFault":true + }, + "exception":true + }, + "ServiceSummaries":{ + "type":"list", + "member":{"shape":"ServiceSummary"} + }, + "ServiceSummary":{ + "type":"structure", + "required":[ + "Name", + "Id" + ], + "members":{ + "Name":{"shape":"ServiceName"}, + "Id":{"shape":"ServiceId"}, + "AttributesReferenceId":{"shape":"String"}, + "Attributes":{"shape":"Attributes"} + } + }, + "SetAlarmStateInput":{ + "type":"structure", + "required":[ + "AlarmName", + "StateValue", + "StateReason" + ], + "members":{ + "AlarmName":{ + "shape":"AlarmName", + "documentation":"

The name of the alarm.

" + }, + "StateValue":{ + "shape":"StateValue", + "documentation":"

The value of the state.

" + }, + "StateReason":{ + "shape":"StateReason", + "documentation":"

The reason that this alarm is set to this specific state, in text format.

" + }, + "StateReasonData":{ + "shape":"StateReasonData", + "documentation":"

The reason that this alarm is set to this specific state, in JSON format.

For SNS or EC2 alarm actions, this is just informational. But for EC2 Auto Scaling or application Auto Scaling alarm actions, the Auto Scaling policy uses the information in this field to take the correct action.

" + } + } + }, + "ServiceLevelObjectiveBudgetReportErrorCode":{"type":"string"}, + "SingleMetricAnomalyDetector":{ + "type":"structure", + "members":{ + "AccountId":{ + "shape":"AccountId", + "internalonly":true + }, + "Namespace":{ + "shape":"Namespace", + "documentation":"

The namespace of the metric to create the anomaly detection model for.

" + }, + "MetricName":{ + "shape":"MetricName", + "documentation":"

The name of the metric to create the anomaly detection model for.

" + }, + "Dimensions":{ + "shape":"Dimensions", + "documentation":"

The metric dimensions to create the anomaly detection model for.

" + }, + "Stat":{ + "shape":"AnomalyDetectorMetricStat", + "documentation":"

The statistic to use for the metric and anomaly detection model.

" + } + }, + "documentation":"

Designates the CloudWatch metric and statistic that provides the time series the anomaly detector uses as input.

" + }, + "SingleMetricSearchTerm":{ + "type":"structure", + "members":{ + "Namespace":{"shape":"Namespace"}, + "MetricName":{"shape":"MetricName"}, + "Dimensions":{"shape":"Dimensions"} + }, + "internalonly":true + }, + "Size":{"type":"long"}, + "Sort":{ + "type":"structure", + "members":{ + "Field":{"shape":"TriageMetricName"}, + "Order":{"shape":"Order"} + } + }, + "SourceNodeId":{"type":"string"}, + "StackName":{"type":"string"}, + "StandardApplicationMetric":{ + "type":"string", + "enum":[ + "LATENCY", + "AVAILABILITY" + ] + }, + "StandardMetrics":{ + "type":"structure", + "required":[ + "ServiceId", + "MetricName", + "Metrics" + ], + "members":{ + "ServiceId":{"shape":"ServiceId"}, + "OperationName":{"shape":"OperationName"}, + "Dependency":{"shape":"StandardMetricsDependency"}, + "MetricName":{"shape":"StandardApplicationMetric"}, + "Statistic":{"shape":"StandardMetricsStatistic"}, + "PeriodSeconds":{"shape":"PeriodSeconds"}, + "Metrics":{"shape":"MetricDataQueries"} + } + }, + "StandardMetricsConfig":{ + "type":"structure", + "required":[ + "ServiceId", + "MetricName" + ], + "members":{ + "ServiceId":{"shape":"ServiceId"}, + "OperationName":{"shape":"OperationName"}, + "Dependency":{"shape":"StandardMetricsDependency"}, + "MetricName":{"shape":"StandardApplicationMetric"}, + "Statistic":{"shape":"StandardMetricsStatistic"}, + "PeriodSeconds":{"shape":"PeriodSeconds"} + } + }, + "StandardMetricsDependency":{"type":"string"}, + "StandardMetricsStatistic":{"type":"string"}, + "StandardUnit":{ + "type":"string", + "enum":[ + "Seconds", + "Microseconds", + "Milliseconds", + "Bytes", + "Kilobytes", + "Megabytes", + "Gigabytes", + "Terabytes", + "Bits", + "Kilobits", + "Megabits", + "Gigabits", + "Terabits", + "Percent", + "Count", + "Bytes/Second", + "Kilobytes/Second", + "Megabytes/Second", + "Gigabytes/Second", + "Terabytes/Second", + "Bits/Second", + "Kilobits/Second", + "Megabits/Second", + "Gigabits/Second", + "Terabits/Second", + "Count/Second", + "None" + ] + }, + "StartMetricStreamsInput":{ + "type":"structure", + "required":["Names"], + "members":{ + "Names":{ + "shape":"MetricStreamNames", + "documentation":"

The array of the names of metric streams to start streaming.

This is an \"all or nothing\" operation. If you do not have permission to access all of the metric streams that you list here, then none of the streams that you list in the operation will start streaming.

" + } + } + }, + "StartMetricStreamsOutput":{ + "type":"structure", + "members":{ + } + }, + "StartTimeAttainment":{ + "type":"double", + "box":true + }, + "StartTimeBudgetSecondsRemaining":{ + "type":"integer", + "box":true + }, + "Stat":{"type":"string"}, + "StateReason":{ + "type":"string", + "max":1023, + "min":0 + }, + "StateReasonData":{ + "type":"string", + "max":4000, + "min":0 + }, + "StateValue":{ + "type":"string", + "enum":[ + "OK", + "ALARM", + "INSUFFICIENT_DATA" + ] + }, + "Statistic":{ + "type":"string", + "enum":[ + "SampleCount", + "Average", + "Sum", + "Minimum", + "Maximum" + ] + }, + "StatisticReferences":{ + "type":"structure", + "required":["MetricReferences"], + "members":{ + "MetricReferences":{"shape":"MetricReferences"} + } + }, + "StatisticSet":{ + "type":"structure", + "required":[ + "SampleCount", + "Sum", + "Minimum", + "Maximum" + ], + "members":{ + "SampleCount":{ + "shape":"DatapointValue", + "documentation":"

The number of samples used for the statistic set.

" + }, + "Sum":{ + "shape":"DatapointValue", + "documentation":"

The sum of values for the sample set.

" + }, + "Minimum":{ + "shape":"DatapointValue", + "documentation":"

The minimum value of the sample set.

" + }, + "Maximum":{ + "shape":"DatapointValue", + "documentation":"

The maximum value of the sample set.

" + } + }, + "documentation":"

Represents a set of statistics that describes a specific metric.

" + }, + "Statistics":{ + "type":"list", + "member":{"shape":"Statistic"}, + "max":5, + "min":1 + }, + "StatusCode":{ + "type":"string", + "enum":[ + "Complete", + "InternalError", + "PartialData", + "Forbidden" + ] + }, + "StopMetricStreamsInput":{ + "type":"structure", + "required":["Names"], + "members":{ + "Names":{ + "shape":"MetricStreamNames", + "documentation":"

The array of the names of metric streams to stop streaming.

This is an \"all or nothing\" operation. If you do not have permission to access all of the metric streams that you list here, then none of the streams that you list in the operation will stop streaming.

" + } + } + }, + "StopMetricStreamsOutput":{ + "type":"structure", + "members":{ + } + }, + "StorageResolution":{ + "type":"integer", + "min":1 + }, + "String":{"type":"string"}, + "SuppressorPeriod":{"type":"integer"}, + "Tag":{ + "type":"structure", + "required":[ + "Key", + "Value" + ], + "members":{ + "Key":{ + "shape":"TagKey", + "documentation":"

A string that you can use to assign a value. The combination of tag keys and values can help you organize and categorize your resources.

" + }, + "Value":{ + "shape":"TagValue", + "documentation":"

The value for the specified tag key.

" + } + }, + "documentation":"

A key-value pair associated with a CloudWatch resource.

" + }, + "TagKey":{ + "type":"string", + "max":128, + "min":1 + }, + "TagKeyList":{ + "type":"list", + "member":{"shape":"TagKey"} + }, + "TagList":{ + "type":"list", + "member":{"shape":"Tag"} + }, + "TagResourceInput":{ + "type":"structure", + "required":[ + "ResourceARN", + "Tags" + ], + "members":{ + "ResourceARN":{ + "shape":"AmazonResourceName", + "documentation":"

The ARN of the CloudWatch resource that you're adding tags to.

The ARN format of an alarm is arn:aws:cloudwatch:Region:account-id:alarm:alarm-name

The ARN format of a Contributor Insights rule is arn:aws:cloudwatch:Region:account-id:insight-rule:insight-rule-name

For more information about ARN format, see Resource Types Defined by Amazon CloudWatch in the Amazon Web Services General Reference.

" + }, + "Tags":{ + "shape":"TagList", + "documentation":"

The list of key-value pairs to associate with the alarm.

" + } + } + }, + "TagResourceOutput":{ + "type":"structure", + "members":{ + } + }, + "TagValue":{ + "type":"string", + "max":256, + "min":0 + }, + "TagrisAccessDeniedException":{ + "type":"structure", + "members":{ + "message":{"shape":"TagrisExceptionMessage"} + }, + "exception":true + }, + "TagrisAccountId":{ + "type":"string", + "max":12, + "min":12 + }, + "TagrisAmazonResourceName":{ + "type":"string", + "max":1011, + "min":1 + }, + "TagrisExceptionMessage":{ + "type":"string", + "max":2048, + "min":0 + }, + "TagrisInternalId":{ + "type":"string", + "max":64, + "min":0 + }, + "TagrisInternalServiceException":{ + "type":"structure", + "members":{ + "message":{"shape":"TagrisExceptionMessage"} + }, + "exception":true, + "fault":true + }, + "TagrisInvalidArnException":{ + "type":"structure", + "members":{ + "message":{"shape":"TagrisExceptionMessage"}, + "sweepListItem":{"shape":"TagrisSweepListItem"} + }, + "exception":true + }, + "TagrisInvalidParameterException":{ + "type":"structure", + "members":{ + "message":{"shape":"TagrisExceptionMessage"} + }, + "exception":true + }, + "TagrisPartialResourcesExistResultsException":{ + "type":"structure", + "members":{ + "message":{"shape":"TagrisExceptionMessage"}, + "resourceExistenceInformation":{"shape":"TagrisSweepListResult"} + }, + "exception":true + }, + "TagrisStatus":{ + "type":"string", + "enum":[ + "ACTIVE", + "NOT_ACTIVE" + ] + }, + "TagrisSweepList":{ + "type":"list", + "member":{"shape":"TagrisSweepListItem"} + }, + "TagrisSweepListItem":{ + "type":"structure", + "members":{ + "TagrisAccountId":{"shape":"TagrisAccountId"}, + "TagrisAmazonResourceName":{"shape":"TagrisAmazonResourceName"}, + "TagrisInternalId":{"shape":"TagrisInternalId"}, + "TagrisVersion":{"shape":"TagrisVersion"} + } + }, + "TagrisSweepListResult":{ + "type":"map", + "key":{"shape":"TagrisAmazonResourceName"}, + "value":{"shape":"TagrisStatus"} + }, + "TagrisThrottledException":{ + "type":"structure", + "members":{ + "message":{"shape":"TagrisExceptionMessage"} + }, + "exception":true + }, + "TagrisVerifyResourcesExistInput":{ + "type":"structure", + "required":["TagrisSweepList"], + "members":{ + "TagrisSweepList":{"shape":"TagrisSweepList"} + } + }, + "TagrisVerifyResourcesExistOutput":{ + "type":"structure", + "required":["TagrisSweepListResult"], + "members":{ + "TagrisSweepListResult":{"shape":"TagrisSweepListResult"} + } + }, + "TagrisVersion":{"type":"long"}, + "TemplateName":{ + "type":"string", + "max":128, + "min":1, + "pattern":"[0-9A-Za-z][\\-\\.\\_0-9A-Za-z]{0,126}[0-9A-Za-z]" + }, + "Threshold":{"type":"double"}, + "Timestamp":{"type":"timestamp"}, + "Timestamps":{ + "type":"list", + "member":{"shape":"Timestamp"} + }, + "TopologyDiscoveryStatus":{ + "type":"string", + "enum":[ + "Enabled", + "Disabled" + ] + }, + "TopologyEdge":{ + "type":"structure", + "required":[ + "SourceNodeId", + "DestinationNodeId", + "EdgeId" + ], + "members":{ + "SourceNodeId":{"shape":"SourceNodeId"}, + "DestinationNodeId":{"shape":"DestinationNodeId"}, + "EdgeId":{"shape":"EdgeId"}, + "StatisticReferences":{"shape":"StatisticReferences"} + } + }, + "TopologyEdges":{ + "type":"list", + "member":{"shape":"TopologyEdge"} + }, + "TopologyNode":{ + "type":"structure", + "required":[ + "Name", + "Type", + "NodeId", + "Attributes", + "StatisticReferences" + ], + "members":{ + "Name":{"shape":"NodeName"}, + "Type":{"shape":"NodeType"}, + "NodeId":{"shape":"NodeId"}, + "Attributes":{"shape":"Attributes"}, + "StatisticReferences":{"shape":"StatisticReferences"}, + "AggregatedNodeIds":{"shape":"AggregatedNodeIds"} + } + }, + "TopologyNodes":{ + "type":"list", + "member":{"shape":"TopologyNode"} + }, + "TotalBudgetSeconds":{ + "type":"integer", + "box":true + }, + "TotalMetricsCount":{"type":"long"}, + "TotalSegments":{ + "type":"integer", + "min":1 + }, + "TreatMissingData":{ + "type":"string", + "max":255, + "min":1 + }, + "TriageAttribute":{"type":"string"}, + "TriageAttributes":{ + "type":"list", + "member":{"shape":"TriageAttribute"} + }, + "TriageDatumId":{"type":"string"}, + "TriageDatumValue":{ + "type":"double", + "box":true + }, + "TriageError":{ + "type":"structure", + "required":[ + "Name", + "ErrorCode", + "ErrorMessage" + ], + "members":{ + "Name":{"shape":"TriageErrorName"}, + "ErrorCode":{"shape":"TriageErrorCode"}, + "ErrorMessage":{"shape":"TriageErrorMessage"} + } + }, + "TriageErrorCode":{"type":"string"}, + "TriageErrorMessage":{"type":"string"}, + "TriageErrorName":{"type":"string"}, + "TriageFilterName":{ + "type":"string", + "enum":[ + "Slo", + "OperationName", + "CanaryName", + "RemoteOperationName", + "DependencyName" + ] + }, + "TriageMetricName":{ + "type":"string", + "enum":[ + "Slo", + "Availability", + "Duration", + "Error", + "Failed", + "Fault", + "LatencyP50", + "LatencyP90", + "LatencyP99", + "SuccessPercent", + "Volume", + "PageLoads", + "LargestContentfulPaint", + "FirstInputDelay", + "CumulativeLayoutShift", + "JSError", + "AjaxError" + ] + }, + "TriageStatistic":{ + "type":"string", + "enum":[ + "SAMPLECOUNT", + "SUM", + "AVERAGE", + "MINIMUM", + "MAXIMUM", + "PERCENTILE", + "P99", + "P90" + ] + }, + "URI":{"type":"string"}, + "Unit":{ + "type":"string", + "enum":[ + "Microseconds", + "Milliseconds", + "Seconds", + "Bytes", + "Kilobytes", + "Megabytes", + "Gigabytes", + "Terabytes", + "Bits", + "Kilobits", + "Megabits", + "Gigabits", + "Terabits", + "Percent", + "Count", + "Bytes/Second", + "Kilobytes/Second", + "Megabytes/Second", + "Gigabytes/Second", + "Terabytes/Second", + "Bits/Second", + "Kilobits/Second", + "Megabits/Second", + "Gigabits/Second", + "Terabits/Second", + "Count/Second", + "None" + ] + }, + "UntagResourceInput":{ + "type":"structure", + "required":[ + "ResourceARN", + "TagKeys" + ], + "members":{ + "ResourceARN":{ + "shape":"AmazonResourceName", + "documentation":"

The ARN of the CloudWatch resource that you're removing tags from.

The ARN format of an alarm is arn:aws:cloudwatch:Region:account-id:alarm:alarm-name

The ARN format of a Contributor Insights rule is arn:aws:cloudwatch:Region:account-id:insight-rule:insight-rule-name

For more information about ARN format, see Resource Types Defined by Amazon CloudWatch in the Amazon Web Services General Reference.

" + }, + "TagKeys":{ + "shape":"TagKeyList", + "documentation":"

The list of tag keys to remove from the resource.

" + } + } + }, + "UntagResourceOutput":{ + "type":"structure", + "members":{ + } + }, + "UpdateInsightRulesTtlInput":{ + "type":"structure", + "required":["RulesTtl"], + "members":{ + "TargetAccountId":{ + "shape":"AccountId", + "internalonly":true + }, + "RulesTtl":{"shape":"InsightRulesTtl"} + } + }, + "UpdateInsightRulesTtlOutput":{ + "type":"structure", + "members":{ + "Failures":{"shape":"BatchFailures"} + } + }, + "UpdateMetricStreamSegmentationDataInput":{ + "type":"structure", + "members":{ + "AccountId":{"shape":"MetricStreamAccountId"}, + "Name":{"shape":"MetricStreamName"}, + "SegmentationData":{"shape":"MetricStreamSegmentationData"}, + "ValidFromDate":{"shape":"Timestamp"}, + "FiltersVersion":{"shape":"MetricStreamFiltersVersion"} + } + }, + "UpdateMetricStreamSegmentationDataOutput":{ + "type":"structure", + "members":{ + } + }, + "UpdateServiceLevelObjectiveInput":{ + "type":"structure", + "required":["Name"], + "members":{ + "Name":{"shape":"ServiceLevelObjectiveName"}, + "Description":{"shape":"ServiceLevelObjectiveDescription"}, + "SliConfig":{"shape":"ServiceLevelIndicatorConfig"}, + "Goal":{"shape":"Goal"}, + "PayerToken":{ + "shape":"PayerToken", + "internalonly":true + } + } + }, + "UpdateServiceLevelObjectiveOutput":{ + "type":"structure", + "required":["Slo"], + "members":{ + "Slo":{"shape":"ServiceLevelObjective"} + } + }, + "Values":{ + "type":"list", + "member":{"shape":"DatapointValue"} + }, + "VendedResourceRuleMapping":{ + "type":"structure", + "members":{ + "ResourceARN":{"shape":"AmazonResourceName"}, + "VendedRules":{"shape":"VendedRules"} + }, + "internalonly":true + }, + "VendedResourceRuleMappings":{ + "type":"list", + "member":{"shape":"VendedResourceRuleMapping"}, + "internalonly":true + }, + "VendedResourceType":{ + "type":"string", + "internalonly":true, + "max":128, + "min":1, + "pattern":"[0-9A-Za-z][\\-\\.\\_0-9A-Za-z]{0,126}[0-9A-Za-z]" + }, + "VendedRule":{ + "type":"structure", + "members":{ + "RuleARN":{"shape":"AmazonResourceName"}, + "VendedRuleType":{"shape":"VendedRuleType"}, + "RuleTemplateProperties":{"shape":"RuleTemplateProperties"} + }, + "internalonly":true + }, + "VendedRuleType":{ + "type":"string", + "enum":["RULE_TEMPLATE"], + "internalonly":true + }, + "VendedRules":{ + "type":"list", + "member":{"shape":"VendedRule"}, + "internalonly":true + }, + "WarningThreshold":{ + "type":"double", + "box":true + } + }, + "documentation":"

Amazon CloudWatch monitors your Amazon Web Services (Amazon Web Services) resources and the applications you run on Amazon Web Services in real time. You can use CloudWatch to collect and track metrics, which are the variables you want to measure for your resources and applications.

CloudWatch alarms send notifications or automatically change the resources you are monitoring based on rules that you define. For example, you can monitor the CPU usage and disk reads and writes of your Amazon EC2 instances. Then, use this data to determine whether you should launch additional instances to handle increased load. You can also use this data to stop under-used instances to save money.

In addition to monitoring the built-in metrics that come with Amazon Web Services, you can monitor your own custom metrics. With CloudWatch, you gain system-wide visibility into resource utilization, application performance, and operational health.

" +} diff --git a/spring-petclinic-admin-server/pom.xml b/spring-petclinic-admin-server/pom.xml new file mode 100644 index 0000000..6e274eb --- /dev/null +++ b/spring-petclinic-admin-server/pom.xml @@ -0,0 +1,74 @@ + + +4.0.0 + +org.springframework.samples.petclinic.admin +spring-petclinic-admin-server +jar +Spring Boot Admin server + + + org.springframework.samples + spring-petclinic-microservices + 2.6.7 + + + + 2.5.4 + 9090 + ${basedir}/../docker + + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + + + de.codecentric + spring-boot-admin-starter-server + ${spring-boot-admin.version} + + + de.codecentric + spring-boot-admin-server-ui + ${spring-boot-admin.version} + + + + + org.jolokia + jolokia-core + + + + + + + buildDocker + + + + com.spotify + docker-maven-plugin + ${docker.plugin.version} + + + + + + + diff --git a/spring-petclinic-admin-server/src/main/java/org/springframework/samples/petclinic/admin/SpringBootAdminApplication.java b/spring-petclinic-admin-server/src/main/java/org/springframework/samples/petclinic/admin/SpringBootAdminApplication.java new file mode 100644 index 0000000..49785d1 --- /dev/null +++ b/spring-petclinic-admin-server/src/main/java/org/springframework/samples/petclinic/admin/SpringBootAdminApplication.java @@ -0,0 +1,31 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.admin; + +import de.codecentric.boot.admin.server.config.EnableAdminServer; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; + +@SpringBootApplication +@EnableAdminServer +@EnableDiscoveryClient +public class SpringBootAdminApplication { + public static void main(String[] args) { + SpringApplication.run(SpringBootAdminApplication.class, args); + } + +} diff --git a/spring-petclinic-admin-server/src/main/resources/application.yml b/spring-petclinic-admin-server/src/main/resources/application.yml new file mode 100644 index 0000000..ecd6082 --- /dev/null +++ b/spring-petclinic-admin-server/src/main/resources/application.yml @@ -0,0 +1,15 @@ +spring: + application: + name: admin-server + config: + import: optional:configserver:${CONFIG_SERVER_URL:http://localhost:8888/} + +eureka: + instance: + preferIpAddress: true +--- +spring: + config: + activate: + on-profile: docker + import: configserver:http://config-server:8888 diff --git a/spring-petclinic-admin-server/src/main/resources/logback-spring.xml b/spring-petclinic-admin-server/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..5d03f79 --- /dev/null +++ b/spring-petclinic-admin-server/src/main/resources/logback-spring.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/spring-petclinic-api-gateway/.gitignore b/spring-petclinic-api-gateway/.gitignore new file mode 100644 index 0000000..c71ea97 --- /dev/null +++ b/spring-petclinic-api-gateway/.gitignore @@ -0,0 +1 @@ +/.apt_generated/ diff --git a/spring-petclinic-api-gateway/pom.xml b/spring-petclinic-api-gateway/pom.xml new file mode 100644 index 0000000..6580c47 --- /dev/null +++ b/spring-petclinic-api-gateway/pom.xml @@ -0,0 +1,190 @@ + + +4.0.0 + +org.springframework.samples.petclinic.api +spring-petclinic-api-gateway +jar +Spring PetClinic API Gateway + + + org.springframework.samples + spring-petclinic-microservices + 2.6.7 + + + + 3.3.7-1 + 3.6.0 + 1.8.2 + 1.0.20 + 1.8.0 + 8081 + ${basedir}/../docker + + + + + + org.springframework.boot + spring-boot-devtools + true + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.cloud + spring-cloud-starter-circuitbreaker-reactor-resilience4j + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + + org.springframework.cloud + spring-cloud-starter-gateway + + + + + org.jolokia + jolokia-core + + + org.projectlombok + lombok + provided + + + io.micrometer + micrometer-registry-prometheus + + + io.github.resilience4j + resilience4j-micrometer + + + + + org.webjars + angularjs + ${webjars-angular.version} + + + org.webjars + jquery + ${webjars-jquery.version} + + + org.webjars + bootstrap + ${webjars-bootstrap.version} + + + org.webjars + angular-ui-router + ${webjars-angular-ui-router.version} + + + org.webjars + webjars-locator-core + + + + + io.opentelemetry.instrumentation + opentelemetry-instrumentation-annotations + 1.22.1 + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + com.squareup.okhttp3 + mockwebserver + test + + + + + + + ro.isdc.wro4j + wro4j-maven-plugin + ${wro4j.version} + + + generate-resources + + run + + + + + ro.isdc.wro.maven.plugin.manager.factory.ConfigurableWroManagerFactory + ${project.build.directory}/classes/static/css + ${basedir}/src/main/wro/wro.xml + ${basedir}/src/main/wro/wro.properties + ${basedir}/src/main/less + + + + org.webjars + bootstrap + ${webjars-bootstrap.version} + + + + + org.mockito + mockito-core + ${mockito.version} + + + + + + + + + buildDocker + + + + com.spotify + docker-maven-plugin + ${docker.plugin.version} + + + + + + diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/ApiGatewayApplication.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/ApiGatewayApplication.java new file mode 100644 index 0000000..df86a6f --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/ApiGatewayApplication.java @@ -0,0 +1,90 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.api; + +import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig; +import io.github.resilience4j.timelimiter.TimeLimiterConfig; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.circuitbreaker.resilience4j.ReactiveResilience4JCircuitBreakerFactory; +import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder; +import org.springframework.cloud.client.circuitbreaker.Customizer; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.http.MediaType; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.reactive.function.server.RequestPredicates; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; + +import java.time.Duration; + + +/** + * @author Maciej Szarlinski + */ +@EnableDiscoveryClient +@SpringBootApplication +public class ApiGatewayApplication { + + public static void main(String[] args) { + SpringApplication.run(ApiGatewayApplication.class, args); + } + + @Bean + @LoadBalanced + RestTemplate loadBalancedRestTemplate() { + return new RestTemplate(); + } + + @Bean + @LoadBalanced + public WebClient.Builder loadBalancedWebClientBuilder() { + return WebClient.builder(); + } + + @Value("classpath:/static/index.html") + private Resource indexHtml; + + /** + * workaround solution for forwarding to index.html + * @see #9785 + */ + @Bean + RouterFunction routerFunction() { + RouterFunction router = RouterFunctions.resources("/**", new ClassPathResource("static/")) + .andRoute(RequestPredicates.GET("/"), + request -> ServerResponse.ok().contentType(MediaType.TEXT_HTML).bodyValue(indexHtml)); + return router; + } + + /** + * Default Resilience4j circuit breaker configuration + */ + @Bean + public Customizer defaultCustomizer() { + return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id) + .circuitBreakerConfig(CircuitBreakerConfig.ofDefaults()) + .timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(4)).build()) + .build()); + } +} diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/TracingRouteGatewayFilterFactory.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/TracingRouteGatewayFilterFactory.java new file mode 100644 index 0000000..2d66bb7 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/TracingRouteGatewayFilterFactory.java @@ -0,0 +1,51 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package org.springframework.samples.petclinic.api; + +import io.opentelemetry.instrumentation.annotations.SpanAttribute; +import io.opentelemetry.instrumentation.annotations.WithSpan; +import org.springframework.cloud.gateway.filter.GatewayFilter; +import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; +import org.springframework.cloud.gateway.route.Route; +import org.springframework.samples.petclinic.api.TracingRouteGatewayFilterFactory.Config; +import org.springframework.samples.petclinic.api.utils.WellKnownAttributes; +import org.springframework.stereotype.Component; + +import java.net.URI; + +import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR; +import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR; + +@Component +public class TracingRouteGatewayFilterFactory extends AbstractGatewayFilterFactory { + public TracingRouteGatewayFilterFactory() { + super(Config.class); + } + + @Override + public String name() { + return "Tracing"; + } + + @Override + public GatewayFilter apply(Config config) { + return (exchange, chain) -> { + Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR); + URI uri = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR); + if (uri == null) { + uri = exchange.getRequest().getURI(); + } + traceRouteInfo(route.getId(), uri.getPath()); + return chain.filter(exchange); + }; + } + + @WithSpan(value = "RecordRoute") + public void traceRouteInfo(@SpanAttribute(WellKnownAttributes.REMOTE_APPLICATION) String application, + @SpanAttribute(WellKnownAttributes.REMOTE_OPERATION) String operation) { + + } + + public static class Config { + } +} diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/application/CustomersServiceClient.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/application/CustomersServiceClient.java new file mode 100644 index 0000000..84dd840 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/application/CustomersServiceClient.java @@ -0,0 +1,117 @@ +/* + * Copyright 2002-2021 the original author or 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. + * + * Modifications Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package org.springframework.samples.petclinic.api.application; + +import io.opentelemetry.instrumentation.annotations.SpanAttribute; +import io.opentelemetry.instrumentation.annotations.WithSpan; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.samples.petclinic.api.dto.OwnerDetails; +import org.springframework.samples.petclinic.api.dto.OwnerRequest; +import org.springframework.samples.petclinic.api.dto.PetDetails; +import org.springframework.samples.petclinic.api.dto.PetRequest; +import org.springframework.samples.petclinic.api.dto.PetType; +import org.springframework.samples.petclinic.api.utils.WellKnownAttributes; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.server.ResponseStatusException; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import org.springframework.web.server.ResponseStatusException; + +/** + * @author Maciej Szarlinski + */ +@Component +@RequiredArgsConstructor +public class CustomersServiceClient { + + private final WebClient.Builder webClientBuilder; + + public Flux getOwners() { + return fluxQuery(OwnerDetails.class, "customers-service", "/owners"); + } + + @WithSpan + public Mono getOwner(final int ownerId) { + return webClientBuilder.build().get() + .uri("http://customers-service/owners/{ownerId}", ownerId) + .retrieve() + .onStatus( + HttpStatus.BAD_REQUEST::equals, + response -> response.bodyToMono(String.class).map(IllegalArgumentException::new)) + .bodyToMono(OwnerDetails.class); + } + +// @WithSpan + public Mono updateOwner(final int ownerId, final OwnerRequest ownerRequest) { + return webClientBuilder.build().put() + .uri("http://customers-service/owners/{ownerId}", ownerId) + .body(Mono.just(ownerRequest), OwnerRequest.class) + .retrieve() + .bodyToMono(Void.class); + } + + @WithSpan + public Mono addOwner(final OwnerRequest ownerRequest) { + return webClientBuilder.build().post() + .uri("http://customers-service/owners") + .body(Mono.just(ownerRequest), OwnerRequest.class) + .retrieve() + .bodyToMono(Void.class); + } + + public Flux getPetTypes() { + return fluxQuery(PetType.class, "customers-service", "/petTypes"); + } + + @WithSpan + public Mono getPet(final int ownerId, final int petId) { + return webClientBuilder.build().get() + .uri("http://customers-service/owners/{ownerId}/pets/{petId}", ownerId, petId) + .retrieve() + .bodyToMono(PetDetails.class); + } + + @WithSpan + public Mono updatePet(final int ownerId, final int petId, final PetRequest petRequest) { + return webClientBuilder.build().put() + .uri("http://customers-service/owners/{ownerId}/pets/{petId}", ownerId, petId) + .body(Mono.just(petRequest), PetRequest.class) + .retrieve() + .bodyToMono(Void.class); + } + + @WithSpan + public Mono addPet(final int ownerId, final PetRequest petRequest) { + return webClientBuilder.build().post() + .uri("http://customers-service/owners/{ownerId}/pets", ownerId) + .body(Mono.just(petRequest), PetRequest.class) + .retrieve() + .bodyToMono(Void.class); + } + + @WithSpan + private Flux fluxQuery(Class clazz, + @SpanAttribute(WellKnownAttributes.REMOTE_APPLICATION) String host, + @SpanAttribute(WellKnownAttributes.REMOTE_OPERATION) String path, + Object... params) { + return webClientBuilder.build().get().uri(String.format("http://%s%s", host, path), params).retrieve().bodyToFlux(clazz); + } +} diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/application/VetsServiceClient.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/application/VetsServiceClient.java new file mode 100644 index 0000000..ee2e465 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/application/VetsServiceClient.java @@ -0,0 +1,27 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package org.springframework.samples.petclinic.api.application; + +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.instrumentation.annotations.WithSpan; +import lombok.RequiredArgsConstructor; +import org.springframework.samples.petclinic.api.dto.VetDetails; +import org.springframework.samples.petclinic.api.utils.WellKnownAttributes; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Flux; + +@Component +@RequiredArgsConstructor +public class VetsServiceClient { + + private final WebClient.Builder webClientBuilder; + + @WithSpan + public Flux getVets() { + return webClientBuilder.build().get() + .uri("lb://vets-service/vets") + .retrieve() + .bodyToFlux(VetDetails.class); + } +} diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/application/VisitsServiceClient.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/application/VisitsServiceClient.java new file mode 100644 index 0000000..0072141 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/application/VisitsServiceClient.java @@ -0,0 +1,90 @@ +/* + * Copyright 2002-2021 the original author or 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. + * + * Modifications Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package org.springframework.samples.petclinic.api.application; + +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.instrumentation.annotations.WithSpan; +import lombok.RequiredArgsConstructor; +import org.springframework.samples.petclinic.api.dto.VisitDetails; +import org.springframework.samples.petclinic.api.dto.Visits; +import org.springframework.samples.petclinic.api.utils.WellKnownAttributes; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import java.util.List; + +import static java.util.stream.Collectors.joining; + +/** + * @author Maciej Szarlinski + */ +@Component +@RequiredArgsConstructor +public class VisitsServiceClient { + + // Could be changed for testing purpose + private String hostname = "http://visits-service/"; + + private final WebClient.Builder webClientBuilder; + + @WithSpan + public Mono getVisitsForPets(final List petIds) { + // Span.current().setAttribute(WellKnownAttributes.REMOTE_APPLICATION, "visits-service"); + // Span.current().setAttribute(WellKnownAttributes.REMOTE_OPERATION, "/pets/visits"); + return webClientBuilder.build() + .get() + .uri(hostname + "pets/visits?petId={petId}", joinIds(petIds)) + .retrieve() + .bodyToMono(Visits.class); + + } + + @WithSpan + public Mono getVisitsForOwnersPets(final int ownerId, final int petId) { + // Span.current().setAttribute(WellKnownAttributes.REMOTE_APPLICATION, "visits-service"); + // Span.current().setAttribute(WellKnownAttributes.REMOTE_OPERATION, "/owners/*/pets/{petId}/visits"); + return webClientBuilder.build() + .get() + .uri(hostname + "owners/{ownerId}/pets/{petId}/visits", ownerId, petId) + .retrieve() + .bodyToMono(Visits.class); + + } + + @WithSpan + public Mono addVisitForOwnersPets(final int ownerId, final int petId, final VisitDetails visitDetails) { + // Span.current().setAttribute(WellKnownAttributes.REMOTE_APPLICATION, "visits-service"); + // Span.current().setAttribute(WellKnownAttributes.REMOTE_OPERATION, "/owners/*/pets/{petId}/visits"); + return webClientBuilder.build() + .post() + .uri(hostname + "owners/{ownerId}/pets/{petId}/visits", ownerId, petId) + .body(Mono.just(visitDetails), VisitDetails.class) + .retrieve() + .bodyToMono(Void.class); + } + + private String joinIds(List petIds) { + return petIds.stream().map(Object::toString).collect(joining(",")); + } + + void setHostname(String hostname) { + this.hostname = hostname; + } +} diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/boundary/web/ApiController.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/boundary/web/ApiController.java new file mode 100644 index 0000000..bbade77 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/boundary/web/ApiController.java @@ -0,0 +1,90 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package org.springframework.samples.petclinic.api.boundary.web; + +import lombok.RequiredArgsConstructor; +import org.springframework.samples.petclinic.api.application.CustomersServiceClient; +import org.springframework.samples.petclinic.api.application.VetsServiceClient; +import org.springframework.samples.petclinic.api.application.VisitsServiceClient; +import org.springframework.samples.petclinic.api.dto.OwnerDetails; +import org.springframework.samples.petclinic.api.dto.OwnerRequest; +import org.springframework.samples.petclinic.api.dto.PetDetails; +import org.springframework.samples.petclinic.api.dto.PetRequest; +import org.springframework.samples.petclinic.api.dto.PetType; +import org.springframework.samples.petclinic.api.dto.VetDetails; +import org.springframework.samples.petclinic.api.dto.VisitDetails; +import org.springframework.samples.petclinic.api.dto.Visits; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/") +public class ApiController { + + private final CustomersServiceClient customersServiceClient; + private final VetsServiceClient vetsServiceClient; + private final VisitsServiceClient visitsServiceClient; + + @GetMapping(value = "customer/owners") + public Flux getOwners() { + return customersServiceClient.getOwners(); + } + + @GetMapping(value = "customer/owners/{ownerId}") + public Mono getOwner(final @PathVariable int ownerId) { + return customersServiceClient.getOwner(ownerId); + } + + @PutMapping(value = "customer/owners/{ownerId}") + public Mono getOwner(final @PathVariable int ownerId, @RequestBody OwnerRequest ownerRequest) { + return customersServiceClient.updateOwner(ownerId, ownerRequest); + } + + @PostMapping(value = "customer/owners") + public Mono addOwner(@RequestBody OwnerRequest ownerRequest) { + return customersServiceClient.addOwner(ownerRequest); + } + + @GetMapping(value = "customer/petTypes") + public Flux getPetTypes() { + return customersServiceClient.getPetTypes(); + } + + @GetMapping(value = "customer/owners/{ownerId}/pets/{petId}") + public Mono getPetTypes(final @PathVariable int ownerId, final @PathVariable int petId) { + return customersServiceClient.getPet(ownerId, petId); + } + + @PutMapping("customer/owners/{ownerId}/pets/{petId}") + public Mono updatePet(final @PathVariable int ownerId, final @PathVariable int petId, @RequestBody PetRequest petRequest) { + return customersServiceClient.updatePet(ownerId, petId, petRequest); + } + + @PostMapping("customer/owners/{ownerId}/pets") + public Mono addPet(final @PathVariable int ownerId, @RequestBody PetRequest petRequest) { + return customersServiceClient.addPet(ownerId, petRequest); + } + + @GetMapping(value = "vet/vets") + public Flux getVets() { + return vetsServiceClient.getVets(); + } + + @GetMapping(value = "visit/owners/{ownerId}/pets/{petId}/visits") + public Mono getVisits(final @PathVariable int ownerId, final @PathVariable int petId) { + return visitsServiceClient.getVisitsForOwnersPets(ownerId, petId); + } + + @PostMapping(value = "visit/owners/{ownerId}/pets/{petId}/visits") + public Mono addVisit(final @PathVariable int ownerId, final @PathVariable int petId, final @RequestBody VisitDetails visitDetails) { + return visitsServiceClient.addVisitForOwnersPets(ownerId, petId, visitDetails); + } +} diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/boundary/web/ApiGatewayController.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/boundary/web/ApiGatewayController.java new file mode 100644 index 0000000..3ee5e12 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/boundary/web/ApiGatewayController.java @@ -0,0 +1,83 @@ +/* + * Copyright 2002-2021 the original author or 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. + * + * Modifications Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package org.springframework.samples.petclinic.api.boundary.web; + +import lombok.RequiredArgsConstructor; +import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreaker; +import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreakerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.samples.petclinic.api.application.CustomersServiceClient; +import org.springframework.samples.petclinic.api.application.VisitsServiceClient; +import org.springframework.samples.petclinic.api.dto.OwnerDetails; +import org.springframework.samples.petclinic.api.dto.Visits; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.server.ServerResponse; +import org.springframework.web.server.ResponseStatusException; +import reactor.core.publisher.Mono; + +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * @author Maciej Szarlinski + */ +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/gateway") +public class ApiGatewayController { + + private final CustomersServiceClient customersServiceClient; + + private final VisitsServiceClient visitsServiceClient; + + private final ReactiveCircuitBreakerFactory cbFactory; + + @GetMapping(value = "owners/{ownerId}") + public Mono getOwnerDetails(final @PathVariable int ownerId) { + return customersServiceClient.getOwner(ownerId) + .onErrorResume(ex -> Mono.error(new ResponseStatusException(HttpStatus.BAD_REQUEST, ex.getMessage()))) + .flatMap(owner -> + visitsServiceClient.getVisitsForPets(owner.getPetIds()) + .transform(it -> { + ReactiveCircuitBreaker cb = cbFactory.create("getOwnerDetails"); + return cb.run(it, throwable -> emptyVisitsForPets()); + }) + .map(addVisitsToOwner(owner)) + ); + } + + private Function addVisitsToOwner(OwnerDetails owner) { + return visits -> { + owner.getPets() + .forEach(pet -> pet.getVisits() + .addAll(visits.getItems().stream() + .filter(v -> v.getPetId() == pet.getId()) + .collect(Collectors.toList())) + ); + return owner; + }; + } + + private Mono emptyVisitsForPets() { + return Mono.just(new Visits()); + } +} diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/OwnerDetails.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/OwnerDetails.java new file mode 100644 index 0000000..35391c0 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/OwnerDetails.java @@ -0,0 +1,52 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.api.dto; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +import static java.util.stream.Collectors.toList; + +/** + * @author Maciej Szarlinski + */ +@Data +public class OwnerDetails { + + private int id; + + private String firstName; + + private String lastName; + + private String address; + + private String city; + + private String telephone; + + private final List pets = new ArrayList<>(); + + @JsonIgnore + public List getPetIds() { + return pets.stream() + .map(PetDetails::getId) + .collect(toList()); + } +} diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/OwnerRequest.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/OwnerRequest.java new file mode 100644 index 0000000..c5fe86b --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/OwnerRequest.java @@ -0,0 +1,19 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package org.springframework.samples.petclinic.api.dto; + +import lombok.Data; + +@Data +public class OwnerRequest { + + private String firstName; + + private String lastName; + + private String address; + + private String city; + + private String telephone; +} diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/PetDetails.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/PetDetails.java new file mode 100644 index 0000000..bf064fe --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/PetDetails.java @@ -0,0 +1,39 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.api.dto; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Maciej Szarlinski + */ +@Data +public class PetDetails { + + private int id; + + private String name; + + private String birthDate; + + private PetType type; + + private final List visits = new ArrayList<>(); + +} diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/PetRequest.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/PetRequest.java new file mode 100644 index 0000000..759db39 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/PetRequest.java @@ -0,0 +1,23 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package org.springframework.samples.petclinic.api.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; + +import javax.validation.constraints.Size; +import java.util.Date; + +@Data +public class PetRequest { + + private int id; + + @JsonFormat(pattern = "yyyy-MM-dd") + private Date birthDate; + + @Size(min = 1) + private String name; + + private int typeId; +} diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/PetType.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/PetType.java new file mode 100644 index 0000000..a05e3ff --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/PetType.java @@ -0,0 +1,32 @@ +/* + * Copyright 2002-2021 the original author or 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. + * + * Modifications Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package org.springframework.samples.petclinic.api.dto; + +import lombok.Data; + +/** + * @author Maciej Szarlinski + */ +@Data +public class PetType { + + private String id; + + private String name; +} diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/SpecialtyDetails.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/SpecialtyDetails.java new file mode 100644 index 0000000..bf23317 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/SpecialtyDetails.java @@ -0,0 +1,13 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package org.springframework.samples.petclinic.api.dto; + +import lombok.Data; + +@Data +public class SpecialtyDetails { + + private Integer id; + + private String name; +} diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/VetDetails.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/VetDetails.java new file mode 100644 index 0000000..08d56ca --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/VetDetails.java @@ -0,0 +1,23 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package org.springframework.samples.petclinic.api.dto; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +@Data +public class VetDetails { + + private Integer id; + + private String firstName; + + private String lastName; + + private Set specialties; + + private final List pets = new ArrayList<>(); +} diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/VisitDetails.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/VisitDetails.java new file mode 100644 index 0000000..e9f3535 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/VisitDetails.java @@ -0,0 +1,35 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.api.dto; + +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author Maciej Szarlinski + */ +@Data +@NoArgsConstructor +public class VisitDetails { + + private Integer id = null; + + private Integer petId = null; + + private String date = null; + + private String description = null; +} diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/Visits.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/Visits.java new file mode 100644 index 0000000..fb5851f --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/dto/Visits.java @@ -0,0 +1,32 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.api.dto; + +import java.util.ArrayList; +import java.util.List; + +import lombok.NoArgsConstructor; +import lombok.Value; + +/** + * @author Maciej Szarlinski + */ +@Value +public class Visits { + + private List items = new ArrayList<>(); + +} diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/utils/WellKnownAttributes.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/utils/WellKnownAttributes.java new file mode 100644 index 0000000..212a845 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/utils/WellKnownAttributes.java @@ -0,0 +1,8 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package org.springframework.samples.petclinic.api.utils; + +public final class WellKnownAttributes { + public static final String REMOTE_APPLICATION = "aws.remote.application"; + public static final String REMOTE_OPERATION = "aws.remote.operation"; +} diff --git a/spring-petclinic-api-gateway/src/main/less/header.less b/spring-petclinic-api-gateway/src/main/less/header.less new file mode 100644 index 0000000..7cb1a78 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/less/header.less @@ -0,0 +1,73 @@ +.navbar { + border-top: 4px solid #6db33f; + background-color: #34302d; + margin-bottom: 0px; + border-bottom: 0; + border-left: 0; + border-right: 0; +} + +.navbar a.navbar-brand { + background: url("../images/spring-logo-dataflow.png") -1px -1px no-repeat; + margin: 12px 0 6px; + width: 229px; + height: 46px; + display: inline-block; + text-decoration: none; + padding: 0; +} + +.navbar a.navbar-brand span { + display: block; + width: 229px; + height: 46px; + background: url("../images/spring-logo-dataflow.png") -1px -48px no-repeat; + opacity: 0; + -moz-transition: opacity 0.12s ease-in-out; + -webkit-transition: opacity 0.12s ease-in-out; + -o-transition: opacity 0.12s ease-in-out; +} + +.navbar a:hover.navbar-brand span { + opacity: 1; +} + +.navbar li > a, .navbar-text { + font-family: "montserratregular", sans-serif; + text-shadow: none; + font-size: 14px; + +/* line-height: 14px; */ + padding: 28px 20px; + transition: all 0.15s; + -webkit-transition: all 0.15s; + -moz-transition: all 0.15s; + -o-transition: all 0.15s; + -ms-transition: all 0.15s; +} + +.navbar li > a { + text-transform: uppercase; +} + +.navbar .navbar-text { + margin-top: 0; + margin-bottom: 0; +} +.navbar li:hover > a { + color: #eeeeee; + background-color: #6db33f; +} + +.navbar-toggle { + border-width: 0; + + .icon-bar + .icon-bar { + margin-top: 3px; + } + .icon-bar { + width: 19px; + height: 3px; + } + +} diff --git a/spring-petclinic-api-gateway/src/main/less/petclinic.less b/spring-petclinic-api-gateway/src/main/less/petclinic.less new file mode 100644 index 0000000..26ff4ca --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/less/petclinic.less @@ -0,0 +1,250 @@ +/* + * Copyright 2016 the original author or authors. + * + * 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. + */ +@icon-font-path: "../webjars/bootstrap/fonts/"; + +@spring-green: #6db33f; +@spring-dark-green: #5fa134; +@spring-brown: #34302D; +@spring-grey: #838789; +@spring-light-grey: #f1f1f1; + +@body-bg: @spring-light-grey; +@text-color: @spring-brown; +@link-color: @spring-dark-green; +@link-hover-color: @spring-dark-green; + +@navbar-default-link-color: @spring-light-grey; +@navbar-default-link-active-color: @spring-light-grey; +@navbar-default-link-hover-color: @spring-light-grey; +@navbar-default-link-hover-bg: @spring-green; +@navbar-default-toggle-icon-bar-bg: @spring-light-grey; +@navbar-default-toggle-hover-bg: transparent; +@navbar-default-link-active-bg: @spring-green; + +@border-radius-base: 0; +@border-radius-large: 0; +@border-radius-small: 0; + +@btn-default-color: @spring-light-grey; +@btn-default-bg: @spring-brown; +@btn-default-border: @spring-green; + +@nav-tabs-active-link-hover-color: @spring-light-grey; +@nav-tabs-active-link-hover-bg: @spring-brown; +@nav-tabs-active-link-hover-border-color: @spring-brown; +@nav-tabs-border-color: @spring-brown; + +@pagination-active-bg: @spring-brown; +@pagination-active-border: @spring-green; +@table-border-color: @spring-brown; + +@import "typography.less"; +@import "header.less"; + +.table > thead > tr > th { + background-color: lighten(@spring-brown, 3%); + color: @spring-light-grey; +} + +.table-filter { + background-color: @spring-brown; + padding: 9px 12px; +} + +.nav > li > a { + color: @spring-grey; +} + +.btn-default { + border-width: 2px; + transition: border 0.15s; + -webkit-transition: border 0.15s; + -moz-transition: border 0.15s; + -o-transition: border 0.15s; + -ms-transition: border 0.15s; + + &:hover, + &:focus, + &:active, + &.active, + .open .dropdown-toggle& { + background-color: @spring-brown; + border-color: @spring-brown; + } +} + + +.container .text-muted { + margin: 20px 0; +} + +code { + font-size: 80%; +} + +.xd-container { + margin-top: 40px; + margin-bottom: 100px; + padding-left: 5px; + padding-right: 5px; +} + +h1 { + margin-bottom: 15px +} + +.index-page--subtitle { + font-size: 16px; + line-height: 24px; + margin: 0 0 30px; +} + +.form-horizontal button.btn-inverse { + margin-left: 32px; +} + +#job-params-modal .modal-dialog { + width: 90%; + margin-left:auto; + margin-right:auto; +} + +[ng-cloak].splash { + display: block !important; +} +[ng-cloak] { + display: none; +} + +.splash { + background: @spring-green; + color: @spring-brown; + display: none; +} + +.error-page { + margin-top: 100px; + text-align: center; +} + +.error-page .error-title { + font-size: 24px; + line-height: 24px; + margin: 30px 0 0; +} + +table td { + vertical-align: middle; +} + +table td .progress { + margin-bottom: 0; +} + +table td.action-column { + width: 1px; +} + +.help-block { + color: lighten(@text-color, 50%); // lighten the text some for contrast +} + +.xd-containers { + font-size: 15px; +} + +.cluster-view > table td { + vertical-align: top; +} + +.cluster-view .label, .cluster-view .column-block { + display: block; +} + +.cluster-view .input-group-addon { + width: 0%; +} + +.cluster-view { + margin-bottom: 0; +} + +.deployment-status-deployed { + .label-success; +} + +.deployment-status-incomplete { + .label-warning; +} + +.deployment-status-failed { + .label-danger; +} + +.deployment-status-deploying { + .label-info +} +.deployment-status-na { +} + +.container-details-table th { + background-color: lighten(@spring-brown, 3%); + color: @spring-light-grey; +} + +.status-help-content-table td { + color: @spring-brown; +} + +.alert-success { + .alert-variant(fade(@alert-success-bg, 70%); @alert-success-border; @alert-success-text); +} +.alert-info { + .alert-variant(fade(@alert-info-bg, 70%); @alert-info-border; @alert-info-text); +} +.alert-warning { + .alert-variant(fade(@alert-warning-bg, 70%); @alert-warning-border; @alert-warning-text); +} +.alert-danger { + .alert-variant(fade(@alert-danger-bg, 70%); @alert-danger-border; @alert-danger-text); +} + +.myspinner { + animation-name: spinner; + animation-duration: 2s; + animation-iteration-count: infinite; + animation-timing-function: linear; + + -webkit-transform-origin: 49% 50%; + -webkit-animation-name: spinner; + -webkit-animation-duration: 2s; + -webkit-animation-iteration-count: infinite; + -webkit-animation-timing-function: linear; +} + +@keyframes "spinner" { + from { transform: rotate( 0deg ); } + to { transform: rotate( 360deg ); } +} + +@-webkit-keyframes "spinner" { + from { -webkit-transform: rotate( 0deg ); } + to { -webkit-transform: rotate( 360deg ); } +} + +hr { + border-top: 1px dotted @spring-brown; +} + +@import "responsive.less"; diff --git a/spring-petclinic-api-gateway/src/main/less/responsive.less b/spring-petclinic-api-gateway/src/main/less/responsive.less new file mode 100644 index 0000000..8f3b215 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/less/responsive.less @@ -0,0 +1,41 @@ +@media (max-width: 768px) { + .navbar-toggle { + position:absolute; + z-index: 9999; + left:0px; + top:0px; + } + + .navbar a.navbar-brand { + display: block; + margin: 0 auto 0 auto; + width: 148px; + height: 50px; + float: none; + background: url("../images/spring-logo-dataflow-mobile.png") 0 center no-repeat; + } + + .homepage-billboard .homepage-subtitle { + font-size: 21px; + line-height: 21px; + } + + .navbar a.navbar-brand span { + display: none; + } + + .navbar { + border-top-width: 0; + } + + .xd-container { + margin-top: 20px; + margin-bottom: 30px; + } + + .index-page--subtitle { + margin-top: 10px; + margin-bottom: 30px; + } + +} diff --git a/spring-petclinic-api-gateway/src/main/less/typography.less b/spring-petclinic-api-gateway/src/main/less/typography.less new file mode 100644 index 0000000..8b8436e --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/less/typography.less @@ -0,0 +1,60 @@ +@font-face { + font-family: 'varela_roundregular'; + + src: url('../fonts/varela_round-webfont.eot'); + src: url('../fonts/varela_round-webfont.eot?#iefix') format('embedded-opentype'), + url('../fonts/varela_round-webfont.woff') format('woff'), + url('../fonts/varela_round-webfont.ttf') format('truetype'), + url('../fonts/varela_round-webfont.svg#varela_roundregular') format('svg'); + font-weight: normal; + font-style: normal; +} + +@font-face { + font-family: 'montserratregular'; + src: url('../fonts/montserrat-webfont.eot'); + src: url('../fonts/montserrat-webfont.eot?#iefix') format('embedded-opentype'), + url('../fonts/montserrat-webfont.woff') format('woff'), + url('../fonts/montserrat-webfont.ttf') format('truetype'), + url('../fonts/montserrat-webfont.svg#montserratregular') format('svg'); + font-weight: normal; + font-style: normal; +} + +body, h1, h2, h3, p, input { + margin: 0; + font-weight: 400; + font-family: "varela_roundregular", sans-serif; + color: #34302d; +} + +h1 { + font-size: 24px; + line-height: 30px; + font-family: "montserratregular", sans-serif; +} + +h2 { + font-size: 18px; + font-weight: 700; + line-height: 24px; + margin-bottom: 10px; + font-family: "montserratregular", sans-serif; +} + +h3 { + font-size: 16px; + line-height: 24px; + margin-bottom: 10px; + font-weight: 700; +} + +p { + //font-size: 15px; + //line-height: 24px; +} + +strong { + font-weight: 700; + font-family: "montserratregular", sans-serif; +} diff --git a/spring-petclinic-api-gateway/src/main/resources/application.yml b/spring-petclinic-api-gateway/src/main/resources/application.yml new file mode 100644 index 0000000..00687b1 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/application.yml @@ -0,0 +1,19 @@ +spring: + application: + name: api-gateway + config: + import: optional:configserver:${CONFIG_SERVER_URL:http://localhost:8888/} + +eureka: + instance: + preferIpAddress: true + client: + service-url: + defaultZone: ${DISCOVERY_SERVER_URL:http://localhost:8761/eureka} + +--- +spring: + config: + activate: + on-profile: docker + import: configserver:http://config-server:8888 diff --git a/spring-petclinic-api-gateway/src/main/resources/logback-spring.xml b/spring-petclinic-api-gateway/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..5d03f79 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/logback-spring.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/spring-petclinic-api-gateway/src/main/resources/messages/messages.properties b/spring-petclinic-api-gateway/src/main/resources/messages/messages.properties new file mode 100644 index 0000000..f916c7a --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/messages/messages.properties @@ -0,0 +1,7 @@ +required=is required +notFound=has not been found +duplicate=is already in use +nonNumeric=must be all numeric +duplicateFormSubmission=Duplicate form submission is not allowed +typeMismatch.date=invalid date +typeMismatch.birthDate=invalid date diff --git a/spring-petclinic-api-gateway/src/main/resources/messages/messages_de.properties b/spring-petclinic-api-gateway/src/main/resources/messages/messages_de.properties new file mode 100644 index 0000000..46c70b5 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/messages/messages_de.properties @@ -0,0 +1,7 @@ +required=muss angegeben werden +notFound=wurde nicht gefunden +duplicate=ist bereits vergeben +nonNumeric=darf nur numerisch sein +duplicateFormSubmission=Wiederholtes Absenden des Formulars ist nicht erlaubt +typeMismatch.date=ung�ltiges Datum +typeMismatch.birthDate=ung�ltiges Datum diff --git a/spring-petclinic-api-gateway/src/main/resources/messages/messages_en.properties b/spring-petclinic-api-gateway/src/main/resources/messages/messages_en.properties new file mode 100644 index 0000000..05d519b --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/messages/messages_en.properties @@ -0,0 +1 @@ +# This file is intentionally empty. Message look-ups will fall back to the default "messages.properties" file. \ No newline at end of file diff --git a/spring-petclinic-api-gateway/src/main/resources/static/fonts/montserrat-webfont.eot b/spring-petclinic-api-gateway/src/main/resources/static/fonts/montserrat-webfont.eot new file mode 100644 index 0000000..0caea91 Binary files /dev/null and b/spring-petclinic-api-gateway/src/main/resources/static/fonts/montserrat-webfont.eot differ diff --git a/spring-petclinic-api-gateway/src/main/resources/static/fonts/montserrat-webfont.svg b/spring-petclinic-api-gateway/src/main/resources/static/fonts/montserrat-webfont.svg new file mode 100644 index 0000000..7bd96bd --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/fonts/montserrat-webfont.svg @@ -0,0 +1,1283 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-petclinic-api-gateway/src/main/resources/static/fonts/montserrat-webfont.ttf b/spring-petclinic-api-gateway/src/main/resources/static/fonts/montserrat-webfont.ttf new file mode 100644 index 0000000..9953fe6 Binary files /dev/null and b/spring-petclinic-api-gateway/src/main/resources/static/fonts/montserrat-webfont.ttf differ diff --git a/spring-petclinic-api-gateway/src/main/resources/static/fonts/montserrat-webfont.woff b/spring-petclinic-api-gateway/src/main/resources/static/fonts/montserrat-webfont.woff new file mode 100644 index 0000000..eb49333 Binary files /dev/null and b/spring-petclinic-api-gateway/src/main/resources/static/fonts/montserrat-webfont.woff differ diff --git a/spring-petclinic-api-gateway/src/main/resources/static/fonts/varela_round-webfont.eot b/spring-petclinic-api-gateway/src/main/resources/static/fonts/varela_round-webfont.eot new file mode 100644 index 0000000..dfee0c2 Binary files /dev/null and b/spring-petclinic-api-gateway/src/main/resources/static/fonts/varela_round-webfont.eot differ diff --git a/spring-petclinic-api-gateway/src/main/resources/static/fonts/varela_round-webfont.svg b/spring-petclinic-api-gateway/src/main/resources/static/fonts/varela_round-webfont.svg new file mode 100644 index 0000000..3280e2c --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/fonts/varela_round-webfont.svg @@ -0,0 +1,7875 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-petclinic-api-gateway/src/main/resources/static/fonts/varela_round-webfont.ttf b/spring-petclinic-api-gateway/src/main/resources/static/fonts/varela_round-webfont.ttf new file mode 100644 index 0000000..3ca0666 Binary files /dev/null and b/spring-petclinic-api-gateway/src/main/resources/static/fonts/varela_round-webfont.ttf differ diff --git a/spring-petclinic-api-gateway/src/main/resources/static/fonts/varela_round-webfont.woff b/spring-petclinic-api-gateway/src/main/resources/static/fonts/varela_round-webfont.woff new file mode 100644 index 0000000..77ba166 Binary files /dev/null and b/spring-petclinic-api-gateway/src/main/resources/static/fonts/varela_round-webfont.woff differ diff --git a/spring-petclinic-api-gateway/src/main/resources/static/images/favicon.png b/spring-petclinic-api-gateway/src/main/resources/static/images/favicon.png new file mode 100644 index 0000000..1c649a3 Binary files /dev/null and b/spring-petclinic-api-gateway/src/main/resources/static/images/favicon.png differ diff --git a/spring-petclinic-api-gateway/src/main/resources/static/images/pets.png b/spring-petclinic-api-gateway/src/main/resources/static/images/pets.png new file mode 100644 index 0000000..bb5cf3a Binary files /dev/null and b/spring-petclinic-api-gateway/src/main/resources/static/images/pets.png differ diff --git a/spring-petclinic-api-gateway/src/main/resources/static/images/platform-bg.png b/spring-petclinic-api-gateway/src/main/resources/static/images/platform-bg.png new file mode 100644 index 0000000..5121858 Binary files /dev/null and b/spring-petclinic-api-gateway/src/main/resources/static/images/platform-bg.png differ diff --git a/spring-petclinic-api-gateway/src/main/resources/static/images/spring-logo-dataflow-mobile.png b/spring-petclinic-api-gateway/src/main/resources/static/images/spring-logo-dataflow-mobile.png new file mode 100644 index 0000000..45d24a6 Binary files /dev/null and b/spring-petclinic-api-gateway/src/main/resources/static/images/spring-logo-dataflow-mobile.png differ diff --git a/spring-petclinic-api-gateway/src/main/resources/static/images/spring-logo-dataflow.png b/spring-petclinic-api-gateway/src/main/resources/static/images/spring-logo-dataflow.png new file mode 100644 index 0000000..ff7cdbb Binary files /dev/null and b/spring-petclinic-api-gateway/src/main/resources/static/images/spring-logo-dataflow.png differ diff --git a/spring-petclinic-api-gateway/src/main/resources/static/images/spring-pivotal-logo.png b/spring-petclinic-api-gateway/src/main/resources/static/images/spring-pivotal-logo.png new file mode 100644 index 0000000..1840af2 Binary files /dev/null and b/spring-petclinic-api-gateway/src/main/resources/static/images/spring-pivotal-logo.png differ diff --git a/spring-petclinic-api-gateway/src/main/resources/static/index.html b/spring-petclinic-api-gateway/src/main/resources/static/index.html new file mode 100644 index 0000000..c947c3e --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/index.html @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + PetClinic :: a Spring Framework demonstration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+
+ + + + diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/app.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/app.js new file mode 100644 index 0000000..66db62a --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/app.js @@ -0,0 +1,36 @@ +'use strict'; +/* App Module */ +var petClinicApp = angular.module('petClinicApp', [ + 'ui.router', 'infrastructure', 'layoutNav', 'layoutFooter', 'layoutWelcome', + 'ownerList', 'ownerDetails', 'ownerForm', 'petForm', 'visits', 'vetList']); + +petClinicApp.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', '$httpProvider', function( + $stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) { + + // safari turns to be lazy sending the Cache-Control header + $httpProvider.defaults.headers.common["Cache-Control"] = 'no-cache'; + $httpProvider.interceptors.push('HttpErrorHandlingInterceptor'); + + $locationProvider.hashPrefix('!'); + + $urlRouterProvider.otherwise('/welcome'); + $stateProvider + .state('app', { + abstract: true, + url: '', + template: '' + }) + .state('welcome', { + parent: 'app', + url: '/welcome', + template: '' + }); +}]); + +['welcome', 'nav', 'footer'].forEach(function(c) { + var mod = 'layout' + c.toUpperCase().substring(0, 1) + c.substring(1); + angular.module(mod, []); + angular.module(mod).component(mod, { + templateUrl: "scripts/fragments/" + c + ".html" + }); +}); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/fragments/footer.html b/spring-petclinic-api-gateway/src/main/resources/static/scripts/fragments/footer.html new file mode 100644 index 0000000..cc1e7c5 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/fragments/footer.html @@ -0,0 +1,6 @@ +
+
+
Sponsored by Pivotal
+
+
\ No newline at end of file diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/fragments/nav.html b/spring-petclinic-api-gateway/src/main/resources/static/scripts/fragments/nav.html new file mode 100644 index 0000000..6005cfe --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/fragments/nav.html @@ -0,0 +1,38 @@ + diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/fragments/welcome.html b/spring-petclinic-api-gateway/src/main/resources/static/scripts/fragments/welcome.html new file mode 100644 index 0000000..df0b55e --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/fragments/welcome.html @@ -0,0 +1,7 @@ +

Welcome to Petclinic

+ +
+
+ pets logo +
+
\ No newline at end of file diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/infrastructure/httpErrorHandlingInterceptor.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/infrastructure/httpErrorHandlingInterceptor.js new file mode 100644 index 0000000..f65ab68 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/infrastructure/httpErrorHandlingInterceptor.js @@ -0,0 +1,17 @@ +'use strict'; + +/** + * Global HTTP errors handler. + */ +angular.module('infrastructure') + .factory('HttpErrorHandlingInterceptor', function () { + return { + responseError: function (response) { + var error = response.data; + alert(error.error + "\r\n" + error.errors.map(function (e) { + return e.field + ": " + e.defaultMessage; + }).join("\r\n")); + return response; + } + } + }); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/infrastructure/infrastructure.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/infrastructure/infrastructure.js new file mode 100644 index 0000000..58dd767 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/infrastructure/infrastructure.js @@ -0,0 +1,3 @@ +'use strict'; + +angular.module('infrastructure', []); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-details/owner-details.component.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-details/owner-details.component.js new file mode 100644 index 0000000..98a43fc --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-details/owner-details.component.js @@ -0,0 +1,7 @@ +'use strict'; + +angular.module('ownerDetails') + .component('ownerDetails', { + templateUrl: 'scripts/owner-details/owner-details.template.html', + controller: 'OwnerDetailsController' + }); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-details/owner-details.controller.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-details/owner-details.controller.js new file mode 100644 index 0000000..d164378 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-details/owner-details.controller.js @@ -0,0 +1,10 @@ +'use strict'; + +angular.module('ownerDetails') + .controller('OwnerDetailsController', ['$http', '$stateParams', function ($http, $stateParams) { + var self = this; + + $http.get('api/gateway/owners/' + $stateParams.ownerId).then(function (resp) { + self.owner = resp.data; + }); + }]); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-details/owner-details.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-details/owner-details.js new file mode 100644 index 0000000..670f24b --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-details/owner-details.js @@ -0,0 +1,11 @@ +'use strict'; + +angular.module('ownerDetails', ['ui.router']) + .config(['$stateProvider', function ($stateProvider) { + $stateProvider + .state('ownerDetails', { + parent: 'app', + url: '/owners/details/:ownerId', + template: '' + }) + }]); \ No newline at end of file diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-details/owner-details.template.html b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-details/owner-details.template.html new file mode 100644 index 0000000..ed2810f --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-details/owner-details.template.html @@ -0,0 +1,70 @@ +

Owner Information

+ + + + + + + + + + + + + + + + + + + + + + +
Name{{$ctrl.owner.firstName}} {{$ctrl.owner.lastName}}
Address{{$ctrl.owner.address}}
City{{$ctrl.owner.city}}
Telephone{{$ctrl.owner.telephone}}
+ Edit Owner + + Add New Pet +
+ +

Pets and Visits

+ + + + + + +
+
+
Name
+
{{pet.name}}
+
Birth Date
+
{{pet.birthDate | date:'yyyy MMM dd'}}
+
Type
+
{{pet.type.name}}
+
+
+ + + + + + + + + + + + + + + +
Visit DateDescription
{{visit.date | date:'yyyy MMM dd'}}{{visit.description}}
+ Edit Pet + + Add Visit +
+
+ + + diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-form/owner-form.component.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-form/owner-form.component.js new file mode 100644 index 0000000..e8dec69 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-form/owner-form.component.js @@ -0,0 +1,7 @@ +'use strict'; + +angular.module('ownerForm') + .component('ownerForm', { + templateUrl: 'scripts/owner-form/owner-form.template.html', + controller: 'OwnerFormController' + }); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-form/owner-form.controller.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-form/owner-form.controller.js new file mode 100644 index 0000000..d25f7a5 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-form/owner-form.controller.js @@ -0,0 +1,30 @@ +'use strict'; + +angular.module('ownerForm') + .controller('OwnerFormController', ["$http", '$state', '$stateParams', function ($http, $state, $stateParams) { + var self = this; + + var ownerId = $stateParams.ownerId || 0; + + if (!ownerId) { + self.owner = {}; + } else { + $http.get("api/customer/owners/" + ownerId).then(function (resp) { + self.owner = resp.data; + }); + } + + self.submitOwnerForm = function () { + var id = self.owner.id; + + if (id) { + $http.put('api/customer/owners/' + id, self.owner).then(function () { + $state.go('ownerDetails', {ownerId: ownerId}); + }); + } else { + $http.post('api/customer/owners', self.owner).then(function () { + $state.go('owners'); + }); + } + }; + }]); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-form/owner-form.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-form/owner-form.js new file mode 100644 index 0000000..1bb6159 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-form/owner-form.js @@ -0,0 +1,16 @@ +'use strict'; + +angular.module('ownerForm', ['ui.router']) + .config(['$stateProvider', function ($stateProvider) { + $stateProvider + .state('ownerNew', { + parent: 'app', + url: '/owners/new', + template: '' + }) + .state('ownerEdit', { + parent: 'app', + url: '/owners/:ownerId/edit', + template: '' + }) + }]); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-form/owner-form.template.html b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-form/owner-form.template.html new file mode 100644 index 0000000..17e97a3 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-form/owner-form.template.html @@ -0,0 +1,39 @@ +

Owner

+
+
+ + + First name is required. +
+ +
+ + + Last name is required. +
+ + +
+ + + Address is required. +
+ +
+ + + City is required. +
+ +
+ + + Telephone is required. +
+ +
+ +
+
+ diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-list/owner-list.component.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-list/owner-list.component.js new file mode 100644 index 0000000..55b6b25 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-list/owner-list.component.js @@ -0,0 +1,7 @@ +'use strict'; + +angular.module('ownerList') + .component('ownerList', { + templateUrl: 'scripts/owner-list/owner-list.template.html', + controller: 'OwnerListController' + }); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-list/owner-list.controller.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-list/owner-list.controller.js new file mode 100644 index 0000000..8229f43 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-list/owner-list.controller.js @@ -0,0 +1,10 @@ +'use strict'; + +angular.module('ownerList') + .controller('OwnerListController', ['$http', function ($http) { + var self = this; + + $http.get('api/customer/owners').then(function (resp) { + self.owners = resp.data; + }); + }]); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-list/owner-list.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-list/owner-list.js new file mode 100644 index 0000000..4714a2f --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-list/owner-list.js @@ -0,0 +1,11 @@ +'use strict'; + +angular.module('ownerList', ['ui.router']) + .config(['$stateProvider', function ($stateProvider) { + $stateProvider + .state('owners', { + parent: 'app', + url: '/owners', + template: '' + }) + }]); \ No newline at end of file diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-list/owner-list.template.html b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-list/owner-list.template.html new file mode 100644 index 0000000..fc78463 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/owner-list/owner-list.template.html @@ -0,0 +1,31 @@ +

Owners

+ +
+
+ +
+
+ + + + + + + + + + + + + + + + + + + +
NameCityTelephone
+ + {{owner.firstName}} {{owner.lastName}} + + {{owner.city}}{{owner.telephone}}
diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/pet-form/pet-form.component.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/pet-form/pet-form.component.js new file mode 100644 index 0000000..6f5e13b --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/pet-form/pet-form.component.js @@ -0,0 +1,7 @@ +'use strict'; + +angular.module('petForm') + .component('petForm', { + templateUrl: 'scripts/pet-form/pet-form.template.html', + controller: 'PetFormController' + }); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/pet-form/pet-form.controller.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/pet-form/pet-form.controller.js new file mode 100644 index 0000000..93bbb6c --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/pet-form/pet-form.controller.js @@ -0,0 +1,52 @@ +'use strict'; + +angular.module('petForm') + .controller('PetFormController', ['$http', '$state', '$stateParams', function ($http, $state, $stateParams) { + var self = this; + var ownerId = $stateParams.ownerId || 0; + + $http.get('api/customer/petTypes').then(function (resp) { + self.types = resp.data; + }).then(function () { + + var petId = $stateParams.petId || 0; + + if (petId) { // edit + $http.get("api/customer/owners/" + ownerId + "/pets/" + petId).then(function (resp) { + self.pet = resp.data; + self.pet.birthDate = new Date(self.pet.birthDate); + self.petTypeId = "" + self.pet.type.id; + }); + } else { + $http.get('api/customer/owners/' + ownerId).then(function (resp) { + self.pet = { + owner: resp.data.firstName + " " + resp.data.lastName + }; + self.petTypeId = "1"; + }) + + } + }); + + self.submit = function () { + var id = self.pet.id || 0; + + var data = { + id: id, + name: self.pet.name, + birthDate: self.pet.birthDate, + typeId: self.petTypeId + }; + + var req; + if (id) { + req = $http.put("api/customer/owners/" + ownerId + "/pets/" + id, data); + } else { + req = $http.post("api/customer/owners/" + ownerId + "/pets", data); + } + + req.then(function () { + $state.go('ownerDetails', {ownerId: ownerId}); + }); + }; + }]); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/pet-form/pet-form.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/pet-form/pet-form.js new file mode 100644 index 0000000..70292ad --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/pet-form/pet-form.js @@ -0,0 +1,16 @@ +'use strict'; + +angular.module('petForm', ['ui.router']) + .config(['$stateProvider', function ($stateProvider) { + $stateProvider + .state('petNew', { + parent: 'app', + url: '/owners/:ownerId/new-pet', + template: '' + }) + .state('petEdit', { + parent: 'app', + url: '/owners/:ownerId/pets/:petId', + template: '' + }) + }]); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/pet-form/pet-form.template.html b/spring-petclinic-api-gateway/src/main/resources/static/scripts/pet-form/pet-form.template.html new file mode 100644 index 0000000..76317e5 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/pet-form/pet-form.template.html @@ -0,0 +1,43 @@ +

Pet

+ +
+
+ +
+

{{$ctrl.pet.owner}}

+
+
+ +
+ +
+ + Name is required. +
+
+ +
+ +
+ + birth date is required. +
+
+ +
+ +
+ +
+
+ +
+
+ +
+
+
diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/vet-list/vet-list.component.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/vet-list/vet-list.component.js new file mode 100644 index 0000000..6d8e950 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/vet-list/vet-list.component.js @@ -0,0 +1,7 @@ +'use strict'; + +angular.module('vetList') + .component('vetList', { + templateUrl: 'scripts/vet-list/vet-list.template.html', + controller: 'VetListController' + }); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/vet-list/vet-list.controller.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/vet-list/vet-list.controller.js new file mode 100644 index 0000000..4adc7fc --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/vet-list/vet-list.controller.js @@ -0,0 +1,10 @@ +'use strict'; + +angular.module('vetList') + .controller('VetListController', ['$http', function ($http) { + var self = this; + + $http.get('api/vet/vets').then(function (resp) { + self.vetList = resp.data; + }); + }]); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/vet-list/vet-list.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/vet-list/vet-list.js new file mode 100644 index 0000000..bcecacc --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/vet-list/vet-list.js @@ -0,0 +1,11 @@ +'use strict'; + +angular.module('vetList', ['ui.router']) + .config(['$stateProvider', function ($stateProvider) { + $stateProvider + .state('vets', { + parent: 'app', + url: '/vets', + template: '' + }) + }]); \ No newline at end of file diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/vet-list/vet-list.template.html b/spring-petclinic-api-gateway/src/main/resources/static/scripts/vet-list/vet-list.template.html new file mode 100644 index 0000000..e705f05 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/vet-list/vet-list.template.html @@ -0,0 +1,15 @@ +

Veterinarians

+ + + + + + + + + + + + + +
NameSpecialties
{{vet.firstName}} {{vet.lastName}}{{specialty.name + ' '}}
diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/visits/visits.component.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/visits/visits.component.js new file mode 100644 index 0000000..0bfbcad --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/visits/visits.component.js @@ -0,0 +1,7 @@ +'use strict'; + +angular.module('visits') + .component('visits', { + templateUrl: 'scripts/visits/visits.template.html', + controller: 'VisitsController' + }); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/visits/visits.controller.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/visits/visits.controller.js new file mode 100644 index 0000000..d68798b --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/visits/visits.controller.js @@ -0,0 +1,25 @@ +'use strict'; + +angular.module('visits') + .controller('VisitsController', ['$http', '$state', '$stateParams', '$filter', function ($http, $state, $stateParams, $filter) { + var self = this; + var petId = $stateParams.petId || 0; + var url = "api/visit/owners/" + ($stateParams.ownerId || 0) + "/pets/" + petId + "/visits"; + self.date = new Date(); + self.desc = ""; + + $http.get(url).then(function (resp) { + self.visits = resp.data; + }); + + self.submit = function () { + var data = { + date: $filter('date')(self.date, "yyyy-MM-dd"), + description: self.desc + }; + + $http.post(url, data).then(function () { + $state.go('ownerDetails', { ownerId: $stateParams.ownerId }); + }); + }; + }]); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/visits/visits.js b/spring-petclinic-api-gateway/src/main/resources/static/scripts/visits/visits.js new file mode 100644 index 0000000..10821ac --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/visits/visits.js @@ -0,0 +1,11 @@ +'use strict'; + +angular.module('visits', ['ui.router']) + .config(['$stateProvider', function ($stateProvider) { + $stateProvider + .state('visits', { + parent: 'app', + url: '/owners/:ownerId/pets/:petId/visits', + template: '' + }) + }]); diff --git a/spring-petclinic-api-gateway/src/main/resources/static/scripts/visits/visits.template.html b/spring-petclinic-api-gateway/src/main/resources/static/scripts/visits/visits.template.html new file mode 100644 index 0000000..ee099fa --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/resources/static/scripts/visits/visits.template.html @@ -0,0 +1,27 @@ +

Visits

+ +
+ +
+ + +
+ +
+ + +
+ +
+ +
+ +
+ +

Previous Visits

+ + + + + +
{{v.date}}{{v.description}}
\ No newline at end of file diff --git a/spring-petclinic-api-gateway/src/main/wro/wro.properties b/spring-petclinic-api-gateway/src/main/wro/wro.properties new file mode 100644 index 0000000..bd6f3a8 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/wro/wro.properties @@ -0,0 +1,4 @@ +#List of preProcessors +preProcessors=lessCssImport +#List of postProcessors +postProcessors=less4j \ No newline at end of file diff --git a/spring-petclinic-api-gateway/src/main/wro/wro.xml b/spring-petclinic-api-gateway/src/main/wro/wro.xml new file mode 100644 index 0000000..8657468 --- /dev/null +++ b/spring-petclinic-api-gateway/src/main/wro/wro.xml @@ -0,0 +1,6 @@ + + + classpath:META-INF/resources/webjars/bootstrap/3.3.7-1/less/bootstrap.less + /petclinic.less + + diff --git a/spring-petclinic-api-gateway/src/test/java/org/springframework/samples/petclinic/api/ApiGatewayApplicationTests.java b/spring-petclinic-api-gateway/src/test/java/org/springframework/samples/petclinic/api/ApiGatewayApplicationTests.java new file mode 100644 index 0000000..5424703 --- /dev/null +++ b/spring-petclinic-api-gateway/src/test/java/org/springframework/samples/petclinic/api/ApiGatewayApplicationTests.java @@ -0,0 +1,30 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.api; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +@ActiveProfiles("test") +@SpringBootTest +class ApiGatewayApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/spring-petclinic-api-gateway/src/test/java/org/springframework/samples/petclinic/api/application/VisitsServiceClientIntegrationTest.java b/spring-petclinic-api-gateway/src/test/java/org/springframework/samples/petclinic/api/application/VisitsServiceClientIntegrationTest.java new file mode 100644 index 0000000..2fc1ff7 --- /dev/null +++ b/spring-petclinic-api-gateway/src/test/java/org/springframework/samples/petclinic/api/application/VisitsServiceClientIntegrationTest.java @@ -0,0 +1,79 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.api.application; + +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.samples.petclinic.api.dto.Visits; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import java.io.IOException; +import java.util.Collections; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class VisitsServiceClientIntegrationTest { + + private static final Integer PET_ID = 1; + + private VisitsServiceClient visitsServiceClient; + + private MockWebServer server; + + @BeforeEach + void setUp() { + server = new MockWebServer(); + visitsServiceClient = new VisitsServiceClient(WebClient.builder()); + visitsServiceClient.setHostname(server.url("/").toString()); + } + + @AfterEach + void shutdown() throws IOException { + this.server.shutdown(); + } + + @Test + void getVisitsForPets_withAvailableVisitsService() { + prepareResponse(response -> response + .setHeader("Content-Type", "application/json") + .setBody("{\"items\":[{\"id\":5,\"date\":\"2018-11-15\",\"description\":\"test visit\",\"petId\":1}]}")); + + Mono visits = visitsServiceClient.getVisitsForPets(Collections.singletonList(1)); + + assertVisitDescriptionEquals(visits.block(), PET_ID,"test visit"); + } + + + private void assertVisitDescriptionEquals(Visits visits, int petId, String description) { + assertEquals(1, visits.getItems().size()); + assertNotNull(visits.getItems().get(0)); + assertEquals(petId, visits.getItems().get(0).getPetId()); + assertEquals(description, visits.getItems().get(0).getDescription()); + } + + private void prepareResponse(Consumer consumer) { + MockResponse response = new MockResponse(); + consumer.accept(response); + this.server.enqueue(response); + } + +} diff --git a/spring-petclinic-api-gateway/src/test/java/org/springframework/samples/petclinic/api/boundary/web/ApiGatewayControllerTest.java b/spring-petclinic-api-gateway/src/test/java/org/springframework/samples/petclinic/api/boundary/web/ApiGatewayControllerTest.java new file mode 100644 index 0000000..6725f40 --- /dev/null +++ b/spring-petclinic-api-gateway/src/test/java/org/springframework/samples/petclinic/api/boundary/web/ApiGatewayControllerTest.java @@ -0,0 +1,114 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.api.boundary.web; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.cloud.circuitbreaker.resilience4j.ReactiveResilience4JAutoConfiguration; +import org.springframework.context.annotation.Import; +import org.springframework.samples.petclinic.api.application.CustomersServiceClient; +import org.springframework.samples.petclinic.api.application.VisitsServiceClient; +import org.springframework.samples.petclinic.api.dto.OwnerDetails; +import org.springframework.samples.petclinic.api.dto.PetDetails; +import org.springframework.samples.petclinic.api.dto.VisitDetails; +import org.springframework.samples.petclinic.api.dto.Visits; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.reactive.server.WebTestClient; +import reactor.core.publisher.Mono; + +import java.net.ConnectException; +import java.util.Collections; + +@ExtendWith(SpringExtension.class) +@WebFluxTest(controllers = ApiGatewayController.class) +@Import({ReactiveResilience4JAutoConfiguration.class, CircuitBreakerConfiguration.class}) +class ApiGatewayControllerTest { + + @MockBean + private CustomersServiceClient customersServiceClient; + + @MockBean + private VisitsServiceClient visitsServiceClient; + + @Autowired + private WebTestClient client; + + + @Test + void getOwnerDetails_withAvailableVisitsService() { + OwnerDetails owner = new OwnerDetails(); + PetDetails cat = new PetDetails(); + cat.setId(20); + cat.setName("Garfield"); + owner.getPets().add(cat); + Mockito + .when(customersServiceClient.getOwner(1)) + .thenReturn(Mono.just(owner)); + + Visits visits = new Visits(); + VisitDetails visit = new VisitDetails(); + visit.setId(300); + visit.setDescription("First visit"); + visit.setPetId(cat.getId()); + visits.getItems().add(visit); + Mockito + .when(visitsServiceClient.getVisitsForPets(Collections.singletonList(cat.getId()))) + .thenReturn(Mono.just(visits)); + + client.get() + .uri("/api/gateway/owners/1") + .exchange() + .expectStatus().isOk() + //.expectBody(String.class) + //.consumeWith(response -> + // Assertions.assertThat(response.getResponseBody()).isEqualTo("Garfield")); + .expectBody() + .jsonPath("$.pets[0].name").isEqualTo("Garfield") + .jsonPath("$.pets[0].visits[0].description").isEqualTo("First visit"); + } + + /** + * Test Resilience4j fallback method + */ + @Test + void getOwnerDetails_withServiceError() { + OwnerDetails owner = new OwnerDetails(); + PetDetails cat = new PetDetails(); + cat.setId(20); + cat.setName("Garfield"); + owner.getPets().add(cat); + Mockito + .when(customersServiceClient.getOwner(1)) + .thenReturn(Mono.just(owner)); + + Mockito + .when(visitsServiceClient.getVisitsForPets(Collections.singletonList(cat.getId()))) + .thenReturn(Mono.error(new ConnectException("Simulate error"))); + + client.get() + .uri("/api/gateway/owners/1") + .exchange() + .expectStatus().isOk() + .expectBody() + .jsonPath("$.pets[0].name").isEqualTo("Garfield") + .jsonPath("$.pets[0].visits").isEmpty(); + } + +} diff --git a/spring-petclinic-api-gateway/src/test/java/org/springframework/samples/petclinic/api/boundary/web/CircuitBreakerConfiguration.java b/spring-petclinic-api-gateway/src/test/java/org/springframework/samples/petclinic/api/boundary/web/CircuitBreakerConfiguration.java new file mode 100644 index 0000000..81bb1fc --- /dev/null +++ b/spring-petclinic-api-gateway/src/test/java/org/springframework/samples/petclinic/api/boundary/web/CircuitBreakerConfiguration.java @@ -0,0 +1,35 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.api.boundary.web; + +import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry; +import io.github.resilience4j.timelimiter.TimeLimiterRegistry; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class CircuitBreakerConfiguration { + + @Bean + public CircuitBreakerRegistry circuitBreakerRegistry() { + return CircuitBreakerRegistry.ofDefaults(); + } + + @Bean + public TimeLimiterRegistry timeLimiterRegistry() { + return TimeLimiterRegistry.ofDefaults(); + } +} diff --git a/spring-petclinic-api-gateway/src/test/jmeter/petclinic_test_plan.jmx b/spring-petclinic-api-gateway/src/test/jmeter/petclinic_test_plan.jmx new file mode 100644 index 0000000..ae19aa4 --- /dev/null +++ b/spring-petclinic-api-gateway/src/test/jmeter/petclinic_test_plan.jmx @@ -0,0 +1,568 @@ + + + + + + false + true + false + + + + PETCLINC_HOST + aaa0badc2dcdd42d886c61e007d66b6a-742232043.us-east-1.elb.amazonaws.com + = + + + PETCLINIC_PORT + 80 + = + + + + + + + + + + + ${PETCLINC_HOST} + ${PETCLINIC_PORT} + + + + 6 + + + + + + + + Accept + application/json, text/plain, */* + + + Content-Type + application/json;charset=UTF-8 + + + Accept-Encoding + gzip, deflate, br + + + + + + + + 1 + 0 + 0 + 300 + 30 + + + + false + -1 + + continue + + + + PET_TYPE + + 1 + 6 + + false + + + + 300 + 100.0 + + + + + + + + + + + /api/customer/owners + GET + true + false + true + false + + + + + + + + 200 + + + Assertion.response_code + false + 8 + + + + + true + + + + false + { + "firstName":"Firstname", + "lastName":"Lastname", + "address":"Adress", + "city":"City", + "telephone":"0000000000" +} + = + + + + + + + + /api/customer/owners + POST + true + false + true + false + + + + + + + + 201 + + + Assertion.response_code + false + 8 + + + + OWNER_ID + $.id + + + + + + + + + + + + + /api/gateway/owners/1 + GET + true + false + true + false + + + + + + + + 200 + + + Assertion.response_code + false + 8 + + + + + true + + + + false + { + "id":"${OWNER_ID}", + "firstName":"Firstname", + "lastName":"Lastname${OWNER_ID}", + "address":"Adress${OWNER_ID}", + "city":"City${OWNER_ID}", + "telephone":"1111111111" +} + = + + + + + + + + /api/customer/owners/1 + PUT + true + false + true + false + + + + + + + + 204 + + + Assertion.response_code + false + 8 + + + + + true + + + + false + { + "name":"Pet", + "birthDate":"2018-12-31T23:00:00.000Z", + "typeId":"${PET_TYPE}" +} + = + + + + + + + + /api/customer/owners/1/pets + POST + true + false + true + false + + + + + + + + 201 + + + Assertion.response_code + false + 8 + + + + PET_ID + $.id + + + + + + 1 + + + + true + + + + false + { + "name":"Pet", + "birthDate":"2018-12-31T23:00:00.000Z", + "typeId":"${PET_TYPE}" +} + = + + + + + + + + /api/customer/owners/1/pets + POST + true + false + true + false + + + + + + + + 201 + + + Assertion.response_code + false + 8 + + + + + + true + + + + false + { + "id": ${PET_ID}, + "name":"Pet${OWNER_ID}", + "birthDate":"2018-12-31T23:00:00.000Z", + "typeId":"${PET_TYPE}" +} + = + + + + + + + + /api/customer/owners/1/pets/1 + PUT + true + false + true + false + + + + + + + + 204 + + + Assertion.response_code + false + 8 + + + + + true + + + + false + { + "date":"2019-03-15", + "description":"Visit" +} + = + + + + + + + + /api/visit/owners/1/pets/1/visits + POST + true + false + true + false + + + + + + + + 201 + + + Assertion.response_code + false + 8 + + + + + 1 + + + + true + + + + false + { + "date":"2019-03-15", + "description":"Visit" +} + = + + + + + + + + /api/visit/owners/1/pets/1/visits + POST + true + false + true + false + + + + + + + + 201 + + + Assertion.response_code + false + 8 + + + + + + + + + + + + + /api/vet/vets + GET + true + false + true + false + + + + + + + + 200 + + + Assertion.response_code + false + 8 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + true + false + false + false + true + 0 + true + true + true + true + true + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + true + false + false + false + true + 0 + true + true + true + true + true + true + + + + + + + + + diff --git a/spring-petclinic-api-gateway/src/test/resources/application-test.yml b/spring-petclinic-api-gateway/src/test/resources/application-test.yml new file mode 100644 index 0000000..cb8e4f5 --- /dev/null +++ b/spring-petclinic-api-gateway/src/test/resources/application-test.yml @@ -0,0 +1,2 @@ +spring.cloud.config.enabled: false +eureka.client.enabled: false diff --git a/spring-petclinic-config-server/pom.xml b/spring-petclinic-config-server/pom.xml new file mode 100644 index 0000000..b8b679b --- /dev/null +++ b/spring-petclinic-config-server/pom.xml @@ -0,0 +1,69 @@ + + +4.0.0 + +org.springframework.samples.petclinic.config +spring-petclinic-config-server +jar +Spring PetClinic Config Server + + + org.springframework.samples + spring-petclinic-microservices + 2.6.7 + + + + 8888 + ${basedir}/../docker + + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.springframework.cloud + spring-cloud-config-server + + + + + org.jolokia + jolokia-core + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + buildDocker + + + + com.spotify + docker-maven-plugin + ${docker.plugin.version} + + + + + + diff --git a/spring-petclinic-config-server/src/main/java/org/springframework/samples/petclinic/config/ConfigServerApplication.java b/spring-petclinic-config-server/src/main/java/org/springframework/samples/petclinic/config/ConfigServerApplication.java new file mode 100644 index 0000000..e6b810b --- /dev/null +++ b/spring-petclinic-config-server/src/main/java/org/springframework/samples/petclinic/config/ConfigServerApplication.java @@ -0,0 +1,32 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.config.server.EnableConfigServer; + +/** + * @author Maciej Szarlinski + */ +@EnableConfigServer +@SpringBootApplication +public class ConfigServerApplication { + + public static void main(String[] args) { + SpringApplication.run(ConfigServerApplication.class, args); + } +} diff --git a/spring-petclinic-config-server/src/main/resources/application.yml b/spring-petclinic-config-server/src/main/resources/application.yml new file mode 100644 index 0000000..9a58811 --- /dev/null +++ b/spring-petclinic-config-server/src/main/resources/application.yml @@ -0,0 +1,12 @@ +server.port: 8888 +spring: + cloud: + config: + server: + git: + uri: https://github.com/spring-petclinic/spring-petclinic-microservices-config + default-label: main + # Use the File System Backend to avoid git pulling. Enable "native" profile in the Config Server. + native: + searchLocations: file:///${GIT_REPO} + diff --git a/spring-petclinic-config-server/src/main/resources/static/index.html b/spring-petclinic-config-server/src/main/resources/static/index.html new file mode 100644 index 0000000..64679fb --- /dev/null +++ b/spring-petclinic-config-server/src/main/resources/static/index.html @@ -0,0 +1,12 @@ + + + +

Spring Cloud Config Server

+

The Spring Cloud Config Server provides an HTTP resource-based API for external yaml configuration for all the Spring Petclinic microservices

+ + + diff --git a/spring-petclinic-config-server/src/test/java/org/springframework/samples/petclinic/config/PetclinicConfigServerApplicationTests.java b/spring-petclinic-config-server/src/test/java/org/springframework/samples/petclinic/config/PetclinicConfigServerApplicationTests.java new file mode 100644 index 0000000..e3d5191 --- /dev/null +++ b/spring-petclinic-config-server/src/test/java/org/springframework/samples/petclinic/config/PetclinicConfigServerApplicationTests.java @@ -0,0 +1,28 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.config; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class PetclinicConfigServerApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/spring-petclinic-config-server/src/test/resources/application.yml b/spring-petclinic-config-server/src/test/resources/application.yml new file mode 100644 index 0000000..b4fb9c7 --- /dev/null +++ b/spring-petclinic-config-server/src/test/resources/application.yml @@ -0,0 +1,6 @@ +spring: + cloud: + config: + server: + git: + uri: https://github.com/spring-petclinic/spring-petclinic-microservices-config diff --git a/spring-petclinic-customers-service/pom.xml b/spring-petclinic-customers-service/pom.xml new file mode 100644 index 0000000..d69ab94 --- /dev/null +++ b/spring-petclinic-customers-service/pom.xml @@ -0,0 +1,157 @@ + + +4.0.0 + +org.springframework.samples.petclinic.client +spring-petclinic-customers-service +jar +Spring PetClinic Customers Service + + + org.springframework.samples + spring-petclinic-microservices + 2.6.7 + + + + 8081 + ${basedir}/../docker + + + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-web + 2.5.12 + + + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + + + mysql + mysql-connector-java + runtime + 8.0.28 + + + org.hsqldb + hsqldb + runtime + 2.7.1 + + + org.jolokia + jolokia-core + + + org.projectlombok + lombok + provided + + + io.micrometer + micrometer-registry-prometheus + + + de.codecentric + chaos-monkey-spring-boot + + + software.amazon.awssdk + sts + 2.20.46 + + + software.amazon.awssdk + sqs + 2.20.46 + + + software.amazon.awssdk + s3 + 2.20.46 + + + + software.amazon.awssdk + dynamodb-enhanced + 2.20.46 + + + + software.amazon.awssdk + kinesis + 2.20.47 + + + + + com.amazonaws + aws-java-sdk-lambda + 1.12.462 + + + + io.opentelemetry.instrumentation + opentelemetry-instrumentation-annotations + 1.22.1 + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.assertj + assertj-core + test + + + + + + buildDocker + + + + com.spotify + docker-maven-plugin + ${docker.plugin.version} + + + + + + diff --git a/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/CustomersServiceApplication.java b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/CustomersServiceApplication.java new file mode 100644 index 0000000..867cdc1 --- /dev/null +++ b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/CustomersServiceApplication.java @@ -0,0 +1,32 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.customers; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; + +/** + * @author Maciej Szarlinski + */ +@EnableDiscoveryClient +@SpringBootApplication +public class CustomersServiceApplication { + + public static void main(String[] args) { + SpringApplication.run(CustomersServiceApplication.class, args); + } +} diff --git a/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/Util.java b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/Util.java new file mode 100644 index 0000000..822582e --- /dev/null +++ b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/Util.java @@ -0,0 +1,13 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package org.springframework.samples.petclinic.customers; + +import com.amazonaws.util.EC2MetadataUtils; + +public class Util { + public static final String REGION_FROM_EKS = System.getProperty("AWS_REGION") != null ? System.getProperty("AWS_REGION") + : System.getenv("AWS_REGION") != null ? System.getenv("AWS_REGION") + : "us-west-2"; + + public static final String REGION_FROM_EC2 = EC2MetadataUtils.getEC2InstanceRegion() != null ? EC2MetadataUtils.getEC2InstanceRegion() : "us-west-2"; +} diff --git a/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/aws/KinesisService.java b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/aws/KinesisService.java new file mode 100644 index 0000000..91f6040 --- /dev/null +++ b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/aws/KinesisService.java @@ -0,0 +1,110 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package org.springframework.samples.petclinic.customers.aws; + +import org.springframework.samples.petclinic.customers.Util; +import org.springframework.stereotype.Component; +import software.amazon.awssdk.auth.credentials.WebIdentityTokenFileCredentialsProvider; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.kinesis.KinesisClient; +import software.amazon.awssdk.services.kinesis.model.CreateStreamRequest; +import software.amazon.awssdk.services.kinesis.model.DescribeStreamRequest; +import software.amazon.awssdk.services.kinesis.model.DescribeStreamResponse; +import software.amazon.awssdk.services.kinesis.model.GetRecordsRequest; +import software.amazon.awssdk.services.kinesis.model.GetRecordsResponse; +import software.amazon.awssdk.services.kinesis.model.GetShardIteratorRequest; +import software.amazon.awssdk.services.kinesis.model.GetShardIteratorResponse; +import software.amazon.awssdk.services.kinesis.model.KinesisException; +import software.amazon.awssdk.services.kinesis.model.Shard; +import software.amazon.awssdk.services.kinesis.model.Record; + +import java.util.ArrayList; +import java.util.List; +@Component +public class KinesisService { + String streamName = "apm_test"; + //This provider looks for the environment variables AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE + + final KinesisClient kinesisClient; + + public KinesisService() { + // AWS web identity is set for EKS clusters, if these are not set then use default credentials + if (System.getenv("AWS_WEB_IDENTITY_TOKEN_FILE") == null && System.getProperty("aws.webIdentityTokenFile") == null) { + kinesisClient = KinesisClient.builder() + .region(Region.of(Util.REGION_FROM_EC2)) + .build(); + } + else { + kinesisClient = KinesisClient.builder() + .region(Region.of(Util.REGION_FROM_EKS)) + .credentialsProvider(WebIdentityTokenFileCredentialsProvider.create()) + .build(); + } + + createStream(); + } + public void createStream() { + try { + CreateStreamRequest streamReq = CreateStreamRequest.builder() + .streamName(streamName) + .shardCount(1) + .build(); + kinesisClient.createStream(streamReq); + + } catch (KinesisException e) { + System.err.println(e.getMessage()); + } + } + + public void getStreamRecords() { + String shardIterator; + String lastShardId = null; + + // Retrieve the Shards from a Stream + DescribeStreamRequest describeStreamRequest = DescribeStreamRequest.builder() + .streamName(streamName) + .build(); + + List shards = new ArrayList<>(); + DescribeStreamResponse streamRes; + do { + streamRes = kinesisClient.describeStream(describeStreamRequest); + shards.addAll(streamRes.streamDescription().shards()); + + if (shards.size() > 0) { + lastShardId = shards.get(shards.size() - 1).shardId(); + } + } while (streamRes.streamDescription().hasMoreShards()); + + GetShardIteratorRequest itReq = GetShardIteratorRequest.builder() + .streamName(streamName) + .shardIteratorType("TRIM_HORIZON") + .shardId(lastShardId) + .build(); + + GetShardIteratorResponse shardIteratorResult = kinesisClient.getShardIterator(itReq); + shardIterator = shardIteratorResult.shardIterator(); + + // Continuously read data records from shard. + List records; + + // Create new GetRecordsRequest with existing shardIterator. + // Set maximum records to return to 1000. + GetRecordsRequest recordsRequest = GetRecordsRequest.builder() + .shardIterator(shardIterator) + .limit(1000) + .build(); + + GetRecordsResponse result = kinesisClient.getRecords(recordsRequest); + + // Put result into record list. Result may be empty. + records = result.records(); + + // Print records + for (Record record : records) { + SdkBytes byteBuffer = record.data(); + System.out.printf("Seq No: %s - %s%n", record.sequenceNumber(), new String(byteBuffer.asByteArray())); + } + } +} diff --git a/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/aws/SqsService.java b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/aws/SqsService.java new file mode 100644 index 0000000..d82f01d --- /dev/null +++ b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/aws/SqsService.java @@ -0,0 +1,64 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package org.springframework.samples.petclinic.customers.aws; + +import org.springframework.samples.petclinic.customers.Util; +import org.springframework.stereotype.Component; +import software.amazon.awssdk.auth.credentials.WebIdentityTokenFileCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.sqs.SqsClient; +import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; +import software.amazon.awssdk.services.sqs.model.CreateQueueResponse; +import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest; +import software.amazon.awssdk.services.sqs.model.PurgeQueueRequest; +import software.amazon.awssdk.services.sqs.model.SendMessageRequest; +import software.amazon.awssdk.services.sqs.model.SqsException; + +@Component +public class SqsService { + private static final String QUEUE_NAME = "apm_test"; + final SqsClient sqs; + + public SqsService() { + // AWS web identity is set for EKS clusters, if these are not set then use default credentials + if (System.getenv("AWS_WEB_IDENTITY_TOKEN_FILE") == null && System.getProperty("aws.webIdentityTokenFile") == null) { + sqs = SqsClient.builder() + .region(Region.of(Util.REGION_FROM_EC2)) + .build(); + } + else { + sqs = SqsClient.builder() + .region(Region.of(Util.REGION_FROM_EKS)) + .credentialsProvider(WebIdentityTokenFileCredentialsProvider.create()) + .build(); + } + + try { + CreateQueueResponse createResult = sqs.createQueue(CreateQueueRequest.builder().queueName(QUEUE_NAME).build()); + } catch (SqsException e) { + if (!e.awsErrorDetails().errorCode().equals("QueueAlreadyExists")) { + throw e; + } + } + } + + public void sendMsg() { + String queueUrl = sqs.getQueueUrl(GetQueueUrlRequest.builder().queueName(QUEUE_NAME).build()).queueUrl(); + + SendMessageRequest sendMsgRequest = SendMessageRequest.builder() + .queueUrl(queueUrl) + .messageBody("hello world") + .delaySeconds(5) + .build(); + sqs.sendMessage(sendMsgRequest); + + PurgeQueueRequest purgeReq = PurgeQueueRequest.builder().queueUrl(queueUrl).build(); + try { + sqs.purgeQueue(purgeReq); + } catch (SqsException e) { + System.out.println(e.awsErrorDetails().errorMessage()); + throw e; + } + } + +} diff --git a/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/model/Owner.java b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/model/Owner.java new file mode 100644 index 0000000..88860fa --- /dev/null +++ b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/model/Owner.java @@ -0,0 +1,125 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.customers.model; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import javax.validation.constraints.Digits; +import javax.validation.constraints.NotBlank; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.beans.support.MutableSortDefinition; +import org.springframework.beans.support.PropertyComparator; +import org.springframework.core.style.ToStringCreator; + +/** + * Simple JavaBean domain object representing an owner. + * + * @author Ken Krebs + * @author Juergen Hoeller + * @author Sam Brannen + * @author Michael Isvy + * @author Maciej Szarlinski + * @author Ramazan Sakin + */ +@Entity +@Table(name = "owners") +public class Owner { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Getter + private Integer id; + + @Getter + @Setter + @Column(name = "first_name") + @NotBlank + private String firstName; + + @Getter + @Setter + @Column(name = "last_name") + @NotBlank + private String lastName; + + @Getter + @Setter + @Column(name = "address") + @NotBlank + private String address; + + @Getter + @Setter + @Column(name = "city") + @NotBlank + private String city; + + @Getter + @Setter + @Column(name = "telephone") + @NotBlank + @Digits(fraction = 0, integer = 12) + private String telephone; + + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "owner") + private Set pets; + + protected Set getPetsInternal() { + if (this.pets == null) { + this.pets = new HashSet<>(); + } + return this.pets; + } + + public List getPets() { + final List sortedPets = new ArrayList<>(getPetsInternal()); + PropertyComparator.sort(sortedPets, new MutableSortDefinition("name", true, true)); + return Collections.unmodifiableList(sortedPets); + } + + public void addPet(Pet pet) { + getPetsInternal().add(pet); + pet.setOwner(this); + } + + @Override + public String toString() { + return new ToStringCreator(this) + + .append("id", this.getId()) + .append("lastName", this.getLastName()) + .append("firstName", this.getFirstName()) + .append("address", this.address) + .append("city", this.city) + .append("telephone", this.telephone) + .toString(); + } +} diff --git a/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/model/OwnerRepository.java b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/model/OwnerRepository.java new file mode 100644 index 0000000..aa720f2 --- /dev/null +++ b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/model/OwnerRepository.java @@ -0,0 +1,30 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.customers.model; + +import org.springframework.data.jpa.repository.JpaRepository; + +/** + * Repository class for Owner domain objects All method names are compliant with Spring Data naming + * conventions so this interface can easily be extended for Spring Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation + * + * @author Ken Krebs + * @author Juergen Hoeller + * @author Sam Brannen + * @author Michael Isvy + * @author Maciej Szarlinski + */ +public interface OwnerRepository extends JpaRepository { } diff --git a/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/model/Pet.java b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/model/Pet.java new file mode 100644 index 0000000..b89924f --- /dev/null +++ b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/model/Pet.java @@ -0,0 +1,80 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.customers.model; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; +import org.springframework.core.style.ToStringCreator; + +/** + * Simple business object representing a pet. + * + * @author Ken Krebs + * @author Juergen Hoeller + * @author Sam Brannen + * @author Maciej Szarlinski + * @author Ramazan Sakin + */ +@Data +@Entity +@Table(name = "pets") +public class Pet { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + @Column(name = "name") + private String name; + + @Column(name = "birth_date") + @Temporal(TemporalType.DATE) + private Date birthDate; + + @ManyToOne + @JoinColumn(name = "type_id") + private PetType type; + + @ManyToOne + @JoinColumn(name = "owner_id") + @JsonIgnore + private Owner owner; + + @Override + public String toString() { + return new ToStringCreator(this) + .append("id", this.getId()) + .append("name", this.getName()) + .append("birthDate", this.getBirthDate()) + .append("type", this.getType().getName()) + .append("ownerFirstname", this.getOwner().getFirstName()) + .append("ownerLastname", this.getOwner().getLastName()) + .toString(); + } + +} diff --git a/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/model/PetRepository.java b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/model/PetRepository.java new file mode 100644 index 0000000..5bd16db --- /dev/null +++ b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/model/PetRepository.java @@ -0,0 +1,49 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.customers.model; + +import java.util.List; +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +/** + * Repository class for Pet domain objects All method names are compliant with Spring Data naming + * conventions so this interface can easily be extended for Spring Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation + * + * @author Ken Krebs + * @author Juergen Hoeller + * @author Sam Brannen + * @author Michael Isvy + * @author Maciej Szarlinski + */ +public interface PetRepository extends JpaRepository { + + /** + * Retrieve all {@link PetType}s from the data store. + * @return a Collection of {@link PetType}s. + */ + @Query("SELECT ptype FROM PetType ptype ORDER BY ptype.name") + List findPetTypes(); + + @Query("FROM PetType ptype WHERE ptype.id = :typeId") + Optional findPetTypeById(@Param("typeId") int typeId); + + +} + diff --git a/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/model/PetType.java b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/model/PetType.java new file mode 100644 index 0000000..3a7162f --- /dev/null +++ b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/model/PetType.java @@ -0,0 +1,47 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.customers.model; + +import lombok.Getter; +import lombok.Setter; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +/** + * @author Juergen Hoeller + * @author Ramazan Sakin + * Can be Cat, Dog, Hamster... + */ +@Entity +@Table(name = "types") +public class PetType { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Getter + @Setter + private Integer id; + + @Getter + @Setter + @Column(name = "name") + private String name; +} diff --git a/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/web/OwnerResource.java b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/web/OwnerResource.java new file mode 100644 index 0000000..fbdc72f --- /dev/null +++ b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/web/OwnerResource.java @@ -0,0 +1,103 @@ +/* + * Copyright 2002-2021 the original author or 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. + * + * Modifications Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package org.springframework.samples.petclinic.customers.web; + +import io.micrometer.core.annotation.Timed; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.samples.petclinic.customers.model.Owner; +import org.springframework.samples.petclinic.customers.model.OwnerRepository; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.server.ResponseStatusException; + +import javax.validation.Valid; +import javax.validation.constraints.Min; +import java.util.List; +import java.util.Optional; + +/** + * @author Juergen Hoeller + * @author Ken Krebs + * @author Arjen Poutsma + * @author Michael Isvy + * @author Maciej Szarlinski + */ +@RequestMapping("/owners") +@RestController +@Timed("petclinic.owner") +@RequiredArgsConstructor +@Slf4j +class OwnerResource { + + private final OwnerRepository ownerRepository; + + /** + * Create Owner + */ + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public Owner createOwner(@Valid @RequestBody Owner owner) throws Exception { + // don't save the owner for testing traffic + if (owner.getFirstName().equals("random-traffic")) { + return owner; + } + return ownerRepository.save(owner); + } + + /** + * Read single Owner + */ + @GetMapping(value = "/{ownerId}") + public Optional findOwner(@PathVariable("ownerId") int ownerId) { + if (ownerId < 1) { + log.error("Invalid owner id provided: {}", ownerId); + String reason = "Invalid user identifier " + ownerId + ": must be a positive number."; + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, reason); + } + return ownerRepository.findById(ownerId); + } + + /** + * Read List of Owners + */ + @GetMapping + public List findAll() { + return ownerRepository.findAll(); + } + + /** + * Update Owner + */ + @PutMapping(value = "/{ownerId}") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void updateOwner(@PathVariable("ownerId") @Min(1) int ownerId, @Valid @RequestBody Owner ownerRequest) { + final Optional owner = ownerRepository.findById(ownerId); + final Owner ownerModel = owner.orElseThrow(() -> new ResourceNotFoundException("Owner "+ownerId+" not found")); + + // This is done by hand for simplicity purpose. In a real life use-case we should consider using MapStruct. + ownerModel.setFirstName(ownerRequest.getFirstName()); + ownerModel.setLastName(ownerRequest.getLastName()); + ownerModel.setCity(ownerRequest.getCity()); + ownerModel.setAddress(ownerRequest.getAddress()); + ownerModel.setTelephone(ownerRequest.getTelephone()); + log.info("Saving owner {}", ownerModel); + ownerRepository.save(ownerModel); + } +} diff --git a/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/web/PetDetails.java b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/web/PetDetails.java new file mode 100644 index 0000000..6e61fc0 --- /dev/null +++ b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/web/PetDetails.java @@ -0,0 +1,50 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.customers.web; + +import lombok.Data; + +import java.util.Date; + +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.samples.petclinic.customers.model.Pet; +import org.springframework.samples.petclinic.customers.model.PetType; + +/** + * @author mszarlinski@bravurasolutions.com on 2016-12-05. + */ +@Data +class PetDetails { + + private long id; + + private String name; + + private String owner; + + @DateTimeFormat(pattern = "yyyy-MM-dd") + private Date birthDate; + + private PetType type; + + PetDetails(Pet pet) { + this.id = pet.getId(); + this.name = pet.getName(); + this.owner = pet.getOwner().getFirstName() + " " + pet.getOwner().getLastName(); + this.birthDate = pet.getBirthDate(); + this.type = pet.getType(); + } +} diff --git a/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/web/PetRequest.java b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/web/PetRequest.java new file mode 100644 index 0000000..b2e2653 --- /dev/null +++ b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/web/PetRequest.java @@ -0,0 +1,40 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.customers.web; + +import lombok.Data; + +import java.util.Date; + +import javax.validation.constraints.Size; + +import com.fasterxml.jackson.annotation.JsonFormat; + +/** + * @author mszarlinski@bravurasolutions.com on 2016-12-05. + */ +@Data +class PetRequest { + private int id; + + @JsonFormat(pattern = "yyyy-MM-dd") + private Date birthDate; + + @Size(min = 1) + private String name; + + private int typeId; +} diff --git a/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/web/PetResource.java b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/web/PetResource.java new file mode 100644 index 0000000..7239f4e --- /dev/null +++ b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/web/PetResource.java @@ -0,0 +1,107 @@ +/* + * Copyright 2002-2021 the original author or 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. + * + * Modifications Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package org.springframework.samples.petclinic.customers.web; + +import io.micrometer.core.annotation.Timed; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.samples.petclinic.customers.aws.KinesisService; +import org.springframework.samples.petclinic.customers.aws.SqsService; +import org.springframework.samples.petclinic.customers.model.*; +import org.springframework.web.bind.annotation.*; + +import javax.validation.constraints.Min; +import java.util.List; +import java.util.Optional; + +/** + * @author Juergen Hoeller + * @author Ken Krebs + * @author Arjen Poutsma + * @author Maciej Szarlinski + * @author Ramazan Sakin + */ +@RestController +@Timed("petclinic.pet") +@RequiredArgsConstructor +@Slf4j +class PetResource { + + private final PetRepository petRepository; + private final OwnerRepository ownerRepository; + private final SqsService sqsService; + private final KinesisService kinesisService; + + @GetMapping("/petTypes") + public List getPetTypes() { + return petRepository.findPetTypes(); + } + + @PostMapping("/owners/{ownerId}/pets") + @ResponseStatus(HttpStatus.CREATED) + public Pet processCreationForm( + @RequestBody PetRequest petRequest, + @PathVariable("ownerId") @Min(1) int ownerId) { + + final Optional optionalOwner = ownerRepository.findById(ownerId); + Owner owner = optionalOwner.orElseThrow(() -> new ResourceNotFoundException("Owner "+ownerId+" not found")); + + sqsService.sendMsg(); + final Pet pet = new Pet(); + owner.addPet(pet); + return save(pet, petRequest); + } + + @PutMapping("/owners/*/pets/{petId}") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void processUpdateForm(@RequestBody PetRequest petRequest) { + int petId = petRequest.getId(); + Pet pet = findPetById(petId); + kinesisService.getStreamRecords(); + save(pet, petRequest); + } + + private Pet save(final Pet pet, final PetRequest petRequest) { + + pet.setName(petRequest.getName()); + pet.setBirthDate(petRequest.getBirthDate()); + + petRepository.findPetTypeById(petRequest.getTypeId()) + .ifPresent(pet::setType); + + log.info("Saving pet {}", pet); + return petRepository.save(pet); + } + + @GetMapping("owners/*/pets/{petId}") + public PetDetails findPet(@PathVariable("petId") int petId) { + return new PetDetails(findPetById(petId)); + } + + + private Pet findPetById(int petId) { + Optional pet = petRepository.findById(petId); + if (!pet.isPresent()) { + throw new ResourceNotFoundException("Pet "+petId+" not found"); + } + return pet.get(); + } + +} diff --git a/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/web/ResourceNotFoundException.java b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/web/ResourceNotFoundException.java new file mode 100644 index 0000000..d3dc97f --- /dev/null +++ b/spring-petclinic-customers-service/src/main/java/org/springframework/samples/petclinic/customers/web/ResourceNotFoundException.java @@ -0,0 +1,28 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.customers.web; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.NOT_FOUND) +public class ResourceNotFoundException extends RuntimeException { + + public ResourceNotFoundException(String message) { + super(message); + } + +} diff --git a/spring-petclinic-customers-service/src/main/resources/application.yml b/spring-petclinic-customers-service/src/main/resources/application.yml new file mode 100644 index 0000000..5b30b03 --- /dev/null +++ b/spring-petclinic-customers-service/src/main/resources/application.yml @@ -0,0 +1,18 @@ +spring: + application: + name: customers-service + config: + import: optional:configserver:${CONFIG_SERVER_URL:http://localhost:8888/} + +eureka: + instance: + preferIpAddress: true + client: + service-url: + defaultZone: ${DISCOVERY_SERVER_URL:http://localhost:8761/eureka} +--- +spring: + config: + activate: + on-profile: docker + import: configserver:http://config-server:8888 diff --git a/spring-petclinic-customers-service/src/main/resources/db/hsqldb/data.sql b/spring-petclinic-customers-service/src/main/resources/db/hsqldb/data.sql new file mode 100644 index 0000000..676b55f --- /dev/null +++ b/spring-petclinic-customers-service/src/main/resources/db/hsqldb/data.sql @@ -0,0 +1,31 @@ +INSERT INTO types VALUES (1, 'cat'); +INSERT INTO types VALUES (2, 'dog'); +INSERT INTO types VALUES (3, 'lizard'); +INSERT INTO types VALUES (4, 'snake'); +INSERT INTO types VALUES (5, 'bird'); +INSERT INTO types VALUES (6, 'hamster'); + +INSERT INTO owners VALUES (1, 'George', 'Franklin', '110 W. Liberty St.', 'Madison', '6085551023'); +INSERT INTO owners VALUES (2, 'Betty', 'Davis', '638 Cardinal Ave.', 'Sun Prairie', '6085551749'); +INSERT INTO owners VALUES (3, 'Eduardo', 'Rodriquez', '2693 Commerce St.', 'McFarland', '6085558763'); +INSERT INTO owners VALUES (4, 'Harold', 'Davis', '563 Friendly St.', 'Windsor', '6085553198'); +INSERT INTO owners VALUES (5, 'Peter', 'McTavish', '2387 S. Fair Way', 'Madison', '6085552765'); +INSERT INTO owners VALUES (6, 'Jean', 'Coleman', '105 N. Lake St.', 'Monona', '6085552654'); +INSERT INTO owners VALUES (7, 'Jeff', 'Black', '1450 Oak Blvd.', 'Monona', '6085555387'); +INSERT INTO owners VALUES (8, 'Maria', 'Escobito', '345 Maple St.', 'Madison', '6085557683'); +INSERT INTO owners VALUES (9, 'David', 'Schroeder', '2749 Blackhawk Trail', 'Madison', '6085559435'); +INSERT INTO owners VALUES (10, 'Carlos', 'Estaban', '2335 Independence La.', 'Waunakee', '6085555487'); + +INSERT INTO pets VALUES (1, 'Leo', '2010-09-07', 1, 1); +INSERT INTO pets VALUES (2, 'Basil', '2012-08-06', 6, 2); +INSERT INTO pets VALUES (3, 'Rosy', '2011-04-17', 2, 3); +INSERT INTO pets VALUES (4, 'Jewel', '2010-03-07', 2, 3); +INSERT INTO pets VALUES (5, 'Iggy', '2010-11-30', 3, 4); +INSERT INTO pets VALUES (6, 'George', '2010-01-20', 4, 5); +INSERT INTO pets VALUES (7, 'Samantha', '2012-09-04', 1, 6); +INSERT INTO pets VALUES (8, 'Max', '2012-09-04', 1, 6); +INSERT INTO pets VALUES (9, 'Lucky', '2011-08-06', 5, 7); +INSERT INTO pets VALUES (10, 'Mulligan', '2007-02-24', 2, 8); +INSERT INTO pets VALUES (11, 'Freddy', '2010-03-09', 5, 9); +INSERT INTO pets VALUES (12, 'Lucky', '2010-06-24', 2, 10); +INSERT INTO pets VALUES (13, 'Sly', '2012-06-08', 1, 10); diff --git a/spring-petclinic-customers-service/src/main/resources/db/hsqldb/schema.sql b/spring-petclinic-customers-service/src/main/resources/db/hsqldb/schema.sql new file mode 100644 index 0000000..33d42ee --- /dev/null +++ b/spring-petclinic-customers-service/src/main/resources/db/hsqldb/schema.sql @@ -0,0 +1,30 @@ +DROP TABLE pets IF EXISTS; +DROP TABLE types IF EXISTS; +DROP TABLE owners IF EXISTS; + +CREATE TABLE types ( + id INTEGER IDENTITY PRIMARY KEY, + name VARCHAR(80) +); +CREATE INDEX types_name ON types (name); + +CREATE TABLE owners ( + id INTEGER IDENTITY PRIMARY KEY, + first_name VARCHAR(30), + last_name VARCHAR(30), + address VARCHAR(255), + city VARCHAR(80), + telephone VARCHAR(12) +); +CREATE INDEX owners_last_name ON owners (last_name); + +CREATE TABLE pets ( + id INTEGER IDENTITY PRIMARY KEY, + name VARCHAR(30), + birth_date DATE, + type_id INTEGER NOT NULL, + owner_id INTEGER NOT NULL +); +ALTER TABLE pets ADD CONSTRAINT fk_pets_owners FOREIGN KEY (owner_id) REFERENCES owners (id); +ALTER TABLE pets ADD CONSTRAINT fk_pets_types FOREIGN KEY (type_id) REFERENCES types (id); +CREATE INDEX pets_name ON pets (name); diff --git a/spring-petclinic-customers-service/src/main/resources/db/mysql/data.sql b/spring-petclinic-customers-service/src/main/resources/db/mysql/data.sql new file mode 100644 index 0000000..d6e91b1 --- /dev/null +++ b/spring-petclinic-customers-service/src/main/resources/db/mysql/data.sql @@ -0,0 +1,31 @@ +INSERT IGNORE INTO types VALUES (1, 'cat'); +INSERT IGNORE INTO types VALUES (2, 'dog'); +INSERT IGNORE INTO types VALUES (3, 'lizard'); +INSERT IGNORE INTO types VALUES (4, 'snake'); +INSERT IGNORE INTO types VALUES (5, 'bird'); +INSERT IGNORE INTO types VALUES (6, 'hamster'); + +INSERT IGNORE INTO owners VALUES (1, 'George', 'Franklin', '110 W. Liberty St.', 'Madison', '6085551023'); +INSERT IGNORE INTO owners VALUES (2, 'Betty', 'Davis', '638 Cardinal Ave.', 'Sun Prairie', '6085551749'); +INSERT IGNORE INTO owners VALUES (3, 'Eduardo', 'Rodriquez', '2693 Commerce St.', 'McFarland', '6085558763'); +INSERT IGNORE INTO owners VALUES (4, 'Harold', 'Davis', '563 Friendly St.', 'Windsor', '6085553198'); +INSERT IGNORE INTO owners VALUES (5, 'Peter', 'McTavish', '2387 S. Fair Way', 'Madison', '6085552765'); +INSERT IGNORE INTO owners VALUES (6, 'Jean', 'Coleman', '105 N. Lake St.', 'Monona', '6085552654'); +INSERT IGNORE INTO owners VALUES (7, 'Jeff', 'Black', '1450 Oak Blvd.', 'Monona', '6085555387'); +INSERT IGNORE INTO owners VALUES (8, 'Maria', 'Escobito', '345 Maple St.', 'Madison', '6085557683'); +INSERT IGNORE INTO owners VALUES (9, 'David', 'Schroeder', '2749 Blackhawk Trail', 'Madison', '6085559435'); +INSERT IGNORE INTO owners VALUES (10, 'Carlos', 'Estaban', '2335 Independence La.', 'Waunakee', '6085555487'); + +INSERT IGNORE INTO pets VALUES (1, 'Leo', '2000-09-07', 1, 1); +INSERT IGNORE INTO pets VALUES (2, 'Basil', '2002-08-06', 6, 2); +INSERT IGNORE INTO pets VALUES (3, 'Rosy', '2001-04-17', 2, 3); +INSERT IGNORE INTO pets VALUES (4, 'Jewel', '2000-03-07', 2, 3); +INSERT IGNORE INTO pets VALUES (5, 'Iggy', '2000-11-30', 3, 4); +INSERT IGNORE INTO pets VALUES (6, 'George', '2000-01-20', 4, 5); +INSERT IGNORE INTO pets VALUES (7, 'Samantha', '1995-09-04', 1, 6); +INSERT IGNORE INTO pets VALUES (8, 'Max', '1995-09-04', 1, 6); +INSERT IGNORE INTO pets VALUES (9, 'Lucky', '1999-08-06', 5, 7); +INSERT IGNORE INTO pets VALUES (10, 'Mulligan', '1997-02-24', 2, 8); +INSERT IGNORE INTO pets VALUES (11, 'Freddy', '2000-03-09', 5, 9); +INSERT IGNORE INTO pets VALUES (12, 'Lucky', '2000-06-24', 2, 10); +INSERT IGNORE INTO pets VALUES (13, 'Sly', '2002-06-08', 1, 10); diff --git a/spring-petclinic-customers-service/src/main/resources/db/mysql/schema.sql b/spring-petclinic-customers-service/src/main/resources/db/mysql/schema.sql new file mode 100644 index 0000000..7209138 --- /dev/null +++ b/spring-petclinic-customers-service/src/main/resources/db/mysql/schema.sql @@ -0,0 +1,31 @@ +CREATE DATABASE IF NOT EXISTS petclinic; +GRANT ALL PRIVILEGES ON petclinic.* TO pc@localhost IDENTIFIED BY 'pc'; + +USE petclinic; + +CREATE TABLE IF NOT EXISTS types ( + id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(80), + INDEX(name) +) engine=InnoDB; + +CREATE TABLE IF NOT EXISTS owners ( + id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(30), + last_name VARCHAR(30), + address VARCHAR(255), + city VARCHAR(80), + telephone VARCHAR(20), + INDEX(last_name) +) engine=InnoDB; + +CREATE TABLE IF NOT EXISTS pets ( + id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(30), + birth_date DATE, + type_id INT(4) UNSIGNED NOT NULL, + owner_id INT(4) UNSIGNED NOT NULL, + INDEX(name), + FOREIGN KEY (owner_id) REFERENCES owners(id), + FOREIGN KEY (type_id) REFERENCES types(id) +) engine=InnoDB; diff --git a/spring-petclinic-customers-service/src/main/resources/logback-spring.xml b/spring-petclinic-customers-service/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..027bb7b --- /dev/null +++ b/spring-petclinic-customers-service/src/main/resources/logback-spring.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/spring-petclinic-customers-service/src/test/java/org/springframework/samples/petclinic/customers/web/PetResourceTest.java b/spring-petclinic-customers-service/src/test/java/org/springframework/samples/petclinic/customers/web/PetResourceTest.java new file mode 100644 index 0000000..6f03634 --- /dev/null +++ b/spring-petclinic-customers-service/src/test/java/org/springframework/samples/petclinic/customers/web/PetResourceTest.java @@ -0,0 +1,101 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.customers.web; + +import java.util.Optional; + +import org.hibernate.validator.internal.IgnoreForbiddenApisErrors; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.samples.petclinic.customers.aws.KinesisService; +import org.springframework.samples.petclinic.customers.aws.SqsService; +import org.springframework.samples.petclinic.customers.model.Owner; +import org.springframework.samples.petclinic.customers.model.OwnerRepository; +import org.springframework.samples.petclinic.customers.model.Pet; +import org.springframework.samples.petclinic.customers.model.PetRepository; +import org.springframework.samples.petclinic.customers.model.PetType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; + + +import static org.mockito.BDDMockito.given; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * @author Maciej Szarlinski + */ +@ExtendWith(SpringExtension.class) +@WebMvcTest(PetResource.class) +@ActiveProfiles("test") +class PetResourceTest { + + @Autowired + MockMvc mvc; + + @MockBean + PetRepository petRepository; + + @MockBean + OwnerRepository ownerRepository; + + @MockBean + SqsService sqsService; + + @MockBean + KinesisService kinesisService; + + @Test + void shouldGetAPetInJSonFormat() throws Exception { + + Pet pet = setupPet(); + + given(petRepository.findById(2)).willReturn(Optional.of(pet)); + + + mvc.perform(get("/owners/2/pets/2").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.id").value(2)) + .andExpect(jsonPath("$.name").value("Basil")) + .andExpect(jsonPath("$.type.id").value(6)); + } + + private Pet setupPet() { + Owner owner = new Owner(); + owner.setFirstName("George"); + owner.setLastName("Bush"); + + Pet pet = new Pet(); + + pet.setName("Basil"); + pet.setId(2); + + PetType petType = new PetType(); + petType.setId(6); + pet.setType(petType); + + owner.addPet(pet); + return pet; + } +} diff --git a/spring-petclinic-customers-service/src/test/resources/application-test.yml b/spring-petclinic-customers-service/src/test/resources/application-test.yml new file mode 100644 index 0000000..b9c699b --- /dev/null +++ b/spring-petclinic-customers-service/src/test/resources/application-test.yml @@ -0,0 +1,18 @@ +spring: + cloud: + config: + enabled: false + sql: + init: + schema-locations: classpath*:db/hsqldb/schema.sql + data-locations: classpath*:db/hsqldb/data.sql + jpa: + hibernate: + ddl-auto: none + +eureka: + client: + enabled: false + +logging.level.org.springframework: INFO + diff --git a/spring-petclinic-discovery-server/pom.xml b/spring-petclinic-discovery-server/pom.xml new file mode 100644 index 0000000..10c65db --- /dev/null +++ b/spring-petclinic-discovery-server/pom.xml @@ -0,0 +1,61 @@ + + +4.0.0 + +org.springframework.samples.petclinic.discovery +spring-petclinic-discovery-server +jar +Spring PetClinic Discovery Server + + + org.springframework.samples + spring-petclinic-microservices + 2.6.7 + + + + 8761 + ${basedir}/../docker + + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-server + + + org.springframework.cloud + spring-cloud-starter-config + + + + + org.glassfish.jaxb + jaxb-runtime + + + + + + buildDocker + + + + com.spotify + docker-maven-plugin + ${docker.plugin.version} + + + + + + diff --git a/spring-petclinic-discovery-server/src/main/java/org/springframework/samples/petclinic/discovery/DiscoveryServerApplication.java b/spring-petclinic-discovery-server/src/main/java/org/springframework/samples/petclinic/discovery/DiscoveryServerApplication.java new file mode 100644 index 0000000..56c49ed --- /dev/null +++ b/spring-petclinic-discovery-server/src/main/java/org/springframework/samples/petclinic/discovery/DiscoveryServerApplication.java @@ -0,0 +1,32 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.discovery; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; + +/** + * @author Maciej Szarlinski + */ +@SpringBootApplication +@EnableEurekaServer +public class DiscoveryServerApplication { + + public static void main(String[] args) { + SpringApplication.run(DiscoveryServerApplication.class, args); + } +} diff --git a/spring-petclinic-discovery-server/src/main/resources/application.yml b/spring-petclinic-discovery-server/src/main/resources/application.yml new file mode 100644 index 0000000..9fbcbc5 --- /dev/null +++ b/spring-petclinic-discovery-server/src/main/resources/application.yml @@ -0,0 +1,21 @@ +spring: + application: + name: discovery-server + config: + import: optional:configserver:${CONFIG_SERVER_URL:http://localhost:8888/} + +# Avoid some debugging logs at startup +logging: + level: + org: + springframework: + boot: INFO + web: INFO + +--- +spring: + config: + activate: + on-profile: docker + import: configserver:http://config-server:8888 + diff --git a/spring-petclinic-discovery-server/src/test/java/org/springframework/samples/petclinic/discovery/DiscoveryServerApplicationTests.java b/spring-petclinic-discovery-server/src/test/java/org/springframework/samples/petclinic/discovery/DiscoveryServerApplicationTests.java new file mode 100644 index 0000000..8bcc0af --- /dev/null +++ b/spring-petclinic-discovery-server/src/test/java/org/springframework/samples/petclinic/discovery/DiscoveryServerApplicationTests.java @@ -0,0 +1,28 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.discovery; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class DiscoveryServerApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/spring-petclinic-vets-service/.gitignore b/spring-petclinic-vets-service/.gitignore new file mode 100644 index 0000000..c71ea97 --- /dev/null +++ b/spring-petclinic-vets-service/.gitignore @@ -0,0 +1 @@ +/.apt_generated/ diff --git a/spring-petclinic-vets-service/pom.xml b/spring-petclinic-vets-service/pom.xml new file mode 100644 index 0000000..36f6e5a --- /dev/null +++ b/spring-petclinic-vets-service/pom.xml @@ -0,0 +1,161 @@ + + +4.0.0 + +org.springframework.samples.petclinic.vets +spring-petclinic-vets-service +jar +Spring PetClinic Vets Service + + + org.springframework.samples + spring-petclinic-microservices + 2.6.7 + + + + 8081 + ${basedir}/../docker + + + + + + org.springframework.boot + spring-boot-starter-web + 2.5.12 + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-cache + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + + + org.projectlombok + lombok + provided + + + javax.cache + cache-api + + + org.ehcache + ehcache + + + org.jolokia + jolokia-core + + + org.hsqldb + hsqldb + 2.7.1 + runtime + + + mysql + mysql-connector-java + 8.0.28 + runtime + + + io.micrometer + micrometer-registry-prometheus + + + de.codecentric + chaos-monkey-spring-boot + + + software.amazon.awssdk + sts + 2.20.46 + + + software.amazon.awssdk + sqs + 2.20.46 + + + software.amazon.awssdk + s3 + 2.20.46 + + + + software.amazon.awssdk + dynamodb-enhanced + 2.20.46 + + + + software.amazon.awssdk + kinesis + 2.20.47 + + + + + com.amazonaws + aws-java-sdk-lambda + 1.12.462 + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + buildDocker + + + + com.spotify + docker-maven-plugin + ${docker.plugin.version} + + + + + + diff --git a/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/VetsServiceApplication.java b/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/VetsServiceApplication.java new file mode 100644 index 0000000..e11e1b0 --- /dev/null +++ b/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/VetsServiceApplication.java @@ -0,0 +1,35 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.vets; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.samples.petclinic.vets.system.VetsProperties; + +/** + * @author Maciej Szarlinski + */ +@EnableDiscoveryClient +@SpringBootApplication +@EnableConfigurationProperties(VetsProperties.class) +public class VetsServiceApplication { + + public static void main(String[] args) { + SpringApplication.run(VetsServiceApplication.class, args); + } +} diff --git a/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/aws/S3Service.java b/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/aws/S3Service.java new file mode 100644 index 0000000..5ee6bf4 --- /dev/null +++ b/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/aws/S3Service.java @@ -0,0 +1,51 @@ +/* + * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + * + * Modifications Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package org.springframework.samples.petclinic.vets.aws; + +import org.springframework.stereotype.Component; +import software.amazon.awssdk.auth.credentials.WebIdentityTokenFileCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; + +@Component +public class S3Service { + private S3Client s3Client; + private static final String ENV_TRACE_BUCKET = "TRACE_DATA_BUCKET"; + private static final String ENV_TRACE_S3_KEY = "TRACE_DATA_S3_KEY"; + + public S3Service(){ + + // AWS web identity is set for EKS clusters, if these are not set then use default credentials + if (System.getenv("AWS_WEB_IDENTITY_TOKEN_FILE") == null && System.getProperty("aws.webIdentityTokenFile") == null) { + s3Client = S3Client.builder() + .region(Region.US_EAST_1) + .build(); + } + else { + s3Client = S3Client.builder() + .region(Region.US_EAST_1) + .credentialsProvider(WebIdentityTokenFileCredentialsProvider.create()) + .build(); + } + } + + public void listBuckets() { + s3Client.listBuckets(); + } +} + diff --git a/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/model/Specialty.java b/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/model/Specialty.java new file mode 100644 index 0000000..c5c0869 --- /dev/null +++ b/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/model/Specialty.java @@ -0,0 +1,48 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.vets.model; + +import lombok.Getter; +import lombok.Setter; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +/** + * Models a {@link Vet Vet's} specialty (for example, dentistry). + * + * @author Juergen Hoeller + * @author Ramazan Sakin + */ + +@Entity +@Table(name = "specialties") +public class Specialty { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Getter + private Integer id; + + @Getter + @Setter + @Column(name = "name") + private String name; + +} diff --git a/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/model/Vet.java b/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/model/Vet.java new file mode 100644 index 0000000..4976a39 --- /dev/null +++ b/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/model/Vet.java @@ -0,0 +1,101 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.vets.model; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.Table; +import javax.validation.constraints.NotBlank; +import javax.xml.bind.annotation.XmlElement; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.beans.support.MutableSortDefinition; +import org.springframework.beans.support.PropertyComparator; + +/** + * Simple JavaBean domain object representing a veterinarian. + * + * @author Ken Krebs + * @author Juergen Hoeller + * @author Sam Brannen + * @author Arjen Poutsma + * @author Maciej Szarlinski + * @author Ramazan Sakin + */ +@Entity +@Table(name = "vets") +public class Vet { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Getter + @Setter + private Integer id; + + @Column(name = "first_name") + @NotBlank + @Getter + @Setter + private String firstName; + + @Column(name = "last_name") + @NotBlank + @Getter + @Setter + private String lastName; + + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "vet_specialties", joinColumns = @JoinColumn(name = "vet_id"), + inverseJoinColumns = @JoinColumn(name = "specialty_id")) + private Set specialties; + + protected Set getSpecialtiesInternal() { + if (this.specialties == null) { + this.specialties = new HashSet<>(); + } + return this.specialties; + } + + @XmlElement + public List getSpecialties() { + List sortedSpecs = new ArrayList<>(getSpecialtiesInternal()); + PropertyComparator.sort(sortedSpecs, new MutableSortDefinition("name", true, true)); + return Collections.unmodifiableList(sortedSpecs); + } + + public int getNrOfSpecialties() { + return getSpecialtiesInternal().size(); + } + + public void addSpecialty(Specialty specialty) { + getSpecialtiesInternal().add(specialty); + } + +} diff --git a/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/model/VetRepository.java b/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/model/VetRepository.java new file mode 100644 index 0000000..cb22d14 --- /dev/null +++ b/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/model/VetRepository.java @@ -0,0 +1,31 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.vets.model; + +import org.springframework.data.jpa.repository.JpaRepository; + +/** + * Repository class for Vet domain objects All method names are compliant with Spring Data naming + * conventions so this interface can easily be extended for Spring Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation + * + * @author Ken Krebs + * @author Juergen Hoeller + * @author Sam Brannen + * @author Michael Isvy + * @author Maciej Szarlinski + */ +public interface VetRepository extends JpaRepository { +} diff --git a/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/system/CacheConfig.java b/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/system/CacheConfig.java new file mode 100644 index 0000000..2f3fb79 --- /dev/null +++ b/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/system/CacheConfig.java @@ -0,0 +1,30 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.vets.system; + +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +/** + * Cache could be disable in unit test. + * @author Maciej Szarlinski + */ +@Configuration +@EnableCaching +@Profile("production") +class CacheConfig { +} diff --git a/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/system/VetsProperties.java b/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/system/VetsProperties.java new file mode 100644 index 0000000..017bffe --- /dev/null +++ b/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/system/VetsProperties.java @@ -0,0 +1,40 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.vets.system; + +import lombok.Data; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * Typesafe custom configuration. + * + * @author Maciej Szarlinski + */ +@Data +@ConfigurationProperties(prefix = "vets") +public class VetsProperties { + + private Cache cache; + + @Data + public static class Cache { + + private int ttl; + + private int heapSize; + } +} diff --git a/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/web/VetResource.java b/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/web/VetResource.java new file mode 100644 index 0000000..9742c5d --- /dev/null +++ b/spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/web/VetResource.java @@ -0,0 +1,52 @@ +/* + * Copyright 2002-2021 the original author or 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. + * + * Modifications Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package org.springframework.samples.petclinic.vets.web; + +import lombok.RequiredArgsConstructor; + +import java.util.List; + +import org.springframework.samples.petclinic.vets.aws.S3Service; +import org.springframework.samples.petclinic.vets.model.Vet; +import org.springframework.samples.petclinic.vets.model.VetRepository; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author Juergen Hoeller + * @author Mark Fisher + * @author Ken Krebs + * @author Arjen Poutsma + * @author Maciej Szarlinski + */ +@RequestMapping("/vets") +@RestController +@RequiredArgsConstructor +class VetResource { + + private final VetRepository vetRepository; + private final S3Service s3Service; + + @GetMapping + public List showResourcesVetList() { + s3Service.listBuckets(); + return vetRepository.findAll(); + } +} diff --git a/spring-petclinic-vets-service/src/main/resources/application.yml b/spring-petclinic-vets-service/src/main/resources/application.yml new file mode 100644 index 0000000..b411b45 --- /dev/null +++ b/spring-petclinic-vets-service/src/main/resources/application.yml @@ -0,0 +1,22 @@ +spring: + application: + name: vets-service + config: + import: optional:configserver:${CONFIG_SERVER_URL:http://localhost:8888/} + cache: + cache-names: vets + profiles: + active: production + +eureka: + instance: + preferIpAddress: true + client: + service-url: + defaultZone: ${DISCOVERY_SERVER_URL:http://localhost:8761/eureka} +--- +spring: + config: + activate: + on-profile: docker + import: configserver:http://config-server:8888 diff --git a/spring-petclinic-vets-service/src/main/resources/db/hsqldb/data.sql b/spring-petclinic-vets-service/src/main/resources/db/hsqldb/data.sql new file mode 100644 index 0000000..e6658a5 --- /dev/null +++ b/spring-petclinic-vets-service/src/main/resources/db/hsqldb/data.sql @@ -0,0 +1,16 @@ +INSERT INTO vets VALUES (1, 'James', 'Carter'); +INSERT INTO vets VALUES (2, 'Helen', 'Leary'); +INSERT INTO vets VALUES (3, 'Linda', 'Douglas'); +INSERT INTO vets VALUES (4, 'Rafael', 'Ortega'); +INSERT INTO vets VALUES (5, 'Henry', 'Stevens'); +INSERT INTO vets VALUES (6, 'Sharon', 'Jenkins'); + +INSERT INTO specialties VALUES (1, 'radiology'); +INSERT INTO specialties VALUES (2, 'surgery'); +INSERT INTO specialties VALUES (3, 'dentistry'); + +INSERT INTO vet_specialties VALUES (2, 1); +INSERT INTO vet_specialties VALUES (3, 2); +INSERT INTO vet_specialties VALUES (3, 3); +INSERT INTO vet_specialties VALUES (4, 2); +INSERT INTO vet_specialties VALUES (5, 1); diff --git a/spring-petclinic-vets-service/src/main/resources/db/hsqldb/schema.sql b/spring-petclinic-vets-service/src/main/resources/db/hsqldb/schema.sql new file mode 100644 index 0000000..eb916e1 --- /dev/null +++ b/spring-petclinic-vets-service/src/main/resources/db/hsqldb/schema.sql @@ -0,0 +1,23 @@ +DROP TABLE vet_specialties IF EXISTS; +DROP TABLE vets IF EXISTS; +DROP TABLE specialties IF EXISTS; + +CREATE TABLE vets ( + id INTEGER IDENTITY PRIMARY KEY, + first_name VARCHAR(30), + last_name VARCHAR(30) +); +CREATE INDEX vets_last_name ON vets (last_name); + +CREATE TABLE specialties ( + id INTEGER IDENTITY PRIMARY KEY, + name VARCHAR(80) +); +CREATE INDEX specialties_name ON specialties (name); + +CREATE TABLE vet_specialties ( + vet_id INTEGER NOT NULL, + specialty_id INTEGER NOT NULL +); +ALTER TABLE vet_specialties ADD CONSTRAINT fk_vet_specialties_vets FOREIGN KEY (vet_id) REFERENCES vets (id); +ALTER TABLE vet_specialties ADD CONSTRAINT fk_vet_specialties_specialties FOREIGN KEY (specialty_id) REFERENCES specialties (id); diff --git a/spring-petclinic-vets-service/src/main/resources/db/mysql/data.sql b/spring-petclinic-vets-service/src/main/resources/db/mysql/data.sql new file mode 100644 index 0000000..9159eca --- /dev/null +++ b/spring-petclinic-vets-service/src/main/resources/db/mysql/data.sql @@ -0,0 +1,16 @@ +INSERT IGNORE INTO vets VALUES (1, 'James', 'Carter'); +INSERT IGNORE INTO vets VALUES (2, 'Helen', 'Leary'); +INSERT IGNORE INTO vets VALUES (3, 'Linda', 'Douglas'); +INSERT IGNORE INTO vets VALUES (4, 'Rafael', 'Ortega'); +INSERT IGNORE INTO vets VALUES (5, 'Henry', 'Stevens'); +INSERT IGNORE INTO vets VALUES (6, 'Sharon', 'Jenkins'); + +INSERT IGNORE INTO specialties VALUES (1, 'radiology'); +INSERT IGNORE INTO specialties VALUES (2, 'surgery'); +INSERT IGNORE INTO specialties VALUES (3, 'dentistry'); + +INSERT IGNORE INTO vet_specialties VALUES (2, 1); +INSERT IGNORE INTO vet_specialties VALUES (3, 2); +INSERT IGNORE INTO vet_specialties VALUES (3, 3); +INSERT IGNORE INTO vet_specialties VALUES (4, 2); +INSERT IGNORE INTO vet_specialties VALUES (5, 1); diff --git a/spring-petclinic-vets-service/src/main/resources/db/mysql/schema.sql b/spring-petclinic-vets-service/src/main/resources/db/mysql/schema.sql new file mode 100644 index 0000000..4f9af3d --- /dev/null +++ b/spring-petclinic-vets-service/src/main/resources/db/mysql/schema.sql @@ -0,0 +1,25 @@ +CREATE DATABASE IF NOT EXISTS petclinic; +GRANT ALL PRIVILEGES ON petclinic.* TO pc@localhost IDENTIFIED BY 'pc'; + +USE petclinic; + +CREATE TABLE IF NOT EXISTS vets ( + id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(30), + last_name VARCHAR(30), + INDEX(last_name) +) engine=InnoDB; + +CREATE TABLE IF NOT EXISTS specialties ( + id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(80), + INDEX(name) +) engine=InnoDB; + +CREATE TABLE IF NOT EXISTS vet_specialties ( + vet_id INT(4) UNSIGNED NOT NULL, + specialty_id INT(4) UNSIGNED NOT NULL, + FOREIGN KEY (vet_id) REFERENCES vets(id), + FOREIGN KEY (specialty_id) REFERENCES specialties(id), + UNIQUE (vet_id,specialty_id) +) engine=InnoDB; diff --git a/spring-petclinic-vets-service/src/main/resources/logback-spring.xml b/spring-petclinic-vets-service/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..5d03f79 --- /dev/null +++ b/spring-petclinic-vets-service/src/main/resources/logback-spring.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/spring-petclinic-vets-service/src/test/java/org/springframework/samples/petclinic/vets/web/VetResourceTest.java b/spring-petclinic-vets-service/src/test/java/org/springframework/samples/petclinic/vets/web/VetResourceTest.java new file mode 100644 index 0000000..00490fe --- /dev/null +++ b/spring-petclinic-vets-service/src/test/java/org/springframework/samples/petclinic/vets/web/VetResourceTest.java @@ -0,0 +1,69 @@ +/* + * Copyright 2002-2021 the original author or 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. + * + * Modifications Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package org.springframework.samples.petclinic.vets.web; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.samples.petclinic.vets.aws.S3Service; +import org.springframework.samples.petclinic.vets.model.Vet; +import org.springframework.samples.petclinic.vets.model.VetRepository; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; + +import static java.util.Arrays.asList; +import static org.mockito.BDDMockito.given; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * @author Maciej Szarlinski + */ +@ExtendWith(SpringExtension.class) +@WebMvcTest(VetResource.class) +@ActiveProfiles("test") +class VetResourceTest { + + @Autowired + MockMvc mvc; + + @MockBean + VetRepository vetRepository; + + @MockBean + S3Service s3Service; + + @Test + void shouldGetAListOfVets() throws Exception { + + Vet vet = new Vet(); + vet.setId(1); + + given(vetRepository.findAll()).willReturn(asList(vet)); + + mvc.perform(get("/vets").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[0].id").value(1)); + } +} diff --git a/spring-petclinic-vets-service/src/test/resources/application-test.yml b/spring-petclinic-vets-service/src/test/resources/application-test.yml new file mode 100644 index 0000000..684fa89 --- /dev/null +++ b/spring-petclinic-vets-service/src/test/resources/application-test.yml @@ -0,0 +1,20 @@ +spring: + cloud: + config: + enabled: false + sql: + init: + schema-locations: classpath*:db/hsqldb/schema.sql + data-locations: classpath*:db/hsqldb/data.sql + jpa: + hibernate: + ddl-auto: none + +eureka: + client: + enabled: false + +vets: + cache: + ttl: 10 + heap-size: 10 diff --git a/spring-petclinic-visits-service/pom.xml b/spring-petclinic-visits-service/pom.xml new file mode 100644 index 0000000..653f086 --- /dev/null +++ b/spring-petclinic-visits-service/pom.xml @@ -0,0 +1,173 @@ + + +4.0.0 + +org.springframework.samples.petclinic.visits +spring-petclinic-visits-service +jar +Spring PetClinic Visits Service + + + org.springframework.samples + spring-petclinic-microservices + 2.6.7 + + + + 8081 + ${basedir}/../docker + + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + 2.5.12 + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + + + io.opentelemetry.instrumentation + opentelemetry-instrumentation-annotations + 1.22.1 + + + + + + com.amazonaws + aws-java-sdk-bom + 1.12.385 + pom + + + + com.amazonaws + aws-java-sdk-s3 + 1.12.385 + + + + + org.projectlombok + lombok + provided + + + org.hsqldb + hsqldb + 2.7.1 + runtime + + + org.jolokia + jolokia-core + + + mysql + mysql-connector-java + 8.0.28 + runtime + + + io.micrometer + micrometer-registry-prometheus + + + de.codecentric + chaos-monkey-spring-boot + + + software.amazon.awssdk + sts + 2.20.46 + + + software.amazon.awssdk + sqs + 2.20.46 + + + software.amazon.awssdk + s3 + 2.20.46 + + + software.amazon.awssdk + sdk-core + 2.20.46 + + + + software.amazon.awssdk + dynamodb-enhanced + 2.20.46 + + + + software.amazon.awssdk + kinesis + 2.20.47 + + + + + com.amazonaws + aws-java-sdk-lambda + 1.12.462 + + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + buildDocker + + + + com.spotify + docker-maven-plugin + ${docker.plugin.version} + + + + + + diff --git a/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/Util.java b/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/Util.java new file mode 100644 index 0000000..46a7044 --- /dev/null +++ b/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/Util.java @@ -0,0 +1,13 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package org.springframework.samples.petclinic.visits; + +import com.amazonaws.util.EC2MetadataUtils; + +public class Util { + public static final String REGION_FROM_EKS = System.getProperty("AWS_REGION") != null ? System.getProperty("AWS_REGION") + : System.getenv("AWS_REGION") != null ? System.getenv("AWS_REGION") + : "us-west-2"; + + public static final String REGION_FROM_EC2 = EC2MetadataUtils.getEC2InstanceRegion() != null ? EC2MetadataUtils.getEC2InstanceRegion() : "us-west-2"; +} \ No newline at end of file diff --git a/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/VisitsServiceApplication.java b/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/VisitsServiceApplication.java new file mode 100644 index 0000000..78f2963 --- /dev/null +++ b/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/VisitsServiceApplication.java @@ -0,0 +1,32 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.visits; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; + +/** + * @author Maciej Szarlinski + */ +@EnableDiscoveryClient +@SpringBootApplication +public class VisitsServiceApplication { + + public static void main(String[] args) { + SpringApplication.run(VisitsServiceApplication.class, args); + } +} diff --git a/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/aws/DdbService.java b/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/aws/DdbService.java new file mode 100644 index 0000000..68861f7 --- /dev/null +++ b/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/aws/DdbService.java @@ -0,0 +1,180 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package org.springframework.samples.petclinic.visits.aws; + +import lombok.Value; +import lombok.extern.slf4j.Slf4j; + +import org.springframework.samples.petclinic.visits.Util; +import org.springframework.stereotype.Component; +import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; +import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; +import software.amazon.awssdk.enhanced.dynamodb.TableSchema; +import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; +import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; +import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.*; +import software.amazon.awssdk.auth.credentials.WebIdentityTokenFileCredentialsProvider; +import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; +import software.amazon.awssdk.core.retry.RetryPolicy; + + +import java.util.HashMap; +import java.util.Map; +import java.time.Instant; + +@Slf4j +@Component +public class DdbService { + + DynamoDbTable table; + + public DdbService() { + RetryPolicy dynamoDbRetryPolicy = RetryPolicy.builder() + .numRetries(1) + .build(); + ClientOverrideConfiguration clientOverrideConfiguration = ClientOverrideConfiguration.builder() + .retryPolicy(dynamoDbRetryPolicy).build(); + + + DynamoDbClient dynamoDbClient = null; + + // AWS web identity is set for EKS clusters, if these are not set then use default credentials + if (System.getenv("AWS_WEB_IDENTITY_TOKEN_FILE") == null && System.getProperty("aws.webIdentityTokenFile") == null) { + dynamoDbClient = DynamoDbClient.builder() + .region(Region.of(Util.REGION_FROM_EC2)) + .overrideConfiguration(clientOverrideConfiguration) + .build(); + } + else { + dynamoDbClient = DynamoDbClient.builder() + .region(Region.of(Util.REGION_FROM_EKS)) + .credentialsProvider(WebIdentityTokenFileCredentialsProvider.create()) + .overrideConfiguration(clientOverrideConfiguration) + .build(); + } + + String tableName = "apm_test"; + try { + // Try to describe the table + dynamoDbClient.describeTable(DescribeTableRequest.builder().tableName(tableName).build()); + log.info("Table " + tableName + " already exists"); + } catch (ResourceNotFoundException e) { + CreateTableRequest request = CreateTableRequest.builder() + .tableName(tableName) + .keySchema(KeySchemaElement.builder() + .attributeName("id") + .keyType(KeyType.HASH) + .build()) + .attributeDefinitions(AttributeDefinition.builder() + .attributeName("id") + .attributeType(ScalarAttributeType.S) + .build()) + .provisionedThroughput(ProvisionedThroughput.builder() + .readCapacityUnits(1L) + .writeCapacityUnits(1L) + .build()) + .build(); + + try { + dynamoDbClient.createTable(request); + } catch (DynamoDbException ex) { + System.err.println(ex.getMessage()); + throw ex; + } + } + + DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder().dynamoDbClient(dynamoDbClient).build(); + // Map Table Using Bean + table = enhancedClient.table("apm_test", TableSchema.fromBean(MyItem.class)); + } + + public void putItems() { + try { + for (int i = 0; i < 1; i++) { + String timestamp = Instant.now().toString(); + // Save the item + MyItem item = new MyItem.Builder(timestamp).withSomeData("This is some data").build(); + table.putItem(item); + } + } catch (Exception e){ + handleCommonErrors(e); + } + } + + @DynamoDbBean + public static class MyItem { + private String id; + private String someData; + + public MyItem() {} + + @DynamoDbPartitionKey + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getSomeData() { + return someData; + } + + public void setSomeData(String someData) { + this.someData = someData; + } + + // Static Builder Class + public static class Builder { + private String id; + private String someData; + + public Builder(String id) { + this.id = id; + } + + public Builder withSomeData(String someData) { + this.someData = someData; + return this; + } + + public MyItem build() { + MyItem item = new MyItem(); + item.id = id; + item.someData = someData; + return item; + } + } + } + + + + // Exception Helper Method + private static void handleCommonErrors(Exception exception) { + try { + throw exception; + } catch (InternalServerErrorException isee) { + log.info("Internal Server Error, generally safe to retry with exponential back-off. Error: " + isee.getMessage()); + throw isee; + } catch (RequestLimitExceededException rlee) { + log.info("Throughput exceeds the current throughput limit for your account, increase account level throughput before " + + "retrying. Error: " + rlee.getMessage()); + throw rlee; + } catch (ProvisionedThroughputExceededException ptee) { + log.info("Request rate is too high. If you're using a custom retry strategy make sure to retry with exponential back-off. " + + "Otherwise consider reducing frequency of requests or increasing provisioned capacity for your table or secondary index. Error: " + + ptee.getMessage()); + throw ptee; + } catch (ResourceNotFoundException rnfe) { + log.info("One of the tables was not found, verify table exists before retrying. Error: " + rnfe.getMessage()); + throw rnfe; + } catch (Exception e) { + log.error("An exception occurred, investigate and configure retry strategy. Error: ", e); + throw new RuntimeException(e); + } + } +} diff --git a/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/model/Visit.java b/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/model/Visit.java new file mode 100644 index 0000000..deede8e --- /dev/null +++ b/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/model/Visit.java @@ -0,0 +1,67 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.visits.model; + +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import javax.validation.constraints.Size; +import java.util.Date; + +/** + * Simple JavaBean domain object representing a visit. + * + * @author Ken Krebs + * @author Maciej Szarlinski + * @author Ramazan Sakin + */ +@Entity +@Table(name = "visits") +@Builder(builderMethodName = "visit") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Visit { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + @Builder.Default + @Column(name = "visit_date") + @Temporal(TemporalType.TIMESTAMP) + @JsonFormat(pattern = "yyyy-MM-dd") + private Date date = new Date(); + + @Size(max = 8192) + @Column(name = "description") + private String description; + + @Column(name = "pet_id") + private int petId; + +} diff --git a/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/model/VisitRepository.java b/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/model/VisitRepository.java new file mode 100644 index 0000000..bd7a6d7 --- /dev/null +++ b/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/model/VisitRepository.java @@ -0,0 +1,38 @@ +/* + * Copyright 2002-2021 the original author or 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. + */ +package org.springframework.samples.petclinic.visits.model; + +import java.util.Collection; +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; + +/** + * Repository class for Visit domain objects All method names are compliant with Spring Data naming conventions so this interface can easily be extended for Spring + * Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation + * + * @author Ken Krebs + * @author Juergen Hoeller + * @author Sam Brannen + * @author Michael Isvy + * @author Maciej Szarlinski + */ +public interface VisitRepository extends JpaRepository { + + List findByPetId(int petId); + + List findByPetIdIn(Collection petIds); +} diff --git a/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/web/VisitResource.java b/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/web/VisitResource.java new file mode 100644 index 0000000..bd2555d --- /dev/null +++ b/spring-petclinic-visits-service/src/main/java/org/springframework/samples/petclinic/visits/web/VisitResource.java @@ -0,0 +1,94 @@ +/* + * Copyright 2002-2021 the original author or 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. + * + * Modifications Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package org.springframework.samples.petclinic.visits.web; + +import java.util.List; +import javax.validation.Valid; +import javax.validation.constraints.Min; + +import io.micrometer.core.annotation.Timed; +import lombok.RequiredArgsConstructor; +import lombok.Value; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.samples.petclinic.visits.aws.DdbService; +import org.springframework.samples.petclinic.visits.model.Visit; +import org.springframework.samples.petclinic.visits.model.VisitRepository; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author Juergen Hoeller + * @author Ken Krebs + * @author Arjen Poutsma + * @author Michael Isvy + * @author Maciej Szarlinski + * @author Ramazan Sakin + */ +@RestController +@RequiredArgsConstructor +@Slf4j +@Timed("petclinic.visit") +class VisitResource { + + private final VisitRepository visitRepository; + + private final DdbService ddbService; + + + @PostMapping("owners/*/pets/{petId}/visits") + @ResponseStatus(HttpStatus.CREATED) + public Visit create( + @Valid @RequestBody Visit visit, + @PathVariable("petId") @Min(1) int petId) { + + ddbService.putItems(); + visit.setPetId(petId); + // petId 9 is used for testing high traffic + // To avoid overwhelming visitRepository, we don't want to save the visit. + if (petId == 9) { + log.info("Testing random traffic with visit {}", visit); + return visit; + } + log.info("Saving visit {}", visit); + return visitRepository.save(visit); + } + + @GetMapping("owners/*/pets/{petId}/visits") + public Visits visits(@PathVariable("petId") @Min(1) int petId) throws Exception { +// return visitRepository.findByPetId(petId); + return new Visits(visitRepository.findByPetId(petId)); + } + + @GetMapping("pets/visits") + public Visits visitsMultiGet(@RequestParam("petId") List petIds) throws Exception { + final List byPetIdIn = visitRepository.findByPetIdIn(petIds); + return new Visits(byPetIdIn); + } + + @Value + static class Visits { + List items; + } +} diff --git a/spring-petclinic-visits-service/src/main/resources/application.yml b/spring-petclinic-visits-service/src/main/resources/application.yml new file mode 100644 index 0000000..8d9fc12 --- /dev/null +++ b/spring-petclinic-visits-service/src/main/resources/application.yml @@ -0,0 +1,18 @@ +spring: + application: + name: visits-service + config: + import: optional:configserver:${CONFIG_SERVER_URL:http://localhost:8888/} + +eureka: + instance: + preferIpAddress: true + client: + service-url: + defaultZone: ${DISCOVERY_SERVER_URL:http://localhost:8761/eureka} +--- +spring: + config: + activate: + on-profile: docker + import: configserver:http://config-server:8888 diff --git a/spring-petclinic-visits-service/src/main/resources/db/hsqldb/data.sql b/spring-petclinic-visits-service/src/main/resources/db/hsqldb/data.sql new file mode 100644 index 0000000..29bc762 --- /dev/null +++ b/spring-petclinic-visits-service/src/main/resources/db/hsqldb/data.sql @@ -0,0 +1,4 @@ +INSERT INTO visits VALUES (1, 7, '2013-01-01', 'rabies shot'); +INSERT INTO visits VALUES (2, 8, '2013-01-02', 'rabies shot'); +INSERT INTO visits VALUES (3, 8, '2013-01-03', 'neutered'); +INSERT INTO visits VALUES (4, 7, '2013-01-04', 'spayed'); diff --git a/spring-petclinic-visits-service/src/main/resources/db/hsqldb/schema.sql b/spring-petclinic-visits-service/src/main/resources/db/hsqldb/schema.sql new file mode 100644 index 0000000..9714a58 --- /dev/null +++ b/spring-petclinic-visits-service/src/main/resources/db/hsqldb/schema.sql @@ -0,0 +1,10 @@ +DROP TABLE visits IF EXISTS; + +CREATE TABLE visits ( + id INTEGER IDENTITY PRIMARY KEY, + pet_id INTEGER NOT NULL, + visit_date DATE, + description VARCHAR(8192) +); + +CREATE INDEX visits_pet_id ON visits (pet_id); diff --git a/spring-petclinic-visits-service/src/main/resources/db/mysql/data.sql b/spring-petclinic-visits-service/src/main/resources/db/mysql/data.sql new file mode 100644 index 0000000..d57dce6 --- /dev/null +++ b/spring-petclinic-visits-service/src/main/resources/db/mysql/data.sql @@ -0,0 +1,4 @@ +INSERT IGNORE INTO visits VALUES (1, 7, '2010-03-04', 'rabies shot'); +INSERT IGNORE INTO visits VALUES (2, 8, '2011-03-04', 'rabies shot'); +INSERT IGNORE INTO visits VALUES (3, 8, '2009-06-04', 'neutered'); +INSERT IGNORE INTO visits VALUES (4, 7, '2008-09-04', 'spayed'); diff --git a/spring-petclinic-visits-service/src/main/resources/db/mysql/schema.sql b/spring-petclinic-visits-service/src/main/resources/db/mysql/schema.sql new file mode 100644 index 0000000..65c448c --- /dev/null +++ b/spring-petclinic-visits-service/src/main/resources/db/mysql/schema.sql @@ -0,0 +1,12 @@ +CREATE DATABASE IF NOT EXISTS petclinic; +GRANT ALL PRIVILEGES ON petclinic.* TO pc@localhost IDENTIFIED BY 'pc'; + +USE petclinic; + +CREATE TABLE IF NOT EXISTS visits ( + id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + pet_id INT(4) UNSIGNED NOT NULL, + visit_date DATE, + description VARCHAR(8192), + FOREIGN KEY (pet_id) REFERENCES pets(id) +) engine=InnoDB; diff --git a/spring-petclinic-visits-service/src/main/resources/logback-spring.xml b/spring-petclinic-visits-service/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..5d03f79 --- /dev/null +++ b/spring-petclinic-visits-service/src/main/resources/logback-spring.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/spring-petclinic-visits-service/src/test/java/org/springframework/samples/petclinic/visits/web/VisitResourceTest.java b/spring-petclinic-visits-service/src/test/java/org/springframework/samples/petclinic/visits/web/VisitResourceTest.java new file mode 100644 index 0000000..b8b0249 --- /dev/null +++ b/spring-petclinic-visits-service/src/test/java/org/springframework/samples/petclinic/visits/web/VisitResourceTest.java @@ -0,0 +1,79 @@ +/* + * Copyright 2002-2021 the original author or 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. + * + * Modifications Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package org.springframework.samples.petclinic.visits.web; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.samples.petclinic.visits.model.VisitRepository; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; + + +import static java.util.Arrays.asList; +import static org.mockito.BDDMockito.given; +import static org.springframework.samples.petclinic.visits.model.Visit.visit; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(SpringExtension.class) +@WebMvcTest(VisitResource.class) +@ActiveProfiles("test") +class VisitResourceTest { + + @Autowired + MockMvc mvc; + + @MockBean + VisitRepository visitRepository; + + //@Test + void shouldFetchVisits() throws Exception { + given(visitRepository.findByPetIdIn(asList(111, 222))) + .willReturn( + asList( + visit() + .id(1) + .petId(111) + .build(), + visit() + .id(2) + .petId(222) + .build(), + visit() + .id(3) + .petId(222) + .build() + ) + ); + + mvc.perform(get("/pets/visits?petId=111,222")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.items[0].id").value(1)) + .andExpect(jsonPath("$.items[1].id").value(2)) + .andExpect(jsonPath("$.items[2].id").value(3)) + .andExpect(jsonPath("$.items[0].petId").value(111)) + .andExpect(jsonPath("$.items[1].petId").value(222)) + .andExpect(jsonPath("$.items[2].petId").value(222)); + } +} diff --git a/spring-petclinic-visits-service/src/test/resources/application-test.yml b/spring-petclinic-visits-service/src/test/resources/application-test.yml new file mode 100644 index 0000000..b9c699b --- /dev/null +++ b/spring-petclinic-visits-service/src/test/resources/application-test.yml @@ -0,0 +1,18 @@ +spring: + cloud: + config: + enabled: false + sql: + init: + schema-locations: classpath*:db/hsqldb/schema.sql + data-locations: classpath*:db/hsqldb/data.sql + jpa: + hibernate: + ddl-auto: none + +eureka: + client: + enabled: false + +logging.level.org.springframework: INFO +