1 | /** |
2 | * Licensed to jclouds, Inc. (jclouds) under one or more |
3 | * contributor license agreements. See the NOTICE file |
4 | * distributed with this work for additional information |
5 | * regarding copyright ownership. jclouds licenses this file |
6 | * to you under the Apache License, Version 2.0 (the |
7 | * "License"); you may not use this file except in compliance |
8 | * with the License. You may obtain a copy of the License at |
9 | * |
10 | * http://www.apache.org/licenses/LICENSE-2.0 |
11 | * |
12 | * Unless required by applicable law or agreed to in writing, |
13 | * software distributed under the License is distributed on an |
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
15 | * KIND, either express or implied. See the License for the |
16 | * specific language governing permissions and limitations |
17 | * under the License. |
18 | */ |
19 | package org.jclouds.ec2.compute.strategy; |
20 | |
21 | import static com.google.common.base.Preconditions.checkNotNull; |
22 | import static com.google.common.collect.Iterables.getOnlyElement; |
23 | |
24 | import java.util.NoSuchElementException; |
25 | |
26 | import javax.inject.Inject; |
27 | import javax.inject.Singleton; |
28 | |
29 | import org.jclouds.aws.util.AWSUtils; |
30 | import org.jclouds.compute.domain.NodeMetadata; |
31 | import org.jclouds.compute.strategy.GetNodeMetadataStrategy; |
32 | import org.jclouds.ec2.EC2Client; |
33 | import org.jclouds.ec2.domain.RunningInstance; |
34 | |
35 | import com.google.common.base.Function; |
36 | import com.google.common.collect.Iterables; |
37 | |
38 | /** |
39 | * |
40 | * @author Adrian Cole |
41 | */ |
42 | @Singleton |
43 | public class EC2GetNodeMetadataStrategy implements GetNodeMetadataStrategy { |
44 | |
45 | private final EC2Client client; |
46 | private final Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata; |
47 | |
48 | @Inject |
49 | protected EC2GetNodeMetadataStrategy(EC2Client client, |
50 | Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata) { |
51 | this.client = checkNotNull(client, "client"); |
52 | this.runningInstanceToNodeMetadata = checkNotNull(runningInstanceToNodeMetadata, "runningInstanceToNodeMetadata"); |
53 | } |
54 | |
55 | @Override |
56 | public NodeMetadata getNode(String id) { |
57 | checkNotNull(id, "id"); |
58 | String[] parts = AWSUtils.parseHandle(id); |
59 | String region = parts[0]; |
60 | String instanceId = parts[1]; |
61 | try { |
62 | RunningInstance runningInstance = getRunningInstanceInRegion(region, instanceId); |
63 | return runningInstanceToNodeMetadata.apply(runningInstance); |
64 | } catch (NoSuchElementException e) { |
65 | return null; |
66 | } |
67 | } |
68 | |
69 | public RunningInstance getRunningInstanceInRegion(String region, String id) { |
70 | return getOnlyElement(Iterables.concat(client.getInstanceServices().describeInstancesInRegion(region, id))); |
71 | } |
72 | |
73 | } |