/
InstanceToNodeMapper.java
508 lines (452 loc) · 18.6 KB
/
InstanceToNodeMapper.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
/*
* Copyright 2011 DTO Solutions, Inc. (http://dtosolutions.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* NodeGenerator.java
*
* User: Greg Schueler <a href="mailto:greg@dtosolutions.com">greg@dtosolutions.com</a>
* Created: Oct 18, 2010 7:03:37 PM
*
*/
package com.dtolabs.rundeck.plugin.resources.ec2;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.ec2.AmazonEC2AsyncClient;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.*;
import com.dtolabs.rundeck.core.common.INodeEntry;
import com.dtolabs.rundeck.core.common.INodeSet;
import com.dtolabs.rundeck.core.common.NodeEntryImpl;
import com.dtolabs.rundeck.core.common.NodeSetImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* InstanceToNodeMapper produces Rundeck node definitions from EC2 Instances
*
* @author Greg Schueler <a href="mailto:greg@dtosolutions.com">greg@dtosolutions.com</a>
*/
class InstanceToNodeMapper {
static final Logger logger = Logger.getLogger(InstanceToNodeMapper.class);
final AWSCredentials credentials;
private ClientConfiguration clientConfiguration;
private ExecutorService executorService = Executors.newSingleThreadExecutor();
private ArrayList<String> filterParams;
private String endpoint;
private boolean runningStateOnly = true;
private Properties mapping;
/**
* Create with the credentials and mapping definition
*/
InstanceToNodeMapper(final AWSCredentials credentials, final Properties mapping, final ClientConfiguration clientConfiguration) {
this.credentials = credentials;
this.mapping = mapping;
this.clientConfiguration = clientConfiguration;
}
/**
* Perform the query and return the set of instances
*
*/
public INodeSet performQuery() {
final NodeSetImpl nodeSet = new NodeSetImpl();
final AmazonEC2Client ec2 ;
if(null!=credentials) {
ec2 = new AmazonEC2Client(credentials, clientConfiguration);
} else{
ec2 = new AmazonEC2Client(clientConfiguration);
}
if (null != getEndpoint()) {
ec2.setEndpoint(getEndpoint());
}
final ArrayList<Filter> filters = buildFilters();
final Set<Instance> instances = query(ec2, new DescribeInstancesRequest().withFilters(filters));
mapInstances(nodeSet, instances);
return nodeSet;
}
/**
* Perform the query asynchronously and return the set of instances
*
*/
public Future<INodeSet> performQueryAsync() {
final AmazonEC2AsyncClient ec2 ;
if(null!=credentials){
ec2= new AmazonEC2AsyncClient(credentials, clientConfiguration, executorService);
} else{
ec2 = new AmazonEC2AsyncClient(new DefaultAWSCredentialsProviderChain(), clientConfiguration, executorService);
}
if (null != getEndpoint()) {
ec2.setEndpoint(getEndpoint());
}
final ArrayList<Filter> filters = buildFilters();
final Future<DescribeInstancesResult> describeInstancesRequest = ec2.describeInstancesAsync(
new DescribeInstancesRequest().withFilters(filters));
return new Future<INodeSet>() {
public boolean cancel(boolean b) {
return describeInstancesRequest.cancel(b);
}
public boolean isCancelled() {
return describeInstancesRequest.isCancelled();
}
public boolean isDone() {
return describeInstancesRequest.isDone();
}
public INodeSet get() throws InterruptedException, ExecutionException {
DescribeInstancesResult describeInstancesResult = describeInstancesRequest.get();
final NodeSetImpl nodeSet = new NodeSetImpl();
final Set<Instance> instances = examineResult(describeInstancesResult);
mapInstances(nodeSet, instances);
return nodeSet;
}
public INodeSet get(final long l, final TimeUnit timeUnit) throws InterruptedException, ExecutionException,
TimeoutException {
DescribeInstancesResult describeInstancesResult = describeInstancesRequest.get(l, timeUnit);
final NodeSetImpl nodeSet = new NodeSetImpl();
final Set<Instance> instances = examineResult(describeInstancesResult);
mapInstances(nodeSet, instances);
return nodeSet;
}
};
}
private Set<Instance> query(final AmazonEC2Client ec2, final DescribeInstancesRequest request) {
//create "running" filter
final DescribeInstancesResult describeInstancesRequest = ec2.describeInstances(request);
return examineResult(describeInstancesRequest);
}
private Set<Instance> examineResult(DescribeInstancesResult describeInstancesRequest) {
final List<Reservation> reservations = describeInstancesRequest.getReservations();
final Set<Instance> instances = new HashSet<Instance>();
for (final Reservation reservation : reservations) {
instances.addAll(reservation.getInstances());
}
return instances;
}
private ArrayList<Filter> buildFilters() {
final ArrayList<Filter> filters = new ArrayList<Filter>();
if (isRunningStateOnly()) {
final Filter filter = new Filter("instance-state-name").withValues(InstanceStateName.Running.toString());
filters.add(filter);
}
if (null != getFilterParams()) {
for (final String filterParam : getFilterParams()) {
final String[] x = filterParam.split("=", 2);
if (!"".equals(x[0]) && !"".equals(x[1])) {
filters.add(new Filter(x[0]).withValues(x[1].split(",")));
}
}
}
return filters;
}
private void mapInstances(final NodeSetImpl nodeSet, final Set<Instance> instances) {
for (final Instance inst : instances) {
final INodeEntry iNodeEntry;
try {
iNodeEntry = InstanceToNodeMapper.instanceToNode(inst, mapping);
if (null != iNodeEntry) {
nodeSet.putNode(iNodeEntry);
}
} catch (GeneratorException e) {
logger.error(e);
}
}
}
/**
* Convert an AWS EC2 Instance to a RunDeck INodeEntry based on the mapping input
*/
@SuppressWarnings("unchecked")
static INodeEntry instanceToNode(final Instance inst, final Properties mapping) throws GeneratorException {
final NodeEntryImpl node = new NodeEntryImpl();
//evaluate single settings.selector=tags/* mapping
if ("tags/*".equals(mapping.getProperty("attributes.selector"))) {
//iterate through instance tags and generate settings
for (final Tag tag : inst.getTags()) {
if (null == node.getAttributes()) {
node.setAttributes(new HashMap<String, String>());
}
node.getAttributes().put(tag.getKey(), tag.getValue());
}
}
if (null != mapping.getProperty("tags.selector")) {
final String selector = mapping.getProperty("tags.selector");
final String value = applySelector(inst, selector, mapping.getProperty("tags.default"), true);
if (null != value) {
final String[] values = value.split(",");
final HashSet<String> tagset = new HashSet<String>();
for (final String s : values) {
tagset.add(s.trim());
}
if (null == node.getTags()) {
node.setTags(tagset);
} else {
final HashSet orig = new HashSet(node.getTags());
orig.addAll(tagset);
node.setTags(orig);
}
}
}
if (null == node.getTags()) {
node.setTags(new HashSet());
}
final HashSet orig = new HashSet(node.getTags());
//apply specific tag selectors
final Pattern tagPat = Pattern.compile("^tag\\.(.+?)\\.selector$");
//evaluate tag selectors
for (final Object o : mapping.keySet()) {
final String key = (String) o;
final String selector = mapping.getProperty(key);
//split selector by = if present
final String[] selparts = selector.split("=");
final Matcher m = tagPat.matcher(key);
if (m.matches()) {
final String tagName = m.group(1);
if (null == node.getAttributes()) {
node.setAttributes(new HashMap<String, String>());
}
final String value = applySelector(inst, selparts[0], null);
if (null != value) {
if (selparts.length > 1 && !value.equals(selparts[1])) {
continue;
}
//use add the tag if the value is not null
orig.add(tagName);
}
}
}
node.setTags(orig);
//apply default values which do not have corresponding selector
final Pattern attribDefPat = Pattern.compile("^([^.]+?)\\.default$");
//evaluate selectors
for (final Object o : mapping.keySet()) {
final String key = (String) o;
final String value = mapping.getProperty(key);
final Matcher m = attribDefPat.matcher(key);
if (m.matches() && (!mapping.containsKey(key + ".selector") || "".equals(mapping.getProperty(
key + ".selector")))) {
final String attrName = m.group(1);
if (null == node.getAttributes()) {
node.setAttributes(new HashMap<String, String>());
}
if (null != value) {
node.getAttributes().put(attrName, value);
}
}
}
final Pattern attribPat = Pattern.compile("^([^.]+?)\\.selector$");
//evaluate selectors
for (final Object o : mapping.keySet()) {
final String key = (String) o;
final String selector = mapping.getProperty(key);
final Matcher m = attribPat.matcher(key);
if (m.matches()) {
final String attrName = m.group(1);
if(attrName.equals("tags")){
//already handled
continue;
}
if (null == node.getAttributes()) {
node.setAttributes(new HashMap<String, String>());
}
final String value = applySelector(inst, selector, mapping.getProperty(attrName + ".default"));
if (null != value) {
//use nodename-settingname to make the setting unique to the node
node.getAttributes().put(attrName, value);
}
}
}
// String hostSel = mapping.getProperty("hostname.selector");
// String host = applySelector(inst, hostSel, mapping.getProperty("hostname.default"));
// if (null == node.getHostname()) {
// System.err.println("Unable to determine hostname for instance: " + inst.getInstanceId());
// return null;
// }
String name = node.getNodename();
if (null == name || "".equals(name)) {
name = node.getHostname();
}
if (null == name || "".equals(name)) {
name = inst.getInstanceId();
}
node.setNodename(name);
// Set ssh port on hostname if not 22
String sshport = node.getAttributes().get("sshport");
if (sshport != null && !sshport.equals("") && !sshport.equals("22")) {
node.setHostname(node.getHostname() + ":" + sshport);
}
return node;
}
/**
* Return the result of the selector applied to the instance, otherwise return the defaultValue. The selector can be
* a comma-separated list of selectors
*/
public static String applySelector(final Instance inst, final String selector, final String defaultValue) throws
GeneratorException {
return applySelector(inst, selector, defaultValue, false);
}
/**
* Return the result of the selector applied to the instance, otherwise return the defaultValue. The selector can be
* a comma-separated list of selectors.
* @param inst the instance
* @param selector the selector string
* @param defaultValue a default value to return if there is no result from the selector
* @param tagMerge if true, allow | separator to merge multiple values
*/
public static String applySelector(final Instance inst, final String selector, final String defaultValue,
final boolean tagMerge) throws
GeneratorException {
if (null != selector) {
for (final String selPart : selector.split(",")) {
if (tagMerge) {
final StringBuilder sb = new StringBuilder();
for (final String subPart : selPart.split(Pattern.quote("|"))) {
final String val = applyMultiSelector(inst, subPart.split(Pattern.quote("+")));
if (null != val) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(val);
}
}
if (sb.length() > 0) {
return sb.toString();
}
} else {
final String val = applyMultiSelector(inst, selPart.split(Pattern.quote("+")));
if (null != val) {
return val;
}
}
}
}
return defaultValue;
}
private static final Pattern quoted = Pattern.compile("^(['\"])(.+)\\1$");
/**
* Return conjoined multiple selector and literal values only if some selector value matches, otherwise null.
* Apply multiple selectors and separators to determine the value, the selector values are conjoined
* in order if they resolve to a non-blank value. If a selector is a quoted string, the contents are
* conjoined literally
*
* @param inst
* @param selectors
*
* @return conjoined selector values with literal separators, if some selector was resolved, otherwise null
*
* @throws GeneratorException
*/
static String applyMultiSelector(final Instance inst, final String... selectors) throws
GeneratorException
{
StringBuilder sb = new StringBuilder();
boolean hasVal = false;
for (String selector : selectors) {
Matcher matcher = quoted.matcher(selector);
if (matcher.matches()) {
sb.append(matcher.group(2));
} else {
String val = applySingleSelector(inst, selector);
if (null != val && !"".equals(val)) {
hasVal = true;
sb.append(val);
}
}
}
return hasVal ? sb.toString() : null;
}
static String applySingleSelector(final Instance inst, final String selector) throws
GeneratorException {
if (null != selector && !"".equals(selector) && selector.startsWith("tags/")) {
final String tag = selector.substring("tags/".length());
final List<Tag> tags = inst.getTags();
for (final Tag tag1 : tags) {
if (tag.equals(tag1.getKey())) {
return tag1.getValue();
}
}
} else if (null != selector && !"".equals(selector)) {
try {
final String value = BeanUtils.getProperty(inst, selector);
if (null != value) {
return value;
}
} catch (Exception e) {
throw new GeneratorException(e);
}
}
return null;
}
/**
* Return the list of "filter=value" filters
*/
public ArrayList<String> getFilterParams() {
return filterParams;
}
/**
* Return the endpoint
*/
public String getEndpoint() {
return endpoint;
}
/**
* Return true if runningStateOnly
*/
public boolean isRunningStateOnly() {
return runningStateOnly;
}
/**
* If true, the an automatic "running" state filter will be applied
*/
public void setRunningStateOnly(final boolean runningStateOnly) {
this.runningStateOnly = runningStateOnly;
}
/**
* Set the list of "filter=value" filters
*/
public void setFilterParams(final ArrayList<String> filterParams) {
this.filterParams = filterParams;
}
/**
* Set the region endpoint to use.
*/
public void setEndpoint(final String endpoint) {
this.endpoint = endpoint;
}
public Properties getMapping() {
return mapping;
}
public void setMapping(Properties mapping) {
this.mapping = mapping;
}
public static class GeneratorException extends Exception {
public GeneratorException() {
}
public GeneratorException(final String message) {
super(message);
}
public GeneratorException(final String message, final Throwable cause) {
super(message, cause);
}
public GeneratorException(final Throwable cause) {
super(cause);
}
}
}