Java源码示例:org.jclouds.compute.ComputeServiceContext
示例1
public static ComputeService buildDefaultComputeService(IaasProvider iaasProvider) {
Properties properties = new Properties();
// load properties
for (Map.Entry<String, String> entry : iaasProvider.getProperties().entrySet()) {
properties.put(entry.getKey(), entry.getValue());
}
// set modules
Iterable<Module> modules =
ImmutableSet.<Module>of(new SshjSshClientModule(), new SLF4JLoggingModule(),
new EnterpriseConfigurationModule());
// build context
ContextBuilder builder =
ContextBuilder.newBuilder(iaasProvider.getProvider())
.credentials(iaasProvider.getIdentity(), iaasProvider.getCredential()).modules(modules)
.overrides(properties);
return builder.buildView(ComputeServiceContext.class).getComputeService();
}
示例2
@Override
public boolean createKeyPairFromPublicKey(String region, String keyPairName, String publicKey) {
IaasProvider iaasInfo = getIaasProvider();
ComputeServiceContext context = iaasInfo.getComputeService().getContext();
CloudStackApi cloudStackApi = context.unwrapApi(CloudStackApi.class);
SshKeyPair sshKeyPair = cloudStackApi.getSSHKeyPairApi().createSSHKeyPair(keyPairName);
if (sshKeyPair != null) {
iaasInfo.getTemplate().getOptions().as(CloudStackTemplateOptions.class)
.keyPair(sshKeyPair.getName());
log.info("A key-pair is created successfully - Key Pair Name: " + sshKeyPair.getName());
return true;
}
log.error("Key-pair is unable to create");
return false;
}
示例3
@Override
public boolean isValidZone(String region, String zone) throws InvalidZoneException {
IaasProvider iaasInfo = getIaasProvider();
ComputeServiceContext context = iaasInfo.getComputeService().getContext();
CloudStackApi cloudStackApi = context.unwrapApi(CloudStackApi.class);
ListZonesOptions listZonesOptions = new ListZonesOptions();
listZonesOptions.available(true);
Set<Zone> zoneSet = cloudStackApi.getZoneApi().listZones(listZonesOptions);
for (org.jclouds.cloudstack.domain.Zone configuredZone : zoneSet) {
if (configuredZone.getName().equalsIgnoreCase(zone)) {
return true;
}
}
String msg = "Invalid zone: " + zone + " in the iaas: " + iaasInfo.getType();
log.error(msg);
throw new InvalidZoneException(msg);
}
示例4
@Override
public void deleteVolume(String volumeId) {
IaasProvider iaasInfo = getIaasProvider();
ComputeServiceContext context = iaasInfo.getComputeService().getContext();
String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
if (region == null) {
log.fatal("Cannot delete the volume [id]: " + volumeId + " of the [region] : " + region + " of Iaas : "
+ iaasInfo);
return;
}
ElasticBlockStoreApi blockStoreApi = context.unwrapApi(AWSEC2Api.class).getElasticBlockStoreApiForRegion(region)
.get();
blockStoreApi.deleteVolumeInRegion(region, volumeId);
log.info("Deletion of Volume [id]: " + volumeId + " was successful. [region] : " + region + " of Iaas : "
+ iaasInfo);
}
示例5
@Override
public void releaseAddress(String ip) {
ComputeServiceContext context = iaasProvider.getComputeService().getContext();
String region = ComputeServiceBuilderUtil.extractRegion(iaasProvider);
NovaApi novaApi = context.unwrapApi(NovaApi.class);
FloatingIPApi floatingIPApi = novaApi.getFloatingIPExtensionForZone(region).get();
for (FloatingIP floatingIP : floatingIPApi.list()) {
if (floatingIP.getIp().equals(ip)) {
floatingIPApi.delete(floatingIP.getId());
break;
}
}
}
示例6
@Override
public synchronized boolean createKeyPairFromPublicKey(String region, String keyPairName, String publicKey) {
IaasProvider iaasInfo = getIaasProvider();
String openstackNovaMsg = " Openstack-nova. Region: " + region + " - Name: ";
ComputeServiceContext context = iaasInfo.getComputeService().getContext();
NovaApi novaApi = context.unwrapApi(NovaApi.class);
KeyPairApi api = novaApi.getKeyPairExtensionForZone(region).get();
KeyPair keyPair = api.createWithPublicKey(keyPairName, publicKey);
if (keyPair != null) {
iaasInfo.getTemplate().getOptions().as(NovaTemplateOptions.class).keyPairName(keyPair.getName());
log.info(SUCCESSFUL_LOG_LINE + openstackNovaMsg + keyPair.getName());
return true;
}
log.error(FAILED_LOG_LINE + openstackNovaMsg);
return false;
}
示例7
public static ComputeServiceContext getComputeApiFromCarinaDirectory(String path) throws IOException {
// docker.ps1 contains the endpoint
String endpoint = "https://" +
Files.readFirstLine(new File(joinPath(path, "docker.ps1")),
Charset.forName("UTF-8")).split("=")[1].replace("\"", "").substring(6);
// enable logging and sshj
Iterable<Module> modules = ImmutableSet.<Module> of(new SLF4JLoggingModule(), new SshjSshClientModule());
Properties overrides = new Properties();
// disable certificate checking for Carina
overrides.setProperty("jclouds.trust-all-certs", "true");
return ContextBuilder.newBuilder("docker")
.credentials(joinPath(path, "cert.pem"), joinPath(path, "key.pem"))
.modules(modules)
.overrides(overrides)
.endpoint(endpoint)
.buildView(ComputeServiceContext.class);
}
示例8
public CloudServersPublish(List<String> args) {
String username = args.get(0);
String apiKey = args.get(1);
numServers = args.size() == 3 ? Integer.valueOf(args.get(2)) : 1;
Iterable<Module> modules = ImmutableSet.<Module> of(new SshjSshClientModule());
// These properties control how often jclouds polls for a status update
Properties overrides = new Properties();
overrides.setProperty(POLL_INITIAL_PERIOD, POLL_PERIOD_TWENTY_SECONDS);
overrides.setProperty(POLL_MAX_PERIOD, POLL_PERIOD_TWENTY_SECONDS);
ComputeServiceContext context = ContextBuilder.newBuilder(PROVIDER)
.credentials(username, apiKey)
.overrides(overrides)
.modules(modules)
.buildView(ComputeServiceContext.class);
computeService = context.getComputeService();
}
示例9
public CreateServerWithKeyPair(String username, String apiKey) {
Iterable<Module> modules = ImmutableSet.<Module> of(new SshjSshClientModule());
// These properties control how often jclouds polls for a status update
Properties overrides = new Properties();
overrides.setProperty(POLL_INITIAL_PERIOD, POLL_PERIOD_TWENTY_SECONDS);
overrides.setProperty(POLL_MAX_PERIOD, POLL_PERIOD_TWENTY_SECONDS);
ComputeServiceContext context = ContextBuilder.newBuilder(PROVIDER)
.credentials(username, apiKey)
.overrides(overrides)
.modules(modules)
.buildView(ComputeServiceContext.class);
computeService = context.getComputeService();
novaApi = context.unwrapApi(NovaApi.class);
}
示例10
public DetachVolume(String username, String apiKey) {
// The provider configures jclouds To use the Rackspace Cloud (US)
// To use the Rackspace Cloud (UK) set the system property or default value to "rackspace-cloudservers-uk"
String provider = System.getProperty("provider.cs", "rackspace-cloudservers-us");
Iterable<Module> modules = ImmutableSet.<Module> of(new SshjSshClientModule());
ComputeServiceContext context = ContextBuilder.newBuilder(provider)
.credentials(username, apiKey)
.modules(modules)
.buildView(ComputeServiceContext.class);
computeService = context.getComputeService();
NovaApi novaApi = context.unwrapApi(NovaApi.class);
serverApi = novaApi.getServerApi(REGION);
volumeAttachmentApi = novaApi.getVolumeAttachmentApi(REGION).get();
cinderApi = ContextBuilder.newBuilder(PROVIDER)
.credentials(username, apiKey)
.buildApi(CinderApi.class);
volumeApi = cinderApi.getVolumeApi(REGION);
}
示例11
public CreateVolumeAndAttach(String username, String apiKey) {
// The provider configures jclouds To use the Rackspace Cloud (US)
// To use the Rackspace Cloud (UK) set the system property or default value to "rackspace-cloudservers-uk"
String provider = System.getProperty("provider.cs", "rackspace-cloudservers-us");
// These properties control how often jclouds polls for a status udpate
Properties overrides = new Properties();
overrides.setProperty(POLL_INITIAL_PERIOD, POLL_PERIOD_TWENTY_SECONDS);
overrides.setProperty(POLL_MAX_PERIOD, POLL_PERIOD_TWENTY_SECONDS);
Iterable<Module> modules = ImmutableSet.<Module> of(new SshjSshClientModule());
ComputeServiceContext context = ContextBuilder.newBuilder(provider)
.credentials(username, apiKey)
.modules(modules)
.overrides(overrides)
.buildView(ComputeServiceContext.class);
computeService = context.getComputeService();
novaApi = context.unwrapApi(NovaApi.class);
volumeAttachmentApi = novaApi.getVolumeAttachmentApi(REGION).get();
cinderApi = ContextBuilder.newBuilder(PROVIDER)
.credentials(username, apiKey)
.buildApi(CinderApi.class);
volumeApi = cinderApi.getVolumeApi(REGION);
}
示例12
private static ComputeService initComputeService(final String provider, final String identity,
final String credential) {
// example of specific properties, in this case optimizing image list to
// only amazon supplied
Properties properties = new Properties();
long scriptTimeout = TimeUnit.MILLISECONDS.convert(20, TimeUnit.MINUTES);
properties.setProperty(TIMEOUT_SCRIPT_COMPLETE, scriptTimeout + "");
// example of injecting a ssh implementation
Iterable<Module> modules =
ImmutableSet.<Module>of(new SshjSshClientModule(), new SLF4JLoggingModule(),
new EnterpriseConfigurationModule());
ContextBuilder builder =
ContextBuilder.newBuilder(provider).credentials(identity, credential).modules(modules)
.overrides(properties);
System.out.printf(">> initializing %s%n", builder.getApiMetadata());
return builder.buildView(ComputeServiceContext.class).getComputeService();
}
示例13
public JCloudsConnector(String provider,String login,String secretKey){
journal.log(Level.INFO, ">> Connecting to "+provider+" ...");
Properties overrides = new Properties();
if(provider.equals("aws-ec2")){
// choose only amazon images that are ebs-backed
//overrides.setProperty(AWSEC2Constants.PROPERTY_EC2_AMI_OWNERS,"107378836295");
overrides.setProperty(AWSEC2Constants.PROPERTY_EC2_AMI_QUERY,
"owner-id=137112412989,107378836295,099720109477;state=available;image-type=machine;root-device-type=ebs");
}
overrides.setProperty(PROPERTY_CONNECTION_TIMEOUT, 0 + "");
overrides.setProperty(PROPERTY_SO_TIMEOUT, 0 + "");
overrides.setProperty(PROPERTY_REQUEST_TIMEOUT, 0 + "");
overrides.setProperty(PROPERTY_RETRY_DELAY_START, 0 + "");
Iterable<Module> modules = ImmutableSet.<Module> of(
new SshjSshClientModule(),
new NullLoggingModule());
ContextBuilder builder = ContextBuilder.newBuilder(provider).credentials(login, secretKey).modules(modules).overrides(overrides);
journal.log(Level.INFO, ">> Authenticating ...");
computeContext=builder.buildView(ComputeServiceContext.class);
ec2api=builder.buildApi(EC2Api.class);
//loadBalancerCtx=builder.buildView(LoadBalancerServiceContext.class);
compute=computeContext.getComputeService();
this.provider = provider;
}
示例14
private static void destroyNodes(final ComputeServiceContext ctx, final String groupname) {
// Destroy all workers identified by the given group
final ComputeService computeService = ctx.getComputeService();
if (computeService != null) {
Set<? extends NodeMetadata> destroyed = computeService
.destroyNodesMatching(
Predicates.<NodeMetadata> and(not(TERMINATED),
inGroup(groupname)));
System.out.printf("<< destroyed nodes %s%n", destroyed);
}
}
示例15
public NovaContext(NovaCredentials credentials, ContextBuilder builder) {
this.novaCredentials = credentials;
ComputeServiceContext context = builder.credentials(credentials.getAccountName(),credentials.getAccountPass())
.endpoint(credentials.getEndpoint())
.buildView(ComputeServiceContext.class);
this.computeService = context.getComputeService();
this.novaApi = computeService.getContext().unwrapApi(NovaApi.class);
this.securityGroupApi = novaApi.getSecurityGroupApi(credentials.getRegion()).get();
this.keyPairApi = novaApi.getKeyPairApi(credentials.getRegion()).get();
}
示例16
public GceContext(Credentials credentials) {
ComputeServiceContext context = ContextBuilder.newBuilder("google-compute-engine")
.modules(Arrays.asList(
new SshjSshClientModule(),
new EnterpriseConfigurationModule(),
new SLF4JLoggingModule()))
.credentials(credentials.identity, credentials.credential)
.buildView(ComputeServiceContext.class);
computeService = context.getComputeService();
gceApi = context.unwrapApi(GoogleComputeEngineApi.class);
fireWallApi = gceApi.firewalls();
networkApi = gceApi.networks();
routeApi = gceApi.routes();
this.credentials = credentials;
}
示例17
public Ec2Context(Ec2Credentials credentials) {
this.credentials = credentials;
Properties properties = new Properties();
long scriptTimeout = TimeUnit.MILLISECONDS.convert(50, TimeUnit.MINUTES);
properties.setProperty(TIMEOUT_SCRIPT_COMPLETE, scriptTimeout + "");
properties.setProperty(TIMEOUT_PORT_OPEN, scriptTimeout + "");
properties.setProperty(PROPERTY_CONNECTION_TIMEOUT, scriptTimeout + "");
properties.setProperty(PROPERTY_EC2_AMI_QUERY, "owner-id=137112412989;state=available;image-type=machine");
properties.setProperty(PROPERTY_EC2_CC_AMI_QUERY, "");
properties.setProperty(Constants.PROPERTY_MAX_RETRIES, Settings.JCLOUDS_PROPERTY_MAX_RETRIES + "");
properties.setProperty(Constants.PROPERTY_RETRY_DELAY_START, Settings.JCLOUDS_PROPERTY_RETRY_DELAY_START + "");
Iterable<Module> modules = ImmutableSet.<Module>of(
new SshjSshClientModule(),
new SLF4JLoggingModule(),
new EnterpriseConfigurationModule());
ContextBuilder build = ContextBuilder.newBuilder("aws-ec2")
.credentials(credentials.getAccessKey(), credentials.getSecretKey())
.modules(modules)
.overrides(properties);
ComputeServiceContext context = build.buildView(ComputeServiceContext.class);
this.computeService = (AWSEC2ComputeService) context.getComputeService();
this.ec2api = computeService.getContext().unwrapApi(EC2Api.class);
this.securityGroupApi = ec2api.getSecurityGroupApi().get();
this.keypairApi = (AWSKeyPairApi) ec2api.getKeyPairApi().get();
vmBatchSize = Settings.AWS_VM_BATCH_SIZE();
}
示例18
@Before
public void setup() {
credentials = mock(NovaCredentials.class);
builder = mock(ContextBuilder.class);
serviceContext = mock(ComputeServiceContext.class);
novaComputeService = mock(NovaComputeService.class);
securityGroupApi = mock(SecurityGroupApi.class);
novaApi = mock(NovaApi.class);
keyPairApi = mock(KeyPairApi.class);
ComputeServiceContext context = mock(ComputeServiceContext.class);
Optional<SecurityGroupApi> securityGroupApiOptional = mock(Optional.class);
Optional<KeyPairApi> keyPairApiOptional = mock(Optional.class);
when(credentials.getAccountName()).thenReturn("pepe");
when(credentials.getAccountPass()).thenReturn("1234");
when(credentials.getEndpoint()).thenReturn("nova endpoint");
when(credentials.getRegion()).thenReturn("region");
when(builder.credentials(credentials.getAccountName(), credentials.getAccountPass())).thenReturn(builder);
when(builder.endpoint(credentials.getEndpoint())).thenReturn(builder);
when(builder.buildView(ComputeServiceContext.class)).thenReturn(serviceContext);
when(serviceContext.getComputeService()).thenReturn(novaComputeService);
when(novaComputeService.getContext()).thenReturn(context);
when(context.unwrapApi(NovaApi.class)).thenReturn(novaApi);
when(novaApi.getSecurityGroupApi(credentials.getRegion())).thenReturn(securityGroupApiOptional);
when(securityGroupApiOptional.get()).thenReturn(securityGroupApi);
when(novaApi.getKeyPairApi(credentials.getRegion())).thenReturn(keyPairApiOptional);
when(keyPairApiOptional.get()).thenReturn(keyPairApi);
}
示例19
public ComputeService get() {
// Synchronizing to avoid deadlock from sun.reflect.annotation.AnnotationType.
// See https://github.com/brooklyncentral/brooklyn/issues/974
synchronized (createComputeServicesMutex) {
ComputeServiceContext computeServiceContext = ContextBuilder.newBuilder(provider)
.modules(modules)
.credentialsSupplier(AbstractComputeServiceRegistry.this.makeCredentials(conf))
.overrides(properties)
.build(ComputeServiceContext.class);
return computeServiceContext.getComputeService();
}
}
示例20
public static String waitForPasswordOnAws(ComputeService computeService, final NodeMetadata node, long timeout, TimeUnit timeUnit) throws TimeoutException {
ComputeServiceContext computeServiceContext = computeService.getContext();
AWSEC2Api ec2Client = computeServiceContext.unwrapApi(AWSEC2Api.class);
final WindowsApi client = ec2Client.getWindowsApi().get();
final String region = node.getLocation().getParent().getId();
// The Administrator password will take some time before it is ready - Amazon says sometimes 15 minutes.
// So we create a predicate that tests if the password is ready, and wrap it in a retryable predicate.
Predicate<String> passwordReady = new Predicate<String>() {
@Override public boolean apply(String s) {
if (Strings.isNullOrEmpty(s)) return false;
PasswordData data = client.getPasswordDataInRegion(region, s);
if (data == null) return false;
return !Strings.isNullOrEmpty(data.getPasswordData());
}
};
LOG.info("Waiting for password, for "+node.getProviderId()+":"+node.getId());
Predicate<String> passwordReadyRetryable = Predicates2.retry(passwordReady, timeUnit.toMillis(timeout), 10*1000, TimeUnit.MILLISECONDS);
boolean ready = passwordReadyRetryable.apply(node.getProviderId());
if (!ready) throw new TimeoutException("Password not available for "+node+" in region "+region+" after "+timeout+" "+timeUnit.name());
// Now pull together Amazon's encrypted password blob, and the private key that jclouds generated
PasswordDataAndPrivateKey dataAndKey = new PasswordDataAndPrivateKey(
client.getPasswordDataInRegion(region, node.getProviderId()),
node.getCredentials().getPrivateKey());
// And apply it to the decryption function
WindowsLoginCredentialsFromEncryptedData f = computeServiceContext.utils().injector().getInstance(WindowsLoginCredentialsFromEncryptedData.class);
LoginCredentials credentials = f.apply(dataAndKey);
return credentials.getPassword();
}
示例21
public static Map<Integer, Integer> dockerPortMappingsFor(JcloudsLocation docker, String containerId) {
ComputeServiceContext context = null;
try {
Properties properties = new Properties();
properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, Boolean.toString(true));
properties.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, Boolean.toString(true));
context = ContextBuilder.newBuilder("docker")
.endpoint(docker.getEndpoint())
.credentials(docker.getIdentity(), docker.getCredential())
.overrides(properties)
.modules(ImmutableSet.<Module>of(new SLF4JLoggingModule(), new SshjSshClientModule()))
.build(ComputeServiceContext.class);
DockerApi api = context.unwrapApi(DockerApi.class);
Container container = api.getContainerApi().inspectContainer(containerId);
Map<Integer, Integer> portMappings = Maps.newLinkedHashMap();
Map<String, List<Map<String, String>>> ports = container.networkSettings().ports();
if (ports == null) ports = ImmutableMap.<String, List<Map<String,String>>>of();
LOG.debug("Docker will forward these ports {}", ports);
for (Map.Entry<String, List<Map<String, String>>> entrySet : ports.entrySet()) {
String containerPort = Iterables.get(Splitter.on("/").split(entrySet.getKey()), 0);
String hostPort = Iterables.getOnlyElement(Iterables.transform(entrySet.getValue(),
new Function<Map<String, String>, String>() {
@Override
public String apply(Map<String, String> hostIpAndPort) {
return hostIpAndPort.get("HostPort");
}
}));
portMappings.put(Integer.parseInt(containerPort), Integer.parseInt(hostPort));
}
return portMappings;
} finally {
if (context != null) {
context.close();
}
}
}
示例22
private void assertComputeServiceType(JcloudsLocation loc, String expectedType) {
// TODO Would be nice to do this more explicitly, rather than relying on toString.
// But this is good enough.
ComputeService computeService = loc.getComputeService();
ComputeServiceContext context = computeService.getContext();
assertTrue(context.toString().contains("id="+expectedType), "computeService="+computeService+"; context="+computeService.getContext());
}
示例23
/**
* Creates a JCloud context.
* @param targetProperties the target properties
* @return a non-null object
* @throws TargetException if the target properties are invalid
*/
ComputeService jcloudContext( Map<String,String> targetProperties ) throws TargetException {
validate( targetProperties );
ComputeServiceContext context = ContextBuilder
.newBuilder( targetProperties.get( PROVIDER_ID ))
.endpoint( targetProperties.get( ENDPOINT ))
.credentials( targetProperties.get( IDENTITY ), targetProperties.get( CREDENTIAL ))
.buildView( ComputeServiceContext.class );
return context.getComputeService();
}
示例24
@Inject
protected AWSEC2ComputeService(ComputeServiceContext context, Map<String, Credentials> credentialStore,
@Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> sizes,
@Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
GetImageStrategy getImageStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy,
CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy,
DestroyNodeStrategy destroyNodeStrategy, ResumeNodeStrategy startNodeStrategy,
SuspendNodeStrategy stopNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider,
@Named("DEFAULT") Provider<TemplateOptions> templateOptionsProvider,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(TIMEOUT_NODE_TERMINATED) Predicate<AtomicReference<NodeMetadata>> nodeTerminated,
@Named(TIMEOUT_NODE_SUSPENDED) Predicate<AtomicReference<NodeMetadata>> nodeSuspended,
InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory,
RunScriptOnNode.Factory runScriptOnNodeFactory, InitAdminAccess initAdminAccess,
PersistNodeCredentials persistNodeCredentials, Timeouts timeouts,
@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, AWSEC2Api client,
ConcurrentMap<RegionAndName, KeyPair> credentialsMap,
@Named("SECURITY") LoadingCache<RegionAndName, String> securityGroupMap,
@Named("PLACEMENT") LoadingCache<RegionAndName, String> placementGroupMap,
@Named("DELETED") Predicate<PlacementGroup> placementGroupDeleted, Optional<ImageExtension> imageExtension,
GroupNamingConvention.Factory namingConvention,
@Named(PROPERTY_EC2_GENERATE_INSTANCE_NAMES) boolean generateInstanceNames,
Optional<SecurityGroupExtension> securityGroupExtension) {
super(context, credentialStore, images, sizes, locations, listNodesStrategy, getImageStrategy,
getNodeMetadataStrategy, runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy,
startNodeStrategy, stopNodeStrategy, templateBuilderProvider, templateOptionsProvider, nodeRunning,
nodeTerminated, nodeSuspended, initScriptRunnerFactory, runScriptOnNodeFactory, initAdminAccess,
persistNodeCredentials, timeouts, userExecutor, client, credentialsMap, securityGroupMap, imageExtension,
namingConvention, generateInstanceNames, securityGroupExtension);
this.client = client;
this.placementGroupMap = placementGroupMap;
this.placementGroupDeleted = placementGroupDeleted;
}
示例25
@Override
public void releaseAddress(String ip) {
IaasProvider iaasInfo = getIaasProvider();
ComputeServiceContext context = iaasInfo.getComputeService().getContext();
CloudStackApi cloudStackApi = context.unwrapApi(CloudStackApi.class);
cloudStackApi.getAddressApi().disassociateIPAddress(ip);
}
示例26
@Override
public String createVolume(int sizeGB, String snapshotId) {
// Snapshot id is not there in IaaS.createVolume() method in stratos 4.0.0
//todo return volume ID if volume is created
IaasProvider iaasInfo = getIaasProvider();
ComputeServiceContext context = iaasInfo.getComputeService()
.getContext();
String zone = ComputeServiceBuilderUtil.extractZone(iaasInfo);
String diskOfferingID = iaasInfo.getTemplate().getOptions().as(CloudStackTemplateOptions.class)
.getDiskOfferingId();
if (zone == null && diskOfferingID == null) {
log.error("Could not create a volume in the , [zone] : " + zone + " of Iaas : " + iaasInfo);
return null;
}
VolumeApi volumeApi = context.unwrapApi(CloudStackApi.class).getVolumeApi();
Volume volume;
if (StringUtils.isEmpty(snapshotId)) {
if (log.isInfoEnabled()) {
log.info("Creating a volume in the zone " + zone);
}
//cloudstack jcloud api does not return a volume object
volumeApi.createVolumeFromCustomDiskOfferingInZone(null, diskOfferingID, zone, sizeGB);
// volume = blockStoreApi.createVolumeInAvailabilityZone(zone, sizeGB);
} else {
if (log.isInfoEnabled()) {
log.info("Creating a volume in the zone " + zone + " from the snapshot " + snapshotId);
}
volumeApi.createVolumeFromSnapshotInZone(null, diskOfferingID, zone);
}
return null;
}
示例27
@Override
public void detachVolume(String instanceId, String volumeId) {
IaasProvider iaasInfo = getIaasProvider();
ComputeServiceContext context = iaasInfo.getComputeService()
.getContext();
if (log.isDebugEnabled()) {
log.debug(String.format("Starting to detach volume %s from the instance %s", volumeId, instanceId));
}
CloudStackApi cloudStackApi = context.unwrapApi(CloudStackApi.class);
cloudStackApi.getVolumeApi().detachVolume(volumeId);
try {
//TODO this is true only for newly created volumes
if (waitForStatus(volumeId, Volume.State.ALLOCATED, 5)) {
log.info(String.format("Detachment of Volume [id]: %s from instance [id]: %s was successful of Iaas : %s", volumeId, instanceId, iaasInfo));
}
} catch (TimeoutException e) {
log.error(String.format("Detachment of Volume [id]: %s from instance [id]: %s was unsuccessful. [volume Status] : %s", volumeId, instanceId, iaasInfo));
}
}
示例28
@Override
public void deleteVolume(String volumeId) {
IaasProvider iaasInfo = getIaasProvider();
ComputeServiceContext context = iaasInfo.getComputeService()
.getContext();
CloudStackApi cloudStackApi = context.unwrapApi(CloudStackApi.class);
cloudStackApi.getVolumeApi().deleteVolume(volumeId);
log.info("Deletion of Volume [id]: " + volumeId + " was successful. "
+ " of Iaas : " + iaasInfo);
}
示例29
private boolean waitForStatus(String volumeId, Volume.State expectedStatus, int timeoutInMilliseconds) throws TimeoutException {
int timeout = 1000 * 60 * timeoutInMilliseconds;
long timout = System.currentTimeMillis() + timeout;
IaasProvider iaasInfo = getIaasProvider();
ComputeServiceContext context = iaasInfo.getComputeService().getContext();
CloudStackApi cloudStackApi = context.unwrapApi(CloudStackApi.class);
//get volume
org.jclouds.cloudstack.domain.Volume volume = cloudStackApi.getVolumeApi().getVolume(volumeId);
Volume.State volumeState = volume.getState();
while (volumeState != expectedStatus) {
try {
if (log.isDebugEnabled()) {
log.debug(String.format("Volume %s is still NOT in %s. Current State=%s", volumeId, expectedStatus, volumeState));
}
if (volumeState == Volume.State.FAILED || volumeState == Volume.State.DESTROYED || volumeState == Volume.State.UNRECOGNIZED) {
log.error("Volume " + volumeId + " is in state" + volumeState);
return false;
}
Thread.sleep(1000);
volumeState = volume.getState();
if (System.currentTimeMillis() > timout) {
throw new TimeoutException();
}
} catch (InterruptedException e) {
// Ignoring the exception
}
}
if (log.isDebugEnabled()) {
log.debug(String.format("Volume %s status became %s", volumeId, expectedStatus));
}
return true;
}
示例30
@Override
public synchronized boolean createKeyPairFromPublicKey(String region, String keyPairName, String publicKey) {
IaasProvider iaasInfo = getIaasProvider();
String ec2Msg = " ec2. Region: " + region + " - Key Pair Name: ";
ComputeServiceContext context = iaasInfo.getComputeService().getContext();
AWSKeyPairApi keyPairApi = context.unwrapApi(AWSEC2Api.class).getKeyPairApiForRegion(region).get();
KeyPair keyPair = keyPairApi.importKeyPairInRegion(region, keyPairName, publicKey);
if (keyPair != null) {
iaasInfo.getTemplate().getOptions().as(AWSEC2TemplateOptions.class).keyPair(keyPair.getKeyName());
log.info(SUCCESSFUL_LOG_LINE + ec2Msg + keyPair.getKeyName());
return true;
}
log.error(FAILED_LOG_LINE + ec2Msg);
return false;
}