diff --git a/LICENSE.header b/LICENSE.header
new file mode 100644
index 00000000000..4eacb643179
--- /dev/null
+++ b/LICENSE.header
@@ -0,0 +1,16 @@
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF 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.
diff --git a/agent/pom.xml b/agent/pom.xml
index 4e5caae80df..2036ae0ca39 100644
--- a/agent/pom.xml
+++ b/agent/pom.xml
@@ -115,38 +115,5 @@
-
-
-
-
- org.eclipse.m2e
- lifecycle-mapping
- 1.0.0
-
-
-
-
-
-
- org.apache.maven.plugins
-
-
- maven-antrun-plugin
-
- [1.7,)
-
- run
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/api/src/com/cloud/deploy/DeployDestination.java b/api/src/com/cloud/deploy/DeployDestination.java
index 05625d60b0f..4ded5ebe7a1 100644
--- a/api/src/com/cloud/deploy/DeployDestination.java
+++ b/api/src/com/cloud/deploy/DeployDestination.java
@@ -16,6 +16,7 @@
// under the License.
package com.cloud.deploy;
+import java.io.Serializable;
import java.util.Map;
import com.cloud.dc.DataCenter;
@@ -26,7 +27,9 @@ import com.cloud.storage.StoragePool;
import com.cloud.storage.Volume;
import com.cloud.utils.NumbersUtil;
-public class DeployDestination {
+public class DeployDestination implements Serializable {
+ private static final long serialVersionUID = 7113840781939014695L;
+
DataCenter _dc;
Pod _pod;
Cluster _cluster;
@@ -76,28 +79,28 @@ public class DeployDestination {
@Override
public boolean equals(Object obj) {
DeployDestination that = (DeployDestination)obj;
- if (this._dc == null || that._dc == null) {
+ if (_dc == null || that._dc == null) {
return false;
}
- if (this._dc.getId() != that._dc.getId()) {
+ if (_dc.getId() != that._dc.getId()) {
return false;
}
- if (this._pod == null || that._pod == null) {
+ if (_pod == null || that._pod == null) {
return false;
}
- if (this._pod.getId() != that._pod.getId()) {
+ if (_pod.getId() != that._pod.getId()) {
return false;
}
- if (this._cluster == null || that._cluster == null) {
+ if (_cluster == null || that._cluster == null) {
return false;
}
- if (this._cluster.getId() != that._cluster.getId()) {
+ if (_cluster.getId() != that._cluster.getId()) {
return false;
}
- if (this._host == null || that._host == null) {
+ if (_host == null || that._host == null) {
return false;
}
- return this._host.getId() == that._host.getId();
+ return _host.getId() == that._host.getId();
}
@Override
diff --git a/api/src/com/cloud/deploy/DeploymentPlanner.java b/api/src/com/cloud/deploy/DeploymentPlanner.java
index 35f406d04f9..eb62cb178bb 100644
--- a/api/src/com/cloud/deploy/DeploymentPlanner.java
+++ b/api/src/com/cloud/deploy/DeploymentPlanner.java
@@ -16,6 +16,7 @@
// under the License.
package com.cloud.deploy;
+import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
@@ -89,7 +90,9 @@ public interface DeploymentPlanner extends Adapter {
Shared, Dedicated;
}
- public static class ExcludeList {
+ public static class ExcludeList implements Serializable {
+ private static final long serialVersionUID = -482175549460148301L;
+
private Set _dcIds;
private Set _podIds;
private Set _clusterIds;
@@ -173,6 +176,12 @@ public interface DeploymentPlanner extends Adapter {
_poolIds.add(poolId);
}
+ public void removePool(long poolId) {
+ if (_poolIds != null) {
+ _poolIds.remove(poolId);
+ }
+ }
+
public void addDataCenter(long dataCenterId) {
if (_dcIds == null) {
_dcIds = new HashSet();
diff --git a/api/src/com/cloud/deploy/HAPlanner.java b/api/src/com/cloud/deploy/HAPlanner.java
new file mode 100644
index 00000000000..aeb5083c522
--- /dev/null
+++ b/api/src/com/cloud/deploy/HAPlanner.java
@@ -0,0 +1,21 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF 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 com.cloud.deploy;
+
+
+public interface HAPlanner extends DeploymentPlanner {
+}
\ No newline at end of file
diff --git a/api/src/com/cloud/event/EventTypes.java b/api/src/com/cloud/event/EventTypes.java
index 5a342cd284d..e88f0104ea7 100755
--- a/api/src/com/cloud/event/EventTypes.java
+++ b/api/src/com/cloud/event/EventTypes.java
@@ -455,6 +455,11 @@ public class EventTypes {
//Alert generation
public static final String ALERT_GENERATE = "ALERT.GENERATE";
+ // OpenDaylight
+ public static final String EVENT_EXTERNAL_OPENDAYLIGHT_ADD_CONTROLLER = "PHYSICAL.ODLCONTROLLER.ADD";
+ public static final String EVENT_EXTERNAL_OPENDAYLIGHT_DELETE_CONTROLLER = "PHYSICAL.ODLCONTROLLER.DELETE";
+ public static final String EVENT_EXTERNAL_OPENDAYLIGHT_CONFIGURE_CONTROLLER = "PHYSICAL.ODLCONTROLLER.CONFIGURE";
+
static {
// TODO: need a way to force author adding event types to declare the entity details as well, with out braking
@@ -760,6 +765,11 @@ public class EventTypes {
entityEventDetails.put(EVENT_AUTOSCALEVMGROUP_DISABLE, AutoScaleVmGroup.class.getName());
entityEventDetails.put(EVENT_GUEST_VLAN_RANGE_DEDICATE, GuestVlan.class.getName());
entityEventDetails.put(EVENT_DEDICATED_GUEST_VLAN_RANGE_RELEASE, GuestVlan.class.getName());
+
+ // OpenDaylight
+ entityEventDetails.put(EVENT_EXTERNAL_OPENDAYLIGHT_ADD_CONTROLLER, "OpenDaylightController");
+ entityEventDetails.put(EVENT_EXTERNAL_OPENDAYLIGHT_DELETE_CONTROLLER, "OpenDaylightController");
+ entityEventDetails.put(EVENT_EXTERNAL_OPENDAYLIGHT_CONFIGURE_CONTROLLER, "OpenDaylightController");
}
public static String getEntityForEvent(String eventName) {
diff --git a/api/src/com/cloud/exception/CloudException.java b/api/src/com/cloud/exception/CloudException.java
index f898719028b..f35249b0732 100644
--- a/api/src/com/cloud/exception/CloudException.java
+++ b/api/src/com/cloud/exception/CloudException.java
@@ -27,6 +27,7 @@ import com.cloud.utils.exception.CSExceptionErrorCode;
*/
public class CloudException extends Exception {
+ private static final long serialVersionUID = 8784427323859682503L;
// This holds a list of uuids and their names. Add uuid:fieldname pairs
protected ArrayList idList = new ArrayList();
@@ -58,10 +59,10 @@ public class CloudException extends Exception {
}
public void setCSErrorCode(int cserrcode) {
- this.csErrorCode = cserrcode;
+ csErrorCode = cserrcode;
}
public int getCSErrorCode() {
- return this.csErrorCode;
+ return csErrorCode;
}
}
diff --git a/api/src/com/cloud/exception/OperationTimedoutException.java b/api/src/com/cloud/exception/OperationTimedoutException.java
index d531c326c37..fe27408eb4e 100644
--- a/api/src/com/cloud/exception/OperationTimedoutException.java
+++ b/api/src/com/cloud/exception/OperationTimedoutException.java
@@ -28,7 +28,15 @@ public class OperationTimedoutException extends CloudException {
long _agentId;
long _seqId;
int _time;
- Command[] _cmds;
+
+ // TODO
+ // I did a reference search on usage of getCommands() and found none
+ //
+ // to prevent serialization problems across boundaries, I'm disabling serialization of _cmds here
+ // getCommands() will still be available within the same serialization boundary, but it will be lost
+ // when exception is propagated across job boundaries.
+ //
+ transient Command[] _cmds;
boolean _isActive;
public OperationTimedoutException(Command[] cmds, long agentId, long seqId, int time, boolean isActive) {
diff --git a/api/src/com/cloud/host/Host.java b/api/src/com/cloud/host/Host.java
index 9d811255e14..689ed12b64e 100755
--- a/api/src/com/cloud/host/Host.java
+++ b/api/src/com/cloud/host/Host.java
@@ -78,6 +78,11 @@ public interface Host extends StateObject, Identity, InternalIdentity {
*/
String getPrivateIpAddress();
+ /**
+ * @return the ip address of the host.
+ */
+ String getStorageUrl();
+
/**
* @return the ip address of the host attached to the storage network.
*/
diff --git a/api/src/com/cloud/hypervisor/HypervisorGuru.java b/api/src/com/cloud/hypervisor/HypervisorGuru.java
index 03493726176..4a35cecb887 100644
--- a/api/src/com/cloud/hypervisor/HypervisorGuru.java
+++ b/api/src/com/cloud/hypervisor/HypervisorGuru.java
@@ -75,4 +75,6 @@ public interface HypervisorGuru extends Adapter {
*
*/
List finalizeExpungeNics(VirtualMachine vm, List nics);
+
+ List finalizeExpungeVolumes(VirtualMachine vm);
}
diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java
index d19c999f16e..2197c2b7143 100644
--- a/api/src/com/cloud/network/Network.java
+++ b/api/src/com/cloud/network/Network.java
@@ -16,6 +16,7 @@
// under the License.
package com.cloud.network;
+import java.io.Serializable;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
@@ -33,7 +34,7 @@ import com.cloud.utils.fsm.StateObject;
/**
* owned by an account.
*/
-public interface Network extends ControlledEntity, StateObject, InternalIdentity, Identity {
+public interface Network extends ControlledEntity, StateObject, InternalIdentity, Identity, Serializable {
public enum GuestType {
Shared, Isolated
@@ -47,9 +48,9 @@ public interface Network extends ControlledEntity, StateObject, I
public static final Service Dns = new Service("Dns", Capability.AllowDnsSuffixModification);
public static final Service Gateway = new Service("Gateway");
public static final Service Firewall = new Service("Firewall", Capability.SupportedProtocols, Capability.MultipleIps, Capability.TrafficStatistics,
- Capability.SupportedTrafficDirection, Capability.SupportedEgressProtocols);
+ Capability.SupportedTrafficDirection, Capability.SupportedEgressProtocols);
public static final Service Lb = new Service("Lb", Capability.SupportedLBAlgorithms, Capability.SupportedLBIsolation, Capability.SupportedProtocols,
- Capability.TrafficStatistics, Capability.LoadBalancingSupportedIps, Capability.SupportedStickinessMethods, Capability.ElasticLb, Capability.LbSchemes);
+ Capability.TrafficStatistics, Capability.LoadBalancingSupportedIps, Capability.SupportedStickinessMethods, Capability.ElasticLb, Capability.LbSchemes);
public static final Service UserData = new Service("UserData");
public static final Service SourceNat = new Service("SourceNat", Capability.SupportedSourceNatTypes, Capability.RedundantRouter);
public static final Service StaticNat = new Service("StaticNat", Capability.ElasticIp);
@@ -128,6 +129,7 @@ public interface Network extends ControlledEntity, StateObject, I
public static final Provider CiscoVnmc = new Provider("CiscoVnmc", true);
// add new Ovs provider
public static final Provider Ovs = new Provider("Ovs", false);
+ public static final Provider Opendaylight = new Provider("Opendaylight", false);
private final String name;
private final boolean isExternal;
@@ -213,7 +215,7 @@ public interface Network extends ControlledEntity, StateObject, I
Allocated("Indicates the network configuration is in allocated but not setup"), Setup("Indicates the network configuration is setup"), Implementing(
"Indicates the network configuration is being implemented"), Implemented("Indicates the network configuration is in use"), Shutdown(
- "Indicates the network configuration is being destroyed"), Destroy("Indicates that the network is destroyed");
+ "Indicates the network configuration is being destroyed"), Destroy("Indicates that the network is destroyed");
protected static final StateMachine2 s_fsm = new StateMachine2();
@@ -223,7 +225,7 @@ public interface Network extends ControlledEntity, StateObject, I
s_fsm.addTransition(State.Implementing, Event.OperationFailed, State.Shutdown);
s_fsm.addTransition(State.Implemented, Event.DestroyNetwork, State.Shutdown);
s_fsm.addTransition(State.Shutdown, Event.OperationSucceeded, State.Allocated);
- s_fsm.addTransition(State.Shutdown, Event.OperationFailed, State.Implemented);
+ s_fsm.addTransition(State.Shutdown, Event.OperationFailed, State.Shutdown);
s_fsm.addTransition(State.Setup, Event.DestroyNetwork, State.Destroy);
s_fsm.addTransition(State.Allocated, Event.DestroyNetwork, State.Destroy);
}
diff --git a/api/src/com/cloud/network/NetworkModel.java b/api/src/com/cloud/network/NetworkModel.java
index fcb6a2e58f4..f6555db565e 100644
--- a/api/src/com/cloud/network/NetworkModel.java
+++ b/api/src/com/cloud/network/NetworkModel.java
@@ -60,6 +60,8 @@ public interface NetworkModel {
*/
List extends IpAddress> listPublicIpsAssignedToGuestNtwk(long accountId, long associatedNetworkId, Boolean sourceNat);
+ List extends IpAddress> listPublicIpsAssignedToGuestNtwk(long associatedNetworkId, Boolean sourceNat);
+
List extends NetworkOffering> getSystemAccountNetworkOfferings(String... offeringNames);
List extends Nic> getNics(long vmId);
diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java
index 57e95c947cd..489bc6cebf0 100755
--- a/api/src/com/cloud/network/NetworkService.java
+++ b/api/src/com/cloud/network/NetworkService.java
@@ -62,7 +62,7 @@ public interface NetworkService {
Network createGuestNetwork(CreateNetworkCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException;
- List extends Network> searchForNetworks(ListNetworksCmd cmd);
+ Pair, Integer> searchForNetworks(ListNetworksCmd cmd);
boolean deleteNetwork(long networkId);
@@ -168,7 +168,7 @@ public interface NetworkService {
InsufficientCapacityException;
/* Requests an IP address for the guest nic */
- NicSecondaryIp allocateSecondaryGuestIP(Account account, long zoneId, Long nicId, Long networkId, String ipaddress) throws InsufficientAddressCapacityException;
+ NicSecondaryIp allocateSecondaryGuestIP(long nicId, String ipaddress) throws InsufficientAddressCapacityException;
boolean releaseSecondaryIpFromNic(long ipAddressId);
diff --git a/api/src/com/cloud/network/Networks.java b/api/src/com/cloud/network/Networks.java
index e4034a5d174..b2c04cda00c 100755
--- a/api/src/com/cloud/network/Networks.java
+++ b/api/src/com/cloud/network/Networks.java
@@ -94,7 +94,7 @@ public class Networks {
return uri.getSchemeSpecificPart();
}
},
- Mido("mido", String.class), Pvlan("pvlan", String.class), Vxlan("vxlan", Long.class), UnDecided(null, null);
+ Mido("mido", String.class), Pvlan("pvlan", String.class), Vxlan("vxlan", Long.class), UnDecided(null, null), OpenDaylight("opendaylight", String.class);
private final String scheme;
private final Class> type;
diff --git a/api/src/com/cloud/network/PhysicalNetwork.java b/api/src/com/cloud/network/PhysicalNetwork.java
index cfa236d3898..5c348c21b7a 100644
--- a/api/src/com/cloud/network/PhysicalNetwork.java
+++ b/api/src/com/cloud/network/PhysicalNetwork.java
@@ -33,7 +33,7 @@ public interface PhysicalNetwork extends Identity, InternalIdentity {
}
public enum IsolationMethod {
- VLAN, L3, GRE, STT, VNS, MIDO, SSP, VXLAN;
+ VLAN, L3, GRE, STT, VNS, MIDO, SSP, VXLAN, ODL;
}
public enum BroadcastDomainRange {
diff --git a/api/src/com/cloud/network/security/SecurityGroupService.java b/api/src/com/cloud/network/security/SecurityGroupService.java
index 1ee504fb9a4..d8b3346f54a 100644
--- a/api/src/com/cloud/network/security/SecurityGroupService.java
+++ b/api/src/com/cloud/network/security/SecurityGroupService.java
@@ -47,5 +47,5 @@ public interface SecurityGroupService {
public List extends SecurityRule> authorizeSecurityGroupEgress(AuthorizeSecurityGroupEgressCmd cmd);
- public boolean securityGroupRulesForVmSecIp(Long nicId, Long networkId, String secondaryIp, boolean ruleAction);
+ public boolean securityGroupRulesForVmSecIp(long nicId, String secondaryIp, boolean ruleAction);
}
diff --git a/api/src/com/cloud/server/ResourceTag.java b/api/src/com/cloud/server/ResourceTag.java
index 93dccbadb79..89458fc9614 100644
--- a/api/src/com/cloud/server/ResourceTag.java
+++ b/api/src/com/cloud/server/ResourceTag.java
@@ -25,11 +25,9 @@ public interface ResourceTag extends ControlledEntity, Identity, InternalIdentit
// FIXME - extract enum to another interface as its used both by resourceTags and resourceMetaData code
public enum ResourceObjectType {
UserVm(true, true), Template(true, true), ISO(true, false), Volume(true, true), Snapshot(true, false), Network(true, true), Nic(false, true), LoadBalancer(true, true), PortForwardingRule(
- true, true), FirewallRule(true, true),
-
- SecurityGroup(true, false), PublicIpAddress(true, true), Project(true, false), Vpc(true, true), NetworkACL(true, true), StaticRoute(true, false), VMSnapshot(true, false), RemoteAccessVpn(
- true, true), Zone(false, true), ServiceOffering(false, true), Storage(false, true), PrivateGateway(false, true), NetworkACLList(false, true), VpnGateway(false,
- true), CustomerGateway(false, true), VpnConnection(false, true);
+ true, true), FirewallRule(true, true), SecurityGroup(true, false), PublicIpAddress(true, true), Project(true, false), Vpc(true, true), NetworkACL(true, true), StaticRoute(
+ true, false), VMSnapshot(true, false), RemoteAccessVpn(true, true), Zone(false, true), ServiceOffering(false, true), Storage(false, true), PrivateGateway(false,
+ true), NetworkACLList(false, true), VpnGateway(false, true), CustomerGateway(false, true), VpnConnection(false, true), User(true, true), DiskOffering(false, true);
ResourceObjectType(boolean resourceTagsSupport, boolean resourceMetadataSupport) {
this.resourceTagsSupport = resourceTagsSupport;
diff --git a/api/src/com/cloud/storage/DataStoreRole.java b/api/src/com/cloud/storage/DataStoreRole.java
index 0a62a569e55..cc20cc0ce96 100644
--- a/api/src/com/cloud/storage/DataStoreRole.java
+++ b/api/src/com/cloud/storage/DataStoreRole.java
@@ -24,13 +24,13 @@ public enum DataStoreRole {
Primary("primary"), Image("image"), ImageCache("imagecache"), Backup("backup");
public boolean isImageStore() {
- return (this.role.equalsIgnoreCase("image") || this.role.equalsIgnoreCase("imagecache")) ? true : false;
+ return (role.equalsIgnoreCase("image") || role.equalsIgnoreCase("imagecache")) ? true : false;
}
private final String role;
DataStoreRole(String type) {
- this.role = type;
+ role = type;
}
public static DataStoreRole getRole(String role) {
diff --git a/api/src/com/cloud/storage/Storage.java b/api/src/com/cloud/storage/Storage.java
index f1868a7a1b3..2175c9b1a0c 100755
--- a/api/src/com/cloud/storage/Storage.java
+++ b/api/src/com/cloud/storage/Storage.java
@@ -28,6 +28,8 @@ public class Storage {
OVA(true, true, true, "ova"),
VHDX(true, true, true, "vhdx"),
BAREMETAL(false, false, false, "BAREMETAL"),
+ VMDK(true, true, false, "vmdk"),
+ VDI(true, true, false, "vdi"),
TAR(false, false, false, "tar");
private final boolean thinProvisioned;
diff --git a/api/src/com/cloud/storage/StorageService.java b/api/src/com/cloud/storage/StorageService.java
index ac3c385695f..7fc1e16ff3a 100644
--- a/api/src/com/cloud/storage/StorageService.java
+++ b/api/src/com/cloud/storage/StorageService.java
@@ -17,8 +17,8 @@
package com.cloud.storage;
import java.net.UnknownHostException;
+import java.util.Map;
-import org.apache.cloudstack.api.command.admin.storage.AddImageStoreCmd;
import org.apache.cloudstack.api.command.admin.storage.CancelPrimaryStorageMaintenanceCmd;
import org.apache.cloudstack.api.command.admin.storage.CreateSecondaryStagingStoreCmd;
import org.apache.cloudstack.api.command.admin.storage.CreateStoragePoolCmd;
@@ -92,19 +92,23 @@ public interface StorageService {
boolean deleteSecondaryStagingStore(DeleteSecondaryStagingStoreCmd cmd);
- ImageStore discoverImageStore(AddImageStoreCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException;
+ public ImageStore discoverImageStore(String name, String url, String providerName, Long dcId, Map details) throws IllegalArgumentException, DiscoveryException,
+ InvalidParameterValueException;
- /**
- * Prepare NFS secondary storage for object store migration
- *
- * @param cmd
- * - the command specifying secondaryStorageId
- * @return the storage pool
- * @throws ResourceUnavailableException
- * TODO
- * @throws InsufficientCapacityException
- * TODO
+
+ /**
+ * Migrate existing NFS to use object store.
+ * @param name object store name.
+ * @param url object store url.
+ * @param providerName object store provider Name.
+ * @param details object store other details
+ * @return Object store created.
+ * @throws IllegalArgumentException
+ * @throws DiscoveryException
+ * @throws InvalidParameterValueException
*/
- public ImageStore prepareSecondaryStorageForObjectStoreMigration(Long storeId) throws ResourceUnavailableException, InsufficientCapacityException;
+ public ImageStore migrateToObjectStore(String name, String url, String providerName, Map details) throws IllegalArgumentException, DiscoveryException,
+ InvalidParameterValueException;
+
}
diff --git a/api/src/com/cloud/storage/Volume.java b/api/src/com/cloud/storage/Volume.java
index bb5ee08b512..84f0872f909 100755
--- a/api/src/com/cloud/storage/Volume.java
+++ b/api/src/com/cloud/storage/Volume.java
@@ -189,7 +189,5 @@ public interface Volume extends ControlledEntity, Identity, InternalIdentity, Ba
Long getVmSnapshotChainSize();
- void setHypervisorSnapshotReserve(Integer hypervisorSnapshotReserve);
-
Integer getHypervisorSnapshotReserve();
}
diff --git a/api/src/com/cloud/user/ResourceLimitService.java b/api/src/com/cloud/user/ResourceLimitService.java
index e878edd56ee..de2773a955c 100644
--- a/api/src/com/cloud/user/ResourceLimitService.java
+++ b/api/src/com/cloud/user/ResourceLimitService.java
@@ -140,7 +140,7 @@ public interface ResourceLimitService {
public long getResourceCount(Account account, ResourceType type);
/**
- * Checks if a limit has been exceeded for an account depending on the displayResource flag
+ * Checks if a limit has been exceeded for an account if displayResource flag is on
*
* @param account
* @param type
@@ -153,7 +153,7 @@ public interface ResourceLimitService {
void checkResourceLimit(Account account, ResourceType type, Boolean displayResource, long... count) throws ResourceAllocationException;
/**
- * Increments the resource count depending on the displayResource flag
+ * Increments the resource count if displayResource flag is on
*
* @param accountId
* @param type
@@ -163,7 +163,7 @@ public interface ResourceLimitService {
void incrementResourceCount(long accountId, ResourceType type, Boolean displayResource, Long... delta);
/**
- * Increments/Decrements the resource count depending on the displayResource flag
+ * Increments/Decrements the resource count depending on the displayResource flag is turned on or off respectively
*
* @param accountId
* @param type
@@ -172,5 +172,13 @@ public interface ResourceLimitService {
*/
void changeResourceCount(long accountId, ResourceType type, Boolean displayResource, Long... delta);
+ /**
+ * Decrements the resource count if displayResource flag is on
+ *
+ * @param accountId
+ * @param type
+ * @param displayResource
+ * @param delta
+ */
void decrementResourceCount(long accountId, ResourceType type, Boolean displayResource, Long... delta);
}
diff --git a/api/src/com/cloud/vm/NicProfile.java b/api/src/com/cloud/vm/NicProfile.java
index ab18ca094f9..4dd7f68ee33 100644
--- a/api/src/com/cloud/vm/NicProfile.java
+++ b/api/src/com/cloud/vm/NicProfile.java
@@ -16,6 +16,7 @@
// under the License.
package com.cloud.vm;
+import java.io.Serializable;
import java.net.URI;
import org.apache.cloudstack.api.InternalIdentity;
@@ -27,7 +28,9 @@ import com.cloud.network.Networks.Mode;
import com.cloud.network.Networks.TrafficType;
import com.cloud.vm.Nic.ReservationStrategy;
-public class NicProfile implements InternalIdentity {
+public class NicProfile implements InternalIdentity, Serializable {
+ private static final long serialVersionUID = 4997005771736090304L;
+
long id;
long networkId;
BroadcastDomainType broadcastType;
@@ -57,6 +60,7 @@ public class NicProfile implements InternalIdentity {
String name;
String requestedIpv4;
String requestedIpv6;
+ String uuid;
public String getDns1() {
return dns1;
@@ -142,6 +146,10 @@ public class NicProfile implements InternalIdentity {
this.format = format;
}
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
+ }
+
public void setTrafficType(TrafficType trafficType) {
this.trafficType = trafficType;
}
@@ -215,29 +223,34 @@ public class NicProfile implements InternalIdentity {
return strategy;
}
+ public String getUuid() {
+ return uuid;
+ }
+
public NicProfile(Nic nic, Network network, URI broadcastUri, URI isolationUri, Integer networkRate, boolean isSecurityGroupEnabled, String name) {
- this.id = nic.getId();
- this.networkId = network.getId();
- this.gateway = nic.getGateway();
- this.mode = network.getMode();
- this.broadcastType = network.getBroadcastDomainType();
- this.trafficType = network.getTrafficType();
- this.ip4Address = nic.getIp4Address();
- this.format = nic.getAddressFormat();
- this.ip6Address = nic.getIp6Address();
- this.macAddress = nic.getMacAddress();
- this.reservationId = nic.getReservationId();
- this.strategy = nic.getReservationStrategy();
- this.deviceId = nic.getDeviceId();
- this.defaultNic = nic.isDefaultNic();
+ id = nic.getId();
+ networkId = network.getId();
+ gateway = nic.getGateway();
+ mode = network.getMode();
+ broadcastType = network.getBroadcastDomainType();
+ trafficType = network.getTrafficType();
+ ip4Address = nic.getIp4Address();
+ format = nic.getAddressFormat();
+ ip6Address = nic.getIp6Address();
+ macAddress = nic.getMacAddress();
+ reservationId = nic.getReservationId();
+ strategy = nic.getReservationStrategy();
+ deviceId = nic.getDeviceId();
+ defaultNic = nic.isDefaultNic();
this.broadcastUri = broadcastUri;
this.isolationUri = isolationUri;
- this.netmask = nic.getNetmask();
+ netmask = nic.getNetmask();
this.isSecurityGroupEnabled = isSecurityGroupEnabled;
- this.vmId = nic.getInstanceId();
+ vmId = nic.getInstanceId();
this.name = name;
- this.ip6Cidr = nic.getIp6Cidr();
- this.ip6Gateway = nic.getIp6Gateway();
+ ip6Cidr = nic.getIp6Cidr();
+ ip6Gateway = nic.getIp6Gateway();
+ uuid = nic.getUuid();
if (networkRate != null) {
this.networkRate = networkRate;
@@ -245,7 +258,7 @@ public class NicProfile implements InternalIdentity {
}
public NicProfile(ReservationStrategy strategy, String ip4Address, String macAddress, String gateway, String netmask) {
- this.format = AddressFormat.Ip4;
+ format = AddressFormat.Ip4;
this.ip4Address = ip4Address;
this.macAddress = macAddress;
this.gateway = gateway;
@@ -274,11 +287,11 @@ public class NicProfile implements InternalIdentity {
}
public boolean isSecurityGroupEnabled() {
- return this.isSecurityGroupEnabled;
+ return isSecurityGroupEnabled;
}
public void setSecurityGroupEnabled(boolean enabled) {
- this.isSecurityGroupEnabled = enabled;
+ isSecurityGroupEnabled = enabled;
}
public String getRequestedIpv4() {
@@ -286,36 +299,36 @@ public class NicProfile implements InternalIdentity {
}
public void deallocate() {
- this.gateway = null;
- this.mode = null;
- this.format = null;
- this.broadcastType = null;
- this.trafficType = null;
- this.ip4Address = null;
- this.ip6Address = null;
- this.macAddress = null;
- this.reservationId = null;
- this.strategy = null;
- this.deviceId = null;
- this.broadcastUri = null;
- this.isolationUri = null;
- this.netmask = null;
- this.dns1 = null;
- this.dns2 = null;
+ gateway = null;
+ mode = null;
+ format = null;
+ broadcastType = null;
+ trafficType = null;
+ ip4Address = null;
+ ip6Address = null;
+ macAddress = null;
+ reservationId = null;
+ strategy = null;
+ deviceId = null;
+ broadcastUri = null;
+ isolationUri = null;
+ netmask = null;
+ dns1 = null;
+ dns2 = null;
}
@Override
public String toString() {
return new StringBuilder("NicProfile[").append(id)
- .append("-")
- .append(vmId)
- .append("-")
- .append(reservationId)
- .append("-")
- .append(ip4Address)
- .append("-")
- .append(broadcastUri)
- .toString();
+ .append("-")
+ .append(vmId)
+ .append("-")
+ .append(reservationId)
+ .append("-")
+ .append(ip4Address)
+ .append("-")
+ .append(broadcastUri)
+ .toString();
}
public String getIp6Gateway() {
diff --git a/api/src/com/cloud/vm/VirtualMachineName.java b/api/src/com/cloud/vm/VirtualMachineName.java
index c5fc3de5ab1..4bbcb64ebca 100755
--- a/api/src/com/cloud/vm/VirtualMachineName.java
+++ b/api/src/com/cloud/vm/VirtualMachineName.java
@@ -26,6 +26,19 @@ import com.cloud.dc.Vlan;
public class VirtualMachineName {
public static final String SEPARATOR = "-";
+ public static boolean isValidCloudStackVmName(String name, String instance) {
+ String[] parts = name.split(SEPARATOR);
+ if (parts.length <= 1) {
+ return false;
+ }
+
+ if (!parts[parts.length - 1].equals(instance)) {
+ return false;
+ }
+
+ return true;
+ }
+
public static String getVnetName(long vnetId) {
StringBuilder vnet = new StringBuilder();
Formatter formatter = new Formatter(vnet);
diff --git a/api/src/org/apache/cloudstack/api/ApiConstants.java b/api/src/org/apache/cloudstack/api/ApiConstants.java
index 8f596b7c2a0..287fff3035b 100755
--- a/api/src/org/apache/cloudstack/api/ApiConstants.java
+++ b/api/src/org/apache/cloudstack/api/ApiConstants.java
@@ -72,7 +72,6 @@ public class ApiConstants {
public static final String DISPLAY_VM = "displayvm";
public static final String DISPLAY_OFFERING = "displayoffering";
public static final String DISPLAY_VOLUME = "displayvolume";
- public static final String CUSTOM_PARAMETERS = "customparameters";
public static final String DNS1 = "dns1";
public static final String DNS2 = "dns2";
public static final String IP6_DNS1 = "ip6dns1";
@@ -210,6 +209,7 @@ public class ApiConstants {
public static final String SENT_BYTES = "sentbytes";
public static final String SERVICE_OFFERING_ID = "serviceofferingid";
public static final String SHOW_CAPACITIES = "showcapacities";
+ public static final String SHOW_REMOVED = "showremoved";
public static final String SIZE = "size";
public static final String SNAPSHOT_ID = "snapshotid";
public static final String SNAPSHOT_POLICY_ID = "snapshotpolicyid";
@@ -554,6 +554,6 @@ public class ApiConstants {
}
public enum VMDetails {
- all, group, nics, stats, secgrp, tmpl, servoff, iso, volume, min, affgrp;
+ all, group, nics, stats, secgrp, tmpl, servoff, diskoff, iso, volume, min, affgrp;
}
}
diff --git a/api/src/org/apache/cloudstack/api/ServerApiException.java b/api/src/org/apache/cloudstack/api/ServerApiException.java
index 81184e3f4f3..a8bb2ed71c9 100644
--- a/api/src/org/apache/cloudstack/api/ServerApiException.java
+++ b/api/src/org/apache/cloudstack/api/ServerApiException.java
@@ -82,4 +82,8 @@ public class ServerApiException extends CloudRuntimeException {
_description = description;
}
+ @Override
+ public String getMessage() {
+ return _description;
+ }
}
diff --git a/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java
index 61f6f49091c..b573bea3e84 100644
--- a/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java
@@ -24,7 +24,6 @@ import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
-import org.apache.cloudstack.api.command.admin.storage.AddImageStoreCmd;
import org.apache.cloudstack.api.response.ImageStoreResponse;
import org.apache.cloudstack.api.response.ZoneResponse;
@@ -74,20 +73,15 @@ public class AddSecondaryStorageCmd extends BaseCmd {
}
@Override
- public void execute() {
- AddImageStoreCmd cmd = new AddImageStoreCmd();
- cmd.setUrl(this.getUrl());
- cmd.setZoneId(this.getZoneId());
- cmd.setProviderName("NFS");
-
- try {
- ImageStore result = _storageService.discoverImageStore(cmd);
+ public void execute(){
+ try{
+ ImageStore result = _storageService.discoverImageStore(null, getUrl(), "NFS", getZoneId(), null);
ImageStoreResponse storeResponse = null;
- if (result != null) {
- storeResponse = _responseGenerator.createImageStoreResponse(result);
- storeResponse.setResponseName(getCommandName());
- storeResponse.setObjectName("secondarystorage");
- this.setResponseObject(storeResponse);
+ if (result != null ) {
+ storeResponse = _responseGenerator.createImageStoreResponse(result);
+ storeResponse.setResponseName(getCommandName());
+ storeResponse.setObjectName("secondarystorage");
+ setResponseObject(storeResponse);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add secondary storage");
}
diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/AddImageStoreCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/AddImageStoreCmd.java
index 5dcedff2392..5e5bd3dcde5 100644
--- a/api/src/org/apache/cloudstack/api/command/admin/storage/AddImageStoreCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/storage/AddImageStoreCmd.java
@@ -95,7 +95,7 @@ public class AddImageStoreCmd extends BaseCmd {
}
public String getProviderName() {
- return this.providerName;
+ return providerName;
}
public void setUrl(String url) {
@@ -129,15 +129,15 @@ public class AddImageStoreCmd extends BaseCmd {
}
@Override
- public void execute() {
- try {
- ImageStore result = _storageService.discoverImageStore(this);
+ public void execute(){
+ try{
+ ImageStore result = _storageService.discoverImageStore(getName(), getUrl(), getProviderName(), getZoneId(), getDetails());
ImageStoreResponse storeResponse = null;
if (result != null) {
storeResponse = _responseGenerator.createImageStoreResponse(result);
storeResponse.setResponseName(getCommandName());
storeResponse.setObjectName("imagestore");
- this.setResponseObject(storeResponse);
+ setResponseObject(storeResponse);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add secondary storage");
}
diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java
index e665b7d0d24..32897e4d59d 100644
--- a/api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java
@@ -86,33 +86,27 @@ public final class AddS3Cmd extends BaseCmd {
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
ResourceAllocationException, NetworkRuleConflictException {
- AddImageStoreCmd cmd = new AddImageStoreCmd() {
- @Override
- public Map getDetails() {
- Map dm = new HashMap();
- dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey());
- dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey());
- dm.put(ApiConstants.S3_END_POINT, getEndPoint());
- dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName());
- if (getHttpsFlag() != null) {
- dm.put(ApiConstants.S3_HTTPS_FLAG, getHttpsFlag().toString());
- }
- if (getConnectionTimeout() != null) {
- dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString());
- }
- if (getMaxErrorRetry() != null) {
- dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString());
- }
- if (getSocketTimeout() != null) {
- dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString());
- }
- return dm;
- }
- };
- cmd.setProviderName("S3");
+ Map dm = new HashMap();
+ dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey());
+ dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey());
+ dm.put(ApiConstants.S3_END_POINT, getEndPoint());
+ dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName());
+ if (getHttpsFlag() != null) {
+ dm.put(ApiConstants.S3_HTTPS_FLAG, getHttpsFlag().toString());
+ }
+ if (getConnectionTimeout() != null) {
+ dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString());
+ }
+ if (getMaxErrorRetry() != null) {
+ dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString());
+ }
+ if (getSocketTimeout() != null) {
+ dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString());
+ }
- try {
- ImageStore result = _storageService.discoverImageStore(cmd);
+
+ try{
+ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm);
ImageStoreResponse storeResponse = null;
if (result != null) {
storeResponse = _responseGenerator.createImageStoreResponse(result);
diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/PrepareSecondaryStorageForMigrationCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/PrepareSecondaryStorageForMigrationCmd.java
deleted file mode 100644
index a57f2dfeffc..00000000000
--- a/api/src/org/apache/cloudstack/api/command/admin/storage/PrepareSecondaryStorageForMigrationCmd.java
+++ /dev/null
@@ -1,110 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF 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.apache.cloudstack.api.command.admin.storage;
-
-import org.apache.log4j.Logger;
-
-import org.apache.cloudstack.api.APICommand;
-import org.apache.cloudstack.api.ApiCommandJobType;
-import org.apache.cloudstack.api.ApiConstants;
-import org.apache.cloudstack.api.ApiErrorCode;
-import org.apache.cloudstack.api.BaseAsyncCmd;
-import org.apache.cloudstack.api.Parameter;
-import org.apache.cloudstack.api.ServerApiException;
-import org.apache.cloudstack.api.response.ImageStoreResponse;
-import org.apache.cloudstack.context.CallContext;
-
-import com.cloud.event.EventTypes;
-import com.cloud.exception.InsufficientCapacityException;
-import com.cloud.exception.ResourceUnavailableException;
-import com.cloud.storage.ImageStore;
-import com.cloud.user.Account;
-
-@APICommand(name = "prepareSecondaryStorageForMigration",
- description = "Prepare a NFS secondary storage to migrate to use object store like S3",
- responseObject = ImageStoreResponse.class)
-public class PrepareSecondaryStorageForMigrationCmd extends BaseAsyncCmd {
- public static final Logger s_logger = Logger.getLogger(PrepareSecondaryStorageForMigrationCmd.class.getName());
- private static final String s_name = "preparesecondarystorageformigrationresponse";
-
- /////////////////////////////////////////////////////
- //////////////// API parameters /////////////////////
- /////////////////////////////////////////////////////
-
- @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = ImageStoreResponse.class, required = true, description = "Secondary image store ID")
- private Long id;
-
- /////////////////////////////////////////////////////
- /////////////////// Accessors ///////////////////////
- /////////////////////////////////////////////////////
-
- public Long getId() {
- return id;
- }
-
- /////////////////////////////////////////////////////
- /////////////// API Implementation///////////////////
- /////////////////////////////////////////////////////
-
- @Override
- public String getCommandName() {
- return s_name;
- }
-
- @Override
- public ApiCommandJobType getInstanceType() {
- return ApiCommandJobType.ImageStore;
- }
-
- @Override
- public Long getInstanceId() {
- return getId();
- }
-
- @Override
- public long getEntityOwnerId() {
- Account account = CallContext.current().getCallingAccount();
- if (account != null) {
- return account.getId();
- }
-
- return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
- }
-
- @Override
- public String getEventType() {
- return EventTypes.EVENT_MIGRATE_PREPARE_SECONDARY_STORAGE;
- }
-
- @Override
- public String getEventDescription() {
- return "preparing secondary storage: " + getId() + " for object store migration";
- }
-
- @Override
- public void execute() throws ResourceUnavailableException, InsufficientCapacityException {
- ImageStore result = _storageService.prepareSecondaryStorageForObjectStoreMigration(getId());
- if (result != null) {
- ImageStoreResponse response = _responseGenerator.createImageStoreResponse(result);
- response.setResponseName(getCommandName());
- response.setResponseName("secondarystorage");
- setResponseObject(response);
- } else {
- throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to prepare secondary storage for object store migration");
- }
- }
-}
diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateCloudToUseObjectStoreCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateCloudToUseObjectStoreCmd.java
new file mode 100644
index 00000000000..983a01c7fbe
--- /dev/null
+++ b/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateCloudToUseObjectStoreCmd.java
@@ -0,0 +1,142 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF 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.apache.cloudstack.api.command.admin.storage;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.apache.log4j.Logger;
+
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.ImageStoreResponse;
+
+import com.cloud.exception.DiscoveryException;
+import com.cloud.storage.ImageStore;
+import com.cloud.user.Account;
+
+@APICommand(name = "updateCloudToUseObjectStore", description = "Migrate current NFS secondary storages to use object store.", responseObject = ImageStoreResponse.class, since = "4.3.0")
+public class UpdateCloudToUseObjectStoreCmd extends BaseCmd {
+ public static final Logger s_logger = Logger.getLogger(UpdateCloudToUseObjectStoreCmd.class.getName());
+ private static final String s_name = "updatecloudtouseobjectstoreresponse";
+
+ /////////////////////////////////////////////////////
+ //////////////// API parameters /////////////////////
+ /////////////////////////////////////////////////////
+
+ @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name for the image store")
+ private String name;
+
+ @Parameter(name=ApiConstants.URL, type=CommandType.STRING, description="the URL for the image store")
+ private String url;
+
+ @Parameter(name=ApiConstants.PROVIDER, type=CommandType.STRING,
+ required=true, description="the image store provider name")
+ private String providerName;
+
+ @Parameter(name=ApiConstants.DETAILS, type=CommandType.MAP, description="the details for the image store. Example: details[0].key=accesskey&details[0].value=s389ddssaa&details[1].key=secretkey&details[1].value=8dshfsss")
+ private Map details;
+
+
+
+ /////////////////////////////////////////////////////
+ /////////////////// Accessors ///////////////////////
+ /////////////////////////////////////////////////////
+
+
+ public String getUrl() {
+ return url;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Map getDetails() {
+ Map detailsMap = null;
+ if (details != null && !details.isEmpty()) {
+ detailsMap = new HashMap();
+ Collection> props = details.values();
+ Iterator> iter = props.iterator();
+ while (iter.hasNext()) {
+ HashMap detail = (HashMap) iter.next();
+ String key = detail.get("key");
+ String value = detail.get("value");
+ detailsMap.put(key, value);
+ }
+ }
+ return detailsMap;
+ }
+
+ public String getProviderName() {
+ return providerName;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+
+ public void setProviderName(String providerName) {
+ this.providerName = providerName;
+ }
+
+ public void setDetails(Map details) {
+ this.details = details;
+ }
+
+ /////////////////////////////////////////////////////
+ /////////////// API Implementation///////////////////
+ /////////////////////////////////////////////////////
+
+
+
+ @Override
+ public String getCommandName() {
+ return s_name;
+ }
+
+ @Override
+ public long getEntityOwnerId() {
+ return Account.ACCOUNT_ID_SYSTEM;
+ }
+
+ @Override
+ public void execute(){
+ try{
+ ImageStore result = _storageService.migrateToObjectStore(getName(), getUrl(), getProviderName(), getDetails());
+ ImageStoreResponse storeResponse = null;
+ if (result != null ) {
+ storeResponse = _responseGenerator.createImageStoreResponse(result);
+ storeResponse.setResponseName(getCommandName());
+ storeResponse.setObjectName("imagestore");
+ setResponseObject(storeResponse);
+ } else {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add secondary storage");
+ }
+ } catch (DiscoveryException ex) {
+ s_logger.warn("Exception: ", ex);
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
+ }
+ }
+}
diff --git a/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java b/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java
index 3b684f41a63..173c95e2c0d 100644
--- a/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java
@@ -27,7 +27,6 @@ import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
-import org.apache.cloudstack.api.command.admin.storage.AddImageStoreCmd;
import org.apache.cloudstack.api.response.ImageStoreResponse;
import com.cloud.exception.DiscoveryException;
@@ -91,27 +90,19 @@ public class AddSwiftCmd extends BaseCmd {
@Override
public void execute() {
- AddImageStoreCmd cmd = new AddImageStoreCmd() {
- @Override
- public Map getDetails() {
- Map dm = new HashMap();
- dm.put(ApiConstants.ACCOUNT, getAccount());
- dm.put(ApiConstants.USERNAME, getUsername());
- dm.put(ApiConstants.KEY, getKey());
- return dm;
- }
- };
- cmd.setProviderName("Swift");
- cmd.setUrl(this.getUrl());
+ Map dm = new HashMap();
+ dm.put(ApiConstants.ACCOUNT, getAccount());
+ dm.put(ApiConstants.USERNAME, getUsername());
+ dm.put(ApiConstants.KEY, getKey());
- try {
- ImageStore result = _storageService.discoverImageStore(cmd);
+ try{
+ ImageStore result = _storageService.discoverImageStore(null, getUrl(), "Swift", null, dm);
ImageStoreResponse storeResponse = null;
if (result != null) {
storeResponse = _responseGenerator.createImageStoreResponse(result);
storeResponse.setResponseName(getCommandName());
storeResponse.setObjectName("secondarystorage");
- this.setResponseObject(storeResponse);
+ setResponseObject(storeResponse);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Swift secondary storage");
}
diff --git a/api/src/org/apache/cloudstack/api/command/admin/systemvm/ScaleSystemVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/ScaleSystemVMCmd.java
index fdb81ea3ee0..370815d625c 100644
--- a/api/src/org/apache/cloudstack/api/command/admin/systemvm/ScaleSystemVMCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/ScaleSystemVMCmd.java
@@ -16,7 +16,10 @@
// under the License.
package org.apache.cloudstack.api.command.admin.systemvm;
-import org.apache.log4j.Logger;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
@@ -28,6 +31,7 @@ import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd;
import org.apache.cloudstack.api.response.ServiceOfferingResponse;
import org.apache.cloudstack.api.response.SystemVmResponse;
import org.apache.cloudstack.context.CallContext;
+import org.apache.log4j.Logger;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
@@ -39,15 +43,8 @@ import com.cloud.offering.ServiceOffering;
import com.cloud.user.Account;
import com.cloud.vm.VirtualMachine;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-@APICommand(name = "scaleSystemVm",
- responseObject = SystemVmResponse.class,
- description = "Scale the service offering for a system vm (console proxy or secondary storage). " + "The system vm must be in a \"Stopped\" state for "
- + "this command to take effect.")
+@APICommand(name = "scaleSystemVm", responseObject = SystemVmResponse.class, description = "Scale the service offering for a system vm (console proxy or secondary storage). "
+ + "The system vm must be in a \"Stopped\" state for " + "this command to take effect.")
public class ScaleSystemVMCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(UpgradeVMCmd.class.getName());
private static final String s_name = "changeserviceforsystemvmresponse";
@@ -59,17 +56,11 @@ public class ScaleSystemVMCmd extends BaseAsyncCmd {
@Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = SystemVmResponse.class, required = true, description = "The ID of the system vm")
private Long id;
- @Parameter(name = ApiConstants.SERVICE_OFFERING_ID,
- type = CommandType.UUID,
- entityType = ServiceOfferingResponse.class,
- required = true,
- description = "the service offering ID to apply to the system vm")
+ @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.UUID, entityType = ServiceOfferingResponse.class, required = true, description = "the service offering ID to apply to the system vm")
private Long serviceOfferingId;
- @Parameter(name = ApiConstants.CUSTOM_PARAMETERS,
- type = CommandType.MAP,
- description = "name value pairs of custom parameters for cpu, memory and cpunumber. example customparameters[i].name=value")
- private Map customParameters;
+ @Parameter(name = ApiConstants.DETAILS, type = CommandType.MAP, description = "name value pairs of custom parameters for cpu, memory and cpunumber. example details[i].name=value")
+ private Map details;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
@@ -83,10 +74,10 @@ public class ScaleSystemVMCmd extends BaseAsyncCmd {
return serviceOfferingId;
}
- public Map getCustomParameters() {
+ public Map getDetails() {
Map customparameterMap = new HashMap();
- if (customParameters != null && customParameters.size() != 0) {
- Collection parameterCollection = customParameters.values();
+ if (details != null && details.size() != 0) {
+ Collection parameterCollection = details.values();
Iterator iter = parameterCollection.iterator();
while (iter.hasNext()) {
HashMap value = (HashMap)iter.next();
diff --git a/api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java
index a89abb8c7ab..da0564e9e67 100644
--- a/api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java
@@ -16,7 +16,10 @@
// under the License.
package org.apache.cloudstack.api.command.admin.systemvm;
-import org.apache.log4j.Logger;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
@@ -28,21 +31,15 @@ import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd;
import org.apache.cloudstack.api.response.ServiceOfferingResponse;
import org.apache.cloudstack.api.response.SystemVmResponse;
import org.apache.cloudstack.context.CallContext;
+import org.apache.log4j.Logger;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.offering.ServiceOffering;
import com.cloud.user.Account;
import com.cloud.vm.VirtualMachine;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-@APICommand(name = "changeServiceForSystemVm",
- responseObject = SystemVmResponse.class,
- description = "Changes the service offering for a system vm (console proxy or secondary storage). " + "The system vm must be in a \"Stopped\" state for "
- + "this command to take effect.")
+@APICommand(name = "changeServiceForSystemVm", responseObject = SystemVmResponse.class, description = "Changes the service offering for a system vm (console proxy or secondary storage). "
+ + "The system vm must be in a \"Stopped\" state for " + "this command to take effect.")
public class UpgradeSystemVMCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(UpgradeVMCmd.class.getName());
private static final String s_name = "changeserviceforsystemvmresponse";
@@ -54,17 +51,11 @@ public class UpgradeSystemVMCmd extends BaseCmd {
@Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = SystemVmResponse.class, required = true, description = "The ID of the system vm")
private Long id;
- @Parameter(name = ApiConstants.SERVICE_OFFERING_ID,
- type = CommandType.UUID,
- entityType = ServiceOfferingResponse.class,
- required = true,
- description = "the service offering ID to apply to the system vm")
+ @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.UUID, entityType = ServiceOfferingResponse.class, required = true, description = "the service offering ID to apply to the system vm")
private Long serviceOfferingId;
- @Parameter(name = ApiConstants.CUSTOM_PARAMETERS,
- type = CommandType.MAP,
- description = "name value pairs of custom parameters for cpu, memory and cpunumber. example customparameters[i].name=value")
- private Map customParameters;
+ @Parameter(name = ApiConstants.DETAILS, type = CommandType.MAP, description = "name value pairs of custom parameters for cpu, memory and cpunumber. example details[i].name=value")
+ private Map details;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
@@ -78,10 +69,10 @@ public class UpgradeSystemVMCmd extends BaseCmd {
return serviceOfferingId;
}
- public Map getCustomParameters() {
+ public Map getDetails() {
Map customparameterMap = new HashMap();
- if (customParameters != null && customParameters.size() != 0) {
- Collection parameterCollection = customParameters.values();
+ if (details != null && details.size() != 0) {
+ Collection parameterCollection = details.values();
Iterator iter = parameterCollection.iterator();
while (iter.hasNext()) {
HashMap value = (HashMap)iter.next();
diff --git a/api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java
index dbaac6e742a..cd3dd7ea9bf 100644
--- a/api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java
@@ -147,6 +147,9 @@ public class CreateVlanIpRangeCmd extends BaseCmd {
}
public String getVlan() {
+ if (vlan == null || vlan.isEmpty()) {
+ vlan = "untagged";
+ }
return vlan;
}
diff --git a/api/src/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java b/api/src/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java
index 367dec91ce7..0761a643452 100644
--- a/api/src/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java
@@ -17,7 +17,6 @@
package org.apache.cloudstack.api.command.user.affinitygroup;
import org.apache.log4j.Logger;
-
import org.apache.cloudstack.affinity.AffinityGroupResponse;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiCommandJobType;
@@ -79,9 +78,9 @@ public class ListAffinityGroupsCmd extends BaseListAccountResourcesCmd {
@Override
public void execute() {
- ListResponse response =
- _queryService.listAffinityGroups(id, affinityGroupName, affinityGroupType, virtualMachineId, this.getAccountName(), this.getDomainId(), this.isRecursive(),
- this.listAll(), this.getStartIndex(), this.getPageSizeVal());
+ ListResponse response = _queryService.listAffinityGroups(id, affinityGroupName,
+ affinityGroupType, virtualMachineId, this.getAccountName(), this.getDomainId(), this.isRecursive(),
+ this.listAll(), this.getStartIndex(), this.getPageSizeVal(), this.getKeyword());
response.setResponseName(getCommandName());
this.setResponseObject(response);
diff --git a/api/src/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java
index 3e66e52249f..95b771fcc43 100644
--- a/api/src/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java
@@ -73,6 +73,9 @@ public class ListIsosCmd extends BaseListTaggedResourcesCmd {
@Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, description = "the ID of the zone")
private Long zoneId;
+ @Parameter(name=ApiConstants.SHOW_REMOVED, type=CommandType.BOOLEAN, description="show removed ISOs as well")
+ private Boolean showRemoved;
+
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
@@ -109,6 +112,10 @@ public class ListIsosCmd extends BaseListTaggedResourcesCmd {
return zoneId;
}
+ public Boolean getShowRemoved() {
+ return (showRemoved != null ? showRemoved : false);
+ }
+
public boolean listInReadyState() {
Account account = CallContext.current().getCallingAccount();
// It is account specific if account is admin type and domainId and accountName are not null
diff --git a/api/src/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java
index 72c52df4630..111fac31174 100644
--- a/api/src/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java
@@ -19,8 +19,6 @@ package org.apache.cloudstack.api.command.user.network;
import java.util.ArrayList;
import java.util.List;
-import org.apache.log4j.Logger;
-
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseListTaggedResourcesCmd;
@@ -30,8 +28,10 @@ import org.apache.cloudstack.api.response.NetworkResponse;
import org.apache.cloudstack.api.response.PhysicalNetworkResponse;
import org.apache.cloudstack.api.response.VpcResponse;
import org.apache.cloudstack.api.response.ZoneResponse;
+import org.apache.log4j.Logger;
import com.cloud.network.Network;
+import com.cloud.utils.Pair;
@APICommand(name = "listNetworks", description = "Lists all available networks.", responseObject = NetworkResponse.class)
public class ListNetworksCmd extends BaseListTaggedResourcesCmd {
@@ -53,24 +53,16 @@ public class ListNetworksCmd extends BaseListTaggedResourcesCmd {
@Parameter(name = ApiConstants.IS_SYSTEM, type = CommandType.BOOLEAN, description = "true if network is system, false otherwise")
private Boolean isSystem;
- @Parameter(name = ApiConstants.ACL_TYPE,
- type = CommandType.STRING,
- description = "list networks by ACL (access control list) type. Supported values are Account and Domain")
+ @Parameter(name = ApiConstants.ACL_TYPE, type = CommandType.STRING, description = "list networks by ACL (access control list) type. Supported values are Account and Domain")
private String aclType;
@Parameter(name = ApiConstants.TRAFFIC_TYPE, type = CommandType.STRING, description = "type of the traffic")
private String trafficType;
- @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID,
- type = CommandType.UUID,
- entityType = PhysicalNetworkResponse.class,
- description = "list networks by physical network id")
+ @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, description = "list networks by physical network id")
private Long physicalNetworkId;
- @Parameter(name = ApiConstants.SUPPORTED_SERVICES,
- type = CommandType.LIST,
- collectionType = CommandType.STRING,
- description = "list networks supporting certain services")
+ @Parameter(name = ApiConstants.SUPPORTED_SERVICES, type = CommandType.LIST, collectionType = CommandType.STRING, description = "list networks supporting certain services")
private List supportedServices;
@Parameter(name = ApiConstants.RESTART_REQUIRED, type = CommandType.BOOLEAN, description = "list networks by restartRequired")
@@ -154,15 +146,14 @@ public class ListNetworksCmd extends BaseListTaggedResourcesCmd {
@Override
public void execute() {
- List extends Network> networks = _networkService.searchForNetworks(this);
+ Pair, Integer> networks = _networkService.searchForNetworks(this);
ListResponse response = new ListResponse();
List networkResponses = new ArrayList();
- for (Network network : networks) {
+ for (Network network : networks.first()) {
NetworkResponse networkResponse = _responseGenerator.createNetworkResponse(network);
networkResponses.add(networkResponse);
}
-
- response.setResponses(networkResponses);
+ response.setResponses(networkResponses, networks.second());
response.setResponseName(getCommandName());
this.setResponseObject(response);
}
diff --git a/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java
index 78bfc186d1c..87f94f72aa1 100644
--- a/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java
@@ -59,8 +59,7 @@ public class CopyTemplateCmd extends BaseAsyncCmd {
@Parameter(name = ApiConstants.SOURCE_ZONE_ID,
type = CommandType.UUID,
entityType = ZoneResponse.class,
- required = true,
- description = "ID of the zone the template is currently hosted on.")
+ description = "ID of the zone the template is currently hosted on. If not specified and template is cross-zone, then we will sync this template to region wide image store.")
private Long sourceZoneId;
/////////////////////////////////////////////////////
@@ -137,7 +136,7 @@ public class CopyTemplateCmd extends BaseAsyncCmd {
}
response.setResponseName(getCommandName());
- this.setResponseObject(response);
+ setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to copy template");
}
diff --git a/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java
index 7e347f3e32f..d393c6a5fdf 100644
--- a/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java
@@ -65,6 +65,9 @@ public class ListTemplatesCmd extends BaseListTaggedResourcesCmd {
@Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, description = "list templates by zoneId")
private Long zoneId;
+ @Parameter(name=ApiConstants.SHOW_REMOVED, type=CommandType.BOOLEAN, description="show removed templates as well")
+ private Boolean showRemoved;
+
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
@@ -89,6 +92,10 @@ public class ListTemplatesCmd extends BaseListTaggedResourcesCmd {
return zoneId;
}
+ public Boolean getShowRemoved() {
+ return (showRemoved != null ? showRemoved : false);
+ }
+
public boolean listInReadyState() {
Account account = CallContext.current().getCallingAccount();
diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/AddIpToVmNicCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/AddIpToVmNicCmd.java
index 09a912293db..c0e8d3e16a6 100644
--- a/api/src/org/apache/cloudstack/api/command/user/vm/AddIpToVmNicCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/vm/AddIpToVmNicCmd.java
@@ -16,8 +16,6 @@
// under the License.
package org.apache.cloudstack.api.command.user.vm;
-import org.apache.log4j.Logger;
-
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiCommandJobType;
import org.apache.cloudstack.api.ApiConstants;
@@ -28,6 +26,7 @@ import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.NicResponse;
import org.apache.cloudstack.api.response.NicSecondaryIpResponse;
import org.apache.cloudstack.context.CallContext;
+import org.apache.log4j.Logger;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenter.NetworkType;
@@ -39,10 +38,10 @@ import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.Network;
-import com.cloud.user.Account;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.Nic;
import com.cloud.vm.NicSecondaryIp;
+import com.cloud.vm.VirtualMachine;
@APICommand(name = "addIpToNic", description = "Assigns secondary IP to NIC", responseObject = NicSecondaryIpResponse.class)
public class AddIpToVmNicCmd extends BaseAsyncCmd {
@@ -52,11 +51,7 @@ public class AddIpToVmNicCmd extends BaseAsyncCmd {
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
- @Parameter(name = ApiConstants.NIC_ID,
- type = CommandType.UUID,
- entityType = NicResponse.class,
- required = true,
- description = "the ID of the nic to which you want to assign private IP")
+ @Parameter(name = ApiConstants.NIC_ID, type = CommandType.UUID, entityType = NicResponse.class, required = true, description = "the ID of the nic to which you want to assign private IP")
private Long nicId;
@Parameter(name = ApiConstants.IP_ADDRESS, type = CommandType.STRING, required = false, description = "Secondary IP Address")
@@ -70,36 +65,19 @@ public class AddIpToVmNicCmd extends BaseAsyncCmd {
return "nic_secondary_ips";
}
- public String getAccountName() {
- return CallContext.current().getCallingAccount().getAccountName();
- }
-
- public long getDomainId() {
- return CallContext.current().getCallingAccount().getDomainId();
- }
-
- private long getZoneId() {
- Network ntwk = _entityMgr.findById(Network.class, getNetworkId());
- if (ntwk == null) {
- throw new InvalidParameterValueException("Can't find zone id for specified");
- }
- return ntwk.getDataCenterId();
- }
-
- public Long getNetworkId() {
+ private long getNetworkId() {
Nic nic = _entityMgr.findById(Nic.class, nicId);
if (nic == null) {
throw new InvalidParameterValueException("Can't find network id for specified nic");
}
- Long networkId = nic.getNetworkId();
- return networkId;
+ return nic.getNetworkId();
}
- public Long getNicId() {
+ public long getNicId() {
return nicId;
}
- public String getIpaddress() {
+ private String getIpaddress() {
if (ipAddr != null) {
return ipAddr;
} else {
@@ -107,18 +85,12 @@ public class AddIpToVmNicCmd extends BaseAsyncCmd {
}
}
- public NetworkType getNetworkType() {
+ private NetworkType getNetworkType() {
Network ntwk = _entityMgr.findById(Network.class, getNetworkId());
DataCenter dc = _entityMgr.findById(DataCenter.class, ntwk.getDataCenterId());
return dc.getNetworkType();
}
- @Override
- public long getEntityOwnerId() {
- Account caller = CallContext.current().getCallingAccount();
- return caller.getAccountId();
- }
-
@Override
public String getEventType() {
return EventTypes.EVENT_NET_IP_ASSIGN;
@@ -126,7 +98,7 @@ public class AddIpToVmNicCmd extends BaseAsyncCmd {
@Override
public String getEventDescription() {
- return "associating ip to nic id: " + getNetworkId() + " in zone " + getZoneId();
+ return "associating ip to nic id=" + getNicId() + " belonging to network id=" + getNetworkId();
}
/////////////////////////////////////////////////////
@@ -156,7 +128,7 @@ public class AddIpToVmNicCmd extends BaseAsyncCmd {
}
try {
- result = _networkService.allocateSecondaryGuestIP(_accountService.getAccount(getEntityOwnerId()), getZoneId(), getNicId(), getNetworkId(), getIpaddress());
+ result = _networkService.allocateSecondaryGuestIP(getNicId(), getIpaddress());
} catch (InsufficientAddressCapacityException e) {
throw new InvalidParameterValueException("Allocating guest ip for nic failed");
}
@@ -166,7 +138,7 @@ public class AddIpToVmNicCmd extends BaseAsyncCmd {
if (getNetworkType() == NetworkType.Basic) {
// add security group rules for the secondary ip addresses
boolean success = false;
- success = _securityGroupService.securityGroupRulesForVmSecIp(getNicId(), getNetworkId(), secondaryIp, true);
+ success = _securityGroupService.securityGroupRulesForVmSecIp(getNicId(), secondaryIp, true);
if (success == false) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to set security group rules for the secondary ip");
}
@@ -197,4 +169,16 @@ public class AddIpToVmNicCmd extends BaseAsyncCmd {
return ApiCommandJobType.IpAddress;
}
+ @Override
+ public long getEntityOwnerId() {
+ Nic nic = _entityMgr.findById(Nic.class, nicId);
+ if (nic == null) {
+ throw new InvalidParameterValueException("Can't find nic for id specified");
+ }
+ long vmId = nic.getInstanceId();
+ VirtualMachine vm = _entityMgr.findById(VirtualMachine.class, vmId);
+
+ return vm.getAccountId();
+ }
+
}
diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java
index 2472a422539..eb19db43866 100755
--- a/api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java
@@ -24,8 +24,6 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
-import org.apache.log4j.Logger;
-
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import org.apache.cloudstack.affinity.AffinityGroupResponse;
import org.apache.cloudstack.api.ACL;
@@ -47,6 +45,7 @@ import org.apache.cloudstack.api.response.TemplateResponse;
import org.apache.cloudstack.api.response.UserVmResponse;
import org.apache.cloudstack.api.response.ZoneResponse;
import org.apache.cloudstack.context.CallContext;
+import org.apache.log4j.Logger;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenter.NetworkType;
@@ -66,9 +65,7 @@ import com.cloud.template.VirtualMachineTemplate;
import com.cloud.user.Account;
import com.cloud.uservm.UserVm;
-@APICommand(name = "deployVirtualMachine",
- description = "Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.",
- responseObject = UserVmResponse.class)
+@APICommand(name = "deployVirtualMachine", description = "Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.", responseObject = UserVmResponse.class)
public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd {
public static final Logger s_logger = Logger.getLogger(DeployVMCmd.class.getName());
@@ -78,27 +75,15 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd {
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
- @Parameter(name = ApiConstants.ZONE_ID,
- type = CommandType.UUID,
- entityType = ZoneResponse.class,
- required = true,
- description = "availability zone for the virtual machine")
+ @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = true, description = "availability zone for the virtual machine")
private Long zoneId;
@ACL
- @Parameter(name = ApiConstants.SERVICE_OFFERING_ID,
- type = CommandType.UUID,
- entityType = ServiceOfferingResponse.class,
- required = true,
- description = "the ID of the service offering for the virtual machine")
+ @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.UUID, entityType = ServiceOfferingResponse.class, required = true, description = "the ID of the service offering for the virtual machine")
private Long serviceOfferingId;
@ACL
- @Parameter(name = ApiConstants.TEMPLATE_ID,
- type = CommandType.UUID,
- entityType = TemplateResponse.class,
- required = true,
- description = "the ID of the template for the virtual machine")
+ @Parameter(name = ApiConstants.TEMPLATE_ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template for the virtual machine")
private Long templateId;
@Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "host name for the virtual machine")
@@ -111,31 +96,21 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd {
@Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "an optional account for the virtual machine. Must be used with domainId.")
private String accountName;
- @Parameter(name = ApiConstants.DOMAIN_ID,
- type = CommandType.UUID,
- entityType = DomainResponse.class,
- description = "an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.")
+ @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.")
private Long domainId;
//Network information
@ACL(accessType = AccessType.UseNetwork)
- @Parameter(name = ApiConstants.NETWORK_IDS,
- type = CommandType.LIST,
- collectionType = CommandType.UUID,
- entityType = NetworkResponse.class,
- description = "list of network ids used by virtual machine. Can't be specified with ipToNetworkList parameter")
+ @Parameter(name = ApiConstants.NETWORK_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = NetworkResponse.class, description = "list of network ids used by virtual machine. Can't be specified with ipToNetworkList parameter")
private List networkIds;
//DataDisk information
@ACL
- @Parameter(name = ApiConstants.DISK_OFFERING_ID,
- type = CommandType.UUID,
- entityType = DiskOfferingResponse.class,
- description = "the ID of the disk offering for the virtual machine. If the template is of ISO format,"
- + " the diskOfferingId is for the root disk volume. Otherwise this parameter is used to indicate the "
- + "offering for the data disk volume. If the templateId parameter passed is from a Template object,"
- + " the diskOfferingId refers to a DATA Disk Volume created. If the templateId parameter passed is "
- + "from an ISO object, the diskOfferingId refers to a ROOT Disk Volume created.")
+ @Parameter(name = ApiConstants.DISK_OFFERING_ID, type = CommandType.UUID, entityType = DiskOfferingResponse.class, description = "the ID of the disk offering for the virtual machine. If the template is of ISO format,"
+ + " the diskOfferingId is for the root disk volume. Otherwise this parameter is used to indicate the "
+ + "offering for the data disk volume. If the templateId parameter passed is from a Template object,"
+ + " the diskOfferingId refers to a DATA Disk Volume created. If the templateId parameter passed is "
+ + "from an ISO object, the diskOfferingId refers to a ROOT Disk Volume created.")
private Long diskOfferingId;
@Parameter(name = ApiConstants.SIZE, type = CommandType.LONG, description = "the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId")
@@ -147,43 +122,27 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd {
@Parameter(name = ApiConstants.HYPERVISOR, type = CommandType.STRING, description = "the hypervisor on which to deploy the virtual machine")
private String hypervisor;
- @Parameter(name = ApiConstants.USER_DATA,
- type = CommandType.STRING,
- description = "an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding. Using HTTP POST(via POST body), you can send up to 32K of data after base64 encoding.",
- length = 32768)
+ @Parameter(name = ApiConstants.USER_DATA, type = CommandType.STRING, description = "an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding. Using HTTP POST(via POST body), you can send up to 32K of data after base64 encoding.", length = 32768)
private String userData;
@Parameter(name = ApiConstants.SSH_KEYPAIR, type = CommandType.STRING, description = "name of the ssh key pair used to login to the virtual machine")
private String sshKeyPairName;
- @Parameter(name = ApiConstants.HOST_ID,
- type = CommandType.UUID,
- entityType = HostResponse.class,
- description = "destination Host ID to deploy the VM to - parameter available for root admin only")
+ @Parameter(name = ApiConstants.HOST_ID, type = CommandType.UUID, entityType = HostResponse.class, description = "destination Host ID to deploy the VM to - parameter available for root admin only")
private Long hostId;
@ACL
- @Parameter(name = ApiConstants.SECURITY_GROUP_IDS,
- type = CommandType.LIST,
- collectionType = CommandType.UUID,
- entityType = SecurityGroupResponse.class,
- description = "comma separated list of security groups id that going to be applied to the virtual machine. "
- + "Should be passed only when vm is created from a zone with Basic Network support." + " Mutually exclusive with securitygroupnames parameter")
+ @Parameter(name = ApiConstants.SECURITY_GROUP_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = SecurityGroupResponse.class, description = "comma separated list of security groups id that going to be applied to the virtual machine. "
+ + "Should be passed only when vm is created from a zone with Basic Network support." + " Mutually exclusive with securitygroupnames parameter")
private List securityGroupIdList;
@ACL
- @Parameter(name = ApiConstants.SECURITY_GROUP_NAMES,
- type = CommandType.LIST,
- collectionType = CommandType.STRING,
- entityType = SecurityGroupResponse.class,
- description = "comma separated list of security groups names that going to be applied to the virtual machine."
- + " Should be passed only when vm is created from a zone with Basic Network support. " + "Mutually exclusive with securitygroupids parameter")
+ @Parameter(name = ApiConstants.SECURITY_GROUP_NAMES, type = CommandType.LIST, collectionType = CommandType.STRING, entityType = SecurityGroupResponse.class, description = "comma separated list of security groups names that going to be applied to the virtual machine."
+ + " Should be passed only when vm is created from a zone with Basic Network support. " + "Mutually exclusive with securitygroupids parameter")
private List securityGroupNameList;
- @Parameter(name = ApiConstants.IP_NETWORK_LIST,
- type = CommandType.MAP,
- description = "ip to network mapping. Can't be specified with networkIds parameter."
- + " Example: iptonetworklist[0].ip=10.10.10.11&iptonetworklist[0].ipv6=fc00:1234:5678::abcd&iptonetworklist[0].networkid=uuid - requests to use ip 10.10.10.11 in network id=uuid")
+ @Parameter(name = ApiConstants.IP_NETWORK_LIST, type = CommandType.MAP, description = "ip to network mapping. Can't be specified with networkIds parameter."
+ + " Example: iptonetworklist[0].ip=10.10.10.11&iptonetworklist[0].ipv6=fc00:1234:5678::abcd&iptonetworklist[0].networkid=uuid - requests to use ip 10.10.10.11 in network id=uuid")
private Map ipToNetworkList;
@Parameter(name = ApiConstants.IP_ADDRESS, type = CommandType.STRING, description = "the ip address for default vm's network")
@@ -192,48 +151,30 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd {
@Parameter(name = ApiConstants.IP6_ADDRESS, type = CommandType.STRING, description = "the ipv6 address for default vm's network")
private String ip6Address;
- @Parameter(name = ApiConstants.KEYBOARD,
- type = CommandType.STRING,
- description = "an optional keyboard device type for the virtual machine. valid value can be one of de,de-ch,es,fi,fr,fr-be,fr-ch,is,it,jp,nl-be,no,pt,uk,us")
+ @Parameter(name = ApiConstants.KEYBOARD, type = CommandType.STRING, description = "an optional keyboard device type for the virtual machine. valid value can be one of de,de-ch,es,fi,fr,fr-be,fr-ch,is,it,jp,nl-be,no,pt,uk,us")
private String keyboard;
@Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "Deploy vm for the project")
private Long projectId;
- @Parameter(name = ApiConstants.START_VM,
- type = CommandType.BOOLEAN,
- description = "true if network offering supports specifying ip ranges; defaulted to true if not specified")
+ @Parameter(name = ApiConstants.START_VM, type = CommandType.BOOLEAN, description = "true if network offering supports specifying ip ranges; defaulted to true if not specified")
private Boolean startVm;
@ACL
- @Parameter(name = ApiConstants.AFFINITY_GROUP_IDS,
- type = CommandType.LIST,
- collectionType = CommandType.UUID,
- entityType = AffinityGroupResponse.class,
- description = "comma separated list of affinity groups id that are going to be applied to the virtual machine."
- + " Mutually exclusive with affinitygroupnames parameter")
+ @Parameter(name = ApiConstants.AFFINITY_GROUP_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = AffinityGroupResponse.class, description = "comma separated list of affinity groups id that are going to be applied to the virtual machine."
+ + " Mutually exclusive with affinitygroupnames parameter")
private List affinityGroupIdList;
@ACL
- @Parameter(name = ApiConstants.AFFINITY_GROUP_NAMES,
- type = CommandType.LIST,
- collectionType = CommandType.STRING,
- entityType = AffinityGroupResponse.class,
- description = "comma separated list of affinity groups names that are going to be applied to the virtual machine."
- + "Mutually exclusive with affinitygroupids parameter")
+ @Parameter(name = ApiConstants.AFFINITY_GROUP_NAMES, type = CommandType.LIST, collectionType = CommandType.STRING, entityType = AffinityGroupResponse.class, description = "comma separated list of affinity groups names that are going to be applied to the virtual machine."
+ + "Mutually exclusive with affinitygroupids parameter")
private List affinityGroupNameList;
- @Parameter(name = ApiConstants.DISPLAY_VM,
- type = CommandType.BOOLEAN,
- since = "4.2",
- description = "an optional field, whether to the display the vm to the end user or not.")
+ @Parameter(name = ApiConstants.DISPLAY_VM, type = CommandType.BOOLEAN, since = "4.2", description = "an optional field, whether to the display the vm to the end user or not.")
private Boolean displayVm;
- @Parameter(name = ApiConstants.CUSTOM_PARAMETERS,
- type = CommandType.MAP,
- since = "4.3",
- description = "used to specify the custom parameters.")
- private Map customParameters;
+ @Parameter(name = ApiConstants.DETAILS, type = CommandType.MAP, since = "4.3", description = "used to specify the custom parameters.")
+ private Map details;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
@@ -261,10 +202,10 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd {
return domainId;
}
- public Map getCustomParameters() {
+ public Map getDetails() {
Map customparameterMap = new HashMap();
- if (customParameters != null && customParameters.size() != 0) {
- Collection parameterCollection = customParameters.values();
+ if (details != null && details.size() != 0) {
+ Collection parameterCollection = details.values();
Iterator iter = parameterCollection.iterator();
while (iter.hasNext()) {
HashMap value = (HashMap)iter.next();
@@ -554,27 +495,23 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd {
if (getNetworkIds() != null) {
throw new InvalidParameterValueException("Can't specify network Ids in Basic zone");
} else {
- vm =
- _userVmService.createBasicSecurityGroupVirtualMachine(zone, serviceOffering, template, getSecurityGroupIdList(), owner, name, displayName,
- diskOfferingId, size, group, getHypervisor(), getHttpMethod(), userData, sshKeyPairName, getIpToNetworkMap(), addrs, displayVm, keyboard,
- getAffinityGroupIdList(), getCustomParameters(), getCustomId());
+ vm = _userVmService.createBasicSecurityGroupVirtualMachine(zone, serviceOffering, template, getSecurityGroupIdList(), owner, name, displayName, diskOfferingId,
+ size, group, getHypervisor(), getHttpMethod(), userData, sshKeyPairName, getIpToNetworkMap(), addrs, displayVm, keyboard, getAffinityGroupIdList(),
+ getDetails(), getCustomId());
}
} else {
if (zone.isSecurityGroupEnabled()) {
- vm =
- _userVmService.createAdvancedSecurityGroupVirtualMachine(zone, serviceOffering, template, getNetworkIds(), getSecurityGroupIdList(), owner, name,
- displayName, diskOfferingId, size, group, getHypervisor(), getHttpMethod(), userData, sshKeyPairName, getIpToNetworkMap(), addrs, displayVm,
- keyboard, getAffinityGroupIdList(), getCustomParameters(), getCustomId());
+ vm = _userVmService.createAdvancedSecurityGroupVirtualMachine(zone, serviceOffering, template, getNetworkIds(), getSecurityGroupIdList(), owner, name,
+ displayName, diskOfferingId, size, group, getHypervisor(), getHttpMethod(), userData, sshKeyPairName, getIpToNetworkMap(), addrs, displayVm, keyboard,
+ getAffinityGroupIdList(), getDetails(), getCustomId());
} else {
if (getSecurityGroupIdList() != null && !getSecurityGroupIdList().isEmpty()) {
throw new InvalidParameterValueException("Can't create vm with security groups; security group feature is not enabled per zone");
}
- vm =
- _userVmService.createAdvancedVirtualMachine(zone, serviceOffering, template, getNetworkIds(), owner, name, displayName, diskOfferingId, size,
- group, getHypervisor(), getHttpMethod(), userData, sshKeyPairName, getIpToNetworkMap(), addrs, displayVm, keyboard, getAffinityGroupIdList(),
- getCustomParameters(), getCustomId());
-
+ vm = _userVmService.createAdvancedVirtualMachine(zone, serviceOffering, template, getNetworkIds(), owner, name, displayName, diskOfferingId, size, group,
+ getHypervisor(), getHttpMethod(), userData, sshKeyPairName, getIpToNetworkMap(), addrs, displayVm, keyboard, getAffinityGroupIdList(), getDetails(),
+ getCustomId());
}
}
@@ -599,5 +536,4 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd {
throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, ex.getMessage());
}
}
-
}
diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java
index 8cb95756367..95d4990bf57 100644
--- a/api/src/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java
@@ -19,8 +19,6 @@ package org.apache.cloudstack.api.command.user.vm;
import java.util.ArrayList;
import java.util.List;
-import org.apache.log4j.Logger;
-
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiCommandJobType;
import org.apache.cloudstack.api.ApiConstants;
@@ -29,9 +27,11 @@ import org.apache.cloudstack.api.BaseListCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.ListResponse;
+import org.apache.cloudstack.api.response.NetworkResponse;
import org.apache.cloudstack.api.response.NicResponse;
import org.apache.cloudstack.api.response.UserVmResponse;
import org.apache.cloudstack.context.CallContext;
+import org.apache.log4j.Logger;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
@@ -55,6 +55,9 @@ public class ListNicsCmd extends BaseListCmd {
@Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, entityType = UserVmResponse.class, required = true, description = "the ID of the vm")
private Long vmId;
+ @Parameter(name = ApiConstants.NETWORK_ID, type = CommandType.UUID, entityType = NetworkResponse.class, description = "list nic of the specific vm's network")
+ private Long networkId;
+
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
@@ -79,6 +82,10 @@ public class ListNicsCmd extends BaseListCmd {
return vmId;
}
+ public Long getNetworkId() {
+ return networkId;
+ }
+
@Override
public long getEntityOwnerId() {
Account caller = CallContext.current().getCallingAccount();
diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java
index 3f161c1698d..28637fbbb35 100644
--- a/api/src/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java
@@ -95,7 +95,7 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd {
type = CommandType.LIST,
collectionType = CommandType.STRING,
description = "comma separated list of host details requested, "
- + "value can be a list of [all, group, nics, stats, secgrp, tmpl, servoff, iso, volume, min, affgrp]."
+ + "value can be a list of [all, group, nics, stats, secgrp, tmpl, servoff, diskoff, iso, volume, min, affgrp]."
+ " If no parameter is passed in, the details will be defaulted to all")
private List viewDetails;
diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/RemoveIpFromVmNicCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/RemoveIpFromVmNicCmd.java
index 9b86577f8e3..24582472b53 100644
--- a/api/src/org/apache/cloudstack/api/command/user/vm/RemoveIpFromVmNicCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/vm/RemoveIpFromVmNicCmd.java
@@ -142,7 +142,7 @@ public class RemoveIpFromVmNicCmd extends BaseAsyncCmd {
if (getNetworkType() == NetworkType.Basic) {
//remove the security group rules for this secondary ip
boolean success = false;
- success = _securityGroupService.securityGroupRulesForVmSecIp(nicSecIp.getNicId(), nicSecIp.getNetworkId(), nicSecIp.getIp4Address(), false);
+ success = _securityGroupService.securityGroupRulesForVmSecIp(nicSecIp.getNicId(), nicSecIp.getIp4Address(), false);
if (success == false) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to set security group rules for the secondary ip");
}
diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/ScaleVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/ScaleVMCmd.java
index e122834810d..d23430095d2 100644
--- a/api/src/org/apache/cloudstack/api/command/user/vm/ScaleVMCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/vm/ScaleVMCmd.java
@@ -16,20 +16,24 @@
// under the License.
package org.apache.cloudstack.api.command.user.vm;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
import java.util.List;
-
-import org.apache.log4j.Logger;
+import java.util.Map;
import org.apache.cloudstack.api.ACL;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseAsyncCmd;
+import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.ServiceOfferingResponse;
import org.apache.cloudstack.api.response.SuccessResponse;
import org.apache.cloudstack.api.response.UserVmResponse;
+import org.apache.log4j.Logger;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
@@ -39,11 +43,6 @@ import com.cloud.exception.VirtualMachineMigrationException;
import com.cloud.user.Account;
import com.cloud.uservm.UserVm;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
@APICommand(name = "scaleVirtualMachine", description = "Scales the virtual machine to a new service offering.", responseObject = SuccessResponse.class)
public class ScaleVMCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(ScaleVMCmd.class.getName());
@@ -58,17 +57,11 @@ public class ScaleVMCmd extends BaseAsyncCmd {
private Long id;
@ACL
- @Parameter(name = ApiConstants.SERVICE_OFFERING_ID,
- type = CommandType.UUID,
- entityType = ServiceOfferingResponse.class,
- required = true,
- description = "the ID of the service offering for the virtual machine")
+ @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.UUID, entityType = ServiceOfferingResponse.class, required = true, description = "the ID of the service offering for the virtual machine")
private Long serviceOfferingId;
- @Parameter(name = ApiConstants.CUSTOM_PARAMETERS,
- type = CommandType.MAP,
- description = "name value pairs of custom parameters for cpu, memory and cpunumber. example customparameters[i].name=value")
- private Map customParameters;
+ @Parameter(name = ApiConstants.DETAILS, type = BaseCmd.CommandType.MAP, description = "name value pairs of custom parameters for cpu,memory and cpunumber. example details[i].name=value")
+ private Map details;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
@@ -83,12 +76,12 @@ public class ScaleVMCmd extends BaseAsyncCmd {
}
//instead of reading a map directly we are using collections.
- //it is because customParameters.values() cannot be cast to a map.
+ //it is because details.values() cannot be cast to a map.
//it gives a exception
- public Map getCustomParameters() {
+ public Map getDetails() {
Map customparameterMap = new HashMap();
- if (customParameters != null && customParameters.size() != 0) {
- Collection parameterCollection = customParameters.values();
+ if (details != null && details.size() != 0) {
+ Collection parameterCollection = details.values();
Iterator iter = parameterCollection.iterator();
while (iter.hasNext()) {
HashMap value = (HashMap)iter.next();
diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java
index 033717d0bc1..12ab711afce 100644
--- a/api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java
@@ -16,7 +16,10 @@
// under the License.
package org.apache.cloudstack.api.command.user.vm;
-import org.apache.log4j.Logger;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
@@ -27,6 +30,7 @@ import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.ServiceOfferingResponse;
import org.apache.cloudstack.api.response.UserVmResponse;
import org.apache.cloudstack.context.CallContext;
+import org.apache.log4j.Logger;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceAllocationException;
@@ -34,13 +38,8 @@ import com.cloud.offering.ServiceOffering;
import com.cloud.user.Account;
import com.cloud.uservm.UserVm;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
@APICommand(name = "changeServiceForVirtualMachine", responseObject = UserVmResponse.class, description = "Changes the service offering for a virtual machine. "
- + "The virtual machine must be in a \"Stopped\" state for " + "this command to take effect.")
+ + "The virtual machine must be in a \"Stopped\" state for " + "this command to take effect.")
public class UpgradeVMCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(UpgradeVMCmd.class.getName());
private static final String s_name = "changeserviceforvirtualmachineresponse";
@@ -52,17 +51,11 @@ public class UpgradeVMCmd extends BaseCmd {
@Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = UserVmResponse.class, required = true, description = "The ID of the virtual machine")
private Long id;
- @Parameter(name = ApiConstants.SERVICE_OFFERING_ID,
- type = CommandType.UUID,
- entityType = ServiceOfferingResponse.class,
- required = true,
- description = "the service offering ID to apply to the virtual machine")
+ @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.UUID, entityType = ServiceOfferingResponse.class, required = true, description = "the service offering ID to apply to the virtual machine")
private Long serviceOfferingId;
- @Parameter(name = ApiConstants.CUSTOM_PARAMETERS,
- type = CommandType.MAP,
- description = "name value pairs of custom parameters for cpu, memory and cpunumber. example customparameters[i].name=value")
- private Map customParameters;
+ @Parameter(name = ApiConstants.DETAILS, type = CommandType.MAP, description = "name value pairs of custom parameters for cpu, memory and cpunumber. example details[i].name=value")
+ private Map details;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
@@ -76,10 +69,10 @@ public class UpgradeVMCmd extends BaseCmd {
return serviceOfferingId;
}
- public Map getCustomParameters() {
+ public Map getDetails() {
Map customparameterMap = new HashMap();
- if (customParameters != null && customParameters.size() != 0) {
- Collection parameterCollection = customParameters.values();
+ if (details != null && details.size() != 0) {
+ Collection parameterCollection = details.values();
Iterator iter = parameterCollection.iterator();
while (iter.hasNext()) {
HashMap value = (HashMap)iter.next();
diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/AddResourceDetailCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/AddResourceDetailCmd.java
index 69d1ca7c2ee..618be7f3958 100644
--- a/api/src/org/apache/cloudstack/api/command/user/volume/AddResourceDetailCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/volume/AddResourceDetailCmd.java
@@ -21,13 +21,12 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
-import org.apache.log4j.Logger;
-
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseAsyncCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.response.SuccessResponse;
+import org.apache.log4j.Logger;
import com.cloud.event.EventTypes;
import com.cloud.server.ResourceTag;
@@ -35,7 +34,7 @@ import com.cloud.server.ResourceTag;
@APICommand(name = "addResourceDetail", description = "Adds detail for the Resource.", responseObject = SuccessResponse.class)
public class AddResourceDetailCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(AddResourceDetailCmd.class.getName());
- private static final String s_name = "addResourceDetailresponse";
+ private static final String s_name = "addresourcedetailresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@@ -47,11 +46,7 @@ public class AddResourceDetailCmd extends BaseAsyncCmd {
@Parameter(name = ApiConstants.RESOURCE_TYPE, type = CommandType.STRING, required = true, description = "type of the resource")
private String resourceType;
- @Parameter(name = ApiConstants.RESOURCE_ID,
- type = CommandType.STRING,
- required = true,
- collectionType = CommandType.STRING,
- description = "resource id to create the details for")
+ @Parameter(name = ApiConstants.RESOURCE_ID, type = CommandType.STRING, required = true, collectionType = CommandType.STRING, description = "resource id to create the details for")
private String resourceId;
/////////////////////////////////////////////////////
diff --git a/api/src/org/apache/cloudstack/api/response/NicResponse.java b/api/src/org/apache/cloudstack/api/response/NicResponse.java
index 7089f884a51..3dd8b297a2b 100644
--- a/api/src/org/apache/cloudstack/api/response/NicResponse.java
+++ b/api/src/org/apache/cloudstack/api/response/NicResponse.java
@@ -18,14 +18,13 @@ package org.apache.cloudstack.api.response;
import java.util.List;
-import com.google.gson.annotations.SerializedName;
-
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseResponse;
import org.apache.cloudstack.api.EntityReference;
import com.cloud.serializer.Param;
import com.cloud.vm.Nic;
+import com.google.gson.annotations.SerializedName;
@SuppressWarnings("unused")
@EntityReference(value = Nic.class)
@@ -95,6 +94,10 @@ public class NicResponse extends BaseResponse {
@Param(description = "the Secondary ipv4 addr of nic")
private List secondaryIps;
+ @SerializedName(ApiConstants.DEVICE_ID)
+ @Param(description = "device id for the network when plugged into the virtual machine", since = "4.4")
+ private String deviceId;
+
public String getId() {
return id;
}
@@ -159,6 +162,10 @@ public class NicResponse extends BaseResponse {
this.ip6Address = ip6Address;
}
+ public void setDeviceId(String deviceId) {
+ this.deviceId = deviceId;
+ }
+
@Override
public int hashCode() {
final int prime = 31;
diff --git a/api/src/org/apache/cloudstack/api/response/ProviderResponse.java b/api/src/org/apache/cloudstack/api/response/ProviderResponse.java
index 5d6ec0d5ca3..4d410837476 100644
--- a/api/src/org/apache/cloudstack/api/response/ProviderResponse.java
+++ b/api/src/org/apache/cloudstack/api/response/ProviderResponse.java
@@ -18,14 +18,13 @@ package org.apache.cloudstack.api.response;
import java.util.List;
-import com.google.gson.annotations.SerializedName;
-
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseResponse;
import org.apache.cloudstack.api.EntityReference;
import com.cloud.network.PhysicalNetworkServiceProvider;
import com.cloud.serializer.Param;
+import com.google.gson.annotations.SerializedName;
@EntityReference(value = PhysicalNetworkServiceProvider.class)
@SuppressWarnings("unused")
diff --git a/api/src/org/apache/cloudstack/api/response/UserVmResponse.java b/api/src/org/apache/cloudstack/api/response/UserVmResponse.java
index 3ca2a1c81b1..26ecb5bb088 100644
--- a/api/src/org/apache/cloudstack/api/response/UserVmResponse.java
+++ b/api/src/org/apache/cloudstack/api/response/UserVmResponse.java
@@ -21,8 +21,6 @@ import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
-import com.google.gson.annotations.SerializedName;
-
import org.apache.cloudstack.affinity.AffinityGroupResponse;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseResponse;
@@ -32,6 +30,7 @@ import com.cloud.network.router.VirtualRouter;
import com.cloud.serializer.Param;
import com.cloud.uservm.UserVm;
import com.cloud.vm.VirtualMachine;
+import com.google.gson.annotations.SerializedName;
@SuppressWarnings("unused")
@EntityReference(value = {VirtualMachine.class, UserVm.class, VirtualRouter.class})
@@ -140,6 +139,14 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp
@Param(description = "the name of the service offering of the virtual machine")
private String serviceOfferingName;
+ @SerializedName(ApiConstants.DISK_OFFERING_ID)
+ @Param(description = "the ID of the disk offering of the virtual machine")
+ private String diskOfferingId;
+
+ @SerializedName("diskofferingname")
+ @Param(description = "the name of the disk offering of the virtual machine")
+ private String diskOfferingName;
+
@SerializedName("forvirtualnetwork")
@Param(description = "the virtual network for the service offering")
private Boolean forVirtualNetwork;
@@ -229,7 +236,7 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp
private Set tags;
@SerializedName(ApiConstants.DETAILS)
- @Param(description = "Template details in key/value pairs.", since = "4.2.1")
+ @Param(description = "Vm details in key/value pairs.", since = "4.2.1")
private Map details;
@SerializedName(ApiConstants.SSH_KEYPAIR)
@@ -247,10 +254,15 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp
@SerializedName(ApiConstants.IS_DYNAMICALLY_SCALABLE)
@Param(description = "true if vm contains XS/VMWare tools inorder to support dynamic scaling of VM cpu/memory.")
private Boolean isDynamicallyScalable;
+
@SerializedName(ApiConstants.SERVICE_STATE)
@Param(description = "State of the Service from LB rule")
private String serviceState;
+ @SerializedName(ApiConstants.OS_TYPE_ID)
+ @Param(description = "OS type id of the vm", since = "4.4")
+ private Long osTypeId;
+
public UserVmResponse() {
securityGroupList = new LinkedHashSet();
nics = new LinkedHashSet();
@@ -383,6 +395,14 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp
return serviceOfferingName;
}
+ public String getDiskOfferingId() {
+ return diskOfferingId;
+ }
+
+ public String getDiskOfferingName() {
+ return diskOfferingName;
+ }
+
public Boolean getForVirtualNetwork() {
return forVirtualNetwork;
}
@@ -602,6 +622,14 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp
this.serviceOfferingName = serviceOfferingName;
}
+ public void setDiskOfferingId(String diskOfferingId) {
+ this.diskOfferingId = diskOfferingId;
+ }
+
+ public void setDiskOfferingName(String diskOfferingName) {
+ this.diskOfferingName = diskOfferingName;
+ }
+
public void setCpuNumber(Integer cpuNumber) {
this.cpuNumber = cpuNumber;
}
@@ -715,4 +743,8 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp
public void setDetails(Map details) {
this.details = details;
}
+
+ public void setOsTypeId(Long osTypeId) {
+ this.osTypeId = osTypeId;
+ }
}
diff --git a/api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java b/api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java
index 32f13f80f22..e73f5263a4f 100644
--- a/api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java
+++ b/api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java
@@ -45,6 +45,7 @@ public interface ExternalNetworkDeviceManager extends Manager {
public static final NetworkDevice PaloAltoFirewall = new NetworkDevice("PaloAltoFirewall", Network.Provider.PaloAlto.getName());
public static final NetworkDevice NiciraNvp = new NetworkDevice("NiciraNvp", Network.Provider.NiciraNvp.getName());
public static final NetworkDevice CiscoVnmc = new NetworkDevice("CiscoVnmc", Network.Provider.CiscoVnmc.getName());
+ public static final NetworkDevice OpenDaylightController = new NetworkDevice("OpenDaylightController", Network.Provider.Opendaylight.getName());
public NetworkDevice(String deviceName, String ntwkServiceprovider) {
_name = deviceName;
diff --git a/api/src/org/apache/cloudstack/query/QueryService.java b/api/src/org/apache/cloudstack/query/QueryService.java
index 792ed04c3da..65a6b064b7c 100644
--- a/api/src/org/apache/cloudstack/query/QueryService.java
+++ b/api/src/org/apache/cloudstack/query/QueryService.java
@@ -18,10 +18,6 @@ package org.apache.cloudstack.query;
import java.util.List;
-import org.apache.cloudstack.affinity.AffinityGroupResponse;
-import org.apache.cloudstack.api.command.admin.host.ListHostsCmd;
-import org.apache.cloudstack.api.command.admin.internallb.ListInternalLBVMsCmd;
-import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd;
import org.apache.cloudstack.api.command.admin.storage.ListImageStoresCmd;
import org.apache.cloudstack.api.command.admin.storage.ListSecondaryStagingStoresCmd;
import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd;
@@ -43,6 +39,10 @@ import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd;
import org.apache.cloudstack.api.command.user.volume.ListResourceDetailsCmd;
import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd;
import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd;
+import org.apache.cloudstack.affinity.AffinityGroupResponse;
+import org.apache.cloudstack.api.command.admin.host.ListHostsCmd;
+import org.apache.cloudstack.api.command.admin.internallb.ListInternalLBVMsCmd;
+import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd;
import org.apache.cloudstack.api.response.AccountResponse;
import org.apache.cloudstack.api.response.AsyncJobResponse;
import org.apache.cloudstack.api.response.DiskOfferingResponse;
@@ -118,8 +118,9 @@ public interface QueryService {
public ListResponse listIsos(ListIsosCmd cmd);
- public ListResponse listAffinityGroups(Long affinityGroupId, String affinityGroupName, String affinityGroupType, Long vmId,
- String accountName, Long domainId, boolean isRecursive, boolean listAll, Long startIndex, Long pageSize);
+ public ListResponse listAffinityGroups(Long affinityGroupId, String affinityGroupName,
+ String affinityGroupType, Long vmId, String accountName, Long domainId, boolean isRecursive,
+ boolean listAll, Long startIndex, Long pageSize, String keyword);
public List listResourceDetails(ListResourceDetailsCmd cmd);
diff --git a/api/test/com/cloud/network/NetworksTest.java b/api/test/com/cloud/network/NetworksTest.java
index 849b1b4f73f..c9102d3a02a 100644
--- a/api/test/com/cloud/network/NetworksTest.java
+++ b/api/test/com/cloud/network/NetworksTest.java
@@ -22,6 +22,7 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import com.cloud.dc.Vlan;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.IsolationType;
import com.cloud.utils.exception.CloudRuntimeException;
@@ -55,6 +56,20 @@ public class NetworksTest {
Assert.assertEquals("id2 should be \"2\"", "2", id2);
}
+ @Test
+ public void vlanValueTest() throws URISyntaxException {
+ String uri1 = "vlan://1";
+ String uri2 = "1";
+ String vtag = BroadcastDomainType.Vlan.getValueFrom(BroadcastDomainType.fromString(uri1));
+ Assert.assertEquals("vtag should be \"1\"", "1", vtag);
+ BroadcastDomainType tiep1 = BroadcastDomainType.getTypeOf(uri1);
+ Assert.assertEquals("the type of uri1 should be 'Vlan'", BroadcastDomainType.Vlan, tiep1);
+ BroadcastDomainType tiep2 = BroadcastDomainType.getTypeOf(uri2);
+ Assert.assertEquals("the type of uri1 should be 'Undecided'", BroadcastDomainType.UnDecided, tiep2);
+ BroadcastDomainType tiep3 = BroadcastDomainType.getTypeOf(Vlan.UNTAGGED);
+ Assert.assertEquals("the type of uri1 should be 'vlan'", BroadcastDomainType.Native, tiep3);
+ }
+
@Test
public void vlanIsolationTypeTest() throws URISyntaxException {
String uri1 = "vlan://1";
diff --git a/api/test/org/apache/cloudstack/api/command/test/AddIpToVmNicTest.java b/api/test/org/apache/cloudstack/api/command/test/AddIpToVmNicTest.java
index 121659b46ed..6f5ab3e1cd9 100644
--- a/api/test/org/apache/cloudstack/api/command/test/AddIpToVmNicTest.java
+++ b/api/test/org/apache/cloudstack/api/command/test/AddIpToVmNicTest.java
@@ -25,7 +25,6 @@ import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Matchers;
import org.mockito.Mockito;
-
import org.apache.cloudstack.api.ResponseGenerator;
import org.apache.cloudstack.api.command.user.vm.AddIpToVmNicCmd;
import org.apache.cloudstack.api.command.user.vm.RemoveIpFromVmNicCmd;
@@ -39,7 +38,6 @@ import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.NetworkService;
-import com.cloud.user.Account;
import com.cloud.vm.NicSecondaryIp;
public class AddIpToVmNicTest extends TestCase {
@@ -68,7 +66,7 @@ public class AddIpToVmNicTest extends TestCase {
NicSecondaryIp secIp = Mockito.mock(NicSecondaryIp.class);
Mockito.when(
- networkService.allocateSecondaryGuestIP(Matchers.any(Account.class), Matchers.anyLong(), Matchers.anyLong(), Matchers.anyLong(), Matchers.anyString()))
+ networkService.allocateSecondaryGuestIP(Matchers.anyLong(), Matchers.anyString()))
.thenReturn(secIp);
ipTonicCmd._networkService = networkService;
@@ -88,7 +86,7 @@ public class AddIpToVmNicTest extends TestCase {
AddIpToVmNicCmd ipTonicCmd = Mockito.mock(AddIpToVmNicCmd.class);
Mockito.when(
- networkService.allocateSecondaryGuestIP(Matchers.any(Account.class), Matchers.anyLong(), Matchers.anyLong(), Matchers.anyLong(), Matchers.anyString()))
+ networkService.allocateSecondaryGuestIP(Matchers.anyLong(), Matchers.anyString()))
.thenReturn(null);
ipTonicCmd._networkService = networkService;
diff --git a/api/test/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java
index d0b2d85f8d5..d68cfb4ca67 100644
--- a/api/test/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java
+++ b/api/test/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java
@@ -16,6 +16,12 @@
// under the License.
package org.apache.cloudstack.api.command.test;
+import static org.mockito.Matchers.anyLong;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.anyString;
+
+import java.util.Map;
+
import junit.framework.Assert;
import junit.framework.TestCase;
@@ -56,7 +62,8 @@ public class AddSecondaryStorageCmdTest extends TestCase {
ImageStore store = Mockito.mock(ImageStore.class);
- Mockito.when(resourceService.discoverImageStore(addImageStoreCmd)).thenReturn(store);
+ Mockito.when(resourceService.discoverImageStore(anyString(), anyString(), anyString(), anyLong(), (Map)anyObject()))
+ .thenReturn(store);
ResponseGenerator responseGenerator = Mockito.mock(ResponseGenerator.class);
addImageStoreCmd._responseGenerator = responseGenerator;
@@ -83,7 +90,8 @@ public class AddSecondaryStorageCmdTest extends TestCase {
StorageService resourceService = Mockito.mock(StorageService.class);
addImageStoreCmd._storageService = resourceService;
- Mockito.when(resourceService.discoverImageStore(addImageStoreCmd)).thenReturn(null);
+ Mockito.when(resourceService.discoverImageStore(anyString(), anyString(), anyString(), anyLong(), (Map)anyObject()))
+ .thenReturn(null);
try {
addImageStoreCmd.execute();
diff --git a/awsapi/pom.xml b/awsapi/pom.xml
index 3d269eda69a..3c2bbe16399 100644
--- a/awsapi/pom.xml
+++ b/awsapi/pom.xml
@@ -317,6 +317,16 @@
+
+ org.apache.maven.plugins
+ maven-checkstyle-plugin
+ ${cs.checkstyle.version}
+
+
+ none
+
+
+
org.apache.maven.plugins
maven-surefire-plugin
@@ -408,6 +418,7 @@
+
diff --git a/build/checkstyle/pom.xml b/build/checkstyle/pom.xml
deleted file mode 100644
index 5984802398c..00000000000
--- a/build/checkstyle/pom.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-
-
- 4.0.0
- Apache CloudStack Checkstyle Configuration
- build-checkstyle
-
- org.apache.cloudstack
- cloud-maven-standard
- 4.4.0-SNAPSHOT
- ../../maven-standard/pom.xml
-
-
diff --git a/client/WEB-INF/classes/resources/messages.properties b/client/WEB-INF/classes/resources/messages.properties
index 384a0778bb2..f186fbf7848 100644
--- a/client/WEB-INF/classes/resources/messages.properties
+++ b/client/WEB-INF/classes/resources/messages.properties
@@ -14,6 +14,21 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
+label.port=Port
+label.remove.ldap=Remove LDAP
+message.remove.ldap=Are you sure you want to delete the LDAP configuration?
+label.configure.ldap=Configure LDAP
+message.configure.ldap=Please confirm you would like to configure LDAP.
+label.ldap.configuration=LDAP Configuration
+label.ldap.port=LDAP port
+label.create.nfs.secondary.staging.store=Create NFS secondary staging store
+label.volatile=Volatile
+label.planner.mode=Planner mode
+label.deployment.planner=Deployment planner
+label.quiesce.vm=Quiesce VM
+label.smb.username=SMB Username
+label.smb.password=SMB Password
+label.smb.domain=SMB Domain
label.hypervisors=Hypervisors
label.home=Home
label.sockets=Sockets
@@ -1252,6 +1267,11 @@ label.zoneWizard.trafficType.management=Management\: Traffic between CloudStack\
label.zoneWizard.trafficType.public=Public\: Traffic between the internet and virtual machines in the cloud.
label.zoneWizard.trafficType.storage=Storage\: Traffic between primary and secondary storage servers, such as VM templates and snapshots
label.ldap.group.name=LDAP Group
+label.openDaylight=OpenDaylight
+label.opendaylight.controllers=OpenDaylight Controllers
+label.opendaylight.controllerdetail=OpenDaylight Controller Details
+label.add.OpenDaylight.device=Add OpenDaylight Controller
+label.delete.OpenDaylight.device=Delete OpenDaylight Controller
managed.state=Managed State
message.acquire.new.ip.vpc=Please confirm that you would like to acquire a new IP for this VPC.
message.acquire.new.ip=Please confirm that you would like to acquire a new IP for this network.
diff --git a/client/pom.xml b/client/pom.xml
index fc01113c7a0..abbc25dbcbf 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -130,6 +130,11 @@
cloud-plugin-network-vxlan
${project.version}
+
+ org.apache.cloudstack
+ cloud-plugin-network-opendaylight
+ ${project.version}
+
org.apache.cloudstack
cloud-plugin-hypervisor-xen
@@ -176,6 +181,11 @@
cloud-plugin-planner-user-dispersing
${project.version}
+
+ org.apache.cloudstack
+ cloud-plugin-planner-skip-heurestics
+ ${project.version}
+
org.apache.cloudstack
cloud-plugin-planner-user-concentrated-pod
@@ -201,6 +211,11 @@
cloud-mom-rabbitmq
${project.version}
+
+ org.apache.cloudstack
+ cloud-mom-inmemory
+ ${project.version}
+
mysql
mysql-connector-java
diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in
index a05310bff77..c5ac7fd67af 100644
--- a/client/tomcatconf/commands.properties.in
+++ b/client/tomcatconf/commands.properties.in
@@ -266,7 +266,7 @@ deleteImageStore=1
createSecondaryStagingStore=1
listSecondaryStagingStores=1
deleteSecondaryStagingStore=1
-prepareSecondaryStorageForMigration=1
+updateCloudToUseObjectStore=1
#### host commands
addHost=3
@@ -706,3 +706,8 @@ importLdapUsers=3
#### juniper-contrail commands
createServiceInstance=1
+
+### OpenDaylight plugin commands
+addOpenDaylightController=1
+deleteOpenDaylightController=1
+listOpenDaylightControllers=1
diff --git a/core/pom.xml b/core/pom.xml
index cdcfd536b93..975e9f64072 100644
--- a/core/pom.xml
+++ b/core/pom.xml
@@ -36,6 +36,11 @@
cloud-engine-api
${project.version}
+
+ org.apache.cloudstack
+ cloud-framework-security
+ ${project.version}
+
commons-codec
commons-codec
diff --git a/core/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml b/core/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml
index be11a1f711f..5e799c06483 100644
--- a/core/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml
+++ b/core/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml
@@ -77,6 +77,11 @@
+
+
+
+
diff --git a/core/resources/META-INF/cloudstack/planner/spring-core-lifecycle-planner-context-inheritable.xml b/core/resources/META-INF/cloudstack/planner/spring-core-lifecycle-planner-context-inheritable.xml
index 715f86d9c28..80779e43466 100644
--- a/core/resources/META-INF/cloudstack/planner/spring-core-lifecycle-planner-context-inheritable.xml
+++ b/core/resources/META-INF/cloudstack/planner/spring-core-lifecycle-planner-context-inheritable.xml
@@ -38,4 +38,9 @@
value="org.apache.cloudstack.affinity.AffinityGroupProcessor" />
+
+
+
+
+
diff --git a/core/src/com/cloud/agent/api/SecStorageSetupCommand.java b/core/src/com/cloud/agent/api/SecStorageSetupCommand.java
index 3c8d7300064..18710320dc8 100644
--- a/core/src/com/cloud/agent/api/SecStorageSetupCommand.java
+++ b/core/src/com/cloud/agent/api/SecStorageSetupCommand.java
@@ -16,50 +16,21 @@
// under the License.
package com.cloud.agent.api;
-import com.cloud.agent.api.LogLevel.Log4jLevel;
+import org.apache.cloudstack.framework.security.keystore.KeystoreManager;
+
import com.cloud.agent.api.to.DataStoreTO;
public class SecStorageSetupCommand extends Command {
private DataStoreTO store;
private String secUrl;
- private Certificates certs;
+ private KeystoreManager.Certificates certs;
- public static class Certificates {
- @LogLevel(Log4jLevel.Off)
- private String privKey;
- @LogLevel(Log4jLevel.Off)
- private String privCert;
- @LogLevel(Log4jLevel.Off)
- private String certChain;
-
- public Certificates() {
-
- }
-
- public Certificates(String prvKey, String privCert, String certChain) {
- this.privKey = prvKey;
- this.privCert = privCert;
- this.certChain = certChain;
- }
-
- public String getPrivKey() {
- return this.privKey;
- }
-
- public String getPrivCert() {
- return this.privCert;
- }
-
- public String getCertChain() {
- return this.certChain;
- }
- }
public SecStorageSetupCommand() {
super();
}
- public SecStorageSetupCommand(DataStoreTO store, String secUrl, Certificates certs) {
+ public SecStorageSetupCommand(DataStoreTO store, String secUrl, KeystoreManager.Certificates certs) {
super();
this.secUrl = secUrl;
this.certs = certs;
@@ -75,8 +46,8 @@ public class SecStorageSetupCommand extends Command {
return secUrl;
}
- public Certificates getCerts() {
- return this.certs;
+ public KeystoreManager.Certificates getCerts() {
+ return certs;
}
public void setSecUrl(String secUrl) {
diff --git a/core/src/com/cloud/agent/api/storage/MigrateVolumeCommand.java b/core/src/com/cloud/agent/api/storage/MigrateVolumeCommand.java
index b82d8481f2c..b73a48a1b37 100644
--- a/core/src/com/cloud/agent/api/storage/MigrateVolumeCommand.java
+++ b/core/src/com/cloud/agent/api/storage/MigrateVolumeCommand.java
@@ -25,6 +25,7 @@ public class MigrateVolumeCommand extends Command {
long volumeId;
String volumePath;
StorageFilerTO pool;
+ String attachedVmName;
public MigrateVolumeCommand(long volumeId, String volumePath, StoragePool pool) {
this.volumeId = volumeId;
@@ -32,6 +33,13 @@ public class MigrateVolumeCommand extends Command {
this.pool = new StorageFilerTO(pool);
}
+ public MigrateVolumeCommand(long volumeId, String volumePath, StoragePool pool, String attachedVmName) {
+ this.volumeId = volumeId;
+ this.volumePath = volumePath;
+ this.pool = new StorageFilerTO(pool);
+ this.attachedVmName = attachedVmName;
+ }
+
@Override
public boolean executeInSequence() {
return true;
@@ -48,4 +56,8 @@ public class MigrateVolumeCommand extends Command {
public StorageFilerTO getPool() {
return pool;
}
+
+ public String getAttachedVmName() {
+ return attachedVmName;
+ }
}
\ No newline at end of file
diff --git a/core/src/com/cloud/host/HostInfo.java b/core/src/com/cloud/host/HostInfo.java
index 89fb8061aa0..4a95aa8d862 100644
--- a/core/src/com/cloud/host/HostInfo.java
+++ b/core/src/com/cloud/host/HostInfo.java
@@ -21,5 +21,6 @@ public final class HostInfo {
public static final String HOST_OS = "Host.OS"; //Fedora, XenServer, Ubuntu, etc
public static final String HOST_OS_VERSION = "Host.OS.Version"; //12, 5.5, 9.10, etc
public static final String HOST_OS_KERNEL_VERSION = "Host.OS.Kernel.Version"; //linux-2.6.31 etc
-
+ public static final String XS620_SNAPSHOT_HOTFIX = "xs620_snapshot_hotfix";
}
+
diff --git a/core/src/com/cloud/storage/template/OVAProcessor.java b/core/src/com/cloud/storage/template/OVAProcessor.java
new file mode 100644
index 00000000000..0db3bb00e0a
--- /dev/null
+++ b/core/src/com/cloud/storage/template/OVAProcessor.java
@@ -0,0 +1,158 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF 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 com.cloud.storage.template;
+
+import java.io.File;
+import java.util.Map;
+
+import javax.ejb.Local;
+import javax.naming.ConfigurationException;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.apache.log4j.Logger;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import com.cloud.exception.InternalErrorException;
+import com.cloud.storage.Storage.ImageFormat;
+import com.cloud.storage.StorageLayer;
+import com.cloud.utils.component.AdapterBase;
+import com.cloud.utils.script.Script;
+
+@Local(value = Processor.class)
+public class OVAProcessor extends AdapterBase implements Processor {
+ private static final Logger s_logger = Logger.getLogger(OVAProcessor.class);
+
+ StorageLayer _storage;
+
+ @Override
+ public FormatInfo process(String templatePath, ImageFormat format, String templateName) throws InternalErrorException {
+ if (format != null) {
+ if (s_logger.isInfoEnabled()) {
+ s_logger.info("We currently don't handle conversion from " + format + " to OVA.");
+ }
+ return null;
+ }
+
+ s_logger.info("Template processing. templatePath: " + templatePath + ", templateName: " + templateName);
+ String templateFilePath = templatePath + File.separator + templateName + "." + ImageFormat.OVA.getFileExtension();
+ if (!_storage.exists(templateFilePath)) {
+ if (s_logger.isInfoEnabled()) {
+ s_logger.info("Unable to find the vmware template file: " + templateFilePath);
+ }
+ return null;
+ }
+
+ s_logger.info("Template processing - untar OVA package. templatePath: " + templatePath + ", templateName: " + templateName);
+ String templateFileFullPath = templatePath + File.separator + templateName + "." + ImageFormat.OVA.getFileExtension();
+ File templateFile = new File(templateFileFullPath);
+
+ Script command = new Script("tar", 0, s_logger);
+ command.add("--no-same-owner");
+ command.add("-xf", templateFileFullPath);
+ command.setWorkDir(templateFile.getParent());
+ String result = command.execute();
+ if (result != null) {
+ s_logger.info("failed to untar OVA package due to " + result + ". templatePath: " + templatePath + ", templateName: " + templateName);
+ return null;
+ }
+
+ FormatInfo info = new FormatInfo();
+ info.format = ImageFormat.OVA;
+ info.filename = templateName + "." + ImageFormat.OVA.getFileExtension();
+ info.size = _storage.getSize(templateFilePath);
+ info.virtualSize = getTemplateVirtualSize(templatePath, info.filename);
+
+ // delete original OVA file
+ // templateFile.delete();
+ return info;
+ }
+
+ @Override
+ public Long getVirtualSize(File file) {
+ try {
+ long size = getTemplateVirtualSize(file.getParent(), file.getName());
+ return size;
+ } catch (Exception e) {
+
+ }
+ return file.length();
+ }
+
+ public long getTemplateVirtualSize(String templatePath, String templateName) throws InternalErrorException {
+ // get the virtual size from the OVF file meta data
+ long virtualSize = 0;
+ String templateFileFullPath = templatePath.endsWith(File.separator) ? templatePath : templatePath + File.separator;
+ templateFileFullPath += templateName.endsWith(ImageFormat.OVA.getFileExtension()) ? templateName : templateName + "." + ImageFormat.OVA.getFileExtension();
+ String ovfFileName = getOVFFilePath(templateFileFullPath);
+ if (ovfFileName == null) {
+ String msg = "Unable to locate OVF file in template package directory: " + templatePath;
+ s_logger.error(msg);
+ throw new InternalErrorException(msg);
+ }
+ try {
+ Document ovfDoc = null;
+ ovfDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(ovfFileName));
+ Element disk = (Element)ovfDoc.getElementsByTagName("Disk").item(0);
+ virtualSize = Long.parseLong(disk.getAttribute("ovf:capacity"));
+ String allocationUnits = disk.getAttribute("ovf:capacityAllocationUnits");
+ if ((virtualSize != 0) && (allocationUnits != null)) {
+ long units = 1;
+ if (allocationUnits.equalsIgnoreCase("KB") || allocationUnits.equalsIgnoreCase("KiloBytes") || allocationUnits.equalsIgnoreCase("byte * 2^10")) {
+ units = 1024;
+ } else if (allocationUnits.equalsIgnoreCase("MB") || allocationUnits.equalsIgnoreCase("MegaBytes") || allocationUnits.equalsIgnoreCase("byte * 2^20")) {
+ units = 1024 * 1024;
+ } else if (allocationUnits.equalsIgnoreCase("GB") || allocationUnits.equalsIgnoreCase("GigaBytes") || allocationUnits.equalsIgnoreCase("byte * 2^30")) {
+ units = 1024 * 1024 * 1024;
+ }
+ virtualSize = virtualSize * units;
+ } else {
+ throw new InternalErrorException("Failed to read capacity and capacityAllocationUnits from the OVF file: " + ovfFileName);
+ }
+ return virtualSize;
+ } catch (Exception e) {
+ String msg = "Unable to parse OVF XML document to get the virtual disk size due to" + e;
+ s_logger.error(msg);
+ throw new InternalErrorException(msg);
+ }
+ }
+
+ private String getOVFFilePath(String srcOVAFileName) {
+ File file = new File(srcOVAFileName);
+ assert (_storage != null);
+ String[] files = _storage.listFiles(file.getParent());
+ if (files != null) {
+ for (String fileName : files) {
+ if (fileName.toLowerCase().endsWith(".ovf")) {
+ File ovfFile = new File(fileName);
+ return file.getParent() + File.separator + ovfFile.getName();
+ }
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public boolean configure(String name, Map params) throws ConfigurationException {
+ _storage = (StorageLayer)params.get(StorageLayer.InstanceConfigKey);
+ if (_storage == null) {
+ throw new ConfigurationException("Unable to get storage implementation");
+ }
+
+ return true;
+ }
+}
diff --git a/core/src/com/cloud/storage/template/VmdkProcessor.java b/core/src/com/cloud/storage/template/VmdkProcessor.java
index be201438a1c..2c08447e9f9 100644
--- a/core/src/com/cloud/storage/template/VmdkProcessor.java
+++ b/core/src/com/cloud/storage/template/VmdkProcessor.java
@@ -16,22 +16,24 @@
// under the License.
package com.cloud.storage.template;
+import java.io.BufferedReader;
import java.io.File;
+import java.io.FileReader;
+import java.io.FileNotFoundException;
+import java.io.IOException;
import java.util.Map;
+import java.util.regex.Pattern;
+import java.util.regex.Matcher;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
-import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.log4j.Logger;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
import com.cloud.exception.InternalErrorException;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.StorageLayer;
import com.cloud.utils.component.AdapterBase;
-import com.cloud.utils.script.Script;
@Local(value = Processor.class)
public class VmdkProcessor extends AdapterBase implements Processor {
@@ -49,7 +51,7 @@ public class VmdkProcessor extends AdapterBase implements Processor {
}
s_logger.info("Template processing. templatePath: " + templatePath + ", templateName: " + templateName);
- String templateFilePath = templatePath + File.separator + templateName + "." + ImageFormat.OVA.getFileExtension();
+ String templateFilePath = templatePath + File.separator + templateName + "." + ImageFormat.VMDK.getFileExtension();
if (!_storage.exists(templateFilePath)) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Unable to find the vmware template file: " + templateFilePath);
@@ -57,28 +59,12 @@ public class VmdkProcessor extends AdapterBase implements Processor {
return null;
}
- s_logger.info("Template processing - untar OVA package. templatePath: " + templatePath + ", templateName: " + templateName);
- String templateFileFullPath = templatePath + File.separator + templateName + "." + ImageFormat.OVA.getFileExtension();
- File templateFile = new File(templateFileFullPath);
-
- Script command = new Script("tar", 0, s_logger);
- command.add("--no-same-owner");
- command.add("-xf", templateFileFullPath);
- command.setWorkDir(templateFile.getParent());
- String result = command.execute();
- if (result != null) {
- s_logger.info("failed to untar OVA package due to " + result + ". templatePath: " + templatePath + ", templateName: " + templateName);
- return null;
- }
-
FormatInfo info = new FormatInfo();
- info.format = ImageFormat.OVA;
- info.filename = templateName + "." + ImageFormat.OVA.getFileExtension();
+ info.format = ImageFormat.VMDK;
+ info.filename = templateName + "." + ImageFormat.VMDK.getFileExtension();
info.size = _storage.getSize(templateFilePath);
info.virtualSize = getTemplateVirtualSize(templatePath, info.filename);
- // delete original OVA file
- // templateFile.delete();
return info;
}
@@ -94,56 +80,37 @@ public class VmdkProcessor extends AdapterBase implements Processor {
}
public long getTemplateVirtualSize(String templatePath, String templateName) throws InternalErrorException {
- // get the virtual size from the OVF file meta data
long virtualSize = 0;
String templateFileFullPath = templatePath.endsWith(File.separator) ? templatePath : templatePath + File.separator;
- templateFileFullPath += templateName.endsWith(ImageFormat.OVA.getFileExtension()) ? templateName : templateName + "." + ImageFormat.OVA.getFileExtension();
- String ovfFileName = getOVFFilePath(templateFileFullPath);
- if (ovfFileName == null) {
- String msg = "Unable to locate OVF file in template package directory: " + templatePath;
- s_logger.error(msg);
- throw new InternalErrorException(msg);
- }
- try {
- Document ovfDoc = null;
- ovfDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(ovfFileName));
- Element disk = (Element)ovfDoc.getElementsByTagName("Disk").item(0);
- virtualSize = Long.parseLong(disk.getAttribute("ovf:capacity"));
- String allocationUnits = disk.getAttribute("ovf:capacityAllocationUnits");
- if ((virtualSize != 0) && (allocationUnits != null)) {
- long units = 1;
- if (allocationUnits.equalsIgnoreCase("KB") || allocationUnits.equalsIgnoreCase("KiloBytes") || allocationUnits.equalsIgnoreCase("byte * 2^10")) {
- units = 1024;
- } else if (allocationUnits.equalsIgnoreCase("MB") || allocationUnits.equalsIgnoreCase("MegaBytes") || allocationUnits.equalsIgnoreCase("byte * 2^20")) {
- units = 1024 * 1024;
- } else if (allocationUnits.equalsIgnoreCase("GB") || allocationUnits.equalsIgnoreCase("GigaBytes") || allocationUnits.equalsIgnoreCase("byte * 2^30")) {
- units = 1024 * 1024 * 1024;
- }
- virtualSize = virtualSize * units;
- } else {
- throw new InternalErrorException("Failed to read capacity and capacityAllocationUnits from the OVF file: " + ovfFileName);
- }
- return virtualSize;
- } catch (Exception e) {
- String msg = "Unable to parse OVF XML document to get the virtual disk size due to" + e;
- s_logger.error(msg);
- throw new InternalErrorException(msg);
- }
- }
+ templateFileFullPath += templateName.endsWith(ImageFormat.VMDK.getFileExtension()) ? templateName : templateName + "." + ImageFormat.VMDK.getFileExtension();
+ String vmdkHeader = "";
- private String getOVFFilePath(String srcOVAFileName) {
- File file = new File(srcOVAFileName);
- assert (_storage != null);
- String[] files = _storage.listFiles(file.getParent());
- if (files != null) {
- for (String fileName : files) {
- if (fileName.toLowerCase().endsWith(".ovf")) {
- File ovfFile = new File(fileName);
- return file.getParent() + File.separator + ovfFile.getName();
+ try {
+ FileReader fileReader = new FileReader(templateFileFullPath);
+ BufferedReader bufferedReader = new BufferedReader(fileReader);
+ Pattern regex = Pattern.compile("(RW|RDONLY|NOACCESS) (\\d+) (FLAT|SPARSE|ZERO|VMFS|VMFSSPARSE|VMFSDRM|VMFSRAW)");
+ String line = null;
+ while((line = bufferedReader.readLine()) != null) {
+ Matcher m = regex.matcher(line);
+ if (m.find( )) {
+ long sectors = Long.parseLong(m.group(2));
+ virtualSize = sectors * 512;
+ break;
}
}
+ bufferedReader.close();
+ } catch(FileNotFoundException ex) {
+ String msg = "Unable to open file '" + templateFileFullPath + "' " + ex.toString();
+ s_logger.error(msg);
+ throw new InternalErrorException(msg);
+ } catch(IOException ex) {
+ String msg = "Unable read open file '" + templateFileFullPath + "' " + ex.toString();
+ s_logger.error(msg);
+ throw new InternalErrorException(msg);
}
- return null;
+
+ s_logger.debug("vmdk file had size="+virtualSize);
+ return virtualSize;
}
@Override
diff --git a/core/src/org/apache/cloudstack/storage/command/CopyCommand.java b/core/src/org/apache/cloudstack/storage/command/CopyCommand.java
index 7fcde1e8d4f..446c61f9a7b 100644
--- a/core/src/org/apache/cloudstack/storage/command/CopyCommand.java
+++ b/core/src/org/apache/cloudstack/storage/command/CopyCommand.java
@@ -16,6 +16,9 @@
// under the License.
package org.apache.cloudstack.storage.command;
+import java.util.HashMap;
+import java.util.Map;
+
import com.cloud.agent.api.Command;
import com.cloud.agent.api.to.DataTO;
@@ -24,6 +27,7 @@ public final class CopyCommand extends Command implements StorageSubSystemComman
private DataTO destTO;
private DataTO cacheTO;
boolean executeInSequence = false;
+ Map options = new HashMap();
public CopyCommand(DataTO srcData, DataTO destData, int timeout, boolean executeInSequence) {
super();
@@ -66,4 +70,12 @@ public final class CopyCommand extends Command implements StorageSubSystemComman
return this.getWait() * 1000;
}
+ public void setOptions(Map options) {
+ this.options = options;
+ }
+
+ public Map getOptions() {
+ return options;
+ }
+
}
diff --git a/core/src/org/apache/cloudstack/storage/to/SnapshotObjectTO.java b/core/src/org/apache/cloudstack/storage/to/SnapshotObjectTO.java
index 03b460902bf..7d1ac2d7e5e 100644
--- a/core/src/org/apache/cloudstack/storage/to/SnapshotObjectTO.java
+++ b/core/src/org/apache/cloudstack/storage/to/SnapshotObjectTO.java
@@ -16,8 +16,11 @@
// under the License.
package org.apache.cloudstack.storage.to;
+import java.util.ArrayList;
+
import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
+import org.apache.commons.lang.ArrayUtils;
import com.cloud.agent.api.to.DataObjectType;
import com.cloud.agent.api.to.DataStoreTO;
@@ -34,6 +37,9 @@ public class SnapshotObjectTO implements DataTO {
private HypervisorType hypervisorType;
private long id;
private boolean quiescevm;
+ private String[] parents;
+ private Long physicalSize = (long) 0;
+
public SnapshotObjectTO() {
@@ -49,9 +55,17 @@ public class SnapshotObjectTO implements DataTO {
}
SnapshotInfo parentSnapshot = snapshot.getParent();
+ ArrayList parentsArry = new ArrayList();
if (parentSnapshot != null) {
this.parentSnapshotPath = parentSnapshot.getPath();
+ while(parentSnapshot != null) {
+ parentsArry.add(parentSnapshot.getPath());
+ parentSnapshot = parentSnapshot.getParent();
+ }
+ parents = parentsArry.toArray(new String[parentsArry.size()]);
+ ArrayUtils.reverse(parents);
}
+
this.dataStore = snapshot.getDataStore().getTO();
this.setName(snapshot.getName());
this.hypervisorType = snapshot.getHypervisorType();
@@ -81,6 +95,14 @@ public class SnapshotObjectTO implements DataTO {
this.path = path;
}
+ public Long getPhysicalSize() {
+ return this.physicalSize;
+ }
+
+ public void setPhysicalSize(Long physicalSize ) {
+ this.physicalSize = physicalSize;
+ }
+
public VolumeObjectTO getVolume() {
return volume;
}
@@ -139,6 +161,10 @@ public class SnapshotObjectTO implements DataTO {
this.quiescevm = quiescevm;
}
+ public String[] getParents() {
+ return parents;
+ }
+
@Override
public String toString() {
return new StringBuilder("SnapshotTO[datastore=").append(dataStore).append("|volume=").append(volume).append("|path").append(path).append("]").toString();
diff --git a/core/test/org/apache/cloudstack/api/agent/test/CheckOnHostCommandTest.java b/core/test/org/apache/cloudstack/api/agent/test/CheckOnHostCommandTest.java
index d266eb3aabe..9edbf102471 100644
--- a/core/test/org/apache/cloudstack/api/agent/test/CheckOnHostCommandTest.java
+++ b/core/test/org/apache/cloudstack/api/agent/test/CheckOnHostCommandTest.java
@@ -81,7 +81,10 @@ public class CheckOnHostCommandTest {
return "10.1.1.1";
};
- @Override
+ public String getStorageUrl() {
+ return null;
+ }
+
public String getStorageIpAddress() {
return "10.1.1.2";
};
diff --git a/deps/XenServerJava/pom.xml b/deps/XenServerJava/pom.xml
index 6633e067e81..5c885b49808 100644
--- a/deps/XenServerJava/pom.xml
+++ b/deps/XenServerJava/pom.xml
@@ -40,29 +40,20 @@
org.apache.maven.plugins
maven-checkstyle-plugin
+ ${cs.checkstyle.version}
+
+
+ none
+
+
org.apache.cloudstack
- build-checkstyle
- ${parent.version}
+ checkstyle
+
+ ${project.parent.version}
-
-
- process-classes
-
- check
-
-
-
-
- true
- tooling/checkstyle.xml
- true
- true
- ${project.basedir}
- **\/*
-
diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Event.java b/deps/XenServerJava/src/com/xensource/xenapi/Event.java
index 68594fb7fe9..ec438140fe2 100644
--- a/deps/XenServerJava/src/com/xensource/xenapi/Event.java
+++ b/deps/XenServerJava/src/com/xensource/xenapi/Event.java
@@ -300,4 +300,19 @@ public class Event extends XenAPIObject {
return Types.toString(result);
}
+ public static Map properFrom(Connection c, Set classes, String token, Double timeout) throws BadServerResponse, XenAPIException, XmlRpcException,
+ Types.SessionNotRegistered,
+ Types.EventsLost {
+ String method_call = "event.from";
+ String session = c.getSessionReference();
+ Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(classes), Marshalling.toXMLRPC(token), Marshalling.toXMLRPC(timeout)};
+ Map response = c.dispatch(method_call, method_params);
+ Object result = response.get("Value");
+ Map value = (Map)result;
+ Map from = new HashMap();
+ from.put("token", value.get("token"));
+ from.put("events", Types.toSetOfEventRecord(value.get("events")));
+ return from;
+ }
+
}
\ No newline at end of file
diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Types.java b/deps/XenServerJava/src/com/xensource/xenapi/Types.java
index c6451ff035b..777d580e0b1 100644
--- a/deps/XenServerJava/src/com/xensource/xenapi/Types.java
+++ b/deps/XenServerJava/src/com/xensource/xenapi/Types.java
@@ -1279,6 +1279,17 @@ public class Types
String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : "";
throw new Types.CrlNameInvalid(p1);
}
+ if (ErrorDescription[0].equals("VDI_NOT_SPARSE"))
+ {
+ String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : "";
+ throw new Types.VdiNotSparse(p1);
+ }
+ if (ErrorDescription[0].equals("VDI_TOO_SMALL"))
+ {
+ String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : "";
+ String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : "";
+ throw new Types.VdiTooSmall(p1, p2);
+ }
if (ErrorDescription[0].equals("HOST_POWER_ON_MODE_DISABLED"))
{
throw new Types.HostPowerOnModeDisabled();
@@ -7822,6 +7833,45 @@ public class Types
}
+ /**
+ * The VDI is too small. Please resize it to at least the minimum size.
+ */
+ public static class VdiTooSmall extends XenAPIException {
+ public final String vdi;
+ public final String minimumSize;
+
+ /**
+ * Create a new VdiTooSmall
+ *
+ * @param vdi
+ * @param minimumSize
+ */
+ public VdiTooSmall(String vdi, String minimumSize) {
+ super("The VDI is too small. Please resize it to at least the minimum size.");
+ this.vdi = vdi;
+ this.minimumSize = minimumSize;
+ }
+
+ }
+
+ /**
+ * The VDI is not stored using a sparse format. It is not possible to query and manipulate only the changed blocks (or 'block differences' or 'disk deltas') between two VDIs. Please select a VDI which uses a sparse-aware technology such as VHD.
+ */
+ public static class VdiNotSparse extends XenAPIException {
+ public final String vdi;
+
+ /**
+ * Create a new VdiNotSparse
+ *
+ * @param vdi
+ */
+ public VdiNotSparse(String vdi) {
+ super("The VDI is not stored using a sparse format. It is not possible to query and manipulate only the changed blocks (or 'block differences' or 'disk deltas') between two VDIs. Please select a VDI which uses a sparse-aware technology such as VHD.");
+ this.vdi = vdi;
+ }
+
+ }
+
/**
* The hosts in this pool are not homogeneous.
*/
diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VDI.java b/deps/XenServerJava/src/com/xensource/xenapi/VDI.java
index 2c32c84e9fa..992a6a6d898 100644
--- a/deps/XenServerJava/src/com/xensource/xenapi/VDI.java
+++ b/deps/XenServerJava/src/com/xensource/xenapi/VDI.java
@@ -1608,6 +1608,29 @@ public class VDI extends XenAPIObject {
return;
}
+ /**
+ * Copy either a full VDI or the block differences between two VDIs into either a fresh VDI or an existing VDI.
+ *
+ * @param sr The destination SR (only required if the destination VDI is not specified
+ * @param baseVdi The base VDI (only required if copying only changed blocks, by default all blocks will be copied)
+ * @param intoVdi The destination VDI to copy blocks into (if omitted then a destination SR must be provided and a fresh VDI will be created)
+ * @return Task
+ */
+ public Task copyAsync2(Connection c, SR sr, VDI baseVdi, VDI intoVdi) throws
+ BadServerResponse,
+ XenAPIException,
+ XmlRpcException,
+ Types.VdiReadonly,
+ Types.VdiTooSmall,
+ Types.VdiNotSparse {
+ String method_call = "Async.VDI.copy";
+ String session = c.getSessionReference();
+ Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sr), Marshalling.toXMLRPC(baseVdi), Marshalling.toXMLRPC(intoVdi)};
+ Map response = c.dispatch(method_call, method_params);
+ Object result = response.get("Value");
+ return Types.toTask(result);
+ }
+
/**
* Make a fresh VDI in the specified SR and copy the supplied VDI's data to the new disk
*
diff --git a/engine/api/src/com/cloud/vm/VirtualMachineManager.java b/engine/api/src/com/cloud/vm/VirtualMachineManager.java
index 80497b1dd5f..ac79860df31 100644
--- a/engine/api/src/com/cloud/vm/VirtualMachineManager.java
+++ b/engine/api/src/com/cloud/vm/VirtualMachineManager.java
@@ -48,9 +48,10 @@ import com.cloud.utils.fsm.NoTransitionException;
* Manages allocating resources to vms.
*/
public interface VirtualMachineManager extends Manager {
+
static final ConfigKey ExecuteInSequence = new ConfigKey("Advanced", Boolean.class, "execute.in.sequence.hypervisor.commands", "false",
- "If set to true, StartCommand, StopCommand, CopyCommand, MigrateCommand will be synchronized on the agent side."
- + " If set to false, these commands become asynchronous. Default value is false.", true);
+ "If set to true, StartCommand, StopCommand, CopyCommand, MigrateCommand will be synchronized on the agent side."
+ + " If set to false, these commands become asynchronous. Default value is false.", false);
public interface Topics {
public static final String VM_POWER_STATE = "vm.powerstate";
@@ -93,39 +94,29 @@ public interface VirtualMachineManager extends Manager {
boolean stateTransitTo(VirtualMachine vm, VirtualMachine.Event e, Long hostId) throws NoTransitionException;
- void advanceStart(String vmUuid, Map params) throws InsufficientCapacityException, ResourceUnavailableException,
- ConcurrentOperationException, OperationTimedoutException;
+ void advanceStart(String vmUuid, Map params, DeploymentPlanner planner) throws InsufficientCapacityException, ResourceUnavailableException,
+ ConcurrentOperationException, OperationTimedoutException;
- void advanceStart(String vmUuid, Map params, DeploymentPlan planToDeploy) throws InsufficientCapacityException,
- ResourceUnavailableException, ConcurrentOperationException, OperationTimedoutException;
+ void advanceStart(String vmUuid, Map params, DeploymentPlan planToDeploy, DeploymentPlanner planner) throws InsufficientCapacityException,
+ ResourceUnavailableException, ConcurrentOperationException, OperationTimedoutException;
- void orchestrateStart(String vmUuid, Map params, DeploymentPlan planToDeploy) throws InsufficientCapacityException,
+ void orchestrateStart(String vmUuid, Map params, DeploymentPlan planToDeploy, DeploymentPlanner planner) throws InsufficientCapacityException,
ResourceUnavailableException, ConcurrentOperationException, OperationTimedoutException;
void advanceStop(String vmUuid, boolean cleanupEvenIfUnableToStop) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException;
- void orchestrateStop(String vmUuid, boolean cleanupEvenIfUnableToStop) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException;
-
void advanceExpunge(String vmUuid) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException;
void destroy(String vmUuid) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException;
- void migrateAway(String vmUuid, long hostId) throws InsufficientServerCapacityException;
+ void migrateAway(String vmUuid, long hostId, DeploymentPlanner planner) throws InsufficientServerCapacityException;
void migrate(String vmUuid, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException;
- void orchestrateMigrate(String vmUuid, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException;
-
- void migrateWithStorage(String vmUuid, long srcId, long destId, Map volumeToPool) throws ResourceUnavailableException,
- ConcurrentOperationException;
-
- void orchestrateMigrateWithStorage(String vmUuid, long srcId, long destId, Map volumeToPool) throws ResourceUnavailableException,
- ConcurrentOperationException;
+ void migrateWithStorage(String vmUuid, long srcId, long destId, Map volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException;
void reboot(String vmUuid, Map params) throws InsufficientCapacityException, ResourceUnavailableException;
- void orchestrateReboot(String vmUuid, Map params) throws InsufficientCapacityException, ResourceUnavailableException;
-
void advanceReboot(String vmUuid, Map params) throws InsufficientCapacityException, ResourceUnavailableException,
ConcurrentOperationException, OperationTimedoutException;
@@ -142,8 +133,6 @@ public interface VirtualMachineManager extends Manager {
void storageMigration(String vmUuid, StoragePool storagePoolId);
- void orchestrateStorageMigration(String vmUuid, StoragePool storagePoolId);
-
/**
* @param vmInstance
* @param newServiceOffering
@@ -166,10 +155,7 @@ public interface VirtualMachineManager extends Manager {
* @throws ResourceUnavailableException
* @throws InsufficientCapacityException
*/
- NicProfile addVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) throws ConcurrentOperationException, ResourceUnavailableException,
- InsufficientCapacityException;
-
- NicProfile orchestrateAddVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) throws ConcurrentOperationException,
+ NicProfile addVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) throws ConcurrentOperationException,
ResourceUnavailableException, InsufficientCapacityException;
/**
@@ -181,8 +167,6 @@ public interface VirtualMachineManager extends Manager {
*/
boolean removeNicFromVm(VirtualMachine vm, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException;
- boolean orchestrateRemoveNicFromVm(VirtualMachine vm, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException;
-
/**
* @param vm
* @param network
@@ -192,9 +176,6 @@ public interface VirtualMachineManager extends Manager {
* @throws ConcurrentOperationException
*/
boolean removeVmFromNetwork(VirtualMachine vm, Network network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException;
-
- boolean orchestrateRemoveVmFromNetwork(VirtualMachine vm, Network network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException;
-
/**
* @param nic
* @param hypervisorType
@@ -209,17 +190,11 @@ public interface VirtualMachineManager extends Manager {
*/
VirtualMachineTO toVmTO(VirtualMachineProfile profile);
- VirtualMachine reConfigureVm(String vmUuid, ServiceOffering newServiceOffering, boolean sameHost) throws ResourceUnavailableException, ConcurrentOperationException;
-
- VirtualMachine orchestrateReConfigureVm(String vmUuid, ServiceOffering newServiceOffering, boolean sameHost) throws ResourceUnavailableException,
- ConcurrentOperationException;
+ VirtualMachine reConfigureVm(String vmUuid, ServiceOffering newServiceOffering, boolean sameHost) throws ResourceUnavailableException, ConcurrentOperationException,
+ InsufficientServerCapacityException;
void findHostAndMigrate(String vmUuid, Long newSvcOfferingId, DeploymentPlanner.ExcludeList excludeHostList) throws InsufficientCapacityException,
ConcurrentOperationException, ResourceUnavailableException;
void migrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long newSvcOfferingId) throws ResourceUnavailableException, ConcurrentOperationException;
-
- void orchestrateMigrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long newSvcOfferingId) throws ResourceUnavailableException,
- ConcurrentOperationException;
-
}
diff --git a/engine/api/src/org/apache/cloudstack/engine/orchestration/service/NetworkOrchestrationService.java b/engine/api/src/org/apache/cloudstack/engine/orchestration/service/NetworkOrchestrationService.java
index fc196e24568..c036c99b63d 100755
--- a/engine/api/src/org/apache/cloudstack/engine/orchestration/service/NetworkOrchestrationService.java
+++ b/engine/api/src/org/apache/cloudstack/engine/orchestration/service/NetworkOrchestrationService.java
@@ -208,11 +208,13 @@ public interface NetworkOrchestrationService {
boolean isSecondaryIpSetForNic(long nicId);
- List extends Nic> listVmNics(Long vmId, Long nicId);
+ List extends Nic> listVmNics(long vmId, Long nicId, Long networkId);
Nic savePlaceholderNic(Network network, String ip4Address, String ip6Address, Type vmType);
DhcpServiceProvider getDhcpServiceProvider(Network network);
void removeDhcpServiceInSubnet(Nic nic);
+
+ boolean resourceCountNeedsUpdate(NetworkOffering ntwkOff, ACLType aclType);
}
diff --git a/engine/api/src/org/apache/cloudstack/engine/orchestration/service/VolumeOrchestrationService.java b/engine/api/src/org/apache/cloudstack/engine/orchestration/service/VolumeOrchestrationService.java
index a9ccc06617a..f79d3361b97 100644
--- a/engine/api/src/org/apache/cloudstack/engine/orchestration/service/VolumeOrchestrationService.java
+++ b/engine/api/src/org/apache/cloudstack/engine/orchestration/service/VolumeOrchestrationService.java
@@ -44,6 +44,7 @@ import com.cloud.utils.fsm.NoTransitionException;
import com.cloud.vm.DiskProfile;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
+import org.apache.cloudstack.framework.config.ConfigKey;
/**
* VolumeOrchestrationService is a PURE orchestration service on CloudStack
@@ -53,6 +54,21 @@ import com.cloud.vm.VirtualMachineProfile;
* to provision volumes.
*/
public interface VolumeOrchestrationService {
+
+ static final ConfigKey CustomDiskOfferingMinSize = new ConfigKey("Advanced",
+ Long.class,
+ "custom.diskoffering.size.min",
+ "1",
+ "Minimum size in GB for custom disk offering.",
+ true
+ );
+ static final ConfigKey CustomDiskOfferingMaxSize = new ConfigKey("Advanced",
+ Long.class,
+ "custom.diskoffering.size.max",
+ "1024",
+ "Maximum size in GB for custom disk offering.",
+ true
+ );
VolumeInfo moveVolume(VolumeInfo volume, long destPoolDcId, Long destPoolPodId, Long destPoolClusterId, HypervisorType dataDiskHyperType)
throws ConcurrentOperationException, StorageUnavailableException;
@@ -78,6 +94,8 @@ public interface VolumeOrchestrationService {
void cleanupVolumes(long vmId) throws ConcurrentOperationException;
+ void disconnectVolumesFromHost(long vmId, long hostId);
+
void migrateVolumes(VirtualMachine vm, VirtualMachineTO vmTo, Host srcHost, Host destHost, Map volumeToPool);
boolean storageMigration(VirtualMachineProfile vm, StoragePool destPool) throws StorageUnavailableException;
diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreManager.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreManager.java
index 210d4ae2fbe..5ebef031c5c 100644
--- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreManager.java
+++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreManager.java
@@ -42,4 +42,6 @@ public interface DataStoreManager {
List listImageStores();
List listImageCacheStores();
+
+ boolean isRegionStore(DataStore store);
}
diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/EndPointSelector.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/EndPointSelector.java
index b812f6efd99..4657316dd8a 100644
--- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/EndPointSelector.java
+++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/EndPointSelector.java
@@ -23,11 +23,17 @@ import java.util.List;
public interface EndPointSelector {
EndPoint select(DataObject srcData, DataObject destData);
+ EndPoint select(DataObject srcData, DataObject destData, StorageAction action);
+
EndPoint select(DataObject object);
EndPoint select(DataStore store);
+ EndPoint select(DataObject object, StorageAction action);
+
List selectAll(DataStore store);
EndPoint select(Scope scope, Long storeId);
+
+ EndPoint selectHypervisorHost(Scope scope);
}
diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreDriver.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreDriver.java
index f3399cd733e..c4dfc5ceb7e 100644
--- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreDriver.java
+++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreDriver.java
@@ -21,9 +21,19 @@ package org.apache.cloudstack.engine.subsystem.api.storage;
import org.apache.cloudstack.framework.async.AsyncCompletionCallback;
import org.apache.cloudstack.storage.command.CommandResult;
+import com.cloud.host.Host;
+import com.cloud.storage.StoragePool;
+import com.cloud.storage.Volume;
+
public interface PrimaryDataStoreDriver extends DataStoreDriver {
public ChapInfo getChapInfo(VolumeInfo volumeInfo);
+ public boolean connectVolumeToHost(VolumeInfo volumeInfo, Host host, DataStore dataStore);
+
+ public void disconnectVolumeFromHost(VolumeInfo volumeInfo, Host host, DataStore dataStore);
+
+ public long getVolumeSizeIncludingHypervisorSnapshotReserve(Volume volume, StoragePool pool);
+
public void takeSnapshot(SnapshotInfo snapshot, AsyncCompletionCallback callback);
public void revertSnapshot(SnapshotInfo snapshot, AsyncCompletionCallback callback);
diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotDataFactory.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotDataFactory.java
index d5255f40407..59e59a60662 100644
--- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotDataFactory.java
+++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotDataFactory.java
@@ -30,4 +30,6 @@ public interface SnapshotDataFactory {
SnapshotInfo getSnapshot(long snapshotId, DataStoreRole role);
List listSnapshotOnCache(long snapshotId);
+
+ SnapshotInfo getReadySnapshotOnCache(long snapshotId);
}
diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotService.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotService.java
index e953eb6e21b..000b9ec4e60 100644
--- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotService.java
+++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotService.java
@@ -25,4 +25,6 @@ public interface SnapshotService {
boolean deleteSnapshot(SnapshotInfo snapshot);
boolean revertSnapshot(Long snapshotId);
+
+ void syncVolumeSnapshotsToRegionStore(long volumeId, DataStore store);
}
diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageAction.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageAction.java
new file mode 100644
index 00000000000..4fbb20ed29e
--- /dev/null
+++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageAction.java
@@ -0,0 +1,25 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF 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.apache.cloudstack.engine.subsystem.api.storage;
+
+public enum StorageAction {
+ TAKESNAPSHOT,
+ BACKUPSNAPSHOT,
+ DELETESNAPSHOT
+}
diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeInfo.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeInfo.java
index 5cba79ad2b4..f93f4efac83 100644
--- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeInfo.java
+++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeInfo.java
@@ -22,6 +22,7 @@ import com.cloud.agent.api.Answer;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.offering.DiskOffering.DiskCacheMode;
import com.cloud.storage.Volume;
+import com.cloud.vm.VirtualMachine;
public interface VolumeInfo extends DataObject, Volume {
boolean isAttachedVM();
@@ -35,6 +36,7 @@ public interface VolumeInfo extends DataObject, Volume {
Long getLastPoolId();
String getAttachedVmName();
+ VirtualMachine getAttachedVM();
void processEventOnly(ObjectInDataStoreStateMachine.Event event);
diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java
index bcc4e7f9c54..3f676ae73dc 100644
--- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java
+++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java
@@ -44,6 +44,10 @@ public interface VolumeService {
ChapInfo getChapInfo(VolumeInfo volumeInfo, DataStore dataStore);
+ boolean connectVolumeToHost(VolumeInfo volumeInfo, Host host, DataStore dataStore);
+
+ void disconnectVolumeFromHost(VolumeInfo volumeInfo, Host host, DataStore dataStore);
+
/**
* Creates the volume based on the given criteria
*
diff --git a/engine/components-api/src/com/cloud/deploy/DeploymentPlanningManager.java b/engine/components-api/src/com/cloud/deploy/DeploymentPlanningManager.java
index b61e89ddcea..de2fc0eaf5a 100644
--- a/engine/components-api/src/com/cloud/deploy/DeploymentPlanningManager.java
+++ b/engine/components-api/src/com/cloud/deploy/DeploymentPlanningManager.java
@@ -39,11 +39,12 @@ public interface DeploymentPlanningManager extends Manager {
*
*
*/
- DeployDestination planDeployment(VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoids) throws InsufficientServerCapacityException,
- AffinityConflictException;
+ DeployDestination planDeployment(VirtualMachineProfile vmProfile, DeploymentPlan plan,
+ ExcludeList avoids, DeploymentPlanner planner) throws InsufficientServerCapacityException, AffinityConflictException;
- String finalizeReservation(DeployDestination plannedDestination, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoids)
- throws InsufficientServerCapacityException, AffinityConflictException;
+ String finalizeReservation(DeployDestination plannedDestination,
+ VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoids)
+ throws InsufficientServerCapacityException, AffinityConflictException;
void cleanupVMReservations();
}
diff --git a/engine/components-api/src/com/cloud/network/IpAddressManager.java b/engine/components-api/src/com/cloud/network/IpAddressManager.java
index e7061f9ecd9..9ccc9466f70 100644
--- a/engine/components-api/src/com/cloud/network/IpAddressManager.java
+++ b/engine/components-api/src/com/cloud/network/IpAddressManager.java
@@ -21,7 +21,6 @@ import java.util.List;
import org.apache.cloudstack.framework.config.ConfigKey;
import com.cloud.dc.DataCenter;
-import com.cloud.dc.Pod;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientAddressCapacityException;
@@ -169,8 +168,8 @@ public interface IpAddressManager {
int getRuleCountForIp(Long addressId, FirewallRule.Purpose purpose, FirewallRule.State state);
- public String allocateGuestIP(Account ipOwner, boolean isSystem, long zoneId, Long networkId, String requestedIp) throws InsufficientAddressCapacityException;
+ public String allocateGuestIP(Network network, String requestedIp) throws InsufficientAddressCapacityException;
- String allocatePublicIpForGuestNic(Long networkId, DataCenter dc, Pod pod, Account caller, String requestedIp) throws InsufficientAddressCapacityException;
+ String allocatePublicIpForGuestNic(Network network, Long podId, Account ipOwner, String requestedIp) throws InsufficientAddressCapacityException;
}
diff --git a/engine/components-api/src/com/cloud/resource/ResourceManager.java b/engine/components-api/src/com/cloud/resource/ResourceManager.java
index e623b9c6da9..95fb3853717 100755
--- a/engine/components-api/src/com/cloud/resource/ResourceManager.java
+++ b/engine/components-api/src/com/cloud/resource/ResourceManager.java
@@ -1,3 +1,4 @@
+
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
@@ -83,6 +84,8 @@ public interface ResourceManager extends ResourceService {
public boolean maintain(final long hostId) throws AgentUnavailableException;
+ public boolean checkAndMaintain(final long hostId);
+
@Override
public boolean deleteHost(long hostId, boolean isForced, boolean isForceDeleteStorage);
diff --git a/engine/components-api/src/com/cloud/template/TemplateManager.java b/engine/components-api/src/com/cloud/template/TemplateManager.java
index 83fedcd89a8..0a07f6b4a3d 100755
--- a/engine/components-api/src/com/cloud/template/TemplateManager.java
+++ b/engine/components-api/src/com/cloud/template/TemplateManager.java
@@ -101,6 +101,8 @@ public interface TemplateManager {
DataStore getImageStore(long zoneId, long tmpltId);
+ DataStore getImageStore(long tmpltId);
+
Long getTemplateSize(long templateId, long zoneId);
DataStore getImageStore(String storeUuid, Long zoneId);
diff --git a/engine/components-api/src/com/cloud/vm/VmWork.java b/engine/components-api/src/com/cloud/vm/VmWork.java
index 751db997d90..ed9f44cb9bb 100644
--- a/engine/components-api/src/com/cloud/vm/VmWork.java
+++ b/engine/components-api/src/com/cloud/vm/VmWork.java
@@ -25,10 +25,13 @@ public class VmWork implements Serializable {
long accountId;
long vmId;
- public VmWork(long userId, long accountId, long vmId) {
+ String handlerName;
+
+ public VmWork(long userId, long accountId, long vmId, String handlerName) {
this.userId = userId;
this.accountId = accountId;
this.vmId = vmId;
+ this.handlerName = handlerName;
}
public long getUserId() {
@@ -42,4 +45,8 @@ public class VmWork implements Serializable {
public long getVmId() {
return vmId;
}
+
+ public String getHandlerName() {
+ return handlerName;
+ }
}
diff --git a/engine/components-api/src/com/cloud/vm/VmWorkConstants.java b/engine/components-api/src/com/cloud/vm/VmWorkConstants.java
new file mode 100644
index 00000000000..20e40b7f84b
--- /dev/null
+++ b/engine/components-api/src/com/cloud/vm/VmWorkConstants.java
@@ -0,0 +1,23 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF 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 com.cloud.vm;
+
+public interface VmWorkConstants {
+ public static final String VM_WORK_QUEUE = "VmWorkJobQueue";
+ public static final String VM_WORK_JOB_DISPATCHER = "VmWorkJobDispatcher";
+ public static final String VM_WORK_JOB_WAKEUP_DISPATCHER = "VmWorkJobWakeupDispatcher";
+}
diff --git a/engine/components-api/src/com/cloud/vm/VmWorkJobHandler.java b/engine/components-api/src/com/cloud/vm/VmWorkJobHandler.java
new file mode 100644
index 00000000000..d49a041bf48
--- /dev/null
+++ b/engine/components-api/src/com/cloud/vm/VmWorkJobHandler.java
@@ -0,0 +1,25 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF 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 com.cloud.vm;
+
+import org.apache.cloudstack.jobs.JobInfo;
+
+import com.cloud.utils.Pair;
+
+public interface VmWorkJobHandler {
+ Pair handleVmWorkJob(VmWork work) throws Exception;
+}
diff --git a/engine/components-api/src/com/cloud/vm/VmWorkJobHandlerProxy.java b/engine/components-api/src/com/cloud/vm/VmWorkJobHandlerProxy.java
new file mode 100644
index 00000000000..ce10a83c7cd
--- /dev/null
+++ b/engine/components-api/src/com/cloud/vm/VmWorkJobHandlerProxy.java
@@ -0,0 +1,133 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF 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 com.cloud.vm;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.log4j.Logger;
+
+import com.google.gson.Gson;
+
+import org.apache.cloudstack.framework.jobs.impl.JobSerializerHelper;
+import org.apache.cloudstack.jobs.JobInfo;
+
+import com.cloud.serializer.GsonHelper;
+import com.cloud.utils.Pair;
+
+/**
+ * VmWorkJobHandlerProxy can not be used as standalone due to run-time
+ * reflection usage in its implementation, run-time reflection conflicts with Spring proxy mode.
+ * It means that we can not instantiate VmWorkJobHandlerProxy beans directly in Spring and expect
+ * it can handle VmWork directly from there.
+ *
+ */
+public class VmWorkJobHandlerProxy implements VmWorkJobHandler {
+
+ private static final Logger s_logger = Logger.getLogger(VmWorkJobHandlerProxy.class);
+
+ private Object _target;
+ private Map, Method> _handlerMethodMap = new HashMap, Method>();
+
+ private Gson _gsonLogger;
+
+ public VmWorkJobHandlerProxy(Object target) {
+ _gsonLogger = GsonHelper.getGsonLogger();
+
+ buildLookupMap(target.getClass());
+ _target = target;
+ }
+
+ private void buildLookupMap(Class> hostClass) {
+ Class> clz = hostClass;
+ while (clz != null && clz != Object.class) {
+ Method[] hostHandlerMethods = clz.getDeclaredMethods();
+
+ for (Method method : hostHandlerMethods) {
+ if (isVmWorkJobHandlerMethod(method)) {
+ Class> paramType = method.getParameterTypes()[0];
+ assert (_handlerMethodMap.get(paramType) == null);
+
+ method.setAccessible(true);
+ _handlerMethodMap.put(paramType, method);
+ }
+ }
+
+ clz = clz.getSuperclass();
+ }
+ }
+
+ @SuppressWarnings("deprecation")
+ private boolean isVmWorkJobHandlerMethod(Method method) {
+ if (method.getParameterTypes().length != 1)
+ return false;
+
+ Class> returnType = method.getReturnType();
+ if (!Pair.class.isAssignableFrom(returnType))
+ return false;
+
+ Class> paramType = method.getParameterTypes()[0];
+ if (!VmWork.class.isAssignableFrom(paramType))
+ return false;
+
+ return true;
+ }
+
+ private Method getHandlerMethod(Class> paramType) {
+ return _handlerMethodMap.get(paramType);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Pair handleVmWorkJob(VmWork work) throws Exception {
+
+ Method method = getHandlerMethod(work.getClass());
+ if (method != null) {
+
+ try {
+ if (s_logger.isDebugEnabled())
+ s_logger.debug("Execute VM work job: " + work.getClass().getName() + _gsonLogger.toJson(work));
+
+ Object obj = method.invoke(_target, work);
+
+ if (s_logger.isDebugEnabled())
+ s_logger.debug("Done executing VM work job: " + work.getClass().getName() + _gsonLogger.toJson(work));
+
+ assert (obj instanceof Pair);
+ return (Pair)obj;
+ } catch (InvocationTargetException e) {
+ s_logger.error("Invocation exception, caused by: " + e.getCause());
+
+ // legacy CloudStack code relies on checked exception for error handling
+ // we need to re-throw the real exception here
+ if (e.getCause() != null && e.getCause() instanceof Exception) {
+ s_logger.info("Rethrow exception " + e.getCause());
+ throw (Exception)e.getCause();
+ }
+
+ throw e;
+ }
+ } else {
+ s_logger.error("Unable to find handler for VM work job: " + work.getClass().getName() + _gsonLogger.toJson(work));
+
+ RuntimeException ex = new RuntimeException("Unable to find handler for VM work job: " + work.getClass().getName());
+ return new Pair(JobInfo.Status.FAILED, JobSerializerHelper.toObjectSerializedString(ex));
+ }
+ }
+}
diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkSerializer.java b/engine/components-api/src/com/cloud/vm/VmWorkSerializer.java
similarity index 100%
rename from engine/orchestration/src/com/cloud/vm/VmWorkSerializer.java
rename to engine/components-api/src/com/cloud/vm/VmWorkSerializer.java
diff --git a/engine/components-api/src/com/cloud/vm/snapshot/VMSnapshotManager.java b/engine/components-api/src/com/cloud/vm/snapshot/VMSnapshotManager.java
index 7d233ca7d30..e7e3372b0db 100644
--- a/engine/components-api/src/com/cloud/vm/snapshot/VMSnapshotManager.java
+++ b/engine/components-api/src/com/cloud/vm/snapshot/VMSnapshotManager.java
@@ -42,5 +42,4 @@ public interface VMSnapshotManager extends VMSnapshotService, Manager {
boolean syncVMSnapshot(VMInstanceVO vm, Long hostId);
boolean hasActiveVMSnapshotTasks(Long vmId);
-
}
diff --git a/engine/orchestration/resources/META-INF/cloudstack/core/spring-engine-orchestration-core-context.xml b/engine/orchestration/resources/META-INF/cloudstack/core/spring-engine-orchestration-core-context.xml
index fc3bae3129f..fd5299c8f70 100644
--- a/engine/orchestration/resources/META-INF/cloudstack/core/spring-engine-orchestration-core-context.xml
+++ b/engine/orchestration/resources/META-INF/cloudstack/core/spring-engine-orchestration-core-context.xml
@@ -60,7 +60,6 @@
-
+
-
+
+
+
+
-
+
diff --git a/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java b/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java
index cdfe744841f..d51df220195 100755
--- a/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java
+++ b/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java
@@ -1475,20 +1475,12 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl
List hosts = sc.list();
for (HostVO host : hosts) {
- long hostId = host.getId();
- DataCenterVO dcVO = _dcDao.findById(host.getDataCenterId());
- HostPodVO podVO = _podDao.findById(host.getPodId());
- String hostDesc = "name: " + host.getName() + " (id:" + hostId + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName();
-
- if (host.getType() != Host.Type.Storage) {
-// List vos = _vmDao.listByHostId(hostId);
-// List vosMigrating = _vmDao.listVmsMigratingFromHost(hostId);
-// if (vos.isEmpty() && vosMigrating.isEmpty()) {
-// _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Migration Complete for host " + hostDesc, "Host ["
-// + hostDesc
-// + "] is ready for maintenance");
-// _resourceMgr.resourceStateTransitTo(host, ResourceState.Event.InternalEnterMaintenance, _msId);
-// }
+ if (_resourceMgr.checkAndMaintain(host.getId())) {
+ DataCenterVO dcVO = _dcDao.findById(host.getDataCenterId());
+ HostPodVO podVO = _podDao.findById(host.getPodId());
+ String hostDesc = "name: " + host.getName() + " (id:" + host.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName();
+ _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Migration Complete for host " + hostDesc, "Host ["
+ + hostDesc + "] is ready for maintenance");
}
}
} catch (Throwable th) {
diff --git a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
index 7201569b970..628528a33c4 100755
--- a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
+++ b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
@@ -58,7 +58,6 @@ import org.apache.cloudstack.framework.jobs.AsyncJobManager;
import org.apache.cloudstack.framework.jobs.Outcome;
import org.apache.cloudstack.framework.jobs.dao.VmWorkJobDao;
import org.apache.cloudstack.framework.jobs.impl.AsyncJobVO;
-import org.apache.cloudstack.framework.jobs.impl.JobSerializerHelper;
import org.apache.cloudstack.framework.jobs.impl.OutcomeImpl;
import org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO;
import org.apache.cloudstack.framework.messagebus.MessageBus;
@@ -118,6 +117,7 @@ import com.cloud.dc.dao.HostPodDao;
import com.cloud.deploy.DataCenterDeployment;
import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlan;
+import com.cloud.deploy.DeploymentPlanner;
import com.cloud.deploy.DeploymentPlanner.ExcludeList;
import com.cloud.deploy.DeploymentPlanningManager;
import com.cloud.domain.dao.DomainDao;
@@ -182,7 +182,7 @@ import com.cloud.utils.db.DB;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.Transaction;
-import com.cloud.utils.db.TransactionCallbackNoReturn;
+import com.cloud.utils.db.TransactionCallback;
import com.cloud.utils.db.TransactionCallbackWithException;
import com.cloud.utils.db.TransactionCallbackWithExceptionNoReturn;
import com.cloud.utils.db.TransactionLegacy;
@@ -205,9 +205,11 @@ import com.cloud.vm.snapshot.VMSnapshotVO;
import com.cloud.vm.snapshot.dao.VMSnapshotDao;
@Local(value = VirtualMachineManager.class)
-public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMachineManager, Listener, Configurable {
+public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMachineManager, VmWorkJobHandler, Listener, Configurable {
private static final Logger s_logger = Logger.getLogger(VirtualMachineManagerImpl.class);
+ public static final String VM_WORK_JOB_HANDLER = VirtualMachineManagerImpl.class.getSimpleName();
+
private static final String VM_SYNC_ALERT_SUBJECT = "VM state sync alert";
@Inject
@@ -270,6 +272,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
protected AffinityGroupVMMapDao _affinityGroupVMMapDao;
@Inject
protected EntityManager _entityMgr;
+
@Inject
ConfigDepot _configDepot;
@@ -312,6 +315,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Inject
protected AsyncJobManager _jobMgr;
+ VmWorkJobHandlerProxy _jobHandlerProxy = new VmWorkJobHandlerProxy(this);
+
Map _vmGurus = new HashMap();
protected StateMachine2 _stateMachine;
@@ -454,7 +459,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
return;
}
- advanceStop(vm, false);
+ advanceStop(vm.getUuid(), false);
+ vm = _vmDao.findByUuid(vm.getUuid());
try {
if (!stateTransitTo(vm, VirtualMachine.Event.ExpungeOperation, vm.getHostId())) {
@@ -479,6 +485,36 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
List nicExpungeCommands = hvGuru.finalizeExpungeNics(vm, profile.getNics());
_networkMgr.cleanupNics(profile);
+ s_logger.debug("Cleaning up hypervisor data structures (ex. SRs in XenServer) for managed storage");
+
+ List volumeExpungeCommands = hvGuru.finalizeExpungeVolumes(vm);
+
+ Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId();
+
+ if (volumeExpungeCommands != null && hostId != null) {
+ Commands cmds = new Commands(Command.OnError.Stop);
+
+ for (Command volumeExpungeCommand : volumeExpungeCommands) {
+ cmds.addCommand(volumeExpungeCommand);
+ }
+
+ _agentMgr.send(hostId, cmds);
+
+ if (!cmds.isSuccessful()) {
+ for (Answer answer : cmds.getAnswers()) {
+ if (!answer.getResult()) {
+ s_logger.warn("Failed to expunge vm due to: " + answer.getDetails());
+
+ throw new CloudRuntimeException("Unable to expunge " + vm + " due to " + answer.getDetails());
+ }
+ }
+ }
+ }
+
+ if (hostId != null) {
+ volumeMgr.disconnectVolumesFromHost(vm.getId(), hostId);
+ }
+
// Clean up volumes based on the vm's instance id
volumeMgr.cleanupVolumes(vm.getId());
@@ -490,7 +526,6 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
// send hypervisor-dependent commands before removing
List finalizeExpungeCommands = hvGuru.finalizeExpunge(vm);
if (finalizeExpungeCommands != null && finalizeExpungeCommands.size() > 0) {
- Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId();
if (hostId != null) {
Commands cmds = new Commands(Command.OnError.Stop);
for (Command command : finalizeExpungeCommands) {
@@ -521,6 +556,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Override
public boolean start() {
+ // TODO, initial delay is hardcoded
+ _executor.scheduleAtFixedRate(new TransitionTask(), 5000, VmJobStateReportInterval.value(), TimeUnit.SECONDS);
_executor.scheduleAtFixedRate(new CleanupTask(), VmOpCleanupInterval.value(), VmOpCleanupInterval.value(), TimeUnit.SECONDS);
cancelWorkItems(_nodeId);
return true;
@@ -556,7 +593,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Override
public void start(String vmUuid, Map params, DeploymentPlan planToDeploy) {
try {
- advanceStart(vmUuid, params, planToDeploy);
+ advanceStart(vmUuid, params, planToDeploy, null);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Unable to start a VM due to concurrent operation", e).add(VirtualMachine.class, vmUuid);
} catch (InsufficientCapacityException e) {
@@ -697,20 +734,19 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
@Override
- public void advanceStart(String vmUuid, Map params)
+ public void advanceStart(String vmUuid, Map params, DeploymentPlanner planner)
throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
-
- advanceStart(vmUuid, params, null);
+ advanceStart(vmUuid, params, null, planner);
}
@Override
- public void advanceStart(String vmUuid, Map params, DeploymentPlan planToDeploy) throws InsufficientCapacityException,
+ public void advanceStart(String vmUuid, Map params, DeploymentPlan planToDeploy, DeploymentPlanner planner) throws InsufficientCapacityException,
ConcurrentOperationException, ResourceUnavailableException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
- if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) {
+ if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
- orchestrateStart(vmUuid, params, planToDeploy);
+ orchestrateStart(vmUuid, params, planToDeploy, planner);
} else {
Outcome outcome = startVmThroughJobQueue(vmUuid, params, planToDeploy);
@@ -722,19 +758,20 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
throw new RuntimeException("Execution excetion", e);
}
- Throwable jobException = retriveExecutionException(outcome.getJob());
- if (jobException != null) {
- if (jobException instanceof ConcurrentOperationException)
- throw (ConcurrentOperationException)jobException;
- else if (jobException instanceof ResourceUnavailableException)
- throw (ResourceUnavailableException)jobException;
+ Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
+ if (jobResult != null) {
+ if (jobResult instanceof ConcurrentOperationException)
+ throw (ConcurrentOperationException)jobResult;
+ else if (jobResult instanceof ResourceUnavailableException)
+ throw (ResourceUnavailableException)jobResult;
}
}
}
+
@Override
- public void orchestrateStart(String vmUuid, Map params, DeploymentPlan planToDeploy) throws InsufficientCapacityException,
- ConcurrentOperationException, ResourceUnavailableException {
+ public void orchestrateStart(String vmUuid, Map params, DeploymentPlan planToDeploy, DeploymentPlanner planner)
+ throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
CallContext cctxt = CallContext.current();
Account account = cctxt.getCallingAccount();
@@ -848,10 +885,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
}
- VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, template, offering, account, params);
+ Account owner = _entityMgr.findById(Account.class, vm.getAccountId());
+ VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, template, offering, owner, params);
DeployDestination dest = null;
try {
- dest = _dpMgr.planDeployment(vmProfile, plan, avoids);
+ dest = _dpMgr.planDeployment(vmProfile, plan, avoids, planner);
} catch (AffinityConflictException e2) {
s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2);
throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict");
@@ -1225,10 +1263,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Override
public void advanceStop(String vmUuid, boolean cleanUpEvenIfUnableToStop)
- throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
+ throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
- if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) {
+ if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateStop(vmUuid, cleanUpEvenIfUnableToStop);
} else {
@@ -1242,21 +1280,19 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
throw new RuntimeException("Execution excetion", e);
}
- Throwable jobException = retriveExecutionException(outcome.getJob());
- if (jobException != null) {
- if (jobException instanceof AgentUnavailableException)
- throw (AgentUnavailableException)jobException;
- else if (jobException instanceof ConcurrentOperationException)
- throw (ConcurrentOperationException)jobException;
- else if (jobException instanceof OperationTimedoutException)
- throw (OperationTimedoutException)jobException;
+ Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
+ if (jobResult != null) {
+ if (jobResult instanceof AgentUnavailableException)
+ throw (AgentUnavailableException)jobResult;
+ else if (jobResult instanceof ConcurrentOperationException)
+ throw (ConcurrentOperationException)jobResult;
+ else if (jobResult instanceof OperationTimedoutException)
+ throw (OperationTimedoutException)jobResult;
}
}
}
- @Override
- public void orchestrateStop(String vmUuid, boolean cleanUpEvenIfUnableToStop) throws AgentUnavailableException, OperationTimedoutException,
- ConcurrentOperationException {
+ private void orchestrateStop(String vmUuid, boolean cleanUpEvenIfUnableToStop) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
advanceStop(vm, cleanUpEvenIfUnableToStop);
@@ -1490,13 +1526,15 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
s_logger.debug("Destroying vm " + vm);
}
- advanceStop(vm, VmDestroyForcestop.value());
+ advanceStop(vmUuid, VmDestroyForcestop.value());
if (!_vmSnapshotMgr.deleteAllVMSnapshots(vm.getId(), null)) {
s_logger.debug("Unable to delete all snapshots for " + vm);
throw new CloudRuntimeException("Unable to delete vm snapshots for " + vm);
}
+ // reload the vm object from db
+ vm = _vmDao.findByUuid(vmUuid);
try {
if (!stateTransitTo(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) {
s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm);
@@ -1520,7 +1558,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Override
public void storageMigration(String vmUuid, StoragePool destPool) {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
- if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) {
+ if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateStorageMigration(vmUuid, destPool);
} else {
@@ -1534,16 +1572,15 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
throw new RuntimeException("Execution excetion", e);
}
- Throwable jobException = retriveExecutionException(outcome.getJob());
- if (jobException != null) {
- if (jobException instanceof RuntimeException)
- throw (RuntimeException)jobException;
+ Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
+ if (jobResult != null) {
+ if (jobResult instanceof RuntimeException)
+ throw (RuntimeException)jobResult;
}
}
}
- @Override
- public void orchestrateStorageMigration(String vmUuid, StoragePool destPool) {
+ private void orchestrateStorageMigration(String vmUuid, StoragePool destPool) {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
try {
@@ -1600,10 +1637,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Override
public void migrate(String vmUuid, long srcHostId, DeployDestination dest)
- throws ResourceUnavailableException, ConcurrentOperationException {
+ throws ResourceUnavailableException, ConcurrentOperationException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
- if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) {
+ if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateMigrate(vmUuid, srcHostId, dest);
} else {
@@ -1617,20 +1654,19 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
throw new RuntimeException("Execution excetion", e);
}
- Throwable jobException = retriveExecutionException(outcome.getJob());
- if (jobException != null) {
- if (jobException instanceof ResourceUnavailableException)
- throw (ResourceUnavailableException)jobException;
- else if (jobException instanceof ConcurrentOperationException)
- throw (ConcurrentOperationException)jobException;
- else if (jobException instanceof RuntimeException)
- throw (RuntimeException)jobException;
+ Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
+ if (jobResult != null) {
+ if (jobResult instanceof ResourceUnavailableException)
+ throw (ResourceUnavailableException)jobResult;
+ else if (jobResult instanceof ConcurrentOperationException)
+ throw (ConcurrentOperationException)jobResult;
+ else if (jobResult instanceof RuntimeException)
+ throw (RuntimeException)jobResult;
}
}
}
- @Override
- public void orchestrateMigrate(String vmUuid, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException {
+ private void orchestrateMigrate(String vmUuid, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
if (vm == null) {
if (s_logger.isDebugEnabled()) {
@@ -1872,10 +1908,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Override
public void migrateWithStorage(String vmUuid, long srcHostId, long destHostId, Map volumeToPool)
- throws ResourceUnavailableException, ConcurrentOperationException {
+ throws ResourceUnavailableException, ConcurrentOperationException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
- if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) {
+ if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateMigrateWithStorage(vmUuid, srcHostId, destHostId, volumeToPool);
} else {
@@ -1889,7 +1925,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
throw new RuntimeException("Execution excetion", e);
}
- Throwable jobException = retriveExecutionException(outcome.getJob());
+ Object jobException = _jobMgr.unmarshallResultObject(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
@@ -1899,9 +1935,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
}
- @Override
- public void orchestrateMigrateWithStorage(String vmUuid, long srcHostId, long destHostId, Map volumeToPool) throws ResourceUnavailableException,
- ConcurrentOperationException {
+ private void orchestrateMigrateWithStorage(String vmUuid, long srcHostId, long destHostId, Map volumeToPool) throws ResourceUnavailableException,
+ ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
@@ -2039,7 +2074,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
@Override
- public void migrateAway(String vmUuid, long srcHostId) throws InsufficientServerCapacityException {
+ public void migrateAway(String vmUuid, long srcHostId, DeploymentPlanner planner) throws InsufficientServerCapacityException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
if (vm == null) {
s_logger.debug("Unable to find a VM for " + vmUuid);
@@ -2072,7 +2107,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
while (true) {
try {
- dest = _dpMgr.planDeployment(profile, plan, excludes);
+ dest = _dpMgr.planDeployment(profile, plan, excludes, planner);
} catch (AffinityConflictException e2) {
s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2);
throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict");
@@ -2100,7 +2135,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
try {
- advanceStop(vm, true);
+ advanceStop(vmUuid, true);
throw new CloudRuntimeException("Unable to migrate " + vm);
} catch (ResourceUnavailableException e) {
s_logger.debug("Unable to stop VM due to " + e.getMessage());
@@ -2152,10 +2187,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Override
public void advanceReboot(String vmUuid, Map params)
- throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
+ throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
- if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) {
+ if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateReboot(vmUuid, params);
} else {
@@ -2169,21 +2204,20 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
throw new RuntimeException("Execution excetion", e);
}
- Throwable jobException = retriveExecutionException(outcome.getJob());
- if (jobException != null) {
- if (jobException instanceof ResourceUnavailableException)
- throw (ResourceUnavailableException)jobException;
- else if (jobException instanceof ConcurrentOperationException)
- throw (ConcurrentOperationException)jobException;
- else if (jobException instanceof InsufficientCapacityException)
- throw (InsufficientCapacityException)jobException;
+ Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
+ if (jobResult != null) {
+ if (jobResult instanceof ResourceUnavailableException)
+ throw (ResourceUnavailableException)jobResult;
+ else if (jobResult instanceof ConcurrentOperationException)
+ throw (ConcurrentOperationException)jobResult;
+ else if (jobResult instanceof InsufficientCapacityException)
+ throw (InsufficientCapacityException)jobResult;
}
}
}
- @Override
- public void orchestrateReboot(String vmUuid, Map params) throws InsufficientCapacityException, ConcurrentOperationException,
- ResourceUnavailableException {
+ private void orchestrateReboot(String vmUuid, Map params) throws InsufficientCapacityException, ConcurrentOperationException,
+ ResourceUnavailableException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
DataCenter dc = _entityMgr.findById(DataCenter.class, vm.getDataCenterId());
@@ -2659,7 +2693,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
if (agentState == State.Shutdowned) {
if (serverState == State.Running || serverState == State.Starting || serverState == State.Stopping) {
try {
- advanceStop(vm, true);
+ advanceStop(vm.getUuid(), true);
} catch (AgentUnavailableException e) {
assert (false) : "How do we hit this with forced on?";
return null;
@@ -2829,7 +2863,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
}
- if (VmJobEnabled.value()) {
+ if(VmJobEnabled.value()) {
if (ping.getHostVmStateReport() != null && ping.getHostVmStateReport().size() > 0) {
_syncMgr.processHostVmStatePingReport(agentId, ping.getHostVmStateReport());
}
@@ -2940,9 +2974,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
return;
}
try {
- lock.addRef();
- List instances =
- _vmDao.findVMInTransition(new Date(new Date().getTime() - (AgentManager.Wait.value() * 1000)), State.Starting, State.Stopping);
+ scanStalledVMInTransitionStateOnDisconnectedHosts();
+
+ List instances = _vmDao.findVMInTransition(new Date(new Date().getTime() - (AgentManager.Wait.value() * 1000)), State.Starting, State.Stopping);
for (VMInstanceVO instance : instances) {
State state = instance.getState();
if (state == State.Stopping) {
@@ -3074,10 +3108,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Override
public NicProfile addVmToNetwork(VirtualMachine vm, Network network, NicProfile requested)
- throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
+ throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
- if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) {
+ if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
return orchestrateAddVmToNetwork(vm, network, requested);
} else {
@@ -3091,32 +3125,26 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
throw new RuntimeException("Execution excetion", e);
}
- AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, outcome.getJob().getId());
- if (jobVo.getResultCode() == JobInfo.Status.SUCCEEDED.ordinal()) {
-
- NicProfile nic = (NicProfile)JobSerializerHelper.fromObjectSerializedString(jobVo.getResult());
- return nic;
- } else {
- Throwable jobException = retriveExecutionException(outcome.getJob());
- if (jobException != null) {
- if (jobException instanceof ResourceUnavailableException)
- throw (ResourceUnavailableException)jobException;
- else if (jobException instanceof ConcurrentOperationException)
- throw (ConcurrentOperationException)jobException;
- else if (jobException instanceof InsufficientCapacityException)
- throw (InsufficientCapacityException)jobException;
- else if (jobException instanceof RuntimeException)
- throw (RuntimeException)jobException;
- }
- throw new RuntimeException("Job failed with unhandled exception");
+ Object jobException = _jobMgr.unmarshallResultObject(outcome.getJob());
+ if (jobException != null) {
+ if (jobException instanceof ResourceUnavailableException)
+ throw (ResourceUnavailableException)jobException;
+ else if (jobException instanceof ConcurrentOperationException)
+ throw (ConcurrentOperationException)jobException;
+ else if (jobException instanceof InsufficientCapacityException)
+ throw (InsufficientCapacityException)jobException;
+ else if (jobException instanceof RuntimeException)
+ throw (RuntimeException)jobException;
+ else if (jobException instanceof Long)
+ return requested;
}
+
+ throw new RuntimeException("Unexpected job execution result");
}
}
- @Override
- public NicProfile orchestrateAddVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) throws ConcurrentOperationException,
- ResourceUnavailableException,
- InsufficientCapacityException {
+ private NicProfile orchestrateAddVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) throws ConcurrentOperationException, ResourceUnavailableException,
+ InsufficientCapacityException {
CallContext cctx = CallContext.current();
s_logger.debug("Adding vm " + vm + " to network " + network + "; requested nic profile " + requested);
@@ -3183,10 +3211,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Override
public boolean removeNicFromVm(VirtualMachine vm, Nic nic)
- throws ConcurrentOperationException, ResourceUnavailableException {
+ throws ConcurrentOperationException, ResourceUnavailableException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
- if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) {
+ if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
return orchestrateRemoveNicFromVm(vm, nic);
} else {
@@ -3200,29 +3228,23 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
throw new RuntimeException("Execution excetion", e);
}
- AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, outcome.getJob().getId());
-
- if (jobVo.getResultCode() == JobInfo.Status.SUCCEEDED.ordinal()) {
- Boolean result = (Boolean)JobSerializerHelper.fromObjectSerializedString(jobVo.getResult());
- return result;
- } else {
- Throwable jobException = retriveExecutionException(outcome.getJob());
- if (jobException != null) {
- if (jobException instanceof ResourceUnavailableException)
- throw (ResourceUnavailableException)jobException;
- else if (jobException instanceof ConcurrentOperationException)
- throw (ConcurrentOperationException)jobException;
- else if (jobException instanceof RuntimeException)
- throw (RuntimeException)jobException;
- }
-
- throw new RuntimeException("Job failed with un-handled exception");
+ Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
+ if (jobResult != null) {
+ if (jobResult instanceof ResourceUnavailableException)
+ throw (ResourceUnavailableException)jobResult;
+ else if (jobResult instanceof ConcurrentOperationException)
+ throw (ConcurrentOperationException)jobResult;
+ else if (jobResult instanceof RuntimeException)
+ throw (RuntimeException)jobResult;
+ else if (jobResult instanceof Boolean)
+ return (Boolean)jobResult;
}
+
+ throw new RuntimeException("Job failed with un-handled exception");
}
}
- @Override
- public boolean orchestrateRemoveNicFromVm(VirtualMachine vm, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException {
+ private boolean orchestrateRemoveNicFromVm(VirtualMachine vm, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException {
CallContext cctx = CallContext.current();
VMInstanceVO vmVO = _vmDao.findById(vm.getId());
NetworkVO network = _networkDao.findById(nic.getNetworkId());
@@ -3288,9 +3310,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
return orchestrateRemoveVmFromNetwork(vm, network, broadcastUri);
}
- @Override
@DB
- public boolean orchestrateRemoveVmFromNetwork(VirtualMachine vm, Network network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException {
+ private boolean orchestrateRemoveVmFromNetwork(VirtualMachine vm, Network network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException {
CallContext cctx = CallContext.current();
VMInstanceVO vmVO = _vmDao.findById(vm.getId());
ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
@@ -3400,7 +3421,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
DeployDestination dest = null;
try {
- dest = _dpMgr.planDeployment(profile, plan, excludes);
+ dest = _dpMgr.planDeployment(profile, plan, excludes, null);
} catch (AffinityConflictException e2) {
s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2);
throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict");
@@ -3430,9 +3451,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Override
public void migrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long oldSvcOfferingId)
- throws ResourceUnavailableException, ConcurrentOperationException {
+ throws ResourceUnavailableException, ConcurrentOperationException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
- if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) {
+ if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateMigrateForScale(vmUuid, srcHostId, dest, oldSvcOfferingId);
} else {
@@ -3446,19 +3467,18 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
throw new RuntimeException("Execution excetion", e);
}
- Throwable jobException = retriveExecutionException(outcome.getJob());
- if (jobException != null) {
- if (jobException instanceof ResourceUnavailableException)
- throw (ResourceUnavailableException)jobException;
- else if (jobException instanceof ConcurrentOperationException)
- throw (ConcurrentOperationException)jobException;
+ Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
+ if (jobResult != null) {
+ if (jobResult instanceof ResourceUnavailableException)
+ throw (ResourceUnavailableException)jobResult;
+ else if (jobResult instanceof ConcurrentOperationException)
+ throw (ConcurrentOperationException)jobResult;
}
}
}
- @Override
- public void orchestrateMigrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long oldSvcOfferingId)
- throws ResourceUnavailableException, ConcurrentOperationException {
+ private void orchestrateMigrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long oldSvcOfferingId)
+ throws ResourceUnavailableException, ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
s_logger.info("Migrating " + vm + " to " + dest);
@@ -3678,11 +3698,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Override
public VMInstanceVO reConfigureVm(String vmUuid, ServiceOffering oldServiceOffering,
- boolean reconfiguringOnExistingHost)
- throws ResourceUnavailableException, ConcurrentOperationException {
+ boolean reconfiguringOnExistingHost)
+ throws ResourceUnavailableException, InsufficientServerCapacityException, ConcurrentOperationException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
- if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) {
+ if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
return orchestrateReConfigureVm(vmUuid, oldServiceOffering, reconfiguringOnExistingHost);
} else {
@@ -3697,27 +3717,26 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
throw new RuntimeException("Execution excetion", e);
}
- AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, outcome.getJob().getId());
- if (jobVo.getResultCode() == JobInfo.Status.SUCCEEDED.ordinal()) {
- return _entityMgr.findById(VMInstanceVO.class, vm.getId());
- } else {
- Throwable jobException = retriveExecutionException(outcome.getJob());
- if (jobException != null) {
- if (jobException instanceof ResourceUnavailableException)
- throw (ResourceUnavailableException)jobException;
- else if (jobException instanceof ConcurrentOperationException)
- throw (ConcurrentOperationException)jobException;
+ Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
+ if (jobResult != null) {
+ if (jobResult instanceof ResourceUnavailableException)
+ throw (ResourceUnavailableException)jobResult;
+ else if (jobResult instanceof ConcurrentOperationException)
+ throw (ConcurrentOperationException)jobResult;
+ else if (jobResult instanceof InsufficientServerCapacityException)
+ throw (InsufficientServerCapacityException)jobResult;
+ else if (jobResult instanceof Throwable) {
+ s_logger.error("Unhandled exception", (Throwable)jobResult);
+ throw new RuntimeException("Unhandled exception", (Throwable)jobResult);
}
-
- throw new RuntimeException("Failed with un-handled exception");
}
+
+ return (VMInstanceVO)vm;
}
}
- @Override
- public VMInstanceVO orchestrateReConfigureVm(String vmUuid, ServiceOffering oldServiceOffering, boolean reconfiguringOnExistingHost)
- throws ResourceUnavailableException,
- ConcurrentOperationException {
+ private VMInstanceVO orchestrateReConfigureVm(String vmUuid, ServiceOffering oldServiceOffering, boolean reconfiguringOnExistingHost) throws ResourceUnavailableException,
+ ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
long newServiceofferingId = vm.getServiceOfferingId();
@@ -3802,26 +3821,26 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
Long vmId = (Long)args;
List pendingWorkJobs = _workJobDao.listPendingWorkJobs(
- VirtualMachine.Type.Instance, vmId);
+ VirtualMachine.Type.Instance, vmId);
if (pendingWorkJobs.size() == 0) {
// there is no pending operation job
VMInstanceVO vm = _vmDao.findById(vmId);
if (vm != null) {
switch (vm.getPowerState()) {
- case PowerOn:
- handlePowerOnReportWithNoPendingJobsOnVM(vm);
- break;
+ case PowerOn:
+ handlePowerOnReportWithNoPendingJobsOnVM(vm);
+ break;
- case PowerOff:
- handlePowerOffReportWithNoPendingJobsOnVM(vm);
- break;
+ case PowerOff:
+ handlePowerOffReportWithNoPendingJobsOnVM(vm);
+ break;
- // PowerUnknown shouldn't be reported, it is a derived
- // VM power state from host state (host un-reachable
- case PowerUnknown:
- default:
- assert (false);
- break;
+ // PowerUnknown shouldn't be reported, it is a derived
+ // VM power state from host state (host un-reachable
+ case PowerUnknown:
+ default:
+ assert (false);
+ break;
}
} else {
s_logger.warn("VM " + vmId + " no longer exists when processing VM state report");
@@ -3834,98 +3853,98 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
private void handlePowerOnReportWithNoPendingJobsOnVM(VMInstanceVO vm) {
//
- // 1) handle left-over transitional VM states
- // 2) handle out of band VM live migration
- // 3) handle out of sync stationary states, marking VM from Stopped to Running with
- // alert messages
+ // 1) handle left-over transitional VM states
+ // 2) handle out of band VM live migration
+ // 3) handle out of sync stationary states, marking VM from Stopped to Running with
+ // alert messages
//
switch (vm.getState()) {
- case Starting:
- try {
- stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId());
- } catch (NoTransitionException e) {
- s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
- }
+ case Starting:
+ try {
+ stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId());
+ } catch (NoTransitionException e) {
+ s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
+ }
- // we need to alert admin or user about this risky state transition
- _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(),
- VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() +
- ") state is sync-ed (Starting -> Running) from out-of-context transition. VM network environment may need to be reset");
- break;
+ // we need to alert admin or user about this risky state transition
+ _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(),
+ VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName()
+ + ") state is sync-ed (Starting -> Running) from out-of-context transition. VM network environment may need to be reset");
+ break;
- case Running:
- try {
- if (vm.getHostId() != null && vm.getHostId().longValue() != vm.getPowerHostId().longValue())
- s_logger.info("Detected out of band VM migration from host " + vm.getHostId() + " to host " + vm.getPowerHostId());
- stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId());
- } catch (NoTransitionException e) {
- s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
- }
- break;
+ case Running:
+ try {
+ if (vm.getHostId() != null && vm.getHostId().longValue() != vm.getPowerHostId().longValue())
+ s_logger.info("Detected out of band VM migration from host " + vm.getHostId() + " to host " + vm.getPowerHostId());
+ stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId());
+ } catch (NoTransitionException e) {
+ s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
+ }
+ break;
- case Stopping:
- case Stopped:
- try {
- stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId());
- } catch (NoTransitionException e) {
- s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
- }
- _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(),
- VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") state is sync-ed (" + vm.getState() +
- " -> Running) from out-of-context transition. VM network environment may need to be reset");
- break;
+ case Stopping:
+ case Stopped:
+ try {
+ stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId());
+ } catch (NoTransitionException e) {
+ s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
+ }
+ _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(),
+ VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") state is sync-ed (" + vm.getState()
+ + " -> Running) from out-of-context transition. VM network environment may need to be reset");
+ break;
- case Destroyed:
- case Expunging:
- s_logger.info("Receive power on report when VM is in destroyed or expunging state. vm: "
+ case Destroyed:
+ case Expunging:
+ s_logger.info("Receive power on report when VM is in destroyed or expunging state. vm: "
+ vm.getId() + ", state: " + vm.getState());
- break;
+ break;
- case Migrating:
- try {
- stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId());
- } catch (NoTransitionException e) {
- s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
- }
- break;
+ case Migrating:
+ try {
+ stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId());
+ } catch (NoTransitionException e) {
+ s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
+ }
+ break;
- case Error:
- default:
- s_logger.info("Receive power on report when VM is in error or unexpected state. vm: "
+ case Error:
+ default:
+ s_logger.info("Receive power on report when VM is in error or unexpected state. vm: "
+ vm.getId() + ", state: " + vm.getState());
- break;
+ break;
}
}
private void handlePowerOffReportWithNoPendingJobsOnVM(VMInstanceVO vm) {
- // 1) handle left-over transitional VM states
- // 2) handle out of sync stationary states, schedule force-stop to release resources
+ // 1) handle left-over transitional VM states
+ // 2) handle out of sync stationary states, schedule force-stop to release resources
//
switch (vm.getState()) {
- case Starting:
- case Stopping:
- case Stopped:
- case Migrating:
- try {
- stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOffReport, vm.getPowerHostId());
- } catch (NoTransitionException e) {
- s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
- }
- _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(),
- VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") state is sync-ed (" + vm.getState() +
- " -> Stopped) from out-of-context transition.");
- // TODO: we need to forcely release all resource allocation
- break;
+ case Starting:
+ case Stopping:
+ case Stopped:
+ case Migrating:
+ try {
+ stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOffReport, vm.getPowerHostId());
+ } catch (NoTransitionException e) {
+ s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
+ }
+ _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(),
+ VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") state is sync-ed (" + vm.getState()
+ + " -> Stopped) from out-of-context transition.");
+ // TODO: we need to forcely release all resource allocation
+ break;
- case Running:
- case Destroyed:
- case Expunging:
- break;
+ case Running:
+ case Destroyed:
+ case Expunging:
+ break;
- case Error:
- default:
- break;
+ case Error:
+ default:
+ break;
}
}
@@ -3935,8 +3954,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
// VMs in expunging state (this need to be handled specially)
//
// checking condition
- // 1) no pending VmWork job
- // 2) on hostId host and host is UP
+ // 1) no pending VmWork job
+ // 2) on hostId host and host is UP
//
// When host is UP, soon or later we will get a report from the host about the VM,
// however, if VM is missing from the host report (it may happen in out of band changes
@@ -3974,17 +3993,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
// We now only alert administrator about this situation
_alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(),
- VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") is stuck in " + vm.getState() +
- " state and its host is unreachable for too long");
+ VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") is stuck in " + vm.getState()
+ + " state and its host is unreachable for too long");
}
}
// VMs that in transitional state without recent power state report
private List listStalledVMInTransitionStateOnUpHost(long hostId, Date cutTime) {
String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status = 'UP' " +
- "AND h.id = ? AND i.power_state_update_time < ? AND i.host_id = h.id " +
- "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " +
- "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)";
+ "AND h.id = ? AND i.power_state_update_time < ? AND i.host_id = h.id " +
+ "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " +
+ "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)";
List l = new ArrayList();
TransactionLegacy txn = null;
@@ -4016,9 +4035,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
// VMs that in transitional state and recently have power state update
private List listVMInTransitionStateWithRecentReportOnUpHost(long hostId, Date cutTime) {
String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status = 'UP' " +
- "AND h.id = ? AND i.power_state_update_time > ? AND i.host_id = h.id " +
- "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " +
- "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)";
+ "AND h.id = ? AND i.power_state_update_time > ? AND i.host_id = h.id " +
+ "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " +
+ "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)";
List l = new ArrayList();
TransactionLegacy txn = null;
@@ -4047,9 +4066,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
private List listStalledVMInTransitionStateOnDisconnectedHosts(Date cutTime) {
String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status != 'UP' " +
- "AND i.power_state_update_time < ? AND i.host_id = h.id " +
- "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " +
- "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)";
+ "AND i.power_state_update_time < ? AND i.host_id = h.id " +
+ "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " +
+ "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)";
List l = new ArrayList();
TransactionLegacy txn = null;
@@ -4101,10 +4120,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
}
- public class VmJobSyncOutcome extends OutcomeImpl {
+ public class VmJobVirtualMachineOutcome extends OutcomeImpl {
private long _vmId;
- public VmJobSyncOutcome(final AsyncJob job, final long vmId) {
+ public VmJobVirtualMachineOutcome(final AsyncJob job, final long vmId) {
super(VirtualMachine.class, job, VmJobCheckInterval.value(), new Predicate() {
@Override
public boolean checkCondition() {
@@ -4125,27 +4144,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
}
- public Throwable retriveExecutionException(AsyncJob job) {
- assert (job != null);
- assert (job.getDispatcher().equals(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER));
-
- AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId());
- if (jobVo != null && jobVo.getResult() != null) {
- Object obj = JobSerializerHelper.fromSerializedString(job.getResult());
-
- if (obj != null && obj instanceof Throwable)
- return (Throwable)obj;
- }
- return null;
- }
-
//
// TODO build a common pattern to reduce code duplication in following methods
// no time for this at current iteration
//
public Outcome startVmThroughJobQueue(final String vmUuid,
- final Map params,
- final DeploymentPlan planToDeploy) {
+ final Map params,
+ final DeploymentPlan planToDeploy) {
final CallContext context = CallContext.current();
final User callingUser = context.getCallingUser();
@@ -4153,14 +4158,14 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
- Transaction.execute(new TransactionCallbackNoReturn() {
+ Object[] result = Transaction.execute(new TransactionCallback