├── infra ├── modules │ ├── lambda │ │ ├── outputs.tf │ │ ├── variables.tf │ │ ├── ecs-unprotect-lambda │ │ │ └── index.py │ │ ├── main.tf │ │ └── ecs-scaledown-lambda │ │ │ └── index.py │ ├── iam │ │ ├── variables.tf │ │ ├── outputs.tf │ │ └── main.tf │ ├── ec2 │ │ ├── outputs.tf │ │ ├── variables.tf │ │ └── main.tf │ └── ecs │ │ ├── outputs.tf │ │ ├── variables.tf │ │ └── main.tf ├── outputs.tf ├── LICENSE ├── variables.tf ├── main.tf └── README.md ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── settings.gradle ├── .idea ├── vcs.xml ├── kotlinc.xml ├── modules.xml ├── misc.xml ├── gradle.xml └── libraries │ └── KotlinJavaRuntime.xml ├── .gitignore ├── aws-ecs-server ├── src │ ├── main │ │ ├── kotlin │ │ │ └── jetbrains │ │ │ │ └── buildServer │ │ │ │ ├── clouds │ │ │ │ └── ecs │ │ │ │ │ ├── EcsInstancesUpdater.kt │ │ │ │ │ ├── apiConnector │ │ │ │ │ ├── EcsApiCallFailureException.kt │ │ │ │ │ ├── EcsCluster.kt │ │ │ │ │ ├── EcsApiConnector.kt │ │ │ │ │ ├── EcsTask.kt │ │ │ │ │ ├── EcsTaskDefinition.kt │ │ │ │ │ └── EcsApiConnectorImpl.kt │ │ │ │ │ ├── EcsCloudInstance.kt │ │ │ │ │ ├── EcsInternalProperties.kt │ │ │ │ │ ├── EcsCloudClientParameters.kt │ │ │ │ │ ├── EcsCloudImage.kt │ │ │ │ │ ├── BrokenEcsCloudInstance.kt │ │ │ │ │ ├── StartingEcsCloudInstance.kt │ │ │ │ │ ├── EcsCloudClientParametersImpl.kt │ │ │ │ │ ├── EcsInstancesUpdaterImpl.kt │ │ │ │ │ ├── EcsParameterConstants.kt │ │ │ │ │ ├── web │ │ │ │ │ ├── EcsClusterChooserController.kt │ │ │ │ │ ├── EcsDeleteImageDialogController.kt │ │ │ │ │ ├── EcsTaskDefinitionChooserController.kt │ │ │ │ │ └── EcsProfileEditController.kt │ │ │ │ │ ├── EcsCloudImageData.kt │ │ │ │ │ ├── EcsCloudInstanceImpl.kt │ │ │ │ │ ├── EcsCloudClientFactory.kt │ │ │ │ │ ├── EcsCloudClient.kt │ │ │ │ │ └── EcsCloudImageImpl.kt │ │ │ │ └── internal │ │ │ │ └── PluginPropertiesUtil.kt │ │ └── resources │ │ │ ├── buildServerResources │ │ │ ├── ecsSettings.css │ │ │ ├── deleteImageDialog.jsp │ │ │ ├── clusters.jsp │ │ │ ├── taskDefs.jsp │ │ │ ├── ecs.svg │ │ │ ├── editProfile.jsp │ │ │ └── ecsSettings.js │ │ │ └── META-INF │ │ │ └── build-server-plugin-teamcity-aws-ecs.xml │ └── test │ │ └── kotlin │ │ └── jetbrains │ │ └── buildServer │ │ └── clouds │ │ └── ecs │ │ └── EcsCloudClientTest.kt ├── aws-ecs-server.iml └── build.gradle ├── aws-ecs-common ├── build.gradle ├── aws-ecs-common.iml └── src │ └── main │ └── kotlin │ └── jetbrains │ └── buildServer │ └── clouds │ └── ecs │ └── EcsContainerEnvironment.kt ├── aws-ecs-agent ├── src │ └── main │ │ ├── resources │ │ └── META-INF │ │ │ └── build-agent-plugin-teamcity-ecs-plugin.xml │ │ └── kotlin │ │ └── jetbrains │ │ └── buildServer │ │ └── clouds │ │ └── ecs │ │ └── EcsAgentConfigurationProvider.kt ├── aws-ecs-agent.iml └── build.gradle ├── teamcity-plugin.xml ├── teamcity-amazon-ecs-plugin.iml ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /infra/modules/lambda/outputs.tf: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /infra/modules/iam/variables.tf: -------------------------------------------------------------------------------- 1 | variable "aws_region" {} 2 | 3 | variable "project_name" {} 4 | 5 | variable "stack_name" {} 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JetBrains/teamcity-amazon-ecs-plugin/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | 2 | 3 | rootProject.name = 'teamcity-amazon-ecs-plugin' 4 | 5 | include 'aws-ecs-agent' 6 | include 'aws-ecs-common' 7 | include 'aws-ecs-server' -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/kotlinc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Terraform artefacts 2 | infra/*.zip 3 | 4 | ## Local .terraform directories 5 | **/.terraform/* 6 | 7 | # .tfstate files 8 | *.tfstate 9 | *.tfstate.* 10 | 11 | # .tfvars files 12 | *.tfvars 13 | 14 | ## Directory-based project format: 15 | .idea/ 16 | -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/EcsInstancesUpdater.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs 4 | 5 | interface EcsInstancesUpdater { 6 | fun registerClient(client: EcsCloudClient) 7 | fun unregisterClient(client: EcsCloudClient) 8 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Aug 03 23:17:01 CEST 2021 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.0-bin.zip 7 | -------------------------------------------------------------------------------- /infra/modules/ec2/outputs.tf: -------------------------------------------------------------------------------- 1 | output "asg_name" { 2 | value = "${aws_autoscaling_group.agents.name}" 3 | } 4 | 5 | output "asg_min_size" { 6 | value = "${aws_autoscaling_group.agents.min_size}" 7 | } 8 | 9 | output "sns_topic_asg_arn" { 10 | value = "${aws_sns_topic.asg-sns-topic.arn}" 11 | } 12 | -------------------------------------------------------------------------------- /infra/modules/ecs/outputs.tf: -------------------------------------------------------------------------------- 1 | output "ecs_cluster_name" { 2 | value = "${aws_ecs_cluster.default.name}" 3 | } 4 | 5 | output "ecs_cluster_id" { 6 | value = "${aws_ecs_cluster.default.id}" 7 | } 8 | 9 | output "ecs_taskdefinition_name" { 10 | value = "${aws_ecs_task_definition.default.id}" 11 | } 12 | -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/apiConnector/EcsApiCallFailureException.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs.apiConnector 4 | 5 | import com.amazonaws.services.ecs.model.Failure 6 | 7 | class EcsApiCallFailureException(failures: MutableList) : Exception(failures.map { it.toString() }.joinToString("\n")) { 8 | } -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/EcsCloudInstance.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs 4 | 5 | import jetbrains.buildServer.clouds.CloudInstance 6 | import jetbrains.buildServer.clouds.ecs.apiConnector.EcsTask 7 | 8 | interface EcsCloudInstance : CloudInstance { 9 | fun terminate() 10 | 11 | fun update(task: EcsTask) 12 | } -------------------------------------------------------------------------------- /infra/outputs.tf: -------------------------------------------------------------------------------- 1 | output "aws_access_key_id" { 2 | value = "${module.iam.aws_access_key_id}" 3 | } 4 | 5 | output "aws_secret_access_key" { 6 | value = "${module.iam.aws_secret_access_key}" 7 | } 8 | 9 | output "ecs_cluster_name" { 10 | value = "${module.ecs.ecs_cluster_name}" 11 | } 12 | 13 | output "ecs_taskdefinition_name" { 14 | value = "${module.ecs.ecs_taskdefinition_name}" 15 | } 16 | -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/EcsInternalProperties.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs 4 | 5 | /** 6 | * Created by Evgeniy Koshkin (evgeniy.koshkin@jetbrains.com) on 13.11.17. 7 | */ 8 | 9 | val ECS_CACHE_EXPIRATION_TIMEOUT = "teamcity.ecs.cache.expirationTimeout" 10 | val ECS_TASKS_MONITORING_PERIOD = "teamcity.ecs.tasks.monitoring.period" 11 | val ECS_METRICS_MONITORING_PERIOD = "teamcity.ecs.metrics.monitoring.period" -------------------------------------------------------------------------------- /aws-ecs-common/build.gradle: -------------------------------------------------------------------------------- 1 | 2 | 3 | plugins{ 4 | id 'com.github.rodm.teamcity-common' version '1.0' 5 | } 6 | 7 | dependencies { 8 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 9 | } 10 | 11 | teamcity { 12 | version = teamcityVersion 13 | } 14 | 15 | compileKotlin { 16 | kotlinOptions { 17 | jvmTarget = "1.8" 18 | } 19 | } 20 | 21 | tasks.withType(JavaCompile) { 22 | sourceCompatibility = "1.8" 23 | targetCompatibility = "1.8" 24 | } -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/apiConnector/EcsCluster.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs.apiConnector 4 | 5 | import com.amazonaws.services.ecs.model.Cluster 6 | 7 | interface EcsCluster { 8 | val arn: String 9 | val name: String 10 | } 11 | 12 | fun Cluster.wrap(): EcsCluster = object : EcsCluster{ 13 | override val arn: String 14 | get() = this@wrap.clusterArn 15 | override val name: String 16 | get() = this@wrap.clusterName 17 | } -------------------------------------------------------------------------------- /aws-ecs-server/src/main/resources/buildServerResources/ecsSettings.css: -------------------------------------------------------------------------------- 1 | 2 | 3 | .section-header { 4 | margin: 13px 0 13px 8px; 5 | } 6 | 7 | .imagesOuterWrapper { 8 | padding-left: 8px; 9 | } 10 | 11 | .imagesTableWrapper { 12 | margin-bottom: 0.5em; 13 | } 14 | 15 | ul.chooser { 16 | list-style-type: none; 17 | margin: 0; 18 | padding: 0; 19 | } 20 | 21 | textarea .subnetList { 22 | width: 100%; 23 | height: 30em; 24 | } 25 | 26 | textarea .securityGroupList { 27 | width: 100%; 28 | height: 30em; 29 | } -------------------------------------------------------------------------------- /infra/modules/lambda/variables.tf: -------------------------------------------------------------------------------- 1 | variable "project_name" {} 2 | variable "stack_name" {} 3 | variable "iam_role_sns_lambda_arn" {} 4 | variable "iam_role_lambda_ecs_asg_arn" {} 5 | variable "iam_role_lambda_ecs_unprotect_asg_arn" {} 6 | variable "ecs_cluster_name" {} 7 | variable "ecs_cluster_id" {} 8 | variable "sns_topic_asg_arn" {} 9 | variable "asg_name" {} 10 | variable "asg_min_size" {} 11 | 12 | variable "log_retention" { 13 | description = "Specifies the number of days you want to retain log events" 14 | default = 1 15 | } 16 | -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/EcsCloudClientParameters.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs 4 | 5 | import com.amazonaws.auth.AWSCredentials 6 | import com.amazonaws.auth.AWSCredentialsProvider 7 | 8 | /** 9 | * Created by Evgeniy Koshkin (evgeniy.koshkin@jetbrains.com) on 20.09.17. 10 | */ 11 | interface EcsCloudClientParameters { 12 | val region: String 13 | 14 | val imagesData: List 15 | val instanceLimit: Int 16 | val awsCredentialsProvider: AWSCredentialsProvider 17 | } -------------------------------------------------------------------------------- /infra/LICENSE: -------------------------------------------------------------------------------- 1 | Licensed under the Apache License, Version 2.0 (the "License"); 2 | you may not use this file except in compliance with the License. 3 | You may obtain a copy of the License at 4 | 5 | http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. -------------------------------------------------------------------------------- /aws-ecs-agent/src/main/resources/META-INF/build-agent-plugin-teamcity-ecs-plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/EcsCloudImage.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs 4 | 5 | import jetbrains.buildServer.clouds.CanStartNewInstanceResult 6 | import jetbrains.buildServer.clouds.CloudImage 7 | import jetbrains.buildServer.clouds.CloudInstanceUserData 8 | 9 | interface EcsCloudImage : CloudImage { 10 | val runningInstanceCount: Int 11 | 12 | fun populateInstances() 13 | fun generateAgentName(instanceId: String): String 14 | 15 | fun canStartNewInstanceWithDetails(): CanStartNewInstanceResult 16 | fun startNewInstance(tag: CloudInstanceUserData): EcsCloudInstance 17 | } -------------------------------------------------------------------------------- /aws-ecs-server/src/main/resources/buildServerResources/deleteImageDialog.jsp: -------------------------------------------------------------------------------- 1 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 2 | <%@ include file="/include.jsp" %> 3 | 4 | 5 | 6 | 7 | 8 |

Are you sure you want to remove the image?

9 | 10 | Following cloud instance(s) will be terminated 11 |
    12 | 13 |
  • 14 |
    15 |
16 |
-------------------------------------------------------------------------------- /infra/modules/iam/outputs.tf: -------------------------------------------------------------------------------- 1 | output "instance_profile_arn" { 2 | value = "${aws_iam_instance_profile.instance_profile.arn}" 3 | } 4 | 5 | output "iam_role_lambda_ecs_asg_arn" { 6 | value = "${aws_iam_role.lambda-ecs-asg.arn}" 7 | } 8 | 9 | output "iam_role_lambda_ecs_unprotect_asg_arn" { 10 | value = "${aws_iam_role.lambda-ecs-unprotect-asg.arn}" 11 | } 12 | 13 | output "iam_role_sns_lambda_arn" { 14 | value = "${aws_iam_role.sns-lambda.arn}" 15 | } 16 | 17 | output "aws_access_key_id" { 18 | value = "${aws_iam_access_key.server.id}" 19 | } 20 | 21 | output "aws_secret_access_key" { 22 | value = "${aws_iam_access_key.server.secret}" 23 | } 24 | -------------------------------------------------------------------------------- /infra/modules/ecs/variables.tf: -------------------------------------------------------------------------------- 1 | variable "aws_region" {} 2 | variable "project_name" {} 3 | variable "stack_name" {} 4 | 5 | variable "app_image" { 6 | default = "jetbrains/teamcity-agent" 7 | } 8 | 9 | variable "app_version" { 10 | default = "latest" 11 | } 12 | 13 | variable "ecs_task_cpu" { 14 | description = "ECS Task definition cpu allocation" 15 | default = 2048 16 | } 17 | 18 | variable "ecs_task_memory" { 19 | description = "ECS Task definition memory allocation" 20 | default = 3953 21 | } 22 | 23 | variable "log_retention" { 24 | description = "Specifies the number of days you want to retain log events" 25 | default = 1 26 | } -------------------------------------------------------------------------------- /teamcity-plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | aws-ecs-plugin 7 | Amazon Elastic Container Service Support 8 | @Plugin_Version@ 9 | Allows running TeamCity build agents on Amazon Elastic Container Service 10 | 11 | JetBrains 12 | https://www.jetbrains.com 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 1.4 11 | 12 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /aws-ecs-server/src/main/resources/META-INF/build-server-plugin-teamcity-aws-ecs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 20 | -------------------------------------------------------------------------------- /.idea/libraries/KotlinJavaRuntime.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /teamcity-amazon-ecs-plugin.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /aws-ecs-agent/aws-ecs-agent.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /aws-ecs-common/aws-ecs-common.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /aws-ecs-server/aws-ecs-server.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /aws-ecs-agent/build.gradle: -------------------------------------------------------------------------------- 1 | 2 | 3 | plugins { 4 | id 'com.github.rodm.teamcity-agent' version "1.0" 5 | } 6 | 7 | teamcity { 8 | version = teamcityVersion 9 | 10 | agent{ 11 | descriptor{ 12 | pluginDeployment{ 13 | useSeparateClassloader = true 14 | } 15 | } 16 | } 17 | } 18 | 19 | dependencies { 20 | compile project(path: ':aws-ecs-common', configuration:'default') 21 | provided "org.jetbrains.teamcity.internal:agent:$teamcityVersion" 22 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 23 | compile "org.json:json:20180813" 24 | testCompile 'org.testng:testng:6.8' 25 | testCompile 'org.jmock:jmock:2.5.1' 26 | } 27 | 28 | agentPlugin.version = null 29 | agentPlugin.baseName = 'teamcity-aws-ecs' 30 | 31 | compileKotlin { 32 | kotlinOptions { 33 | jvmTarget = "1.8" 34 | } 35 | } 36 | 37 | tasks.withType(JavaCompile) { 38 | sourceCompatibility = "1.8" 39 | targetCompatibility = "1.8" 40 | } -------------------------------------------------------------------------------- /infra/modules/ec2/variables.tf: -------------------------------------------------------------------------------- 1 | variable "project_name" {} 2 | variable "stack_name" {} 3 | variable "iam_role_sns_lambda_arn" {} 4 | 5 | variable "instance_type" { 6 | description = "EC2 instance type that will be used for ECS" 7 | } 8 | 9 | variable "ec2_keypair_name" {} 10 | 11 | variable "instance_profile_arn" {} 12 | 13 | variable "docker_basesize" {} 14 | 15 | variable "asg_scaling_adjustment" { 16 | description = "The number of members by which to scale" 17 | default = 1 18 | } 19 | 20 | variable "asg_cooldown" { 21 | description = "ASG cooldown period" 22 | default = 120 23 | } 24 | 25 | variable "asg_metric_period" { 26 | description = "ASG up/down metric period" 27 | default = 60 28 | } 29 | 30 | variable "asg_min_size" { 31 | description = "Required mix size for ASG" 32 | default = 1 33 | } 34 | 35 | variable "asg_max_size" { 36 | description = "Required max size for ASG" 37 | default = 3 38 | } 39 | 40 | variable "vpc_zone_identifier" { 41 | type = "list" 42 | } 43 | 44 | variable "ec2_volume_size" { 45 | description = "The size of instance volume in gigabytes for docker service." 46 | default = "50" 47 | } 48 | -------------------------------------------------------------------------------- /aws-ecs-common/src/main/kotlin/jetbrains/buildServer/clouds/ecs/EcsContainerEnvironment.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs 4 | 5 | /** 6 | * Created by ekoshkin (koshkinev@gmail.com) on 07.06.17. 7 | */ 8 | 9 | const val TEAMCITY_ECS_PREFIX = "TEAMCITY_ECS_" 10 | const val TEAMCITY_ECS_PROVIDED_PREFIX = "TC_ECS_PROVIDED_" 11 | 12 | const val SERVER_URL_ECS_ENV = TEAMCITY_ECS_PREFIX + "SERVER_URL" 13 | const val SERVER_UUID_ECS_ENV = TEAMCITY_ECS_PREFIX + "SERVER_UUID" 14 | const val IMAGE_ID_ECS_ENV = TEAMCITY_ECS_PREFIX + "IMAGE_ID" 15 | const val PROFILE_ID_ECS_ENV = TEAMCITY_ECS_PREFIX + "CLOUD_PROFILE_ID" 16 | const val INSTANCE_ID_ECS_ENV = TEAMCITY_ECS_PREFIX + "INSTANCE_ID" 17 | const val STARTING_INSTANCE_ID_ECS_ENV = TEAMCITY_ECS_PREFIX + "STARTING_INSTANCE_ID" 18 | const val AGENT_NAME_ECS_ENV = TEAMCITY_ECS_PREFIX + "AGENT_NAME" 19 | 20 | const val OFFICIAL_IMAGE_SERVER_URL_ECS_ENV = "SERVER_URL" 21 | const val ECS_CONTAINER_METADATA_URI = "ECS_CONTAINER_METADATA_URI" 22 | const val ECS_CONTAINER_METADATA_FILE = "ECS_CONTAINER_METADATA_FILE" 23 | 24 | const val REQUIRED_PROFILE_ID_CONFIG_PARAM = "system.cloud.profile_id" 25 | const val STARTING_INSTANCE_ID_CONFIG_PARAM = "teamcity.agent.startingInstanceId" -------------------------------------------------------------------------------- /aws-ecs-server/src/main/resources/buildServerResources/clusters.jsp: -------------------------------------------------------------------------------- 1 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 2 | <%@ include file="/include.jsp" %> 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | No clusters found 21 | 22 | 23 |
    24 | 25 |
  • 26 |
    27 |
28 |
29 |
30 |
31 |
-------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/BrokenEcsCloudInstance.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs 4 | 5 | import jetbrains.buildServer.clouds.CloudErrorInfo 6 | import jetbrains.buildServer.clouds.InstanceStatus 7 | import jetbrains.buildServer.clouds.ecs.apiConnector.EcsTask 8 | import jetbrains.buildServer.serverSide.AgentDescription 9 | import java.util.* 10 | 11 | class BrokenEcsCloudInstance(private val instanceId: String, 12 | private val cloudImage: EcsCloudImage, 13 | private val errorInfo: CloudErrorInfo) : EcsCloudInstance { 14 | override fun update(task: EcsTask) { 15 | // do nothing 16 | } 17 | 18 | private val startTime = Date() 19 | 20 | override fun terminate() { 21 | // do nothing 22 | } 23 | 24 | override fun getStatus() = InstanceStatus.ERROR 25 | 26 | override fun getInstanceId() = instanceId 27 | 28 | override fun getName() = instanceId 29 | 30 | override fun getStartedTime() = startTime 31 | 32 | override fun getImage() = cloudImage 33 | 34 | override fun getNetworkIdentity(): String? = null 35 | 36 | override fun getImageId() = cloudImage.id 37 | 38 | override fun getErrorInfo() = errorInfo 39 | 40 | override fun containsAgent(p0: AgentDescription) = false 41 | } -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/StartingEcsCloudInstance.kt: -------------------------------------------------------------------------------- 1 | package jetbrains.buildServer.clouds.ecs 2 | 3 | import jetbrains.buildServer.clouds.CloudErrorInfo 4 | import jetbrains.buildServer.clouds.InstanceStatus 5 | import jetbrains.buildServer.clouds.ecs.apiConnector.EcsTask 6 | import jetbrains.buildServer.serverSide.AgentDescription 7 | import java.util.* 8 | 9 | class StartingEcsCloudInstance(private val instanceId: String, 10 | private val cloudImage: EcsCloudImage 11 | ) : EcsCloudInstance { 12 | private val startTime = Date() 13 | @Volatile 14 | private var wasTerminated = false 15 | val terminateRequested : Boolean 16 | get() = wasTerminated 17 | 18 | 19 | override fun terminate() { 20 | wasTerminated = true 21 | } 22 | 23 | override fun update(task: EcsTask) { 24 | // do nothing 25 | } 26 | 27 | override fun getErrorInfo(): CloudErrorInfo? = null 28 | 29 | override fun getInstanceId() = instanceId 30 | 31 | override fun getName() = "Starting..." 32 | 33 | override fun getImageId() = cloudImage.id 34 | 35 | override fun getImage() = cloudImage 36 | 37 | override fun getStartedTime() = startTime 38 | 39 | override fun getNetworkIdentity() = null 40 | 41 | override fun getStatus() = InstanceStatus.SCHEDULED_TO_START 42 | 43 | override fun containsAgent(agent: AgentDescription) = false; 44 | } -------------------------------------------------------------------------------- /aws-ecs-server/src/main/resources/buildServerResources/taskDefs.jsp: -------------------------------------------------------------------------------- 1 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 2 | <%@ include file="/include.jsp" %> 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | No task definistions found 21 | 22 | 23 |
    24 | 25 |
  • 26 | 27 | 28 |
  • 29 |
    30 |
31 |
32 |
33 |
34 |
-------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/EcsCloudClientParametersImpl.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs 4 | 5 | import com.amazonaws.auth.AWSCredentials 6 | import com.amazonaws.auth.AWSCredentialsProvider 7 | import jetbrains.buildServer.clouds.CloudClientParameters 8 | import jetbrains.buildServer.util.StringUtil 9 | import jetbrains.buildServer.util.amazon.AWSCommonParams 10 | import jetbrains.buildServer.util.amazon.AWSCommonParams.* 11 | 12 | fun CloudClientParameters.toEcsParams() : EcsCloudClientParameters = EcsCloudClientParametersImpl(this) 13 | 14 | class EcsCloudClientParametersImpl(private val genericParams: CloudClientParameters) : EcsCloudClientParameters { 15 | override val region: String 16 | get() = AWSCommonParams.getRegionName(genericParams.parameters)!! 17 | 18 | override val instanceLimit: Int 19 | get() { 20 | val parameter = genericParams.getParameter(PROFILE_INSTANCE_LIMIT_PARAM) 21 | return if (StringUtil.isEmpty(parameter)) -1 else Integer.valueOf(parameter) 22 | } 23 | 24 | override val imagesData: List 25 | get() = genericParams.cloudImages.map { EcsCloudImageData(it) } 26 | 27 | //NOTE: copy pasted from jetbrains.buildServer.util.amazon.AWSCommonParams 28 | 29 | override val awsCredentialsProvider: AWSCredentialsProvider 30 | get() { 31 | return genericParams.parameters.toAwsCredentialsProvider() 32 | } 33 | } 34 | 35 | fun Map.toAwsCredentialsProvider(): AWSCredentialsProvider = getCredentialsProvider(this) -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/EcsInstancesUpdaterImpl.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs 4 | 5 | import com.intellij.openapi.diagnostic.Logger 6 | import jetbrains.buildServer.serverSide.TeamCityProperties 7 | import jetbrains.buildServer.serverSide.executors.ExecutorServices 8 | import java.util.concurrent.TimeUnit 9 | 10 | /** 11 | * Created by Evgeniy Koshkin (evgeniy.koshkin@jetbrains.com) on 13.11.17. 12 | */ 13 | class EcsInstancesUpdaterImpl(executors: ExecutorServices) : EcsInstancesUpdater { 14 | private val LOG = Logger.getInstance(EcsInstancesUpdaterImpl::class.java.getName()) 15 | 16 | private val registeredClients: MutableCollection = ArrayList() 17 | 18 | override fun registerClient(client: EcsCloudClient) { 19 | registeredClients.add(client) 20 | } 21 | 22 | override fun unregisterClient(client: EcsCloudClient) { 23 | registeredClients.remove(client) 24 | } 25 | 26 | init { 27 | val delay = TeamCityProperties.getLong(ECS_TASKS_MONITORING_PERIOD, 1) 28 | executors.normalExecutorService.scheduleWithFixedDelay({ populateInstances() }, delay, delay, TimeUnit.MINUTES) 29 | } 30 | 31 | private fun populateInstances() { 32 | val populateInstancesStartTime = System.currentTimeMillis() 33 | registeredClients.forEach { client -> client.images.forEach { image -> (image as EcsCloudImage).populateInstances() } } 34 | LOG.debug("Populate ECS instances task finished in " + TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - populateInstancesStartTime) + " seconds") 35 | } 36 | } -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/apiConnector/EcsApiConnector.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs.apiConnector 4 | 5 | import com.amazonaws.services.ecs.model.LaunchType 6 | 7 | /** 8 | * Created by Evgeniy Koshkin (evgeniy.koshkin@jetbrains.com) on 19.09.17. 9 | */ 10 | interface EcsApiConnector { 11 | fun listTaskDefinitions(): List //list of task definition arns 12 | fun describeTaskDefinition(taskDefinitionArn: String): EcsTaskDefinition? 13 | 14 | fun runTask(launchType: LaunchType?, 15 | taskDefinition: EcsTaskDefinition, 16 | cluster: String?, 17 | taskGroup: String?, 18 | subnets: Collection, 19 | securityGroups: Collection, 20 | assignPublicIp: Boolean, 21 | additionalEnvironment: Map, 22 | startedBy: String?, 23 | fargatePlatformVersion: String?): List 24 | 25 | fun stopTask(task: String, cluster: String?, reason: String?) 26 | 27 | fun listRunningTasks(cluster: String?, startedBy: String?): List //list of task arns 28 | fun listStoppedTasks(cluster: String?, startedBy: String?): List //list of task arns 29 | fun describeTask(taskArn:String, cluster: String?): EcsTask? 30 | 31 | fun listClusters(): List //list of cluster arns 32 | fun describeCluster(clusterArn:String): EcsCluster? 33 | fun testConnection(): TestConnectionResult 34 | 35 | fun getMaxCPUReservation(cluster: String?, period: Int): Int 36 | } 37 | 38 | class TestConnectionResult(val message: String?, val success: Boolean) { 39 | } -------------------------------------------------------------------------------- /infra/variables.tf: -------------------------------------------------------------------------------- 1 | # Project parameters 2 | variable "project_name" { 3 | default = "teamcity" 4 | } 5 | 6 | variable "stack_name" { 7 | description = "Name of the stack: sandbox/staging/production." 8 | default = "example" 9 | } 10 | 11 | # EC2 parameters 12 | variable "instance_type" { 13 | description = "EC2 instance type that will be used for ECS." 14 | default = "c3.xlarge" 15 | } 16 | 17 | variable "ec2_keypair_name" { 18 | description = "The key name that should be used for the EC2 instance." 19 | } 20 | 21 | variable "ec2_volume_size" { 22 | description = "The size of instance volume in gigabytes for docker service." 23 | default = "50" 24 | } 25 | 26 | variable "vpc_id" { 27 | description = "The id of the VPC" 28 | } 29 | 30 | # Autoscaler parameters 31 | variable "asg_min_size" { 32 | description = "The minimum size of the auto scale group." 33 | default = 1 34 | } 35 | 36 | variable "asg_max_size" { 37 | description = "The maximum size of the auto scale group." 38 | default = 3 39 | } 40 | 41 | # Agent parameters 42 | variable "app_image" { 43 | description = "The image used to start a agent." 44 | default = "jetbrains/teamcity-agent" 45 | } 46 | 47 | variable "app_version" { 48 | description = "The version of agent image." 49 | default = "latest" 50 | } 51 | 52 | variable "agent_cpu" { 53 | description = "The minimum number of CPU units to reserve for the agent." 54 | default = 2048 55 | } 56 | 57 | variable "agent_mem" { 58 | description = "The number of MiB of memory to reserve for the agent." 59 | default = 3740 60 | } 61 | 62 | variable "agent_disk" { 63 | description = "The size of docker base device, which limits the size of agent." 64 | default = "20G" 65 | } 66 | -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/apiConnector/EcsTask.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs.apiConnector 4 | 5 | import com.amazonaws.services.ecs.model.Task 6 | import java.util.* 7 | 8 | /** 9 | * Created by Evgeniy Koshkin (evgeniy.koshkin@jetbrains.com) on 19.09.17. 10 | */ 11 | interface EcsTask { 12 | val arn: String 13 | val id: String 14 | val taskDefinitionArn: String 15 | val clusterArn: String? 16 | val lastStatus: String 17 | val desiredStatus: String 18 | val cratedAt: Date 19 | val startedAt: Date? 20 | fun getOverridenContainerEnv(envVarName: String): String? 21 | } 22 | 23 | fun Task.wrap(): EcsTask = object : EcsTask{ 24 | override val id: String 25 | get() = this@wrap.taskArn.substring(this@wrap.taskArn.indexOf(":task/") + 6) 26 | override val taskDefinitionArn: String 27 | get() = this@wrap.taskDefinitionArn 28 | override val clusterArn: String? 29 | get() = this@wrap.clusterArn 30 | override val desiredStatus: String 31 | get() = this@wrap.desiredStatus 32 | override val lastStatus: String 33 | get() = this@wrap.lastStatus 34 | override val arn: String 35 | get() = this@wrap.taskArn 36 | override val cratedAt: Date 37 | get() = this@wrap.createdAt 38 | override val startedAt: Date? 39 | get() = this@wrap.startedAt 40 | 41 | override fun getOverridenContainerEnv(envVarName: String): String? { 42 | for(containerOverrides in this@wrap.overrides.containerOverrides){ 43 | containerOverrides.environment 44 | .filter { it.name.equals(envVarName) } 45 | .forEach { return it.value } 46 | } 47 | return null 48 | } 49 | } -------------------------------------------------------------------------------- /aws-ecs-server/build.gradle: -------------------------------------------------------------------------------- 1 | 2 | 3 | plugins { 4 | id 'com.github.rodm.teamcity-server' version "1.0" 5 | } 6 | 7 | repositories { 8 | maven { url "https://jcenter.bintray.com" } 9 | } 10 | 11 | dependencyManagement { 12 | imports { 13 | mavenBom 'com.amazonaws:aws-java-sdk-bom:1.11.908' 14 | } 15 | } 16 | 17 | teamcity { 18 | version = teamcityVersion 19 | 20 | server { 21 | descriptor = rootProject.file('teamcity-plugin.xml') 22 | tokens = [Plugin_Version: project.version] 23 | } 24 | } 25 | 26 | dependencies { 27 | compile 'com.amazonaws:aws-java-sdk-ecs:1.11.908' 28 | compile 'com.amazonaws:aws-java-sdk-cloudwatch:1.11.908' 29 | 30 | compile project(path: ':aws-ecs-common', configuration:'default') 31 | agent project(path: ':aws-ecs-agent', configuration: 'plugin') 32 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 33 | compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3" 34 | 35 | 36 | compile 'jetbrains.buildServer.util:amazon-util:2021.1-SNAPSHOT' 37 | provided "org.jetbrains.teamcity:cloud-interface:$teamcityVersion" 38 | provided "org.jetbrains.teamcity:cloud-shared:$teamcityVersion" 39 | provided "org.jetbrains.teamcity:cloud-server-api:$teamcityVersion" 40 | provided "org.jetbrains.teamcity:server-web-api:$teamcityVersion" 41 | provided "org.jetbrains.teamcity.internal:server:$teamcityVersion" 42 | } 43 | 44 | serverPlugin.version = null 45 | serverPlugin.baseName = 'aws-ecs' 46 | 47 | tasks.withType(JavaCompile) { 48 | sourceCompatibility = "1.8" 49 | targetCompatibility = "1.8" 50 | } 51 | 52 | compileKotlin { 53 | kotlinOptions { 54 | jvmTarget = "1.8" 55 | } 56 | } 57 | 58 | compileTestKotlin { 59 | kotlinOptions { 60 | jvmTarget = "1.8" 61 | } 62 | } -------------------------------------------------------------------------------- /infra/modules/ecs/main.tf: -------------------------------------------------------------------------------- 1 | resource "aws_ecs_cluster" "default" { 2 | name = "${var.project_name}-${var.stack_name}" 3 | } 4 | 5 | resource "aws_ecs_task_definition" "default" { 6 | family = "${var.project_name}-agent-${var.stack_name}" 7 | 8 | container_definitions = < 16 | val requiresCompatibilitiesString: String 17 | fun isCompatibleWithLaunchType(launchType: String?): Boolean 18 | } 19 | 20 | fun TaskDefinition.wrap(): EcsTaskDefinition = object : EcsTaskDefinition{ 21 | override fun isCompatibleWithLaunchType(launchType: String?): Boolean { 22 | if(launchType.isNullOrEmpty()) return true 23 | 24 | var requiresCompatibilities = this@wrap.requiresCompatibilities 25 | if(requiresCompatibilities.isEmpty()) requiresCompatibilities = listOf(Compatibility.EC2.name) 26 | 27 | return requiresCompatibilities.contains(launchType) 28 | } 29 | 30 | override val requiresCompatibilitiesString: String 31 | get(){ 32 | var requiresCompatibilities = this@wrap.requiresCompatibilities 33 | if(requiresCompatibilities.isEmpty()) requiresCompatibilities = listOf(Compatibility.EC2.name) 34 | return requiresCompatibilities.joinToString(separator = " ,") 35 | } 36 | 37 | override val displayName: String 38 | get() = "${this@wrap.family}:${this@wrap.revision}" 39 | 40 | override val family: String 41 | get() = this@wrap.family 42 | 43 | override val containers: Collection 44 | get() = this@wrap.containerDefinitions.map { containerDef -> containerDef.name } 45 | 46 | override val arn: String 47 | get() = this@wrap.taskDefinitionArn 48 | } -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/EcsParameterConstants.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs 4 | 5 | import jetbrains.buildServer.clouds.CloudImageParameters 6 | 7 | /** 8 | * Created by Evgeniy Koshkin (evgeniy.koshkin@jetbrains.com) on 21.09.17. 9 | */ 10 | 11 | const val PROFILE_INSTANCE_LIMIT_PARAM = "profileInstanceLimit" 12 | const val IMAGE_INSTANCE_LIMIT_PARAM = "maxInstances" 13 | const val CPU_RESERVATION_LIMIT_PARAM = "cpuReservationLimit" 14 | const val LAUNCH_TYPE_PARAM = "launchType" 15 | const val TASK_DEFINITION_PARAM = "taskDefinition" 16 | const val TASK_GROUP_PARAM = "taskGroup" 17 | const val SUBNETS_PARAM = "subnets" 18 | const val SECURITY_GROUPS_PARAM = "securityGroups" 19 | const val ASSIGN_PUBLIC_IP_PARAM = "assignPublicIp" 20 | const val CLUSTER_PARAM = "cluster" 21 | const val AGENT_NAME_PREFIX = "agentNamePrefix" 22 | const val FARGATE_PLATFORM_VERSION = "fargatePlatformVersion" 23 | 24 | class EcsParameterConstants{ 25 | companion object{ 26 | val FARGATE_VERSIONS = arrayOf( 27 | "LATEST", 28 | "1.4.0", 29 | "1.3.0", 30 | "1.2.0", 31 | "1.1.0", 32 | "1.0.0" 33 | ) 34 | } 35 | 36 | val agentNamePrefix: String = AGENT_NAME_PREFIX 37 | val launchType: String = LAUNCH_TYPE_PARAM 38 | val taskDefinition: String = TASK_DEFINITION_PARAM 39 | val cluster: String = CLUSTER_PARAM 40 | val taskGroup: String = TASK_GROUP_PARAM 41 | val subnets: String = SUBNETS_PARAM 42 | val securityGroups: String = SECURITY_GROUPS_PARAM 43 | val assignPublicIp: String = ASSIGN_PUBLIC_IP_PARAM 44 | val maxInstances: String = IMAGE_INSTANCE_LIMIT_PARAM 45 | val agentPoolIdField: String = CloudImageParameters.AGENT_POOL_ID_FIELD 46 | val profileInstanceLimit: String = PROFILE_INSTANCE_LIMIT_PARAM 47 | val cpuReservationLimit: String = CPU_RESERVATION_LIMIT_PARAM 48 | val fargatePlatformVersion = FARGATE_PLATFORM_VERSION 49 | } -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/web/EcsClusterChooserController.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs.web 4 | 5 | import jetbrains.buildServer.clouds.ecs.apiConnector.EcsApiConnectorImpl 6 | import jetbrains.buildServer.clouds.ecs.apiConnector.EcsCluster 7 | import jetbrains.buildServer.clouds.ecs.toAwsCredentialsProvider 8 | import jetbrains.buildServer.controllers.BaseController 9 | import jetbrains.buildServer.controllers.BasePropertiesBean 10 | import jetbrains.buildServer.internal.PluginPropertiesUtil 11 | import jetbrains.buildServer.util.amazon.AWSCommonParams 12 | import jetbrains.buildServer.web.openapi.PluginDescriptor 13 | import jetbrains.buildServer.web.openapi.WebControllerManager 14 | import org.springframework.web.servlet.ModelAndView 15 | import javax.servlet.http.HttpServletRequest 16 | import javax.servlet.http.HttpServletResponse 17 | 18 | private const val ECS_CLUSTERS_HTML = "ecsClusters.html" 19 | 20 | class EcsClusterChooserController(private val pluginDescriptor: PluginDescriptor, 21 | web: WebControllerManager) : BaseController() { 22 | val url = pluginDescriptor.getPluginResourcesPath(ECS_CLUSTERS_HTML) 23 | 24 | init { 25 | web.registerController(url, this) 26 | } 27 | 28 | override fun doHandle(request: HttpServletRequest, response: HttpServletResponse): ModelAndView? { 29 | val propsBean = BasePropertiesBean(null) 30 | PluginPropertiesUtil.bindPropertiesFromRequest(request, propsBean, true) 31 | val props = propsBean.properties 32 | 33 | val modelAndView = ModelAndView(pluginDescriptor.getPluginResourcesPath("clusters.jsp")) 34 | try { 35 | val api = EcsApiConnectorImpl(props.toAwsCredentialsProvider(), AWSCommonParams.getRegionName(props)) 36 | modelAndView.model["clusters"] = api.listClusters() 37 | .mapNotNull { clusterArn -> api.describeCluster(clusterArn) } 38 | .sortedBy { cluster -> cluster.name } 39 | modelAndView.model["error"] = "" 40 | } catch (ex: Exception){ 41 | modelAndView.model["clusters"] = emptyList() 42 | modelAndView.model["error"] = ex.localizedMessage 43 | } 44 | return modelAndView 45 | } 46 | } -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/web/EcsDeleteImageDialogController.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs.web 4 | 5 | import jetbrains.buildServer.clouds.server.CloudManagerBase 6 | import jetbrains.buildServer.controllers.BaseController 7 | import jetbrains.buildServer.util.StringUtil 8 | import jetbrains.buildServer.web.openapi.PluginDescriptor 9 | import jetbrains.buildServer.web.openapi.WebControllerManager 10 | import org.springframework.web.servlet.ModelAndView 11 | import javax.servlet.http.HttpServletRequest 12 | import javax.servlet.http.HttpServletResponse 13 | 14 | /** 15 | * Created by Evgeniy Koshkin (evgeniy.koshkin@jetbrains.com) on 12.10.17. 16 | */ 17 | class EcsDeleteImageDialogController(web: WebControllerManager, 18 | private val pluginDescriptor: PluginDescriptor, 19 | private val cloudManager: CloudManagerBase) : BaseController() { 20 | val url: String 21 | get() = pluginDescriptor.getPluginResourcesPath(URL) 22 | 23 | init { 24 | web.registerController(url, this) 25 | } 26 | 27 | @Throws(Exception::class) 28 | override fun doHandle(httpServletRequest: HttpServletRequest, httpServletResponse: HttpServletResponse): ModelAndView? { 29 | val projectId = httpServletRequest.getParameter("projectId") 30 | val profileId = httpServletRequest.getParameter("profileId") 31 | val imageId = httpServletRequest.getParameter("imageId") 32 | if (StringUtil.isEmpty(imageId)) return null 33 | 34 | val client = cloudManager.getClientIfExistsByProjectExtId(projectId, profileId) 35 | val image = client.findImageById(imageId) 36 | 37 | if (BaseController.isGet(httpServletRequest)) { 38 | val modelAndView = ModelAndView(pluginDescriptor.getPluginResourcesPath("deleteImageDialog.jsp")) 39 | modelAndView.modelMap.put("instances", if (image == null) emptyList() else image.instances) 40 | return modelAndView 41 | } else if (isPost(httpServletRequest) && image != null) { 42 | for (instance in image.instances) { 43 | client.terminateInstance(instance) 44 | } 45 | } 46 | return null 47 | } 48 | 49 | companion object { 50 | val URL = "deleteKubeImage.html" 51 | } 52 | } -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/internal/PluginPropertiesUtil.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.internal 4 | 5 | import jetbrains.buildServer.controllers.BasePropertiesBean 6 | import jetbrains.buildServer.serverSide.crypt.RSACipher 7 | 8 | import javax.servlet.http.HttpServletRequest 9 | 10 | //NOTE: copy pasted from PluginPropertiesUtil 11 | object PluginPropertiesUtil { 12 | private val PROPERTY_PREFIX = "prop:" 13 | private val ENCRYPTED_PROPERTY_PREFIX = "prop:encrypted:" 14 | 15 | @JvmOverloads 16 | fun bindPropertiesFromRequest(request: HttpServletRequest, bean: BasePropertiesBean, includeEmptyValues: Boolean = false) { 17 | bean.clearProperties() 18 | 19 | for (o in request.parameterMap.keys) { 20 | val paramName = o as String 21 | if (paramName.startsWith(PROPERTY_PREFIX)) { 22 | if (paramName.startsWith(ENCRYPTED_PROPERTY_PREFIX)) { 23 | setEncryptedProperty(paramName, request, bean, includeEmptyValues) 24 | } else { 25 | setStringProperty(paramName, request, bean, includeEmptyValues) 26 | } 27 | } 28 | } 29 | } 30 | 31 | private fun setStringProperty(paramName: String, request: HttpServletRequest, 32 | bean: BasePropertiesBean, includeEmptyValues: Boolean) { 33 | val propName = paramName.substring(PROPERTY_PREFIX.length) 34 | val propertyValue = request.getParameter(paramName).trim { it <= ' ' } 35 | if (includeEmptyValues || propertyValue.length > 0) { 36 | bean.setProperty(propName, toUnixLineFeeds(propertyValue)) 37 | } 38 | } 39 | 40 | private fun setEncryptedProperty(paramName: String, request: HttpServletRequest, 41 | bean: BasePropertiesBean, includeEmptyValues: Boolean) { 42 | val propName = paramName.substring(ENCRYPTED_PROPERTY_PREFIX.length) 43 | val propertyValue = RSACipher.decryptWebRequestData(request.getParameter(paramName)) 44 | if (propertyValue != null && (includeEmptyValues || propertyValue.length > 0)) { 45 | bean.setProperty(propName, toUnixLineFeeds(propertyValue)) 46 | } 47 | } 48 | 49 | private fun toUnixLineFeeds(str: String): String { 50 | return str.replace("\r", "") 51 | } 52 | } -------------------------------------------------------------------------------- /infra/main.tf: -------------------------------------------------------------------------------- 1 | module "iam" { 2 | source = "modules/iam" 3 | aws_region = "${data.aws_region.current.name}" 4 | project_name = "${var.project_name}" 5 | stack_name = "${var.stack_name}" 6 | } 7 | 8 | data "aws_region" "current" { 9 | current = true 10 | } 11 | 12 | data "aws_vpc" "vpc" { 13 | id = "${var.vpc_id}" 14 | } 15 | 16 | data "aws_subnet_ids" "vpc" { 17 | vpc_id = "${data.aws_vpc.vpc.id}" 18 | } 19 | 20 | module "ec2" { 21 | source = "modules/ec2" 22 | project_name = "${var.project_name}" 23 | stack_name = "${var.stack_name}" 24 | instance_type = "${var.instance_type}" 25 | asg_min_size = "${var.asg_min_size}" 26 | asg_max_size = "${var.asg_max_size}" 27 | ec2_keypair_name = "${var.ec2_keypair_name}" 28 | ec2_volume_size = "${var.ec2_volume_size}" 29 | docker_basesize = "${var.agent_disk}" 30 | instance_profile_arn = "${module.iam.instance_profile_arn}" 31 | iam_role_sns_lambda_arn = "${module.iam.iam_role_sns_lambda_arn}" 32 | vpc_zone_identifier = "${data.aws_subnet_ids.vpc.ids}" 33 | } 34 | 35 | module "lambda" { 36 | source = "modules/lambda" 37 | project_name = "${var.project_name}" 38 | stack_name = "${var.stack_name}" 39 | asg_name = "${module.ec2.asg_name}" 40 | asg_min_size = "${module.ec2.asg_min_size}" 41 | ecs_cluster_id = "${module.ecs.ecs_cluster_id}" 42 | ecs_cluster_name = "${module.ecs.ecs_cluster_name}" 43 | sns_topic_asg_arn = "${module.ec2.sns_topic_asg_arn}" 44 | iam_role_sns_lambda_arn = "${module.iam.iam_role_sns_lambda_arn}" 45 | iam_role_lambda_ecs_asg_arn = "${module.iam.iam_role_lambda_ecs_asg_arn}" 46 | iam_role_lambda_ecs_unprotect_asg_arn = "${module.iam.iam_role_lambda_ecs_unprotect_asg_arn}" 47 | } 48 | 49 | module "ecs" { 50 | source = "modules/ecs" 51 | aws_region = "${data.aws_region.current.name}" 52 | project_name = "${var.project_name}" 53 | stack_name = "${var.stack_name}" 54 | ecs_task_cpu = "${var.agent_cpu}" 55 | ecs_task_memory = "${var.agent_mem}" 56 | app_image = "${var.app_image}" 57 | app_version = "${var.app_version}" 58 | } 59 | -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/EcsCloudImageData.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs 4 | 5 | import com.amazonaws.services.ecs.model.LaunchType 6 | import jetbrains.buildServer.clouds.CloudImageParameters 7 | import jetbrains.buildServer.clouds.ecs.apiConnector.EcsApiConnector 8 | import jetbrains.buildServer.util.StringUtil 9 | import java.io.File 10 | 11 | fun EcsCloudImageData.toImage(apiConnector: EcsApiConnector, 12 | serverUUID: String, 13 | idxStorage: File, 14 | profileId: String): EcsCloudImage 15 | = EcsCloudImageImpl(this, apiConnector, serverUUID, idxStorage, profileId) 16 | 17 | class EcsCloudImageData(private val rawImageData: CloudImageParameters) { 18 | val id: String = rawImageData.id!! 19 | val agentPoolId: Int? = rawImageData.agentPoolId 20 | val taskGroup: String? = rawImageData.getParameter(TASK_GROUP_PARAM) 21 | val subnets: String? = rawImageData.getParameter(SUBNETS_PARAM) 22 | val securityGroups: String? = rawImageData.getParameter(SECURITY_GROUPS_PARAM) 23 | val cluster: String? = rawImageData.getParameter(CLUSTER_PARAM) 24 | val taskDefinition: String = rawImageData.getParameter(TASK_DEFINITION_PARAM)!! 25 | val fargatePlatformVersion: String? = rawImageData.getParameter(FARGATE_PLATFORM_VERSION) 26 | 27 | val launchType: String? 28 | get() { 29 | val parameter = rawImageData.getParameter(LAUNCH_TYPE_PARAM) 30 | return if(parameter.isNullOrEmpty()) null else parameter 31 | } 32 | 33 | val instanceLimit: Int 34 | get() { 35 | val parameter = rawImageData.getParameter(IMAGE_INSTANCE_LIMIT_PARAM) 36 | return if (StringUtil.isEmpty(parameter)) -1 else Integer.valueOf(parameter) 37 | } 38 | 39 | val cpuReservalionLimit: Int 40 | get() { 41 | val parameter = rawImageData.getParameter(CPU_RESERVATION_LIMIT_PARAM) 42 | return if (StringUtil.isEmpty(parameter)) -1 else Integer.valueOf(parameter) 43 | } 44 | 45 | val agentNamePrefix: String 46 | get() { 47 | val prefix = rawImageData.getParameter(AGENT_NAME_PREFIX) 48 | if(prefix == null || prefix.isEmpty()) return "ecs:" 49 | else return prefix 50 | } 51 | 52 | val assignPublicIp: Boolean 53 | get() = rawImageData.getParameter(ASSIGN_PUBLIC_IP_PARAM)?.toBoolean() ?: false 54 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/web/EcsTaskDefinitionChooserController.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs.web 4 | 5 | import jetbrains.buildServer.clouds.ecs.apiConnector.EcsApiConnectorImpl 6 | import jetbrains.buildServer.clouds.ecs.apiConnector.EcsTaskDefinition 7 | import jetbrains.buildServer.clouds.ecs.toAwsCredentialsProvider 8 | import jetbrains.buildServer.controllers.BaseController 9 | import jetbrains.buildServer.controllers.BasePropertiesBean 10 | import jetbrains.buildServer.internal.PluginPropertiesUtil 11 | import jetbrains.buildServer.util.amazon.AWSCommonParams 12 | import jetbrains.buildServer.web.openapi.PluginDescriptor 13 | import jetbrains.buildServer.web.openapi.WebControllerManager 14 | import org.springframework.web.servlet.ModelAndView 15 | import javax.servlet.http.HttpServletRequest 16 | import javax.servlet.http.HttpServletResponse 17 | 18 | private const val ECS_TASK_DEFS_HTML = "ecsTaskDefs.html" 19 | 20 | class EcsTaskDefinitionChooserController(private val pluginDescriptor: PluginDescriptor, 21 | web: WebControllerManager) : BaseController() { 22 | val url = pluginDescriptor.getPluginResourcesPath(ECS_TASK_DEFS_HTML) 23 | 24 | init { 25 | web.registerController(url, this) 26 | } 27 | 28 | override fun doHandle(request: HttpServletRequest, response: HttpServletResponse): ModelAndView? { 29 | val launchType = request.getParameter("launchType") 30 | val propsBean = BasePropertiesBean(null) 31 | PluginPropertiesUtil.bindPropertiesFromRequest(request, propsBean, true) 32 | val props = propsBean.properties 33 | 34 | val modelAndView = ModelAndView(pluginDescriptor.getPluginResourcesPath("taskDefs.jsp")) 35 | try { 36 | val api = EcsApiConnectorImpl(props.toAwsCredentialsProvider(), AWSCommonParams.getRegionName(props)) 37 | val sortedTasDefs = api.listTaskDefinitions() 38 | .mapNotNull { taskDefArn -> api.describeTaskDefinition(taskDefArn) } 39 | .filter { taskDef -> taskDef.isCompatibleWithLaunchType(launchType) } 40 | .sortedBy { taskDef -> taskDef.displayName } 41 | modelAndView.model["taskDefs"] = sortedTasDefs 42 | modelAndView.model["error"] = "" 43 | } catch (ex: Exception){ 44 | modelAndView.model["taskDefs"] = emptyList() 45 | modelAndView.model["error"] = ex.localizedMessage 46 | } 47 | return modelAndView 48 | } 49 | } -------------------------------------------------------------------------------- /aws-ecs-server/src/main/resources/buildServerResources/ecs.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Icon-Architecture/64/Arch_Amazon-Elastic-Container-Service_64 5 | Created with Sketch. 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TeamCity Amazon ECS plugin 2 | [![official JetBrains project](https://jb.gg/badges/official.svg)](https://plugins.jetbrains.com/plugin/10067-amazon-ecs-support) 3 | [![plugin status]( 4 | https://teamcity.jetbrains.com/app/rest/builds/buildType:(id:TestDrive_TeamCityAmazonEcsPlugin_Build)/statusIcon.svg)](https://teamcity.jetbrains.com/viewType.html?buildTypeId=TestDrive_TeamCityAmazonEcsPlugin_Build&guest=1) 5 | 6 | TeamCity plugin which allows running build agents on an AWS ECS cluster. 7 | 8 | ## Compatibility 9 | 10 | The plugin is compatible with TeamCity 2017.1.x and later. 11 | 12 | ## Installation 13 | 14 | You can [download the plugin](https://teamcity.jetbrains.com/guestAuth/app/rest/builds/buildType:TestDrive_TeamCityAmazonEcsPlugin_Build,tags:release/artifacts/content/aws-ecs.zip) and install it as an [additional TeamCity plugin](https://confluence.jetbrains.com/display/TCDL/Installing+Additional+Plugins). 15 | 16 | ## Plugin Configuration 17 | 18 | Configure Amazon ECS [Cloud Profile](https://confluence.jetbrains.com/display/TCD10/Agent+Cloud+Profile#AgentCloudProfile-ConfiguringCloudProfile) for your project in the Server Administration UI. 19 | 20 | The plugin supports Amazon ECS cluster images to start new tasks with a TeamCity build agent running in one of the containers. The plugin supports the [official TeamCity Build Agent Docker image](https://hub.docker.com/r/jetbrains/teamcity-agent) out of the box. You can use your own image as well. 21 | 22 | ### Limit Cluster Resources Usage 23 | 24 | Specify ECS cloud image advanced setting 'Max cluster CPU reservation' to stop creating new TeamCity cloud instances when cluster is overloaded. This requires additional permission granted to AWS user: cloudwatch:GetMetricStatistics 25 | 26 | ### Proxy Settings 27 | 28 | Use [global server proxy settings](https://confluence.jetbrains.com/pages/viewpage.action?pageId=74845225#HowTo...-ConfigureTeamCitytoUseProxyServerforOutgoingConnections). 29 | 30 | Or set plugin specific [internal properties](https://confluence.jetbrains.com/display/TCD10/Configuring+TeamCity+Server+Startup+Properties#ConfiguringTeamCityServerStartupProperties-TeamCityinternalproperties) 31 | - teamcity.ecs.https.proxyHost 32 | - teamcity.ecs.https.proxyPort 33 | - teamcity.ecs.https.proxyLogin 34 | - teamcity.ecs.https.proxyPassword 35 | 36 | 37 | ## Required IAM Role 38 | 39 | Allow following actions to AIM role you use in cloud profile. 40 | - ecs:DescribeClusters 41 | - ecs:DescribeTaskDefinition 42 | - ecs:DescribeTasks 43 | - ecs:ListClusters 44 | - ecs:ListTaskDefinitions 45 | - ecs:ListTasks 46 | - ecs:RunTask 47 | - ecs:StopTask 48 | - (optional) cloudwatch:GetMetricStatistics 49 | 50 | ## ECS Cluster Setup 51 | 52 | Optionaly use [provided Terraform template](infra/README.md) to setup ECS cluster. 53 | 54 | ## License 55 | 56 | Apache 2.0 57 | 58 | ## Feedback 59 | 60 | Please feel free to post feedback in the repository [issues](https://youtrack.jetbrains.com/issues/TW). 61 | -------------------------------------------------------------------------------- /infra/modules/lambda/ecs-unprotect-lambda/index.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import boto3 3 | import logging 4 | import os 5 | 6 | logging.basicConfig() 7 | logger = logging.getLogger() 8 | logger.setLevel(logging.INFO) 9 | 10 | # Establish boto3 session 11 | session = boto3.session.Session() 12 | logger.debug("Session is in region %s ", session.region_name) 13 | 14 | ecsClient = session.client(service_name='ecs') 15 | asgClient = session.client('autoscaling') 16 | 17 | clusterName = os.getenv('ECS_CLUSTER_NAME', 'teamcity-sandbox') 18 | asgGroupName = os.getenv('ASG_GROUP_NAME', 'teamcity-sandbox-ecs-asg') 19 | 20 | def env_to_num(env, default): 21 | try: 22 | return int(os.getenv(env, default)) 23 | except ValueError: 24 | return default 25 | retainInstances = env_to_num('RETAIN_INSTANCES',0) 26 | 27 | def lambda_handler(event, context): 28 | logger.info("Start lambda function") 29 | 30 | # Get list of container instance IDs from the clusterName 31 | clusterListResp = ecsClient.list_container_instances(cluster=clusterName) 32 | 33 | # Get list of describe container instances from the clusterName 34 | descrInsts = ecsClient.describe_container_instances( 35 | cluster=clusterName, 36 | containerInstances=clusterListResp['containerInstanceArns'], 37 | ) 38 | 39 | # Get ARN list of instances without any tasks 40 | idleInstances = [] 41 | for containerInstance in descrInsts['containerInstances']: 42 | runTask = containerInstance['runningTasksCount'] 43 | pendTask = containerInstance['pendingTasksCount'] 44 | ec2InstanceId = containerInstance['ec2InstanceId'] 45 | status = containerInstance['status'] 46 | logger.debug("Instance %s has %s tasks" , ec2InstanceId, runTask + pendTask) 47 | if status == 'ACTIVE' and runTask + pendTask == 0: 48 | idleInstances.append(containerInstance) 49 | logger.info("Cluster %s has %s idle instances", clusterName, len(idleInstances)) 50 | 51 | # Save idle instance 52 | idleInstances = idleInstances[retainInstances:] 53 | 54 | # Delete instance protection for autoscaling group 55 | for containerInstance in idleInstances: 56 | logger.info("Unprotect instances %s", containerInstance['ec2InstanceId']) 57 | # Make API calls to set DRAINING and unset ScaleIn protection 58 | try: 59 | response = ecsClient.update_container_instances_state( 60 | cluster=clusterName, 61 | containerInstances=[containerInstance['containerInstanceArn']], 62 | status='DRAINING' 63 | ) 64 | logger.debug("Response received from update_container_instances_state %s",response) 65 | response = asgClient.set_instance_protection( 66 | InstanceIds=[containerInstance['ec2InstanceId']], 67 | AutoScalingGroupName=asgGroupName, 68 | ProtectedFromScaleIn=False 69 | ) 70 | logger.debug("Response received from set_instance_protection %s",response) 71 | except Exception, e: 72 | logger.error(str(e)) 73 | -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/EcsCloudInstanceImpl.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs 4 | 5 | import com.intellij.openapi.diagnostic.Logger 6 | import jetbrains.buildServer.agent.Constants 7 | import jetbrains.buildServer.clouds.CloudErrorInfo 8 | import jetbrains.buildServer.clouds.CloudImage 9 | import jetbrains.buildServer.clouds.InstanceStatus 10 | import jetbrains.buildServer.clouds.ecs.apiConnector.EcsApiConnector 11 | import jetbrains.buildServer.clouds.ecs.apiConnector.EcsTask 12 | import jetbrains.buildServer.serverSide.AgentDescription 13 | import java.util.* 14 | 15 | class EcsCloudInstanceImpl(private val instanceId: String, val cloudImage: EcsCloudImage, val ecsTask: EcsTask, val apiConnector: EcsApiConnector) : EcsCloudInstance { 16 | private val LOG = Logger.getInstance(EcsCloudInstanceImpl::class.java.getName()) 17 | private var myCurrentError: CloudErrorInfo? = null 18 | private var myTask: EcsTask = ecsTask 19 | 20 | override fun getStatus(): InstanceStatus { 21 | val lastStatus = myTask.lastStatus 22 | when (myTask.desiredStatus) { 23 | "RUNNING" -> { 24 | when(lastStatus){ 25 | "PENDING" -> return InstanceStatus.STARTING 26 | "RUNNING" -> return InstanceStatus.RUNNING 27 | else -> return InstanceStatus.RUNNING 28 | } 29 | } 30 | "STOPPED" -> { 31 | when(lastStatus){ 32 | "RUNNING" -> return InstanceStatus.STOPPING 33 | "PENDING" -> return InstanceStatus.STOPPED 34 | "STOPPED" -> return InstanceStatus.STOPPED 35 | else -> return InstanceStatus.STOPPED 36 | } 37 | } 38 | else -> return InstanceStatus.UNKNOWN 39 | } 40 | } 41 | 42 | override fun getInstanceId(): String { 43 | return instanceId 44 | } 45 | 46 | override fun getName(): String { 47 | return ecsTask.id 48 | } 49 | 50 | override fun getStartedTime(): Date { 51 | val startedAt = ecsTask.startedAt 52 | when { 53 | startedAt != null -> return startedAt 54 | else -> return ecsTask.cratedAt 55 | } 56 | } 57 | 58 | override fun getNetworkIdentity(): String? { 59 | //TODO: provide identity 60 | return null 61 | } 62 | 63 | override fun getImage(): CloudImage { 64 | return cloudImage 65 | } 66 | 67 | override fun getImageId(): String { 68 | return cloudImage.id 69 | } 70 | 71 | override fun getErrorInfo(): CloudErrorInfo? { 72 | return myCurrentError 73 | } 74 | 75 | override fun containsAgent(agent: AgentDescription): Boolean { 76 | if (agent.configurationParameters[REQUIRED_PROFILE_ID_CONFIG_PARAM] == null) 77 | return false 78 | 79 | return instanceId == agent.configurationParameters[Constants.ENV_PREFIX + INSTANCE_ID_ECS_ENV] 80 | } 81 | 82 | override fun terminate() { 83 | try{ 84 | apiConnector.stopTask(ecsTask.arn, ecsTask.clusterArn, "Terminated by TeamCity server") 85 | myCurrentError = null 86 | } catch (ex:Exception){ 87 | val msg = "Failed to stop cloud instance with id $instanceId" 88 | LOG.warnAndDebugDetails(msg, ex) 89 | myCurrentError = CloudErrorInfo(msg) 90 | } 91 | cloudImage.populateInstances() 92 | } 93 | 94 | override fun update(task: EcsTask) { 95 | LOG.debug("Updating task '${task.id}:${task.arn}', status: ${task.lastStatus} -> ${task.desiredStatus}") 96 | myTask = task 97 | } 98 | } -------------------------------------------------------------------------------- /infra/modules/lambda/main.tf: -------------------------------------------------------------------------------- 1 | ######### 2 | # Lambda 3 | ######### 4 | 5 | data "archive_file" "ecs-scaledown-file" { 6 | source_file = "${path.module}/ecs-scaledown-lambda/index.py" 7 | output_path = "ecs-scaledown-lambda.zip" 8 | type = "zip" 9 | } 10 | 11 | resource "aws_lambda_function" "ecs-asg" { 12 | function_name = "${var.project_name}-${var.stack_name}-ecs-asg" 13 | role = "${var.iam_role_lambda_ecs_asg_arn}" 14 | handler = "index.lambda_handler" 15 | runtime = "python2.7" 16 | timeout = 300 17 | filename = "${data.archive_file.ecs-scaledown-file.output_path}" 18 | source_code_hash = "${data.archive_file.ecs-scaledown-file.output_base64sha256}" 19 | } 20 | 21 | resource "aws_lambda_permission" "allow_sns" { 22 | statement_id = "AllowExecutionFromSNS" 23 | action = "lambda:InvokeFunction" 24 | function_name = "${aws_lambda_function.ecs-asg.function_name}" 25 | principal = "sns.amazonaws.com" 26 | source_arn = "${var.sns_topic_asg_arn}" 27 | } 28 | 29 | resource "aws_sns_topic_subscription" "lambda-sns" { 30 | topic_arn = "${var.sns_topic_asg_arn}" 31 | protocol = "lambda" 32 | endpoint = "${aws_lambda_function.ecs-asg.arn}" 33 | } 34 | 35 | resource "aws_cloudwatch_log_group" "ecs-asg" { 36 | name = "/aws/lambda/${var.project_name}-${var.stack_name}-ecs-asg" 37 | retention_in_days = "${var.log_retention}" 38 | } 39 | 40 | data "archive_file" "ecs-unprotect-file" { 41 | source_file = "${path.module}/ecs-unprotect-lambda/index.py" 42 | output_path = "ecs-unprotect-lambda.zip" 43 | type = "zip" 44 | } 45 | 46 | resource "aws_lambda_function" "ecs-asg-unprotect" { 47 | function_name = "${var.project_name}-${var.stack_name}-ecs-unprotect-asg" 48 | role = "${var.iam_role_lambda_ecs_unprotect_asg_arn}" 49 | handler = "index.lambda_handler" 50 | runtime = "python2.7" 51 | timeout = 300 52 | filename = "${data.archive_file.ecs-unprotect-file.output_path}" 53 | source_code_hash = "${data.archive_file.ecs-unprotect-file.output_base64sha256}" 54 | 55 | environment { 56 | variables = { 57 | ECS_CLUSTER_NAME = "${var.ecs_cluster_name}" 58 | ASG_GROUP_NAME = "${var.asg_name}" 59 | RETAIN_INSTANCES = "${var.asg_min_size}" 60 | } 61 | } 62 | } 63 | 64 | resource "aws_cloudwatch_event_rule" "unprotect-scheduler" { 65 | name = "${var.project_name}-${var.stack_name}-unprotect-scheduler" 66 | 67 | event_pattern = < 36) 18 | return string.substring(0, 36) 19 | else 20 | return string 21 | } 22 | 23 | /** 24 | * Created by Evgeniy Koshkin (evgeniy.koshkin@jetbrains.com) on 05.07.17. 25 | */ 26 | class EcsCloudClientFactory(cloudRegister: CloudRegistrar, 27 | private val pluginDescriptor: PluginDescriptor, 28 | serverPaths: ServerPaths, 29 | private val serverSettings: ServerSettings, 30 | private val instanceUpdater: EcsInstancesUpdater) : CloudClientFactory { 31 | private val editUrl = pluginDescriptor.getPluginResourcesPath(EDIT_ECS_HTML) 32 | private val idxStorage = File(serverPaths.pluginDataDirectory, "ecsCloudIdx") 33 | 34 | init { 35 | cloudRegister.registerCloudFactory(this) 36 | if (!idxStorage.exists()){ 37 | idxStorage.mkdirs() 38 | } 39 | } 40 | 41 | override fun getCloudCode(): String { 42 | return "awsecs" 43 | } 44 | 45 | override fun getDisplayName(): String { 46 | return "Amazon Elastic Container Service" 47 | } 48 | 49 | override fun getEditProfileUrl(): String? { 50 | return editUrl 51 | } 52 | 53 | override fun getTypeDescription(): String = """ 54 | Agents are linux containers running in AWS ECS cluster. Provides a high availability of agents. Doesn't support Docker containers nor Docker compose 55 | """.trimIndent() 56 | 57 | override fun getProfileIconUrl(): String = pluginDescriptor.getPluginResourcesPath("ecs.svg") 58 | 59 | override fun canBeAgentOfType(description: AgentDescription): Boolean { 60 | val map = description.availableParameters 61 | return map.containsKey(Constants.ENV_PREFIX + SERVER_UUID_ECS_ENV) && 62 | map.containsKey(Constants.ENV_PREFIX + PROFILE_ID_ECS_ENV) && 63 | map.containsKey(Constants.ENV_PREFIX + IMAGE_ID_ECS_ENV) && 64 | map.containsKey(Constants.ENV_PREFIX + INSTANCE_ID_ECS_ENV) 65 | } 66 | 67 | override fun createNewClient(state: CloudState, params: CloudClientParameters): CloudClientEx { 68 | val ecsParams = params.toEcsParams() 69 | val apiConnector = EcsApiConnectorImpl(ecsParams.awsCredentialsProvider, ecsParams.region) 70 | val serverUUID = serverSettings.serverUUID!! 71 | val images = ecsParams.imagesData.map{ 72 | val image = it.toImage(apiConnector, serverUUID, idxStorage, state.profileId) 73 | image.populateInstances() 74 | image 75 | } 76 | return EcsCloudClient(images, instanceUpdater, ecsParams, serverUUID, idxStorage, state.profileId) 77 | } 78 | 79 | override fun getInitialParameterValues(): MutableMap { 80 | val result = HashMap() 81 | result.putAll(AWSCommonParams.getDefaults(serverSettings.serverUUID)) 82 | return result 83 | } 84 | 85 | override fun getPropertiesProcessor(): PropertiesProcessor { 86 | return PropertiesProcessor { properties -> 87 | val invalids = ArrayList() 88 | for (e in AWSCommonParams.validate(properties!!, false)) { 89 | invalids.add(InvalidProperty(e.key, e.value)) 90 | } 91 | invalids 92 | } 93 | } 94 | } -------------------------------------------------------------------------------- /aws-ecs-agent/src/main/kotlin/jetbrains/buildServer/clouds/ecs/EcsAgentConfigurationProvider.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs 4 | 5 | import jetbrains.buildServer.agent.AgentLifeCycleAdapter 6 | import jetbrains.buildServer.agent.AgentLifeCycleListener 7 | import jetbrains.buildServer.agent.BuildAgent 8 | import jetbrains.buildServer.agent.BuildAgentConfigurationEx 9 | import jetbrains.buildServer.http.HttpUtil 10 | import jetbrains.buildServer.util.EventDispatcher 11 | import jetbrains.buildServer.util.StringUtil 12 | import org.apache.commons.httpclient.HttpStatus 13 | import org.apache.commons.httpclient.methods.GetMethod 14 | import org.json.JSONObject 15 | import java.io.File 16 | import java.lang.RuntimeException 17 | 18 | /** 19 | * Created by Evgeniy Koshkin (evgeniy.koshkin@jetbrains.com) on 20.09.17. 20 | */ 21 | class EcsAgentConfigurationProvider(agentEvents: EventDispatcher, 22 | private val agentConfigurationEx: BuildAgentConfigurationEx) { 23 | private val REGEX = Regex("arn:aws:ecs:[^:]+:\\d+:task\\/(.+)") 24 | 25 | init { 26 | agentEvents.addListener(object : AgentLifeCycleAdapter() { 27 | override fun afterAgentConfigurationLoaded(agent: BuildAgent) { 28 | super.afterAgentConfigurationLoaded(agent) 29 | appendEcsSpecificConfiguration() 30 | } 31 | }) 32 | } 33 | 34 | private fun readMetaDatFromUrl(metaDataUrl: String): String?{ 35 | val client = HttpUtil.createHttpClient(5) 36 | // val uri = "http://169.254.170.2/v2/metadata" 37 | val get = GetMethod(metaDataUrl + "/task") 38 | try { 39 | client.executeMethod(get) 40 | if (get.statusCode != HttpStatus.SC_OK) { 41 | throw RuntimeException("Server returned [" + get.statusCode + "] " + get.statusText + " for " + metaDataUrl) 42 | } 43 | val response = get.responseBodyAsString 44 | val obj = JSONObject(response) 45 | val taskArn = obj.getString("TaskARN") 46 | val find = REGEX.find(taskArn) 47 | return find?.groups?.get(1)?.value 48 | } finally { 49 | get.releaseConnection() 50 | } 51 | } 52 | 53 | private fun readMetaDataFile(metadataFilePath: String): String? { 54 | val obj = JSONObject(File(metadataFilePath).readText()) 55 | val taskArn = obj.getString("TaskARN") 56 | val find = REGEX.find(taskArn) 57 | return find?.groups?.get(1)?.value 58 | } 59 | 60 | private fun appendEcsSpecificConfiguration() { 61 | val environment = System.getenv() 62 | val providedServerUrl = environment[SERVER_URL_ECS_ENV] 63 | if (!StringUtil.isEmpty(providedServerUrl)) agentConfigurationEx.serverUrl = providedServerUrl 64 | 65 | val profileId = environment[PROFILE_ID_ECS_ENV] 66 | if (!StringUtil.isEmpty(profileId)) agentConfigurationEx.addConfigurationParameter(REQUIRED_PROFILE_ID_CONFIG_PARAM, profileId!!) 67 | if (environment[AGENT_NAME_ECS_ENV] != null) { 68 | agentConfigurationEx.name = environment[AGENT_NAME_ECS_ENV] 69 | } else if (environment[ECS_CONTAINER_METADATA_URI] != null){ 70 | val data = readMetaDatFromUrl(environment[ECS_CONTAINER_METADATA_URI]!!) 71 | if (data != null) { 72 | agentConfigurationEx.name = data 73 | } 74 | } else if (environment[ECS_CONTAINER_METADATA_FILE] != null) { 75 | val data = readMetaDataFile(environment[ECS_CONTAINER_METADATA_FILE]!!) 76 | if (data != null) { 77 | agentConfigurationEx.name = data 78 | } 79 | } 80 | 81 | if (environment[STARTING_INSTANCE_ID_ECS_ENV] != null) { 82 | agentConfigurationEx.addConfigurationParameter(STARTING_INSTANCE_ID_CONFIG_PARAM, environment[STARTING_INSTANCE_ID_ECS_ENV].toString()); 83 | } 84 | 85 | environment.entries.forEach { entry -> 86 | val key = entry.key 87 | val value = entry.value 88 | if (key.startsWith(TEAMCITY_ECS_PROVIDED_PREFIX)){ 89 | agentConfigurationEx.addConfigurationParameter(key.removePrefix(TEAMCITY_ECS_PROVIDED_PREFIX), value) 90 | } 91 | } 92 | } 93 | } -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/web/EcsProfileEditController.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs.web 4 | 5 | import com.amazonaws.services.ecs.model.LaunchType 6 | import com.intellij.openapi.diagnostic.Logger 7 | import jetbrains.buildServer.BuildProject 8 | import jetbrains.buildServer.clouds.ecs.EcsParameterConstants 9 | import jetbrains.buildServer.clouds.ecs.apiConnector.EcsApiConnectorImpl 10 | import jetbrains.buildServer.clouds.ecs.toAwsCredentialsProvider 11 | import jetbrains.buildServer.controllers.ActionErrors 12 | import jetbrains.buildServer.controllers.BaseFormXmlController 13 | import jetbrains.buildServer.controllers.BasePropertiesBean 14 | import jetbrains.buildServer.internal.PluginPropertiesUtil 15 | import jetbrains.buildServer.serverSide.agentPools.AgentPool 16 | import jetbrains.buildServer.serverSide.agentPools.AgentPoolManager 17 | import jetbrains.buildServer.serverSide.agentPools.AgentPoolUtil 18 | import jetbrains.buildServer.util.amazon.AWSCommonParams 19 | import jetbrains.buildServer.web.openapi.PluginDescriptor 20 | import jetbrains.buildServer.web.openapi.WebControllerManager 21 | import org.jdom.Element 22 | import org.springframework.web.servlet.ModelAndView 23 | import javax.servlet.http.HttpServletRequest 24 | import javax.servlet.http.HttpServletResponse 25 | 26 | const val EDIT_ECS_HTML = "editEcs.html" 27 | 28 | class EcsProfileEditController(val pluginDescriptor: PluginDescriptor, 29 | val agentPoolManager: AgentPoolManager, 30 | web: WebControllerManager, 31 | private val taskDefsController: EcsTaskDefinitionChooserController, 32 | private val clustersController: EcsClusterChooserController, 33 | private val deleteImageDialogController: EcsDeleteImageDialogController) : BaseFormXmlController() { 34 | private val LOG = Logger.getInstance(EcsProfileEditController::class.java.getName()) 35 | private val url = pluginDescriptor.getPluginResourcesPath(EDIT_ECS_HTML) 36 | 37 | init { 38 | web.registerController(url, this) 39 | } 40 | 41 | override fun doPost(request: HttpServletRequest, response: HttpServletResponse, xmlResponse: Element) { 42 | if (request.getParameter("testConnection").toBoolean()){ 43 | val propsBean = BasePropertiesBean(null) 44 | PluginPropertiesUtil.bindPropertiesFromRequest(request, propsBean, true) 45 | val props = propsBean.properties 46 | try { 47 | val api = EcsApiConnectorImpl(props.toAwsCredentialsProvider(), AWSCommonParams.getRegionName(props)) 48 | val testConnectionResult = api.testConnection() 49 | if (!testConnectionResult.success) { 50 | val errors = ActionErrors() 51 | errors.addError("connection", testConnectionResult.message) 52 | writeErrors(xmlResponse, errors) 53 | } 54 | } catch (ex: Exception){ 55 | LOG.debug(ex) 56 | val errors = ActionErrors() 57 | errors.addError("connection", ex.message) 58 | writeErrors(xmlResponse, errors) 59 | } 60 | } 61 | } 62 | 63 | override fun doGet(request: HttpServletRequest, response: HttpServletResponse): ModelAndView { 64 | val mv = ModelAndView(pluginDescriptor.getPluginResourcesPath("editProfile.jsp")) 65 | val projectId = request.getParameter("projectId") 66 | val pools = ArrayList() 67 | if (BuildProject.ROOT_PROJECT_ID != projectId) { 68 | pools.add(AgentPoolUtil.DUMMY_PROJECT_POOL) 69 | } 70 | pools.addAll(agentPoolManager.getProjectOwnedAgentPools(projectId)) 71 | mv.model.put("launchTypes", LaunchType.values().toMutableList()) 72 | mv.model["fargateVersions"] = EcsParameterConstants.FARGATE_VERSIONS.toMutableList() 73 | mv.model.put("agentPools", pools) 74 | mv.model.put("taskDefChooserUrl", taskDefsController.url) 75 | mv.model.put("clusterChooserUrl", clustersController.url) 76 | mv.model.put("deleteImageUrl", deleteImageDialogController.url) 77 | mv.model.put("testConnectionUrl", url + "?testConnection=true") 78 | return mv 79 | } 80 | } -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/EcsCloudClient.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs 4 | 5 | import com.google.common.collect.Maps 6 | import com.intellij.openapi.diagnostic.Logger 7 | import jetbrains.buildServer.agent.Constants 8 | import jetbrains.buildServer.clouds.* 9 | import jetbrains.buildServer.serverSide.AgentDescription 10 | import java.io.File 11 | import java.util.* 12 | import java.util.concurrent.ConcurrentHashMap 13 | 14 | class EcsCloudClient(images: List, 15 | private val updater: EcsInstancesUpdater, 16 | private val ecsClientParams: EcsCloudClientParameters, 17 | private val serverUuid: String, 18 | private val idxStorage: File, 19 | private val cloudProfileId: String) : CloudClientEx { 20 | private val LOG = Logger.getInstance(EcsCloudClient::class.java.getName()) 21 | 22 | private var myImageIdToImageMap: ConcurrentHashMap = ConcurrentHashMap(Maps.uniqueIndex(images, { it?.id })) 23 | 24 | init { 25 | updater.registerClient(this) 26 | } 27 | 28 | override fun isInitialized(): Boolean { 29 | //TODO: wait while all images populate list of their instances 30 | return true 31 | } 32 | 33 | override fun dispose() { 34 | updater.unregisterClient(this) 35 | LOG.debug("EcsCloudClient disposed") 36 | } 37 | 38 | override fun getErrorInfo(): CloudErrorInfo? { 39 | return null 40 | } 41 | 42 | override fun canStartNewInstanceWithDetails(image: CloudImage): CanStartNewInstanceResult { 43 | val ecsImage = image as EcsCloudImage 44 | if (!myImageIdToImageMap.containsKey(ecsImage.id)) { 45 | LOG.debug("Can't start instance of unknown cloud image with id ${ecsImage.id}") 46 | return CanStartNewInstanceResult.no("unknown ECS image ${ecsImage.id}") 47 | } 48 | 49 | 50 | if (ecsClientParams.instanceLimit in 0..images.sumBy{(it as EcsCloudImage).runningInstanceCount}) { 51 | return CanStartNewInstanceResult.no("Profile running instances limit reached") 52 | } 53 | 54 | return ecsImage.canStartNewInstanceWithDetails() 55 | } 56 | 57 | override fun startNewInstance(image: CloudImage, tag: CloudInstanceUserData): CloudInstance { 58 | try{ 59 | return (image as EcsCloudImage).startNewInstance(tag) 60 | } catch (ex: Exception){ 61 | LOG.debug("Failed to start cloud instance", ex) 62 | throw ex 63 | } 64 | } 65 | 66 | override fun terminateInstance(instance: CloudInstance) { 67 | val kubeCloudInstance = instance as EcsCloudInstance 68 | kubeCloudInstance.terminate() 69 | } 70 | 71 | override fun restartInstance(instance: CloudInstance) { 72 | throw UnsupportedOperationException("Restart not implemented") 73 | } 74 | 75 | override fun generateAgentName(agent: AgentDescription): String? { 76 | val agentParameters = agent.availableParameters 77 | val instanceId = agentParameters.get(Constants.ENV_PREFIX + INSTANCE_ID_ECS_ENV) 78 | if (instanceId.isNullOrEmpty()) return null 79 | val imageId = agentParameters.get(Constants.ENV_PREFIX + IMAGE_ID_ECS_ENV) 80 | val image = myImageIdToImageMap.get(imageId) ?: return null 81 | return image.generateAgentName(instanceId!!); 82 | } 83 | 84 | override fun getImages(): MutableCollection { 85 | return Collections.unmodifiableCollection(myImageIdToImageMap.values) 86 | } 87 | 88 | override fun findImageById(imageId: String): CloudImage? { 89 | return myImageIdToImageMap.get(imageId) 90 | } 91 | 92 | override fun findInstanceByAgent(agent: AgentDescription): CloudInstance? { 93 | val agentParameters = agent.getAvailableParameters() 94 | 95 | if (serverUuid != agentParameters.get(Constants.ENV_PREFIX + SERVER_UUID_ECS_ENV) || cloudProfileId != agentParameters.get(Constants.ENV_PREFIX + PROFILE_ID_ECS_ENV)) 96 | return null 97 | 98 | val imageId = agentParameters.get(Constants.ENV_PREFIX + IMAGE_ID_ECS_ENV) 99 | val instanceId = agentParameters.get(Constants.ENV_PREFIX + INSTANCE_ID_ECS_ENV) 100 | if (imageId != null && instanceId != null) { 101 | val cloudImage = myImageIdToImageMap[imageId] 102 | if (cloudImage != null) { 103 | return cloudImage.findInstanceById(instanceId) 104 | } 105 | } 106 | return null 107 | } 108 | } -------------------------------------------------------------------------------- /infra/modules/ec2/main.tf: -------------------------------------------------------------------------------- 1 | data "aws_ami" "amazon_ecs_os" { 2 | most_recent = true 3 | 4 | filter { 5 | name = "name" 6 | values = ["*-amazon-ecs-optimized"] 7 | values = ["hvm"] 8 | } 9 | 10 | owners = ["amazon"] 11 | } 12 | 13 | resource "aws_launch_configuration" "default" { 14 | name_prefix = "${var.project_name}-${var.stack_name}-lc-" 15 | image_id = "${data.aws_ami.amazon_ecs_os.id}" 16 | instance_type = "${var.instance_type}" 17 | 18 | iam_instance_profile = "${var.instance_profile_arn}" 19 | key_name = "${var.ec2_keypair_name}" 20 | 21 | user_data = <> /etc/sysconfig/docker 30 | 31 | --==BOUNDARY== 32 | Content-Type: text/x-shellscript; charset="us-ascii" 33 | 34 | #!/bin/bash 35 | # Set any ECS agent configuration options 36 | echo ECS_CLUSTER=${var.project_name}-${var.stack_name} >> /etc/ecs/ecs.config 37 | 38 | --==BOUNDARY==-- 39 | USERDATA 40 | 41 | root_block_device { 42 | volume_size = "20" 43 | volume_type = "gp2" 44 | } 45 | 46 | ebs_block_device { 47 | device_name = "/dev/xvdcz" 48 | volume_size = "${var.ec2_volume_size}" 49 | volume_type = "gp2" 50 | } 51 | 52 | lifecycle { 53 | create_before_destroy = true 54 | } 55 | } 56 | 57 | resource "aws_autoscaling_group" "agents" { 58 | name = "${var.project_name}-${var.stack_name}-ecs-asg" 59 | launch_configuration = "${aws_launch_configuration.default.id}" 60 | max_size = "${var.asg_max_size}" 61 | min_size = "${var.asg_min_size}" 62 | protect_from_scale_in = true 63 | 64 | vpc_zone_identifier = ["${var.vpc_zone_identifier}"] 65 | 66 | tag { 67 | key = "Name" 68 | value = "${var.project_name}-${var.stack_name}-ecs-node" 69 | propagate_at_launch = true 70 | } 71 | } 72 | 73 | resource "aws_autoscaling_policy" "agents-scale-up" { 74 | name = "${var.project_name}-${var.stack_name}-agents-scale-up" 75 | scaling_adjustment = "${var.asg_scaling_adjustment}" 76 | adjustment_type = "ChangeInCapacity" 77 | cooldown = "${var.asg_cooldown}" 78 | autoscaling_group_name = "${aws_autoscaling_group.agents.name}" 79 | } 80 | 81 | resource "aws_cloudwatch_metric_alarm" "memory-high" { 82 | alarm_name = "${var.project_name}-${var.stack_name}-agents-mem-high" 83 | period = "${var.asg_metric_period}" 84 | evaluation_periods = "1" 85 | metric_name = "CPUReservation" 86 | comparison_operator = "GreaterThanOrEqualToThreshold" 87 | threshold = "100" 88 | namespace = "AWS/ECS" 89 | statistic = "Average" 90 | 91 | alarm_actions = [ 92 | "${aws_autoscaling_policy.agents-scale-up.arn}", 93 | ] 94 | 95 | dimensions { 96 | ClusterName = "${var.project_name}-${var.stack_name}" 97 | } 98 | } 99 | 100 | resource "aws_autoscaling_policy" "agents-scale-down" { 101 | name = "${var.project_name}-${var.stack_name}-agents-scale-down" 102 | scaling_adjustment = "-${var.asg_scaling_adjustment}" 103 | adjustment_type = "ChangeInCapacity" 104 | cooldown = "${var.asg_cooldown}" 105 | autoscaling_group_name = "${aws_autoscaling_group.agents.name}" 106 | } 107 | 108 | resource "aws_cloudwatch_metric_alarm" "memory-low" { 109 | alarm_name = "${var.project_name}-${var.stack_name}-agents-mem-low" 110 | period = "${var.asg_metric_period}" 111 | evaluation_periods = "1" 112 | metric_name = "CPUReservation" 113 | comparison_operator = "LessThanThreshold" 114 | threshold = "100" 115 | namespace = "AWS/ECS" 116 | statistic = "Average" 117 | 118 | alarm_actions = [ 119 | "${aws_autoscaling_policy.agents-scale-down.arn}", 120 | ] 121 | 122 | dimensions { 123 | ClusterName = "${var.project_name}-${var.stack_name}" 124 | } 125 | } 126 | 127 | resource "aws_autoscaling_notification" "agents-scale-down" { 128 | group_names = [ 129 | "${aws_autoscaling_group.agents.name}", 130 | ] 131 | 132 | notifications = [ 133 | "autoscaling:EC2_INSTANCE_LAUNCH", 134 | "autoscaling:EC2_INSTANCE_TERMINATE", 135 | "autoscaling:EC2_INSTANCE_LAUNCH_ERROR", 136 | "autoscaling:EC2_INSTANCE_TERMINATE_ERROR", 137 | ] 138 | 139 | topic_arn = "${aws_sns_topic.asg-sns-topic.arn}" 140 | } 141 | 142 | resource "aws_sns_topic" "asg-sns-topic" { 143 | name = "${var.project_name}-${var.stack_name}-ASGSNSTopic" 144 | } 145 | 146 | resource "aws_autoscaling_lifecycle_hook" "terminate" { 147 | name = "terminate" 148 | autoscaling_group_name = "${aws_autoscaling_group.agents.name}" 149 | default_result = "ABANDON" 150 | heartbeat_timeout = 5400 151 | lifecycle_transition = "autoscaling:EC2_INSTANCE_TERMINATING" 152 | notification_target_arn = "${aws_sns_topic.asg-sns-topic.arn}" 153 | role_arn = "${var.iam_role_sns_lambda_arn}" 154 | } 155 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /infra/modules/iam/main.tf: -------------------------------------------------------------------------------- 1 | resource "aws_iam_role" "ec2_instance_role" { 2 | assume_role_policy = <): EcsCloudClient { 52 | return createClient(images, mapOf()) 53 | } 54 | 55 | private fun createClient(images: List, params: Map): EcsCloudClient { 56 | return createClient("server-uuid", "profile-id", images, MockCloudClientParameters(params)) 57 | } 58 | 59 | private fun createClient(serverUuid: String, profileId: String, images: List, cloudClientParameters: CloudClientParameters): EcsCloudClient { 60 | return EcsCloudClient(images, updater, EcsCloudClientParametersImpl(cloudClientParameters), serverUuid, createTempDir(), profileId) 61 | } 62 | 63 | @Test 64 | @Throws(Exception::class) 65 | fun testCanStartNewInstance_UnknownImage() { 66 | val cloudClient = createClient(emptyList()) 67 | val image = m.mock(EcsCloudImage::class.java) 68 | m.checking(object : Expectations() { 69 | init { 70 | allowing(image).id 71 | will(Expectations.returnValue("image-1-id")) 72 | } 73 | }) 74 | Assert.assertFalse(cloudClient.canStartNewInstance(image)) 75 | } 76 | 77 | @Test 78 | @Throws(Exception::class) 79 | fun testCanStartNewInstance() { 80 | val image = m.mock(EcsCloudImage::class.java) 81 | m.checking(object : Expectations() { 82 | init { 83 | allowing(image).name; will(returnValue("image-1-name")) 84 | allowing(image).id; will(returnValue("image-1-id")) 85 | allowing(image).runningInstanceCount; will(returnValue(0)) 86 | allowing(image).canStartNewInstanceWithDetails(); will(returnValue(CanStartNewInstanceResult.yes())) 87 | } 88 | }) 89 | val images = listOf(image) 90 | val cloudClient = createClient(images) 91 | Assert.assertTrue(cloudClient.canStartNewInstanceWithDetails(image).isPositive) 92 | } 93 | 94 | @Test 95 | @Throws(Exception::class) 96 | fun testCanStartNewInstance_ProfileLimit() { 97 | val image = m.mock(EcsCloudImage::class.java) 98 | m.checking(object : Expectations() { 99 | init { 100 | allowing(image).id; will(Expectations.returnValue("image-1-id")) 101 | allowing(image).runningInstanceCount; will(Expectations.returnValue(1)) 102 | allowing(image).canStartNewInstanceWithDetails(); will(returnValue(true)) 103 | } 104 | }) 105 | val images = listOf(image) 106 | val paramsMap = mapOf(Pair(PROFILE_INSTANCE_LIMIT_PARAM, "1")) 107 | val cloudClient = createClient(images, paramsMap) 108 | val canStartResult = cloudClient.canStartNewInstanceWithDetails(image) 109 | Assert.assertFalse(canStartResult.isPositive) 110 | then(canStartResult.reason).isEqualTo("Profile running instances limit reached") 111 | } 112 | 113 | @Test 114 | @Throws(Exception::class) 115 | fun testCanStartNewInstance_ImageCanNotStartNewInstance() { 116 | val image = m.mock(EcsCloudImage::class.java) 117 | m.checking(object : Expectations() { 118 | init { 119 | allowing(image).name; will(Expectations.returnValue("image-1-name")) 120 | allowing(image).id; will(Expectations.returnValue("image-1-id")) 121 | allowing(image).runningInstanceCount; will(Expectations.returnValue(1)) 122 | allowing(image).canStartNewInstanceWithDetails(); will(returnValue(CanStartNewInstanceResult.no("Kann nicht"))) 123 | } 124 | }) 125 | val images = listOf(image) 126 | val cloudClient = createClient(images) 127 | val canStartResult = cloudClient.canStartNewInstanceWithDetails(image) 128 | Assert.assertFalse(canStartResult.isPositive) 129 | then(canStartResult.reason).isEqualTo("Kann nicht") 130 | } 131 | 132 | @Test 133 | @Throws(Exception::class) 134 | fun testDuplicateImageName() { 135 | val image1 = m.mock(EcsCloudImage::class.java, "1") 136 | val image2 = m.mock(EcsCloudImage::class.java, "2") 137 | m.checking(object : Expectations() { 138 | init { 139 | allowing(image1).id; will(Expectations.returnValue("image-1-id")) 140 | allowing(image1).name; will(Expectations.returnValue("image")) 141 | allowing(image1).runningInstanceCount; will(Expectations.returnValue(0)) 142 | allowing(image2).id; will(Expectations.returnValue("image-2-id")) 143 | allowing(image2).name; will(Expectations.returnValue("image")) 144 | allowing(image2).runningInstanceCount; will(Expectations.returnValue(0)) 145 | } 146 | }) 147 | createClient(listOf(image1, image2)) 148 | } 149 | 150 | @Test 151 | @TestFor(issues= ["TW-62422"]) 152 | fun testStartNewInstanceManyImages(){ 153 | val imageCount = 4 154 | val imagesList = arrayListOf() 155 | for (i in 1..imageCount){ 156 | imagesList.add(m.mock(EcsCloudImage::class.java, "image-$i")) 157 | } 158 | m.checking(object : Expectations() { 159 | init { 160 | var idx = 0 161 | for (image in imagesList) { 162 | idx++; 163 | allowing(image).name; will(Expectations.returnValue("image-$idx-name")) 164 | allowing(image).id; will(Expectations.returnValue("image-$idx-id")) 165 | allowing(image).runningInstanceCount; will(Expectations.returnValue(idx-1)) 166 | 167 | allowing(image).canStartNewInstanceWithDetails(); will(returnValue( 168 | if (idx%2==0) CanStartNewInstanceResult.yes() else CanStartNewInstanceResult.no("odd reason") 169 | )) 170 | } 171 | } 172 | }) 173 | val cloudClient = createClient(imagesList, mapOf(Pair(PROFILE_INSTANCE_LIMIT_PARAM, "8"))) 174 | Assert.assertTrue(cloudClient.canStartNewInstanceWithDetails(imagesList[3]).isPositive) 175 | Assert.assertFalse(cloudClient.canStartNewInstanceWithDetails(imagesList[2]).isPositive) 176 | Assert.assertTrue(cloudClient.canStartNewInstanceWithDetails(imagesList[1]).isPositive) 177 | Assert.assertFalse(cloudClient.canStartNewInstanceWithDetails(imagesList[0]).isPositive) 178 | } 179 | } 180 | 181 | class MockCloudClientParameters(val params: Map) : CloudClientParameters() { 182 | override fun getProfileId(): String { 183 | TODO("not implemented") //To change body of created functions use File | Settings | File Templates. 184 | } 185 | 186 | override fun getParameter(name: String): String? { 187 | return params.get(name) 188 | } 189 | 190 | override fun getParameters(): MutableMap { 191 | return params.toMutableMap() 192 | } 193 | 194 | override fun getProfileDescription(): String { 195 | TODO("not implemented") //To change body of created functions use File | Settings | File Templates. 196 | } 197 | 198 | override fun getCloudImages(): MutableCollection { 199 | TODO("not implemented") //To change body of created functions use File | Settings | File Templates. 200 | } 201 | 202 | override fun listParameterNames(): MutableCollection { 203 | return params.keys.toMutableList() 204 | } 205 | 206 | } -------------------------------------------------------------------------------- /infra/modules/lambda/ecs-scaledown-lambda/index.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import boto3 3 | from urlparse import urlparse 4 | import base64 5 | import json 6 | import datetime 7 | import time 8 | import logging 9 | 10 | 11 | 12 | logging.basicConfig() 13 | logger = logging.getLogger() 14 | logger.setLevel(logging.DEBUG) 15 | 16 | # Establish boto3 session 17 | session = boto3.session.Session() 18 | logger.debug("Session is in region %s ", session.region_name) 19 | 20 | ec2Client = session.client(service_name='ec2') 21 | ecsClient = session.client(service_name='ecs') 22 | asgClient = session.client('autoscaling') 23 | snsClient = session.client('sns') 24 | lambdaClient = session.client('lambda') 25 | 26 | 27 | """Publish SNS message to trigger lambda again. 28 | :param message: To repost the complete original message received when ASG terminating event was received. 29 | :param topicARN: SNS topic to publish the message to. 30 | """ 31 | def publishToSNS(message, topicARN): 32 | logger.info("Publish to SNS topic %s",topicARN) 33 | snsResponse = snsClient.publish( 34 | TopicArn=topicARN, 35 | Message=json.dumps(message), 36 | Subject='Publishing SNS message to invoke lambda again..' 37 | ) 38 | return "published" 39 | 40 | 41 | """Check task status on the ECS container instance ID. 42 | :param Ec2InstanceId: The EC2 instance ID is used to identify the cluster, container instances in cluster 43 | """ 44 | def checkContainerInstanceTaskStatus(Ec2InstanceId): 45 | containerInstanceId = None 46 | clusterName = None 47 | tmpMsgAppend = None 48 | 49 | # Describe instance attributes and get the Clustername from userdata section which would have set ECS_CLUSTER name 50 | ec2Resp = ec2Client.describe_instance_attribute(InstanceId=Ec2InstanceId, Attribute='userData') 51 | userdataEncoded = ec2Resp['UserData'] 52 | userdataDecoded = base64.b64decode(userdataEncoded['Value']) 53 | logger.debug("Describe instance attributes response %s", ec2Resp) 54 | 55 | tmpList = userdataDecoded.split() 56 | for token in tmpList: 57 | if token.find("ECS_CLUSTER") > -1: 58 | # Split and get the cluster name 59 | clusterName = token.split('=')[1] 60 | logger.info("Cluster name %s",clusterName) 61 | 62 | # Get list of container instance IDs from the clusterName 63 | clusterListResp = ecsClient.list_container_instances(cluster=clusterName) 64 | containerDetResp = ecsClient.describe_container_instances(cluster=clusterName, containerInstances=clusterListResp[ 65 | 'containerInstanceArns']) 66 | logger.debug("describe container instances response %s",containerDetResp) 67 | 68 | for containerInstances in containerDetResp['containerInstances']: 69 | logger.debug("Container Instance ARN: %s and ec2 Instance ID %s",containerInstances['containerInstanceArn'], 70 | containerInstances['ec2InstanceId']) 71 | if containerInstances['ec2InstanceId'] == Ec2InstanceId: 72 | logger.info("Container instance ID of interest : %s",containerInstances['containerInstanceArn']) 73 | containerInstanceId = containerInstances['containerInstanceArn'] 74 | 75 | # Check if the instance state is set to DRAINING. If not, set it, so the ECS Cluster will handle de-registering instance, draining tasks and draining them 76 | containerStatus = containerInstances['status'] 77 | if containerStatus == 'DRAINING': 78 | logger.info("Container ID %s with EC2 instance-id %s is draining tasks",containerInstanceId, 79 | Ec2InstanceId) 80 | tmpMsgAppend = {"containerInstanceId": containerInstanceId} 81 | else: 82 | # Make ECS API call to set the container status to DRAINING 83 | logger.info("Make ECS API call to set the container status to DRAINING...") 84 | ecsResponse = ecsClient.update_container_instances_state(cluster=clusterName,containerInstances=[containerInstanceId],status='DRAINING') 85 | # When you set instance state to draining, append the containerInstanceID to the message as well 86 | tmpMsgAppend = {"containerInstanceId": containerInstanceId} 87 | 88 | # Using container Instance ID, get the task list, and task running on that instance. 89 | if containerInstanceId != None: 90 | # List tasks on the container instance ID, to get task Arns 91 | listTaskResp = ecsClient.list_tasks(cluster=clusterName, containerInstance=containerInstanceId) 92 | logger.debug("Container instance task list %s",listTaskResp['taskArns']) 93 | 94 | # If the chosen instance has tasks 95 | if len(listTaskResp['taskArns']) > 0: 96 | logger.info("Tasks are on this instance...%s",Ec2InstanceId) 97 | return 1, tmpMsgAppend 98 | else: 99 | logger.info("NO tasks are on this instance...%s",Ec2InstanceId) 100 | return 0, tmpMsgAppend 101 | else: 102 | logger.info("NO tasks are on this instance....%s",Ec2InstanceId) 103 | return 0, tmpMsgAppend 104 | 105 | 106 | def lambda_handler(event, context): 107 | 108 | line = event['Records'][0]['Sns']['Message'] 109 | message = json.loads(line) 110 | Ec2InstanceId = message['EC2InstanceId'] 111 | asgGroupName = message['AutoScalingGroupName'] 112 | snsArn = event['Records'][0]['EventSubscriptionArn'] 113 | TopicArn = event['Records'][0]['Sns']['TopicArn'] 114 | 115 | lifecyclehookname = None 116 | clusterName = None 117 | tmpMsgAppend = None 118 | completeHook = 0 119 | 120 | logger.info("Lambda received the event %s",event) 121 | logger.debug("records: %s",event['Records'][0]) 122 | logger.debug("sns: %s",event['Records'][0]['Sns']) 123 | logger.debug("Message: %s",message) 124 | logger.debug("Ec2 Instance Id %s ,%s",Ec2InstanceId, asgGroupName) 125 | logger.debug("SNS ARN %s",snsArn) 126 | 127 | # Describe instance attributes and get the Clustername from userdata section which would have set ECS_CLUSTER name 128 | ec2Resp = ec2Client.describe_instance_attribute(InstanceId=Ec2InstanceId, Attribute='userData') 129 | logger.debug("Describe instance attributes response %s",ec2Resp) 130 | userdataEncoded = ec2Resp['UserData'] 131 | userdataDecoded = base64.b64decode(userdataEncoded['Value']) 132 | 133 | tmpList = userdataDecoded.split() 134 | for token in tmpList: 135 | if token.find("ECS_CLUSTER") > -1: 136 | # Split and get the cluster name 137 | clusterName = token.split('=')[1] 138 | logger.debug("Cluster name %s",clusterName) 139 | 140 | # Get list of container instance IDs from the clusterName 141 | clusterListResp = ecsClient.list_container_instances(cluster=clusterName) 142 | logger.debug("list container instances response %s",clusterListResp) 143 | 144 | # If the event received is instance terminating... 145 | if 'LifecycleTransition' in message.keys(): 146 | logger.debug("message autoscaling %s",message['LifecycleTransition']) 147 | if message['LifecycleTransition'].find('autoscaling:EC2_INSTANCE_TERMINATING') > -1: 148 | 149 | # Get lifecycle hook name 150 | lifecycleHookName = message['LifecycleHookName'] 151 | logger.debug("Setting lifecycle hook name %s ",lifecycleHookName) 152 | 153 | # Check if there are any tasks running on the instance 154 | tasksRunning, tmpMsgAppend = checkContainerInstanceTaskStatus(Ec2InstanceId) 155 | logger.debug("Returned values received: %s ",tasksRunning) 156 | if tmpMsgAppend != None: 157 | message.update(tmpMsgAppend) 158 | 159 | # If tasks are still running... 160 | if tasksRunning == 1: 161 | response = snsClient.list_subscriptions() 162 | for key in response['Subscriptions']: 163 | logger.info("Endpoint %s AND TopicArn %s and protocol %s ",key['Endpoint'], key['TopicArn'], 164 | key['Protocol']) 165 | if TopicArn == key['TopicArn'] and key['Protocol'] == 'lambda': 166 | logger.info("TopicArn match, publishToSNS function...") 167 | msgResponse = publishToSNS(message, key['TopicArn']) 168 | logger.debug("msgResponse %s and time is %s",msgResponse, datetime.datetime) 169 | # If tasks are NOT running... 170 | elif tasksRunning == 0: 171 | completeHook = 1 172 | logger.debug("Setting lifecycle to complete;No tasks are running on instance, completing lifecycle action....") 173 | 174 | try: 175 | response = asgClient.complete_lifecycle_action( 176 | LifecycleHookName=lifecycleHookName, 177 | AutoScalingGroupName=asgGroupName, 178 | LifecycleActionResult='CONTINUE', 179 | InstanceId=Ec2InstanceId) 180 | logger.info("Response received from complete_lifecycle_action %s",response) 181 | logger.info("Completedlifecycle hook action") 182 | except Exception, e: 183 | print(str(e)) 184 | -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/apiConnector/EcsApiConnectorImpl.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs.apiConnector 4 | 5 | import com.amazonaws.ClientConfiguration 6 | import com.amazonaws.auth.AWSCredentials 7 | import com.amazonaws.auth.AWSCredentialsProvider 8 | import com.amazonaws.services.cloudwatch.AmazonCloudWatch 9 | import com.amazonaws.services.cloudwatch.AmazonCloudWatchClientBuilder 10 | import com.amazonaws.services.cloudwatch.model.Dimension 11 | import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsRequest 12 | import com.amazonaws.services.cloudwatch.model.Statistic 13 | import com.amazonaws.services.ecs.AmazonECS 14 | import com.amazonaws.services.ecs.AmazonECSClientBuilder 15 | import com.amazonaws.services.ecs.model.* 16 | import com.intellij.openapi.diagnostic.Logger 17 | import jetbrains.buildServer.serverSide.TeamCityProperties 18 | import jetbrains.buildServer.version.ServerVersionHolder 19 | import java.util.* 20 | import java.util.concurrent.TimeUnit 21 | 22 | 23 | class EcsApiConnectorImpl(awsCredentialsProvider: AWSCredentialsProvider, awsRegion: String?) : EcsApiConnector { 24 | private val LOG = Logger.getInstance(EcsApiConnectorImpl::class.java.getName()) 25 | private val ecs: AmazonECS 26 | private val cloudWatch: AmazonCloudWatch 27 | 28 | init { 29 | val clientConfig = ClientConfiguration().withUserAgentPrefix("JetBrains TeamCity " + ServerVersionHolder.getVersion().displayVersion) 30 | 31 | val httpProxy = TeamCityProperties.getProperty("teamcity.ecs.https.proxyHost", TeamCityProperties.getProperty("teamcity.https.proxyHost")) 32 | val httpProxyPort = TeamCityProperties.getInteger("teamcity.ecs.https.proxyPort", TeamCityProperties.getInteger("teamcity.https.proxyPort", -1)) 33 | val httpProxyUser = TeamCityProperties.getProperty("teamcity.ecs.https.proxyLogin", TeamCityProperties.getProperty("teamcity.https.proxyLogin")) 34 | val httpProxyPassword = TeamCityProperties.getProperty("teamcity.ecs.https.proxyPassword", TeamCityProperties.getProperty("teamcity.https.proxyPassword")) 35 | 36 | LOG.debug(String.format("ECS client proxy settings: proxy - %s, port - %d, user - %s", httpProxy, httpProxyPort, httpProxyUser, httpProxyPassword)) 37 | 38 | if (!httpProxy.isEmpty()){ 39 | clientConfig.setProxyHost(httpProxy) 40 | } 41 | 42 | if (httpProxyPort >= 0){ 43 | clientConfig.setProxyPort(httpProxyPort) 44 | } 45 | 46 | if (!httpProxyUser.isEmpty()){ 47 | clientConfig.setProxyUsername(httpProxyUser) 48 | } 49 | 50 | if (!httpProxyPassword.isEmpty()){ 51 | clientConfig.setProxyPassword(httpProxyPassword) 52 | } 53 | 54 | val ecsBuilder = AmazonECSClientBuilder 55 | .standard() 56 | .withClientConfiguration(clientConfig) 57 | .withRegion(awsRegion) 58 | ecsBuilder.withCredentials(awsCredentialsProvider) 59 | ecs = ecsBuilder.build() 60 | 61 | var cloudWatchBuilder = AmazonCloudWatchClientBuilder.standard() 62 | .withClientConfiguration(clientConfig) 63 | .withRegion(awsRegion) 64 | cloudWatchBuilder.withCredentials(awsCredentialsProvider) 65 | cloudWatch = cloudWatchBuilder.build() 66 | } 67 | 68 | override fun runTask( 69 | launchType: LaunchType?, 70 | taskDefinition: EcsTaskDefinition, 71 | cluster: String?, 72 | taskGroup: String?, 73 | subnets: Collection, 74 | securityGroups: Collection, 75 | assignPublicIp: Boolean, 76 | additionalEnvironment: Map, 77 | startedBy: String?, 78 | fargatePlatformVersion: String? 79 | ): List { 80 | val containerOverrides = taskDefinition.containers.map { 81 | containerName -> ContainerOverride() 82 | .withName(containerName) 83 | .withEnvironment(additionalEnvironment.entries.map { entry -> KeyValuePair().withName(entry.key).withValue(entry.value) }) 84 | } 85 | 86 | var request = RunTaskRequest() 87 | .withTaskDefinition(taskDefinition.arn) 88 | .withOverrides(TaskOverride().withContainerOverrides(containerOverrides)) 89 | .withStartedBy(startedBy) 90 | if (launchType != null){ 91 | request.withLaunchType(launchType) 92 | } 93 | if (launchType == LaunchType.FARGATE && fargatePlatformVersion != null){ 94 | request.withPlatformVersion(fargatePlatformVersion) 95 | } 96 | if(cluster != null && !cluster.isEmpty()) request = request.withCluster(cluster) 97 | if(taskGroup != null && !taskGroup.isEmpty()) request = request.withGroup(taskGroup) 98 | if(!subnets.isEmpty() || !securityGroups.isEmpty()) request = request.withNetworkConfiguration( 99 | NetworkConfiguration().withAwsvpcConfiguration( 100 | AwsVpcConfiguration() 101 | .let { if (subnets.isNotEmpty()) it.withSubnets(subnets).withAssignPublicIp(if(assignPublicIp) AssignPublicIp.ENABLED else AssignPublicIp.DISABLED) else it } 102 | .let { if (securityGroups.isNotEmpty()) it.withSecurityGroups(securityGroups) else it })) 103 | 104 | val runTaskResult = ecs.runTask(request) 105 | if (!runTaskResult.failures.isEmpty()) 106 | throw EcsApiCallFailureException(runTaskResult.failures) 107 | 108 | return runTaskResult.tasks.map { it.wrap() } 109 | } 110 | 111 | override fun listTaskDefinitions(): List { 112 | var taskDefArns:List = ArrayList() 113 | var nextToken: String? = null; 114 | do{ 115 | var request = ListTaskDefinitionsRequest() 116 | if(nextToken != null) request = request.withNextToken(nextToken) 117 | val taskDefsResult = ecs.listTaskDefinitions(request) 118 | taskDefArns = taskDefArns.plus(taskDefsResult.taskDefinitionArns) 119 | nextToken = taskDefsResult.nextToken 120 | } 121 | while(nextToken != null) 122 | return taskDefArns 123 | } 124 | 125 | override fun describeTaskDefinition(taskDefinitionArn: String): EcsTaskDefinition? { 126 | return ecs.describeTaskDefinition(DescribeTaskDefinitionRequest().withTaskDefinition(taskDefinitionArn)).taskDefinition.wrap() 127 | } 128 | 129 | override fun stopTask(task: String, cluster: String?, reason: String?) { 130 | ecs.stopTask(StopTaskRequest().withTask(task).withCluster(cluster)) 131 | } 132 | 133 | override fun listRunningTasks(cluster: String?, startedBy: String?): List { 134 | return listTasks(cluster, startedBy, DesiredStatus.RUNNING) 135 | } 136 | 137 | override fun listStoppedTasks(cluster: String?, startedBy: String?): List { 138 | return listTasks(cluster, startedBy, DesiredStatus.STOPPED) 139 | } 140 | 141 | private fun listTasks(cluster: String?, startedBy: String?, desiredStatus:DesiredStatus): List { 142 | var taskArns:List = ArrayList() 143 | var nextToken: String? = null; 144 | do{ 145 | var listTasksRequest = ListTasksRequest() 146 | .withCluster(cluster) 147 | .withStartedBy(startedBy) 148 | .withDesiredStatus(desiredStatus) 149 | 150 | if(nextToken != null) listTasksRequest = listTasksRequest.withNextToken(nextToken) 151 | 152 | val tasksResult = ecs.listTasks(listTasksRequest) 153 | taskArns = taskArns.plus(tasksResult.taskArns) 154 | nextToken = tasksResult.nextToken 155 | } 156 | while(nextToken != null) 157 | return taskArns 158 | } 159 | 160 | override fun describeTask(taskArn: String, cluster: String?): EcsTask? { 161 | try { 162 | val tasksResult = ecs.describeTasks(DescribeTasksRequest().withTasks(taskArn).withCluster(cluster)) 163 | if (!tasksResult.failures.isEmpty()) 164 | throw EcsApiCallFailureException(tasksResult.failures) 165 | 166 | return tasksResult.tasks[0]?.wrap() 167 | } catch (ex:Throwable){ 168 | LOG.warnAndDebugDetails("Unable find task $taskArn in cluster $cluster", ex) 169 | return null 170 | } 171 | } 172 | 173 | override fun listClusters(): List { 174 | var clusterArns:List = ArrayList() 175 | var nextToken: String? = null 176 | do{ 177 | var request = ListClustersRequest() 178 | if(nextToken != null) request = request.withNextToken(nextToken) 179 | val tasksResult = ecs.listClusters(request) 180 | clusterArns = clusterArns.plus(tasksResult.clusterArns) 181 | nextToken = tasksResult.nextToken 182 | } 183 | while(nextToken != null) 184 | return clusterArns 185 | } 186 | 187 | override fun describeCluster(clusterArn: String): EcsCluster? { 188 | val describeClustersResult = ecs.describeClusters(DescribeClustersRequest().withClusters(clusterArn)) 189 | if (!describeClustersResult.failures.isEmpty()) 190 | throw EcsApiCallFailureException(describeClustersResult.failures) 191 | 192 | return describeClustersResult.clusters[0]?.wrap() 193 | } 194 | 195 | override fun testConnection(): TestConnectionResult { 196 | try { 197 | ecs.listClusters() 198 | return TestConnectionResult("Connection successful", true) 199 | } catch (ex: Exception){ 200 | return TestConnectionResult(ex.localizedMessage, false) 201 | } 202 | } 203 | 204 | override fun getMaxCPUReservation(cluster: String?, period:Int): Int { 205 | val currentTimeMillis = System.currentTimeMillis() 206 | val request = GetMetricStatisticsRequest() 207 | .withMetricName("CPUReservation") 208 | .withNamespace("AWS/ECS") 209 | .withDimensions(Dimension().withName("ClusterName").withValue(cluster)) 210 | .withStatistics(Statistic.Maximum) 211 | .withStartTime(Date(currentTimeMillis - TimeUnit.MINUTES.toMillis(period.toLong() * 2))) 212 | .withEndTime(Date(currentTimeMillis)) 213 | .withPeriod(period * 60) 214 | val datapoints = cloudWatch.getMetricStatistics(request).datapoints 215 | if(datapoints.isEmpty()) return -1 216 | return datapoints[0].maximum.toInt() 217 | } 218 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 © JetBrains s.r.o. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /aws-ecs-server/src/main/kotlin/jetbrains/buildServer/clouds/ecs/EcsCloudImageImpl.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package jetbrains.buildServer.clouds.ecs 4 | 5 | import com.amazonaws.services.ecs.model.LaunchType 6 | import com.intellij.openapi.diagnostic.Logger 7 | import jetbrains.buildServer.clouds.* 8 | import jetbrains.buildServer.clouds.ecs.apiConnector.EcsApiConnector 9 | import jetbrains.buildServer.clouds.ecs.apiConnector.EcsTask 10 | import jetbrains.buildServer.serverSide.TeamCityProperties 11 | import jetbrains.buildServer.util.FileUtil 12 | import jetbrains.buildServer.util.StringUtil 13 | import kotlinx.coroutines.* 14 | import kotlinx.coroutines.sync.Mutex 15 | import kotlinx.coroutines.sync.withLock 16 | import java.io.ByteArrayInputStream 17 | import java.io.File 18 | import java.util.* 19 | import java.util.concurrent.ConcurrentHashMap 20 | import java.util.concurrent.atomic.AtomicBoolean 21 | import java.util.concurrent.atomic.AtomicInteger 22 | import java.util.concurrent.atomic.AtomicLong 23 | import kotlin.collections.ArrayList 24 | import kotlin.collections.HashSet 25 | 26 | 27 | class EcsCloudImageImpl(private val imageData: EcsCloudImageData, 28 | private val apiConnector: EcsApiConnector, 29 | private val serverUUID: String, 30 | idxStorage: File, 31 | private val profileId: String) : EcsCloudImage { 32 | 33 | private val LOG = Logger.getInstance(EcsCloudImageImpl::class.java.getName()) 34 | private val ERROR_INSTANCES_TIMEOUT: Long = 60*1000 35 | 36 | private val idxFile = File(idxStorage, imageName4File() + ".idx") 37 | private val idxCounter = AtomicInteger(0) 38 | private val idxTouched = AtomicBoolean(false) 39 | private val idxMutex = Mutex() 40 | private val counterContext = newSingleThreadContext("IdxContext") 41 | private val errorInstances= ConcurrentHashMap>() 42 | 43 | private val muteTime = AtomicLong(0) 44 | 45 | init{ 46 | try { 47 | if (!idxFile.exists()) { 48 | idxCounter.set(1) 49 | idxTouched.set(true) 50 | storeIdx() 51 | } else { 52 | runBlocking { 53 | idxMutex.withLock { 54 | idxCounter.set(Integer.parseInt(FileUtil.readText(idxFile))) 55 | } 56 | } 57 | } 58 | } catch (ex: Exception) { 59 | LOG.warnAndDebugDetails("Unable to process idx file '${idxFile.absolutePath}'. Will reset the index for ${imageData.taskDefinition}", ex) 60 | idxCounter.set(1) 61 | } 62 | 63 | GlobalScope.async{ 64 | while (true) { 65 | try { 66 | storeIdx() 67 | expireErrorInstances() 68 | delay(1000) 69 | } catch (ex: Exception){ 70 | LOG.warnAndDebugDetails("An error occurred during processing of periodic tasks", ex) 71 | } 72 | } 73 | } 74 | } 75 | 76 | override fun canStartNewInstanceWithDetails(): CanStartNewInstanceResult { 77 | if (System.currentTimeMillis() < muteTime.get()) 78 | return CanStartNewInstanceResult.no("image is still muted") 79 | 80 | if(instanceLimit in 0..runningInstanceCount) 81 | return CanStartNewInstanceResult.no("image's running instances limit reached") 82 | 83 | if (cpuReservalionLimit > 0) { 84 | val monitoringPeriod = TeamCityProperties.getInteger(ECS_METRICS_MONITORING_PERIOD, 1) 85 | if (apiConnector.getMaxCPUReservation(cluster, monitoringPeriod) > cpuReservalionLimit){ 86 | return CanStartNewInstanceResult.no("CPU reservation limit reached") 87 | } 88 | } 89 | return CanStartNewInstanceResult.yes() 90 | } 91 | 92 | 93 | private val myIdToInstanceMap = ConcurrentHashMap() 94 | private var myCurrentError: CloudErrorInfo? = null 95 | 96 | private val instanceLimit: Int 97 | get() = imageData.instanceLimit 98 | 99 | private val cpuReservalionLimit: Int 100 | get() = imageData.cpuReservalionLimit 101 | 102 | private val cluster: String? 103 | get() = imageData.cluster 104 | 105 | private val taskGroup: String? 106 | get() = imageData.taskGroup 107 | 108 | private val subnets: Collection 109 | get() { 110 | val rawSubnetsString = imageData.subnets?.trim() 111 | return if(rawSubnetsString.isNullOrEmpty()) emptyList() else rawSubnetsString!!.lines() 112 | } 113 | 114 | private val securityGroups: Collection 115 | get() { 116 | val rawSecurityGroupsString = imageData.securityGroups?.trim() 117 | return if(rawSecurityGroupsString.isNullOrEmpty()) emptyList() else rawSecurityGroupsString!!.lines() 118 | } 119 | 120 | private val assignPublicIp: Boolean 121 | get() = imageData.assignPublicIp 122 | 123 | private val launchType: LaunchType? 124 | get() { 125 | return try { 126 | LaunchType.fromValue(imageData.launchType) 127 | } catch (ex:Exception) { 128 | null 129 | } 130 | } 131 | 132 | private val fargatePlatformVersion: String? 133 | get() { 134 | if (launchType != LaunchType.EC2){ 135 | return imageData.fargatePlatformVersion 136 | } else { 137 | return null 138 | } 139 | } 140 | 141 | private val taskDefinition: String 142 | get() = imageData.taskDefinition 143 | 144 | override val runningInstanceCount: Int 145 | get() = myIdToInstanceMap.filterValues { instance -> instance.status.isStartingOrStarted }.size 146 | 147 | override fun getAgentPoolId(): Int? { 148 | return imageData.agentPoolId 149 | } 150 | 151 | override fun getName(): String { 152 | return taskDefinition 153 | } 154 | 155 | override fun getId(): String { 156 | return imageData.id 157 | } 158 | 159 | override fun getProfileId(): String = profileId 160 | 161 | override fun getInstances(): MutableCollection { 162 | return myIdToInstanceMap.values 163 | } 164 | 165 | override fun getErrorInfo(): CloudErrorInfo? { 166 | return myCurrentError 167 | } 168 | 169 | override fun findInstanceById(id: String): CloudInstance? { 170 | return myIdToInstanceMap[id] 171 | } 172 | 173 | override fun populateInstances() { 174 | LOG.debug("Populating instances for $name") 175 | try { 176 | val startedBy = startedByTeamCity(serverUUID) 177 | 178 | val runningTasks = apiConnector.listRunningTasks(cluster, startedBy).mapNotNull { taskArn -> apiConnector.describeTask(taskArn, cluster) } 179 | val stoppedTasks = apiConnector.listStoppedTasks(cluster, startedBy).mapNotNull { taskArn -> apiConnector.describeTask(taskArn, cluster) } 180 | LOG.debug("Will process ${runningTasks.size} running and ${stoppedTasks.size} stopped tasks") 181 | 182 | synchronized(myIdToInstanceMap) { 183 | val keySet = HashSet(myIdToInstanceMap.keys) 184 | val newTasks = ArrayList() 185 | for (task in runningTasks.union(stoppedTasks)) { 186 | val taskProfileId = task.getOverridenContainerEnv(PROFILE_ID_ECS_ENV) 187 | val taskImageId = task.getOverridenContainerEnv(IMAGE_ID_ECS_ENV) 188 | if(profileId == taskProfileId && taskImageId == id){ 189 | val instanceId = task.getOverridenContainerEnv(INSTANCE_ID_ECS_ENV) 190 | if(instanceId == null) { 191 | LOG.warn("Can't resolve cloud instance id of ecs task ${task.arn}") 192 | continue 193 | } 194 | if (keySet.remove(instanceId)) { 195 | val instance = myIdToInstanceMap[instanceId] 196 | if (instance == null) { 197 | LOG.warn("Unable to find instance with id '$instanceId'. Was it removed?") 198 | continue 199 | } 200 | instance.update(task) 201 | } else { 202 | newTasks.add(task) 203 | } 204 | } 205 | } 206 | //remove absent instances 207 | keySet.forEach { 208 | LOG.info("Instance '$it' is no longer available") 209 | myIdToInstanceMap.remove(it) 210 | } 211 | newTasks.forEach{ 212 | val instanceId = it.getOverridenContainerEnv(INSTANCE_ID_ECS_ENV) 213 | if (instanceId != null) { 214 | LOG.info("Found new instance '$instanceId'") 215 | myIdToInstanceMap[instanceId] = EcsCloudInstanceImpl(instanceId, this, it, apiConnector) 216 | } else { 217 | LOG.info("Found no instance id for task with arn '${it.arn}'") 218 | } 219 | } 220 | myCurrentError = null 221 | } 222 | } catch (ex: Throwable) { 223 | val msg = "Unable to populate instances for ${imageData.id}" 224 | LOG.warnAndDebugDetails(msg, ex) 225 | myCurrentError = CloudErrorInfo(msg, ex.message.toString(), ex) 226 | } 227 | } 228 | 229 | 230 | @Synchronized 231 | override fun startNewInstance(userData: CloudInstanceUserData): EcsCloudInstance { 232 | if (!canStartNewInstanceWithDetails().isPositive) { 233 | return BrokenEcsCloudInstance("cantStart", this, CloudErrorInfo("limit reached")) 234 | } 235 | val instanceId = generateNewInstanceId() 236 | val startingInstance = StartingEcsCloudInstance(instanceId, this) 237 | myIdToInstanceMap[instanceId] = startingInstance 238 | LOG.debug("attempting to start new ECS instance with generated instanceId: $instanceId") 239 | try { 240 | val taskDefinition = apiConnector.describeTaskDefinition(taskDefinition) ?: throw CloudException("""Task definition $taskDefinition is missing""") 241 | 242 | val additionalEnvironment = HashMap() 243 | additionalEnvironment[SERVER_UUID_ECS_ENV] = serverUUID 244 | additionalEnvironment[SERVER_URL_ECS_ENV] = userData.serverAddress 245 | additionalEnvironment[OFFICIAL_IMAGE_SERVER_URL_ECS_ENV] = userData.serverAddress 246 | additionalEnvironment[PROFILE_ID_ECS_ENV] = userData.profileId 247 | additionalEnvironment[IMAGE_ID_ECS_ENV] = id 248 | additionalEnvironment[INSTANCE_ID_ECS_ENV] = instanceId 249 | additionalEnvironment[AGENT_NAME_ECS_ENV] = generateAgentName(instanceId) 250 | 251 | for (pair in userData.customAgentConfigurationParameters){ 252 | if (pair.key.equals(STARTING_INSTANCE_ID_CONFIG_PARAM)) { 253 | additionalEnvironment[STARTING_INSTANCE_ID_ECS_ENV] = pair.value 254 | } else { 255 | additionalEnvironment[TEAMCITY_ECS_PROVIDED_PREFIX + pair.key] = pair.value 256 | } 257 | } 258 | 259 | val tasks = apiConnector.runTask(launchType, taskDefinition, cluster, taskGroup, subnets, securityGroups, 260 | assignPublicIp, additionalEnvironment, startedByTeamCity(serverUUID), fargatePlatformVersion) 261 | LOG.info("Started ECS instance ${tasks[0].id}, generatedInstanceId: $instanceId") 262 | val startedInstance = EcsCloudInstanceImpl(instanceId, this, tasks[0], apiConnector) 263 | myIdToInstanceMap[instanceId] = startedInstance 264 | if (startingInstance.terminateRequested){ 265 | startedInstance.terminate() 266 | } 267 | return startedInstance 268 | } catch (ex: Throwable){ 269 | val errInstance = BrokenEcsCloudInstance(instanceId, this, CloudErrorInfo(ex.message.toString(), ex.message.toString(), ex)) 270 | myIdToInstanceMap[instanceId] = errInstance 271 | errorInstances[instanceId] = Pair(errInstance, System.currentTimeMillis() + ERROR_INSTANCES_TIMEOUT) 272 | muteTime.set(System.currentTimeMillis() + ERROR_INSTANCES_TIMEOUT) 273 | return errInstance 274 | } 275 | } 276 | 277 | override fun generateAgentName(instanceId: String): String { 278 | return imageData.agentNamePrefix + instanceId 279 | } 280 | 281 | private fun generateNewInstanceId(): String { 282 | lateinit var retval : String 283 | do{ 284 | retval = String.format("${imageData.taskDefinition}-${idxCounter.getAndIncrement()}") 285 | } while (myIdToInstanceMap.containsKey(retval)) 286 | LOG.info("Will create a new instance with name $retval") 287 | return retval 288 | } 289 | 290 | private fun imageName4File():String { 291 | return StringUtil.replaceNonAlphaNumericChars(imageData.taskDefinition, '_') 292 | } 293 | 294 | private fun storeIdx() = runBlocking { 295 | if (idxTouched.compareAndSet(true, false)){ 296 | idxMutex.withLock { 297 | FileUtil.writeViaTmpFile(idxFile, ByteArrayInputStream(idxCounter.get().toString().toByteArray()), 298 | FileUtil.IOAction.DO_NOTHING) 299 | } 300 | } 301 | } 302 | 303 | private fun expireErrorInstances() = runBlocking { 304 | errorInstances.forEach{ 305 | if (it.value.second < System.currentTimeMillis()) { 306 | errorInstances.remove(it.key) 307 | } 308 | } 309 | } 310 | } -------------------------------------------------------------------------------- /aws-ecs-server/src/main/resources/buildServerResources/editProfile.jsp: -------------------------------------------------------------------------------- 1 | <%@ include file="/include.jsp" %> 2 | 3 | <%@ taglib prefix="props" tagdir="/WEB-INF/tags/props" %> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | <%@ taglib prefix="l" tagdir="/WEB-INF/tags/layout" %> 6 | <%@ taglib prefix="forms" tagdir="/WEB-INF/tags/forms" %> 7 | <%@ taglib prefix="util" uri="/WEB-INF/functions/util" %> 8 | <%@ taglib prefix="bs" tagdir="/WEB-INF/tags" %> 9 | <%@ taglib prefix="admin" tagdir="/WEB-INF/tags/admin" %> 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 42 | 43 | 44 | 45 | 46 | 51 | 52 | 53 |
40 | Test connection 41 |
47 | 48 | 49 | Maximum number of instances that can be started. Use blank to have no limit 50 |
54 | 55 |

Agent images

56 | 57 |
58 | 76 | Add image 77 |
78 | 79 | 81 |
82 |
83 |
84 | 85 | 87 | 88 | 89 | 90 | 103 | 104 | 105 | 106 | 114 | 115 | 116 | 117 | 125 | 126 | 127 | 128 | 132 | 133 | 134 | 135 | 143 | 144 | 145 | 146 | 153 | 154 | 155 | 156 | 161 | 162 | 163 | 164 | 169 | 170 | 171 | 172 | 177 | 178 | 179 | 180 | 186 | 187 | 188 | 189 | 194 | 195 | 196 | 197 | 206 | 207 |
Launch type:  91 |
92 | 99 |
100 |
The launch type on which to run tasks.
101 | 102 |
107 | 112 | 113 |
Task definition:  118 |
119 | 120 | ')"> 121 |
122 |
The family and revision (family:revision) or full Amazon Resource Name (ARN) of the task definition to run. If a revision is not specified, the latest ACTIVE revision is used.
123 | 124 |
129 | 130 | If no or incorrect prefix provided, default value ECS will be used 131 |
Cluster: 136 |
137 | 138 | ')"> 139 |
140 |
The short name or full Amazon Resource Name (ARN) of the cluster on which to run cloud agents. Leave blank to use the default cluster.
141 | 142 |
Task group: 147 |
148 | 149 |
The name of the task group to associate with the cloud agent tasks. Leave blank to use the family name of the task definition.
150 | 151 |
152 |
Subnets: 157 | 158 |
New line delimited list of subnet ARNs in cluster VPC that TeamCity should consider for task placement.
159 | 160 |
Security Groups: 165 | 166 |
New line delimited list of security group IDs in cluster VPC that TeamCity should apply to the task if run with the networking mode awsvpc. If left blank, the default VPC security group will be used.
167 | 168 |
Assign public IP: 173 | 174 |
Enable or disable auto-assign public IP.
175 | 176 |
Max number of instances: 181 |
182 | 183 |
184 | 185 |
190 | 191 | Maximum allowed cluster CPU reservation percentile. Will deny to start new cloud instances when limit is being reached. Use blank to have no limit. 192 | 193 |
198 | 204 | 205 |
208 | 209 | 210 | 211 | 212 |
213 | 214 | Cancel 215 |
216 |
217 | 218 | 220 | 221 |
222 | 223 |
224 | 225 | Cancel 226 |
227 |
228 | 229 | 241 | 242 | -------------------------------------------------------------------------------- /aws-ecs-server/src/main/resources/buildServerResources/ecsSettings.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | if (!BS) BS = {}; 4 | if (!BS.Ecs) BS.Ecs = {}; 5 | 6 | if(!BS.Ecs.ProfileSettingsForm) BS.Ecs.ProfileSettingsForm = OO.extend(BS.PluginPropertiesForm, { 7 | 8 | testConnectionUrl: '', 9 | 10 | _dataKeys: [ 'launchType', 'taskDefinition', 'agentNamePrefix', 'cluster', 'taskGroup', 'subnets', 'fargatePlatformVersion', 'securityGroups', 'assignPublicIp', 'maxInstances', 'cpuReservationLimit', 'agent_pool_id'], 11 | 12 | templates: { 13 | imagesTableRow: $j('\ 14 | \ 15 | \ 16 | \ 17 | \ 18 | \ 19 | \ 20 | \ 21 | \ 22 | ')}, 23 | 24 | selectors: { 25 | rmImageLink: '.removeVmImageLink', 26 | editImageLink: '.editVmImageLink', 27 | imagesTableRow: '.imagesTableRow' 28 | }, 29 | 30 | defaults: { 31 | launchType: '!SHOULD_NOT_BE_EMPTY!', 32 | taskDefinition: '!SHOULD_NOT_BE_EMPTY!', 33 | cluster: '', 34 | taskGroup: 'family:', 35 | maxInstances: '', 36 | cpuReservationLimit: '' 37 | }, 38 | 39 | _errors: { 40 | badParam: 'Bad parameter', 41 | required: 'This field cannot be blank', 42 | requiredForFargate: 'This field is required when using FARGATE launch type', 43 | notSelected: 'Something should be selected', 44 | nonNegative: 'Must be non-negative number', 45 | nonPercentile: 'Must be a number from range 1..100' 46 | }, 47 | 48 | _displayedErrors: {}, 49 | 50 | initialize: function(){ 51 | this.$imagesTable = $j('#ecsImagesTable'); 52 | this.$imagesTableWrapper = $j('.imagesTableWrapper'); 53 | this.$emptyImagesListMessage = $j('.emptyImagesListMessage'); //TODO: implement 54 | this.$showAddImageDialogButton = $j('#showAddImageDialogButton'); 55 | 56 | //add / edit image dialog 57 | this.$addImageButton = $j('#ecsAddImageButton'); 58 | this.$cancelAddImageButton = $j('#ecsCancelAddImageButton'); 59 | 60 | this.$deleteImageButton = $j('#ecsDeleteImageButton'); 61 | this.$cancelDeleteImageButton = $j('#ecsCancelDeleteImageButton'); 62 | 63 | this.$launchType = $j('#launchType'); 64 | this.$taskDefinition = $j('#taskDefinition'); 65 | this.$agentNamePrefix = $j('#agentNamePrefix'); 66 | this.$taskGroup = $j('#taskGroup'); 67 | this.$subnets = $j('#subnets'); 68 | this.$fargatePlatformVersion = $j('#fargatePlatformVersion'); 69 | this.$securityGroups = $j('#securityGroups'); 70 | this.$assignPublicIp = $j('#assignPublicIp'); 71 | this.$cluster = $j('#cluster'); 72 | this.$maxInstances = $j('#maxInstances'); 73 | this.$cpuReservationLimit = $j('#cpuReservationLimit'); 74 | this.$agentPoolId = $j('#agent_pool_id'); 75 | 76 | this.$imagesDataElem = $j('#' + 'source_images_json'); 77 | 78 | var self = this; 79 | var rawImagesData = this.$imagesDataElem.val() || '[]'; 80 | this._imagesDataLength = 0; 81 | try { 82 | var imagesData = JSON.parse(rawImagesData); 83 | this.imagesData = imagesData.reduce(function (accumulator, imageDataStr) { 84 | accumulator[self._imagesDataLength++] = imageDataStr; 85 | return accumulator; 86 | }, {}); 87 | } catch (e) { 88 | this.imagesData = {}; 89 | BS.Log.error('bad images data: ' + rawImagesData); 90 | } 91 | 92 | this._bindHandlers(); 93 | this._renderImagesTable(); 94 | 95 | BS.Clouds.Admin.CreateProfileForm.checkIfModified(); 96 | }, 97 | 98 | _bindHandlers: function () { 99 | var self = this; 100 | 101 | this.$showAddImageDialogButton.on('click', this._showDialogClickHandler.bind(this)); 102 | this.$addImageButton.on('click', this._submitDialogClickHandler.bind(this)); 103 | this.$cancelAddImageButton.on('click', this._cancelDialogClickHandler.bind(this)); 104 | 105 | this.$imagesTable.on('click', this.selectors.rmImageLink, function () { 106 | self.showDeleteImageDialog($j(this)); 107 | return false; 108 | }); 109 | this.$deleteImageButton.on('click', this._submitDeleteImageDialogClickHandler.bind(this)); 110 | this.$cancelDeleteImageButton.on('click', this._cancelDeleteImageDialogClickHandler.bind(this)); 111 | 112 | var editDelegates = this.selectors.imagesTableRow + ' .highlight, ' + this.selectors.editImageLink; 113 | var that = this; 114 | this.$imagesTable.on('click', editDelegates, function () { 115 | if (!that.$addImageButton.prop('disabled')) { 116 | self.showEditImageDialog($j(this)); 117 | } 118 | return false; 119 | }); 120 | 121 | this.$launchType.on('change', function (e, value) { 122 | if(value !== undefined) this.$launchType.val(value); 123 | this._image['launchType'] = this.$launchType.val(); 124 | this.validateOptions(e.target.getAttribute('data-id')); 125 | var subnetsTr = $j('.fargate-only'); 126 | if(this.$launchType.val() === 'FARGATE'){ 127 | subnetsTr.each(function(){ 128 | $j(this).removeClass("advancedSetting"); 129 | $j(this).removeClass("advancedSettingHighlight"); 130 | $j(this).removeClass("advanced_hidden"); 131 | }) 132 | } else { 133 | subnetsTr.each(function(){ 134 | $j(this).addClass("advancedSetting"); 135 | if($j("tr[class*='advancedSettingHighlight']")) { 136 | $j(this).addClass("advancedSettingHighlight"); 137 | } 138 | if($j("tr[class*='advanced_hidden']")) { 139 | $j(this).addClass("advanced_hidden"); 140 | } 141 | }) 142 | } 143 | }.bind(this)); 144 | 145 | this.$taskDefinition.on('change', function (e, value) { 146 | if(value !== undefined) this.$taskDefinition.val(value); 147 | this._image['taskDefinition'] = this.$taskDefinition.val(); 148 | this.validateOptions(e.target.getAttribute('data-id')); 149 | }.bind(this)); 150 | 151 | this.$agentNamePrefix.on('change', function (e, value) { 152 | if(value !== undefined) this.$agentNamePrefix.val(value); 153 | this._image['agentNamePrefix'] = this.$agentNamePrefix.val(); 154 | this.validateOptions(e.target.getAttribute('data-id')); 155 | }.bind(this)); 156 | 157 | this.$cluster.on('change', function (e, value) { 158 | if(value !== undefined) this.$cluster.val(value); 159 | this._image['cluster'] = this.$cluster.val(); 160 | this.validateOptions(e.target.getAttribute('data-id')); 161 | }.bind(this)); 162 | 163 | this.$taskGroup.on('change', function (e, value) { 164 | if(value !== undefined) this.$taskGroup.val(value); 165 | this._image['taskGroup'] = this.$taskGroup.val(); 166 | this.validateOptions(e.target.getAttribute('data-id')); 167 | }.bind(this)); 168 | 169 | this.$subnets.on('change', function (e, value) { 170 | if(value !== undefined) this.$subnets.val(value); 171 | this._image['subnets'] = this.$subnets.val(); 172 | this.validateOptions(e.target.getAttribute('data-id')); 173 | }.bind(this)); 174 | 175 | this.$fargatePlatformVersion.on('change', function (e, value) { 176 | if(value !== undefined) this.$fargatePlatformVersion.val(value); 177 | this._image['fargatePlatformVersion'] = this.$fargatePlatformVersion.val(); 178 | this.validateOptions(e.target.getAttribute('data-id')); 179 | }.bind(this)); 180 | 181 | this.$securityGroups.on('change', function (e, value) { 182 | if(value !== undefined) this.$securityGroups.val(value); 183 | this._image['securityGroups'] = this.$securityGroups.val(); 184 | this.validateOptions(e.target.getAttribute('data-id')); 185 | }.bind(this)); 186 | 187 | this.$assignPublicIp.click(function() { 188 | this._image['assignPublicIp'] = this.$assignPublicIp.prop('checked'); 189 | }.bind(this)); 190 | 191 | this.$maxInstances.on('change', function (e, value) { 192 | if(value !== undefined) this.$maxInstances.val(value); 193 | this._image['maxInstances'] = this.$maxInstances.val(); 194 | this.validateOptions(e.target.getAttribute('data-id')); 195 | }.bind(this)); 196 | 197 | this.$cpuReservationLimit.on('change', function (e, value) { 198 | if(value !== undefined) this.$cpuReservationLimit.val(value); 199 | this._image['cpuReservationLimit'] = this.$cpuReservationLimit.val(); 200 | this.validateOptions(e.target.getAttribute('data-id')); 201 | }.bind(this)); 202 | 203 | this.$agentPoolId.on('change', function (e, value) { 204 | if(value !== undefined) this.$agentPoolId.val(value); 205 | this._image['agent_pool_id'] = this.$agentPoolId.val(); 206 | this.validateOptions(e.target.getAttribute('data-id')); 207 | }.bind(this)); 208 | }, 209 | 210 | _renderImagesTable: function () { 211 | this._clearImagesTable(); 212 | 213 | if (this._imagesDataLength) { 214 | Object.keys(this.imagesData).forEach(function (imageId) { 215 | var image = this.imagesData[imageId]; 216 | var src = image['source-id']; 217 | $j('#initial_images_list').val($j('#initial_images_list').val() + src + ","); 218 | this._renderImageRow(image, imageId); 219 | }.bind(this)); 220 | } 221 | 222 | this._toggleImagesTable(); 223 | BS.Clouds.Admin.CreateProfileForm.checkIfModified(); 224 | }, 225 | 226 | _clearImagesTable: function () { 227 | this.$imagesTable.find('.imagesTableRow').remove(); 228 | }, 229 | 230 | _toggleImagesTable: function () { 231 | var toggle = !!this._imagesDataLength; 232 | this.$imagesTableWrapper.removeClass('hidden'); 233 | this.$emptyImagesListMessage.toggleClass('hidden', toggle); 234 | this.$imagesTable.toggleClass('hidden', !toggle); 235 | }, 236 | 237 | _renderImageRow: function (props, id) { 238 | var $row = this.templates.imagesTableRow.clone().attr('data-image-id', id); 239 | var defaults = this.defaults; 240 | 241 | this._dataKeys.forEach(function (className) { 242 | $row.find('.' + className).text(props[className] || defaults[className]); 243 | }); 244 | 245 | $row.find(this.selectors.rmImageLink).data('image-id', id); 246 | $row.find(this.selectors.editImageLink).data('image-id', id); 247 | this.$imagesTable.append($row); 248 | }, 249 | 250 | _showDialogClickHandler: function () { 251 | if (! this.$showAddImageDialogButton.attr('disabled')) { 252 | this.showAddImageDialog(); 253 | } 254 | return false; 255 | }, 256 | 257 | _submitDialogClickHandler: function() { 258 | if (this.validateOptions()) { 259 | if (this.$addImageButton.val().toLowerCase() === 'save') { 260 | this.editImage(this.$addImageButton.data('image-id')); 261 | } else { 262 | this.addImage(); 263 | } 264 | BS.Ecs.ImageDialog.close(); 265 | } 266 | return false; 267 | }, 268 | 269 | _cancelDialogClickHandler: function () { 270 | BS.Ecs.ImageDialog.close(); 271 | return false; 272 | }, 273 | 274 | selectTaskDef: function(taskDef){ 275 | this.$taskDefinition.trigger('change', taskDef || ''); 276 | }, 277 | 278 | selectCluster: function(cluster){ 279 | this.$cluster.trigger('change', cluster || ''); 280 | }, 281 | 282 | showAddImageDialog: function () { 283 | $j('#EcsImageDialogTitle').text('Add Amazon Elastic Container Service Cloud Image'); 284 | 285 | BS.Hider.addHideFunction('EcsImageDialog', this._resetDataAndDialog.bind(this)); 286 | this.$addImageButton.val('Add').data('image-id', 'undefined'); 287 | 288 | this._image = {}; 289 | 290 | BS.Ecs.ImageDialog.showCentered(); 291 | }, 292 | 293 | showEditImageDialog: function ($elem) { 294 | var imageId = $elem.parents(this.selectors.imagesTableRow).data('image-id'); 295 | 296 | $j('#EcsImageDialogTitle').text('Edit Amazon Elastic Container Service Cloud Image'); 297 | 298 | BS.Hider.addHideFunction('EcsImageDialog', this._resetDataAndDialog.bind(this)); 299 | 300 | typeof imageId !== 'undefined' && (this._image = $j.extend({}, this.imagesData[imageId])); 301 | this.$addImageButton.val('Save').data('image-id', imageId); 302 | if (imageId === 'undefined'){ 303 | this.$addImageButton.removeData('image-id'); 304 | } 305 | 306 | var image = this._image; 307 | 308 | this.$launchType.trigger('change', image['launchType'] || ''); 309 | this.selectTaskDef(image['taskDefinition'] || ''); 310 | this.$agentNamePrefix.trigger('change', image['agentNamePrefix'] || ''); 311 | this.$taskGroup.trigger('change', image['taskGroup'] || ''); 312 | this.$subnets.trigger('change', image['subnets'] || ''); 313 | this.$fargatePlatformVersion.trigger('change', image['fargatePlatformVersion'] || ''); 314 | this.$securityGroups.trigger('change', image['securityGroups'] || ''); 315 | this.$assignPublicIp.prop('checked', image['assignPublicIp'] === 'true' ? image['assignPublicIp'] : ''); 316 | this.selectCluster(image['cluster'] || ''); 317 | this.$maxInstances.trigger('change', image['maxInstances'] || ''); 318 | this.$cpuReservationLimit.trigger('change', image['cpuReservationLimit'] || ''); 319 | this.$agentPoolId.trigger('change', image['agent_pool_id'] || ''); 320 | 321 | BS.Ecs.ImageDialog.showCentered(); 322 | }, 323 | 324 | _resetDataAndDialog: function () { 325 | this._image = {}; 326 | 327 | this.$launchType.trigger('change', ''); 328 | this.selectTaskDef(''); 329 | this.$agentNamePrefix.trigger('change', ''); 330 | this.$taskGroup.trigger('change', ''); 331 | this.$subnets.trigger('change', ''); 332 | this.$fargatePlatformVersion.trigger('change', 'LATEST'); 333 | this.$securityGroups.trigger('change', ''); 334 | this.$assignPublicIp.prop('checked', ''); 335 | this.selectCluster(''); 336 | this.$maxInstances.trigger('change', ''); 337 | this.$cpuReservationLimit.trigger('change', ''); 338 | this.$agentPoolId.trigger('change', ''); 339 | }, 340 | 341 | validateOptions: function (options){ 342 | var isValid = true; 343 | 344 | var validators = { 345 | launchType : function () { 346 | var launchType = this._image['launchType']; 347 | if (!launchType || launchType === '' || launchType === undefined) { 348 | this.addOptionError('notSelected', 'launchType'); 349 | isValid = false; 350 | } 351 | }.bind(this), 352 | 353 | taskDefinition : function () { 354 | if (!this._image['taskDefinition']) { 355 | this.addOptionError('required', 'taskDefinition'); 356 | isValid = false; 357 | } 358 | }.bind(this), 359 | 360 | maxInstances: function () { 361 | var maxInstances = this._image['maxInstances']; 362 | if (maxInstances && (!$j.isNumeric(maxInstances) || maxInstances < 0 )) { 363 | this.addOptionError('nonNegative', 'maxInstances'); 364 | isValid = false; 365 | } 366 | }.bind(this), 367 | 368 | cpuReservationLimit: function () { 369 | var cpuReservationLimit = this._image['cpuReservationLimit']; 370 | if (cpuReservationLimit && (!$j.isNumeric(cpuReservationLimit) || cpuReservationLimit < 0 || cpuReservationLimit > 100 )) { 371 | this.addOptionError('nonPercentile', 'cpuReservationLimit'); 372 | isValid = false; 373 | } 374 | }.bind(this), 375 | 376 | agent_pool_id : function () { 377 | var agentPoolId = this._image['agent_pool_id']; 378 | if (!agentPoolId || agentPoolId === '' || agentPoolId === undefined) { 379 | this.addOptionError('notSelected', 'agent_pool_id'); 380 | isValid = false; 381 | } 382 | }.bind(this) 383 | }; 384 | 385 | if (options && ! $j.isArray(options)) { 386 | options = [options]; 387 | } 388 | 389 | this.clearOptionsErrors(options); 390 | 391 | (options || this._dataKeys).forEach(function(option) { 392 | if(validators[option]) validators[option](); 393 | }); 394 | 395 | return isValid; 396 | }, 397 | 398 | addOptionError: function (errorKey, optionName) { 399 | var html; 400 | 401 | if (errorKey && optionName) { 402 | this._displayedErrors[optionName] = this._displayedErrors[optionName] || []; 403 | 404 | if (typeof errorKey !== 'string') { 405 | html = this._errors[errorKey.key]; 406 | Object.keys(errorKey.props).forEach(function(key) { 407 | html = html.replace('%%'+key+'%%', errorKey.props[key]); 408 | }); 409 | errorKey = errorKey.key; 410 | } else { 411 | html = this._errors[errorKey]; 412 | } 413 | 414 | if (this._displayedErrors[optionName].indexOf(errorKey) === -1) { 415 | this._displayedErrors[optionName].push(errorKey); 416 | this.addError(html, $j('.option-error_' + optionName)); 417 | } 418 | } 419 | }, 420 | 421 | addError: function (errorHTML, target) { 422 | target.append($j('
').html(errorHTML)); 423 | }, 424 | 425 | clearOptionsErrors: function (options) { 426 | (options || this._dataKeys).forEach(function (optionName) { 427 | this.clearErrors(optionName); 428 | }.bind(this)); 429 | }, 430 | 431 | clearErrors: function (errorId) { 432 | var target = $j('.option-error_' + errorId); 433 | if (errorId) { 434 | delete this._displayedErrors[errorId]; 435 | } 436 | target.empty(); 437 | }, 438 | 439 | addImage: function () { 440 | var newImageId = this.generateNewImageId(), 441 | newImage = this._image; 442 | newImage['source-id'] = newImageId; 443 | this._renderImageRow(newImage, newImageId); 444 | this.imagesData[newImageId] = newImage; 445 | this._imagesDataLength += 1; 446 | this.saveImagesData(); 447 | this._toggleImagesTable(); 448 | }, 449 | 450 | generateNewImageId: function () { 451 | if($j.isEmptyObject(this.imagesData)) return 1; 452 | else return Math.max.apply(Math, $j.map(this.imagesData, function callback(currentValue) { 453 | return currentValue['source-id']; 454 | })) + 1; 455 | }, 456 | 457 | editImage: function (id) { 458 | this._image['source-id'] = id; 459 | this.imagesData[id] = this._image; 460 | this.saveImagesData(); 461 | this.$imagesTable.find(this.selectors.imagesTableRow).remove(); 462 | this._renderImagesTable(); 463 | }, 464 | 465 | removeImage: function (imageId) { 466 | delete this.imagesData[imageId]; 467 | this._imagesDataLength -= 1; 468 | this.$imagesTable.find('tr[data-image-id=\'' + imageId + '\']').remove(); 469 | this.saveImagesData(); 470 | this._toggleImagesTable(); 471 | }, 472 | 473 | saveImagesData: function () { 474 | var imageData = Object.keys(this.imagesData).reduce(function (accumulator, id) { 475 | var _val = $j.extend({}, this.imagesData[id]); 476 | 477 | delete _val.$image; 478 | accumulator.push(_val); 479 | 480 | return accumulator; 481 | }.bind(this), []); 482 | this.$imagesDataElem.val(JSON.stringify(imageData)); 483 | }, 484 | 485 | testConnection: function() { 486 | BS.ajaxRequest(this.testConnectionUrl, { 487 | parameters: BS.Clouds.Admin.CreateProfileForm.serializeParameters(), 488 | onFailure: function (response) { 489 | BS.TestConnectionDialog.show(false, response, null); 490 | }.bind(this), 491 | onSuccess: function (response) { 492 | var wereErrors = BS.XMLResponse.processErrors(response.responseXML, { 493 | onConnectionError: function(elem) { 494 | BS.TestConnectionDialog.show(false, elem.firstChild.nodeValue, null); 495 | } 496 | }, BS.PluginPropertiesForm.propertiesErrorsHandler); 497 | if(!wereErrors){ 498 | BS.TestConnectionDialog.show(true, "", null); 499 | } 500 | }.bind(this) 501 | }); 502 | }, 503 | 504 | showDeleteImageDialog: function ($elem) { 505 | var imageId = $elem.parents(this.selectors.imagesTableRow).data('image-id'); 506 | 507 | BS.ajaxUpdater($("ecsDeleteImageDialogBody"), BS.Ecs.DeleteImageDialog.url + window.location.search, { 508 | method: 'get', 509 | parameters : { 510 | imageId : imageId 511 | }, 512 | onComplete: function() { 513 | BS.Ecs.DeleteImageDialog.show(imageId); 514 | } 515 | }); 516 | }, 517 | 518 | _cancelDeleteImageDialogClickHandler: function () { 519 | BS.Ecs.DeleteImageDialog.close(); 520 | return false; 521 | }, 522 | 523 | _submitDeleteImageDialogClickHandler: function() { 524 | var imageId = BS.Ecs.DeleteImageDialog.currentImageId; 525 | BS.ajaxRequest(BS.Ecs.DeleteImageDialog.url + window.location.search, { 526 | method: 'post', 527 | parameters : { 528 | imageId : imageId 529 | }, 530 | onComplete: function() { 531 | BS.Ecs.ProfileSettingsForm.removeImage(imageId); 532 | BS.Ecs.DeleteImageDialog.close(); 533 | } 534 | }); 535 | } 536 | }); 537 | 538 | if(!BS.Ecs.ImageDialog) BS.Ecs.ImageDialog = OO.extend(BS.AbstractModalDialog, { 539 | getContainer: function() { 540 | return $('EcsImageDialog'); 541 | } 542 | }); 543 | 544 | if(!BS.Ecs.TaskDefChooser){ 545 | BS.Ecs.TaskDefChooser = new BS.Popup('taskDefChooser', { 546 | hideDelay: 0, 547 | hideOnMouseOut: false, 548 | hideOnMouseClickOutside: true, 549 | loadingText: "Loading task definitions..." 550 | }); 551 | 552 | BS.Ecs.TaskDefChooser.showPopup = function(nearestElement, dataLoadUrl){ 553 | var serializeParameters = BS.Clouds.Admin.CreateProfileForm.serializeParameters(); 554 | serializeParameters += "&launchType=" + BS.Ecs.ProfileSettingsForm.$launchType.val(); 555 | this.showPopupNearElement(nearestElement, { 556 | parameters: serializeParameters, 557 | url: dataLoadUrl, 558 | shift:{x:15,y:15} 559 | }); 560 | }; 561 | 562 | BS.Ecs.TaskDefChooser.selectTaskDef = function (taskDef) { 563 | BS.Ecs.ProfileSettingsForm.selectTaskDef(taskDef); 564 | this.hidePopup(); 565 | }; 566 | } 567 | 568 | if(!BS.Ecs.ClusterChooser) { 569 | BS.Ecs.ClusterChooser = new BS.Popup('clusterChooser', { 570 | hideDelay: 0, 571 | hideOnMouseOut: false, 572 | hideOnMouseClickOutside: true, 573 | loadingText: "Loading clusters..." 574 | }); 575 | 576 | BS.Ecs.ClusterChooser.showPopup = function(nearestElement, dataLoadUrl) { 577 | this.showPopupNearElement(nearestElement, { 578 | parameters: BS.Clouds.Admin.CreateProfileForm.serializeParameters(), 579 | url: dataLoadUrl, 580 | shift:{x:15,y:15} 581 | }); 582 | }; 583 | 584 | BS.Ecs.ClusterChooser.selectCluster = function (cluster) { 585 | BS.Ecs.ProfileSettingsForm.$cluster.trigger('change', cluster || ''); 586 | this.hidePopup(); 587 | }; 588 | } 589 | 590 | if(!BS.Ecs.DeleteImageDialog) BS.Ecs.DeleteImageDialog = OO.extend(BS.AbstractModalDialog, { 591 | url: '', 592 | currentImageId: '', 593 | 594 | getContainer: function() { 595 | return $('EcsDeleteImageDialog'); 596 | }, 597 | 598 | show: function (imageId) { 599 | BS.Ecs.DeleteImageDialog.currentImageId = imageId; 600 | BS.Ecs.DeleteImageDialog.showCentered(); 601 | } 602 | }); --------------------------------------------------------------------------------
editdelete