1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.jclouds.vcloud.terremark.compute.strategy;
20
21 import static com.google.common.base.Predicates.notNull;
22 import static com.google.common.collect.Iterables.all;
23 import static com.google.common.collect.Iterables.filter;
24 import static com.google.common.collect.Iterables.size;
25 import static com.google.common.collect.Iterables.transform;
26 import static org.jclouds.compute.predicates.NodePredicates.TERMINATED;
27 import static org.jclouds.compute.predicates.NodePredicates.parentLocationId;
28 import static org.jclouds.compute.predicates.NodePredicates.inGroup;
29
30 import java.util.Map;
31
32 import javax.inject.Inject;
33 import javax.inject.Singleton;
34
35 import org.jclouds.compute.domain.NodeMetadata;
36 import org.jclouds.compute.strategy.ListNodesStrategy;
37 import org.jclouds.domain.Credentials;
38 import org.jclouds.vcloud.terremark.compute.domain.OrgAndName;
39
40 import com.google.common.base.Function;
41
42
43
44
45
46
47 @Singleton
48 public class CleanupOrphanKeys {
49 final Function<NodeMetadata, OrgAndName> nodeToOrgAndName;
50 final DeleteKeyPair deleteKeyPair;
51 final ListNodesStrategy listNodes;
52 final Map<String, Credentials> credentialStore;
53
54 @Inject
55 CleanupOrphanKeys(Function<NodeMetadata, OrgAndName> nodeToOrgAndName, DeleteKeyPair deleteKeyPair,
56 Map<String, Credentials> credentialStore, ListNodesStrategy listNodes) {
57 this.nodeToOrgAndName = nodeToOrgAndName;
58 this.deleteKeyPair = deleteKeyPair;
59 this.listNodes = listNodes;
60 this.credentialStore = credentialStore;
61 }
62
63 public void execute(Iterable<? extends NodeMetadata> deadOnes) {
64
65
66 for (NodeMetadata node : deadOnes){
67 credentialStore.remove("node#" + node.getId());
68 credentialStore.remove("node#" + node.getId() + "#adminPassword");
69 }
70 Iterable<OrgAndName> orgGroups = filter(transform(deadOnes, nodeToOrgAndName), notNull());
71 for (OrgAndName orgGroup : orgGroups) {
72 Iterable<? extends NodeMetadata> nodesInOrg = listNodes.listDetailsOnNodesMatching(parentLocationId(orgGroup
73 .getOrg().toASCIIString()));
74 Iterable<? extends NodeMetadata> nodesInGroup = filter(nodesInOrg, inGroup(orgGroup.getName()));
75 if (size(nodesInGroup) == 0 || all(nodesInGroup, TERMINATED))
76 deleteKeyPair.execute(orgGroup);
77 }
78 }
79
80 }