cleaned up nova impl

This commit is contained in:
Adrian Cole 2011-12-21 23:59:35 -08:00
parent 5587b4e6be
commit ca749a2c8b
31 changed files with 108 additions and 2362 deletions

View File

@ -85,22 +85,10 @@
</dependency>
<dependency>
<groupId>org.jclouds.driver</groupId>
<artifactId>jclouds-slf4j</artifactId>
<artifactId>jclouds-log4j</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
<version>1.6.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>0.9.29</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>

View File

@ -264,6 +264,15 @@ public interface NovaAsyncClient {
@Path("/images/{id}")
ListenableFuture<Boolean> deleteImage(@PathParam("id") int id);
/**
* @see NovaClient#deleteImage
*/
@DELETE
@ExceptionParser(ReturnFalseOnNotFoundOr404.class)
@Consumes
@Path("/images/{id}")
ListenableFuture<Boolean> deleteImage(@PathParam("id") String id);
/**
* @see NovaClient#createImageFromServer
*/

View File

@ -236,6 +236,7 @@ public interface NovaClient {
* @see Image
*/
boolean deleteImage(int id);
boolean deleteImage(String id);
/**
*

View File

@ -1,76 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.compute.config;
import org.jclouds.compute.config.BindComputeStrategiesByClass;
import org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.openstack.nova.compute.strategy.NovaCreateNodeWithGroupEncodedIntoName;
import org.jclouds.openstack.nova.compute.strategy.NovaDestroyNodeStrategy;
import org.jclouds.openstack.nova.compute.strategy.NovaGetNodeMetadataStrategy;
import org.jclouds.openstack.nova.compute.strategy.NovaListNodesStrategy;
import org.jclouds.openstack.nova.compute.strategy.NovaLifeCycleStrategy;
/**
*
* @author Adrian Cole
*
*/
public class NovaBindComputeStrategiesByClass extends BindComputeStrategiesByClass {
@Override
protected Class<? extends CreateNodeWithGroupEncodedIntoName> defineAddNodeWithTagStrategy() {
return NovaCreateNodeWithGroupEncodedIntoName.class;
}
@Override
protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {
return NovaDestroyNodeStrategy.class;
}
@Override
protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() {
return NovaGetNodeMetadataStrategy.class;
}
@Override
protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {
return NovaListNodesStrategy.class;
}
@Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return NovaLifeCycleStrategy.class;
}
@Override
protected Class<? extends ResumeNodeStrategy> defineStartNodeStrategy() {
return NovaLifeCycleStrategy.class;
}
@Override
protected Class<? extends SuspendNodeStrategy> defineStopNodeStrategy() {
return NovaLifeCycleStrategy.class;
}
}

View File

@ -1,53 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.compute.config;
import java.util.Set;
import org.jclouds.openstack.nova.compute.suppliers.NovaHardwareSupplier;
import org.jclouds.openstack.nova.compute.suppliers.NovaImageSupplier;
import org.jclouds.compute.config.BindComputeSuppliersByClass;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.domain.Location;
import org.jclouds.location.suppliers.JustProvider;
import com.google.common.base.Supplier;
/**
*
* @author Adrian Cole
*
*/
public class NovaBindComputeSuppliersByClass extends BindComputeSuppliersByClass {
@Override
protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {
return NovaHardwareSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {
return NovaImageSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Location>>> defineLocationSupplier() {
return JustProvider.class;
}
}

View File

@ -18,23 +18,102 @@
*/
package org.jclouds.openstack.nova.compute.config;
import org.jclouds.compute.config.BaseComputeServiceContextModule;
import java.util.Map;
import javax.inject.Singleton;
import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.config.ComputeServiceAdapterContextModule;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.internal.BaseComputeService;
import org.jclouds.domain.Location;
import org.jclouds.functions.IdentityFunction;
import org.jclouds.location.suppliers.OnlyLocationOrFirstZone;
import org.jclouds.openstack.nova.NovaAsyncClient;
import org.jclouds.openstack.nova.NovaClient;
import org.jclouds.openstack.nova.compute.functions.FlavorToHardware;
import org.jclouds.openstack.nova.compute.functions.NovaImageToImage;
import org.jclouds.openstack.nova.compute.functions.NovaImageToOperatingSystem;
import org.jclouds.openstack.nova.compute.functions.ServerToNodeMetadata;
import org.jclouds.openstack.nova.compute.strategy.NovaComputeServiceAdapter;
import org.jclouds.openstack.nova.domain.Flavor;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Provides;
import com.google.inject.TypeLiteral;
/**
* Configures the {@link NovaComputeServiceContext}; requires {@link BaseComputeService}
* bound.
* Configures the {@link NovaComputeServiceContext}; requires {@link BaseComputeService} bound.
*
* @author Adrian Cole
*/
public class NovaComputeServiceContextModule extends BaseComputeServiceContextModule {
public class NovaComputeServiceContextModule
extends
ComputeServiceAdapterContextModule<NovaClient, NovaAsyncClient, Server, Flavor, org.jclouds.openstack.nova.domain.Image, Location> {
public NovaComputeServiceContextModule() {
super(NovaClient.class, NovaAsyncClient.class);
}
@SuppressWarnings("unchecked")
@Override
protected void configure() {
install(new NovaComputeServiceDependenciesModule());
install(new NovaBindComputeStrategiesByClass());
install(new NovaBindComputeSuppliersByClass());
super.configure();
bind(new TypeLiteral<ComputeServiceAdapter<Server, Flavor, org.jclouds.openstack.nova.domain.Image, Location>>() {
}).to(NovaComputeServiceAdapter.class);
bind(new TypeLiteral<Function<Server, NodeMetadata>>() {
}).to(ServerToNodeMetadata.class);
bind(new TypeLiteral<Function<org.jclouds.openstack.nova.domain.Image, Image>>() {
}).to(NovaImageToImage.class);
bind(new TypeLiteral<Function<org.jclouds.openstack.nova.domain.Image, OperatingSystem>>() {
}).to(NovaImageToOperatingSystem.class);
bind(new TypeLiteral<Function<Flavor, Hardware>>() {
}).to(FlavorToHardware.class);
// we aren't converting location from a provider-specific type
bind(new TypeLiteral<Function<Location, Location>>() {
}).to((Class) IdentityFunction.class);
// there are no locations except the provider
bind(new TypeLiteral<Supplier<Location>>() {
}).to(OnlyLocationOrFirstZone.class);
}
@VisibleForTesting
public static final Map<ServerStatus, NodeState> serverToNodeState = ImmutableMap
.<ServerStatus, NodeState> builder().put(ServerStatus.ACTIVE, NodeState.RUNNING)//
.put(ServerStatus.SUSPENDED, NodeState.SUSPENDED)//
.put(ServerStatus.DELETED, NodeState.TERMINATED)//
.put(ServerStatus.QUEUE_RESIZE, NodeState.PENDING)//
.put(ServerStatus.PREP_RESIZE, NodeState.PENDING)//
.put(ServerStatus.RESIZE, NodeState.PENDING)//
.put(ServerStatus.VERIFY_RESIZE, NodeState.PENDING)//
.put(ServerStatus.RESCUE, NodeState.PENDING)//
.put(ServerStatus.BUILD, NodeState.PENDING)//
.put(ServerStatus.PASSWORD, NodeState.PENDING)//
.put(ServerStatus.REBUILD, NodeState.PENDING)//
.put(ServerStatus.DELETE_IP, NodeState.PENDING)//
.put(ServerStatus.REBOOT, NodeState.PENDING)//
.put(ServerStatus.HARD_REBOOT, NodeState.PENDING)//
.put(ServerStatus.UNKNOWN, NodeState.UNRECOGNIZED)//
.put(ServerStatus.UNRECOGNIZED, NodeState.UNRECOGNIZED).build();
@Singleton
@Provides
Map<ServerStatus, NodeState> provideServerToNodeState() {
return serverToNodeState;
}
}

View File

@ -1,108 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.compute.config;
import java.util.Map;
import javax.inject.Singleton;
import org.jclouds.openstack.nova.NovaAsyncClient;
import org.jclouds.openstack.nova.NovaClient;
import org.jclouds.openstack.nova.compute.functions.NovaImageToImage;
import org.jclouds.openstack.nova.compute.functions.NovaImageToOperatingSystem;
import org.jclouds.openstack.nova.compute.functions.FlavorToHardware;
import org.jclouds.openstack.nova.compute.functions.ServerToNodeMetadata;
import org.jclouds.openstack.nova.domain.Flavor;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.internal.BaseComputeService;
import org.jclouds.compute.internal.ComputeServiceContextImpl;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Scopes;
import com.google.inject.TypeLiteral;
/**
* Configures the {@link NovaComputeServiceContext}; requires {@link BaseComputeService}
* bound.
*
* @author Adrian Cole
*/
public class NovaComputeServiceDependenciesModule extends AbstractModule {
@Override
protected void configure() {
bind(new TypeLiteral<Function<Server, NodeMetadata>>() {
}).to(ServerToNodeMetadata.class);
bind(new TypeLiteral<Function<org.jclouds.openstack.nova.domain.Image, Image>>() {
}).to(NovaImageToImage.class);
bind(new TypeLiteral<Function<org.jclouds.openstack.nova.domain.Image, OperatingSystem>>() {
}).to(NovaImageToOperatingSystem.class);
bind(new TypeLiteral<Function<Flavor, Hardware>>() {
}).to(FlavorToHardware.class);
bind(new TypeLiteral<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<NovaClient, NovaAsyncClient>>() {
}).in(Scopes.SINGLETON);
bind(new TypeLiteral<RestContext<NovaClient, NovaAsyncClient>>() {
}).to(new TypeLiteral<RestContextImpl<NovaClient, NovaAsyncClient>>() {
}).in(Scopes.SINGLETON);
}
@VisibleForTesting
public static final Map<ServerStatus, NodeState> serverToNodeState = ImmutableMap
.<ServerStatus, NodeState> builder().put(ServerStatus.ACTIVE, NodeState.RUNNING)//
.put(ServerStatus.SUSPENDED, NodeState.SUSPENDED)//
.put(ServerStatus.DELETED, NodeState.TERMINATED)//
.put(ServerStatus.QUEUE_RESIZE, NodeState.PENDING)//
.put(ServerStatus.PREP_RESIZE, NodeState.PENDING)//
.put(ServerStatus.RESIZE, NodeState.PENDING)//
.put(ServerStatus.VERIFY_RESIZE, NodeState.PENDING)//
.put(ServerStatus.RESCUE, NodeState.PENDING)//
.put(ServerStatus.BUILD, NodeState.PENDING)//
.put(ServerStatus.PASSWORD, NodeState.PENDING)//
.put(ServerStatus.REBUILD, NodeState.PENDING)//
.put(ServerStatus.DELETE_IP, NodeState.PENDING)//
.put(ServerStatus.REBOOT, NodeState.PENDING)//
.put(ServerStatus.HARD_REBOOT, NodeState.PENDING)//
.put(ServerStatus.UNKNOWN, NodeState.UNRECOGNIZED)//
.put(ServerStatus.UNRECOGNIZED, NodeState.UNRECOGNIZED).build();
@Singleton
@Provides
Map<ServerStatus, NodeState> provideServerToNodeState() {
return serverToNodeState;
}
}

View File

@ -1,64 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withMetadata;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.openstack.nova.NovaClient;
import org.jclouds.openstack.nova.domain.Server;
import com.google.common.base.Function;
/**
* @author Adrian Cole
*/
@Singleton
public class NovaCreateNodeWithGroupEncodedIntoName implements CreateNodeWithGroupEncodedIntoName {
protected final NovaClient client;
protected final Map<String, Credentials> credentialStore;
protected final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected NovaCreateNodeWithGroupEncodedIntoName(NovaClient client, Map<String, Credentials> credentialStore,
Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = checkNotNull(client, "client");
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.serverToNodeMetadata = checkNotNull(serverToNodeMetadata, "serverToNodeMetadata");
}
@Override
public NodeMetadata createNodeWithGroupEncodedIntoName(String group, String name, Template template) {
Server from = client.createServer(name, template.getImage().getId(), template.getHardware().getId(),
withMetadata(template.getOptions().getUserMetadata()));
credentialStore.put("node#" + from.getId(), LoginCredentials.builder().password(from.getAdminPass()).build());
return serverToNodeMetadata.apply(from);
}
}

View File

@ -1,51 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.openstack.nova.NovaClient;
/**
* @author Adrian Cole
*/
@Singleton
public class NovaDestroyNodeStrategy implements DestroyNodeStrategy {
private final NovaClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected NovaDestroyNodeStrategy(NovaClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata destroyNode(String id) {
int serverId = Integer.parseInt(id);
// if false server wasn't around in the first place
client.deleteServer(serverId);
return getNode.getNode(id);
}
}

View File

@ -1,53 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.openstack.nova.NovaClient;
import org.jclouds.openstack.nova.domain.Server;
import com.google.common.base.Function;
/**
* @author Adrian Cole
*/
@Singleton
public class NovaGetNodeMetadataStrategy implements GetNodeMetadataStrategy {
private final NovaClient client;
private final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected NovaGetNodeMetadataStrategy(NovaClient client,
Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = client;
this.serverToNodeMetadata = serverToNodeMetadata;
}
@Override
public NodeMetadata getNode(String id) {
int serverId = Integer.parseInt(id);
Server server = client.getServer(serverId);
return server == null ? null : serverToNodeMetadata.apply(server);
}
}

View File

@ -1,64 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.openstack.nova.NovaClient;
import org.jclouds.openstack.nova.domain.RebootType;
/**
* @author Adrian Cole
*/
@Singleton
public class NovaLifeCycleStrategy implements RebootNodeStrategy, SuspendNodeStrategy, ResumeNodeStrategy {
private final NovaClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected NovaLifeCycleStrategy(NovaClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata rebootNode(String id) {
int serverId = Integer.parseInt(id);
// if false server wasn't around in the first place
client.rebootServer(serverId, RebootType.SOFT);
return getNode.getNode(id);
}
@Override
public NodeMetadata suspendNode(String id) {
throw new UnsupportedOperationException("suspend not supported");
}
@Override
public NodeMetadata resumeNode(String id) {
throw new UnsupportedOperationException("resume not supported");
}
}

View File

@ -1,61 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.openstack.nova.NovaClient;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.options.ListOptions;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
/**
* @author Adrian Cole
*/
@Singleton
public class NovaListNodesStrategy implements ListNodesStrategy {
private final NovaClient client;
private final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected NovaListNodesStrategy(NovaClient client,
Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = client;
this.serverToNodeMetadata = serverToNodeMetadata;
}
@Override
public Iterable<? extends ComputeMetadata> listNodes() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
return Iterables.filter(Iterables.transform(client.listServers(ListOptions.Builder.withDetails()),
serverToNodeMetadata), filter);
}
}

View File

@ -1,67 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.compute.suppliers;
import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import org.jclouds.openstack.nova.NovaClient;
import org.jclouds.openstack.nova.domain.Flavor;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
/**
*
* @author Adrian Cole
*/
@Singleton
public class NovaHardwareSupplier implements Supplier<Set<? extends Hardware>> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final NovaClient sync;
private final Function<Flavor, Hardware> flavorToHardware;
@Inject
NovaHardwareSupplier(NovaClient sync, Function<Flavor, Hardware> flavorToHardware) {
this.sync = sync;
this.flavorToHardware = flavorToHardware;
}
@Override
public Set<? extends Hardware> get() {
final Set<Hardware> hardware;
logger.debug(">> providing hardware");
hardware = Sets.newLinkedHashSet(Iterables.transform(sync.listFlavors(withDetails()), flavorToHardware));
logger.debug("<< hardware(%d)", hardware.size());
return hardware;
}
}

View File

@ -1,70 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.compute.suppliers;
import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import org.jclouds.openstack.nova.NovaClient;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
/**
*
* @author Adrian Cole
*/
@Singleton
public class NovaImageSupplier implements Supplier<Set<? extends Image>> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
protected final NovaClient sync;
protected final Function<org.jclouds.openstack.nova.domain.Image, Image> cloudServersImageToImage;
@Inject
NovaImageSupplier(NovaClient sync,
Function<org.jclouds.openstack.nova.domain.Image, Image> cloudServersImageToImage) {
this.sync = sync;
this.cloudServersImageToImage = cloudServersImageToImage;
}
@Override
public Set<? extends Image> get() {
Set<Image> images;
logger.debug(">> providing images");
images = Sets.<Image> newLinkedHashSet(Iterables.transform(sync.listImages(withDetails()),
cloudServersImageToImage));
logger.debug("<< images(%d)", images.size());
return images;
}
}

View File

@ -24,13 +24,13 @@ import org.testng.annotations.Test;
/**
* @author Adrian Cole
*/
@Test(groups = "unit")
@Test(groups = "unit", testName ="NovaComputeServiceContextModuleTest")
public class NovaComputeServiceContextModuleTest {
public void testAllStatusCovered() {
for (ServerStatus state : ServerStatus.values()) {
assert NovaComputeServiceDependenciesModule.serverToNodeState.containsKey(state) : state;
assert NovaComputeServiceContextModule.serverToNodeState.containsKey(state) : state;
}
}

View File

@ -40,7 +40,7 @@ import org.jclouds.compute.domain.VolumeBuilder;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope;
import org.jclouds.openstack.nova.compute.config.NovaComputeServiceDependenciesModule;
import org.jclouds.openstack.nova.compute.config.NovaComputeServiceContextModule;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus;
import org.jclouds.openstack.nova.functions.ParseServerFromJsonResponseTest;
@ -61,7 +61,7 @@ public class ServerToNodeMetadataTest {
@Test
public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException,
ClassNotFoundException, URISyntaxException {
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState;
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceContextModule.serverToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of();
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
Server server = ParseServerFromJsonResponseTest.parseServer();
@ -96,7 +96,7 @@ public class ServerToNodeMetadataTest {
@Test
public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException,
ClassNotFoundException, URISyntaxException {
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState;
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceContextModule.serverToNodeState;
org.jclouds.compute.domain.Image jcImage = NovaImageToImageTest.convertImage();
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(jcImage);
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
@ -121,7 +121,7 @@ public class ServerToNodeMetadataTest {
@Test
public void testApplyWhereImageAndHardwareFound() throws UnknownHostException, NoSuchMethodException,
ClassNotFoundException, URISyntaxException {
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState;
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceContextModule.serverToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(NovaImageToImageTest.convertImage());
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor());
Server server = ParseServerFromJsonResponseTest.parseServer();

View File

@ -1,70 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.live;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import org.jclouds.Constants;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Resources;
/**
* @author Victor Galkin
*/
public class PropertyHelper {
private static String provider = "nova";
public static Map<String, String> setupKeyPair(Properties properties) throws IOException {
return ImmutableMap.of(
"private", Resources.toString(Resources.getResource(PropertyHelper.class, properties.getProperty("test.ssh.keyfile.private")), Charsets.UTF_8),
"public", Resources.toString(Resources.getResource(PropertyHelper.class, properties.getProperty("test.ssh.keyfile.public")), Charsets.UTF_8));
}
public static Properties setupProperties(Class<?> clazz) throws IOException {
Properties properties = new Properties();
String propertiesPath = System.getProperty("test.properties");
if (propertiesPath != null) {
InputStream propertiesStream = clazz.getResourceAsStream(propertiesPath);
properties.load(propertiesStream);
}
properties.putAll(System.getProperties());
return properties;
}
public static Properties setupOverrides(final Properties properties) {
properties.setProperty(provider + ".identity", properties.getProperty("test." + provider + ".identity"));
properties.setProperty(provider + ".credential", properties.getProperty("test." + provider + ".credential"));
properties.setProperty(provider + ".endpoint", properties.getProperty("test." + provider + ".endpoint"));
properties.setProperty(provider + ".apiversion", properties.getProperty("test." + provider + ".apiversion"));
properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
properties.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true");
return properties;
}
}

View File

@ -1,177 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.live.compute;
import static com.google.common.base.Predicates.and;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.Sets.filter;
import static org.jclouds.compute.predicates.NodePredicates.TERMINATED;
import static org.jclouds.compute.predicates.NodePredicates.all;
import static org.jclouds.compute.predicates.NodePredicates.inGroup;
import static org.jclouds.openstack.nova.live.PropertyHelper.setupKeyPair;
import static org.jclouds.openstack.nova.live.PropertyHelper.setupOverrides;
import static org.jclouds.openstack.nova.live.PropertyHelper.setupProperties;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.http.handlers.BackoffLimitedRetryHandler;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.net.IPSocket;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen;
import org.jclouds.ssh.SshException;
import org.jclouds.sshj.SshjSshClient;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.testng.annotations.BeforeTest;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Module;
/**
* @author Victor Galkin
*/
public class ComputeBase {
protected ComputeServiceContext context;
protected ComputeService computeService;
protected String provider = "nova";
protected Map<String, String> keyPair;
protected Properties overrides;
protected String testImageId;
@BeforeTest
public void before() throws InterruptedException, ExecutionException, TimeoutException, IOException {
Properties properties = setupProperties(this.getClass());
setupOverrides(properties);
overrides = properties;
keyPair = setupKeyPair(properties);
testImageId = properties.getProperty("test.nova.image.id");
initializeContextAndComputeService(properties);
}
@SuppressWarnings("unused")
private RetryablePredicate<IPSocket> buildSocket() {
SocketOpen socketOpen = Guice.createInjector(getSshModule()).getInstance(SocketOpen.class);
return new RetryablePredicate<IPSocket>(socketOpen, 60, 1, TimeUnit.SECONDS);
}
private Module getSshModule() {
return new SshjSshClientModule();
}
protected TemplateBuilder getDefaultTemplateBuilder() {
return computeService.templateBuilder().imageId(testImageId).options(getDefaultTemplateOptions());
}
private TemplateOptions getDefaultTemplateOptions() {
return TemplateOptions.Builder.blockUntilRunning(false);
//.installPrivateKey(Payloads.newStringPayload(keyPair.get("private")));
}
protected NodeMetadata getDefaultNodeImmediately(String group) throws RunNodesException {
for (ComputeMetadata node : computeService.listNodes()) {
if (((NodeMetadata) node).getGroup() != null)
if (((NodeMetadata) node).getGroup().equals(group))
if (((NodeMetadata) node).getState().equals(NodeState.PENDING)
|| ((NodeMetadata) node).getState().equals(NodeState.RUNNING)) return (NodeMetadata) node;
}
return createDefaultNode(group);
}
protected NodeMetadata createDefaultNode(TemplateOptions options, String group) throws RunNodesException {
return computeService.createNodesInGroup(group, 1, getDefaultTemplateBuilder().options(options).build())
.iterator().next();
}
protected NodeMetadata createDefaultNode(String group) throws RunNodesException {
return createDefaultNode(getDefaultTemplateOptions(), group);
}
protected void initializeContextAndComputeService(Properties properties) throws IOException {
if (context != null)
context.close();
context = new ComputeServiceContextFactory().createContext(provider, ImmutableSet.of(
new SLF4JLoggingModule(), getSshModule()), properties);
computeService = context.getComputeService();
}
protected String awaitForStartup(String nodeId) throws InterruptedException {
while (true) {
NodeMetadata metadata = computeService.getNodeMetadata(nodeId);
Set<String> addresses = metadata.getPublicAddresses();
System.out.println(addresses);
System.out.println(metadata.getState());
if (metadata.getState() == NodeState.RUNNING && addresses != null && !addresses.isEmpty())
return addresses.iterator().next();
Thread.sleep(1000);
}
}
protected Set<? extends NodeMetadata> getFreshNodes(String group) {
return filter(computeService.listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED)));
}
protected void awaitForSshPort(String address, Credentials credentials) throws URISyntaxException {
IPSocket socket = new IPSocket(address, 22);
SshjSshClient ssh = new SshjSshClient(
new BackoffLimitedRetryHandler(), socket, 10000, credentials.identity, null, credentials.credential.getBytes());
while (true) {
try {
System.out.println("ping: " + socket);
ssh.connect();
return;
} catch (SshException ignore) {
}
}
}
protected void assertLocationSameOrChild(Location test, Location expected) {
if (!test.equals(expected)) {
assertEquals(test.getParent().getId(), expected.getId());
} else {
assertEquals(test, expected);
}
}
}

View File

@ -1,98 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.live.compute;
import static org.jclouds.openstack.nova.live.PropertyHelper.setupOverrides;
import static org.jclouds.openstack.nova.live.PropertyHelper.setupProperties;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Set;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
/**
* Not intended to be run with maven and does not performs a cleanup after tests
*
* @author Dmitri Babaev
*/
public class ComputeServiceCheck {
private ComputeServiceContextFactory contextFactory;
private ComputeServiceContext context;
private String testImageId;
@BeforeTest
public void setupClient() throws IOException {
contextFactory = new ComputeServiceContextFactory();
Properties properties = setupOverrides(setupProperties(this.getClass()));
context = contextFactory.createContext("nova",
ImmutableSet.of(new SshjSshClientModule(), new SLF4JLoggingModule()), properties);
testImageId = properties.getProperty("test.nova.image.id");
}
@Test
public void testLists() {
ComputeService cs = context.getComputeService();
System.out.println(cs.listImages());
System.out.println(cs.listHardwareProfiles());
System.out.println(cs.listAssignableLocations());
System.out.println(cs.listNodes());
}
@Test
public void testCreateServer() throws RunNodesException {
ComputeService cs = context.getComputeService();
TemplateOptions options = new TemplateOptions().blockUntilRunning(false);
Template template = cs.templateBuilder().imageId(testImageId).hardwareId("2").options(options).build();
Set<? extends NodeMetadata> metedata = cs.createNodesInGroup("test", 1, template);
System.out.println(metedata);
}
@Test(expectedExceptions = NoSuchElementException.class)
public void testDefaultTempateDoesNotSpecifyTheOS() {
ComputeService cs = context.getComputeService();
Template template = cs.templateBuilder().build();
System.out.println(template);
}
@AfterTest
public void after() {
context.close();
}
//curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://dragon004.hw.griddynamics.net:8774/v1.0/
//curl -v -H "X-Auth-Token: c97b10659008d5a9ce91462f8c6a5c2c80439762" http://dragon004.hw.griddynamics.net:8774/v1.0/images/detail?format=json
}

View File

@ -1,474 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.live.compute;
import static com.google.common.base.Predicates.and;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.collect.Maps.newLinkedHashMap;
import static com.google.common.collect.Maps.uniqueIndex;
import static com.google.common.collect.Sets.filter;
import static com.google.common.collect.Sets.newTreeSet;
import static org.jclouds.compute.ComputeTestUtils.buildScript;
import static org.jclouds.compute.options.TemplateOptions.Builder.overrideLoginCredentials;
import static org.jclouds.compute.predicates.NodePredicates.TERMINATED;
import static org.jclouds.compute.predicates.NodePredicates.all;
import static org.jclouds.compute.predicates.NodePredicates.inGroup;
import static org.jclouds.compute.predicates.NodePredicates.runningInGroup;
import static org.jclouds.compute.util.ComputeServiceUtils.getCores;
import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Set;
import java.util.SortedSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import net.schmizz.sshj.userauth.UserAuthException;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.RunScriptOnNodesException;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.ComputeType;
import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.rest.AuthorizationException;
import org.jclouds.scriptbuilder.domain.Statements;
import org.jclouds.ssh.SshClient;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.inject.Module;
/**
* Generally disabled, as it incurs higher fees.
*
* @author Adrian Cole
*/
@Test(groups = "novalive", enabled = true, sequential = true)
public class NovaComputeServiceLiveTest extends ComputeBase {
private static String group = "compute service test group";
protected void checkNodes(Iterable<? extends NodeMetadata> nodes, String tag) throws IOException {
for (NodeMetadata node : nodes) {
assertNotNull(node.getProviderId());
assertNotNull(node.getGroup());
assertEquals(node.getGroup(), group);
// assertEquals(node.getState(), NodeState.RUNNING);
Credentials fromStore = context.getCredentialStore().get("node#" + node.getId());
assertEquals(fromStore, node.getCredentials());
assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : "no ips in" + node;
// assertNotNull(node.getCredentials());
// if (node.getCredentials().identity != null) {
// assertNotNull(node.getCredentials().identity);
// assertNotNull(node.getCredentials().credential);
// doCheckJavaIsInstalledViaSsh(node);
// }
assertEquals(node.getLocation().getScope(), LocationScope.HOST);
}
}
@BeforeTest
@Override
public void before() throws IOException, ExecutionException, TimeoutException, InterruptedException {
super.before();
computeService.destroyNodesMatching(inGroup(group));
}
@Test(enabled = true, expectedExceptions = AuthorizationException.class, timeOut = 60000)
public void testCorrectAuthException() throws Exception {
Properties properties = new Properties();
properties.putAll(overrides);
properties.remove(provider + ".identity");
ComputeServiceContext context = null;
try {
context = new ComputeServiceContextFactory().createContext(provider, "MOMMA", "MIA",
ImmutableSet.<Module> of(new SLF4JLoggingModule()), properties);
context.getComputeService().listNodes();
} finally {
if (context != null)
context.close();
}
}
@Test(timeOut = 60000)
public void testImagesCache() throws Exception {
computeService.listImages();
long time = System.currentTimeMillis();
computeService.listImages();
long duration = System.currentTimeMillis() - time;
assert duration < 1000 : String.format("%dms to get images", duration);
}
@Test(enabled = true, expectedExceptions = NoSuchElementException.class, timeOut = 60000)
public void testCorrectExceptionRunningNodesNotFound() throws Exception {
computeService.runScriptOnNodesMatching(runningInGroup("zebras-are-awesome"),
buildScript(new OperatingSystem.Builder().family(OsFamily.UBUNTU).description("ffoo").build()));
}
@Test(expectedExceptions = UserAuthException.class, timeOut = 240000)
void testScriptExecutionWithWrongCredentials() throws Throwable {
NodeMetadata node = getDefaultNodeImmediately(group);
String address = awaitForStartup(node.getId());
awaitForSshPort(address, new Credentials("root", keyPair.get("private")));
OperatingSystem os = node.getOperatingSystem();
try {
@SuppressWarnings("unused")
Map<? extends NodeMetadata, ExecResponse> responses = runJavaInstallationScriptWithCreds(group, os,
LoginCredentials.builder().user("root").password("romeo").build());
} catch (RunScriptOnNodesException e) {
throw e.getNodeErrors().values().iterator().next().getCause();
}
}
@Test(timeOut = 240000)
public void testScriptExecutionAfterBootWithBasicTemplate() throws InterruptedException, RunNodesException,
RunScriptOnNodesException, URISyntaxException, IOException {
NodeMetadata node = getDefaultNodeImmediately(group);
String address = awaitForStartup(node.getId());
awaitForSshPort(address, new Credentials("root", keyPair.get("private")));
for (Map.Entry<? extends NodeMetadata, ExecResponse> response : computeService.runScriptOnNodesMatching(
runningInGroup(group),
Statements.exec("echo hello"),
overrideLoginCredentials(LoginCredentials.builder().user("root").privateKey(keyPair.get("private")).build())
.wrapInInitScript(false).runAsRoot(false)).entrySet())
assert response.getValue().getOutput().trim().equals("hello") : response.getKey() + ": " + response.getValue();
// TODO runJavaInstallationScriptWithCreds(group, os, new
// Credentials("root", keyPair.get("private")));
// TODO no response? if os is null (ZYPPER)
node = computeService.getNodeMetadata(node.getId());
checkNodes(Sets.newHashSet(node), group);
@SuppressWarnings("unused")
Credentials good = node.getCredentials();
// TODO check good is being private key .overrideCredentialsWith
// TODO test for .blockOnPort
}
@Test(timeOut = 60000)
public void testTemplateMatch() throws Exception {
Template template = buildTemplate(getDefaultTemplateBuilder());
Template toMatch = computeService.templateBuilder().imageId(template.getImage().getId()).build();
assertEquals(toMatch.getImage(), template.getImage());
}
// protected void checkHttpGet(NodeMetadata node) {
// ComputeTestUtils.checkHttpGet(context.utils().http(), node, 8080);
// }
@Test(timeOut = 60000)
public void testCreateTwoNodesWithRunScript() throws Exception {
computeService.destroyNodesMatching(inGroup(group));
Template template = getDefaultTemplateBuilder().options(TemplateOptions.Builder.blockUntilRunning(true)).build();
SortedSet<NodeMetadata> nodes = newTreeSet(computeService.createNodesInGroup(group, 2, template));
assertEquals(nodes.size(), 2);
checkNodes(nodes, group);
NodeMetadata node1 = nodes.first();
NodeMetadata node2 = nodes.last();
// credentials aren't always the same
// assertEquals(node1.getCredentials(), node2.getCredentials());
assertLocationSameOrChild(node1.getLocation(), template.getLocation());
assertLocationSameOrChild(node2.getLocation(), template.getLocation());
assertEquals(node1.getImageId(), template.getImage().getId());
assertEquals(node2.getImageId(), template.getImage().getId());
// checkOsMatchesTemplate(node1);
// checkOsMatchesTemplate(node2);
// TODO add with script;
}
// protected void checkOsMatchesTemplate(NodeMetadata node) {
// if (node.getOperatingSystem() != null)
// assert
// node.getOperatingSystem().getFamily().equals(getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily())
// : String
// .format("expecting family %s but got %s",
// getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily(),
// node
// .getOperatingSystem());
// }
@Test(timeOut = 60000)
public void testCreateAnotherNodeWithNewContextToEnsureSharedMemIsntRequired() throws Exception {
getDefaultNodeImmediately(group);
initializeContextAndComputeService(overrides);
NodeMetadata node = createDefaultNode(TemplateOptions.Builder.blockUntilRunning(true), group);
checkNodes(Sets.<NodeMetadata> newHashSet(node), group);
assertLocationSameOrChild(node.getLocation(), getDefaultTemplateBuilder().build().getLocation());
// checkOsMatchesTemplate(node);
}
@Test(timeOut = 60000)
public void testCredentialsCache() throws Exception {
LinkedList<NodeMetadata> nodes = new LinkedList<NodeMetadata>();
nodes.add(getDefaultNodeImmediately(group));
initializeContextAndComputeService(overrides);
nodes.add(createDefaultNode(group));
initializeContextAndComputeService(overrides);
for (NodeMetadata node : nodes)
assert (context.getCredentialStore().get("node#" + node.getId()) != null) : "credentials for " + node.getId();
}
protected Map<? extends NodeMetadata, ExecResponse> runJavaInstallationScriptWithCreds(final String group,
OperatingSystem os, LoginCredentials creds) throws RunScriptOnNodesException {
return computeService.runScriptOnNodesMatching(runningInGroup(group), buildScript(os),
overrideLoginCredentials(creds).nameTask("runJavaInstallationScriptWithCreds"));
}
protected Template buildTemplate(TemplateBuilder templateBuilder) {
return templateBuilder.build();
}
@Test(timeOut = 120000)
public void testGetNodeMetadata() throws Exception {
Set<NodeMetadata> nodes = Sets.newHashSet(getDefaultNodeImmediately(group));
Map<String, ? extends NodeMetadata> metadataMap = newLinkedHashMap(uniqueIndex(
filter(computeService.listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))),
new Function<NodeMetadata, String>() {
@Override
public String apply(NodeMetadata from) {
return from.getId();
}
}));
for (NodeMetadata node : nodes) {
awaitForStartup(node.getId());
metadataMap.remove(node.getId());
NodeMetadata nodeMetadata = computeService.getNodeMetadata(node.getId());
assertEquals(parseGroupFromName(nodeMetadata.getName()), group);
assertEquals(nodeMetadata.getProviderId(), node.getProviderId());
assertEquals(nodeMetadata.getGroup(), node.getGroup());
assertLocationSameOrChild(nodeMetadata.getLocation(), getDefaultTemplateBuilder().build().getLocation());
assertEquals(nodeMetadata.getImageId(), getDefaultTemplateBuilder().build().getImage().getId());
// checkOsMatchesTemplate(metadata);
assertEquals(nodeMetadata.getState(), NodeState.RUNNING);
// due to DHCP the addresses can actually change in-between runs.
assertTrue(nodeMetadata.getPrivateAddresses().size() > 0);
assertTrue(nodeMetadata.getPublicAddresses().size() > 0);
}
assertNodeZero(metadataMap.values(), nodes);
}
protected void assertNodeZero(Collection<? extends NodeMetadata> metadataSet, Set<NodeMetadata> nodes) {
assert metadataSet.size() == 0 : String.format("nodes left in set: [%s] which didn't match set: [%s]",
metadataSet, nodes);
}
@Test(timeOut = 60000)
public void testListNodes() throws Exception {
for (ComputeMetadata node : computeService.listNodes()) {
assert node.getProviderId() != null;
assert node.getLocation() != null;
assertEquals(node.getType(), ComputeType.NODE);
}
}
@Test(timeOut = 60000)
public void testGetNodesWithDetails() throws Exception {
for (NodeMetadata node : computeService.listNodesDetailsMatching(all())) {
assert node.getProviderId() != null : node;
assert node.getLocation() != null : node;
assertEquals(node.getType(), ComputeType.NODE);
assert node.getProviderId() != null : node;
// nullable
// assert nodeMetadata.getImage() != null : node;
// user specified name is not always supported
// assert nodeMetadata.getName().parseGroupFromName() != null :
// nodeMetadata;
if (node.getState() == NodeState.RUNNING) {
assert node.getPublicAddresses() != null : node;
assert node.getPublicAddresses().size() > 0 || node.getPrivateAddresses().size() > 0 : node;
assertNotNull(node.getPrivateAddresses());
}
}
}
@Test(timeOut = 60000)
public void testDestroyNodes() {
int toDestroy = getFreshNodes(group).size();
Set<? extends NodeMetadata> destroyed = computeService.destroyNodesMatching(inGroup(group));
assertEquals(toDestroy, destroyed.size());
for (NodeMetadata node : filter(computeService.listNodesDetailsMatching(all()), inGroup(group))) {
assert node.getState() == NodeState.TERMINATED : node;
assertEquals(context.getCredentialStore().get("node#" + node.getId()), null);
}
}
@Test(timeOut = 60000)
public void testCreateAndRunService() throws Exception {
@SuppressWarnings("unused")
NodeMetadata node = getDefaultNodeImmediately(group);
// TODO .inboundPorts
// checkHttpGet(node);
}
public void testListImages() throws Exception {
for (Image image : computeService.listImages()) {
assert image.getProviderId() != null : image;
// image.getLocationId() can be null, if it is a location-free image
assertEquals(image.getType(), ComputeType.IMAGE);
}
}
@Test(timeOut = 60000)
public void testGetAssignableLocations() throws Exception {
for (Location location : computeService.listAssignableLocations()) {
System.err.printf("location %s%n", location);
assert location.getId() != null : location;
assert location != location.getParent() : location;
assert location.getScope() != null : location;
switch (location.getScope()) {
case PROVIDER:
assertProvider(location);
break;
case REGION:
assertProvider(location.getParent());
break;
case ZONE:
Location provider = location.getParent().getParent();
// zone can be a direct descendant of provider
if (provider == null)
provider = location.getParent();
assertProvider(provider);
break;
case HOST:
Location provider2 = location.getParent().getParent().getParent();
// zone can be a direct descendant of provider
if (provider2 == null)
provider2 = location.getParent().getParent();
assertProvider(provider2);
break;
}
}
}
public void testOptionToNotBlock() throws Exception {
// TODO no inbound ports
// TemplateOptions options =
// computeService.templateOptions().blockUntilRunning(false).inboundPorts();
long time = System.currentTimeMillis();
NodeMetadata node = getOnlyElement(computeService.createNodesInGroup(group, 1, getDefaultTemplateBuilder()
.build()));
assert node.getState() != NodeState.RUNNING;
long duration = System.currentTimeMillis() - time;
assert duration < 30 * 1000 : "duration longer than 30 seconds!: " + duration / 1000;
}
private void assertProvider(Location provider) {
assertEquals(provider.getScope(), LocationScope.PROVIDER);
assertEquals(provider.getParent(), null);
}
@Test(timeOut = 60000, enabled = false)
public void testListHardwareProfiles() throws Exception {
// TODO: failing, OpenStack returns a hardware with 0 CPU cores
for (Hardware hardware : computeService.listHardwareProfiles()) {
assert hardware.getProviderId() != null;
assert getCores(hardware) > 0;
assert hardware.getVolumes().size() >= 0;
assert hardware.getRam() > 0;
assertEquals(hardware.getType(), ComputeType.HARDWARE);
}
}
@Test(timeOut = 60000)
public void testCompareSizes() throws Exception {
TemplateBuilder templateBuilder = getDefaultTemplateBuilder();
Hardware defaultSize = templateBuilder.build().getHardware();
Hardware smallest = templateBuilder.smallest().build().getHardware();
Hardware fastest = templateBuilder.fastest().build().getHardware();
Hardware biggest = templateBuilder.biggest().build().getHardware();
System.out.printf("smallest %s%n", smallest);
System.out.printf("fastest %s%n", fastest);
System.out.printf("biggest %s%n", biggest);
assertEquals(defaultSize, smallest);
assert getCores(smallest) <= getCores(fastest);
assert getCores(biggest) <= getCores(fastest);
assert biggest.getRam() >= fastest.getRam();
assert biggest.getRam() >= smallest.getRam();
assert getCores(fastest) >= getCores(biggest);
assert getCores(fastest) >= getCores(smallest);
}
protected void doCheckJavaIsInstalledViaSsh(NodeMetadata node) throws IOException {
SshClient ssh = context.utils().sshForNode().apply(node);
try {
ssh.connect();
ExecResponse hello = ssh.exec("echo hello");
assertEquals(hello.getOutput().trim(), "hello");
ExecResponse exec = ssh.exec("java -version");
assert exec.getError().indexOf("1.6") != -1 || exec.getOutput().indexOf("1.6") != -1 : exec + "\n"
+ ssh.exec("cat /tmp/bootstrap/stdout.log /tmp/bootstrap/stderr.log");
} finally {
if (ssh != null)
ssh.disconnect();
}
}
@AfterTest
protected void cleanup() throws InterruptedException, ExecutionException, TimeoutException {
computeService.destroyNodesMatching(inGroup(group));
context.close();
}
}

View File

@ -1,89 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.live.compute;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import static org.jclouds.compute.predicates.NodePredicates.inGroup;
/**
* @author Victor Galkin
*/
public class ServiceActionsLiveTest extends ComputeBase {
static private String group = "ServiceActionsLiveTest";
@BeforeTest
@Override
public void before() throws IOException, ExecutionException, TimeoutException, InterruptedException {
super.before();
computeService.destroyNodesMatching(inGroup(group));
}
@Test
public void testReboot() throws Exception {
getDefaultNodeImmediately(group);
computeService.rebootNodesMatching(inGroup(group));// TODO test
Thread.sleep(5000);
// // validation
//testGetNodeMetadata();
}
@Test(enabled = false)
public void testSuspendResume() throws Exception {
//TODO: failing, suspend is not supported by the nova provider yet
getDefaultNodeImmediately(group);
computeService.suspendNodesMatching(inGroup(group));
Set<? extends NodeMetadata> stoppedNodes = getFreshNodes(group);
assert Iterables.all(stoppedNodes, new Predicate<NodeMetadata>() {
@Override
public boolean apply(NodeMetadata input) {
boolean returnVal = input.getState() == NodeState.SUSPENDED;
if (!returnVal)
System.err.printf("warning: node %s in state %s%n", input.getId(), input.getState());
return returnVal;
}
}) : stoppedNodes;
computeService.resumeNodesMatching(inGroup(group));
//testGetNodeMetadata();
}
@AfterTest
protected void cleanup() throws InterruptedException, ExecutionException, TimeoutException {
computeService.destroyNodesMatching(inGroup(group));
context.close();
}
}

View File

@ -1,120 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.live.novaclient;
import static org.jclouds.openstack.nova.live.PropertyHelper.setupKeyPair;
import static org.jclouds.openstack.nova.live.PropertyHelper.setupOverrides;
import static org.jclouds.openstack.nova.live.PropertyHelper.setupProperties;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.net.IPSocket;
import org.jclouds.openstack.nova.NovaClient;
import org.jclouds.openstack.nova.domain.Image;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen;
import org.jclouds.rest.RestContextFactory;
import org.jclouds.ssh.SshClient;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.testng.annotations.BeforeTest;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Injector;
import com.google.inject.Module;
/**
* @author Victor Galkin
*/
public class ClientBase {
protected int testImageId;
protected NovaClient client;
protected SshClient.Factory sshFactory;
@SuppressWarnings("unused")
private Predicate<IPSocket> socketTester;
protected String provider = "nova";
protected String serverPrefix = System.getProperty("user.name") + ".cs";
protected Map<String, String> keyPair;
Map<String, String> metadata = ImmutableMap.of("jclouds", "rackspace");
@BeforeTest
public void before() throws IOException {
Properties properties = setupOverrides(setupProperties(this.getClass()));
Injector injector = new RestContextFactory().createContextBuilder(provider,
ImmutableSet.<Module>of(new SLF4JLoggingModule(), new SshjSshClientModule()), properties)
.buildInjector();
client = injector.getInstance(NovaClient.class);
sshFactory = injector.getInstance(SshClient.Factory.class);
SocketOpen socketOpen = injector.getInstance(SocketOpen.class);
socketTester = new RetryablePredicate<IPSocket>(socketOpen, 120, 1, TimeUnit.SECONDS);
injector.injectMembers(socketOpen); // add logger
keyPair = setupKeyPair(properties);
testImageId = Integer.valueOf(properties.getProperty("test.nova.image.id"));
}
protected Server getDefaultServerImmediately() {
String defaultName = serverPrefix + "default";
for (Server server : client.listServers()) {
if (server.getName().equals(defaultName))
return server;
}
return createDefaultServer(defaultName);
}
protected Server createDefaultServer(String serverName) {
String imageRef = client.getImage(testImageId).getURI().toASCIIString();
String flavorRef = client.getFlavor(1).getURI().toASCIIString();
return client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt",
"rackspace".getBytes()).withMetadata(metadata));
}
protected Image getDefaultImageImmediately(Server server) {
String defaultName = "hoofie";
for (Image image : client.listImages()) {
if (image.getName() != null)
if (image.getName().equals(defaultName))
return image;
}
return createDefaultImage("hoofie", server);
}
private Image createDefaultImage(String name, Server server) {
return client.createImageFromServer("hoofie", server.getId());
}
protected void waitServerDeleted(int serverId) throws InterruptedException {
while (null != client.getServer(serverId)) {
System.out.println("Await deleted server" + serverId);
Thread.sleep(1000);
}
}
}

View File

@ -1,67 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.live.novaclient;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import org.jclouds.net.IPSocket;
import org.jclouds.openstack.nova.NovaClient;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus;
import org.jclouds.ssh.SshClient;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import java.util.Map;
/**
* @author Victor Galkin
*/
@Test(groups = "live", sequential = true)
public class DeleteServersInVariousStatesLiveTest {
protected NovaClient client;
protected SshClient.Factory sshFactory;
@SuppressWarnings("unused")
private Predicate<IPSocket> socketTester;
protected String provider = "nova";
Map<String, String> metadata = ImmutableMap.of("jclouds", "rackspace");
Server server = null;
@AfterMethod
public void after() {
if (server != null) client.deleteServer(server.getId());
}
@Test(enabled = true)
public void testDeleteAfterCreate() throws Exception {
}
@SuppressWarnings("unused")
private void blockUntilServerActive(int serverId) throws InterruptedException {
Server currentDetails;
for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.ACTIVE; currentDetails = client
.getServer(serverId)) {
System.out.printf("blocking on status active%n%s%n", currentDetails);
Thread.sleep(5 * 1000);
}
}
}

View File

@ -1,396 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.live.novaclient;
import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import java.io.IOException;
import java.util.Set;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.http.HttpResponseException;
import org.jclouds.io.Payload;
import org.jclouds.net.IPSocket;
import org.jclouds.openstack.nova.domain.Flavor;
import org.jclouds.openstack.nova.domain.Image;
import org.jclouds.openstack.nova.domain.ImageStatus;
import org.jclouds.openstack.nova.domain.RebootType;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus;
import org.jclouds.openstack.nova.options.RebuildServerOptions;
import org.jclouds.ssh.SshClient;
import org.jclouds.util.Strings2;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;
import com.google.common.collect.Iterables;
/**
* Tests behavior of {@code NovaClient}
*
* @author Adrian Cole
*/
// disabled [Web Hosting #129069
@Test(groups = "live", sequential = true)
public class NovaClientLiveTest extends ClientBase {
@Test
public void testListServers() throws Exception {
Set<Server> response = client.listServers();
assert null != response;
long initialContainerCount = response.size();
assertTrue(initialContainerCount >= 0);
}
@Test
public void testListServersDetail() throws Exception {
Set<Server> response = client.listServers(withDetails());
assert null != response;
long initialContainerCount = response.size();
assertTrue(initialContainerCount >= 0);
}
@Test(enabled = false)
public void testListImages() throws Exception {
//TODO: failing, image name should not be null (issue in the OpenStack)
Set<Image> response = client.listImages();
assert null != response;
long imageCount = response.size();
assertTrue(imageCount >= 1);
for (Image image : response) {
assertTrue(image.getId() >= 0);
assert null != image.getName() : image;
}
}
@Test(enabled = false)
public void testListImagesDetail() throws Exception {
//TODO: failing, image name should not be null (issue in the OpenStack)
Set<Image> response = client.listImages(withDetails());
assert null != response;
long imageCount = response.size();
assertTrue(imageCount >= 0);
for (Image image : response) {
assertTrue(image.getId() >= 1);
assert null != image.getName() : image;
assert null != image.getStatus() : image;
}
}
@Test
public void testGetImagesDetail() throws Exception {
Set<Image> response = client.listImages(withDetails());
assert null != response;
long imageCount = response.size();
assertTrue(imageCount >= 0);
for (Image image : response) {
try {
Image newDetails = client.getImage(image.getId());
assertEquals(image, newDetails);
} catch (HttpResponseException e) {// Ticket #9867
if (e.getResponse().getStatusCode() != 400)
throw e;
}
}
}
@Test
public void testGetImageDetailsNotFound() throws Exception {
assert client.getImage(12312987) == null;
}
@Test
public void testGetServerDetailsNotFound() throws Exception {
assert client.getServer(12312987) == null;
}
@Test
public void testGetServersDetail() throws Exception {
Set<Server> response = client.listServers(withDetails());
assert null != response;
assertTrue(response.size() >= 0);
for (Server server : response) {
Server newDetails = client.getServer(server.getId());
System.out.println("====");
System.out.println(server);
System.out.println(newDetails);
System.out.println("====");
}
for (Server server : response) {
Server newDetails = client.getServer(server.getId());
assertEquals(server, newDetails);
}
}
@Test
public void testListFlavors() throws Exception {
Set<Flavor> response = client.listFlavors();
assert null != response;
long flavorCount = response.size();
assertTrue(flavorCount >= 1);
for (Flavor flavor : response) {
assertTrue(flavor.getId() >= 0);
assert null != flavor.getName() : flavor;
}
}
@Test
public void testListFlavorsDetail() throws Exception {
Set<Flavor> response = client.listFlavors(withDetails());
assert null != response;
long flavorCount = response.size();
assertTrue(flavorCount >= 0);
for (Flavor flavor : response) {
assertTrue(flavor.getId() >= 1);
assert null != flavor.getName() : flavor;
assert null != flavor.getDisk() : flavor;
assert null != flavor.getRam() : flavor;
}
}
@Test
public void testGetFlavorsDetail() throws Exception {
Set<Flavor> response = client.listFlavors(withDetails());
assert null != response;
long flavorCount = response.size();
assertTrue(flavorCount >= 0);
for (Flavor flavor : response) {
Flavor newDetails = client.getFlavor(flavor.getId());
assertEquals(flavor, newDetails);
}
}
@Test
public void testGetFlavorDetailsNotFound() throws Exception {
assert client.getFlavor(12312987) == null;
}
@Test(enabled = true)
public void testCreateServer() throws Exception {
Server server = createDefaultServer(serverPrefix + "for_create");
assertNotNull(server.getAdminPass());
int serverId = server.getId();
@SuppressWarnings("unused")
String adminPass = server.getAdminPass();
blockUntilServerActive(serverId);
blockUntilPublicAddress(serverId);
client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next().getAddress();
}
private void blockUntilPublicAddress(int serverId) throws InterruptedException {
while (client.getServer(serverId).getAddresses().getPublicAddresses().isEmpty()) {
System.out.println("Awaiting public address");
Thread.sleep(1000);
}
}
private void blockUntilServerActive(int serverId) throws InterruptedException {
Server currentDetails;
for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.ACTIVE; currentDetails = client
.getServer(serverId)) {
System.out.printf("blocking on status active%n%s%n", currentDetails);
Thread.sleep(5 * 1000);
}
}
private void blockUntilServerVerifyResize(int serverId) throws InterruptedException {
Server currentDetails;
for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.VERIFY_RESIZE; currentDetails = client
.getServer(serverId)) {
System.out.printf("blocking on status verify resize%n%s%n", currentDetails);
Thread.sleep(5 * 1000);
}
}
private void blockUntilImageActive(int createdImageId) throws InterruptedException {
Image currentDetails;
for (currentDetails = client.getImage(createdImageId); currentDetails.getStatus() != ImageStatus.ACTIVE; currentDetails = client
.getImage(createdImageId)) {
System.out.printf("blocking on status active%n%s%n", currentDetails);
Thread.sleep(5 * 1000);
}
}
@Test(enabled = false, timeOut = 300000)
public void testServerDetails() throws Exception {
//TODO: failing, /v1.1/servers/{server id}/ips URL is not available (issue in the OpenStack)
Server server = getDefaultServerImmediately();
assertNotNull(server.getHostId(), "Host id: ");
assertNotNull(server.getAddresses());
// check metadata
assertEquals(server.getMetadata(), metadata);
assertTrue(server.getImageRef().endsWith(String.valueOf(testImageId)));
// listAddresses tests..
assertEquals(client.getAddresses(server.getId()), server.getAddresses());
assertEquals(server.getAddresses().getPublicAddresses().size(), 1);
assertEquals(client.listPublicAddresses(server.getId()), server.getAddresses().getPublicAddresses());
assertEquals(server.getAddresses().getPrivateAddresses().size(), 1);
assertEquals(client.listPrivateAddresses(server.getId()), server.getAddresses().getPrivateAddresses());
assertPassword(server, server.getAdminPass());
assertTrue(server.getFlavorRef().endsWith("1"));
assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress();
}
private void assertPassword(Server server, String pass) throws IOException {
IPSocket socket = new IPSocket(Iterables.get(server.getAddresses().getPublicAddresses(), 0).getAddress(), 22);
//socketTester.apply(socket);
SshClient client = sshFactory.create(socket,
LoginCredentials.builder().user("root").privateKey(keyPair.get("private")).build());
try {
client.connect();
Payload etcPasswd = client.get("/etc/jclouds.txt");
String etcPasswdContents = Strings2.toStringAndClose(etcPasswd.getInput());
assertEquals("rackspace", etcPasswdContents.trim());
} finally {
if (client != null)
client.disconnect();
}
}
@Test(enabled = true, timeOut = 5 * 60 * 1000)
public void testRenameServer() throws Exception {
Server server = getDefaultServerImmediately();
int serverId = server.getId();
String oldName = server.getName();
client.renameServer(serverId, oldName + "new");
blockUntilServerActive(serverId);
assertEquals(oldName + "new", client.getServer(serverId).getName());
}
@Test(enabled = false, timeOut = 5 * 60 * 1000)
public void testChangePassword() throws Exception {
//TODO: failing, fix acceptPassword method logic, however password is not changed by OpenStack
int serverId = getDefaultServerImmediately().getId();
blockUntilServerActive(serverId);
blockUntilPublicAddress(serverId);
client.changeAdminPass(serverId, "elmo");
//TODO: wait until SSH is available
assertPassword(client.getServer(serverId), "elmo");
}
@Test(enabled = false, timeOut = 10 * 600 * 1000)
public void testCreateImage() throws Exception {
//TODO: failing, create image from instance returns incorrect JSON
Server server = getDefaultServerImmediately();
Image image = getDefaultImageImmediately(server);
blockUntilImageActive(image.getId());
assertEquals("hoofie", image.getName());
assertEquals(image.getServerRef(), "");
}
@Test(enabled = false, timeOut = 10 * 60 * 1000)
public void testRebuildServer() throws Exception {
//TODO: failing, create image from instance returns incorrect JSON
Server server = getDefaultServerImmediately();
Image image = getDefaultImageImmediately(server);
client.rebuildServer(server.getId(), new RebuildServerOptions().withImage(String.valueOf(image.getId())));
blockUntilServerActive(server.getId());
// issue Web Hosting #119580 createdImageId comes back incorrect after rebuild
assertEquals(image.getURI(), client.getServer(server.getId()).getImageRef());
}
@Test(enabled = true, timeOut = 10 * 60 * 1000)
public void testRebootHard() throws Exception {
Server server = getDefaultServerImmediately();
client.rebootServer(server.getId(), RebootType.HARD);
blockUntilServerActive(server.getId());
//TODO check
}
@Test(enabled = true, timeOut = 10 * 60 * 1000)
public void testRebootSoft() throws Exception {
Server server = getDefaultServerImmediately();
client.rebootServer(server.getId(), RebootType.SOFT);
blockUntilServerActive(server.getId());
//TODO check
}
@Test(enabled = false, timeOut = 60000, dependsOnMethods = "testRebootSoft")
public void testRevertResize() throws Exception {
Server server = getDefaultServerImmediately();
int serverId = server.getId();
client.resizeServer(serverId, 2);
blockUntilServerVerifyResize(serverId);
client.revertResizeServer(serverId);
blockUntilServerActive(serverId);
assertEquals(1, client.getServer(serverId).getFlavorRef());
}
@Test(enabled = false, timeOut = 10 * 60 * 1000)
public void testConfirmResize() throws Exception {
Server server = getDefaultServerImmediately();
int serverId = server.getId();
client.resizeServer(serverId, 2);
blockUntilServerVerifyResize(serverId);
client.confirmResizeServer(serverId);
blockUntilServerActive(serverId);
assertEquals(2, client.getServer(serverId).getFlavorRef());
}
@Test(enabled = true, timeOut = 60000)
void deleteServer2() throws Exception {
Server server = getDefaultServerImmediately();
int serverId = server.getId();
client.deleteServer(serverId);
waitServerDeleted(serverId);
}
@Test(enabled = false, timeOut = 60000)
void testDeleteImage() throws Exception {
//TODO: failing, create image from instance returns incorrect JSON
Image image = getDefaultImageImmediately(getDefaultServerImmediately());
client.deleteImage(image.getId());
assert client.getImage(image.getId()) == null;
}
@Test(enabled = true, timeOut = 60000)
void deleteServer1() throws Exception {
Server server = getDefaultServerImmediately();
int serverId = server.getId();
client.deleteServer(serverId);
waitServerDeleted(serverId);
}
@Test
public void testDeleteAllCreatedServers() {
for (Server server : client.listServers()) {
if (server.getName().startsWith(serverPrefix)) {
client.deleteServer(server.getId());
System.out.println("Deleted server: " + server);
}
}
}
@AfterTest
void deleteServersOnEnd() {
testDeleteAllCreatedServers();
}
}

View File

@ -1,136 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you 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.
*/
package org.jclouds.openstack.nova.live.novaclient;
import static org.jclouds.openstack.nova.live.PropertyHelper.setupKeyPair;
import static org.jclouds.openstack.nova.live.PropertyHelper.setupOverrides;
import static org.jclouds.openstack.nova.live.PropertyHelper.setupProperties;
import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.jclouds.http.HttpResponseException;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.net.IPSocket;
import org.jclouds.openstack.nova.NovaClient;
import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen;
import org.jclouds.rest.RestContextFactory;
import org.jclouds.ssh.SshClient;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Injector;
import com.google.inject.Module;
/**
* @author Victor Galkin
*/
@Test(groups = "live", sequential = true)
public class ServerCreateLiveTest {
protected NovaClient client;
protected SshClient.Factory sshFactory;
@SuppressWarnings("unused")
private Predicate<IPSocket> socketTester;
protected String provider = "nova";
Map<String, String> metadata = ImmutableMap.of("jclouds", "rackspace");
Server server = null;
Map<String, String> keyPair;
@BeforeTest
public void setupClient() throws IOException {
Properties properties = setupOverrides(setupProperties(this.getClass()));
Injector injector = new RestContextFactory().createContextBuilder(provider,
ImmutableSet.<Module>of(new SLF4JLoggingModule(), new SshjSshClientModule()), properties)
.buildInjector();
client = injector.getInstance(NovaClient.class);
sshFactory = injector.getInstance(SshClient.Factory.class);
SocketOpen socketOpen = injector.getInstance(SocketOpen.class);
socketTester = new RetryablePredicate<IPSocket>(socketOpen, 120, 1, TimeUnit.SECONDS);
injector.injectMembers(socketOpen); // add logger
keyPair = setupKeyPair(properties);
}
@Test(expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = ".*Internal Server Error.*")
public void testCreateServerWithUnknownImage() throws Exception {
try {
server = client.createServer("serverName", String.valueOf(88888888), "1", withFile("/etc/jclouds.txt",
"rackspace".getBytes()).withMetadata(metadata));
} catch (HttpResponseException e) {
throw e;
}
}
@Test(expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = ".*Internal Server Error.*")
public void testCreateServerWithUnknownFlavor() throws Exception {
try {
server = client.createServer("serverName", String.valueOf(13), "88888888", withFile("/etc/jclouds.txt",
"rackspace".getBytes()).withMetadata(metadata));
} catch (HttpResponseException e) {
throw e;
}
}
@AfterMethod
public void after() {
if (server != null) client.deleteServer(server.getId());
}
@Test(enabled = true)
public void testCreateServer() throws Exception {
// String imageRef = client.getImage(13).getURI().toASCIIString();
// String flavorRef = client.getFlavor(1).getURI().toASCIIString();
// String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt();
// Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt",
// "rackspace".getBytes()).withMetadata(metadata));
//
// assertNotNull(server.getAdminPass());
// assertEquals(server.getStatus(), ServerStatus.BUILD);
// serverId = server.getId();
// adminPass = server.getAdminPass();
// blockUntilServerActive(serverId);
// client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next().getAddress();
}
@SuppressWarnings("unused")
private void blockUntilServerActive(int serverId) throws InterruptedException {
Server currentDetails;
for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.ACTIVE; currentDetails = client
.getServer(serverId)) {
System.out.printf("blocking on status active%n%s%n", currentDetails);
Thread.sleep(5 * 1000);
}
}
}

View File

@ -1,7 +0,0 @@
test.nova.endpoint=http://dragon004.hw.griddynamics.net:8774
test.nova.apiversion=1.1
test.nova.identity=admin
test.nova.credential=d744752f-20d3-4d75-979f-f62f16033b07
test.nova.image.id=17
test.ssh.keyfile.private=/keys/rhelimg.pem
test.ssh.keyfile.public=/keys/rhelimg.pub

View File

@ -1,15 +0,0 @@
-----BEGIN RSA PRIVATE KEY-----
MIICWgIBAAKBgQDItJzHxyFVPZwjE2Wl+17OLJotFruaMaoKLOH8yOr0WnKFYDCs
AiN88AvwH2YKaF6SQR3gmMTE8SbuKSXR/PVUZfWfhvDinVbAi8gn8A6P5xkym5A6
uBnJn1Mb0rZAKCJT/nN62vomGGO/3VYkpQcKAWgfSpaB7F1BIebaWR/CgQIBIwKB
gQCa1Hjx4sHxTMjn28NxaiSQa4zg9EeUNPDjRzH9hQ0FpNwAfWdgHugtLjUYUrxu
bcVMQNyIsF1HeDP5jXTycq6e01EYDODnuPC3a06u6Drep0xm/8XuODwekApN811r
kfx9AsgRL9ZwkLqMY8E+OXUmsGVXzEM9jUO3iwA4CCBb/wJBAO0klCumLDm9rYXX
m3YHuwqcgFPnwSodTWX4tIzHKM0tn3PwajJ1x9kCVxsj9uFzz4LXNrxVrUKcYnVx
e/d7sksCQQDYqkr+vt9XaoQSio1M/OOkzc3ynmqtYrNrq9xM1M5IYY2/y5IVLAU3
6tiyqXTObSTJT+iFd+OwQymi8FgeN77jAkBzLwYj1F6fs+aRd1ojYtcxCi+zubWY
HNxzW4rlSsqszQROQZKqy35TdipPAtb/yolczu6zP46rU0XEA+vBWVaZAkB1nkX4
ATdp9/6NuO2e0mzzEKMADNrTJvOveo2Iy0tpHwPOhHPfm43N5eNZrHKb8htItlmn
ijnGFdTGKrN+HkMNAkAqh8ulNxVBAK5E0VzzzC2zAh2UFRe3J5K0SgzFkR8W9aM1
Vb+iZvj4tVlbFtFLGv0ssty8Q0jS7+Hy75XMatry
-----END RSA PRIVATE KEY-----

View File

@ -1,18 +0,0 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="STDOUT" />
</root>
<logger name="org.jclouds" level="debug" />
<logger name="jclouds.wire" level="debug" />
<logger name="jclouds.headers" level="debug" />
<logger name="jclouds.ssh" level="debug" />
</configuration>

View File

@ -23,6 +23,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URI;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
@ -90,12 +91,14 @@ public interface OpenStackAuthAsyncClient {
}
@GET
@Consumes
@ResponseParser(ParseAuthenticationResponseFromHeaders.class)
ListenableFuture<AuthenticationResponse> authenticate(@HeaderParam(AuthHeaders.AUTH_USER) String user,
@HeaderParam(AuthHeaders.AUTH_KEY) String key);
@GET
@Consumes
@ResponseParser(ParseAuthenticationResponseFromHeaders.class)
ListenableFuture<AuthenticationResponse> authenticateStorage(@HeaderParam(AuthHeaders.STORAGE_USER) String user,
@HeaderParam(AuthHeaders.STORAGE_PASS) String key);

View File

@ -51,7 +51,7 @@ public class OpenStackAuthAsyncClientTest extends RestClientTest<OpenStackAuthAs
HttpRequest httpRequest = processor.createRequest(method, "foo", "bar");
assertRequestLineEquals(httpRequest, "GET http://localhost:8080/v1.0 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "X-Auth-Key: bar\nX-Auth-User: foo\n");
assertNonPayloadHeadersEqual(httpRequest, "Accept: */*\nX-Auth-Key: bar\nX-Auth-User: foo\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseAuthenticationResponseFromHeaders.class);
@ -65,7 +65,7 @@ public class OpenStackAuthAsyncClientTest extends RestClientTest<OpenStackAuthAs
HttpRequest httpRequest = processor.createRequest(method, "foo", "bar");
assertRequestLineEquals(httpRequest, "GET http://localhost:8080/v1.0 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "X-Storage-Pass: bar\nX-Storage-User: foo\n");
assertNonPayloadHeadersEqual(httpRequest, "Accept: */*\nX-Storage-Pass: bar\nX-Storage-User: foo\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseAuthenticationResponseFromHeaders.class);