-
Notifications
You must be signed in to change notification settings - Fork 227
/
ECSTaskTemplate.java
1781 lines (1570 loc) · 72 KB
/
ECSTaskTemplate.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The MIT License
*
* Copyright (c) 2015, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.cloudbees.jenkins.plugins.amazonecs;
import com.amazonaws.services.ecs.AmazonECS;
import com.amazonaws.services.ecs.model.AwsVpcConfiguration;
import com.amazonaws.services.ecs.model.ContainerDefinition;
import com.amazonaws.services.ecs.model.EFSAuthorizationConfig;
import com.amazonaws.services.ecs.model.EFSAuthorizationConfigIAM;
import com.amazonaws.services.ecs.model.EFSTransitEncryption;
import com.amazonaws.services.ecs.model.EFSVolumeConfiguration;
import com.amazonaws.services.ecs.model.HostEntry;
import com.amazonaws.services.ecs.model.HostVolumeProperties;
import com.amazonaws.services.ecs.model.KeyValuePair;
import com.amazonaws.services.ecs.model.LaunchType;
import com.amazonaws.services.ecs.model.OSFamily;
import com.amazonaws.services.ecs.model.CPUArchitecture;
import com.amazonaws.services.ecs.model.CapacityProviderStrategyItem;
import com.amazonaws.services.ecs.model.LinuxParameters;
import com.amazonaws.services.ecs.model.MountPoint;
import com.amazonaws.services.ecs.model.NetworkMode;
import com.amazonaws.services.ecs.model.PlacementStrategy;
import com.amazonaws.services.ecs.model.PlacementStrategyType;
import com.amazonaws.services.ecs.model.PortMapping;
import com.amazonaws.services.ecs.model.RegisterTaskDefinitionRequest;
import com.amazonaws.services.ecs.model.RepositoryCredentials;
import com.amazonaws.services.ecs.model.Volume;
import com.amazonaws.services.ecs.model.DescribeClustersRequest;
import com.amazonaws.services.ecs.model.DescribeClustersResult;
import com.amazonaws.services.ecs.model.Cluster;
import com.amazonaws.services.ecs.model.Ulimit;
import com.amazonaws.services.ecs.model.UlimitName;
import static com.google.common.base.Strings.isNullOrEmpty;
import com.amazonaws.services.elasticfilesystem.model.AccessPointDescription;
import com.amazonaws.services.elasticfilesystem.model.FileSystemDescription;
import com.cloudbees.jenkins.plugins.amazonecs.aws.EFSService;
import hudson.Extension;
import hudson.RelativePath;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.model.Label;
import hudson.model.labels.LabelAtom;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import static org.apache.commons.collections.CollectionUtils.isEmpty;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Serializable;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
public class ECSTaskTemplate extends AbstractDescribableImpl<ECSTaskTemplate> implements Serializable {
private static final long serialVersionUID = -426721853953018205L;
/**
* Template Name
*/
private final String templateName;
/**
* White-space separated list of {@link hudson.model.Node} labels.
*
* @see Label
*/
@CheckForNull
private final String label;
@CheckForNull
private final String agentContainerName;
/**
* Task Definition Override to use, instead of a Jenkins-managed Task definition. May be a family name or an ARN.
*/
@CheckForNull
private final String taskDefinitionOverride;
/**
* ARN of the task definition created for a dynamic agent
*/
private String dynamicTaskDefinitionOverride;
/**
* Docker image
* @see ContainerDefinition#withImage(String)
*/
private final String image;
/**
* Agent remote FS
*/
@Nullable
private final String remoteFSRoot;
/**
* The number of MiB of memory reserved for the Docker container. If your
* container attempts to exceed the memory allocated here, the container
* is killed by ECS.
*
* @see ContainerDefinition#withMemory(Integer)
*/
private final int memory;
/**
* The soft limit (in MiB) of memory to reserve for the container. When
* system memory is under contention, Docker attempts to keep the container
* memory to this soft limit; however, your container can consume more
* memory when it needs to, up to either the hard limit specified with the
* memory parameter (if applicable), or all of the available memory on the
* container instance, whichever comes first.
*
* @see ContainerDefinition#withMemoryReservation(Integer)
*/
private final int memoryReservation;
/* a hint to ECSService regarding whether it can ask AWS to make a new container or not */
public int getMemoryConstraint() {
if (this.memoryReservation > 0) {
return this.memoryReservation;
}
return this.memory;
}
/**
* The number of <code>cpu</code> units reserved for the container. A
* container instance has 1,024 <code>cpu</code> units for every CPU
* core. This parameter specifies the minimum amount of CPU to reserve
* for a container, and containers share unallocated CPU units with other
* containers on the instance with the same ratio as their allocated
* amount.
*
* @see ContainerDefinition#withCpu(Integer)
*/
private final int cpu;
/**
* The ephemeral storage settings to use for tasks run with the task definition.
*
* @see com.amazonaws.services.ecs.model.TaskDefinition#withEphemeralStorage
*/
private Integer ephemeralStorageSizeInGiB;
/**
* Sets the size of Share Memory (in MiB) using the
* <code>--shm-size</code> option for the container.
* A container instance has 64mb <code>/dev/shm</code> size
* by default.
*
* @see LinuxParameters#withSharedMemorySize(Integer)
*/
private final int sharedMemorySize;
/**
* Subnets to be assigned on the awsvpc network when using Fargate
*
* @see AwsVpcConfiguration#setSubnets(Collection)
*/
private String subnets;
/**
* Security groups to be assigned on the awsvpc network when using Fargate
*
* @see AwsVpcConfiguration#setSecurityGroups(Collection)
*/
private String securityGroups;
/**
* Assign a public Ip to instance on awsvpc network when using Fargate
*
* @see AwsVpcConfiguration#setAssignPublicIp(String)
*/
private boolean assignPublicIp;
/**
* Space delimited list of Docker dns search domains
*
* @see ContainerDefinition#withDnsSearchDomains(Collection)
*/
@CheckForNull
private String dnsSearchDomains;
/**
* Space delimited list of Docker entry points
*
* @see ContainerDefinition#withEntryPoint(String...)
*/
@CheckForNull
private String entrypoint;
/**
* ARN of the IAM role to use for the agent ECS task
*
* @see RegisterTaskDefinitionRequest#withTaskRoleArn(String)
*/
@CheckForNull
private String taskrole;
/**
* ARN of the IAM role to use for the agent ECS task
*
* @see RegisterTaskDefinitionRequest#withExecutionRoleArn(String)
*/
@CheckForNull
private String executionRole;
/**
* ARN of the Secrets Manager to use for the agent ECS task
*
* @see ContainerDefinition#withRepositoryCredentials(RepositoryCredentials)
*/
@CheckForNull
private String repositoryCredentials;
/**
* JVM arguments to start slave.jar
*/
@CheckForNull
private String jvmArgs;
/**
* Container mount points, imported from volumes
*/
private List<MountPointEntry> mountPoints;
/**
* Container mount points connecting to EFS
*/
private List<EFSMountPointEntry> efsMountPoints;
/**
* Task launch type
*/
private final String launchType;
/**
* Task operating system family type
*/
private final String operatingSystemFamily;
/**
* Task CPU architecture type
*/
private final String cpuArchitecture;
/**
* Use default capacity provider will omit launch types and capacity strategies
*
*/
private boolean defaultCapacityProvider;
/**
* Task network mode
*/
private final String networkMode;
/**
* Indicates whether the container should run in privileged mode
*/
private final boolean privileged;
/**
* Indicates whether to append a unique agent ID (the agent name)
* at the end of the remoteFSRoot path.
*/
private final boolean uniqueRemoteFSRoot;
/**
* Task launch type platform version
*/
private final String platformVersion;
/**
* User for container
*/
@Nullable
private String containerUser;
/**
* List of kernel capabilities to be added
*/
@Nullable
private String kernelCapabilities;
private List<EnvironmentEntry> environments;
private List<ExtraHostEntry> extraHosts;
private List<PortMappingEntry> portMappings;
private List<UlimitEntry> ulimits;
private List<PlacementStrategyEntry> placementStrategies;
private List<CapacityProviderStrategyEntry> capacityProviderStrategies;
private List<Tag> tags;
/**
* The log configuration specification for the container.
* This parameter maps to LogConfig in the Create a container section of
* the Docker Remote API and the --log-driver option to docker run.
* Valid log drivers are displayed in the LogConfiguration data type.
* This parameter requires version 1.18 of the Docker Remote API or greater
* on your container instance. To check the Docker Remote API version on
* your container instance, log into your container instance and run the
* following command: sudo docker version | grep "Server API version"
* The Amazon ECS container agent running on a container instance must
* register the logging drivers available on that instance with the
* ECS_AVAILABLE_LOGGING_DRIVERS environment variable before containers
* placed on that instance can use these log configuration options.
* For more information, see Amazon ECS Container Agent Configuration
* in the Amazon EC2 Container Service Developer Guide.
*/
@CheckForNull
private String logDriver;
private List<LogDriverOption> logDriverOptions;
private String inheritFrom;
/**
* Enable command execution during runtime (comparable to a `docker exec ...`).
* Cf. https://aws.amazon.com/blogs/containers/new-using-amazon-ecs-exec-access-your-containers-fargate-ec2/
*/
private boolean enableExecuteCommand;
@DataBoundConstructor
public ECSTaskTemplate(String templateName,
@Nullable String label,
@Nullable String agentContainerName,
@Nullable String taskDefinitionOverride,
@Nullable String dynamicTaskDefinitionOverride,
String image,
@Nullable final String repositoryCredentials,
@Nullable String launchType,
@Nullable String operatingSystemFamily,
@Nullable String cpuArchitecture,
boolean defaultCapacityProvider,
@Nullable List<CapacityProviderStrategyEntry> capacityProviderStrategies,
String networkMode,
@Nullable String remoteFSRoot,
boolean uniqueRemoteFSRoot,
String platformVersion,
int memory,
int memoryReservation,
int cpu,
@Nullable Integer ephemeralStorageSizeInGiB,
@Nullable String subnets,
@Nullable String securityGroups,
boolean assignPublicIp,
boolean privileged,
@Nullable String containerUser,
@Nullable String kernelCapabilities,
@Nullable List<LogDriverOption> logDriverOptions,
@Nullable List<Tag> tags,
@Nullable List<EnvironmentEntry> environments,
@Nullable List<ExtraHostEntry> extraHosts,
@Nullable List<MountPointEntry> mountPoints,
@Nullable List<EFSMountPointEntry> efsMountPoints,
@Nullable List<PortMappingEntry> portMappings,
@Nullable List<UlimitEntry> ulimits,
@Nullable String executionRole,
@Nullable List<PlacementStrategyEntry> placementStrategies,
@Nullable String taskrole,
@Nullable String inheritFrom,
int sharedMemorySize,
boolean enableExecuteCommand) {
// if the user enters a task definition override, always prefer to use it, rather than the jenkins template.
if (taskDefinitionOverride != null && !taskDefinitionOverride.trim().isEmpty()) {
this.taskDefinitionOverride = taskDefinitionOverride.trim();
if (agentContainerName != null && !agentContainerName.trim().isEmpty()) {
this.agentContainerName = agentContainerName.trim();
} else {
this.agentContainerName = null;
}
// Always set the template name to the empty string if we are using a task definition override,
// since we don't want Jenkins to touch our definitions.
this.templateName = "";
} else {
// If the template name is empty we will add a default name and a
// random element that will help to find it later when we want to delete it.
this.templateName = templateName.isEmpty() ?
"jenkinsTask-" + UUID.randomUUID().toString() : templateName;
// Make sure we don't have both a template name and a task definition override.
this.taskDefinitionOverride = null;
// An agent container name doesn't make sense when there is only one container
// definition.
this.agentContainerName = null;
}
this.label = label;
this.image = image;
this.repositoryCredentials = StringUtils.trimToNull(repositoryCredentials);
this.remoteFSRoot = remoteFSRoot;
this.uniqueRemoteFSRoot = uniqueRemoteFSRoot;
this.platformVersion = platformVersion;
this.memory = memory;
this.memoryReservation = memoryReservation;
this.cpu = cpu;
this.ephemeralStorageSizeInGiB = ephemeralStorageSizeInGiB;
this.launchType = launchType;
this.operatingSystemFamily = operatingSystemFamily;
this.cpuArchitecture = cpuArchitecture;
this.defaultCapacityProvider = defaultCapacityProvider;
this.capacityProviderStrategies = capacityProviderStrategies;
this.networkMode = networkMode;
this.subnets = subnets;
this.securityGroups = securityGroups;
this.assignPublicIp = assignPublicIp;
this.privileged = privileged;
this.containerUser = StringUtils.trimToNull(containerUser);
this.kernelCapabilities = StringUtils.trimToNull(kernelCapabilities);
this.logDriverOptions = logDriverOptions;
this.tags = tags;
this.environments = environments;
this.extraHosts = extraHosts;
this.mountPoints = mountPoints;
this.efsMountPoints = efsMountPoints;
this.portMappings = portMappings;
this.ulimits = ulimits;
this.executionRole = executionRole;
this.placementStrategies = placementStrategies;
this.taskrole = taskrole;
this.inheritFrom = inheritFrom;
this.sharedMemorySize = sharedMemorySize;
this.dynamicTaskDefinitionOverride = StringUtils.trimToNull(dynamicTaskDefinitionOverride);
this.enableExecuteCommand = enableExecuteCommand;
}
@DataBoundSetter
public void setDynamicTaskDefinition(String dynamicTaskDefArn) {
this.dynamicTaskDefinitionOverride = StringUtils.trimToNull(dynamicTaskDefArn);
}
@DataBoundSetter
public void setTaskrole(String taskRoleArn) {
this.taskrole = StringUtils.trimToNull(taskRoleArn);
}
@DataBoundSetter
public void setExecutionRole(String executionRole) {
this.executionRole = StringUtils.trimToNull(executionRole);
}
@DataBoundSetter
public void setRepositoryCredentials(final String repositoryCredentials) {
this.repositoryCredentials = StringUtils.trimToNull(repositoryCredentials);
}
@DataBoundSetter
public void setEntrypoint(String entrypoint) {
this.entrypoint = StringUtils.trimToNull(entrypoint);
}
@DataBoundSetter
public void setJvmArgs(String jvmArgs) {
this.jvmArgs = StringUtils.trimToNull(jvmArgs);
}
@DataBoundSetter
public void setContainerUser(String containerUser) {
this.containerUser = StringUtils.trimToNull(containerUser);
}
@DataBoundSetter
public void setKernelCapabilities(String kernelCapabilities) {
this.kernelCapabilities = StringUtils.trimToNull(kernelCapabilities);
}
@DataBoundSetter
public void setLogDriver(String logDriver) {
this.logDriver = StringUtils.trimToNull(logDriver);
}
@DataBoundSetter
public void setInheritFrom(String inheritFrom) {
this.inheritFrom = inheritFrom;
}
@DataBoundSetter
public void setSubnets(String subnets) { this.subnets = StringUtils.trimToNull(subnets); }
@DataBoundSetter
public void setSecurityGroups(String securityGroups) { this.securityGroups = StringUtils.trimToNull(securityGroups); }
@DataBoundSetter
public void setDnsSearchDomains(String dnsSearchDomains) {
this.dnsSearchDomains = StringUtils.trimToNull(dnsSearchDomains);
}
public boolean isFargate() {
if (!this.defaultCapacityProvider && this.capacityProviderStrategies != null && ! this.capacityProviderStrategies.isEmpty()) {
for (CapacityProviderStrategyEntry capacityProviderStrategy : this.capacityProviderStrategies) {
String provider = capacityProviderStrategy.provider;
if (provider.contains(LaunchType.FARGATE.toString())) {
return true;
}
}
return false;
}
return StringUtils.trimToNull(this.launchType) != null && launchType.equals(LaunchType.FARGATE.toString());
}
public boolean isEC2() {
return StringUtils.trimToNull(this.launchType) != null && launchType.equals(LaunchType.EC2.toString());
}
public String getLabel() {
return label;
}
public String getAgentContainerName() {
return agentContainerName;
}
public String getTaskDefinitionOverride() {
return taskDefinitionOverride;
}
public String getDynamicTaskDefinition() {
return dynamicTaskDefinitionOverride;
}
public String getImage() {
return image;
}
public String getRemoteFSRoot() {
return remoteFSRoot;
}
public String makeRemoteFSRoot(@Nonnull String name) {
if (!uniqueRemoteFSRoot || remoteFSRoot == null) {
return remoteFSRoot;
}
return remoteFSRoot + "/" + name;
}
public boolean getUniqueRemoteFSRoot() {
return uniqueRemoteFSRoot;
}
public String getPlatformVersion() {
return platformVersion;
}
public int getMemory() {
return memory;
}
public int getMemoryReservation() {
return memoryReservation;
}
public int getCpu() {
return cpu;
}
public int getSharedMemorySize() { return sharedMemorySize; }
public Integer getEphemeralStorageSizeInGiB() {
return ephemeralStorageSizeInGiB;
}
public String getSubnets() {
return subnets;
}
public String getSecurityGroups() {
return securityGroups;
}
public boolean getAssignPublicIp() {
return assignPublicIp;
}
public boolean getDefaultCapacityProvider() {
return defaultCapacityProvider;
}
public String getDnsSearchDomains() {
return dnsSearchDomains;
}
public String getEntrypoint() {
return entrypoint;
}
public String getTaskrole() {
return taskrole;
}
public String getExecutionRole() {
return executionRole;
}
public String getRepositoryCredentials() {
return repositoryCredentials;
}
public String getJvmArgs() {
return jvmArgs;
}
public boolean getPrivileged() {
return privileged;
}
public String getContainerUser() {
return containerUser;
}
public String getKernelCapabilities() {
return kernelCapabilities;
}
public String getLaunchType() {
if (StringUtils.trimToNull(this.launchType) == null) {
return LaunchType.
EC2.toString();
}
return launchType;
}
public String getOperatingSystemFamily() {
if (StringUtils.trimToNull(this.operatingSystemFamily) == null) {
return OSFamily.
LINUX.toString();
}
return operatingSystemFamily;
}
public String getCpuArchitecture() {
if (StringUtils.trimToNull(this.cpuArchitecture) == null) {
return CPUArchitecture.
X86_64.toString();
}
return cpuArchitecture;
}
public String getNetworkMode() {
return networkMode;
}
public String getLogDriver() {
return logDriver;
}
public String getInheritFrom() {
return inheritFrom;
}
public String getTemplateName() {return templateName; }
public boolean isEnableExecuteCommand() {
return enableExecuteCommand;
}
@Override
public String toString() {
return Arrays.stream(this.getClass().getDeclaredFields()).filter(f -> !Modifier.isStatic(f.getModifiers()) ).map(f -> {
try {
return String.format("%s: %s",f.getName(),f.get(this));
} catch (IllegalAccessException e) {
throw new RuntimeException();
}
}).collect(Collectors.joining("\n"));
}
public static class LogDriverOption extends AbstractDescribableImpl<LogDriverOption> implements Serializable {
private static final long serialVersionUID = 8585792353105873086L;
public String name, value;
@DataBoundConstructor
public LogDriverOption(String name, String value) {
this.name = name;
this.value = value;
}
@Override
public String toString() {
return "LogDriverOption{" + name + ": " + value + "}";
}
@Extension
public static class DescriptorImpl extends Descriptor<LogDriverOption> {
@Override
public String getDisplayName() {
return "logDriverOption";
}
}
}
public List<LogDriverOption> getLogDriverOptions() {
return logDriverOptions;
}
public static class Tag extends AbstractDescribableImpl<Tag> implements Serializable {
private static final long serialVersionUID = 4357423231051873086L;
public String name, value;
@DataBoundConstructor
public Tag(String name, String value) {
this.name = name;
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tag tag = (Tag) o;
return Objects.equals(name, tag.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
@Override
public String toString() {
return "Tag{" + name + ": " + value + "}";
}
@Extension
public static class DescriptorImpl extends Descriptor<Tag> {
@Override
public String getDisplayName() {
return "tag";
}
}
}
public List<Tag> getTags() { return tags; }
Map<String,String> getLogDriverOptionsMap() {
if (null == logDriverOptions || logDriverOptions.isEmpty()) {
return null;
}
Map<String,String> options = new HashMap<String,String>();
for (LogDriverOption logDriverOption : logDriverOptions) {
String name = logDriverOption.name;
String value = logDriverOption.value;
if (StringUtils.isEmpty(name) || StringUtils.isEmpty(value)) {
continue;
}
options.put(name, value);
}
return options;
}
Map<String,String> getTagsMap() {
if (null == tags || tags.isEmpty()) {
return null;
}
Map<String,String> options = new HashMap<String,String>();
for (Tag tag : tags) {
String name = tag.name;
String value = tag.value;
if (StringUtils.isEmpty(name) || StringUtils.isEmpty(value)) {
continue;
}
options.put(name, value);
}
return options;
}
public List<EnvironmentEntry> getEnvironments() {
return environments;
}
public List<ExtraHostEntry> getExtraHosts() {
return extraHosts;
}
public List<PortMappingEntry> getPortMappings() {
return portMappings;
}
public List<UlimitEntry> getUlimits() {
return ulimits;
}
public List<PlacementStrategyEntry> getPlacementStrategies() {
return placementStrategies;
}
public List<CapacityProviderStrategyEntry> getCapacityProviderStrategies() {
return capacityProviderStrategies;
}
/**
* This merge does not take an into consideration the child intentionally setting empty values for parameters like "entrypoint" - in fact
* it's not uncommon to override the entrypoint of a container and set it to blank so you can use your own entrypoint as part of the command.
* What's really needed is a "MergeStrategy <pre>BinaryOperator<ECSTaskTemplate></pre> that's user selectable.
*
* @param parent inherit settings from
* @return a 'merged' template
*/
public ECSTaskTemplate merge(ECSTaskTemplate parent) {
if(parent == null) {
return this;
}
String templateName = isNullOrEmpty(this.templateName) ? parent.getTemplateName() : this.templateName;
String label = isNullOrEmpty(this.label) ? parent.getLabel() : this.label;
String agentContainerName = isNullOrEmpty(this.agentContainerName) ? parent.getAgentContainerName() : this.agentContainerName;
String taskDefinitionOverride = isNullOrEmpty(this.taskDefinitionOverride) ? parent.getTaskDefinitionOverride() : this.taskDefinitionOverride;
String image = isNullOrEmpty(this.image) ? parent.getImage() : this.image;
String repositoryCredentials = isNullOrEmpty(this.repositoryCredentials) ? parent.getRepositoryCredentials() : this.repositoryCredentials;
String launchType = isNullOrEmpty(this.launchType) ? parent.getLaunchType() : this.launchType;
String operatingSystemFamily = isNullOrEmpty(this.operatingSystemFamily) ? parent.getOperatingSystemFamily() : this.operatingSystemFamily;
String cpuArchitecture = isNullOrEmpty(this.cpuArchitecture) ? parent.getCpuArchitecture() : this.cpuArchitecture;
boolean defaultCapacityProvider = this.defaultCapacityProvider ? this.defaultCapacityProvider : parent.getDefaultCapacityProvider();
String networkMode = isNullOrEmpty(this.networkMode) ? parent.getNetworkMode() : this.networkMode;
String remoteFSRoot = isNullOrEmpty(this.remoteFSRoot) ? parent.getRemoteFSRoot() : this.remoteFSRoot;
// Bug potential here. If I intenionally set it false in the child, then it will be ignored and take the parent. Need null to mean 'unset'
boolean uniqueRemoteFSRoot = this.uniqueRemoteFSRoot || parent.getUniqueRemoteFSRoot();
String platformVersion = isNullOrEmpty(this.platformVersion) ? parent.getPlatformVersion() : this.platformVersion;
int memory = this.memory == 0 ? parent.getMemory() : this.memory;
int memoryReservation = this.memoryReservation == 0 ? parent.getMemoryReservation() : this.memoryReservation;
int cpu = this.cpu == 0 ? parent.getCpu() : this.cpu;
Integer ephemeralStorageSizeInGiB = this.ephemeralStorageSizeInGiB == null ? parent.getEphemeralStorageSizeInGiB() : this.ephemeralStorageSizeInGiB;
int sharedMemorySize = this.sharedMemorySize == 0 ? parent.getSharedMemorySize() : this.sharedMemorySize;
String subnets = isNullOrEmpty(this.subnets) ? parent.getSubnets() : this.subnets;
String securityGroups = isNullOrEmpty(this.securityGroups) ? parent.getSecurityGroups() : this.securityGroups;
// Bug potential here. If I intenionally set it false in the child, then it will be ignored and take the parent. Need null to mean 'unset'
boolean assignPublicIp = this.assignPublicIp ? this.assignPublicIp : parent.getAssignPublicIp();
// Bug potential here. If I intenionally set it false in the child, then it will be ignored and take the parent. Need null to mean 'unset'
boolean privileged = this.privileged ? this.privileged : parent.getPrivileged();
String containerUser = isNullOrEmpty(this.containerUser) ? parent.getContainerUser() : this.containerUser;
String kernelCapabilities = isNullOrEmpty(this.kernelCapabilities) ? parent.getKernelCapabilities() : this.kernelCapabilities;
String logDriver = isNullOrEmpty(this.logDriver) ? parent.getLogDriver() : this.logDriver;
String entrypoint = isNullOrEmpty(this.entrypoint) ? parent.getEntrypoint() : this.entrypoint;
Set<Tag> mergedTagsSet = new HashSet<>(isEmpty(this.tags) ? new ArrayList<>() : this.tags);
Optional.ofNullable(parent.getTags()).ifPresent(mergedTagsSet::addAll);
List<Tag> tags = new ArrayList<>(mergedTagsSet);
// TODO probably merge lists with parent instead of overriding them
List<LogDriverOption> logDriverOptions = isEmpty(this.logDriverOptions) ? parent.getLogDriverOptions() : this.logDriverOptions;
List<EnvironmentEntry> environments = isEmpty(this.environments) ? parent.getEnvironments() : this.environments;
List<ExtraHostEntry> extraHosts = isEmpty(this.extraHosts) ? parent.getExtraHosts() : this.extraHosts;
List<MountPointEntry> mountPoints = isEmpty(this.mountPoints) ? parent.getMountPoints() : this.mountPoints;
List<EFSMountPointEntry> efsMountPoints = isEmpty(this.efsMountPoints) ? parent.getEfsMountPoints() : this.efsMountPoints;
List<PortMappingEntry> portMappings = isEmpty(this.portMappings) ? parent.getPortMappings() : this.portMappings;
List<UlimitEntry> ulimits = isEmpty(this.ulimits) ? parent.getUlimits() : this.ulimits;
List<PlacementStrategyEntry> placementStrategies = isEmpty(this.placementStrategies) ? parent.getPlacementStrategies() : this.placementStrategies;
List<CapacityProviderStrategyEntry> capacityProviderStrategies = isEmpty(this.capacityProviderStrategies) ? parent.getCapacityProviderStrategies() : this.capacityProviderStrategies;
String executionRole = isNullOrEmpty(this.executionRole) ? parent.getExecutionRole() : this.executionRole;
String taskrole = isNullOrEmpty(this.taskrole) ? parent.getTaskrole() : this.taskrole;
boolean enableExecuteCommand = this.enableExecuteCommand ? true : parent.isEnableExecuteCommand();
ECSTaskTemplate merged = new ECSTaskTemplate(templateName,
label,
agentContainerName,
taskDefinitionOverride,
null,
image,
repositoryCredentials,
launchType,
operatingSystemFamily,
cpuArchitecture,
defaultCapacityProvider,
capacityProviderStrategies,
networkMode,
remoteFSRoot,
uniqueRemoteFSRoot,
platformVersion,
memory,
memoryReservation,
cpu,
ephemeralStorageSizeInGiB,
subnets,
securityGroups,
assignPublicIp,
privileged,
containerUser,
kernelCapabilities,
logDriverOptions,
tags,
environments,
extraHosts,
mountPoints,
efsMountPoints,
portMappings,
ulimits,
executionRole,
placementStrategies,
taskrole,
null,
sharedMemorySize,
enableExecuteCommand);
merged.setLogDriver(logDriver);
merged.setEntrypoint(entrypoint);
return merged;
}
Collection<KeyValuePair> getEnvironmentKeyValuePairs() {
if (null == environments || environments.isEmpty()) {
return null;
}
Collection<KeyValuePair> items = new ArrayList<KeyValuePair>();
for (EnvironmentEntry environment : environments) {
String name = environment.name;
String value = environment.value;
if (StringUtils.isEmpty(name) || StringUtils.isEmpty(value)) {
continue;
}
items.add(new KeyValuePair().withName(name).withValue(value));
}
return items;
}
Collection<HostEntry> getExtraHostEntries() {
if (null == extraHosts || extraHosts.isEmpty()) {
return null;
}
Collection<HostEntry> items = new ArrayList<HostEntry>();
for (ExtraHostEntry extrahost : extraHosts) {
String ipAddress = extrahost.ipAddress;
String hostname = extrahost.hostname;
if (StringUtils.isEmpty(ipAddress) || StringUtils.isEmpty(hostname)) {
continue;
}
items.add(new HostEntry().withIpAddress(ipAddress).withHostname(hostname));
}
return items;
}
public List<MountPointEntry> getMountPoints() {
return mountPoints;
}
public List<EFSMountPointEntry> getEfsMountPoints() {
return efsMountPoints;
}
Collection<Volume> getVolumeEntries() {
Collection<Volume> vols = new LinkedList<Volume>();
if (null != mountPoints ) {
for (MountPointEntry mount : mountPoints) {
String name = mount.name;
String sourcePath = mount.sourcePath;
HostVolumeProperties hostVolume = new HostVolumeProperties();
if (StringUtils.isEmpty(name))
continue;
if (! StringUtils.isEmpty(sourcePath))
hostVolume.setSourcePath(sourcePath);
vols.add(new Volume().withName(name)
.withHost(hostVolume));
}
}
if (null != efsMountPoints) {
for (EFSMountPointEntry mount : efsMountPoints) {
if (StringUtils.isEmpty(mount.name)) {
continue;
}
EFSAuthorizationConfig efsAuthorizationConfig = null;
if (StringUtils.isNotEmpty(mount.accessPointId)) {
efsAuthorizationConfig = new EFSAuthorizationConfig()
.withAccessPointId(mount.accessPointId)
.withIam(BooleanUtils.isTrue(mount.iam)