diff --git a/.gitignore b/.gitignore index dab1b3fc0b9..f50f2e3c9e6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -G# Licensed to the Apache Software Foundation (ASF) under one +# 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 diff --git a/agent/src/com/cloud/agent/AgentShell.java b/agent/src/com/cloud/agent/AgentShell.java index 936e3cd7a27..87004f9a1e4 100644 --- a/agent/src/com/cloud/agent/AgentShell.java +++ b/agent/src/com/cloud/agent/AgentShell.java @@ -167,7 +167,8 @@ public class AgentShell implements IAgentShell, Daemon { void loadProperties() throws ConfigurationException { final File file = PropertiesUtil.findConfigFile("agent.properties"); - if (file == null) { + + if (null == file) { throw new ConfigurationException("Unable to find agent.properties."); } @@ -303,12 +304,17 @@ public class AgentShell implements IAgentShell, Daemon { // For KVM agent, do it specially here File file = new File("/etc/cloudstack/agent/log4j-cloud.xml"); - if (!file.exists()) { + if(!file.exists()) { file = PropertiesUtil.findConfigFile("log4j-cloud.xml"); } - DOMConfigurator.configureAndWatch(file.getAbsolutePath()); - s_logger.info("Agent started"); + if (null != file) { + DOMConfigurator.configureAndWatch(file.getAbsolutePath()); + + s_logger.info("Agent started"); + } else { + s_logger.error("Could not start the Agent because the absolut path of the \"log4j-cloud.xml\" file cannot be determined."); + } final Class c = this.getClass(); _version = c.getPackage().getImplementationVersion(); diff --git a/api/src/com/cloud/alert/Alert.java b/api/src/com/cloud/alert/Alert.java index d835bf84499..6555b6fded1 100644 --- a/api/src/com/cloud/alert/Alert.java +++ b/api/src/com/cloud/alert/Alert.java @@ -39,4 +39,5 @@ public interface Alert extends Identity, InternalIdentity { Date getResolved(); boolean getArchived(); + String getName(); } diff --git a/api/src/com/cloud/event/EventTypes.java b/api/src/com/cloud/event/EventTypes.java index 0554d7aa704..d3c29e93028 100755 --- a/api/src/com/cloud/event/EventTypes.java +++ b/api/src/com/cloud/event/EventTypes.java @@ -398,6 +398,8 @@ public class EventTypes { public static final String EVENT_EXTERNAL_NVP_CONTROLLER_ADD = "PHYSICAL.NVPCONTROLLER.ADD"; public static final String EVENT_EXTERNAL_NVP_CONTROLLER_DELETE = "PHYSICAL.NVPCONTROLLER.DELETE"; public static final String EVENT_EXTERNAL_NVP_CONTROLLER_CONFIGURE = "PHYSICAL.NVPCONTROLLER.CONFIGURE"; + public static final String EVENT_EXTERNAL_OVS_CONTROLLER_ADD = "PHYSICAL.OVSCONTROLLER.ADD"; + public static final String EVENT_EXTERNAL_OVS_CONTROLLER_DELETE = "PHYSICAL.OVSCONTROLLER.DELETE"; // AutoScale public static final String EVENT_COUNTER_CREATE = "COUNTER.CREATE"; @@ -450,6 +452,10 @@ public class EventTypes { // Object store migration public static final String EVENT_MIGRATE_PREPARE_SECONDARY_STORAGE = "MIGRATE.PREPARE.SS"; + //Alert generation + public static final String ALERT_GENERATE = "ALERT.GENERATE"; + + static { // TODO: need a way to force author adding event types to declare the entity details as well, with out braking diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index bb94f81cc3c..d19c999f16e 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -126,6 +126,8 @@ public interface Network extends ControlledEntity, StateObject, I public static final Provider NiciraNvp = new Provider("NiciraNvp", false); public static final Provider InternalLbVm = new Provider("InternalLbVm", false); public static final Provider CiscoVnmc = new Provider("CiscoVnmc", true); + // add new Ovs provider + public static final Provider Ovs = new Provider("Ovs", false); private final String name; private final boolean isExternal; diff --git a/api/src/com/cloud/network/OvsProvider.java b/api/src/com/cloud/network/OvsProvider.java new file mode 100644 index 00000000000..c9937282bef --- /dev/null +++ b/api/src/com/cloud/network/OvsProvider.java @@ -0,0 +1,10 @@ +package com.cloud.network; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface OvsProvider extends InternalIdentity, Identity { + public boolean isEnabled(); + + public long getNspId(); +} diff --git a/api/src/com/cloud/network/element/VirtualRouterElementService.java b/api/src/com/cloud/network/element/VirtualRouterElementService.java index e929d14ae50..c8d45cafe53 100644 --- a/api/src/com/cloud/network/element/VirtualRouterElementService.java +++ b/api/src/com/cloud/network/element/VirtualRouterElementService.java @@ -18,9 +18,12 @@ package com.cloud.network.element; import java.util.List; +import org.apache.cloudstack.api.command.admin.router.ConfigureOvsElementCmd; import org.apache.cloudstack.api.command.admin.router.ConfigureVirtualRouterElementCmd; +import org.apache.cloudstack.api.command.admin.router.ListOvsElementsCmd; import org.apache.cloudstack.api.command.admin.router.ListVirtualRouterElementsCmd; +import com.cloud.network.OvsProvider; import com.cloud.network.VirtualRouterProvider; import com.cloud.network.VirtualRouterProvider.Type; import com.cloud.utils.component.PluggableService; @@ -28,9 +31,12 @@ import com.cloud.utils.component.PluggableService; public interface VirtualRouterElementService extends PluggableService { VirtualRouterProvider configure(ConfigureVirtualRouterElementCmd cmd); + OvsProvider configure(ConfigureOvsElementCmd cmd); VirtualRouterProvider addElement(Long nspId, Type providerType); VirtualRouterProvider getCreatedElement(long id); List searchForVirtualRouterElement(ListVirtualRouterElementsCmd cmd); + + List searchForOvsElement(ListOvsElementsCmd cmd); } diff --git a/api/src/com/cloud/network/lb/LoadBalancingRule.java b/api/src/com/cloud/network/lb/LoadBalancingRule.java index 4b2f9c4237b..be69332ea78 100644 --- a/api/src/com/cloud/network/lb/LoadBalancingRule.java +++ b/api/src/com/cloud/network/lb/LoadBalancingRule.java @@ -437,13 +437,15 @@ public class LoadBalancingRule { private String key; private String password = null; private String chain = null; + private String fingerprint; private boolean revoked; - public LbSslCert(String cert, String key, String password, String chain, boolean revoked) { + public LbSslCert(String cert, String key, String password, String chain, String fingerprint, boolean revoked) { this.cert = cert; this.key = key; this.password = password; this.chain = chain; + this.fingerprint = fingerprint; this.revoked = revoked; } @@ -464,6 +466,10 @@ public class LoadBalancingRule { return chain; } + public String getFingerprint() { + return fingerprint; + } + public boolean isRevoked() { return revoked; } diff --git a/api/src/com/cloud/network/vpc/NetworkACLService.java b/api/src/com/cloud/network/vpc/NetworkACLService.java index 56a21804ea5..db37833e4f0 100644 --- a/api/src/com/cloud/network/vpc/NetworkACLService.java +++ b/api/src/com/cloud/network/vpc/NetworkACLService.java @@ -19,6 +19,7 @@ package com.cloud.network.vpc; import java.util.List; import org.apache.cloudstack.api.command.user.network.CreateNetworkACLCmd; +import org.apache.cloudstack.api.command.user.network.ListNetworkACLListsCmd; import org.apache.cloudstack.api.command.user.network.ListNetworkACLsCmd; import com.cloud.exception.ResourceUnavailableException; @@ -43,13 +44,10 @@ public interface NetworkACLService { /** * List NetworkACLs by Id/Name/Network or Vpc it belongs to - * @param id - * @param name - * @param networkId - * @param vpcId + * @param cmd * @return */ - Pair, Integer> listNetworkACLs(Long id, String name, Long networkId, Long vpcId); + Pair,Integer> listNetworkACLs(ListNetworkACLListsCmd cmd); /** * Delete specified network ACL. Deletion fails if the list is not empty diff --git a/api/src/com/cloud/server/ResourceTag.java b/api/src/com/cloud/server/ResourceTag.java index 000808d9f36..6d18834c6b5 100644 --- a/api/src/com/cloud/server/ResourceTag.java +++ b/api/src/com/cloud/server/ResourceTag.java @@ -22,15 +22,31 @@ import org.apache.cloudstack.api.InternalIdentity; public interface ResourceTag extends ControlledEntity, Identity, InternalIdentity { - //FIXME - extract enum to another interface as its used both by resourceTags and resourceMetaData code + // 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, - false), NetworkACL(true, false), StaticRoute(true, false), VMSnapshot(true, false), RemoteAccessVpn(true, true), Zone(false, true), ServiceOffering( - false, - true), Storage(false, true); + 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); ResourceObjectType(boolean resourceTagsSupport, boolean resourceMetadataSupport) { this.resourceTagsSupport = resourceTagsSupport; diff --git a/api/src/com/cloud/storage/VolumeApiService.java b/api/src/com/cloud/storage/VolumeApiService.java index 47afa104b4d..db23c1be227 100644 --- a/api/src/com/cloud/storage/VolumeApiService.java +++ b/api/src/com/cloud/storage/VolumeApiService.java @@ -87,7 +87,7 @@ public interface VolumeApiService { Snapshot allocSnapshot(Long volumeId, Long policyId) throws ResourceAllocationException; - Volume updateVolume(long volumeId, String path, String state, Long storageId, Boolean displayVolume); + Volume updateVolume(long volumeId, String path, String state, Long storageId, Boolean displayVolume, String customId, long owner); /** * Extracts the volume to a particular location. diff --git a/api/src/com/cloud/user/ResourceLimitService.java b/api/src/com/cloud/user/ResourceLimitService.java index bec65d5b7e8..f8923b708a9 100644 --- a/api/src/com/cloud/user/ResourceLimitService.java +++ b/api/src/com/cloud/user/ResourceLimitService.java @@ -139,4 +139,40 @@ 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 + * + * @param account + * @param type + * @param displayResource + * @param count + * the number of resources being allocated, count will be added to current allocation and compared + * against maximum allowed allocation + * @throws ResourceAllocationException + */ + void checkResourceLimit(Account account, ResourceType type, Boolean displayResource, long... count) throws ResourceAllocationException; + + + /** + * Increments the resource count depending on the displayResource flag + * + * @param accountId + * @param type + * @param displayResource + * @param delta + */ + void incrementResourceCount(long accountId, ResourceType type, Boolean displayResource, Long... delta); + + /** + * Increments/Decrements the resource count depending on the displayResource flag + * + * @param accountId + * @param type + * @param displayResource + * @param delta + */ + void changeResourceCount(long accountId, ResourceType type, Boolean displayResource, Long... delta); + + void decrementResourceCount(long accountId, ResourceType type, Boolean displayResource, Long... delta); } diff --git a/api/src/com/cloud/vm/UserVmService.java b/api/src/com/cloud/vm/UserVmService.java index 444c47ab96c..5306bf92e57 100755 --- a/api/src/com/cloud/vm/UserVmService.java +++ b/api/src/com/cloud/vm/UserVmService.java @@ -137,6 +137,7 @@ public interface UserVmService { * caller. * * + * * @param zone * - availability zone for the virtual machine * @param serviceOffering @@ -182,15 +183,10 @@ public interface UserVmService { * @param displayVm * - Boolean flag whether to the display the vm to the end user or not * @param affinityGroupIdList - * @param accountName - * - an optional account for the virtual machine. Must be used - * with domainId - * @param domainId - * - an optional domainId for the virtual machine. If the account - * parameter is used, domainId must also be used * @param cpuSpeed * @param memory * @param cpuNumber + * @param customId * @return UserVm object if successful. * * @throws InsufficientCapacityException @@ -204,9 +200,9 @@ public interface UserVmService { * @throws InsufficientResourcesException */ UserVm createBasicSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List securityGroupIdList, - Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, HTTPMethod httpmethod, - String userData, String sshKeyPair, Map requestedIps, IpAddresses defaultIp, Boolean displayVm, String keyboard, - List affinityGroupIdList, Integer cpuSpeed, Integer memory, Integer cpuNumber, Long rootdisksize) throws InsufficientCapacityException, + Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, HTTPMethod httpmethod, + String userData, String sshKeyPair, Map requestedIps, IpAddresses defaultIp, Boolean displayVm, String keyboard, + List affinityGroupIdList, Map customParameter, String customId) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; /** @@ -214,6 +210,7 @@ public interface UserVmService { * the database and returns the VM to the caller. * * + * * @param zone * - availability zone for the virtual machine * @param serviceOffering @@ -261,15 +258,9 @@ public interface UserVmService { * @param displayVm * - Boolean flag whether to the display the vm to the end user or not * @param affinityGroupIdList - * @param accountName - * - an optional account for the virtual machine. Must be used - * with domainId - * @param domainId - * - an optional domainId for the virtual machine. If the account - * parameter is used, domainId must also be used - * @param CpuSpeed * @param memory * @param cpuNumber + * @param customId * @return UserVm object if successful. * * @throws InsufficientCapacityException @@ -283,9 +274,9 @@ public interface UserVmService { * @throws InsufficientResourcesException */ UserVm createAdvancedSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List networkIdList, - List securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, - HTTPMethod httpmethod, String userData, String sshKeyPair, Map requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, - List affinityGroupIdList, Integer cpuSpeed, Integer memory, Integer cpuNumber, Long rootdisksize) throws InsufficientCapacityException, + List securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, + HTTPMethod httpmethod, String userData, String sshKeyPair, Map requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, + List affinityGroupIdList, Map customParameters, String customId) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; /** @@ -293,6 +284,7 @@ public interface UserVmService { * in the database and returns the VM to the caller. * * + * * @param zone * - availability zone for the virtual machine * @param serviceOffering @@ -337,15 +329,10 @@ public interface UserVmService { * @param displayVm * - Boolean flag whether to the display the vm to the end user or not * @param affinityGroupIdList - * @param accountName - * - an optional account for the virtual machine. Must be used - * with domainId - * @param domainId - * - an optional domainId for the virtual machine. If the account - * parameter is used, domainId must also be used * @param cpuSpeed * @param memory * @param cpuNumber + * @param customId * @return UserVm object if successful. * * @throws InsufficientCapacityException @@ -359,9 +346,9 @@ public interface UserVmService { * @throws InsufficientResourcesException */ UserVm createAdvancedVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List networkIdList, Account owner, - String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData, - String sshKeyPair, Map requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, List affinityGroupIdList, - Integer cpuSpeed, Integer memory, Integer cpuNumber, Long rootdkisksize) + String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData, + String sshKeyPair, Map requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, List affinityGroupIdList, + Map customParameters, String customId) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; diff --git a/api/src/org/apache/cloudstack/alert/AlertService.java b/api/src/org/apache/cloudstack/alert/AlertService.java new file mode 100644 index 00000000000..2143fe8d23f --- /dev/null +++ b/api/src/org/apache/cloudstack/alert/AlertService.java @@ -0,0 +1,103 @@ + +// 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.alert; + +import java.util.HashSet; +import java.util.Set; + +import com.cloud.capacity.Capacity; +import com.cloud.exception.InvalidParameterValueException; + +public interface AlertService { + public static class AlertType { + private static Set defaultAlertTypes = new HashSet(); + private final String name; + private final short type; + + private AlertType(short type, String name, boolean isDefault) { + this.name = name; + this.type = type; + if (isDefault) { + defaultAlertTypes.add(this); + } + } + + public static final AlertType ALERT_TYPE_MEMORY = new AlertType(Capacity.CAPACITY_TYPE_MEMORY, "ALERT.MEMORY", true); + public static final AlertType ALERT_TYPE_CPU = new AlertType(Capacity.CAPACITY_TYPE_CPU, "ALERT.CPU", true); + public static final AlertType ALERT_TYPE_STORAGE = new AlertType(Capacity.CAPACITY_TYPE_STORAGE, "ALERT.STORAGE", true); + public static final AlertType ALERT_TYPE_STORAGE_ALLOCATED = new AlertType(Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED, "ALERT.STORAGE.ALLOCATED", true); + public static final AlertType ALERT_TYPE_VIRTUAL_NETWORK_PUBLIC_IP = new AlertType(Capacity.CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP, "ALERT.NETWORK.PUBLICIP", true); + public static final AlertType ALERT_TYPE_PRIVATE_IP = new AlertType(Capacity.CAPACITY_TYPE_PRIVATE_IP, "ALERT.NETWORK.PRIVATEIP", true); + public static final AlertType ALERT_TYPE_SECONDARY_STORAGE = new AlertType(Capacity.CAPACITY_TYPE_SECONDARY_STORAGE, "ALERT.STORAGE.SECONDARY", true); + public static final AlertType ALERT_TYPE_HOST = new AlertType((short)7, "ALERT.COMPUTE.HOST", true); + public static final AlertType ALERT_TYPE_USERVM = new AlertType((short)8, "ALERT.USERVM", true); + public static final AlertType ALERT_TYPE_DOMAIN_ROUTER = new AlertType((short)9, "ALERT.SERVICE.DOMAINROUTER", true); + public static final AlertType ALERT_TYPE_CONSOLE_PROXY = new AlertType((short)10, "ALERT.SERVICE.CONSOLEPROXY", true); + public static final AlertType ALERT_TYPE_ROUTING = new AlertType((short)11, "ALERT.NETWORK.ROUTING", true); + public static final AlertType ALERT_TYPE_STORAGE_MISC = new AlertType((short)12, "ALERT.STORAGE.MISC", true); + public static final AlertType ALERT_TYPE_USAGE_SERVER = new AlertType((short)13, "ALERT.USAGE", true); + public static final AlertType ALERT_TYPE_MANAGMENT_NODE = new AlertType((short)14, "ALERT.MANAGEMENT", true); + public static final AlertType ALERT_TYPE_DOMAIN_ROUTER_MIGRATE = new AlertType((short)15, "ALERT.NETWORK.DOMAINROUTERMIGRATE", true); + public static final AlertType ALERT_TYPE_CONSOLE_PROXY_MIGRATE = new AlertType((short)16, "ALERT.SERVICE.CONSOLEPROXYMIGRATE", true); + public static final AlertType ALERT_TYPE_USERVM_MIGRATE = new AlertType((short)17, "ALERT.USERVM.MIGRATE", true); + public static final AlertType ALERT_TYPE_VLAN = new AlertType((short)18, "ALERT.NETWORK.VLAN", true); + public static final AlertType ALERT_TYPE_SSVM = new AlertType((short)19, "ALERT.SERVICE.SSVM", true); + public static final AlertType ALERT_TYPE_USAGE_SERVER_RESULT = new AlertType((short)20, "ALERT.USAGE.RESULT", true); + public static final AlertType ALERT_TYPE_STORAGE_DELETE = new AlertType((short)21, "ALERT.STORAGE.DELETE", true); + public static final AlertType ALERT_TYPE_UPDATE_RESOURCE_COUNT = new AlertType((short)22, "ALERT.RESOURCE.COUNT", true); + public static final AlertType ALERT_TYPE_USAGE_SANITY_RESULT = new AlertType((short)23, "ALERT.USAGE.SANITY", true); + public static final AlertType ALERT_TYPE_DIRECT_ATTACHED_PUBLIC_IP = new AlertType((short)24, "ALERT.NETWORK.DIRECTPUBLICIP", true); + public static final AlertType ALERT_TYPE_LOCAL_STORAGE = new AlertType((short)25, "ALERT.STORAGE.LOCAL", true); + public static final AlertType ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED = new AlertType((short)26, "ALERT.RESOURCE.EXCEED", true); + public static final AlertType ALERT_TYPE_SYNC = new AlertType((short)27, "ALERT.TYPE.SYNC", true); + + public short getType() { + return type; + } + + public String getName() { + return name; + } + + private static AlertType getAlertType(short type) { + for (AlertType alertType : defaultAlertTypes) { + if (alertType.getType() == type) { + return alertType; + } + } + return null; + } + + @Override + public String toString() { + return String.valueOf(this.getType()); + } + + public static AlertType generateAlert(short type, String name) { + AlertType defaultAlert = getAlertType(type); + if (defaultAlert != null && !defaultAlert.getName().equalsIgnoreCase(name)) { + throw new InvalidParameterValueException("There is a default alert having type " + type + " and name " + defaultAlert.getName()); + } else { + return new AlertType(type, name, false); + } + } + } + + boolean generateAlert(AlertType alertType, long dataCenterId, Long podId, String msg); + +} diff --git a/api/src/org/apache/cloudstack/api/ApiConstants.java b/api/src/org/apache/cloudstack/api/ApiConstants.java index 523bb6024db..745a722bfa4 100755 --- a/api/src/org/apache/cloudstack/api/ApiConstants.java +++ b/api/src/org/apache/cloudstack/api/ApiConstants.java @@ -54,6 +54,7 @@ public class ApiConstants { public static final String CREATED = "created"; public static final String CUSTOMIZED = "customized"; public static final String CUSTOMIZED_IOPS = "customizediops"; + public static final String CUSTOM_ID = "customid"; public static final String MIN_IOPS = "miniops"; public static final String MAX_IOPS = "maxiops"; public static final String HYPERVISOR_SNAPSHOT_RESERVE = "hypervisorsnapshotreserve"; @@ -71,6 +72,7 @@ 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"; @@ -407,10 +409,20 @@ public class ApiConstants { public static final String VSWITCH_TYPE_PUBLIC_TRAFFIC = "publicvswitchtype"; public static final String VSWITCH_NAME_GUEST_TRAFFIC = "guestvswitchname"; public static final String VSWITCH_NAME_PUBLIC_TRAFFIC = "publicvswitchname"; + // Ovs controller + public static final String OVS_DEVICE_ID = "ovsdeviceid"; + public static final String OVS_DEVICE_NAME = "ovsdevicename"; + // OpenDaylight controller + public static final String ODL_DEVICE_ID = "odldeviceid"; + public static final String ODL_DEVICE_NAME = "odldevicename"; + public static final String ODL_TRANSPORT_ZONE_UUID = "transportzoneuuid"; + public static final String ODL_GATEWAYSERVICE_UUID = "l3gatewayserviceuuid"; + public static final String EXTERNAL_SWITCH_MGMT_DEVICE_ID = "vsmdeviceid"; public static final String EXTERNAL_SWITCH_MGMT_DEVICE_NAME = "vsmdevicename"; public static final String EXTERNAL_SWITCH_MGMT_DEVICE_STATE = "vsmdevicestate"; - // Would we need to have a capacity field for Cisco N1KV VSM? Max hosts managed by it perhaps? May remove this later. + // Would we need to have a capacity field for Cisco N1KV VSM? Max hosts managed by it perhaps? May remove this +// later. public static final String EXTERNAL_SWITCH_MGMT_DEVICE_CAPACITY = "vsmdevicecapacity"; public static final String CISCO_NEXUS_VSM_NAME = "vsmname"; public static final String VSM_USERNAME = "vsmusername"; @@ -534,6 +546,7 @@ public class ApiConstants { public static final String FOR_DISPLAY = "fordisplay"; public static final String PASSIVE = "passive"; public static final String VERSION = "version"; + public static final String START = "start"; public enum HostDetails { all, capacity, events, stats, min; diff --git a/api/src/org/apache/cloudstack/api/BaseAsyncCreateCustomIdCmd.java b/api/src/org/apache/cloudstack/api/BaseAsyncCreateCustomIdCmd.java new file mode 100644 index 00000000000..0f75653e35d --- /dev/null +++ b/api/src/org/apache/cloudstack/api/BaseAsyncCreateCustomIdCmd.java @@ -0,0 +1,27 @@ +// 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; + + +public abstract class BaseAsyncCreateCustomIdCmd extends BaseAsyncCreateCmd{ + @Parameter(name=ApiConstants.CUSTOM_ID, type=CommandType.STRING, description="an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only") + private String customId; + + public String getCustomId() { + return customId; + } +} diff --git a/api/src/org/apache/cloudstack/api/BaseAsyncCustomIdCmd.java b/api/src/org/apache/cloudstack/api/BaseAsyncCustomIdCmd.java new file mode 100644 index 00000000000..95be24f5483 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/BaseAsyncCustomIdCmd.java @@ -0,0 +1,27 @@ +// 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; + + +public abstract class BaseAsyncCustomIdCmd extends BaseAsyncCmd { + @Parameter(name=ApiConstants.CUSTOM_ID, type=CommandType.STRING, description="an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only") + private String customId; + + public String getCustomId() { + return customId; + } +} diff --git a/api/src/org/apache/cloudstack/api/BaseCmd.java b/api/src/org/apache/cloudstack/api/BaseCmd.java index b060f43a022..86a7c726d6c 100644 --- a/api/src/org/apache/cloudstack/api/BaseCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseCmd.java @@ -26,14 +26,14 @@ import java.util.regex.Pattern; import javax.inject.Inject; -import org.apache.log4j.Logger; - import org.apache.cloudstack.affinity.AffinityGroupService; +import org.apache.cloudstack.alert.AlertService; import org.apache.cloudstack.network.element.InternalLoadBalancerElementService; import org.apache.cloudstack.network.lb.ApplicationLoadBalancerService; import org.apache.cloudstack.network.lb.InternalLoadBalancerVMService; import org.apache.cloudstack.query.QueryService; import org.apache.cloudstack.usage.UsageService; +import org.apache.log4j.Logger; import com.cloud.configuration.ConfigurationService; import com.cloud.domain.Domain; @@ -191,9 +191,12 @@ public abstract class BaseCmd { public InternalLoadBalancerVMService _internalLbSvc; @Inject public NetworkModel _ntwkModel; - + @Inject + public AlertService _alertSvc; + public abstract void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException, NetworkRuleConflictException; + ResourceAllocationException, NetworkRuleConflictException; + public void configure() { } diff --git a/api/src/org/apache/cloudstack/api/BaseCustomIdCmd.java b/api/src/org/apache/cloudstack/api/BaseCustomIdCmd.java new file mode 100644 index 00000000000..df59b44a56a --- /dev/null +++ b/api/src/org/apache/cloudstack/api/BaseCustomIdCmd.java @@ -0,0 +1,27 @@ +// 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; + +public abstract class BaseCustomIdCmd extends BaseCmd { + + @Parameter(name=ApiConstants.CUSTOM_ID, type=CommandType.STRING, description="an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only") + private String customId; + + public String getCustomId() { + return customId; + } +} diff --git a/api/src/org/apache/cloudstack/api/ResponseGenerator.java b/api/src/org/apache/cloudstack/api/ResponseGenerator.java index 2d37b6a188b..e7a1b350632 100644 --- a/api/src/org/apache/cloudstack/api/ResponseGenerator.java +++ b/api/src/org/apache/cloudstack/api/ResponseGenerator.java @@ -67,6 +67,7 @@ import org.apache.cloudstack.api.response.NetworkOfferingResponse; import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.api.response.NicResponse; import org.apache.cloudstack.api.response.NicSecondaryIpResponse; +import org.apache.cloudstack.api.response.OvsProviderResponse; import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.cloudstack.api.response.PodResponse; import org.apache.cloudstack.api.response.PortableIpRangeResponse; @@ -134,6 +135,7 @@ import com.cloud.network.IpAddress; import com.cloud.network.Network; import com.cloud.network.Network.Service; import com.cloud.network.Networks.IsolationType; +import com.cloud.network.OvsProvider; import com.cloud.network.PhysicalNetwork; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.PhysicalNetworkTrafficType; @@ -353,6 +355,8 @@ public interface ResponseGenerator { VirtualRouterProviderResponse createVirtualRouterProviderResponse(VirtualRouterProvider result); + OvsProviderResponse createOvsProviderResponse(OvsProvider result); + StorageNetworkIpRangeResponse createStorageNetworkIpRangeResponse(StorageNetworkIpRange result); RegionResponse createRegionResponse(Region region); diff --git a/api/src/org/apache/cloudstack/api/command/admin/alert/GenerateAlertCmd.java b/api/src/org/apache/cloudstack/api/command/admin/alert/GenerateAlertCmd.java new file mode 100644 index 00000000000..b23a3be9dea --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/alert/GenerateAlertCmd.java @@ -0,0 +1,123 @@ +// 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.alert; + +import org.apache.cloudstack.alert.AlertService; +import org.apache.cloudstack.alert.AlertService.AlertType; +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.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.log4j.Logger; + +import com.cloud.event.EventTypes; + +@APICommand(name = "generateAlert", description = "Generates an alert", responseObject = SuccessResponse.class, since="4.3") +public class GenerateAlertCmd extends BaseAsyncCmd { + + public static final Logger s_logger = Logger.getLogger(GenerateAlertCmd.class.getName()); + + private static final String s_name = "generatealertresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.TYPE, type = CommandType.SHORT, description = "Type of the alert", required=true) + private Short type; + + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "Name of the alert", required=true) + private String name; + + @Parameter(name = ApiConstants.DESCRIPTION, type = CommandType.STRING, description = "Alert description", required=true) + private String description; + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, description="Zone id for which alert is generated") + private Long zoneId; + + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, description="Pod id for which alert is generated") + private Long podId; + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + @Override + public String getCommandName() { + return s_name; + } + + public Short getType() { + return type; + } + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } + + public long getZoneId() { + if (zoneId == null) { + return 0L; + } + return zoneId; + } + + public Long getPodId() { + return podId; + } + + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + + + @Override + public void execute() { + AlertType alertType = AlertService.AlertType.generateAlert(getType(), getName()); + if (_alertSvc.generateAlert(alertType, getZoneId(), getPodId(), getDescription())) { + SuccessResponse response = new SuccessResponse(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to generate an alert"); + } + } + + @Override + public String getEventType() { + return EventTypes.ALERT_GENERATE; + } + + @Override + public String getEventDescription() { + return "Generating alert of type " + type + "; name " + name; + } + + @Override + public long getEntityOwnerId() { + return 0; + } +} \ No newline at end of file diff --git a/api/src/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java index 90ab67ce9b1..2fc4084e0ab 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java @@ -19,14 +19,13 @@ package org.apache.cloudstack.api.command.admin.resource; 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.BaseListCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.AlertResponse; import org.apache.cloudstack.api.response.ListResponse; +import org.apache.log4j.Logger; import com.cloud.alert.Alert; import com.cloud.utils.Pair; @@ -47,6 +46,9 @@ public class ListAlertsCmd extends BaseListCmd { @Parameter(name = ApiConstants.TYPE, type = CommandType.STRING, description = "list by alert type") private String type; + + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "list by alert name", since="4.3") + private String name; // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// @@ -59,6 +61,10 @@ public class ListAlertsCmd extends BaseListCmd { public String getType() { return type; } + + public String getName() { + return name; + } // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// @@ -80,6 +86,7 @@ public class ListAlertsCmd extends BaseListCmd { alertResponse.setAlertType(alert.getType()); alertResponse.setDescription(alert.getSubject()); alertResponse.setLastSent(alert.getLastSent()); + alertResponse.setName(alert.getName()); alertResponse.setObjectName("alert"); alertResponseList.add(alertResponse); diff --git a/api/src/org/apache/cloudstack/api/command/admin/router/ConfigureOvsElementCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/ConfigureOvsElementCmd.java new file mode 100644 index 00000000000..a72dbefb32e --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/router/ConfigureOvsElementCmd.java @@ -0,0 +1,116 @@ +package org.apache.cloudstack.api.command.admin.router; + +import java.util.List; + +import javax.inject.Inject; + +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.OvsProviderResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.log4j.Logger; + +import com.cloud.event.EventTypes; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.OvsProvider; +import com.cloud.network.element.VirtualRouterElementService; +import com.cloud.user.Account; + +@APICommand(name = "configureOvsElement", responseObject = OvsProviderResponse.class, description = "Configures an ovs element.") +public class ConfigureOvsElementCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger + .getLogger(ConfigureOvsElementCmd.class.getName()); + private static final String s_name = "configureovselementresponse"; + @Inject + private List _service; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = OvsProviderResponse.class, required = true, description = "the ID of the ovs provider") + private Long id; + + @Parameter(name = ApiConstants.ENABLED, type = CommandType.BOOLEAN, required = true, description = "Enabled/Disabled the service provider") + private Boolean enabled; + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + public void setId(Long id) { + this.id = id; + } + + public Long getId() { + return id; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + public Boolean getEnabled() { + return enabled; + } + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + public static String getResultObjectName() { + return "boolean"; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_NETWORK_ELEMENT_CONFIGURE; + } + + @Override + public String getEventDescription() { + return "configuring ovs provider: " + id; + } + + @Override + public ApiCommandJobType getInstanceType() { + return ApiCommandJobType.None; + } + + @Override + public Long getInstanceId() { + return id; + } + + @Override + public void execute() throws ConcurrentOperationException, + ResourceUnavailableException, InsufficientCapacityException { + CallContext.current().setEventDetails("Ovs element: " + id); + OvsProvider result = _service.get(0).configure(this); + if (result != null) { + OvsProviderResponse ovsResponse = _responseGenerator + .createOvsProviderResponse(result); + ovsResponse.setResponseName(getCommandName()); + this.setResponseObject(ovsResponse); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, + "Failed to configure the ovs provider"); + } + } +} diff --git a/api/src/org/apache/cloudstack/api/command/admin/router/ListOvsElementsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/ListOvsElementsCmd.java new file mode 100644 index 00000000000..3e3ee635f48 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/router/ListOvsElementsCmd.java @@ -0,0 +1,91 @@ +package org.apache.cloudstack.api.command.admin.router; + +import java.util.ArrayList; +import java.util.List; + +import javax.inject.Inject; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.user.network.ListNetworkOfferingsCmd; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.OvsProviderResponse; +import org.apache.cloudstack.api.response.ProviderResponse; +import org.apache.log4j.Logger; + +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.OvsProvider; +import com.cloud.network.element.VirtualRouterElementService; + +@APICommand(name = "listOvsElements", description = "Lists all available ovs elements.", responseObject = OvsProviderResponse.class) +public class ListOvsElementsCmd extends BaseListCmd { + public static final Logger s_logger = Logger + .getLogger(ListNetworkOfferingsCmd.class.getName()); + private static final String _name = "listovselementsresponse"; + @Inject + private List _service; + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = OvsProviderResponse.class, description = "list ovs elements by id") + private Long id; + + @Parameter(name = ApiConstants.NSP_ID, type = CommandType.UUID, entityType = ProviderResponse.class, description = "list ovs elements by network service provider id") + private Long nspId; + + @Parameter(name = ApiConstants.ENABLED, type = CommandType.BOOLEAN, description = "list network offerings by enabled state") + private Boolean enabled; + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + public void setId(Long id) { + this.id = id; + } + + public Long getId() { + return id; + } + + public void setNspId(Long nspId) { + this.nspId = nspId; + } + + public Long getNspId() { + return nspId; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + public Boolean getEnabled() { + return enabled; + } + + @Override + public String getCommandName() { + return _name; + } + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException { + List providers = _service.get(0).searchForOvsElement(this); + ListResponse response = new ListResponse(); + List providerResponses = new ArrayList(); + for (OvsProvider provider : providers) { + OvsProviderResponse providerResponse = _responseGenerator.createOvsProviderResponse(provider); + providerResponses.add(providerResponse); + } + response.setResponses(providerResponses); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + + } +} 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 a7c864da53d..247df1eaed5 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 @@ -39,6 +39,11 @@ 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 " @@ -61,6 +66,11 @@ public class ScaleSystemVMCmd extends BaseAsyncCmd { 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; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -73,6 +83,21 @@ public class ScaleSystemVMCmd extends BaseAsyncCmd { return serviceOfferingId; } + public Map getCustomParameters() { + Map customparameterMap = new HashMap(); + if (customParameters != null && customParameters.size() != 0) { + Collection parameterCollection = customParameters.values(); + Iterator iter = parameterCollection.iterator(); + while (iter.hasNext()) { + HashMap value = (HashMap) iter.next(); + for (String key : value.keySet()) { + customparameterMap.put(key, value.get(key)); + } + } + } + return customparameterMap; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// 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 1357a7d8d63..a49828be89f 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 @@ -34,6 +34,11 @@ 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 " @@ -56,6 +61,11 @@ public class UpgradeSystemVMCmd extends BaseCmd { 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; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -68,6 +78,21 @@ public class UpgradeSystemVMCmd extends BaseCmd { return serviceOfferingId; } + public Map getCustomParameters() { + Map customparameterMap = new HashMap(); + if (customParameters != null && customParameters.size() !=0){ + Collection parameterCollection = customParameters.values(); + Iterator iter = parameterCollection.iterator(); + while (iter.hasNext()) { + HashMap value = (HashMap) iter.next(); + for (String key : value.keySet()) { + customparameterMap.put(key, value.get(key)); + } + } + } + return customparameterMap; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java b/api/src/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java index ccc5a89d11b..5c008148207 100644 --- a/api/src/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java @@ -54,6 +54,7 @@ public class ListCapabilitiesCmd extends BaseCmd { response.setAllowUsersCreateProjects((Boolean)capabilities.get("allowusercreateprojects")); response.setDiskOffMaxSize((Long)capabilities.get("customDiskOffMaxSize")); response.setRegionSecondaryEnabled((Boolean)capabilities.get("regionSecondaryEnabled")); + response.setKVMSnapshotEnabled((Boolean)capabilities.get("KVMSnapshotEnabled")); if (capabilities.containsKey("apiLimitInterval")) { response.setApiLimitInterval((Integer)capabilities.get("apiLimitInterval")); } diff --git a/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLListsCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLListsCmd.java index 6dd59659116..56aad945101 100644 --- a/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLListsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLListsCmd.java @@ -24,6 +24,7 @@ import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.NetworkACLResponse; @@ -33,8 +34,8 @@ import org.apache.cloudstack.api.response.VpcResponse; import com.cloud.network.vpc.NetworkACL; import com.cloud.utils.Pair; -@APICommand(name = "listNetworkACLLists", description = "Lists all network ACLs", responseObject = NetworkACLResponse.class) -public class ListNetworkACLListsCmd extends BaseListCmd { +@APICommand(name = "listNetworkACLLists", description="Lists all network ACLs", responseObject=NetworkACLResponse.class) +public class ListNetworkACLListsCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListNetworkACLListsCmd.class.getName()); private static final String s_name = "listnetworkacllistsresponse"; @@ -84,8 +85,8 @@ public class ListNetworkACLListsCmd extends BaseListCmd { } @Override - public void execute() { - Pair, Integer> result = _networkACLService.listNetworkACLs(getId(), getName(), getNetworkId(), getVpcId()); + public void execute(){ + Pair,Integer> result = _networkACLService.listNetworkACLs(this); ListResponse response = new ListResponse(); List aclResponses = new ArrayList(); diff --git a/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java index 0aa319a6bfe..99c620ca14d 100644 --- a/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java @@ -43,7 +43,8 @@ public class ListNetworkACLsCmd extends BaseListTaggedResourcesCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, description = "Lists network ACL Item with the specified ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkACLItemResponse.class, + description="Lists network ACL Item with the specified ID") private Long id; @Parameter(name = ApiConstants.NETWORK_ID, type = CommandType.UUID, entityType = NetworkResponse.class, description = "list network ACL Items by network Id") 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 7180f4ea3d5..fee6db25c87 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,6 +24,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import org.apache.cloudstack.api.BaseAsyncCreateCustomIdCmd; import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; @@ -69,7 +70,7 @@ 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) -public class DeployVMCmd extends BaseAsyncCreateCmd { +public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd { public static final Logger s_logger = Logger.getLogger(DeployVMCmd.class.getName()); private static final String s_name = "deployvirtualmachineresponse"; @@ -229,29 +230,11 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { description = "an optional field, whether to the display the vm to the end user or not.") private Boolean displayVm; - @Parameter(name = ApiConstants.CPU_SPEED, - type = CommandType.INTEGER, - since = "4.3", - description = "optional field to specify the cpu speed when using dynamic compute offering.") - private Integer cpuSpeed; - - @Parameter(name = ApiConstants.MEMORY, - type = CommandType.INTEGER, - since = "4.3", - description = "optional field to specify the memory when using dynamic compute offering") - private Integer memory; - - @Parameter(name = ApiConstants.CPU_NUMBER, - type = CommandType.INTEGER, - since = "4.3", - description = "optional field to specify the number of cpu cores when using dynamic offering.") - private Integer cpuNumber; - - @Parameter(name = ApiConstants.ROOT_DISK_SIZE, - type = CommandType.LONG, - since = "4.3", - description = "optional field to specify the number of cpu cores when using dynamic offering.") - private Long rootdisksize; + @Parameter(name = ApiConstants.CUSTOM_PARAMETERS, + type = CommandType.MAP, + since= "4.3", + description = "used to specify the custom parameters.") + private Map customParameters; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -279,6 +262,21 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { return domainId; } + public Map getCustomParameters() { + Map customparameterMap = new HashMap(); + if (customParameters != null && customParameters.size() !=0){ + Collection parameterCollection = customParameters.values(); + Iterator iter = parameterCollection.iterator(); + while (iter.hasNext()) { + HashMap value = (HashMap) iter.next(); + for (String key : value.keySet()) { + customparameterMap.put(key, value.get(key)); + } + } + } + return customparameterMap; + } + public String getGroup() { return group; } @@ -291,21 +289,6 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { return displayVm; } - public Integer getMemory() { - return memory; - } - - public Integer getCpuSpeed() { - return cpuSpeed; - } - - public Integer getCpuNumber() { - return cpuNumber; - } - - public Long getRootdisksize() { - return rootdisksize; - } public List getSecurityGroupIdList() { if (securityGroupNameList != null && securityGroupIdList != null) { @@ -576,14 +559,14 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { vm = _userVmService.createBasicSecurityGroupVirtualMachine(zone, serviceOffering, template, getSecurityGroupIdList(), owner, name, displayName, diskOfferingId, size, group, getHypervisor(), getHttpMethod(), userData, sshKeyPairName, getIpToNetworkMap(), addrs, displayVm, keyboard, - getAffinityGroupIdList(), cpuSpeed, memory, cpuNumber, rootdisksize); + getAffinityGroupIdList(), getCustomParameters(), 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(), cpuSpeed, memory, cpuNumber, rootdisksize); + keyboard, getAffinityGroupIdList(), getCustomParameters(), getCustomId()); } else { if (getSecurityGroupIdList() != null && !getSecurityGroupIdList().isEmpty()) { @@ -592,7 +575,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { vm = _userVmService.createAdvancedVirtualMachine(zone, serviceOffering, template, getNetworkIds(), owner, name, displayName, diskOfferingId, size, group, getHypervisor(), getHttpMethod(), userData, sshKeyPairName, getIpToNetworkMap(), addrs, displayVm, keyboard, getAffinityGroupIdList(), - cpuSpeed, memory, cpuNumber, rootdisksize); + getCustomParameters(), getCustomId()); } } 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 6cbb78b0dd2..9b86577f8e3 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 @@ -37,7 +37,7 @@ import com.cloud.network.Network; import com.cloud.user.Account; import com.cloud.vm.NicSecondaryIp; -@APICommand(name = "removeIpFromNic", description = "Assigns secondary IP to NIC.", responseObject = SuccessResponse.class) +@APICommand(name = "removeIpFromNic", description = "Removes secondary IP from the NIC.", responseObject = SuccessResponse.class) public class RemoveIpFromVmNicCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RemoveIpFromVmNicCmd.class.getName()); private static final String s_name = "removeipfromnicresponse"; 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 6cb49c165e4..08a4a5673dc 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 @@ -39,6 +39,12 @@ 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()); @@ -60,6 +66,11 @@ public class ScaleVMCmd extends BaseAsyncCmd { 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; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -72,6 +83,24 @@ public class ScaleVMCmd extends BaseAsyncCmd { return serviceOfferingId; } + //instead of reading a map directly we are using collections. + //it is because customParameters.values() cannot be cast to a map. + //it gives a exception + public Map getCustomParameters() { + Map customparameterMap = new HashMap(); + if (customParameters != null && customParameters.size() !=0){ + Collection parameterCollection = customParameters.values(); + Iterator iter = parameterCollection.iterator(); + while (iter.hasNext()) { + HashMap value = (HashMap) iter.next(); + for (String key : value.keySet()) { + customparameterMap.put(key, value.get(key)); + } + } + } + return customparameterMap; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java index fbb785f2c33..967d8f4d525 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java @@ -16,6 +16,7 @@ // under the License. package org.apache.cloudstack.api.command.user.vm; +import org.apache.cloudstack.api.BaseCustomIdCmd; import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; @@ -36,7 +37,7 @@ import com.cloud.uservm.UserVm; @APICommand(name = "updateVirtualMachine", description = "Updates properties of a virtual machine. The VM has to be stopped and restarted for the " + "new properties to take effect. UpdateVirtualMachine does not first check whether the VM is stopped. " + "Therefore, stop the VM manually before issuing this call.", responseObject = UserVmResponse.class) -public class UpdateVMCmd extends BaseCmd { +public class UpdateVMCmd extends BaseCustomIdCmd { public static final Logger s_logger = Logger.getLogger(UpdateVMCmd.class.getName()); private static final String s_name = "updatevirtualmachineresponse"; 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 3dfcdf9f158..43497811b13 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 @@ -34,6 +34,11 @@ 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.") public class UpgradeVMCmd extends BaseCmd { @@ -54,6 +59,11 @@ public class UpgradeVMCmd extends BaseCmd { 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; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -66,6 +76,21 @@ public class UpgradeVMCmd extends BaseCmd { return serviceOfferingId; } + public Map getCustomParameters() { + Map customparameterMap = new HashMap(); + if (customParameters != null && customParameters.size() !=0){ + Collection parameterCollection = customParameters.values(); + Iterator iter = parameterCollection.iterator(); + while (iter.hasNext()) { + HashMap value = (HashMap) iter.next(); + for (String key : value.keySet()) { + customparameterMap.put(key, value.get(key)); + } + } + } + return customparameterMap; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java index eb4ac88a835..cb7b13a6a7e 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java @@ -16,19 +16,21 @@ // under the License. package org.apache.cloudstack.api.command.user.volume; +import org.apache.cloudstack.api.BaseAsyncCreateCustomIdCmd; +import org.apache.cloudstack.api.BaseCmd; 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.BaseAsyncCreateCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.SnapshotResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.context.CallContext; @@ -41,7 +43,7 @@ import com.cloud.storage.Volume; @APICommand(name = "createVolume", responseObject = VolumeResponse.class, description = "Creates a disk volume from a disk offering. This disk volume must still be attached to a virtual machine to make use of it.") -public class CreateVolumeCmd extends BaseAsyncCreateCmd { +public class CreateVolumeCmd extends BaseAsyncCreateCustomIdCmd { public static final Logger s_logger = Logger.getLogger(CreateVolumeCmd.class.getName()); private static final String s_name = "createvolumeresponse"; @@ -50,7 +52,7 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ACCOUNT, - type = CommandType.STRING, + type = BaseCmd.CommandType.STRING, description = "the account associated with the disk volume. Must be used with the domainId parameter.") private String accountName; @@ -98,6 +100,9 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd { @Parameter(name = ApiConstants.DISPLAY_VOLUME, type = CommandType.BOOLEAN, description = "an optional field, whether to display the volume to the end user or not.") private Boolean displayVolume; + @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, entityType = UserVmResponse.class, description = "the ID of the virtual machine; to be used with snapshot Id, VM to which the volume gets attached after creation") + private Long virtualMachineId; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -146,6 +151,10 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd { return displayVolume; } + public Long getVirtualMachineId() { + return virtualMachineId; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/UpdateVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/UpdateVolumeCmd.java index f12cef844f0..7233b4fb5d3 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/UpdateVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/UpdateVolumeCmd.java @@ -16,6 +16,7 @@ // under the License. package org.apache.cloudstack.api.command.user.volume; +import org.apache.cloudstack.api.BaseAsyncCustomIdCmd; import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; @@ -34,7 +35,7 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.storage.Volume; @APICommand(name = "updateVolume", description = "Updates the volume.", responseObject = VolumeResponse.class) -public class UpdateVolumeCmd extends BaseAsyncCmd { +public class UpdateVolumeCmd extends BaseAsyncCustomIdCmd { public static final Logger s_logger = Logger.getLogger(UpdateVolumeCmd.class.getName()); private static final String s_name = "updatevolumeresponse"; @@ -140,7 +141,7 @@ public class UpdateVolumeCmd extends BaseAsyncCmd { @Override public void execute() { CallContext.current().setEventDetails("Volume Id: " + getId()); - Volume result = _volumeService.updateVolume(getId(), getPath(), getState(), getStorageId(), getDisplayVolume()); + Volume result = _volumeService.updateVolume(getId(), getPath(), getState(), getStorageId(), getDisplayVolume(), getCustomId(), getEntityOwnerId()); if (result != null) { VolumeResponse response = _responseGenerator.createVolumeResponse(result); response.setResponseName(getCommandName()); diff --git a/api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java index 0aafa399d08..f12d15b5f0e 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java @@ -16,8 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vpc; -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; @@ -30,6 +28,7 @@ import org.apache.cloudstack.api.response.VpcOfferingResponse; import org.apache.cloudstack.api.response.VpcResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.context.CallContext; +import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -43,47 +42,54 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateVPCCmd.class.getName()); private static final String s_name = "createvpcresponse"; - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// - @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "the account associated with the VPC. " - + "Must be used with the domainId parameter.") + @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "the account associated with the VPC. " + + "Must be used with the domainId parameter.") private String accountName; - @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "the domain ID associated with the VPC. " - + "If used with the account parameter returns the VPC associated with the account for the specified domain.") + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, + description = "the domain ID associated with the VPC. " + + "If used with the account parameter returns the VPC associated with the account for the specified domain.") private Long domainId; - @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "create VPC for the project") + @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, + description = "create VPC for the project") private Long projectId; - @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = true, description = "the ID of the availability zone") + @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, + required = true, description = "the ID of the availability zone") private Long zoneId; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "the name of the VPC") private String vpcName; - @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, required = true, description = "the display text of " + "the VPC") + @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, required = true, description = "the display text of " + + "the VPC") private String displayText; - @Parameter(name = ApiConstants.CIDR, type = CommandType.STRING, required = true, description = "the cidr of the VPC. All VPC " - + "guest networks' cidrs should be within this CIDR") + @Parameter(name = ApiConstants.CIDR, type = CommandType.STRING, required = true, description = "the cidr of the VPC. All VPC " + + "guest networks' cidrs should be within this CIDR") private String cidr; - @Parameter(name = ApiConstants.VPC_OFF_ID, - type = CommandType.UUID, - entityType = VpcOfferingResponse.class, - required = true, - description = "the ID of the VPC offering") + @Parameter(name = ApiConstants.VPC_OFF_ID, type = CommandType.UUID, entityType = VpcOfferingResponse.class, + required = true, description = "the ID of the VPC offering") private Long vpcOffering; - @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "VPC network domain. All networks inside the VPC will belong to this domain") + @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, + description = "VPC network domain. All networks inside the VPC will belong to this domain") private String networkDomain; - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// + @Parameter(name = ApiConstants.START, type = CommandType.BOOLEAN, + description = "If set to false, the VPC won't start (VPC VR will not get allocated) until its first network gets implemented. " + + "True by default.", since = "4.3") + private Boolean start; + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// public String getAccountName() { return accountName; @@ -117,6 +123,13 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd { return networkDomain; } + public boolean isStart() { + if (start != null) { + return start; + } + return true; + } + @Override public void create() throws ResourceAllocationException { Vpc vpc = _vpcService.createVpc(getZoneId(), getVpcOffering(), getEntityOwnerId(), getVpcName(), getDisplayText(), getCidr(), getNetworkDomain()); @@ -131,10 +144,14 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd { @Override public void execute() { Vpc vpc = null; + boolean success = true; try { - if (_vpcService.startVpc(getEntityId(), true)) { - vpc = _entityMgr.findById(Vpc.class, getEntityId()); + if (isStart()) { + success = _vpcService.startVpc(getEntityId(), true); + } else { + s_logger.debug("Not starting VPC as " + ApiConstants.START + "=false was passed to the API"); } + vpc = _entityMgr.findById(Vpc.class, getEntityId()); } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); @@ -147,7 +164,7 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd { throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } - if (vpc != null) { + if (vpc != null && success) { VpcResponse response = _responseGenerator.createVpcResponse(vpc); response.setResponseName(getCommandName()); setResponseObject(response); diff --git a/api/src/org/apache/cloudstack/api/response/AlertResponse.java b/api/src/org/apache/cloudstack/api/response/AlertResponse.java index 5a279157613..a2554c3b095 100644 --- a/api/src/org/apache/cloudstack/api/response/AlertResponse.java +++ b/api/src/org/apache/cloudstack/api/response/AlertResponse.java @@ -42,6 +42,9 @@ public class AlertResponse extends BaseResponse { + "MANAGMENT_NODE = 13: lost connection to default route (to the gateway), " + "DOMAIN_ROUTER_MIGRATE = 14, CONSOLE_PROXY_MIGRATE = 15, USERVM_MIGRATE = 16, VLAN = 17, SSVM = 18, " + "USAGE_SERVER_RESULT = 19") private Short alertType; + + @SerializedName(ApiConstants.NAME) @Param(description="the name of the alert", since="4.3") + private String alertName; @SerializedName(ApiConstants.DESCRIPTION) @Param(description = "description of the alert") @@ -66,4 +69,8 @@ public class AlertResponse extends BaseResponse { public void setLastSent(Date lastSent) { this.lastSent = lastSent; } + + public void setName(String name) { + this.alertName = name; + } } diff --git a/api/src/org/apache/cloudstack/api/response/CapabilitiesResponse.java b/api/src/org/apache/cloudstack/api/response/CapabilitiesResponse.java index 17dcdd805fe..4840c60528f 100644 --- a/api/src/org/apache/cloudstack/api/response/CapabilitiesResponse.java +++ b/api/src/org/apache/cloudstack/api/response/CapabilitiesResponse.java @@ -61,6 +61,10 @@ public class CapabilitiesResponse extends BaseResponse { @Param(description = "time interval (in seconds) to reset api count") private Integer apiLimitInterval; + @SerializedName("kvmsnapshotenabled") + @Param(description = "true if snapshot is supported for KVM host, false otherwise") + private boolean KVMSnapshotEnabled; + @SerializedName("apilimitmax") @Param(description = "Max allowed number of api requests within the specified interval") private Integer apiLimitMax; @@ -97,6 +101,10 @@ public class CapabilitiesResponse extends BaseResponse { this.regionSecondaryEnabled = regionSecondaryEnabled; } + public void setKVMSnapshotEnabled(boolean KVMSnapshotEnabled) { + this.KVMSnapshotEnabled = KVMSnapshotEnabled; + } + public void setApiLimitInterval(Integer apiLimitInterval) { this.apiLimitInterval = apiLimitInterval; } diff --git a/api/src/org/apache/cloudstack/api/response/OvsProviderResponse.java b/api/src/org/apache/cloudstack/api/response/OvsProviderResponse.java new file mode 100644 index 00000000000..23e61341072 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/response/OvsProviderResponse.java @@ -0,0 +1,77 @@ +package org.apache.cloudstack.api.response; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; + +import com.cloud.network.OvsProvider; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +@EntityReference(value = OvsProvider.class) +@SuppressWarnings("unused") +public class OvsProviderResponse extends BaseResponse implements + ControlledEntityResponse { + @SerializedName(ApiConstants.ID) + @Param(description = "the id of the ovs") + private String id; + @SerializedName(ApiConstants.NSP_ID) + @Param(description = "the physical network service provider id of the provider") + private String nspId; + @SerializedName(ApiConstants.ENABLED) + @Param(description = "Enabled/Disabled the service provider") + private Boolean enabled; + @SerializedName(ApiConstants.ACCOUNT) + @Param(description = "the account associated with the provider") + private String accountName; + @SerializedName(ApiConstants.PROJECT_ID) + @Param(description = "the project id of the ipaddress") + private String projectId; + @SerializedName(ApiConstants.PROJECT) + @Param(description = "the project name of the address") + private String projectName; + @SerializedName(ApiConstants.DOMAIN_ID) + @Param(description = "the domain ID associated with the provider") + private String domainId; + + @SerializedName(ApiConstants.DOMAIN) + @Param(description = "the domain associated with the provider") + private String domainName; + + @Override + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + @Override + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + @Override + public void setProjectId(String projectId) { + this.projectId = projectId; + } + + @Override + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public void setNspId(String nspId) { + this.nspId = nspId; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } +} diff --git a/api/src/org/apache/cloudstack/api/response/ServiceOfferingResponse.java b/api/src/org/apache/cloudstack/api/response/ServiceOfferingResponse.java index 7ec739eed00..c8dee140323 100644 --- a/api/src/org/apache/cloudstack/api/response/ServiceOfferingResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ServiceOfferingResponse.java @@ -44,15 +44,15 @@ public class ServiceOfferingResponse extends BaseResponse { @SerializedName("cpunumber") @Param(description = "the number of CPU") - private int cpuNumber; + private Integer cpuNumber; @SerializedName("cpuspeed") @Param(description = "the clock rate CPU speed in Mhz") - private int cpuSpeed; + private Integer cpuSpeed; @SerializedName("memory") @Param(description = "the memory in MB") - private int memory; + private Integer memory; @SerializedName("created") @Param(description = "the date this service offering was created") @@ -130,6 +130,10 @@ public class ServiceOfferingResponse extends BaseResponse { @Param(description = "additional key/value details tied with this service offering", since = "4.2.0") private Map details; + @SerializedName("iscustomized") + @Param(description = "is true if the offering is customized", since = "4.3.0") + private Boolean isCustomized; + public ServiceOfferingResponse() { } @@ -185,7 +189,7 @@ public class ServiceOfferingResponse extends BaseResponse { return cpuNumber; } - public void setCpuNumber(int cpuNumber) { + public void setCpuNumber(Integer cpuNumber) { this.cpuNumber = cpuNumber; } @@ -193,7 +197,7 @@ public class ServiceOfferingResponse extends BaseResponse { return cpuSpeed; } - public void setCpuSpeed(int cpuSpeed) { + public void setCpuSpeed(Integer cpuSpeed) { this.cpuSpeed = cpuSpeed; } @@ -201,7 +205,7 @@ public class ServiceOfferingResponse extends BaseResponse { return memory; } - public void setMemory(int memory) { + public void setMemory(Integer memory) { this.memory = memory; } @@ -309,4 +313,9 @@ public class ServiceOfferingResponse extends BaseResponse { this.details = details; } + public void setIscutomized(boolean iscutomized) { + this.isCustomized = iscutomized; + + } + } diff --git a/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java b/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java index 5c56e9d0506..fd2919dc117 100644 --- a/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java +++ b/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java @@ -58,6 +58,7 @@ import org.apache.axis2.databinding.ADBBean; import org.apache.axis2.databinding.ADBException; import org.apache.axis2.databinding.utils.writer.MTOMAwareXMLSerializer; import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import org.springframework.web.context.support.SpringBeanAutowiringSupport; @@ -103,7 +104,6 @@ import com.amazon.ec2.RunInstancesResponse; import com.amazon.ec2.StartInstancesResponse; import com.amazon.ec2.StopInstancesResponse; import com.amazon.ec2.TerminateInstancesResponse; - import com.cloud.bridge.model.UserCredentialsVO; import com.cloud.bridge.persist.dao.CloudStackUserDaoImpl; import com.cloud.bridge.persist.dao.OfferingDaoImpl; @@ -203,12 +203,16 @@ public class EC2RestServlet extends HttpServlet { if (null != propertiesFile) { logger.info("Use EC2 properties file: " + propertiesFile.getAbsolutePath()); EC2Prop = new Properties(); + FileInputStream ec2PropFile = null; try { - EC2Prop.load(new FileInputStream(propertiesFile)); + ec2PropFile = new FileInputStream(propertiesFile); + EC2Prop.load(ec2PropFile); } catch (FileNotFoundException e) { logger.warn("Unable to open properties file: " + propertiesFile.getAbsolutePath(), e); } catch (IOException e) { logger.warn("Unable to read properties file: " + propertiesFile.getAbsolutePath(), e); + } finally { + IOUtils.closeQuietly(ec2PropFile); } String keystore = EC2Prop.getProperty("keystore"); keystorePassword = EC2Prop.getProperty("keystorePass"); @@ -492,7 +496,7 @@ public class EC2RestServlet extends HttpServlet { response.sendError(530, "Missing cert parameter"); return; } -// logger.debug( "SetCertificate cert: [" + certificate[0] + "]" ); + // logger.debug( "SetCertificate cert: [" + certificate[0] + "]" ); String[] accessKey = request.getParameterValues("AWSAccessKeyId"); if (null == accessKey || 0 == accessKey.length) { @@ -578,12 +582,12 @@ public class EC2RestServlet extends HttpServlet { credentialDao.setCertificateId( accessKey[0], null ); */txn = TransactionLegacy.open(TransactionLegacy.AWSAPI_DB); - UserCredentialsVO user = ucDao.getByAccessKey(accessKey[0]); - user.setCertUniqueId(null); - ucDao.update(user.getId(), user); - response.setStatus(200); - endResponse(response, "User certificate deleted successfully"); - txn.commit(); + UserCredentialsVO user = ucDao.getByAccessKey(accessKey[0]); + user.setCertUniqueId(null); + ucDao.update(user.getId(), user); + response.setStatus(200); + endResponse(response, "User certificate deleted successfully"); + txn.commit(); } else response.setStatus(404); @@ -830,7 +834,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request RevokeSecurityGroupIngressResponse EC2response = - EC2SoapServiceImpl.toRevokeSecurityGroupIngressResponse(ServiceProvider.getInstance().getEC2Engine().revokeSecurityGroup(EC2request)); + EC2SoapServiceImpl.toRevokeSecurityGroupIngressResponse(ServiceProvider.getInstance().getEC2Engine().revokeSecurityGroup(EC2request)); serializeResponse(response, EC2response); } @@ -915,7 +919,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request AuthorizeSecurityGroupIngressResponse EC2response = - EC2SoapServiceImpl.toAuthorizeSecurityGroupIngressResponse(ServiceProvider.getInstance().getEC2Engine().authorizeSecurityGroup(EC2request)); + EC2SoapServiceImpl.toAuthorizeSecurityGroupIngressResponse(ServiceProvider.getInstance().getEC2Engine().authorizeSecurityGroup(EC2request)); serializeResponse(response, EC2response); } @@ -1012,7 +1016,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request CreateSecurityGroupResponse EC2response = - EC2SoapServiceImpl.toCreateSecurityGroupResponse(ServiceProvider.getInstance().getEC2Engine().createSecurityGroup(groupName, groupDescription)); + EC2SoapServiceImpl.toCreateSecurityGroupResponse(ServiceProvider.getInstance().getEC2Engine().createSecurityGroup(groupName, groupDescription)); serializeResponse(response, EC2response); } @@ -1028,7 +1032,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request DeleteSecurityGroupResponse EC2response = - EC2SoapServiceImpl.toDeleteSecurityGroupResponse(ServiceProvider.getInstance().getEC2Engine().deleteSecurityGroup(groupName)); + EC2SoapServiceImpl.toDeleteSecurityGroupResponse(ServiceProvider.getInstance().getEC2Engine().deleteSecurityGroup(groupName)); serializeResponse(response, EC2response); } @@ -1166,7 +1170,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request ModifyImageAttributeResponse EC2response = - EC2SoapServiceImpl.toModifyImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyImageAttribute(ec2request)); + EC2SoapServiceImpl.toModifyImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyImageAttribute(ec2request)); serializeResponse(response, EC2response); } @@ -1231,7 +1235,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request ResetImageAttributeResponse EC2response = - EC2SoapServiceImpl.toResetImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyImageAttribute(ec2request)); + EC2SoapServiceImpl.toResetImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyImageAttribute(ec2request)); serializeResponse(response, EC2response); } @@ -1443,7 +1447,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request DescribeAvailabilityZonesResponse EC2response = - EC2SoapServiceImpl.toDescribeAvailabilityZonesResponse(ServiceProvider.getInstance().getEC2Engine().describeAvailabilityZones(EC2request)); + EC2SoapServiceImpl.toDescribeAvailabilityZonesResponse(ServiceProvider.getInstance().getEC2Engine().describeAvailabilityZones(EC2request)); serializeResponse(response, EC2response); } @@ -1499,7 +1503,7 @@ public class EC2RestServlet extends HttpServlet { } DescribeImageAttributeResponse EC2response = - EC2SoapServiceImpl.toDescribeImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().describeImageAttribute(ec2request)); + EC2SoapServiceImpl.toDescribeImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().describeImageAttribute(ec2request)); serializeResponse(response, EC2response); } @@ -1677,7 +1681,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request DescribeInstanceAttributeResponse EC2response = - EC2SoapServiceImpl.toDescribeInstanceAttributeResponse(ServiceProvider.getInstance().getEC2Engine().describeInstances(EC2request)); + EC2SoapServiceImpl.toDescribeInstanceAttributeResponse(ServiceProvider.getInstance().getEC2Engine().describeInstances(EC2request)); serializeResponse(response, EC2response); } @@ -1707,7 +1711,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request ModifyInstanceAttributeResponse EC2response = - EC2SoapServiceImpl.toModifyInstanceAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyInstanceAttribute(ec2Request)); + EC2SoapServiceImpl.toModifyInstanceAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyInstanceAttribute(ec2Request)); serializeResponse(response, EC2response); } @@ -1766,7 +1770,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request EC2Engine engine = ServiceProvider.getInstance().getEC2Engine(); DescribeVolumesResponse EC2response = - EC2SoapServiceImpl.toDescribeVolumesResponse(ServiceProvider.getInstance().getEC2Engine().describeVolumes(EC2request), engine); + EC2SoapServiceImpl.toDescribeVolumesResponse(ServiceProvider.getInstance().getEC2Engine().describeVolumes(EC2request), engine); serializeResponse(response, EC2response); } @@ -1988,7 +1992,7 @@ public class EC2RestServlet extends HttpServlet { * parameter to see if the signature has expired and if so the request fails. */ private boolean authenticateRequest(HttpServletRequest request, HttpServletResponse response) throws SignatureException, IOException, InstantiationException, - IllegalAccessException, ClassNotFoundException, SQLException, ParseException { + IllegalAccessException, ClassNotFoundException, SQLException, ParseException { String cloudSecretKey = null; String cloudAccessKey = null; String signature = null; diff --git a/awsapi/src/com/cloud/bridge/service/controller/s3/ServiceProvider.java b/awsapi/src/com/cloud/bridge/service/controller/s3/ServiceProvider.java index deb886f411f..e00408e1edf 100644 --- a/awsapi/src/com/cloud/bridge/service/controller/s3/ServiceProvider.java +++ b/awsapi/src/com/cloud/bridge/service/controller/s3/ServiceProvider.java @@ -34,15 +34,14 @@ import javax.annotation.PostConstruct; import javax.inject.Inject; import org.apache.axis2.AxisFault; +import org.apache.cloudstack.managed.context.ManagedContextTimerTask; +import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import org.springframework.stereotype.Component; import com.amazon.ec2.AmazonEC2SkeletonInterface; import com.amazon.s3.AmazonS3SkeletonInterface; - -import org.apache.cloudstack.managed.context.ManagedContextTimerTask; - import com.cloud.bridge.model.MHostVO; import com.cloud.bridge.model.SHost; import com.cloud.bridge.model.SHostVO; @@ -111,8 +110,8 @@ public class ServiceProvider extends ManagerBase { instance = this; } + @Override public boolean configure(String name, Map params) throws ConfigurationException { - initialize(); return true; } @@ -122,7 +121,7 @@ public class ServiceProvider extends ManagerBase { long mhostId = 0; if (mhost != null) mhostId = mhost.getId() != null ? mhost.getId().longValue() : 0L; - return mhostId; + return mhostId; } /** @@ -268,12 +267,16 @@ public class ServiceProvider extends ManagerBase { File propertiesFile = ConfigurationHelper.findConfigurationFile("cloud-bridge.properties"); properties = new Properties(); if (propertiesFile != null) { + FileInputStream startProps = null; try { - properties.load(new FileInputStream(propertiesFile)); + startProps = new FileInputStream(propertiesFile); + properties.load(startProps); } catch (FileNotFoundException e) { logger.warn("Unable to open properties file: " + propertiesFile.getAbsolutePath(), e); } catch (IOException e) { logger.warn("Unable to read properties file: " + propertiesFile.getAbsolutePath(), e); + } finally { + IOUtils.closeQuietly(startProps); } logger.info("Use startup properties file: " + propertiesFile.getAbsolutePath()); diff --git a/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java b/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java index 59abca0e2aa..ccac6749479 100644 --- a/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java +++ b/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java @@ -35,6 +35,7 @@ import javax.inject.Inject; import javax.naming.ConfigurationException; import javax.xml.parsers.ParserConfigurationException; +import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import org.xml.sax.SAXException; @@ -122,12 +123,18 @@ public class EC2Engine extends ManagerBase { if (null != propertiesFile) { logger.info("Use EC2 properties file: " + propertiesFile.getAbsolutePath()); Properties EC2Prop = new Properties(); + FileInputStream ec2PropFile = null; try { EC2Prop.load(new FileInputStream(propertiesFile)); + ec2PropFile = new FileInputStream( propertiesFile ); + EC2Prop.load(ec2PropFile); + } catch (FileNotFoundException e) { logger.warn("Unable to open properties file: " + propertiesFile.getAbsolutePath(), e); } catch (IOException e) { logger.warn("Unable to read properties file: " + propertiesFile.getAbsolutePath(), e); + } finally { + IOUtils.closeQuietly(ec2PropFile); } managementServer = EC2Prop.getProperty("managementServer"); cloudAPIPort = EC2Prop.getProperty("cloudAPIPort", null); @@ -364,12 +371,12 @@ public class EC2Engine extends ManagerBase { CloudStackSecurityGroup resp = null; if (ipPerm.getProtocol().equalsIgnoreCase("icmp")) { resp = - getApi().authorizeSecurityGroupIngress(null, constructList(ipPerm.getIpRangeSet()), null, null, ipPerm.getIcmpCode(), ipPerm.getIcmpType(), - ipPerm.getProtocol(), null, request.getName(), null, secGroupList); + getApi().authorizeSecurityGroupIngress(null, constructList(ipPerm.getIpRangeSet()), null, null, ipPerm.getIcmpCode(), ipPerm.getIcmpType(), + ipPerm.getProtocol(), null, request.getName(), null, secGroupList); } else { resp = - getApi().authorizeSecurityGroupIngress(null, constructList(ipPerm.getIpRangeSet()), null, ipPerm.getToPort().longValue(), null, null, - ipPerm.getProtocol(), null, request.getName(), ipPerm.getFromPort().longValue(), secGroupList); + getApi().authorizeSecurityGroupIngress(null, constructList(ipPerm.getIpRangeSet()), null, ipPerm.getToPort().longValue(), null, null, + ipPerm.getProtocol(), null, request.getName(), ipPerm.getFromPort().longValue(), secGroupList); } if (resp != null) { List ingressRules = resp.getIngressRules(); @@ -808,7 +815,7 @@ public class EC2Engine extends ManagerBase { CloudStackIpAddress cloudIp = cloudIps.get(0); List vmList = - getApi().listVirtualMachines(null, null, true, null, null, null, null, request.getInstanceId(), null, null, null, null, null, null, null, null, null); + getApi().listVirtualMachines(null, null, true, null, null, null, null, request.getInstanceId(), null, null, null, null, null, null, null, null, null); if (vmList == null || vmList.size() == 0) { throw new Exception("Instance not found"); } @@ -863,7 +870,7 @@ public class EC2Engine extends ManagerBase { CloudStackZone zone = findZone(); //CloudStackNetwork net = findNetwork(zone); -// CloudStackIpAddress resp = getApi().associateIpAddress(null, null, null, "0036952d-48df-4422-9fd0-94b0885e18cb"); + //CloudStackIpAddress resp = getApi().associateIpAddress(null, null, null, "0036952d-48df-4422-9fd0-94b0885e18cb"); CloudStackIpAddress resp = getApi().associateIpAddress(zone.getId(), caller.getName(), caller.getDomainId(), null); ec2Address.setAssociatedInstanceId(resp.getId()); @@ -965,8 +972,8 @@ public class EC2Engine extends ManagerBase { String osTypeId = imageSet[0].getOsTypeId(); CloudStackTemplate resp = - getApi().createTemplate((request.getDescription() == null ? "" : request.getDescription()), request.getName(), osTypeId, null, null, null, null, null, - null, volumeId); + getApi().createTemplate((request.getDescription() == null ? "" : request.getDescription()), request.getName(), osTypeId, null, null, null, null, null, + null, volumeId); if (resp == null || resp.getId() == null) { throw new Exception("Image couldn't be created"); } @@ -996,9 +1003,9 @@ public class EC2Engine extends ManagerBase { EC2CreateImageResponse image = new EC2CreateImageResponse(); try { List templates = - getApi().registerTemplate((request.getDescription() == null ? request.getName() : request.getDescription()), request.getFormat(), - request.getHypervisor(), request.getName(), toOSTypeId(request.getOsTypeName()), request.getLocation(), toZoneId(request.getZoneName(), null), null, - null, null, null, null, null, null, null, null); + getApi().registerTemplate((request.getDescription() == null ? request.getName() : request.getDescription()), request.getFormat(), + request.getHypervisor(), request.getName(), toOSTypeId(request.getOsTypeName()), request.getLocation(), toZoneId(request.getZoneName(), null), null, + null, null, null, null, null, null, null, null); if (templates != null) { // technically we will only ever register a single template... for (CloudStackTemplate template : templates) { @@ -1217,13 +1224,13 @@ public class EC2Engine extends ManagerBase { throw new EC2ServiceException(ServerError.InternalError, "No Customize Disk Offering Found"); } -// // -> no volume name is given in the Amazon request but is required in the cloud API + // -> no volume name is given in the Amazon request but is required in the cloud API CloudStackVolume vol = - getApi().createVolume(UUID.randomUUID().toString(), null, diskOfferingId, null, size, snapshotId, toZoneId(request.getZoneName(), null)); + getApi().createVolume(UUID.randomUUID().toString(), null, diskOfferingId, null, size, snapshotId, toZoneId(request.getZoneName(), null)); if (vol != null) { resp.setAttached(vol.getAttached()); resp.setCreated(vol.getCreated()); -// resp.setDevice(); + //resp.setDevice(); resp.setDeviceId(vol.getDeviceId()); resp.setHypervisor(vol.getHypervisor()); resp.setId(vol.getId()); @@ -1442,8 +1449,8 @@ public class EC2Engine extends ManagerBase { for (int i = 0; i < createInstances; i++) { try { CloudStackUserVm resp = - getApi().deployVirtualMachine(svcOffering.getId(), request.getTemplateId(), zoneId, null, null, null, null, null, null, null, - request.getKeyName(), null, null, groupIds, groupNames, request.getSize().longValue(), request.getUserData()); + getApi().deployVirtualMachine(svcOffering.getId(), request.getTemplateId(), zoneId, null, null, null, null, null, null, null, + request.getKeyName(), null, null, groupIds, groupNames, request.getSize().longValue(), request.getUserData()); EC2Instance vm = new EC2Instance(); vm.setId(resp.getId().toString()); vm.setName(resp.getName()); @@ -1666,7 +1673,7 @@ public class EC2Engine extends ManagerBase { * @param ifs - filter out unwanted instances */ private EC2DescribeInstancesResponse listVirtualMachines(String[] virtualMachineIds, EC2InstanceFilterSet ifs, List resourceTags) - throws Exception { + throws Exception { EC2DescribeInstancesResponse instances = new EC2DescribeInstancesResponse(); if (null == virtualMachineIds || 0 == virtualMachineIds.length) { @@ -1690,7 +1697,7 @@ public class EC2Engine extends ManagerBase { * @param instanceId - if interested in volumes for a specific instance, null if instance is not important */ private EC2DescribeVolumesResponse listVolumes(String volumeId, String instanceId, EC2DescribeVolumesResponse volumes, List resourceTagSet) - throws Exception { + throws Exception { List vols = getApi().listVolumes(null, null, null, volumeId, null, null, null, null, null, instanceId, null, resourceTagSet); if (vols != null && vols.size() > 0) { @@ -1881,11 +1888,11 @@ public class EC2Engine extends ManagerBase { * EC2Instance objects loaded. */ private EC2DescribeInstancesResponse lookupInstances(String instanceId, EC2DescribeInstancesResponse instances, List resourceTagSet) - throws Exception { + throws Exception { String instId = instanceId != null ? instanceId : null; List vms = - getApi().listVirtualMachines(null, null, true, null, null, null, null, instId, null, null, null, null, null, null, null, null, resourceTagSet); + getApi().listVirtualMachines(null, null, true, null, null, null, null, instId, null, null, null, null, null, null, null, null, resourceTagSet); if (vms != null && vms.size() > 0) { for (CloudStackUserVm cloudVm : vms) { @@ -2301,7 +2308,7 @@ public class EC2Engine extends ManagerBase { */ private CloudStackNetwork createDefaultGuestNetwork(String zoneId, CloudStackNetworkOffering offering, CloudStackAccount owner) throws Exception { return getApi().createNetwork(owner.getName() + "-network", owner.getName() + "-network", offering.getId(), zoneId, owner.getName(), owner.getDomainId(), true, - null, null, null, null, null, null, null, null); + null, null, null, null, null, null, null, null); } /** @@ -2688,8 +2695,8 @@ public class EC2Engine extends ManagerBase { if (errorMessage.contains("Object vm_instance(uuid:") && errorMessage.contains(") does not exist")) { throw new EC2ServiceException(ClientError.InvalidInstanceID_NotFound, "Specified Instance ID does not exist"); } else if (errorMessage.contains("Unable to find security group by name") || errorMessage.contains("Unable to find security group") || - (errorMessage.contains("Object security_group(uuid:") && errorMessage.contains(") does not exist")) || - errorMessage.contains("Unable to find group by name ")) { + (errorMessage.contains("Object security_group(uuid:") && errorMessage.contains(") does not exist")) || + errorMessage.contains("Unable to find group by name ")) { throw new EC2ServiceException(ClientError.InvalidGroup_NotFound, "Specified Security Group does not exist"); } else if (errorMessage.contains("Invalid port numbers")) { throw new EC2ServiceException(ClientError.InvalidPermission_Malformed, "Specified Port value is invalid"); @@ -2708,7 +2715,7 @@ public class EC2Engine extends ManagerBase { } else if (errorMessage.contains("Object snapshots(uuid:") && errorMessage.contains(") does not exist")) { throw new EC2ServiceException(ClientError.InvalidSnapshot_NotFound, "Specified Snapshot ID doesn't exist"); } else if ((errorMessage.contains("A key pair with name '") && errorMessage.contains("' does not exist")) || - (errorMessage.contains("A key pair with name '") && errorMessage.contains("' was not found"))) { + (errorMessage.contains("A key pair with name '") && errorMessage.contains("' was not found"))) { throw new EC2ServiceException(ClientError.InvalidKeyPair_NotFound, "Specified Key pair name is invalid"); } else if (errorMessage.contains("A key pair with name '") && errorMessage.contains("' already exists")) { throw new EC2ServiceException(ClientError.InvalidKeyPair_Duplicate, "Specified Key pair already exists"); @@ -2735,7 +2742,7 @@ public class EC2Engine extends ManagerBase { } else if (errorMessage.contains("Unable to find tags by parameters specified")) { throw new EC2ServiceException(ClientError.InvalidParameterValue, "Specified resourceTag for the specified resourceId doesn't exist"); } else if (errorMessage.contains("Failed to enable static nat for the ip address with specified ipId " - + "as vm with specified vmId is already associated with specified currentIp")) { + + "as vm with specified vmId is already associated with specified currentIp")) { throw new EC2ServiceException(ClientError.InvalidParameterValue, "Specified publicIp is already associated to the specified VM"); } else if (errorMessage.contains("Specified IP address id is not associated with any vm Id")) { throw new EC2ServiceException(ClientError.InvalidParameterValue, "Specified publicIp is not associated to any VM"); @@ -2783,7 +2790,7 @@ public class EC2Engine extends ManagerBase { throw new EC2ServiceException(ClientError.InvalidAMIID_NotFound, "Specified ImageId is unavailable"); } else if (errorMessage.contains("cannot stop VM") && errorMessage.contains("when it is in state Starting")) { throw new EC2ServiceException(ClientError.IncorrectInstanceState, - "Unable to stop. One or more of the specified instances is in an incorrect state 'pending'"); + "Unable to stop. One or more of the specified instances is in an incorrect state 'pending'"); } else if (errorMessage.contains("Failed to authorize security group ingress rule(s)")) { throw new EC2ServiceException(ClientError.InvalidParameterValue, "Specified Ip-permission is invalid" + " or the Ip-permission already exists"); } else if (errorMessage.contains("Failed to reboot vm instance")) { @@ -2798,7 +2805,7 @@ public class EC2Engine extends ManagerBase { throw new EC2ServiceException(ClientError.VolumeLimitExceeded, "You have reached the limit on the number of volumes that can be created"); } else if (errorMessage.contains("Maximum number of resources of type 'public_ip' for account") && errorMessage.contains("has been exceeded")) { throw new EC2ServiceException(ClientError.AddressLimitExceeded, - "You have reached the limit on the number of elastic ip addresses your account can have"); + "You have reached the limit on the number of elastic ip addresses your account can have"); } else if (errorMessage.contains("Unable to apply save userdata entry on router")) { throw new EC2ServiceException(ClientError.InvalidParameterValue, "The value supplied for parameter UserData is invalid"); } else { @@ -2846,7 +2853,7 @@ public class EC2Engine extends ManagerBase { throw new EC2ServiceException(ServerError.InternalError, "Unable to start the instance that was stopped during image creation"); } else if (errorMessage.contains("One or more of instanceIds specified is in stopped state")) { throw new EC2ServiceException(ClientError.IncorrectInstanceState, - "Unable to reboot. One or more of the specified instances is in an incorrect state 'stopped'"); + "Unable to reboot. One or more of the specified instances is in an incorrect state 'stopped'"); } else if (errorMessage.contains("Specified ipAddress doesn't exist")) { throw new EC2ServiceException(ClientError.InvalidParameterValue, "Specified publicIp doesn't exist"); } else if (errorMessage.contains("Min Count is greater than the number of instances left to allocate")) { @@ -2865,7 +2872,7 @@ public class EC2Engine extends ManagerBase { throw new EC2ServiceException(ClientError.InvalidInstanceID_NotFound, "One or more of the specified instanceId not found"); } else if (errorMessage.contains("Cannot modify, instance should be in stopped state")) { throw new EC2ServiceException(ClientError.IncorrectInstanceState, - "Unable to modify instance attribute. Specified instance is not in the correct state 'stopped'"); + "Unable to modify instance attribute. Specified instance is not in the correct state 'stopped'"); } else { throw new EC2ServiceException(ServerError.InternalError, "An unexpected error occured"); } diff --git a/client/WEB-INF/classes/resources/messages.properties b/client/WEB-INF/classes/resources/messages.properties index faf593bf709..df09cf2de62 100644 --- a/client/WEB-INF/classes/resources/messages.properties +++ b/client/WEB-INF/classes/resources/messages.properties @@ -54,7 +54,7 @@ message.action.delete.nic=Please confirm that want to remove this NIC, which wil changed.item.properties=Changed item properties confirm.enable.s3=Please fill in the following information to enable support for S3-backed Secondary Storage confirm.enable.swift=Please fill in the following information to enable support for Swift -error.could.not.change.your.password.because.ldap.is.enabled=Error cloud not change your password because LDAP is enabled. +error.could.not.change.your.password.because.ldap.is.enabled=Error could not change your password because LDAP is enabled. error.could.not.enable.zone=Could not enable zone error.installWizard.message=Something went wrong; you may go back and correct any errors error.invalid.username.password=Invalid username or password diff --git a/client/WEB-INF/classes/resources/messages_ja.properties b/client/WEB-INF/classes/resources/messages_ja.properties index d01efe88ff1..42324491418 100644 --- a/client/WEB-INF/classes/resources/messages_ja.properties +++ b/client/WEB-INF/classes/resources/messages_ja.properties @@ -1,4 +1,4 @@ -a# Licensed to the Apache Software Foundation (ASF) under one +# 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 @@ -14,6 +14,12 @@ a# Licensed to the Apache Software Foundation (ASF) under one # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. +label.hypervisors=\u30cf\u30a4\u30d1\u30fc\u30d0\u30a4\u30b6\u30fc +label.home=\u30db\u30fc\u30e0 +label.sockets=\u30bd\u30b1\u30c3\u30c8 +label.root.disk.size=\u30eb\u30fc\u30c8 \u30c7\u30a3\u30b9\u30af \u30b5\u30a4\u30ba +label.s3.nfs.server=S3 NFS \u30b5\u30fc\u30d0\u30fc +label.s3.nfs.path=S3 NFS \u30d1\u30b9 label.delete.events=\u30a4\u30d9\u30f3\u30c8\u306e\u524a\u9664 label.delete.alerts=\u30a2\u30e9\u30fc\u30c8\u306e\u524a\u9664 label.archive.alerts=\u30a2\u30e9\u30fc\u30c8\u306e\u30a2\u30fc\u30ab\u30a4\u30d6 @@ -33,6 +39,7 @@ label.custom.disk.iops=\u30ab\u30b9\u30bf\u30e0 IOPS label.disk.iops.min=\u6700\u5c0f IOPS label.disk.iops.max=\u6700\u5927 IOPS label.disk.iops.total=IOPS \u5408\u8a08 +label.hypervisor.snapshot.reserve=\u30cf\u30a4\u30d1\u30fc\u30d0\u30a4\u30b6\u30fc \u30b9\u30ca\u30c3\u30d7\u30b7\u30e7\u30c3\u30c8\u4e88\u7d04 label.view.secondary.ips=\u30bb\u30ab\u30f3\u30c0\u30ea IP \u30a2\u30c9\u30ec\u30b9\u306e\u8868\u793a message.validate.invalid.characters=\u7121\u52b9\u306a\u6587\u5b57\u304c\u898b\u3064\u304b\u308a\u307e\u3057\u305f\u3002\u4fee\u6574\u3057\u3066\u304f\u3060\u3055\u3044\u3002 message.acquire.ip.nic=\u3053\u306e NIC \u306e\u305f\u3081\u306b\u65b0\u3057\u3044\u30bb\u30ab\u30f3\u30c0\u30ea IP \u30a2\u30c9\u30ec\u30b9\u3092\u53d6\u5f97\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b?
\u6ce8: \u65b0\u3057\u304f\u53d6\u5f97\u3057\u305f\u30bb\u30ab\u30f3\u30c0\u30ea IP \u30a2\u30c9\u30ec\u30b9\u306f\u4eee\u60f3\u30de\u30b7\u30f3\u5185\u3067\u624b\u52d5\u3067\u69cb\u6210\u3059\u308b\u5fc5\u8981\u304c\u3042\u308a\u307e\u3059\u3002 @@ -43,6 +50,7 @@ message.action.delete.nic=\u3053\u306e NIC \u3092\u524a\u9664\u3057\u3066\u3082\ changed.item.properties=\u9805\u76ee\u306e\u30d7\u30ed\u30d1\u30c6\u30a3\u306e\u5909\u66f4 confirm.enable.s3=S3 \u30d9\u30fc\u30b9\u306e\u30bb\u30ab\u30f3\u30c0\u30ea \u30b9\u30c8\u30ec\u30fc\u30b8\u306e\u30b5\u30dd\u30fc\u30c8\u3092\u6709\u52b9\u306b\u3059\u308b\u306b\u306f\u3001\u6b21\u306e\u60c5\u5831\u3092\u5165\u529b\u3057\u3066\u304f\u3060\u3055\u3044\u3002 confirm.enable.swift=Swift \u306e\u30b5\u30dd\u30fc\u30c8\u3092\u6709\u52b9\u306b\u3059\u308b\u306b\u306f\u3001\u6b21\u306e\u60c5\u5831\u3092\u5165\u529b\u3057\u3066\u304f\u3060\u3055\u3044\u3002 +error.could.not.change.your.password.because.ldap.is.enabled=LDAP \u304c\u6709\u52b9\u306a\u305f\u3081\u3001\u30a8\u30e9\u30fc\u306b\u3088\u3063\u3066\u30d1\u30b9\u30ef\u30fc\u30c9\u306f\u5909\u66f4\u3055\u308c\u307e\u305b\u3093\u3067\u3057\u305f\u3002 error.could.not.enable.zone=\u30be\u30fc\u30f3\u3092\u6709\u52b9\u306b\u3067\u304d\u307e\u305b\u3093\u3067\u3057\u305f error.installWizard.message=\u554f\u984c\u304c\u767a\u751f\u3057\u307e\u3057\u305f\u3002\u623b\u3063\u3066\u30a8\u30e9\u30fc\u3092\u4fee\u6b63\u3067\u304d\u307e\u3059\u3002 error.invalid.username.password=\u7121\u52b9\u306a\u30e6\u30fc\u30b6\u30fc\u540d\u307e\u305f\u306f\u30d1\u30b9\u30ef\u30fc\u30c9\u3067\u3059\u3002 @@ -75,6 +83,7 @@ label.account.specific=\u30a2\u30ab\u30a6\u30f3\u30c8\u56fa\u6709 label.account=\u30a2\u30ab\u30a6\u30f3\u30c8 label.accounts=\u30a2\u30ab\u30a6\u30f3\u30c8 label.acquire.new.ip=\u65b0\u3057\u3044 IP \u30a2\u30c9\u30ec\u30b9\u306e\u53d6\u5f97 +label.acquire.new.secondary.ip=\u30bb\u30ab\u30f3\u30c0\u30ea IP \u30a2\u30c9\u30ec\u30b9\u306e\u53d6\u5f97 label.action.attach.disk.processing=\u30c7\u30a3\u30b9\u30af\u3092\u30a2\u30bf\u30c3\u30c1\u3057\u3066\u3044\u307e\u3059... label.action.attach.disk=\u30c7\u30a3\u30b9\u30af\u306e\u30a2\u30bf\u30c3\u30c1 label.action.attach.iso.processing=ISO \u3092\u30a2\u30bf\u30c3\u30c1\u3057\u3066\u3044\u307e\u3059... @@ -198,6 +207,8 @@ label.action.enable.user.processing=\u30e6\u30fc\u30b6\u30fc\u3092\u6709\u52b9\u label.action.enable.user=\u30e6\u30fc\u30b6\u30fc\u306e\u6709\u52b9\u5316 label.action.enable.zone.processing=\u30be\u30fc\u30f3\u3092\u6709\u52b9\u306b\u3057\u3066\u3044\u307e\u3059... label.action.enable.zone=\u30be\u30fc\u30f3\u306e\u6709\u52b9\u5316 +label.action.expunge.instance=\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u306e\u62b9\u6d88 +label.action.expunge.instance.processing=\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3092\u62b9\u6d88\u3057\u3066\u3044\u307e\u3059... label.action.force.reconnect.processing=\u518d\u63a5\u7d9a\u3057\u3066\u3044\u307e\u3059... label.action.force.reconnect=\u5f37\u5236\u518d\u63a5\u7d9a label.action.generate.keys.processing=\u30ad\u30fc\u3092\u751f\u6210\u3057\u3066\u3044\u307e\u3059... @@ -247,6 +258,8 @@ label.action.stop.systemvm.processing=\u30b7\u30b9\u30c6\u30e0 VM \u3092\u505c\u label.action.stop.systemvm=\u30b7\u30b9\u30c6\u30e0 VM \u306e\u505c\u6b62 label.action.take.snapshot.processing=\u30b9\u30ca\u30c3\u30d7\u30b7\u30e7\u30c3\u30c8\u3092\u4f5c\u6210\u3057\u3066\u3044\u307e\u3059.... label.action.take.snapshot=\u30b9\u30ca\u30c3\u30d7\u30b7\u30e7\u30c3\u30c8\u306e\u4f5c\u6210 +label.action.revert.snapshot.processing=\u30b9\u30ca\u30c3\u30d7\u30b7\u30e7\u30c3\u30c8\u306b\u623b\u3057\u3066\u3044\u307e\u3059... +label.action.revert.snapshot=\u30b9\u30ca\u30c3\u30d7\u30b7\u30e7\u30c3\u30c8\u306b\u623b\u3059 label.action.unmanage.cluster.processing=\u30af\u30e9\u30b9\u30bf\u30fc\u3092\u975e\u7ba1\u7406\u5bfe\u8c61\u306b\u3057\u3066\u3044\u307e\u3059... label.action.unmanage.cluster=\u30af\u30e9\u30b9\u30bf\u30fc\u306e\u975e\u7ba1\u7406\u5bfe\u8c61\u5316 label.action.update.OS.preference.processing=OS \u57fa\u672c\u8a2d\u5b9a\u3092\u66f4\u65b0\u3057\u3066\u3044\u307e\u3059... @@ -255,7 +268,7 @@ label.action.update.resource.count.processing=\u30ea\u30bd\u30fc\u30b9\u6570\u30 label.action.update.resource.count=\u30ea\u30bd\u30fc\u30b9\u6570\u306e\u66f4\u65b0 label.action.vmsnapshot.create=VM \u30b9\u30ca\u30c3\u30d7\u30b7\u30e7\u30c3\u30c8\u306e\u4f5c\u6210 label.action.vmsnapshot.delete=VM \u30b9\u30ca\u30c3\u30d7\u30b7\u30e7\u30c3\u30c8\u306e\u524a\u9664 -label.action.vmsnapshot.revert=VM \u30b9\u30ca\u30c3\u30d7\u30b7\u30e7\u30c3\u30c8\u3092\u5143\u306b\u623b\u3059 +label.action.vmsnapshot.revert=VM \u30b9\u30ca\u30c3\u30d7\u30b7\u30e7\u30c3\u30c8\u306b\u623b\u3059 label.actions=\u64cd\u4f5c label.activate.project=\u30d7\u30ed\u30b8\u30a7\u30af\u30c8\u306e\u30a2\u30af\u30c6\u30a3\u30d6\u5316 label.active.sessions=\u30a2\u30af\u30c6\u30a3\u30d6\u306a\u30bb\u30c3\u30b7\u30e7\u30f3 @@ -292,6 +305,7 @@ label.add.new.F5=\u65b0\u3057\u3044 F5 \u306e\u8ffd\u52a0 label.add.new.gateway=\u65b0\u3057\u3044\u30b2\u30fc\u30c8\u30a6\u30a7\u30a4\u306e\u8ffd\u52a0 label.add.new.NetScaler=\u65b0\u3057\u3044 NetScaler \u306e\u8ffd\u52a0 label.add.new.SRX=\u65b0\u3057\u3044 SRX \u306e\u8ffd\u52a0 +label.add.new.PA=\u65b0\u3057\u3044 Palo Alto \u306e\u8ffd\u52a0 label.add.new.tier=\u65b0\u3057\u3044\u968e\u5c64\u306e\u8ffd\u52a0 label.add.NiciraNvp.device=NVP \u30b3\u30f3\u30c8\u30ed\u30fc\u30e9\u30fc\u306e\u8ffd\u52a0 label.add.physical.network=\u7269\u7406\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u306e\u8ffd\u52a0 @@ -306,6 +320,7 @@ label.add.secondary.storage=\u30bb\u30ab\u30f3\u30c0\u30ea \u30b9\u30c8\u30ec\u3 label.add.security.group=\u30bb\u30ad\u30e5\u30ea\u30c6\u30a3 \u30b0\u30eb\u30fc\u30d7\u306e\u8ffd\u52a0 label.add.service.offering=\u30b5\u30fc\u30d3\u30b9 \u30aa\u30d5\u30a1\u30ea\u30f3\u30b0\u306e\u8ffd\u52a0 label.add.SRX.device=SRX \u30c7\u30d0\u30a4\u30b9\u306e\u8ffd\u52a0 +label.add.PA.device=Palo Alto \u30c7\u30d0\u30a4\u30b9\u306e\u8ffd\u52a0 label.add.static.nat.rule=\u9759\u7684 NAT \u898f\u5247\u306e\u8ffd\u52a0 label.add.static.route=\u9759\u7684\u30eb\u30fc\u30c8\u306e\u8ffd\u52a0 label.add.system.service.offering=\u30b7\u30b9\u30c6\u30e0 \u30b5\u30fc\u30d3\u30b9 \u30aa\u30d5\u30a1\u30ea\u30f3\u30b0\u306e\u8ffd\u52a0 @@ -369,6 +384,7 @@ label.back=\u623b\u308b label.bandwidth=\u5e2f\u57df\u5e45 label.basic.mode=\u57fa\u672c\u30e2\u30fc\u30c9 label.basic=\u57fa\u672c +label.bigswitch.controller.address=Big Switch VNS \u30b3\u30f3\u30c8\u30ed\u30fc\u30e9\u30fc\u306e\u30a2\u30c9\u30ec\u30b9 label.bootable=\u8d77\u52d5\u53ef\u80fd label.broadcast.domain.range=\u30d6\u30ed\u30fc\u30c9\u30ad\u30e3\u30b9\u30c8 \u30c9\u30e1\u30a4\u30f3\u306e\u7bc4\u56f2 label.broadcast.domain.type=\u30d6\u30ed\u30fc\u30c9\u30ad\u30e3\u30b9\u30c8 \u30c9\u30e1\u30a4\u30f3\u306e\u7a2e\u985e @@ -410,6 +426,11 @@ label.cluster.type=\u30af\u30e9\u30b9\u30bf\u30fc\u306e\u7a2e\u985e label.cluster=\u30af\u30e9\u30b9\u30bf\u30fc label.clusters=\u30af\u30e9\u30b9\u30bf\u30fc label.clvm=CLVM +label.rbd=RBD +label.rbd.monitor=Ceph \u30e2\u30cb\u30bf\u30fc +label.rbd.pool=Ceph \u30d7\u30fc\u30eb +label.rbd.id=Cephx \u30e6\u30fc\u30b6\u30fc +label.rbd.secret=Cephx \u30b7\u30fc\u30af\u30ec\u30c3\u30c8 label.code=\u30b3\u30fc\u30c9 label.community=\u30b3\u30df\u30e5\u30cb\u30c6\u30a3 label.compute.and.storage=\u30b3\u30f3\u30d4\u30e5\u30fc\u30c6\u30a3\u30f3\u30b0\u3068\u30b9\u30c8\u30ec\u30fc\u30b8 @@ -461,6 +482,7 @@ label.delete.NetScaler=NetScaler \u306e\u524a\u9664 label.delete.NiciraNvp=NVP \u30b3\u30f3\u30c8\u30ed\u30fc\u30e9\u30fc\u306e\u524a\u9664 label.delete.project=\u30d7\u30ed\u30b8\u30a7\u30af\u30c8\u306e\u524a\u9664 label.delete.SRX=SRX \u306e\u524a\u9664 +label.delete.PA=Palo Alto \u306e\u524a\u9664 label.delete.VPN.connection=VPN \u63a5\u7d9a\u306e\u524a\u9664 label.delete.VPN.customer.gateway=VPN \u30ab\u30b9\u30bf\u30de\u30fc \u30b2\u30fc\u30c8\u30a6\u30a7\u30a4\u306e\u524a\u9664 label.delete.VPN.gateway=VPN \u30b2\u30fc\u30c8\u30a6\u30a7\u30a4\u306e\u524a\u9664 @@ -485,10 +507,14 @@ label.disable.vpn=VPN \u306e\u7121\u52b9\u5316 label.disabled=\u7121\u52b9 label.disabling.vpn.access=VPN \u30a2\u30af\u30bb\u30b9\u3092\u7121\u52b9\u306b\u3057\u3066\u3044\u307e\u3059 label.disk.allocated=\u5272\u308a\u5f53\u3066\u6e08\u307f\u306e\u30c7\u30a3\u30b9\u30af +label.disk.bytes.read.rate=\u30c7\u30a3\u30b9\u30af\u8aad\u307f\u53d6\u308a\u901f\u5ea6 (BPS) +label.disk.bytes.write.rate=\u30c7\u30a3\u30b9\u30af\u66f8\u304d\u8fbc\u307f\u901f\u5ea6 (BPS) +label.disk.iops.read.rate=\u30c7\u30a3\u30b9\u30af\u8aad\u307f\u53d6\u308a\u901f\u5ea6 (IOPS) +label.disk.iops.write.rate=\u30c7\u30a3\u30b9\u30af\u66f8\u304d\u8fbc\u307f\u901f\u5ea6 (IOPS) label.disk.offering=\u30c7\u30a3\u30b9\u30af \u30aa\u30d5\u30a1\u30ea\u30f3\u30b0 label.disk.read.bytes=\u30c7\u30a3\u30b9\u30af\u8aad\u307f\u53d6\u308a (\u30d0\u30a4\u30c8) label.disk.read.io=\u30c7\u30a3\u30b9\u30af\u8aad\u307f\u53d6\u308a (IO) -label.disk.size.gb=\u30c7\u30a3\u30b9\u30af \u30b5\u30a4\u30ba (GB \u5358\u4f4d) +label.disk.size.gb=\u30c7\u30a3\u30b9\u30af \u30b5\u30a4\u30ba (GB) label.disk.size=\u30c7\u30a3\u30b9\u30af \u30b5\u30a4\u30ba label.disk.total=\u30c7\u30a3\u30b9\u30af\u5408\u8a08 label.disk.volume=\u30c7\u30a3\u30b9\u30af \u30dc\u30ea\u30e5\u30fc\u30e0 @@ -510,6 +536,7 @@ label.done=\u5b8c\u4e86 label.double.quotes.are.not.allowed=\u4e8c\u91cd\u5f15\u7528\u7b26\u306f\u4f7f\u7528\u3067\u304d\u307e\u305b\u3093 label.download.progress=\u30c0\u30a6\u30f3\u30ed\u30fc\u30c9\u306e\u9032\u6357\u72b6\u6cc1 label.drag.new.position=\u65b0\u3057\u3044\u4f4d\u7f6e\u306b\u30c9\u30e9\u30c3\u30b0 +label.edit.affinity.group=\u30a2\u30d5\u30a3\u30cb\u30c6\u30a3 \u30b0\u30eb\u30fc\u30d7\u306e\u7de8\u96c6 label.edit.lb.rule=\u8ca0\u8377\u5206\u6563\u898f\u5247\u306e\u7de8\u96c6 label.edit.network.details=\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u306e\u8a73\u7d30\u306e\u7de8\u96c6 label.edit.project.details=\u30d7\u30ed\u30b8\u30a7\u30af\u30c8\u306e\u8a73\u7d30\u306e\u7de8\u96c6 @@ -541,9 +568,12 @@ label.error.code=\u30a8\u30e9\u30fc \u30b3\u30fc\u30c9 label.error=\u30a8\u30e9\u30fc label.ESP.encryption=ESP \u6697\u53f7\u5316 label.ESP.hash=ESP \u30cf\u30c3\u30b7\u30e5 +label.ESP.lifetime=ESP \u6709\u52b9\u671f\u9593 (\u79d2) label.ESP.policy=ESP \u30dd\u30ea\u30b7\u30fc label.esx.host=ESX/ESXi \u30db\u30b9\u30c8 label.example=\u4f8b +label.expunge=\u62b9\u6d88 +label.external.link=\u5916\u90e8\u30ea\u30f3\u30af label.f5=F5 label.failed=\u5931\u6557 label.featured=\u304a\u3059\u3059\u3081 @@ -614,7 +644,7 @@ label.installWizard.addZoneIntro.subtitle=\u30be\u30fc\u30f3\u306b\u3064\u3044\u label.installWizard.addZoneIntro.title=\u30be\u30fc\u30f3\u3092\u8ffd\u52a0\u3057\u307e\u3057\u3087\u3046 label.installWizard.click.launch=[\u8d77\u52d5] \u3092\u30af\u30ea\u30c3\u30af\u3057\u3066\u304f\u3060\u3055\u3044\u3002 label.installWizard.subtitle=\u3053\u306e\u30ac\u30a4\u30c9 \u30c4\u30a2\u30fc\u306f CloudStack&\#8482; \u74b0\u5883\u306e\u30bb\u30c3\u30c8\u30a2\u30c3\u30d7\u306b\u5f79\u7acb\u3061\u307e\u3059 -label.installWizard.title=CloudStack&\#8482 \u3078\u3088\u3046\u3053\u305d +label.installWizard.title=CloudStack&\#8482; \u3078\u3088\u3046\u3053\u305d label.instance.limits=\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5236\u9650 label.instance.name=\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u540d label.instance=\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9 @@ -679,6 +709,7 @@ label.launch=\u8d77\u52d5 label.LB.isolation=\u8ca0\u8377\u5206\u6563\u5206\u96e2 label.least.connections=\u6700\u5c0f\u63a5\u7d9a label.level=\u30ec\u30d9\u30eb +label.linklocal.ip=\u30ea\u30f3\u30af \u30ed\u30fc\u30ab\u30eb IP \u30a2\u30c9\u30ec\u30b9 label.load.balancer=\u8ca0\u8377\u5206\u6563\u88c5\u7f6e label.load.balancing.policies=\u8ca0\u8377\u5206\u6563\u30dd\u30ea\u30b7\u30fc label.load.balancing=\u8ca0\u8377\u5206\u6563 @@ -699,7 +730,9 @@ label.max.cpus=\u6700\u5927 CPU \u30b3\u30a2\u6570 label.max.guest.limit=\u6700\u5927\u30b2\u30b9\u30c8\u5236\u9650 label.max.memory=\u6700\u5927\u30e1\u30e2\u30ea (MiB) label.max.networks=\u6700\u5927\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u6570 +label.max.primary.storage=\u6700\u5927\u30d7\u30e9\u30a4\u30de\u30ea (GiB) label.max.public.ips=\u6700\u5927\u30d1\u30d6\u30ea\u30c3\u30af IP \u30a2\u30c9\u30ec\u30b9\u6570 +label.max.secondary.storage=\u6700\u5927\u30bb\u30ab\u30f3\u30c0\u30ea (GiB) label.max.snapshots=\u6700\u5927\u30b9\u30ca\u30c3\u30d7\u30b7\u30e7\u30c3\u30c8\u6570 label.max.templates=\u6700\u5927\u30c6\u30f3\u30d7\u30ec\u30fc\u30c8\u6570 label.max.vms=\u6700\u5927\u30e6\u30fc\u30b6\u30fc VM \u6570 @@ -708,6 +741,7 @@ label.max.vpcs=\u6700\u5927 VPC \u6570 label.maximum=\u6700\u5927 label.may.continue=\u7d9a\u884c\u3067\u304d\u307e\u3059\u3002 label.memory.allocated=\u5272\u308a\u5f53\u3066\u6e08\u307f\u306e\u30e1\u30e2\u30ea +label.memory.limits=\u30e1\u30e2\u30ea\u5236\u9650 (MiB) label.memory.mb=\u30e1\u30e2\u30ea (MB) label.memory.total=\u30e1\u30e2\u30ea\u5408\u8a08 label.memory.used=\u30e1\u30e2\u30ea\u4f7f\u7528\u91cf @@ -787,6 +821,7 @@ label.network.domain.text=\u30cd\u30c3\u30c8\u30ef\u30fc\u30af \u30c9\u30e1\u30a label.network.domain=\u30cd\u30c3\u30c8\u30ef\u30fc\u30af \u30c9\u30e1\u30a4\u30f3 label.network.id=\u30cd\u30c3\u30c8\u30ef\u30fc\u30af ID label.network.label.display.for.blank.value=\u30c7\u30d5\u30a9\u30eb\u30c8 \u30b2\u30fc\u30c8\u30a6\u30a7\u30a4\u3092\u4f7f\u7528 +label.network.limits=\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u5236\u9650 label.network.name=\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u540d label.network.offering.display.text=\u30cd\u30c3\u30c8\u30ef\u30fc\u30af \u30aa\u30d5\u30a1\u30ea\u30f3\u30b0\u8868\u793a\u30c6\u30ad\u30b9\u30c8 label.network.offering.id=\u30cd\u30c3\u30c8\u30ef\u30fc\u30af \u30aa\u30d5\u30a1\u30ea\u30f3\u30b0 ID @@ -845,12 +880,15 @@ label.os.type=OS \u306e\u7a2e\u985e label.owned.public.ips=\u6240\u6709\u3059\u308b\u30d1\u30d6\u30ea\u30c3\u30af IP \u30a2\u30c9\u30ec\u30b9 label.owner.account=\u6240\u6709\u8005\u30a2\u30ab\u30a6\u30f3\u30c8 label.owner.domain=\u6240\u6709\u8005\u30c9\u30e1\u30a4\u30f3 +label.PA.log.profile=Palo Alto \u30ed\u30b0 \u30d7\u30ed\u30d5\u30a1\u30a4\u30eb +label.PA.threat.profile=Palo Alto \u8105\u5a01\u30d7\u30ed\u30d5\u30a1\u30a4\u30eb label.parent.domain=\u89aa\u30c9\u30e1\u30a4\u30f3 label.password.enabled=\u30d1\u30b9\u30ef\u30fc\u30c9\u7ba1\u7406\u6709\u52b9 label.password=\u30d1\u30b9\u30ef\u30fc\u30c9 label.path=\u30d1\u30b9 label.perfect.forward.secrecy=Perfect Forward Secrecy label.physical.network.ID=\u7269\u7406\u30cd\u30c3\u30c8\u30ef\u30fc\u30af ID +label.physical.network=\u7269\u7406\u30cd\u30c3\u30c8\u30ef\u30fc\u30af label.PING.CIFS.password=PING CIFS \u30d1\u30b9\u30ef\u30fc\u30c9 label.PING.CIFS.username=PING CIFS \u30e6\u30fc\u30b6\u30fc\u540d label.PING.dir=PING \u30c7\u30a3\u30ec\u30af\u30c8\u30ea @@ -871,6 +909,7 @@ label.previous=\u623b\u308b label.primary.allocated=\u5272\u308a\u5f53\u3066\u6e08\u307f\u306e\u30d7\u30e9\u30a4\u30de\u30ea \u30b9\u30c8\u30ec\u30fc\u30b8 label.primary.network=\u30d7\u30e9\u30a4\u30de\u30ea \u30cd\u30c3\u30c8\u30ef\u30fc\u30af label.primary.storage.count=\u30d7\u30e9\u30a4\u30de\u30ea \u30b9\u30c8\u30ec\u30fc\u30b8 \u30d7\u30fc\u30eb +label.primary.storage.limits=\u30d7\u30e9\u30a4\u30de\u30ea \u30b9\u30c8\u30ec\u30fc\u30b8\u5236\u9650 (GiB) label.primary.storage=\u30d7\u30e9\u30a4\u30de\u30ea \u30b9\u30c8\u30ec\u30fc\u30b8 label.primary.used=\u30d7\u30e9\u30a4\u30de\u30ea \u30b9\u30c8\u30ec\u30fc\u30b8\u4f7f\u7528\u91cf label.private.Gateway=\u30d7\u30e9\u30a4\u30d9\u30fc\u30c8 \u30b2\u30fc\u30c8\u30a6\u30a7\u30a4 @@ -932,6 +971,9 @@ label.reserved.system.gateway=\u4e88\u7d04\u6e08\u307f\u30b7\u30b9\u30c6\u30e0 \ label.reserved.system.ip=\u4e88\u7d04\u6e08\u307f\u30b7\u30b9\u30c6\u30e0 IP \u30a2\u30c9\u30ec\u30b9 label.reserved.system.netmask=\u4e88\u7d04\u6e08\u307f\u30b7\u30b9\u30c6\u30e0 \u30cd\u30c3\u30c8\u30de\u30b9\u30af label.reset.VPN.connection=VPN \u63a5\u7d9a\u306e\u30ea\u30bb\u30c3\u30c8 +label.resize.new.offering.id=\u65b0\u3057\u3044\u30aa\u30d5\u30a1\u30ea\u30f3\u30b0 +label.resize.new.size=\u65b0\u3057\u3044\u30b5\u30a4\u30ba (GB) +label.resize.shrink.ok=\u7e2e\u5c0f\u53ef\u80fd\u306b\u3059\u308b label.resource.limits=\u30ea\u30bd\u30fc\u30b9\u5236\u9650 label.resource.state=\u30ea\u30bd\u30fc\u30b9\u306e\u72b6\u614b label.resource=\u30ea\u30bd\u30fc\u30b9 @@ -1012,6 +1054,7 @@ label.specify.vlan=VLAN \u3092\u6307\u5b9a\u3059\u308b label.specify.vxlan=VXLAN \u3092\u6307\u5b9a\u3059\u308b label.SR.name = SR \u540d\u30e9\u30d9\u30eb label.srx=SRX +label.PA=Palo Alto label.start.IP=\u958b\u59cb IP \u30a2\u30c9\u30ec\u30b9 label.start.port=\u958b\u59cb\u30dd\u30fc\u30c8 label.start.reserved.system.IP=\u4e88\u7d04\u6e08\u307f\u958b\u59cb\u30b7\u30b9\u30c6\u30e0 IP \u30a2\u30c9\u30ec\u30b9 @@ -1053,6 +1096,7 @@ label.storage.tags=\u30b9\u30c8\u30ec\u30fc\u30b8 \u30bf\u30b0 label.storage.traffic=\u30b9\u30c8\u30ec\u30fc\u30b8 \u30c8\u30e9\u30d5\u30a3\u30c3\u30af label.storage.type=\u30b9\u30c8\u30ec\u30fc\u30b8\u306e\u7a2e\u985e label.qos.type=QoS \u306e\u7a2e\u985e +label.cache.mode=\u66f8\u304d\u8fbc\u307f\u30ad\u30e3\u30c3\u30b7\u30e5\u306e\u7a2e\u985e label.storage=\u30b9\u30c8\u30ec\u30fc\u30b8 label.subdomain.access=\u30b5\u30d6\u30c9\u30e1\u30a4\u30f3 \u30a2\u30af\u30bb\u30b9 label.submit=\u9001\u4fe1 @@ -1140,9 +1184,11 @@ label.virtual.machines=\u4eee\u60f3\u30de\u30b7\u30f3 label.virtual.network=\u4eee\u60f3\u30cd\u30c3\u30c8\u30ef\u30fc\u30af label.virtual.router=\u4eee\u60f3\u30eb\u30fc\u30bf\u30fc label.virtual.routers=\u4eee\u60f3\u30eb\u30fc\u30bf\u30fc -label.vlan.id=VLAN ID -label.vlan.range=VLAN \u306e\u7bc4\u56f2 -label.vlan=VLAN +label.vlan.id=VLAN/VNI ID +label.vlan.range=VLAN/VNI \u306e\u7bc4\u56f2 +label.vlan=VLAN/VNI +label.vnet=VLAN/VNI +label.vnet.id=VLAN/VNI ID label.vxlan.id=VXLAN ID label.vxlan.range=VXLAN \u306e\u7bc4\u56f2 label.vxlan=VXLAN @@ -1205,6 +1251,7 @@ label.zoneWizard.trafficType.guest=\u30b2\u30b9\u30c8\: \u30a8\u30f3\u30c9 \u30e label.zoneWizard.trafficType.management=\u7ba1\u7406\: \u30db\u30b9\u30c8\u3084 CloudStack \u30b7\u30b9\u30c6\u30e0 VM \u306a\u3069\u3001\u7ba1\u7406\u30b5\u30fc\u30d0\u30fc\u3068\u901a\u4fe1\u3059\u308b CloudStack \u306e\u5185\u90e8\u30ea\u30bd\u30fc\u30b9\u9593\u306e\u30c8\u30e9\u30d5\u30a3\u30c3\u30af\u3067\u3059\u3002 label.zoneWizard.trafficType.public=\u30d1\u30d6\u30ea\u30c3\u30af\: \u30a4\u30f3\u30bf\u30fc\u30cd\u30c3\u30c8\u3068\u30af\u30e9\u30a6\u30c9\u5185\u306e\u4eee\u60f3\u30de\u30b7\u30f3\u306e\u9593\u306e\u30c8\u30e9\u30d5\u30a3\u30c3\u30af\u3067\u3059\u3002 label.zoneWizard.trafficType.storage=\u30b9\u30c8\u30ec\u30fc\u30b8\: VM \u30c6\u30f3\u30d7\u30ec\u30fc\u30c8\u3084\u30b9\u30ca\u30c3\u30d7\u30b7\u30e7\u30c3\u30c8\u306a\u3069\u3001\u30d7\u30e9\u30a4\u30de\u30ea\u304a\u3088\u3073\u30bb\u30ab\u30f3\u30c0\u30ea \u30b9\u30c8\u30ec\u30fc\u30b8 \u30b5\u30fc\u30d0\u30fc\u9593\u306e\u30c8\u30e9\u30d5\u30a3\u30c3\u30af\u3067\u3059\u3002 +label.ldap.group.name=LDAP \u30b0\u30eb\u30fc\u30d7 managed.state=\u7ba1\u7406\u5bfe\u8c61\u72b6\u614b message.acquire.new.ip.vpc=\u3053\u306e VPC \u306e\u65b0\u3057\u3044 IP \u30a2\u30c9\u30ec\u30b9\u3092\u53d6\u5f97\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? message.acquire.new.ip=\u3053\u306e\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u306e\u65b0\u3057\u3044 IP \u30a2\u30c9\u30ec\u30b9\u3092\u53d6\u5f97\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? @@ -1251,6 +1298,7 @@ message.action.enable.nexusVswitch=\u3053\u306e Nexus 1000V \u3092\u6709\u52b9\u message.action.enable.physical.network=\u3053\u306e\u7269\u7406\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u3092\u6709\u52b9\u306b\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? message.action.enable.pod=\u3053\u306e\u30dd\u30c3\u30c9\u3092\u6709\u52b9\u306b\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? message.action.enable.zone=\u3053\u306e\u30be\u30fc\u30f3\u3092\u6709\u52b9\u306b\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? +message.action.expunge.instance=\u3053\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3092\u62b9\u6d88\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? message.action.force.reconnect=\u30db\u30b9\u30c8\u306f\u5f37\u5236\u7684\u306b\u518d\u63a5\u7d9a\u3057\u307e\u3057\u305f\u3002\u3053\u306e\u51e6\u7406\u306b\u306f\u6570\u5206\u304b\u304b\u308b\u53ef\u80fd\u6027\u304c\u3042\u308a\u307e\u3059\u3002 message.action.host.enable.maintenance.mode=\u4fdd\u5b88\u30e2\u30fc\u30c9\u3092\u6709\u52b9\u306b\u3059\u308b\u3068\u3001\u3053\u306e\u30db\u30b9\u30c8\u3067\u5b9f\u884c\u4e2d\u306e\u3059\u3079\u3066\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u304c\u307b\u304b\u306e\u4f7f\u7528\u3067\u304d\u308b\u30db\u30b9\u30c8\u306b\u30e9\u30a4\u30d6 \u30de\u30a4\u30b0\u30ec\u30fc\u30b7\u30e7\u30f3\u3055\u308c\u307e\u3059\u3002 message.action.instance.reset.password=\u3053\u306e\u4eee\u60f3\u30de\u30b7\u30f3\u306e\u30eb\u30fc\u30c8 \u30d1\u30b9\u30ef\u30fc\u30c9\u3092\u5909\u66f4\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? @@ -1271,7 +1319,10 @@ message.action.stop.instance=\u3053\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3 message.action.stop.router=\u3053\u306e\u4eee\u60f3\u30eb\u30fc\u30bf\u30fc\u3067\u63d0\u4f9b\u3059\u308b\u3059\u3079\u3066\u306e\u30b5\u30fc\u30d3\u30b9\u304c\u4e2d\u65ad\u3055\u308c\u307e\u3059\u3002\u3053\u306e\u30eb\u30fc\u30bf\u30fc\u3092\u505c\u6b62\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? message.action.stop.systemvm=\u3053\u306e\u30b7\u30b9\u30c6\u30e0 VM \u3092\u505c\u6b62\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? message.action.take.snapshot=\u3053\u306e\u30dc\u30ea\u30e5\u30fc\u30e0\u306e\u30b9\u30ca\u30c3\u30d7\u30b7\u30e7\u30c3\u30c8\u3092\u4f5c\u6210\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? +message.action.revert.snapshot=\u6240\u6709\u30dc\u30ea\u30e5\u30fc\u30e0\u3092\u3053\u306e\u30b9\u30ca\u30c3\u30d7\u30b7\u30e7\u30c3\u30c8\u306b\u623b\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? message.action.unmanage.cluster=\u30af\u30e9\u30b9\u30bf\u30fc\u3092\u975e\u7ba1\u7406\u5bfe\u8c61\u306b\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? +message.action.vmsnapshot.delete=\u3053\u306e VM \u30b9\u30ca\u30c3\u30d7\u30b7\u30e7\u30c3\u30c8\u3092\u524a\u9664\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? +message.action.vmsnapshot.revert=VM \u30b9\u30ca\u30c3\u30d7\u30b7\u30e7\u30c3\u30c8\u3092\u5143\u306b\u623b\u3059 message.activate.project=\u3053\u306e\u30d7\u30ed\u30b8\u30a7\u30af\u30c8\u3092\u30a2\u30af\u30c6\u30a3\u30d6\u306b\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? message.add.cluster.zone=\u30be\u30fc\u30f3 \u306b\u30cf\u30a4\u30d1\u30fc\u30d0\u30a4\u30b6\u30fc\u3067\u7ba1\u7406\u3055\u308c\u308b\u30af\u30e9\u30b9\u30bf\u30fc\u3092\u8ffd\u52a0\u3057\u307e\u3059 message.add.cluster=\u30be\u30fc\u30f3 \u306e\u30dd\u30c3\u30c9 \u306b\u30cf\u30a4\u30d1\u30fc\u30d0\u30a4\u30b6\u30fc\u3067\u7ba1\u7406\u3055\u308c\u308b\u30af\u30e9\u30b9\u30bf\u30fc\u3092\u8ffd\u52a0\u3057\u307e\u3059 @@ -1324,6 +1375,7 @@ message.confirm.action.force.reconnect=\u3053\u306e\u30db\u30b9\u30c8\u3092\u5f3 message.confirm.delete.F5=F5 \u3092\u524a\u9664\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? message.confirm.delete.NetScaler=NetScaler \u3092\u524a\u9664\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? message.confirm.delete.SRX=SRX \u3092\u524a\u9664\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? +message.confirm.delete.PA=Palo Alto \u3092\u524a\u9664\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? message.confirm.destroy.router=\u3053\u306e\u30eb\u30fc\u30bf\u30fc\u3092\u7834\u68c4\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? message.confirm.disable.provider=\u3053\u306e\u30d7\u30ed\u30d0\u30a4\u30c0\u30fc\u3092\u7121\u52b9\u306b\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? message.confirm.enable.provider=\u3053\u306e\u30d7\u30ed\u30d0\u30a4\u30c0\u30fc\u3092\u6709\u52b9\u306b\u3057\u3066\u3082\u3088\u308d\u3057\u3044\u3067\u3059\u304b? diff --git a/client/WEB-INF/classes/resources/messages_zh_CN.properties b/client/WEB-INF/classes/resources/messages_zh_CN.properties index acb67bb51f7..7cb65d3236b 100644 --- a/client/WEB-INF/classes/resources/messages_zh_CN.properties +++ b/client/WEB-INF/classes/resources/messages_zh_CN.properties @@ -14,6 +14,12 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. +label.hypervisors=\u865a\u62df\u673a\u7ba1\u7406\u7a0b\u5e8f +label.home=\u9996\u9875 +label.sockets=\u63d2\u69fd +label.root.disk.size=\u6839\u78c1\u76d8\u5927\u5c0f +label.s3.nfs.server=S3 NFS \u670d\u52a1\u5668 +label.s3.nfs.path=S3 NFS \u8def\u5f84 label.delete.events=\u5220\u9664\u4e8b\u4ef6 label.delete.alerts=\u5220\u9664\u8b66\u62a5 label.archive.alerts=\u5b58\u6863\u8b66\u62a5 @@ -33,6 +39,7 @@ label.custom.disk.iops=\u81ea\u5b9a\u4e49 IOPS label.disk.iops.min=\u6700\u5c0f IOPS label.disk.iops.max=\u6700\u5927 IOPS label.disk.iops.total=\u603b IOPS +label.hypervisor.snapshot.reserve=\u865a\u62df\u673a\u7ba1\u7406\u7a0b\u5e8f\u5feb\u7167\u9884\u7559 label.view.secondary.ips=\u67e5\u770b\u8f85\u52a9 IP message.validate.invalid.characters=\u67e5\u627e\u5230\u65e0\u6548\u5b57\u7b26\uff0c\u8bf7\u66f4\u6b63\u3002 message.acquire.ip.nic=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u83b7\u53d6\u6b64 NIC \u7684\u65b0\u8f85\u52a9 IP\u3002
\u6ce8\u610f: \u60a8\u9700\u8981\u5728\u865a\u62df\u673a\u5185\u90e8\u624b\u52a8\u914d\u7f6e\u65b0\u83b7\u53d6\u7684\u8f85\u52a9 IP\u3002 @@ -43,6 +50,7 @@ message.action.delete.nic=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u79fb\u9664 changed.item.properties=\u66f4\u6539\u9879\u76ee\u5c5e\u6027 confirm.enable.s3=\u8bf7\u586b\u5199\u4ee5\u4e0b\u4fe1\u606f\u4ee5\u542f\u7528\u5bf9 S3 \u652f\u6301\u7684\u8f85\u52a9\u5b58\u50a8\u7684\u652f\u6301 confirm.enable.swift=\u8bf7\u586b\u5199\u4ee5\u4e0b\u4fe1\u606f\u4ee5\u542f\u7528\u5bf9 SWIFT \u7684\u652f\u6301 +error.could.not.change.your.password.because.ldap.is.enabled=\u9519\u8bef\u3002LDAP \u5904\u4e8e\u542f\u7528\u72b6\u6001\uff0c\u65e0\u6cd5\u66f4\u6539\u60a8\u7684\u5bc6\u7801\u3002 error.could.not.enable.zone=\u65e0\u6cd5\u542f\u7528\u533a\u57df error.installWizard.message=\u51fa\u73b0\u95ee\u9898\uff1b\u8bf7\u8fd4\u56de\u5e76\u66f4\u6b63\u4efb\u4f55\u9519\u8bef error.invalid.username.password=\u7528\u6237\u540d\u6216\u5bc6\u7801\u65e0\u6548 @@ -199,6 +207,8 @@ label.action.enable.user.processing=\u6b63\u5728\u542f\u7528\u7528\u6237... label.action.enable.user=\u542f\u7528\u7528\u6237 label.action.enable.zone.processing=\u6b63\u5728\u542f\u7528\u533a\u57df... label.action.enable.zone=\u542f\u7528\u533a\u57df +label.action.expunge.instance=\u5220\u9664\u5b9e\u4f8b +label.action.expunge.instance.processing=\u6b63\u5728\u5220\u9664\u5b9e\u4f8b... label.action.force.reconnect.processing=\u6b63\u5728\u91cd\u65b0\u8fde\u63a5... label.action.force.reconnect=\u5f3a\u5236\u91cd\u65b0\u8fde\u63a5 label.action.generate.keys.processing=\u6b63\u5728\u751f\u6210\u5bc6\u94a5... @@ -248,6 +258,8 @@ label.action.stop.systemvm.processing=\u6b63\u5728\u505c\u6b62\u7cfb\u7edf VM... label.action.stop.systemvm=\u505c\u6b62\u7cfb\u7edf VM label.action.take.snapshot.processing=\u6b63\u5728\u521b\u5efa\u5feb\u7167... label.action.take.snapshot=\u521b\u5efa\u5feb\u7167 +label.action.revert.snapshot.processing=\u6b63\u5728\u8fd8\u539f\u5230\u5feb\u7167... +label.action.revert.snapshot=\u8fd8\u539f\u5230\u5feb\u7167 label.action.unmanage.cluster.processing=\u6b63\u5728\u53d6\u6d88\u6258\u7ba1\u7fa4\u96c6... label.action.unmanage.cluster=\u53d6\u6d88\u6258\u7ba1\u7fa4\u96c6 label.action.update.OS.preference.processing=\u6b63\u5728\u66f4\u65b0\u64cd\u4f5c\u7cfb\u7edf\u9996\u9009\u9879... @@ -293,6 +305,7 @@ label.add.new.F5=\u6dfb\u52a0\u65b0 F5 label.add.new.gateway=\u6dfb\u52a0\u65b0\u7f51\u5173 label.add.new.NetScaler=\u6dfb\u52a0\u65b0 NetScaler label.add.new.SRX=\u6dfb\u52a0\u65b0 SRX +label.add.new.PA=\u6dfb\u52a0\u65b0 Palo Alto label.add.new.tier=\u6dfb\u52a0\u65b0\u5c42 label.add.NiciraNvp.device=\u6dfb\u52a0 Nvp \u63a7\u5236\u5668 label.add.physical.network=\u6dfb\u52a0\u7269\u7406\u7f51\u7edc @@ -307,6 +320,7 @@ label.add.secondary.storage=\u6dfb\u52a0\u8f85\u52a9\u5b58\u50a8 label.add.security.group=\u6dfb\u52a0\u5b89\u5168\u7ec4 label.add.service.offering=\u6dfb\u52a0\u670d\u52a1\u65b9\u6848 label.add.SRX.device=\u6dfb\u52a0 SRX \u8bbe\u5907 +label.add.PA.device=\u6dfb\u52a0 Palo Alto \u8bbe\u5907 label.add.static.nat.rule=\u6dfb\u52a0\u9759\u6001 NAT \u89c4\u5219 label.add.static.route=\u6dfb\u52a0\u9759\u6001\u8def\u7531 label.add.system.service.offering=\u6dfb\u52a0\u7cfb\u7edf\u670d\u52a1\u65b9\u6848 @@ -412,6 +426,11 @@ label.cluster.type=\u7fa4\u96c6\u7c7b\u578b label.cluster=\u7fa4\u96c6 label.clusters=\u7fa4\u96c6 label.clvm=CLVM +label.rbd=RBD +label.rbd.monitor=Ceph \u76d1\u89c6\u5668 +label.rbd.pool=Ceph \u6c60 +label.rbd.id=Cephx \u7528\u6237 +label.rbd.secret=Cephx \u5bc6\u94a5 label.code=\u4ee3\u7801 label.community=\u793e\u533a label.compute.and.storage=\u8ba1\u7b97\u4e0e\u5b58\u50a8 @@ -463,6 +482,7 @@ label.delete.NetScaler=\u5220\u9664 NetScaler label.delete.NiciraNvp=\u79fb\u9664 Nvp \u63a7\u5236\u5668 label.delete.project=\u5220\u9664\u9879\u76ee label.delete.SRX=\u5220\u9664 SRX +label.delete.PA=\u5220\u9664 Palo Alto label.delete.VPN.connection=\u5220\u9664 VPN \u8fde\u63a5 label.delete.VPN.customer.gateway=\u5220\u9664 VPN \u5ba2\u6237\u7f51\u5173 label.delete.VPN.gateway=\u5220\u9664 VPN \u7f51\u5173 @@ -552,6 +572,7 @@ label.ESP.lifetime=ESP \u4f7f\u7528\u671f\u9650(\u7b2c\u4e8c\u9636\u6bb5) label.ESP.policy=ESP \u7b56\u7565 label.esx.host=ESX/ESXi \u4e3b\u673a label.example=\u793a\u4f8b +label.expunge=\u5220\u9664 label.external.link=\u5916\u90e8\u94fe\u63a5 label.f5=F5 label.failed=\u5931\u8d25 @@ -800,6 +821,7 @@ label.network.domain.text=\u7f51\u7edc\u57df label.network.domain=\u7f51\u7edc\u57df label.network.id=\u7f51\u7edc ID label.network.label.display.for.blank.value=\u4f7f\u7528\u9ed8\u8ba4\u7f51\u5173 +label.network.limits=\u7f51\u7edc\u9650\u5236 label.network.name=\u7f51\u7edc\u540d\u79f0 label.network.offering.display.text=\u7f51\u7edc\u65b9\u6848\u663e\u793a\u6587\u672c label.network.offering.id=\u7f51\u7edc\u65b9\u6848 ID @@ -858,6 +880,8 @@ label.os.type=\u64cd\u4f5c\u7cfb\u7edf\u7c7b\u578b label.owned.public.ips=\u62e5\u6709\u7684\u516c\u7528 IP \u5730\u5740\u6570 label.owner.account=\u6240\u6709\u8005\u5e10\u6237 label.owner.domain=\u6240\u6709\u8005\u57df +label.PA.log.profile=Palo Alto \u65e5\u5fd7\u914d\u7f6e\u6587\u4ef6 +label.PA.threat.profile=Palo Alto \u5a01\u80c1\u914d\u7f6e\u6587\u4ef6 label.parent.domain=\u7236\u57df label.password.enabled=\u5df2\u542f\u7528\u5bc6\u7801 label.password=\u5bc6\u7801 @@ -1030,11 +1054,12 @@ label.specify.vlan=\u6307\u5b9a VLAN label.specify.vxlan=\u6307\u5b9a VXLAN label.SR.name = SR \u540d\u79f0\u6807\u7b7e label.srx=SRX +label.PA=Palo Alto label.start.IP=\u8d77\u59cb IP label.start.port=\u8d77\u59cb\u7aef\u53e3 label.start.reserved.system.IP=\u8d77\u59cb\u9884\u7559\u7cfb\u7edf IP label.start.vlan=\u8d77\u59cb VLAN -label.start.vxlan=\u8d77\u59cb VXLAN +label.start.vxlan=\u542f\u52a8 VXLAN label.state=\u72b6\u6001 label.static.nat.enabled=\u5df2\u542f\u7528\u9759\u6001 NAT label.static.nat.to=\u9759\u6001 NAT \u76ee\u6807 @@ -1071,6 +1096,7 @@ label.storage.tags=\u5b58\u50a8\u6807\u7b7e label.storage.traffic=\u5b58\u50a8\u901a\u4fe1 label.storage.type=\u5b58\u50a8\u7c7b\u578b label.qos.type=QoS \u7c7b\u578b +label.cache.mode=\u5199\u5165\u7f13\u5b58\u7c7b\u578b label.storage=\u5b58\u50a8 label.subdomain.access=\u5b50\u57df\u8bbf\u95ee label.submit=\u63d0\u4ea4 @@ -1158,11 +1184,13 @@ label.virtual.machines=\u865a\u62df\u673a label.virtual.network=\u865a\u62df\u7f51\u7edc label.virtual.router=\u865a\u62df\u8def\u7531\u5668 label.virtual.routers=\u865a\u62df\u8def\u7531\u5668 -label.vlan.id=VLAN ID -label.vlan.range=VLAN \u8303\u56f4 -label.vlan=VLAN +label.vlan.id=VLAN/VNI ID +label.vlan.range=VLAN/VNI \u8303\u56f4 +label.vlan=VLAN/VNI +label.vnet=VLAN/VNI +label.vnet.id=VLAN/VNI ID label.vxlan.id=VXLAN ID -label.vxlan.range=VXLAN Range +label.vxlan.range=VXLAN \u8303\u56f4 label.vxlan=VXLAN label.vm.add=\u6dfb\u52a0\u5b9e\u4f8b label.vm.destroy=\u9500\u6bc1 @@ -1206,7 +1234,7 @@ label.weekly=\u6bcf\u5468 label.welcome.cloud.console=\u6b22\u8fce\u4f7f\u7528\u7ba1\u7406\u63a7\u5236\u53f0 label.welcome=\u6b22\u8fce label.what.is.cloudstack=\u4ec0\u4e48\u662f CloudStack&\#8482? -label.xen.traffic.label=XenServer \u6d41\u91cf\u6807\u7b7e +label.xen.traffic.label=XenServer \u901a\u4fe1\u6807\u7b7e label.yes=\u662f label.zone.details=\u533a\u57df\u8be6\u60c5 label.zone.id=\u533a\u57df ID @@ -1223,6 +1251,7 @@ label.zoneWizard.trafficType.guest=\u6765\u5bbe\: \u6700\u7ec8\u7528\u6237\u865a label.zoneWizard.trafficType.management=\u7ba1\u7406\: CloudStack \u7684\u5185\u90e8\u8d44\u6e90(\u5305\u62ec\u4e0e\u7ba1\u7406\u670d\u52a1\u5668\u901a\u4fe1\u7684\u4efb\u4f55\u7ec4\u4ef6\uff0c\u4f8b\u5982\u4e3b\u673a\u548c CloudStack \u7cfb\u7edf VM)\u4e4b\u95f4\u7684\u901a\u4fe1 label.zoneWizard.trafficType.public=\u516c\u7528\: \u4e91\u4e2d Internet \u4e0e\u865a\u62df\u673a\u4e4b\u95f4\u7684\u901a\u4fe1\u3002 label.zoneWizard.trafficType.storage=\u5b58\u50a8\: \u4e3b\u5b58\u50a8\u670d\u52a1\u5668\u4e0e\u8f85\u52a9\u5b58\u50a8\u670d\u52a1\u5668(\u4f8b\u5982 VM \u6a21\u677f\u4e0e\u5feb\u7167)\u4e4b\u95f4\u7684\u901a\u4fe1 +label.ldap.group.name=LDAP \u7ec4 managed.state=\u6258\u7ba1\u72b6\u6001 message.acquire.new.ip.vpc=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u4e3a\u6b64 VPC \u83b7\u53d6\u4e00\u4e2a\u65b0 IP\u3002 message.acquire.new.ip=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u4e3a\u6b64\u7f51\u7edc\u83b7\u53d6\u4e00\u4e2a\u65b0 IP\u3002 @@ -1269,6 +1298,7 @@ message.action.enable.nexusVswitch=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u5 message.action.enable.physical.network=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u542f\u7528\u6b64\u7269\u7406\u7f51\u7edc\u3002 message.action.enable.pod=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u542f\u7528\u6b64\u63d0\u4f9b\u70b9\u3002 message.action.enable.zone=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u542f\u7528\u6b64\u533a\u57df\u3002 +message.action.expunge.instance=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u5220\u9664\u6b64\u5b9e\u4f8b\u3002 message.action.force.reconnect=\u5df2\u6210\u529f\u5f3a\u5236\u91cd\u65b0\u8fde\u63a5\u60a8\u7684\u4e3b\u673a\u3002\u6b64\u8fc7\u7a0b\u53ef\u80fd\u9700\u8981\u957f\u8fbe\u51e0\u5206\u949f\u65f6\u95f4\u3002 message.action.host.enable.maintenance.mode=\u542f\u7528\u7ef4\u62a4\u6a21\u5f0f\u4f1a\u5bfc\u81f4\u5c06\u6b64\u4e3b\u673a\u4e0a\u6b63\u5728\u8fd0\u884c\u7684\u6240\u6709\u5b9e\u4f8b\u5b9e\u65f6\u8fc1\u79fb\u5230\u4efb\u4f55\u53ef\u7528\u7684\u4e3b\u673a\u3002 message.action.instance.reset.password=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u66f4\u6539\u6b64\u865a\u62df\u673a\u7684 ROOT \u7528\u6237\u5bc6\u7801\u3002 @@ -1289,6 +1319,7 @@ message.action.stop.instance=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u505c\u6 message.action.stop.router=\u6b64\u865a\u62df\u8def\u7531\u5668\u63d0\u4f9b\u7684\u6240\u6709\u670d\u52a1\u90fd\u5c06\u4e2d\u65ad\u3002\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u505c\u6b62\u6b64\u8def\u7531\u5668\u3002 message.action.stop.systemvm=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u505c\u6b62\u6b64\u7cfb\u7edf VM\u3002 message.action.take.snapshot=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u521b\u5efa\u6b64\u5377\u7684\u5feb\u7167\u3002 +message.action.revert.snapshot=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u5c06\u62e5\u6709\u7684\u5377\u8fd8\u539f\u4e3a\u6b64\u5feb\u7167\u3002 message.action.unmanage.cluster=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u53d6\u6d88\u6258\u7ba1\u6b64\u7fa4\u96c6\u3002 message.action.vmsnapshot.delete=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u5220\u9664\u6b64 VM \u5feb\u7167\u3002 message.action.vmsnapshot.revert=\u8fd8\u539f VM \u5feb\u7167 @@ -1344,6 +1375,7 @@ message.confirm.action.force.reconnect=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u898 message.confirm.delete.F5=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u5220\u9664 F5 message.confirm.delete.NetScaler=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u5220\u9664 NetScaler message.confirm.delete.SRX=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u5220\u9664 SRX +message.confirm.delete.PA=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u5220\u9664 Palo Alto message.confirm.destroy.router=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u9500\u6bc1\u6b64\u8def\u7531\u5668 message.confirm.disable.provider=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u7981\u7528\u6b64\u63d0\u4f9b\u7a0b\u5e8f message.confirm.enable.provider=\u8bf7\u786e\u8ba4\u60a8\u786e\u5b9e\u8981\u542f\u7528\u6b64\u63d0\u4f9b\u7a0b\u5e8f @@ -1412,7 +1444,7 @@ message.installWizard.copy.whatIsAHost=\u4e3b\u673a\u662f\u6307\u4e00\u53f0\u8ba message.installWizard.copy.whatIsAPod=\u4e00\u4e2a\u63d0\u4f9b\u70b9\u901a\u5e38\u4ee3\u8868\u4e00\u4e2a\u673a\u67b6\u3002\u540c\u4e00\u63d0\u4f9b\u70b9\u4e2d\u7684\u4e3b\u673a\u4f4d\u4e8e\u540c\u4e00\u5b50\u7f51\u4e2d\u3002

\u63d0\u4f9b\u70b9\u662f CloudStack&\#8482; \u90e8\u7f72\u4e2d\u7684\u7b2c\u4e8c\u5927\u7ec4\u7ec7\u5355\u4f4d\u3002\u63d0\u4f9b\u70b9\u5305\u542b\u5728\u533a\u57df\u4e2d\u3002\u6bcf\u4e2a\u533a\u57df\u4e2d\u53ef\u4ee5\u5305\u542b\u4e00\u4e2a\u6216\u591a\u4e2a\u63d0\u4f9b\u70b9\uff1b\u5728\u57fa\u672c\u5b89\u88c5\u4e2d\uff0c\u60a8\u7684\u533a\u57df\u4e2d\u5c06\u4ec5\u5305\u542b\u4e00\u4e2a\u63d0\u4f9b\u70b9\u3002 message.installWizard.copy.whatIsAZone=\u533a\u57df\u662f CloudStack&\#8482; \u90e8\u7f72\u4e2d\u6700\u5927\u7684\u7ec4\u7ec7\u5355\u4f4d\u3002\u867d\u7136\u5141\u8bb8\u4e00\u4e2a\u6570\u636e\u4e2d\u5fc3\u4e2d\u5b58\u5728\u591a\u4e2a\u533a\u57df\uff0c\u4f46\u662f\u4e00\u4e2a\u533a\u57df\u901a\u5e38\u4e0e\u4e00\u4e2a\u6570\u636e\u4e2d\u5fc3\u76f8\u5bf9\u5e94\u3002\u5c06\u57fa\u7840\u67b6\u6784\u7f16\u7ec4\u5230\u533a\u57df\u4e2d\u7684\u597d\u5904\u662f\u53ef\u4ee5\u63d0\u4f9b\u7269\u7406\u9694\u79bb\u548c\u5197\u4f59\u3002\u4f8b\u5982\uff0c\u6bcf\u4e2a\u533a\u57df\u90fd\u53ef\u4ee5\u62e5\u6709\u5404\u81ea\u7684\u7535\u6e90\u4f9b\u5e94\u548c\u7f51\u7edc\u4e0a\u884c\u65b9\u6848\uff0c\u5e76\u4e14\u5404\u533a\u57df\u53ef\u4ee5\u5728\u5730\u7406\u4f4d\u7f6e\u4e0a\u76f8\u9694\u5f88\u8fdc(\u867d\u7136\u5e76\u975e\u5fc5\u987b\u76f8\u9694\u5f88\u8fdc)\u3002 message.installWizard.copy.whatIsCloudStack=CloudStack&\#8482 \u662f\u4e00\u4e2a\u8f6f\u4ef6\u5e73\u53f0\uff0c\u53ef\u5c06\u8ba1\u7b97\u8d44\u6e90\u96c6\u4e2d\u5728\u4e00\u8d77\u4ee5\u6784\u5efa\u516c\u5171\u3001\u79c1\u6709\u548c\u6df7\u5408\u57fa\u7840\u8bbe\u65bd\u5373\u670d\u52a1(IaaS)\u4e91\u3002CloudStack&\#8482 \u8d1f\u8d23\u7ba1\u7406\u7ec4\u6210\u4e91\u57fa\u7840\u67b6\u6784\u7684\u7f51\u7edc\u3001\u5b58\u50a8\u548c\u8ba1\u7b97\u8282\u70b9\u3002\u4f7f\u7528 CloudStack&\#8482 \u53ef\u4ee5\u90e8\u7f72\u3001\u7ba1\u7406\u548c\u914d\u7f6e\u4e91\u8ba1\u7b97\u73af\u5883\u3002

CloudStack&\#8482 \u901a\u8fc7\u6269\u5c55\u5546\u7528\u786c\u4ef6\u4e0a\u8fd0\u884c\u7684\u6bcf\u4e2a\u865a\u62df\u673a\u6620\u50cf\u7684\u8303\u56f4\uff0c\u63d0\u4f9b\u4e86\u4e00\u4e2a\u5b9e\u65f6\u53ef\u7528\u7684\u4e91\u57fa\u7840\u67b6\u6784\u8f6f\u4ef6\u5806\u6808\u7528\u4e8e\u4ee5\u670d\u52a1\u65b9\u5f0f\u4ea4\u4ed8\u865a\u62df\u6570\u636e\u4e2d\u5fc3\uff0c\u5373\u4ea4\u4ed8\u6784\u5efa\u3001\u90e8\u7f72\u548c\u7ba1\u7406\u591a\u5c42\u6b21\u548c\u591a\u79df\u6237\u4e91\u5e94\u7528\u7a0b\u5e8f\u5fc5\u9700\u7684\u6240\u6709\u7ec4\u4ef6\u3002\u5f00\u6e90\u7248\u672c\u548c Premium \u7248\u672c\u90fd\u5df2\u53ef\u7528\uff0c\u4e14\u63d0\u4f9b\u7684\u529f\u80fd\u51e0\u4e4e\u5b8c\u5168\u76f8\u540c\u3002 -message.installWizard.copy.whatIsPrimaryStorage=CloudStack&\#8482; \u4e91\u57fa\u7840\u67b6\u6784\u4f7f\u7528\u4ee5\u4e0b\u4e24\u79cd\u7c7b\u578b\u7684\u5b58\u50a8: \u4e3b\u5b58\u50a8\u548c\u8f85\u52a9\u5b58\u50a8\u3002\u8fd9\u4e24\u79cd\u7c7b\u578b\u7684\u5b58\u50a8\u53ef\u4ee5\u662f iSCSI \u6216 NFS \u670d\u52a1\u5668\uff0c\u4e5f\u53ef\u4ee5\u662f\u672c\u5730\u78c1\u76d8\u3002

\u4e3b\u5b58\u50a8\u4e0e\u7fa4\u96c6\u76f8\u5173\u8054\uff0c\u7528\u4e8e\u5b58\u50a8\u8be5\u7fa4\u96c6\u4e2d\u7684\u4e3b\u673a\u4e0a\u6b63\u5728\u8fd0\u884c\u7684\u6240\u6709 VM \u5bf9\u5e94\u7684\u6bcf\u4e2a\u6765\u5bbe VM \u7684\u78c1\u76d8\u5377\u3002\u4e3b\u5b58\u50a8\u670d\u52a1\u5668\u901a\u5e38\u4f4d\u4e8e\u9760\u8fd1\u4e3b\u673a\u7684\u4f4d\u7f6e\u3002 +message.installWizard.copy.whatIsPrimaryStorage=CloudStack&\#8482; \u4e91\u57fa\u7840\u67b6\u6784\u4f7f\u7528\u4ee5\u4e0b\u4e24\u79cd\u7c7b\u578b\u7684\u5b58\u50a8\: \u4e3b\u5b58\u50a8\u548c\u8f85\u52a9\u5b58\u50a8\u3002\u8fd9\u4e24\u79cd\u7c7b\u578b\u7684\u5b58\u50a8\u53ef\u4ee5\u662f iSCSI \u6216 NFS \u670d\u52a1\u5668\uff0c\u4e5f\u53ef\u4ee5\u662f\u672c\u5730\u78c1\u76d8\u3002

\u4e3b\u5b58\u50a8\u4e0e\u7fa4\u96c6\u76f8\u5173\u8054\uff0c\u7528\u4e8e\u5b58\u50a8\u8be5\u7fa4\u96c6\u4e2d\u7684\u4e3b\u673a\u4e0a\u6b63\u5728\u8fd0\u884c\u7684\u6240\u6709 VM \u5bf9\u5e94\u7684\u6bcf\u4e2a\u6765\u5bbe VM \u7684\u78c1\u76d8\u5377\u3002\u4e3b\u5b58\u50a8\u670d\u52a1\u5668\u901a\u5e38\u4f4d\u4e8e\u9760\u8fd1\u4e3b\u673a\u7684\u4f4d\u7f6e\u3002 message.installWizard.copy.whatIsSecondaryStorage=\u8f85\u52a9\u5b58\u50a8\u4e0e\u533a\u57df\u76f8\u5173\u8054\uff0c\u7528\u4e8e\u5b58\u50a8\u4ee5\u4e0b\u9879\u76ee\:
  • \u6a21\u677f - \u53ef\u7528\u4e8e\u542f\u52a8 VM \u5e76\u53ef\u4ee5\u5305\u542b\u5176\u4ed6\u914d\u7f6e\u4fe1\u606f(\u4f8b\u5982\uff0c\u5df2\u5b89\u88c5\u7684\u5e94\u7528\u7a0b\u5e8f)\u7684\u64cd\u4f5c\u7cfb\u7edf\u6620\u50cf
  • ISO \u6620\u50cf - \u53ef\u91cd\u65b0\u542f\u52a8\u6216\u4e0d\u53ef\u91cd\u65b0\u542f\u52a8\u7684\u64cd\u4f5c\u7cfb\u7edf\u6620\u50cf
  • \u78c1\u76d8\u5377\u5feb\u7167 - \u5df2\u4fdd\u5b58\u7684 VM \u6570\u636e\u526f\u672c\uff0c\u53ef\u7528\u4e8e\u6267\u884c\u6570\u636e\u6062\u590d\u6216\u521b\u5efa\u65b0\u6a21\u677f
message.installWizard.now.building=\u73b0\u5728\u6b63\u5728\u6784\u5efa\u60a8\u7684\u4e91... message.installWizard.tooltip.addCluster.name=\u7fa4\u96c6\u7684\u540d\u79f0\u3002\u6b64\u540d\u79f0\u53ef\u4ee5\u662f\u60a8\u9009\u62e9\u7684\u6587\u672c\uff0c\u4e14\u672a\u7531 CloudStack \u4f7f\u7528\u3002 diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in index cb9dcf0b071..966b7c4227b 100644 --- a/client/tomcatconf/commands.properties.in +++ b/client/tomcatconf/commands.properties.in @@ -71,7 +71,7 @@ assignVirtualMachine=7 migrateVirtualMachine=1 migrateVirtualMachineWithVolume=1 recoverVirtualMachine=7 -expungeVirtualMachine=1 +expungeVirtualMachine=7 #### snapshot commands createSnapshot=15 @@ -246,6 +246,7 @@ deleteEvents=15 listAlerts=3 archiveAlerts=1 deleteAlerts=1 +generateAlert=1 #### system capacity commands listCapacity=3 @@ -502,6 +503,11 @@ createVirtualRouterElement=7 configureVirtualRouterElement=7 listVirtualRouterElements=7 +#### ovs commands +createOvsElement=7 +configureOvsElement=7 +listOvsElements=7 + #### usage commands generateUsageRecords=1 listUsageRecords=7 diff --git a/core/src/com/cloud/agent/api/MigrateCommand.java b/core/src/com/cloud/agent/api/MigrateCommand.java index 0d8f70cf047..e79c8a51bcf 100644 --- a/core/src/com/cloud/agent/api/MigrateCommand.java +++ b/core/src/com/cloud/agent/api/MigrateCommand.java @@ -24,15 +24,17 @@ public class MigrateCommand extends Command { String hostGuid; boolean isWindows; VirtualMachineTO vmTO; + boolean executeInSequence = false; protected MigrateCommand() { } - public MigrateCommand(String vmName, String destIp, boolean isWindows, VirtualMachineTO vmTO) { + public MigrateCommand(String vmName, String destIp, boolean isWindows, VirtualMachineTO vmTO, boolean executeInSequence) { this.vmName = vmName; this.destIp = destIp; this.isWindows = isWindows; this.vmTO = vmTO; + this.executeInSequence = executeInSequence; } public boolean isWindows() { @@ -61,6 +63,6 @@ public class MigrateCommand extends Command { @Override public boolean executeInSequence() { - return true; + return executeInSequence; } } diff --git a/core/src/com/cloud/agent/api/StopAnswer.java b/core/src/com/cloud/agent/api/StopAnswer.java index 6ced335ab3c..b5931747175 100755 --- a/core/src/com/cloud/agent/api/StopAnswer.java +++ b/core/src/com/cloud/agent/api/StopAnswer.java @@ -18,35 +18,28 @@ package com.cloud.agent.api; public class StopAnswer extends RebootAnswer { - private String hypervisortoolsversion; - Integer timeOffset; + private String platform; protected StopAnswer() { } - public StopAnswer(StopCommand cmd, String details, String hypervisortoolsversion, Integer timeOffset, boolean success) { - super(cmd, details, success); - this.hypervisortoolsversion = hypervisortoolsversion; - this.timeOffset = timeOffset; + public StopAnswer(StopCommand cmd, String details, String platform, boolean success) { + super(cmd, details, success); + this.platform = platform; } public StopAnswer(StopCommand cmd, String details, boolean success) { - super(cmd, details, success); - this.hypervisortoolsversion = null; - this.timeOffset = null; + super(cmd, details, success); + this.platform = null; } public StopAnswer(StopCommand cmd, Exception e) { super(cmd, e); - this.hypervisortoolsversion = null; - this.timeOffset = null; + this.platform = null; } - public String getHypervisorToolsVersion() { - return hypervisortoolsversion; + public String getPlatform() { + return platform; } - public Integer getTimeOffset() { - return timeOffset; - } } diff --git a/engine/api/src/com/cloud/vm/VirtualMachineManager.java b/engine/api/src/com/cloud/vm/VirtualMachineManager.java index c78942fbd05..7292d659f7e 100644 --- a/engine/api/src/com/cloud/vm/VirtualMachineManager.java +++ b/engine/api/src/com/cloud/vm/VirtualMachineManager.java @@ -49,7 +49,7 @@ import com.cloud.utils.fsm.NoTransitionException; */ 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 will be synchronized on the agent side." + "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); public interface Topics { @@ -145,9 +145,9 @@ public interface VirtualMachineManager extends Manager { /** * @param vmInstance - * @param newServiceOfferingId + * @param newServiceOffering */ - void checkIfCanUpgrade(VirtualMachine vmInstance, long newServiceOfferingId); + void checkIfCanUpgrade(VirtualMachine vmInstance, ServiceOffering newServiceOffering); /** * @param vmId 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 7379ed690a6..a9ccc06617a 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 @@ -39,6 +39,7 @@ import com.cloud.storage.Volume; import com.cloud.storage.Volume.Type; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; +import com.cloud.uservm.UserVm; import com.cloud.utils.fsm.NoTransitionException; import com.cloud.vm.DiskProfile; import com.cloud.vm.VirtualMachine; @@ -63,7 +64,7 @@ public interface VolumeOrchestrationService { String getVmNameOnVolume(Volume volume); - VolumeInfo createVolumeFromSnapshot(Volume volume, Snapshot snapshot) throws StorageUnavailableException; + VolumeInfo createVolumeFromSnapshot(Volume volume, Snapshot snapshot, UserVm vm) throws StorageUnavailableException; Volume migrateVolume(Volume volume, StoragePool destPool) throws StorageUnavailableException; diff --git a/engine/components-api/src/com/cloud/alert/AlertManager.java b/engine/components-api/src/com/cloud/alert/AlertManager.java index 5aea465f6ee..56a27df1b42 100755 --- a/engine/components-api/src/com/cloud/alert/AlertManager.java +++ b/engine/components-api/src/com/cloud/alert/AlertManager.java @@ -16,43 +16,13 @@ // under the License. package com.cloud.alert; +import org.apache.cloudstack.alert.AlertService; import org.apache.cloudstack.framework.config.ConfigKey; -import com.cloud.capacity.CapacityVO; import com.cloud.utils.component.Manager; -public interface AlertManager extends Manager { - public static final short ALERT_TYPE_MEMORY = CapacityVO.CAPACITY_TYPE_MEMORY; - public static final short ALERT_TYPE_CPU = CapacityVO.CAPACITY_TYPE_CPU; - public static final short ALERT_TYPE_STORAGE = CapacityVO.CAPACITY_TYPE_STORAGE; - public static final short ALERT_TYPE_STORAGE_ALLOCATED = CapacityVO.CAPACITY_TYPE_STORAGE_ALLOCATED; - public static final short ALERT_TYPE_VIRTUAL_NETWORK_PUBLIC_IP = CapacityVO.CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP; - public static final short ALERT_TYPE_PRIVATE_IP = CapacityVO.CAPACITY_TYPE_PRIVATE_IP; - public static final short ALERT_TYPE_SECONDARY_STORAGE = CapacityVO.CAPACITY_TYPE_SECONDARY_STORAGE; - public static final short ALERT_TYPE_HOST = 7; - public static final short ALERT_TYPE_USERVM = 8; - public static final short ALERT_TYPE_DOMAIN_ROUTER = 9; - public static final short ALERT_TYPE_CONSOLE_PROXY = 10; - public static final short ALERT_TYPE_ROUTING = 11; // lost connection to default route (to the gateway) - public static final short ALERT_TYPE_STORAGE_MISC = 12; // lost connection to default route (to the gateway) - public static final short ALERT_TYPE_USAGE_SERVER = 13; // lost connection to default route (to the gateway) - public static final short ALERT_TYPE_MANAGMENT_NODE = 14; // lost connection to default route (to the gateway) - public static final short ALERT_TYPE_DOMAIN_ROUTER_MIGRATE = 15; - public static final short ALERT_TYPE_CONSOLE_PROXY_MIGRATE = 16; - public static final short ALERT_TYPE_USERVM_MIGRATE = 17; - public static final short ALERT_TYPE_VLAN = 18; - public static final short ALERT_TYPE_SSVM = 19; - public static final short ALERT_TYPE_USAGE_SERVER_RESULT = 20; // Usage job result - public static final short ALERT_TYPE_STORAGE_DELETE = 21; - public static final short ALERT_TYPE_UPDATE_RESOURCE_COUNT = 22; // Generated when we fail to update the resource - // count - public static final short ALERT_TYPE_USAGE_SANITY_RESULT = 23; - public static final short ALERT_TYPE_DIRECT_ATTACHED_PUBLIC_IP = 24; - public static final short ALERT_TYPE_LOCAL_STORAGE = 25; - public static final short ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED = 26; // Generated when the resource limit exceeds the limit. Currently used for recurring snapshots only - - public static final short ALERT_TYPE_SYNC = 27; - +public interface AlertManager extends Manager, AlertService{ + static final ConfigKey StorageCapacityThreshold = new ConfigKey(Double.class, "cluster.storage.capacity.notificationthreshold", "Alert", "0.75", "Percentage (as a value between 0 and 1) of storage utilization above which alerts will be sent about low storage available.", true, ConfigKey.Scope.Cluster, null); @@ -65,9 +35,10 @@ public interface AlertManager extends Manager { "Alert", "0.75", "Percentage (as a value between 0 and 1) of allocated storage utilization above which alerts will be sent about low storage available.", true, ConfigKey.Scope.Cluster, null); - void clearAlert(short alertType, long dataCenterId, long podId); - - void sendAlert(short alertType, long dataCenterId, Long podId, String subject, String body); + void clearAlert(AlertType alertType, long dataCenterId, long podId); void recalculateCapacity(); + + void sendAlert(AlertType alertType, long dataCenterId, Long podId, String subject, String body); + } diff --git a/engine/components-api/src/com/cloud/capacity/CapacityManager.java b/engine/components-api/src/com/cloud/capacity/CapacityManager.java index 4332ede20dd..13624e69453 100755 --- a/engine/components-api/src/com/cloud/capacity/CapacityManager.java +++ b/engine/components-api/src/com/cloud/capacity/CapacityManager.java @@ -82,4 +82,13 @@ public interface CapacityManager { * @return true if the count of host's running VMs >= hypervisor limit */ boolean checkIfHostReachMaxGuestLimit(Host host); + + /** + * Check if specified host has capability to support cpu cores and speed freq + * @param hostId the host to be checked + * @param cpuNum cpu number to check + * @param cpuSpeed cpu Speed to check + * @return true if the count of host's running VMs >= hypervisor limit + */ + boolean checkIfHostHasCpuCapability(long hostId, Integer cpuNum, Integer cpuSpeed); } diff --git a/engine/components-api/src/com/cloud/event/UsageEventUtils.java b/engine/components-api/src/com/cloud/event/UsageEventUtils.java index e71afb015db..90a2f17f1b8 100644 --- a/engine/components-api/src/com/cloud/event/UsageEventUtils.java +++ b/engine/components-api/src/com/cloud/event/UsageEventUtils.java @@ -153,11 +153,16 @@ public class UsageEventUtils { if (account == null) return; + // if an invalid zone is passed in, create event without zone UUID + String zoneUuid = null; + if (dc != null) + zoneUuid = dc.getUuid(); + Event event = new Event(Name, EventCategory.USAGE_EVENT.getName(), usageEventType, resourceType, resourceUUID); Map eventDescription = new HashMap(); eventDescription.put("account", account.getUuid()); - eventDescription.put("zone", dc.getUuid()); + eventDescription.put("zone", zoneUuid); eventDescription.put("event", usageEventType); eventDescription.put("resource", resourceType); eventDescription.put("id", resourceUUID); 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 880002cd538..0c76f008c32 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 @@ -20,11 +20,16 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" + xmlns:util="http://www.springframework.org/schema/util" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd - http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd + http://www.springframework.org/schema/aop + http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context - http://www.springframework.org/schema/context/spring-context-3.0.xsd" + http://www.springframework.org/schema/context/spring-context-3.0.xsd + http://www.springframework.org/schema/util + http://www.springframework.org/schema/util/spring-util-3.0.xsd" > + + + + + diff --git a/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java b/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java index 1e8b1488c9c..42648df9a89 100755 --- a/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java +++ b/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java @@ -818,7 +818,7 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl HostPodVO podVO = _podDao.findById(host.getPodId()); String hostDesc = "name: " + host.getName() + " (id:" + host.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName(); if ((host.getType() != Host.Type.SecondaryStorage) && (host.getType() != Host.Type.ConsoleProxy)) { - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Host disconnected, " + hostDesc, + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Host disconnected, " + hostDesc, "If the agent for host [" + hostDesc + "] is not restarted within " + AlertWait + " seconds, HA will begin on the VMs"); } event = Status.Event.AgentDisconnected; @@ -828,8 +828,8 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl 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.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Host in ALERT state, " + hostDesc, - "In availability zone " + host.getDataCenterId() + ", host is in alert state: " + host.getId() + "-" + host.getName()); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Host in ALERT state, " + hostDesc, "In availability zone " + host.getDataCenterId() + + ", host is in alert state: " + host.getId() + "-" + host.getName()); } } else { s_logger.debug("The next status of Agent " + host.getId() + " is not Alert, no need to investigate what happened"); @@ -1201,11 +1201,11 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl String hostDesc = "name: " + host.getName() + " (id:" + host.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName(); - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_ROUTING, host.getDataCenterId(), host.getPodId(), + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_ROUTING, host.getDataCenterId(), host.getPodId(), "Host lost connection to gateway, " + hostDesc, "Host [" + hostDesc + "] lost connection to gateway (default route) and is possibly having network connection issues."); } else { - _alertMgr.clearAlert(AlertManager.ALERT_TYPE_ROUTING, host.getDataCenterId(), host.getPodId()); + _alertMgr.clearAlert(AlertManager.AlertType.ALERT_TYPE_ROUTING, host.getDataCenterId(), host.getPodId()); } } else { s_logger.debug("Not processing " + PingRoutingCommand.class.getSimpleName() + " for agent id=" + cmdHostId + diff --git a/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java b/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java index a73d5a50d9d..d1fd2a7c899 100755 --- a/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java +++ b/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java @@ -94,7 +94,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.nio.Link; import com.cloud.utils.nio.Task; -@Local(value = {AgentManager.class, ClusteredAgentRebalanceService.class}) +@Local(value = { AgentManager.class, ClusteredAgentRebalanceService.class }) public class ClusteredAgentManagerImpl extends AgentManagerImpl implements ClusterManagerListener, ClusteredAgentRebalanceService { final static Logger s_logger = Logger.getLogger(ClusteredAgentManagerImpl.class); private static final ScheduledExecutorService s_transferExecutor = Executors.newScheduledThreadPool(2, new NamedThreadFactory("Cluster-AgentRebalancingExecutor")); @@ -108,7 +108,6 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust protected HashMap _peers; protected HashMap _sslEngines; private final Timer _timer = new Timer("ClusteredAgentManager Timer"); - private final Timer _agentLbTimer = new Timer("ClusteredAgentManager AgentRebalancing Timer"); boolean _agentLbHappened = false; @Inject @@ -129,13 +128,13 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } protected final ConfigKey EnableLB = new ConfigKey(Boolean.class, "agent.lb.enabled", "Advanced", "false", - "Enable agent load balancing between management server nodes", true); + "Enable agent load balancing between management server nodes", true); protected final ConfigKey ConnectedAgentThreshold = new ConfigKey(Double.class, "agent.load.threshold", "Advanced", "0.7", - "What percentage of the agents can be held by one management server before load balancing happens", true); + "What percentage of the agents can be held by one management server before load balancing happens", true); protected final ConfigKey LoadSize = new ConfigKey(Integer.class, "direct.agent.load.size", "Advanced", "16", - "How many agents to connect to in each round", true); + "How many agents to connect to in each round", true); protected final ConfigKey ScanInterval = new ConfigKey(Integer.class, "direct.agent.scan.interval", "Advanced", "90", - "Interval between scans to load agents", false, ConfigKey.Scope.Global, 1000); + "Interval between scans to load agents", false, ConfigKey.Scope.Global, 1000); @Override public boolean configure(String name, Map xmlParams) throws ConfigurationException { @@ -277,9 +276,9 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust @Override protected AgentAttache createAttacheForDirectConnect(Host host, ServerResource resource) { -// if (resource instanceof DummySecondaryStorageResource) { -// return new DummyAttache(this, host.getId(), false); -// } +// if (resource instanceof DummySecondaryStorageResource) { +// return new DummyAttache(this, host.getId(), false); +// } s_logger.debug("create ClusteredDirectAgentAttache for " + host.getId()); final DirectAgentAttache attache = new ClusteredDirectAgentAttache(this, host.getId(), host.getName(), _nodeId, resource, host.isInMaintenanceStates(), this); AgentAttache old = null; @@ -329,23 +328,23 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } AgentAttache attache = findAttache(hostId); if (attache != null) { - //don't process disconnect if the host is being rebalanced + // don't process disconnect if the host is being rebalanced if (isAgentRebalanceEnabled()) { HostTransferMapVO transferVO = _hostTransferDao.findById(hostId); if (transferVO != null) { if (transferVO.getFutureOwner() == _nodeId && transferVO.getState() == HostTransferState.TransferStarted) { s_logger.debug("Not processing " + Event.AgentDisconnected + " event for the host id=" + hostId + " as the host is being connected to " + - _nodeId); + _nodeId); return true; } } } - //don't process disconnect if the disconnect came for the host via delayed cluster notification, - //but the host has already reconnected to the current management server + // don't process disconnect if the disconnect came for the host via delayed cluster notification, + // but the host has already reconnected to the current management server if (!attache.forForward()) { s_logger.debug("Not processing " + Event.AgentDisconnected + " event for the host id=" + hostId + - " as the host is directly connected to the current management server " + _nodeId); + " as the host is directly connected to the current management server " + _nodeId); return true; } @@ -376,7 +375,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust public void notifyNodesInCluster(AgentAttache attache) { s_logger.debug("Notifying other nodes of to disconnect"); - Command[] cmds = new Command[] {new ChangeAgentCommand(attache.getId(), Event.AgentDisconnected)}; + Command[] cmds = new Command[] { new ChangeAgentCommand(attache.getId(), Event.AgentDisconnected) }; _clusterMgr.broadcast(attache.getId(), _gson.toJson(cmds)); } @@ -385,23 +384,23 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust if (s_logger.isDebugEnabled()) { s_logger.debug("Notifying other MS nodes to run host scan task"); } - Command[] cmds = new Command[] {new ScheduleHostScanTaskCommand()}; + Command[] cmds = new Command[] { new ScheduleHostScanTaskCommand() }; _clusterMgr.broadcast(0, _gson.toJson(cmds)); } protected static void logT(byte[] bytes, final String msg) { s_logger.trace("Seq " + Request.getAgentId(bytes) + "-" + Request.getSequence(bytes) + ": MgmtId " + Request.getManagementServerId(bytes) + ": " + - (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); + (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); } protected static void logD(byte[] bytes, final String msg) { s_logger.debug("Seq " + Request.getAgentId(bytes) + "-" + Request.getSequence(bytes) + ": MgmtId " + Request.getManagementServerId(bytes) + ": " + - (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); + (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); } protected static void logI(byte[] bytes, final String msg) { s_logger.info("Seq " + Request.getAgentId(bytes) + "-" + Request.getSequence(bytes) + ": MgmtId " + Request.getManagementServerId(bytes) + ": " + - (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); + (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); } public boolean routeToPeer(String peer, byte[] bytes) { @@ -426,7 +425,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust if (s_logger.isDebugEnabled()) { logD(bytes, "Routing to peer"); } - Link.write(ch, new ByteBuffer[] {ByteBuffer.wrap(bytes)}, sslEngine); + Link.write(ch, new ByteBuffer[] { ByteBuffer.wrap(bytes) }, sslEngine); return true; } catch (IOException e) { try { @@ -568,9 +567,8 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } } _timer.cancel(); - _agentLbTimer.cancel(); - //cancel all transfer tasks + // cancel all transfer tasks s_transferExecutor.shutdownNow(); cleanupTransferMap(_nodeId); @@ -620,14 +618,15 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } Request req = Request.parse(data); Command[] cmds = req.getCommands(); - CancelCommand cancel = (CancelCommand)cmds[0]; + CancelCommand cancel = (CancelCommand) cmds[0]; if (s_logger.isDebugEnabled()) { logD(data, "Cancel request received"); } agent.cancel(cancel.getSequence()); final Long current = agent._currentSequence; - //if the request is the current request, always have to trigger sending next request in sequence, - //otherwise the agent queue will be blocked + // if the request is the current request, always have to trigger sending next request in +// sequence, + // otherwise the agent queue will be blocked if (req.executeInSequence() && (current != null && current == Request.getSequence(data))) { agent.sendNext(Request.getSequence(data)); } @@ -648,7 +647,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust return; } else { if (agent instanceof Routable) { - Routable cluster = (Routable)agent; + Routable cluster = (Routable) agent; cluster.routeToAgent(data); } else { agent.send(Request.parse(data)); @@ -665,7 +664,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust if (mgmtId != -1 && mgmtId != _nodeId) { routeToPeer(Long.toString(mgmtId), data); if (Request.requiresSequentialExecution(data)) { - AgentAttache attache = (AgentAttache)link.attachment(); + AgentAttache attache = (AgentAttache) link.attachment(); if (attache != null) { attache.sendNext(Request.getSequence(data)); } else if (s_logger.isDebugEnabled()) { @@ -727,7 +726,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust @Override public boolean executeRebalanceRequest(long agentId, long currentOwnerId, long futureOwnerId, Event event) throws AgentUnavailableException, - OperationTimedoutException { + OperationTimedoutException { boolean result = false; if (event == Event.RequestAgentRebalance) { return setToWaitForRebalance(agentId, currentOwnerId, futureOwnerId); @@ -794,7 +793,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } else { if (s_logger.isDebugEnabled()) { s_logger.debug("There are no hosts to rebalance in the system. Current number of active management server nodes in the system is " + allMS.size() + - "; number of managed agents is " + allManagedAgents.size()); + "; number of managed agents is " + allManagedAgents.size()); } return; } @@ -849,7 +848,8 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust if (s_logger.isDebugEnabled()) { s_logger.debug("Removing mapping from op_host_transfer as it failed to be set to transfer mode"); } - //just remove the mapping (if exists) as nothing was done on the peer management server yet + // just remove the mapping (if exists) as nothing was done on the peer management +// server yet _hostTransferDao.remove(transfer.getId()); } } @@ -934,7 +934,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust synchronized (_agentToTransferIds) { if (_agentToTransferIds.size() > 0) { s_logger.debug("Found " + _agentToTransferIds.size() + " agents to transfer"); - //for (Long hostId : _agentToTransferIds) { + // for (Long hostId : _agentToTransferIds) { for (Iterator iterator = _agentToTransferIds.iterator(); iterator.hasNext();) { Long hostId = iterator.next(); AgentAttache attache = findAttache(hostId); @@ -947,7 +947,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust // no need to do anything with the real attache as we haven't modified it yet Date cutTime = DateUtil.currentGMTTime(); HostTransferMapVO transferMap = - _hostTransferDao.findActiveHostTransferMapByHostId(hostId, new Date(cutTime.getTime() - rebalanceTimeOut)); + _hostTransferDao.findActiveHostTransferMapByHostId(hostId, new Date(cutTime.getTime() - rebalanceTimeOut)); if (transferMap == null) { s_logger.debug("Timed out waiting for the host id=" + hostId + " to be ready to transfer, skipping rebalance for the host"); @@ -966,7 +966,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust ManagementServerHostVO ms = _mshostDao.findByMsid(transferMap.getFutureOwner()); if (ms != null && ms.getState() != ManagementServerHost.State.Up) { s_logger.debug("Can't transfer host " + hostId + " as it's future owner is not in UP state: " + ms + - ", skipping rebalance for the host"); + ", skipping rebalance for the host"); iterator.remove(); _hostTransferDao.completeAgentTransfer(hostId); continue; @@ -983,7 +983,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } else { s_logger.debug("Agent " + hostId + " can't be transfered yet as its request queue size is " + attache.getQueueSize() + - " and listener queue size is " + attache.getNonRecurringListenersSize()); + " and listener queue size is " + attache.getNonRecurringListenersSize()); } } } else { @@ -1050,7 +1050,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust if (result) { if (s_logger.isDebugEnabled()) { s_logger.debug("Loading directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + - " as a part of rebalance process"); + " as a part of rebalance process"); } result = loadDirectlyConnectedHost(host, true); } else { @@ -1059,16 +1059,16 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } catch (Exception ex) { s_logger.warn("Failed to load directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + - " as a part of rebalance process due to:", ex); + " as a part of rebalance process due to:", ex); result = false; } if (result) { s_logger.debug("Successfully loaded directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + - " as a part of rebalance process"); + " as a part of rebalance process"); } else { s_logger.warn("Failed to load directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + - " as a part of rebalance process"); + " as a part of rebalance process"); } } @@ -1089,18 +1089,18 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust return; } - ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache)attache; + ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache) attache; if (success) { - //1) Set transfer mode to false - so the agent can start processing requests normally + // 1) Set transfer mode to false - so the agent can start processing requests normally forwardAttache.setTransferMode(false); - //2) Get all transfer requests and route them to peer + // 2) Get all transfer requests and route them to peer Request requestToTransfer = forwardAttache.getRequestToTransfer(); while (requestToTransfer != null) { s_logger.debug("Forwarding request " + requestToTransfer.getSequence() + " held in transfer attache " + hostId + " from the management server " + - _nodeId + " to " + futureOwnerId); + _nodeId + " to " + futureOwnerId); boolean routeResult = routeToPeer(Long.toString(futureOwnerId), requestToTransfer.getBytes()); if (!routeResult) { logD(requestToTransfer.getBytes(), "Failed to route request to peer"); @@ -1138,10 +1138,10 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } synchronized (_agents) { - ClusteredDirectAgentAttache attache = (ClusteredDirectAgentAttache)_agents.get(hostId); + ClusteredDirectAgentAttache attache = (ClusteredDirectAgentAttache) _agents.get(hostId); if (attache != null && attache.getQueueSize() == 0 && attache.getNonRecurringListenersSize() == 0) { handleDisconnectWithoutInvestigation(attache, Event.StartAgentRebalance, true, true); - ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache)createAttache(hostId); + ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache) createAttache(hostId); if (forwardAttache == null) { s_logger.warn("Unable to create a forward attache for the host " + hostId + " as a part of rebalance process"); return false; @@ -1154,7 +1154,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust s_logger.warn("Attache for the agent " + hostId + " no longer exists on management server " + _nodeId + ", can't start host rebalancing"); } else { s_logger.warn("Attache for the agent " + hostId + " has request queue size= " + attache.getQueueSize() + " and listener queue size " + - attache.getNonRecurringListenersSize() + ", can't start host rebalancing"); + attache.getNonRecurringListenersSize() + ", can't start host rebalancing"); } return false; } @@ -1211,7 +1211,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust // Scheduling host scan task in peer MS is a best effort operation during host add, regular host scan // happens at fixed intervals anyways. So handling any exceptions that may be thrown s_logger.warn("Exception happened while trying to schedule host scan task on mgmt server " + _clusterMgr.getSelfPeerName() + - ", ignoring as regular host scan happens at fixed interval anyways", e); + ", ignoring as regular host scan happens at fixed interval anyways", e); return null; } @@ -1249,8 +1249,8 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust s_logger.error("Excection in gson decoding : ", e); } - if (cmds.length == 1 && cmds[0] instanceof ChangeAgentCommand) { //intercepted - ChangeAgentCommand cmd = (ChangeAgentCommand)cmds[0]; + if (cmds.length == 1 && cmds[0] instanceof ChangeAgentCommand) { // intercepted + ChangeAgentCommand cmd = (ChangeAgentCommand) cmds[0]; if (s_logger.isDebugEnabled()) { s_logger.debug("Intercepting command for agent change: agent " + cmd.getAgentId() + " event: " + cmd.getEvent()); @@ -1271,7 +1271,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust answers[0] = new ChangeAgentAnswer(cmd, result); return _gson.toJson(answers); } else if (cmds.length == 1 && cmds[0] instanceof TransferAgentCommand) { - TransferAgentCommand cmd = (TransferAgentCommand)cmds[0]; + TransferAgentCommand cmd = (TransferAgentCommand) cmds[0]; if (s_logger.isDebugEnabled()) { s_logger.debug("Intercepting command for agent rebalancing: agent " + cmd.getAgentId() + " event: " + cmd.getEvent()); @@ -1294,7 +1294,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust answers[0] = new Answer(cmd, result, null); return _gson.toJson(answers); } else if (cmds.length == 1 && cmds[0] instanceof PropagateResourceEventCommand) { - PropagateResourceEventCommand cmd = (PropagateResourceEventCommand)cmds[0]; + PropagateResourceEventCommand cmd = (PropagateResourceEventCommand) cmds[0]; s_logger.debug("Intercepting command to propagate event " + cmd.getEvent().name() + " for host " + cmd.getHostId()); @@ -1311,7 +1311,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust answers[0] = new Answer(cmd, result, null); return _gson.toJson(answers); } else if (cmds.length == 1 && cmds[0] instanceof ScheduleHostScanTaskCommand) { - ScheduleHostScanTaskCommand cmd = (ScheduleHostScanTaskCommand)cmds[0]; + ScheduleHostScanTaskCommand cmd = (ScheduleHostScanTaskCommand) cmds[0]; String response = handleScheduleHostScanTaskCommand(cmd); return response; } @@ -1328,14 +1328,14 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust if (s_logger.isDebugEnabled()) { s_logger.debug("Completed dispatching -> " + pdu.getAgentId() + ", json: " + pdu.getJsonPackage() + " in " + - (System.currentTimeMillis() - startTick) + " ms, return result: " + jsonReturn); + (System.currentTimeMillis() - startTick) + " ms, return result: " + jsonReturn); } return jsonReturn; } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Completed dispatching -> " + pdu.getAgentId() + ", json: " + pdu.getJsonPackage() + " in " + - (System.currentTimeMillis() - startTick) + " ms, return null result"); + (System.currentTimeMillis() - startTick) + " ms, return null result"); } } } catch (AgentUnavailableException e) { @@ -1369,7 +1369,8 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust if (s_logger.isTraceEnabled()) { s_logger.trace("Agent rebalance task check, management server id:" + _nodeId); } - //initiate agent lb task will be scheduled and executed only once, and only when number of agents loaded exceeds _connectedAgentsThreshold + // initiate agent lb task will be scheduled and executed only once, and only when number of agents +// loaded exceeds _connectedAgentsThreshold if (!_agentLbHappened) { QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getManagementServerId(), Op.NNULL); @@ -1385,12 +1386,12 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust double load = managedHostsCount / allHostsCount; if (load >= ConnectedAgentThreshold.value()) { s_logger.debug("Scheduling agent rebalancing task as the average agent load " + load + " is more than the threshold " + - ConnectedAgentThreshold.value()); + ConnectedAgentThreshold.value()); scheduleRebalanceAgents(); _agentLbHappened = true; } else { s_logger.debug("Not scheduling agent rebalancing task as the averages load " + load + " is less than the threshold " + - ConnectedAgentThreshold.value()); + ConnectedAgentThreshold.value()); } } } diff --git a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java index 3a3de701f9f..1cac898f927 100755 --- a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java +++ b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java @@ -40,8 +40,6 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.log4j.Logger; - import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; @@ -69,6 +67,7 @@ import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.storage.to.VolumeObjectTO; import org.apache.cloudstack.utils.identity.ManagementServerNode; +import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.Listener; @@ -965,15 +964,15 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.info("The guru did not like the answers so stopping " + vm); } - StopCommand cmd = new StopCommand(vm, ExecuteInSequence.value()); - StopAnswer answer = (StopAnswer)_agentMgr.easySend(destHostId, cmd); - if (answer != null) { - String hypervisortoolsversion = answer.getHypervisorToolsVersion(); - if (hypervisortoolsversion != null) { - if (vm.getType() == VirtualMachine.Type.User) { + StopCommand cmd = new StopCommand(vm, ExecuteInSequence.value()); + StopAnswer answer = (StopAnswer) _agentMgr.easySend(destHostId, cmd); + if ( answer != null ) { + if (vm.getType() == VirtualMachine.Type.User) { + String platform = answer.getPlatform(); + if (platform != null) { UserVmVO userVm = _userVmDao.findById(vm.getId()); _userVmDao.loadDetails(userVm); - userVm.setDetail("hypervisortoolsversion", hypervisortoolsversion); + userVm.setDetail("platform", platform); _userVmDao.saveDetails(userVm); } } @@ -1129,14 +1128,14 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac VirtualMachine vm = profile.getVirtualMachine(); StopCommand stop = new StopCommand(vm, ExecuteInSequence.value()); try { - StopAnswer answer = (StopAnswer)_agentMgr.send(vm.getHostId(), stop); - if (answer != null) { - String hypervisortoolsversion = answer.getHypervisorToolsVersion(); - if (hypervisortoolsversion != null) { - if (vm.getType() == VirtualMachine.Type.User) { + StopAnswer answer = (StopAnswer) _agentMgr.send(vm.getHostId(), stop); + if ( answer != null ) { + if (vm.getType() == VirtualMachine.Type.User) { + String platform = answer.getPlatform(); + if (platform != null) { UserVmVO userVm = _userVmDao.findById(vm.getId()); _userVmDao.loadDetails(userVm); - userVm.setDetail("hypervisortoolsversion", hypervisortoolsversion); + userVm.setDetail("platform", platform); _userVmDao.saveDetails(userVm); } } @@ -1369,14 +1368,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac StopAnswer answer = null; try { answer = (StopAnswer)_agentMgr.send(vm.getHostId(), stop); - - if (answer != null) { - String hypervisortoolsversion = answer.getHypervisorToolsVersion(); - if (hypervisortoolsversion != null) { - if (vm.getType() == VirtualMachine.Type.User) { + if ( answer != null ) { + if (vm.getType() == VirtualMachine.Type.User) { + String platform = answer.getPlatform(); + if ( platform != null) { UserVmVO userVm = _userVmDao.findById(vm.getId()); _userVmDao.loadDetails(userVm); - userVm.setDetail("hypervisortoolsversion", hypervisortoolsversion); + userVm.setDetail("platform", platform); _userVmDao.saveDetails(userVm); } } @@ -1384,16 +1382,6 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac stopped = answer.getResult(); if (!stopped) { throw new CloudRuntimeException("Unable to stop the virtual machine due to " + answer.getDetails()); - } else { - Integer timeoffset = answer.getTimeOffset(); - if (timeoffset != null) { - if (vm.getType() == VirtualMachine.Type.User) { - UserVmVO userVm = _userVmDao.findById(vm.getId()); - _userVmDao.loadDetails(userVm); - userVm.setDetail("timeoffset", timeoffset.toString()); - _userVmDao.saveDetails(userVm); - } - } } vmGuru.finalizeStop(profile, answer); @@ -1676,11 +1664,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new CloudRuntimeException("VM is not Running, unable to migrate the vm currently " + vm + " , current state: " + vm.getState().toString()); } - short alertType = AlertManager.ALERT_TYPE_USERVM_MIGRATE; + AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM_MIGRATE; if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) { - alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE; + alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE; } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) { - alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY_MIGRATE; + alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE; } VirtualMachineProfile vmSrc = new VirtualMachineProfileImpl(vm); @@ -1735,7 +1723,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac boolean migrated = false; try { boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows"); - MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows, to); + MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows, to, ExecuteInSequence.value()); mc.setHostGuid(dest.getHost().getGuid()); try { @@ -1936,11 +1924,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac " doesn't involve migrating the volumes."); } - short alertType = AlertManager.ALERT_TYPE_USERVM_MIGRATE; + AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM_MIGRATE; if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) { - alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE; + alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE; } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) { - alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY_MIGRATE; + alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE; } _networkMgr.prepareNicForMigration(profile, destination); @@ -2066,8 +2054,16 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } Host host = _hostDao.findById(hostId); + Long poolId = null; + List vols = _volsDao.findReadyRootVolumesByInstance(vm.getId()); + for (VolumeVO rootVolumeOfVm : vols) { + StoragePoolVO rootDiskPool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId()); + if (rootDiskPool != null) { + poolId = rootDiskPool.getId(); + } + } - DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, null, null); + DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, poolId, null); ExcludeList excludes = new ExcludeList(); excludes.addHost(hostId); @@ -2555,13 +2551,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac if (agentState == State.Error) { agentState = State.Stopped; - short alertType = AlertManager.ALERT_TYPE_USERVM; + AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM; if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) { - alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER; + alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER; } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) { - alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY; + alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY; } else if (VirtualMachine.Type.SecondaryStorageVm.equals(vm.getType())) { - alertType = AlertManager.ALERT_TYPE_SSVM; + alertType = AlertManager.AlertType.ALERT_TYPE_SSVM; } HostPodVO podVO = _podDao.findById(vm.getPodIdToDeployIn()); @@ -2573,21 +2569,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac ") stopped on host " + hostDesc + " due to storage failure", "Virtual Machine " + vm.getInstanceName() + " (id: " + vm.getId() + ") running on host [" + vm.getHostId() + "] stopped due to storage failure."); } - // track hypervsion tools version - if (info.hvtoolsversion != null && !info.hvtoolsversion.isEmpty()) { + // track platform info + if( info.platform != null && !info.platform.isEmpty() ) { if (vm.getType() == VirtualMachine.Type.User) { UserVmVO userVm = _userVmDao.findById(vm.getId()); _userVmDao.loadDetails(userVm); - userVm.setDetail("hypervisortoolsversion", info.hvtoolsversion); - _userVmDao.saveDetails(userVm); - } - } - // track hypervsion tools version - if (info.hvtoolsversion != null && !info.hvtoolsversion.isEmpty()) { - if (vm.getType() == VirtualMachine.Type.User) { - UserVmVO userVm = _userVmDao.findById(vm.getId()); - _userVmDao.loadDetails(userVm); - userVm.setDetail("hypervisortoolsversion", info.hvtoolsversion); + userVm.setDetail("platform", info.platform); _userVmDao.saveDetails(userVm); } } @@ -2975,17 +2962,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac public String name; public State state; public String hostUuid; - public String hvtoolsversion; public VMInstanceVO vm; + public String platform; @SuppressWarnings("unchecked") - public AgentVmInfo(String name, VMInstanceVO vm, State state, String host, String hvtoolsversion) { + public AgentVmInfo(String name, VMInstanceVO vm, State state, String host, String platform) { this.name = name; this.state = state; this.vm = vm; - hostUuid = host; - this.hvtoolsversion = hvtoolsversion; - + this.hostUuid = host; + this.platform = platform; + } public AgentVmInfo(String name, VMInstanceVO vm, State state, String host) { @@ -2999,9 +2986,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac public String getHostUuid() { return hostUuid; } - - public String getHvtoolsversion() { - return hvtoolsversion; + + public String getPlatform() { + return platform; } } @@ -3011,10 +2998,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public void checkIfCanUpgrade(VirtualMachine vmInstance, long newServiceOfferingId) { - ServiceOfferingVO newServiceOffering = _offeringDao.findById(vmInstance.getId(), newServiceOfferingId); + public void checkIfCanUpgrade(VirtualMachine vmInstance, ServiceOffering newServiceOffering) { if (newServiceOffering == null) { - throw new InvalidParameterValueException("Unable to find a service offering with id " + newServiceOfferingId); + throw new InvalidParameterValueException("Unable to find a service offering with id " + newServiceOffering.getId()); } // Check that the VM is stopped / running @@ -3025,7 +3011,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } // Check if the service offering being upgraded to is what the VM is already running with - if (vmInstance.getServiceOfferingId() == newServiceOffering.getId()) { + if (!newServiceOffering.isDynamic() && vmInstance.getServiceOfferingId() == newServiceOffering.getId()) { if (s_logger.isInfoEnabled()) { s_logger.info("Not upgrading vm " + vmInstance.toString() + " since it already has the requested " + "service offering (" + newServiceOffering.getName() + ")"); @@ -3507,11 +3493,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new CloudRuntimeException("VM is not Running, unable to migrate the vm currently " + vm + " , current state: " + vm.getState().toString()); } - short alertType = AlertManager.ALERT_TYPE_USERVM_MIGRATE; + AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM_MIGRATE; if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) { - alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE; + alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE; } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) { - alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY_MIGRATE; + alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE; } VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); @@ -3558,7 +3544,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac boolean migrated = false; try { boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows"); - MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows, to); + MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows, to, ExecuteInSequence.value()); mc.setHostGuid(dest.getHost().getGuid()); try { @@ -3734,7 +3720,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac VMInstanceVO vm = _vmDao.findByUuid(vmUuid); long newServiceofferingId = vm.getServiceOfferingId(); - ServiceOffering newServiceOffering = _entityMgr.findById(ServiceOffering.class, newServiceofferingId); + ServiceOffering newServiceOffering = _offeringDao.findById(vm.getId(), newServiceofferingId); HostVO hostVo = _hostDao.findById(vm.getHostId()); Float memoryOvercommitRatio = CapacityManager.MemOverprovisioningFactor.valueIn(hostVo.getClusterId()); @@ -3860,7 +3846,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } // we need to alert admin or user about this risky state transition - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(), + _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; @@ -3882,7 +3868,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } catch (NoTransitionException e) { s_logger.warn("Unexpected VM state transition exception, race-condition?", e); } - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(), + _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; @@ -3924,7 +3910,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } catch (NoTransitionException e) { s_logger.warn("Unexpected VM state transition exception, race-condition?", e); } - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(), + _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 @@ -3985,7 +3971,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac VMInstanceVO vm = _vmDao.findById(vmId); // We now only alert administrator about this situation - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(), + _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"); } @@ -4150,61 +4136,64 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } return null; } - - public Outcome startVmThroughJobQueue(final String vmUuid, - final Map params, - final DeploymentPlan planToDeploy) { - - final CallContext context = CallContext.current(); + + // + // 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 CallContext context = CallContext.current(); final User callingUser = context.getCallingUser(); final Account callingAccount = context.getCallingAccount(); final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - VmWorkJobVO workJob = null; + Transaction.execute(new TransactionCallbackNoReturn () { + public void doInTransactionWithoutResult(TransactionStatus status) { + VmWorkJobVO workJob = null; + + _vmDao.lockRow(vm.getId(), true); + List pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, + vm.getId(), VmWorkStart.class.getName()); + + if (pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + workJob = new VmWorkJobVO(context.getContextId()); - _vmDao.lockRow(vm.getId(), true); - List pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, - vm.getId(), VmWorkStart.class.getName()); + workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkStart.class.getName()); - if (pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - workJob = new VmWorkJobVO(context.getContextId()); + workJob.setAccountId(callingAccount.getId()); + workJob.setUserId(callingUser.getId()); + workJob.setStep(VmWorkJobVO.Step.Starting); + workJob.setVmType(vm.getType()); + workJob.setVmInstanceId(vm.getId()); - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkStart.class.getName()); + // save work context info (there are some duplications) + VmWorkStart workInfo = new VmWorkStart(callingUser.getId(), callingAccount.getId(), vm.getId()); + workInfo.setPlan(planToDeploy); + workInfo.setParams(params); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - workJob.setAccountId(callingAccount.getId()); - workJob.setUserId(callingUser.getId()); - workJob.setStep(VmWorkJobVO.Step.Starting); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkStart workInfo = new VmWorkStart(callingUser.getId(), callingAccount.getId(), vm.getId()); - workInfo.setPlan(planToDeploy); - workInfo.setParams(params); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - - // Transaction syntax sugar has a cost here - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(vm.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - - return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), - VirtualMachine.PowerState.PowerOn, vm.getId(), null); + _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); + } + + // Transaction syntax sugar has a cost here + context.putContextParameter("workJob", workJob); + context.putContextParameter("jobId", new Long(workJob.getId())); + } + }); + + final long jobId = (Long)context.getContextParameter("jobId"); + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), + VirtualMachine.PowerState.PowerOn, vm.getId(), null); } public Outcome stopVmThroughJobQueue(final String vmUuid, final boolean cleanup) { @@ -4213,49 +4202,48 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final User user = context.getCallingUser(); final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); + + Transaction.execute(new TransactionCallbackNoReturn () { + public void doInTransactionWithoutResult(TransactionStatus status) { + _vmDao.lockRow(vm.getId(), true); + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkStop.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkStop.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setStep(VmWorkJobVO.Step.Prepare); + workJob.setVmType(vm.getType()); + workJob.setVmInstanceId(vm.getId()); + + // save work context info (there are some duplications) + VmWorkStop workInfo = new VmWorkStop(user.getId(), account.getId(), vm.getId(), cleanup); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); + } + + context.putContextParameter("workJob", workJob); + context.putContextParameter("jobId", new Long(workJob.getId())); + } + }); - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkStop.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkStop.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setStep(VmWorkJobVO.Step.Prepare); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkStop workInfo = new VmWorkStop(user.getId(), account.getId(), vm.getId(), cleanup); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(vm.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - - return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), - VirtualMachine.PowerState.PowerOff, vm.getId(), null); + final long jobId = (Long)context.getContextParameter("jobId"); + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), + VirtualMachine.PowerState.PowerOff, vm.getId(), null); } public Outcome rebootVmThroughJobQueue(final String vmUuid, @@ -4266,49 +4254,48 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final User user = context.getCallingUser(); final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); + + Transaction.execute(new TransactionCallbackNoReturn () { + public void doInTransactionWithoutResult(TransactionStatus status) { + _vmDao.lockRow(vm.getId(), true); + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkReboot.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkReboot.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setStep(VmWorkJobVO.Step.Prepare); + workJob.setVmType(vm.getType()); + workJob.setVmInstanceId(vm.getId()); + + // save work context info (there are some duplications) + VmWorkReboot workInfo = new VmWorkReboot(user.getId(), account.getId(), vm.getId(), params); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); + } + + context.putContextParameter("workJob", workJob); + context.putContextParameter("jobId", new Long(workJob.getId())); + } + }); - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkReboot.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkReboot.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setStep(VmWorkJobVO.Step.Prepare); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkReboot workInfo = new VmWorkReboot(user.getId(), account.getId(), vm.getId(), params); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(vm.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - - return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), - vm.getId()); + final long jobId = (Long)context.getContextParameter("jobId"); + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), + vm.getId()); } public Outcome migrateVmThroughJobQueue(final String vmUuid, final long srcHostId, final DeployDestination dest) { @@ -4318,48 +4305,47 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkMigrate.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkMigrate.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkMigrate workInfo = new VmWorkMigrate(user.getId(), account.getId(), vm.getId(), srcHostId, dest); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(vm.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - - return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), - VirtualMachine.PowerState.PowerOn, vm.getId(), vm.getPowerHostId()); + Transaction.execute(new TransactionCallbackNoReturn () { + public void doInTransactionWithoutResult(TransactionStatus status) { + + _vmDao.lockRow(vm.getId(), true); + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkMigrate.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkMigrate.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setVmType(vm.getType()); + workJob.setVmInstanceId(vm.getId()); + + // save work context info (there are some duplications) + VmWorkMigrate workInfo = new VmWorkMigrate(user.getId(), account.getId(), vm.getId(), srcHostId, dest); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); + } + context.putContextParameter("workJob", workJob); + context.putContextParameter("jobId", new Long(workJob.getId())); + } + }); + + final long jobId = (Long)context.getContextParameter("jobId"); + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), + VirtualMachine.PowerState.PowerOn, vm.getId(), vm.getPowerHostId()); } public Outcome migrateVmWithStorageThroughJobQueue( @@ -4372,55 +4358,50 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkMigrateWithStorage.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkMigrate.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkMigrateWithStorage workInfo = new VmWorkMigrateWithStorage(user.getId(), account.getId(), vm.getId(), - srcHostId, destHostId, volumeToPool); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(vm.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - - return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), - VirtualMachine.PowerState.PowerOn, vm.getId(), destHostId); + Transaction.execute(new TransactionCallbackNoReturn () { + public void doInTransactionWithoutResult(TransactionStatus status) { + + _vmDao.lockRow(vm.getId(), true); + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkMigrateWithStorage.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkMigrate.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setVmType(vm.getType()); + workJob.setVmInstanceId(vm.getId()); + + // save work context info (there are some duplications) + VmWorkMigrateWithStorage workInfo = new VmWorkMigrateWithStorage(user.getId(), account.getId(), vm.getId(), + srcHostId, destHostId, volumeToPool); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); + } + context.putContextParameter("workJob", workJob); + context.putContextParameter("jobId", new Long(workJob.getId())); + } + }); + + final long jobId = (Long)context.getContextParameter("jobId"); + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), + VirtualMachine.PowerState.PowerOn, vm.getId(), destHostId); } - - // - // TODO build a common pattern to reduce code duplication in following methods - // no time for this at current iteration - // + public Outcome migrateVmForScaleThroughJobQueue( final String vmUuid, final long srcHostId, final DeployDestination dest, final Long newSvcOfferingId) { @@ -4430,47 +4411,46 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkMigrateForScale.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkMigrate.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkMigrateForScale workInfo = new VmWorkMigrateForScale(user.getId(), account.getId(), vm.getId(), - srcHostId, dest, newSvcOfferingId); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(vm.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - + Transaction.execute(new TransactionCallbackNoReturn () { + public void doInTransactionWithoutResult(TransactionStatus status) { + + _vmDao.lockRow(vm.getId(), true); + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkMigrateForScale.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkMigrate.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setVmType(vm.getType()); + workJob.setVmInstanceId(vm.getId()); + + // save work context info (there are some duplications) + VmWorkMigrateForScale workInfo = new VmWorkMigrateForScale(user.getId(), account.getId(), vm.getId(), + srcHostId, dest, newSvcOfferingId); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); + } + context.putContextParameter("workJob", workJob); + context.putContextParameter("jobId", new Long(workJob.getId())); + } + }); + + final long jobId = (Long)context.getContextParameter("jobId"); + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId()); } @@ -4483,47 +4463,46 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkStorageMigration.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkStorageMigration.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkStorageMigration workInfo = new VmWorkStorageMigration(user.getId(), account.getId(), vm.getId(), - destPool); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(vm.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - + Transaction.execute(new TransactionCallbackNoReturn () { + public void doInTransactionWithoutResult(TransactionStatus status) { + + _vmDao.lockRow(vm.getId(), true); + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkStorageMigration.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkStorageMigration.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setVmType(vm.getType()); + workJob.setVmInstanceId(vm.getId()); + + // save work context info (there are some duplications) + VmWorkStorageMigration workInfo = new VmWorkStorageMigration(user.getId(), account.getId(), vm.getId(), + destPool); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); + } + context.putContextParameter("workJob", workJob); + context.putContextParameter("jobId", new Long(workJob.getId())); + } + }); + + final long jobId = (Long)context.getContextParameter("jobId"); + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId()); } @@ -4534,47 +4513,46 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final User user = context.getCallingUser(); final Account account = context.getCallingAccount(); - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkAddVmToNetwork.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkAddVmToNetwork.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkAddVmToNetwork workInfo = new VmWorkAddVmToNetwork(user.getId(), account.getId(), vm.getId(), - network, requested); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(vm.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - + Transaction.execute(new TransactionCallbackNoReturn () { + public void doInTransactionWithoutResult(TransactionStatus status) { + + _vmDao.lockRow(vm.getId(), true); + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkAddVmToNetwork.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkAddVmToNetwork.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setVmType(vm.getType()); + workJob.setVmInstanceId(vm.getId()); + + // save work context info (there are some duplications) + VmWorkAddVmToNetwork workInfo = new VmWorkAddVmToNetwork(user.getId(), account.getId(), vm.getId(), + network, requested); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); + } + context.putContextParameter("workJob", workJob); + context.putContextParameter("jobId", new Long(workJob.getId())); + } + }); + + final long jobId = (Long)context.getContextParameter("jobId"); + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId()); } @@ -4585,47 +4563,46 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final User user = context.getCallingUser(); final Account account = context.getCallingAccount(); - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkRemoveNicFromVm.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkRemoveNicFromVm.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkRemoveNicFromVm workInfo = new VmWorkRemoveNicFromVm(user.getId(), account.getId(), vm.getId(), - nic); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(vm.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - + Transaction.execute(new TransactionCallbackNoReturn () { + public void doInTransactionWithoutResult(TransactionStatus status) { + + _vmDao.lockRow(vm.getId(), true); + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkRemoveNicFromVm.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkRemoveNicFromVm.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setVmType(vm.getType()); + workJob.setVmInstanceId(vm.getId()); + + // save work context info (there are some duplications) + VmWorkRemoveNicFromVm workInfo = new VmWorkRemoveNicFromVm(user.getId(), account.getId(), vm.getId(), + nic); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); + } + context.putContextParameter("workJob", workJob); + context.putContextParameter("jobId", new Long(workJob.getId())); + } + }); + + final long jobId = (Long)context.getContextParameter("jobId"); + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId()); } @@ -4636,47 +4613,46 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final User user = context.getCallingUser(); final Account account = context.getCallingAccount(); - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkRemoveVmFromNetwork.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkRemoveVmFromNetwork.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkRemoveVmFromNetwork workInfo = new VmWorkRemoveVmFromNetwork(user.getId(), account.getId(), vm.getId(), - network, broadcastUri); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(vm.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - + Transaction.execute(new TransactionCallbackNoReturn () { + public void doInTransactionWithoutResult(TransactionStatus status) { + + _vmDao.lockRow(vm.getId(), true); + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkRemoveVmFromNetwork.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkRemoveVmFromNetwork.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setVmType(vm.getType()); + workJob.setVmInstanceId(vm.getId()); + + // save work context info (there are some duplications) + VmWorkRemoveVmFromNetwork workInfo = new VmWorkRemoveVmFromNetwork(user.getId(), account.getId(), vm.getId(), + network, broadcastUri); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); + } + context.putContextParameter("workJob", workJob); + context.putContextParameter("jobId", new Long(workJob.getId())); + } + }); + + final long jobId = (Long)context.getContextParameter("jobId"); + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId()); } @@ -4689,47 +4665,46 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkReconfigure.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkReconfigure.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkReconfigure workInfo = new VmWorkReconfigure(user.getId(), account.getId(), vm.getId(), - oldServiceOffering, reconfiguringOnExistingHost); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(vm.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - + Transaction.execute(new TransactionCallbackNoReturn () { + public void doInTransactionWithoutResult(TransactionStatus status) { + + _vmDao.lockRow(vm.getId(), true); + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkReconfigure.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkReconfigure.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setVmType(vm.getType()); + workJob.setVmInstanceId(vm.getId()); + + // save work context info (there are some duplications) + VmWorkReconfigure workInfo = new VmWorkReconfigure(user.getId(), account.getId(), vm.getId(), + oldServiceOffering, reconfiguringOnExistingHost); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); + } + context.putContextParameter("workJob", workJob); + context.putContextParameter("jobId", new Long(workJob.getId())); + } + }); + + final long jobId = (Long)context.getContextParameter("jobId"); + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId()); } diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java index c02e0adf98e..40b0f447392 100755 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java @@ -146,6 +146,7 @@ public class VMEntityManagerImpl implements VMEntityManager { //FIXME: profile should work on VirtualMachineEntity VMInstanceVO vm = _vmDao.findByUuid(vmEntityVO.getUuid()); VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm); + vmProfile.setServiceOffering(_serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId())); DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterId(), vm.getPodIdToDeployIn(), null, null, null, null); if (planToDeploy != null && planToDeploy.getDataCenterId() != 0) { plan = diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java b/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java index 7179944f7ba..b5c1539ba9d 100755 --- a/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java @@ -47,6 +47,7 @@ import org.apache.cloudstack.framework.config.Configurable; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.managed.context.ManagedContextRunnable; import org.apache.cloudstack.region.PortableIpDao; +import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.Listener; @@ -147,6 +148,7 @@ import com.cloud.network.rules.StaticNatRule; import com.cloud.network.rules.StaticNatRuleImpl; import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.network.vpc.NetworkACLManager; +import com.cloud.network.vpc.Vpc; import com.cloud.network.vpc.VpcManager; import com.cloud.network.vpc.dao.PrivateIpDao; import com.cloud.network.vpn.RemoteAccessVpnService; @@ -1031,22 +1033,22 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra (network.getGuestType() == Network.GuestType.Isolated || (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced))) { List ips = null; + Account owner = _entityMgr.findById(Account.class, network.getAccountId()); if (network.getVpcId() != null) { ips = _ipAddressDao.listByAssociatedVpc(network.getVpcId(), true); if (ips.isEmpty()) { - throw new CloudRuntimeException("Vpc is not implemented; there is no source nat ip"); + Vpc vpc = _vpcMgr.getActiveVpc(network.getVpcId()); + s_logger.debug("Creating a source nat ip for vpc " + vpc); + _vpcMgr.assignSourceNatIpAddressToVpc(owner, vpc); } } else { ips = _ipAddressDao.listByAssociatedNetwork(network.getId(), true); - } - - if (ips.isEmpty()) { - s_logger.debug("Creating a source nat ip for network " + network); - Account owner = _entityMgr.findById(Account.class, network.getAccountId()); - _ipAddrMgr.assignSourceNatIpAddressToGuestNetwork(owner, network); + if (ips.isEmpty()) { + s_logger.debug("Creating a source nat ip for network " + network); + _ipAddrMgr.assignSourceNatIpAddressToGuestNetwork(owner, network); + } } } - // get providers to implement List providersToImplement = getNetworkProviders(network.getId()); for (NetworkElement element : _networkElements) { @@ -2839,7 +2841,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra if (!answer.getResult()) { s_logger.warn("Unable to setup agent " + hostId + " due to " + ((answer != null) ? answer.getDetails() : "return null")); String msg = "Incorrect Network setup on agent, Reinitialize agent after network names are setup, details : " + answer.getDetails(); - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId, host.getPodId(), msg, msg); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, host.getPodId(), msg, msg); throw new ConnectionException(true, msg); } else { if (answer.needReconnect()) { diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java b/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java index fdc2d2393e3..7b0d968ab07 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java @@ -253,7 +253,8 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati @DB @Override - public VolumeInfo createVolumeFromSnapshot(Volume volume, Snapshot snapshot) throws StorageUnavailableException { + public VolumeInfo createVolumeFromSnapshot(Volume volume, Snapshot snapshot, UserVm vm) + throws StorageUnavailableException { Account account = _entityMgr.findById(Account.class, volume.getAccountId()); final HashSet poolsToAvoid = new HashSet(); @@ -266,17 +267,62 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati DataCenter dc = _entityMgr.findById(DataCenter.class, volume.getDataCenterId()); DiskProfile dskCh = new DiskProfile(volume, diskOffering, snapshot.getHypervisorType()); - // Determine what pod to store the volume in - while ((pod = findPod(null, null, dc, account.getId(), podsToAvoid)) != null) { - podsToAvoid.add(pod.first().getId()); + String msg = "There are no available storage pools to store the volume in"; + + if(vm != null){ + Pod podofVM = _entityMgr.findById(Pod.class, vm.getPodIdToDeployIn()); + if(podofVM != null){ + pod = new Pair(podofVM, podofVM.getId()); + } + } + + if(vm != null && pod != null){ + //if VM is running use the hostId to find the clusterID. If it is stopped, refer the cluster where the ROOT volume of the VM exists. + Long hostId = null; + Long clusterId = null; + if(vm.getState() == State.Running){ + hostId = vm.getHostId(); + if(hostId != null){ + Host vmHost = _entityMgr.findById(Host.class, hostId); + clusterId = vmHost.getClusterId(); + } + }else{ + List rootVolumesOfVm = _volsDao.findByInstanceAndType(vm.getId(), Volume.Type.ROOT); + if (rootVolumesOfVm.size() != 1) { + throw new CloudRuntimeException("The VM " + vm.getHostName() + " has more than one ROOT volume and is in an invalid state. Please contact Cloud Support."); + } else { + VolumeVO rootVolumeOfVm = rootVolumesOfVm.get(0); + StoragePoolVO rootDiskPool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId()); + clusterId = (rootDiskPool == null ? null : rootDiskPool.getClusterId()); + } + } // Determine what storage pool to store the volume in - while ((pool = findStoragePool(dskCh, dc, pod.first(), null, null, null, poolsToAvoid)) != null) { + while ((pool = findStoragePool(dskCh, dc, pod.first(), clusterId, hostId, vm, poolsToAvoid)) != null) { break; } + + if (pool == null) { + //pool could not be found in the VM's pod/cluster. + if(s_logger.isDebugEnabled()){ + s_logger.debug("Could not find any storage pool to create Volume in the pod/cluster of the provided VM "+vm.getUuid()); + } + StringBuilder addDetails = new StringBuilder(msg); + addDetails.append(", Could not find any storage pool to create Volume in the pod/cluster of the VM "); + addDetails.append(vm.getUuid()); + msg = addDetails.toString(); + } + }else{ + // Determine what pod to store the volume in + while ((pod = findPod(null, null, dc, account.getId(), podsToAvoid)) != null) { + podsToAvoid.add(pod.first().getId()); + // Determine what storage pool to store the volume in + while ((pool = findStoragePool(dskCh, dc, pod.first(), null, null, null, poolsToAvoid)) != null) { + break; + } + } } if (pool == null) { - String msg = "There are no available storage pools to store the volume in"; s_logger.info(msg); throw new StorageUnavailableException(msg, -1); } @@ -524,10 +570,17 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati vol = _volsDao.persist(vol); // Save usage event and update resource count for user vm volumes - if (vm instanceof UserVm) { - - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, vol.getAccountId(), vol.getDataCenterId(), vol.getId(), vol.getName(), offering.getId(), - null, size, Volume.class.getName(), vol.getUuid()); + if (vm.getType() == VirtualMachine.Type.User) { + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, + vol.getAccountId(), + vol.getDataCenterId(), + vol.getId(), + vol.getName(), + offering.getId(), + null, + size, + Volume.class.getName(), + vol.getUuid()); _resourceLimitMgr.incrementResourceCount(vm.getAccountId(), ResourceType.volume); _resourceLimitMgr.incrementResourceCount(vm.getAccountId(), ResourceType.primary_storage, new Long(vol.getSize())); @@ -564,7 +617,7 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati vol = _volsDao.persist(vol); // Create event and update resource count for volumes if vm is a user vm - if (vm instanceof UserVm) { + if (vm.getType() == VirtualMachine.Type.User) { Long offeringId = null; diff --git a/engine/schema/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml b/engine/schema/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml index a8a1bffdb01..4f7d7ea6562 100644 --- a/engine/schema/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml +++ b/engine/schema/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml @@ -209,8 +209,7 @@ - - + @@ -323,7 +322,11 @@ - + + + + + diff --git a/engine/schema/src/com/cloud/alert/AlertVO.java b/engine/schema/src/com/cloud/alert/AlertVO.java index 98d8557d287..ade505d2e3f 100755 --- a/engine/schema/src/com/cloud/alert/AlertVO.java +++ b/engine/schema/src/com/cloud/alert/AlertVO.java @@ -72,16 +72,14 @@ public class AlertVO implements Alert { @Column(name = "archived") private boolean archived; + + @Column(name="name") + private String name; public AlertVO() { this.uuid = UUID.randomUUID().toString(); } - public AlertVO(Long id) { - this.id = id; - this.uuid = UUID.randomUUID().toString(); - } - @Override public long getId() { return id; @@ -184,4 +182,14 @@ public class AlertVO implements Alert { public void setArchived(Boolean archived) { this.archived = archived; } + + @Override + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } } diff --git a/engine/schema/src/com/cloud/event/UsageEventVO.java b/engine/schema/src/com/cloud/event/UsageEventVO.java index 719a79bde6e..2278103b82e 100644 --- a/engine/schema/src/com/cloud/event/UsageEventVO.java +++ b/engine/schema/src/com/cloud/event/UsageEventVO.java @@ -30,6 +30,10 @@ import com.cloud.utils.db.GenericDao; @Entity @Table(name = "usage_event") public class UsageEventVO implements UsageEvent { + public enum DynamicParameters { + cpuSpeed, cpuNumber, memory + }; + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/engine/schema/src/com/cloud/event/dao/UsageEventDetailsDaoImpl.java b/engine/schema/src/com/cloud/event/dao/UsageEventDetailsDaoImpl.java index b2be1c934eb..2126fff45c6 100644 --- a/engine/schema/src/com/cloud/event/dao/UsageEventDetailsDaoImpl.java +++ b/engine/schema/src/com/cloud/event/dao/UsageEventDetailsDaoImpl.java @@ -16,12 +16,17 @@ // under the License. package com.cloud.event.dao; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ejb.Local; +import com.cloud.utils.exception.CloudRuntimeException; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -36,6 +41,8 @@ import com.cloud.utils.db.TransactionLegacy; public class UsageEventDetailsDaoImpl extends GenericDaoBase implements UsageEventDetailsDao { public static final Logger s_logger = Logger.getLogger(UsageEventDetailsDaoImpl.class.getName()); + private static final String EVENT_DETAILS_QUERY = "SELECT details.id, details.usage_event_id, details.name, details.value FROM `cloud`.`usage_event_details` details WHERE details.usage_event_id = ?"; + protected final SearchBuilder EventDetailsSearch; protected final SearchBuilder DetailSearch; @@ -74,13 +81,38 @@ public class UsageEventDetailsDaoImpl extends GenericDaoBase findDetails(long eventId) { - SearchCriteria sc = EventDetailsSearch.create(); - sc.setParameters("eventId", eventId); + Connection conn = null; + PreparedStatement pstmt = null; + ResultSet resultSet = null; + Map details = new HashMap(); + try { + conn = TransactionLegacy.getStandaloneConnection(); - List results = search(sc, null); - Map details = new HashMap(results.size()); - for (UsageEventDetailsVO result : results) { - details.put(result.getKey(), result.getValue()); + pstmt = conn.prepareStatement(EVENT_DETAILS_QUERY); + pstmt.setLong(1, eventId); + resultSet = pstmt.executeQuery(); + + while (resultSet.next()) { + details.put(resultSet.getString(3), resultSet.getString(4)); + } + + } catch (SQLException e) { + throw new CloudRuntimeException("Error while executing SQL prepared statement", e); + } catch (Throwable e) { + throw new CloudRuntimeException("Caught: " + e); + } finally { + if (pstmt != null) { + try { + pstmt.close(); + } catch (SQLException e) { + } + } + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + } + } } return details; diff --git a/engine/schema/src/com/cloud/network/dao/OvsProviderDao.java b/engine/schema/src/com/cloud/network/dao/OvsProviderDao.java new file mode 100644 index 00000000000..b23e3d31f30 --- /dev/null +++ b/engine/schema/src/com/cloud/network/dao/OvsProviderDao.java @@ -0,0 +1,14 @@ +package com.cloud.network.dao; + +import java.util.List; + +import com.cloud.network.element.OvsProviderVO; +import com.cloud.utils.db.GenericDao; + +public interface OvsProviderDao extends GenericDao { + public OvsProviderVO findByNspId(long nspId); + + public List listByEnabled(boolean enabled); + + public OvsProviderVO findByIdAndEnabled(long id, boolean enabled); +} diff --git a/engine/schema/src/com/cloud/network/dao/OvsProviderDaoImpl.java b/engine/schema/src/com/cloud/network/dao/OvsProviderDaoImpl.java new file mode 100644 index 00000000000..2026ccf2a7e --- /dev/null +++ b/engine/schema/src/com/cloud/network/dao/OvsProviderDaoImpl.java @@ -0,0 +1,57 @@ +package com.cloud.network.dao; + +import java.util.List; + +import javax.ejb.Local; + +import org.springframework.stereotype.Component; + +import com.cloud.network.element.OvsProviderVO; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Component +@Local(value = OvsProviderDao.class) +@DB() +public class OvsProviderDaoImpl extends GenericDaoBase + implements OvsProviderDao { + final SearchBuilder AllFieldsSearch; + + public OvsProviderDaoImpl() { + super(); + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("id", AllFieldsSearch.entity().getId(), + SearchCriteria.Op.EQ); + AllFieldsSearch.and("nsp_id", AllFieldsSearch.entity().getNspId(), + SearchCriteria.Op.EQ); + AllFieldsSearch.and("uuid", AllFieldsSearch.entity().getUuid(), + SearchCriteria.Op.EQ); + AllFieldsSearch.and("enabled", AllFieldsSearch.entity().isEnabled(), + SearchCriteria.Op.EQ); + AllFieldsSearch.done(); + } + + @Override + public OvsProviderVO findByNspId(long nspId) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("nsp_id", nspId); + return findOneBy(sc); + } + + @Override + public List listByEnabled(boolean enabled) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("enabled", enabled); + return listBy(sc); + } + + @Override + public OvsProviderVO findByIdAndEnabled(long id, boolean enabled) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("id", id); + sc.setParameters("enabled", enabled); + return findOneBy(sc); + } +} diff --git a/engine/schema/src/com/cloud/network/dao/SslCertDaoImpl.java b/engine/schema/src/com/cloud/network/dao/SslCertDaoImpl.java index 99354c5dbc2..cab001bf922 100644 --- a/engine/schema/src/com/cloud/network/dao/SslCertDaoImpl.java +++ b/engine/schema/src/com/cloud/network/dao/SslCertDaoImpl.java @@ -33,7 +33,7 @@ public class SslCertDaoImpl extends GenericDaoBase implements S listByAccountId = createSearchBuilder(); listByAccountId.and("accountId", listByAccountId.entity().getAccountId(), SearchCriteria.Op.EQ); listByAccountId.done(); - } + } @Override public List listByAccountId(Long accountId) { diff --git a/engine/schema/src/com/cloud/network/element/OvsProviderVO.java b/engine/schema/src/com/cloud/network/element/OvsProviderVO.java new file mode 100644 index 00000000000..bc3455a2bb7 --- /dev/null +++ b/engine/schema/src/com/cloud/network/element/OvsProviderVO.java @@ -0,0 +1,83 @@ +package com.cloud.network.element; + +import java.util.Date; +import java.util.UUID; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.network.OvsProvider; +import com.cloud.utils.db.GenericDao; + +@Entity +@Table(name = ("ovs_providers")) +public class OvsProviderVO implements OvsProvider { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + long id; + + @Column(name = "nsp_id") + private long nspId; + + @Column(name = "uuid") + private String uuid; + + @Column(name = "enabled") + private boolean enabled; + + @Column(name = GenericDao.REMOVED_COLUMN) + Date removed; + + public OvsProviderVO() { + this.uuid = UUID.randomUUID().toString(); + } + + public OvsProviderVO(long nspId) { + this.nspId = nspId; + this.uuid = UUID.randomUUID().toString(); + } + + @Override + public long getNspId() { + return nspId; + } + + public String getUuid() { + return uuid; + } + + @Override + public long getId() { + return id; + } + + public Date getRemoved() { + return removed; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + public void setId(long id) { + this.id = id; + } + + public void setNspId(long nspId) { + this.nspId = nspId; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } +} diff --git a/engine/schema/src/com/cloud/service/ServiceOfferingVO.java b/engine/schema/src/com/cloud/service/ServiceOfferingVO.java index 67fea00a43e..f1cc39b9326 100755 --- a/engine/schema/src/com/cloud/service/ServiceOfferingVO.java +++ b/engine/schema/src/com/cloud/service/ServiceOfferingVO.java @@ -34,10 +34,6 @@ import com.cloud.vm.VirtualMachine; @DiscriminatorValue(value = "Service") @PrimaryKeyJoinColumn(name = "id") public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering { - public enum DynamicParameters { - cpuSpeed, cpuNumber, memory - }; - @Column(name = "cpu") private Integer cpu; @@ -83,6 +79,11 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering @Transient Map details; + // This flag is required to tell if the offering is dynamic once the cpu, memory and speed are set. + // In some cases cpu, memory and speed are set to non-null values even if the offering is dynamic. + @Transient + boolean isDynamic; + protected ServiceOfferingVO() { super(); } @@ -162,6 +163,20 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering this.deploymentPlanner = deploymentPlanner; } + public ServiceOfferingVO(ServiceOfferingVO offering) { + super(offering.getId(), offering.getName(), offering.getDisplayText(), false, offering.getTags(), offering.isRecreatable(), offering.getUseLocalStorage(), offering.getSystemUse(), true, offering.getDomainId()); + this.cpu = offering.getCpu(); + this.ramSize = offering.getRamSize(); + this.speed = offering.getSpeed(); + this.rateMbps = offering.getRateMbps(); + this.multicastRateMbps = offering.getMulticastRateMbps(); + this.offerHA = offering.getOfferHA(); + this.limitCpuUse = offering.getLimitCpuUse(); + this.volatileVm = offering.getVolatileVm(); + this.hostTag = offering.getHostTag(); + this.vm_type = offering.getSystemVmType(); + } + @Override public boolean getOfferHA() { return offerHA; @@ -297,7 +312,10 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering @Override public boolean isDynamic() { - return cpu == null || speed == null || ramSize == null; + return cpu == null || speed == null || ramSize == null || isDynamic; } + public void setDynamicFlag(boolean isdynamic) { + this.isDynamic = isdynamic; + } } diff --git a/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java b/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java index 10d661687e1..ecab8d2943c 100644 --- a/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java +++ b/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java @@ -17,6 +17,7 @@ package com.cloud.service.dao; import java.util.List; +import java.util.Map; import com.cloud.service.ServiceOfferingVO; import com.cloud.utils.db.GenericDao; @@ -47,5 +48,5 @@ public interface ServiceOfferingDao extends GenericDao boolean isDynamic(long serviceOfferingId); - ServiceOfferingVO getcomputeOffering(long serviceOfferingId, Integer cpuCores, Integer cpuSpeed, Integer memory); + ServiceOfferingVO getcomputeOffering(ServiceOfferingVO serviceOffering, Map customParameters); } diff --git a/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java b/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java index f1f97fc79f5..5d423e0a1e7 100644 --- a/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java +++ b/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java @@ -25,6 +25,7 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.persistence.EntityExistsException; +import com.cloud.event.UsageEventVO; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -191,14 +192,12 @@ public class ServiceOfferingDaoImpl extends GenericDaoBase dynamicOffering = userVmDetailsDao.listDetailsKeyPairs(vmId); - offering.setCpu(Integer.parseInt(dynamicOffering.get(ServiceOfferingVO.DynamicParameters.cpuNumber.name()))); - offering.setSpeed(Integer.parseInt(dynamicOffering.get(ServiceOfferingVO.DynamicParameters.cpuSpeed.name()))); - offering.setRamSize(Integer.parseInt(dynamicOffering.get(ServiceOfferingVO.DynamicParameters.memory.name()))); - return offering; + return getcomputeOffering(offering, dynamicOffering); } return offering; } @@ -207,15 +206,12 @@ public class ServiceOfferingDaoImpl extends GenericDaoBase dynamicOffering = userVmDetailsDao.listDetailsKeyPairs(vmId); - offering.setCpu(Integer.parseInt(dynamicOffering.get(ServiceOfferingVO.DynamicParameters.cpuNumber.name()))); - offering.setSpeed(Integer.parseInt(dynamicOffering.get(ServiceOfferingVO.DynamicParameters.cpuSpeed.name()))); - offering.setRamSize(Integer.parseInt(dynamicOffering.get(ServiceOfferingVO.DynamicParameters.memory.name()))); - return offering; - + return getcomputeOffering(offering, dynamicOffering); } return offering; } @@ -227,11 +223,19 @@ public class ServiceOfferingDaoImpl extends GenericDaoBase customParameters) { + ServiceOfferingVO dummyoffering = new ServiceOfferingVO(serviceOffering); + dummyoffering.setDynamicFlag(true); + if (customParameters.containsKey(UsageEventVO.DynamicParameters.cpuNumber.name())) { + dummyoffering.setCpu(Integer.parseInt(customParameters.get(UsageEventVO.DynamicParameters.cpuNumber.name()))); + } + if (customParameters.containsKey(UsageEventVO.DynamicParameters.cpuSpeed.name())) { + dummyoffering.setSpeed(Integer.parseInt(customParameters.get(UsageEventVO.DynamicParameters.cpuSpeed.name()))); + } + if (customParameters.containsKey(UsageEventVO.DynamicParameters.memory.name())) { + dummyoffering.setRamSize(Integer.parseInt(customParameters.get(UsageEventVO.DynamicParameters.memory.name()))); + } + + return dummyoffering; } } diff --git a/engine/schema/src/com/cloud/storage/DiskOfferingVO.java b/engine/schema/src/com/cloud/storage/DiskOfferingVO.java index 8a9dd3d32f8..1ff62ab7f24 100755 --- a/engine/schema/src/com/cloud/storage/DiskOfferingVO.java +++ b/engine/schema/src/com/cloud/storage/DiskOfferingVO.java @@ -206,6 +206,22 @@ public class DiskOfferingVO implements DiskOffering { state = State.Active; } + public DiskOfferingVO(long id, String name, String displayText, boolean mirrored, String tags, boolean recreatable, + boolean useLocalStorage, boolean systemUse, boolean customized, Long domainId) { + this.id = id; + type = Type.Service; + this.name = name; + this.displayText = displayText; + this.tags = tags; + this.recreatable = recreatable; + this.useLocalStorage = useLocalStorage; + this.systemUse = systemUse; + this.customized = customized; + this.domainId = domainId; + uuid = UUID.randomUUID().toString(); + state = State.Active; + } + @Override public State getState() { return state; diff --git a/engine/schema/src/com/cloud/storage/dao/VolumeDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/VolumeDaoImpl.java index c64a253b81c..5120387433f 100755 --- a/engine/schema/src/com/cloud/storage/dao/VolumeDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/VolumeDaoImpl.java @@ -346,6 +346,7 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol CountByAccount.select(null, Func.COUNT, null); CountByAccount.and("account", CountByAccount.entity().getAccountId(), SearchCriteria.Op.EQ); CountByAccount.and("state", CountByAccount.entity().getState(), SearchCriteria.Op.NIN); + CountByAccount.and("displayVolume", CountByAccount.entity().isDisplayVolume(), Op.EQ); CountByAccount.done(); primaryStorageSearch = createSearchBuilder(SumCount.class); @@ -355,6 +356,7 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol primaryStorageSearch.and().op("path", primaryStorageSearch.entity().getPath(), Op.NNULL); primaryStorageSearch.or("states", primaryStorageSearch.entity().getState(), Op.IN); primaryStorageSearch.cp(); + primaryStorageSearch.and("displayVolume", primaryStorageSearch.entity().isDisplayVolume(), Op.EQ); primaryStorageSearch.and("isRemoved", primaryStorageSearch.entity().getRemoved(), Op.NULL); primaryStorageSearch.done(); @@ -382,6 +384,7 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol SearchCriteria sc = CountByAccount.create(); sc.setParameters("account", accountId); sc.setParameters("state", Volume.State.Destroy); + sc.setParameters("displayVolume", 1); return customSearch(sc, null).get(0); } @@ -393,6 +396,7 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol sc.setParameters("virtualRouterVmIds", virtualRouters.toArray(new Object[virtualRouters.size()])); } sc.setParameters("states", State.Allocated); + sc.setParameters("displayVolume", 1); List storageSpace = customSearch(sc, null); if (storageSpace != null) { return storageSpace.get(0).sum; diff --git a/engine/schema/src/com/cloud/usage/UsageVMInstanceVO.java b/engine/schema/src/com/cloud/usage/UsageVMInstanceVO.java index 06a7beeecf0..8d9491f54a1 100644 --- a/engine/schema/src/com/cloud/usage/UsageVMInstanceVO.java +++ b/engine/schema/src/com/cloud/usage/UsageVMInstanceVO.java @@ -27,6 +27,7 @@ import javax.persistence.TemporalType; @Entity @Table(name = "usage_vm_instance") public class UsageVMInstanceVO { + @Column(name = "usage_type") private int usageType; @@ -45,6 +46,15 @@ public class UsageVMInstanceVO { @Column(name = "service_offering_id") private long serviceOfferingId; + @Column(name="cpu_cores") + private Long cpuCores; + + @Column(name="memory") + private Long memory; + + @Column(name="cpu_speed") + private Long cpuSpeed; + @Column(name = "template_id") private long templateId; @@ -127,4 +137,28 @@ public class UsageVMInstanceVO { public void setEndDate(Date endDate) { this.endDate = endDate; } + + public Long getMemory() { + return memory; + } + + public void setMemory(Long memory) { + this.memory = memory; + } + + public Long getCpuCores() { + return cpuCores; + } + + public void setCpuCores(Long cpuCores) { + this.cpuCores = cpuCores; + } + + public Long getCpuSpeed() { + return cpuSpeed; + } + + public void setCpuSpeed(Long cpuSpeed) { + this.cpuSpeed = cpuSpeed; + } } diff --git a/engine/schema/src/com/cloud/vm/dao/UserVmDao.java b/engine/schema/src/com/cloud/vm/dao/UserVmDao.java index 606d424c034..0a4acbbe8b0 100755 --- a/engine/schema/src/com/cloud/vm/dao/UserVmDao.java +++ b/engine/schema/src/com/cloud/vm/dao/UserVmDao.java @@ -40,11 +40,11 @@ public interface UserVmDao extends GenericDao { /** * Updates display name and group for vm; enables/disables ha * @param id vm id. - * @param displan name and enable for ha * @param userData updates the userData of the vm * @param displayVm updates the displayvm attribute signifying whether it has to be displayed to the end user or not. + * @param customId */ - void updateVM(long id, String displayName, boolean enable, Long osTypeId, String userData, boolean displayVm, boolean isDynamicallyScalable); + void updateVM(long id, String displayName, boolean enable, Long osTypeId, String userData, boolean displayVm, boolean isDynamicallyScalable, String customId); List findDestroyedVms(Date date); diff --git a/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java b/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java index 43bdef16ba5..b675fb61bc0 100755 --- a/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java +++ b/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java @@ -215,7 +215,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use } @Override - public void updateVM(long id, String displayName, boolean enable, Long osTypeId, String userData, boolean displayVm, boolean isDynamicallyScalable) { + public void updateVM(long id, String displayName, boolean enable, Long osTypeId, String userData, boolean displayVm, boolean isDynamicallyScalable, String customId) { UserVmVO vo = createForUpdate(); vo.setDisplayName(displayName); vo.setHaEnabled(enable); @@ -223,6 +223,10 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use vo.setUserData(userData); vo.setDisplayVm(displayVm); vo.setDynamicallyScalable(isDynamicallyScalable); + if (customId != null){ + vo.setUuid(customId); + } + update(id, vo); } diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/NetworkACLItemDetailVO.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/NetworkACLItemDetailVO.java new file mode 100644 index 00000000000..fb27d374a94 --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/NetworkACLItemDetailVO.java @@ -0,0 +1,82 @@ +// 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.resourcedetail; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.apache.cloudstack.api.ResourceDetail; + +@Entity +@Table(name = "network_acl_item_details") +public class NetworkACLItemDetailVO implements ResourceDetail { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "network_acl_item_id") + private long resourceId; + + @Column(name = "name") + private String name; + + @Column(name = "value", length = 1024) + private String value; + + @Column(name = "display") + private boolean display; + + public NetworkACLItemDetailVO() { + } + + public NetworkACLItemDetailVO(long id, String name, String value) { + this.resourceId = id; + this.name = name; + this.value = value; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getName() { + return name; + } + + @Override + public String getValue() { + return value; + } + + @Override + public long getResourceId() { + return resourceId; + } + + @Override + public boolean isDisplay() { + return display; + } +} + diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/NetworkACLListDetailVO.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/NetworkACLListDetailVO.java new file mode 100644 index 00000000000..71cf563478a --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/NetworkACLListDetailVO.java @@ -0,0 +1,82 @@ +// 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.resourcedetail; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.apache.cloudstack.api.ResourceDetail; + +@Entity +@Table(name = "network_acl_details") +public class NetworkACLListDetailVO implements ResourceDetail { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "network_acl_id") + private long resourceId; + + @Column(name = "name") + private String name; + + @Column(name = "value", length = 1024) + private String value; + + @Column(name = "display") + private boolean display; + + public NetworkACLListDetailVO() { + } + + public NetworkACLListDetailVO(long id, String name, String value) { + this.resourceId = id; + this.name = name; + this.value = value; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getName() { + return name; + } + + @Override + public String getValue() { + return value; + } + + @Override + public long getResourceId() { + return resourceId; + } + + @Override + public boolean isDisplay() { + return display; + } +} + diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/ResourceDetailsDaoBase.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/ResourceDetailsDaoBase.java index 5a94a15f688..2d086444213 100644 --- a/engine/schema/src/org/apache/cloudstack/resourcedetail/ResourceDetailsDaoBase.java +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/ResourceDetailsDaoBase.java @@ -75,6 +75,7 @@ public abstract class ResourceDetailsDaoBase extends G public void removeDetail(long resourceId, String key) { if (key != null) { SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("resourceId", resourceId); sc.setParameters("name", key); remove(sc); } diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/VpcDetailVO.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/VpcDetailVO.java new file mode 100644 index 00000000000..beb38b50d1b --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/VpcDetailVO.java @@ -0,0 +1,81 @@ +// 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.resourcedetail; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.apache.cloudstack.api.ResourceDetail; + +@Entity +@Table(name = "vpc_details") +public class VpcDetailVO implements ResourceDetail { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "vpc_id") + private long resourceId; + + @Column(name = "name") + private String name; + + @Column(name = "value", length = 1024) + private String value; + + @Column(name = "display") + private boolean display; + + public VpcDetailVO() { + } + + public VpcDetailVO(long id, String name, String value) { + this.resourceId = id; + this.name = name; + this.value = value; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getName() { + return name; + } + + @Override + public String getValue() { + return value; + } + + @Override + public long getResourceId() { + return resourceId; + } + + @Override + public boolean isDisplay() { + return display; + } +} diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/VpcGatewayDetailVO.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/VpcGatewayDetailVO.java new file mode 100644 index 00000000000..b78bfa8b5db --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/VpcGatewayDetailVO.java @@ -0,0 +1,81 @@ +// 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.resourcedetail; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.apache.cloudstack.api.ResourceDetail; + +@Entity +@Table(name = "vpc_gateway_details") +public class VpcGatewayDetailVO implements ResourceDetail { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "vpc_gateway_id") + private long resourceId; + + @Column(name = "name") + private String name; + + @Column(name = "value", length = 1024) + private String value; + + @Column(name = "display") + private boolean display; + + public VpcGatewayDetailVO() { + } + + public VpcGatewayDetailVO(long id, String name, String value) { + this.resourceId = id; + this.name = name; + this.value = value; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getName() { + return name; + } + + @Override + public String getValue() { + return value; + } + + @Override + public long getResourceId() { + return resourceId; + } + + @Override + public boolean isDisplay() { + return display; + } +} diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLItemDetailsDao.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLItemDetailsDao.java new file mode 100644 index 00000000000..db820ac5123 --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLItemDetailsDao.java @@ -0,0 +1,26 @@ +// 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.resourcedetail.dao; + +import org.apache.cloudstack.resourcedetail.NetworkACLItemDetailVO; +import org.apache.cloudstack.resourcedetail.ResourceDetailsDao; + +import com.cloud.utils.db.GenericDao; + +public interface NetworkACLItemDetailsDao extends GenericDao, ResourceDetailsDao { + +} \ No newline at end of file diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLItemDetailsDaoImpl.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLItemDetailsDaoImpl.java new file mode 100644 index 00000000000..930c77a4500 --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLItemDetailsDaoImpl.java @@ -0,0 +1,33 @@ +// 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.resourcedetail.dao; + +import javax.ejb.Local; + +import org.apache.cloudstack.resourcedetail.NetworkACLItemDetailVO; +import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; +import org.springframework.stereotype.Component; + +@Component +@Local(value = { NetworkACLItemDetailsDao.class }) +public class NetworkACLItemDetailsDaoImpl extends ResourceDetailsDaoBase implements NetworkACLItemDetailsDao { + + @Override + public void addDetail(long resourceId, String key, String value) { + super.addDetail(new NetworkACLItemDetailVO(resourceId, key, value)); + } +} \ No newline at end of file diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLListDetailsDao.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLListDetailsDao.java new file mode 100644 index 00000000000..1c8524505dd --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLListDetailsDao.java @@ -0,0 +1,26 @@ +// 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.resourcedetail.dao; + +import org.apache.cloudstack.resourcedetail.NetworkACLListDetailVO; +import org.apache.cloudstack.resourcedetail.ResourceDetailsDao; + +import com.cloud.utils.db.GenericDao; + +public interface NetworkACLListDetailsDao extends GenericDao, ResourceDetailsDao { + +} \ No newline at end of file diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLListDetailsDaoImpl.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLListDetailsDaoImpl.java new file mode 100644 index 00000000000..0b7037f7975 --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLListDetailsDaoImpl.java @@ -0,0 +1,33 @@ +// 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.resourcedetail.dao; + +import javax.ejb.Local; + +import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; +import org.apache.cloudstack.resourcedetail.NetworkACLListDetailVO; +import org.springframework.stereotype.Component; + +@Component +@Local(value = { NetworkACLListDetailsDao.class }) +public class NetworkACLListDetailsDaoImpl extends ResourceDetailsDaoBase implements NetworkACLListDetailsDao { + + @Override + public void addDetail(long resourceId, String key, String value) { + super.addDetail(new NetworkACLListDetailVO(resourceId, key, value)); + } +} diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcDetailsDao.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcDetailsDao.java new file mode 100644 index 00000000000..8ebd5005d61 --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcDetailsDao.java @@ -0,0 +1,26 @@ +// 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.resourcedetail.dao; + +import org.apache.cloudstack.resourcedetail.ResourceDetailsDao; +import org.apache.cloudstack.resourcedetail.VpcDetailVO; + +import com.cloud.utils.db.GenericDao; + +public interface VpcDetailsDao extends GenericDao, ResourceDetailsDao { + +} diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcDetailsDaoImpl.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcDetailsDaoImpl.java new file mode 100644 index 00000000000..64597231009 --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcDetailsDaoImpl.java @@ -0,0 +1,33 @@ +// 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.resourcedetail.dao; + +import javax.ejb.Local; + +import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; +import org.apache.cloudstack.resourcedetail.VpcDetailVO; +import org.springframework.stereotype.Component; + +@Component +@Local(value = { VpcDetailsDao.class }) +public class VpcDetailsDaoImpl extends ResourceDetailsDaoBase implements VpcDetailsDao { + + @Override + public void addDetail(long resourceId, String key, String value) { + super.addDetail(new VpcDetailVO(resourceId, key, value)); + } +} diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcGatewayDetailsDao.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcGatewayDetailsDao.java new file mode 100644 index 00000000000..4f1691926a8 --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcGatewayDetailsDao.java @@ -0,0 +1,27 @@ +// 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.resourcedetail.dao; + +import org.apache.cloudstack.resourcedetail.ResourceDetailsDao; +import org.apache.cloudstack.resourcedetail.VpcGatewayDetailVO; + +import com.cloud.utils.db.GenericDao; + +public interface VpcGatewayDetailsDao extends GenericDao, ResourceDetailsDao { + +} + diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcGatewayDetailsDaoImpl.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcGatewayDetailsDaoImpl.java new file mode 100644 index 00000000000..2b4c563a4cf --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcGatewayDetailsDaoImpl.java @@ -0,0 +1,33 @@ +// 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.resourcedetail.dao; + +import javax.ejb.Local; + +import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; +import org.apache.cloudstack.resourcedetail.VpcGatewayDetailVO; +import org.springframework.stereotype.Component; + +@Component +@Local(value = { VpcGatewayDetailsDao.class }) +public class VpcGatewayDetailsDaoImpl extends ResourceDetailsDaoBase implements VpcGatewayDetailsDao { + + @Override + public void addDetail(long resourceId, String key, String value) { + super.addDetail(new VpcGatewayDetailVO(resourceId, key, value)); + } +} \ No newline at end of file diff --git a/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateServiceImpl.java b/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateServiceImpl.java index b88460203c8..dbd95e8b35f 100644 --- a/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateServiceImpl.java +++ b/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateServiceImpl.java @@ -364,7 +364,7 @@ public class TemplateServiceImpl implements TemplateService { tmpltInfo.getSize() - UriUtils.getRemoteSize(tmplt.getUrl())); } catch (ResourceAllocationException e) { s_logger.warn(e.getMessage()); - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, zoneId, null, e.getMessage(), e.getMessage()); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, zoneId, null, e.getMessage(), e.getMessage()); } finally { _resourceLimitMgr.recalculateResourceCount(accountId, _accountMgr.getAccount(accountId).getDomainId(), com.cloud.configuration.Resource.ResourceType.secondary_storage.getOrdinal()); diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/XenserverSnapshotStrategy.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/XenserverSnapshotStrategy.java index 22182b1615e..14fb6180861 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/XenserverSnapshotStrategy.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/XenserverSnapshotStrategy.java @@ -201,7 +201,7 @@ public class XenserverSnapshotStrategy extends SnapshotStrategyBase { return true; } - if (!Snapshot.State.BackedUp.equals(snapshotVO.getState())) { + if (!Snapshot.State.BackedUp.equals(snapshotVO.getState()) && !Snapshot.State.Error.equals(snapshotVO.getState())) { throw new InvalidParameterValueException("Can't delete snapshotshot " + snapshotId + " due to it is in " + snapshotVO.getState() + " Status"); } diff --git a/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/provider/DefaultHostListener.java b/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/provider/DefaultHostListener.java index d2984e20da6..4838bf678e0 100644 --- a/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/provider/DefaultHostListener.java +++ b/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/provider/DefaultHostListener.java @@ -63,7 +63,7 @@ public class DefaultHostListener implements HypervisorHostListener { if (!answer.getResult()) { String msg = "Unable to attach storage pool" + poolId + " to the host" + hostId; - alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, pool.getDataCenterId(), pool.getPodId(), msg, msg); + alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, pool.getDataCenterId(), pool.getPodId(), msg, msg); throw new CloudRuntimeException("Unable establish connection from storage head to storage pool " + pool.getId() + " due to " + answer.getDetails() + pool.getId()); } diff --git a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java index 284f9932ae8..9f71abd7003 100644 --- a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java +++ b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java @@ -25,9 +25,6 @@ import java.util.Map; import javax.inject.Inject; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; - import org.apache.cloudstack.engine.cloud.entity.api.VolumeEntity; import org.apache.cloudstack.engine.subsystem.api.storage.ChapInfo; import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; @@ -60,6 +57,8 @@ import org.apache.cloudstack.storage.datastore.PrimaryDataStoreProviderManager; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO; import org.apache.cloudstack.storage.to.VolumeObjectTO; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; import com.cloud.agent.api.Answer; import com.cloud.agent.api.storage.ListVolumeAnswer; @@ -1204,7 +1203,7 @@ public class VolumeServiceImpl implements VolumeService { com.cloud.configuration.Resource.ResourceType.secondary_storage, volInfo.getSize() - volInfo.getPhysicalSize()); } catch (ResourceAllocationException e) { s_logger.warn(e.getMessage()); - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, volume.getDataCenterId(), volume.getPodId(), e.getMessage(), + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, volume.getDataCenterId(), volume.getPodId(), e.getMessage(), e.getMessage()); } finally { _resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(), diff --git a/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java b/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java index 3e7138f46d7..1058da3fedd 100644 --- a/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java +++ b/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java @@ -40,13 +40,12 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.log4j.Logger; - import org.apache.cloudstack.framework.config.ConfigDepot; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.Configurable; import org.apache.cloudstack.managed.context.ManagedContextRunnable; import org.apache.cloudstack.utils.identity.ManagementServerNode; +import org.apache.log4j.Logger; import com.cloud.cluster.dao.ManagementServerHostDao; import com.cloud.cluster.dao.ManagementServerHostPeerDao; @@ -256,15 +255,15 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C try { if (s_logger.isDebugEnabled()) { s_logger.debug("Cluster PDU " + getSelfPeerName() + " -> " + pdu.getDestPeer() + ". agent: " + pdu.getAgentId() + ", pdu seq: " + - pdu.getSequenceId() + ", pdu ack seq: " + pdu.getAckSequenceId() + ", json: " + pdu.getJsonPackage()); + pdu.getSequenceId() + ", pdu ack seq: " + pdu.getAckSequenceId() + ", json: " + pdu.getJsonPackage()); } long startTick = System.currentTimeMillis(); String strResult = peerService.execute(pdu); if (s_logger.isDebugEnabled()) { s_logger.debug("Cluster PDU " + getSelfPeerName() + " -> " + pdu.getDestPeer() + " completed. time: " + - (System.currentTimeMillis() - startTick) + "ms. agent: " + pdu.getAgentId() + ", pdu seq: " + pdu.getSequenceId() + - ", pdu ack seq: " + pdu.getAckSequenceId() + ", json: " + pdu.getJsonPackage()); + (System.currentTimeMillis() - startTick) + "ms. agent: " + pdu.getAgentId() + ", pdu seq: " + pdu.getSequenceId() + + ", pdu ack seq: " + pdu.getAckSequenceId() + ", json: " + pdu.getJsonPackage()); } if ("true".equals(strResult)) @@ -274,7 +273,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C invalidatePeerService(pdu.getDestPeer()); if (s_logger.isInfoEnabled()) { s_logger.info("Exception on remote execution, peer: " + pdu.getDestPeer() + ", iteration: " + i + ", exception message :" + - e.getMessage()); + e.getMessage()); } } } @@ -564,7 +563,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C if (profiler.getDuration() >= HeartbeatInterval.value()) { if (s_logger.isDebugEnabled()) s_logger.debug("Management server heartbeat takes too long to finish. profiler: " + profiler.toString() + ", profilerHeartbeatUpdate: " + - profilerHeartbeatUpdate.toString() + ", profilerPeerScan: " + profilerPeerScan.toString()); + profilerHeartbeatUpdate.toString() + ", profilerPeerScan: " + profilerPeerScan.toString()); } } @@ -625,8 +624,10 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C if (_heartbeatConnection != null) { Connection conn = TransactionLegacy.getStandaloneConnection(); if (conn != null) { - _heartbeatConnection.reset(TransactionLegacy.getStandaloneConnection()); + _heartbeatConnection.reset(conn); } + // The stand-alone connection does not have to be closed here because there will be another reference to it. + // As a matter of fact, it will be assigned to the connection instance variable in the ConnectionConcierge class. } } @@ -720,7 +721,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C } } } - break; + break; case nodeRemoved: { List l = msg.getNodes(); @@ -730,11 +731,10 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C } } } - break; + break; default: break; - } } @@ -772,7 +772,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C s_logger.info("Found " + inactiveList.size() + " inactive management server node based on timestamp"); for (ManagementServerHostVO host : inactiveList) s_logger.info("management server node msid: " + host.getMsid() + ", name: " + host.getName() + ", service ip: " + host.getServiceIP() + - ", version: " + host.getVersion()); + ", version: " + host.getVersion()); } List downHostList = new ArrayList(); @@ -810,7 +810,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C if (_mshostPeerDao.countStateSeenInPeers(_mshostId, _runId, ManagementServerHost.State.Down) > 0) { String msg = - "We have detected that at least one management server peer reports that this management server is down, perform active fencing to avoid split-brain situation"; + "We have detected that at least one management server peer reports that this management server is down, perform active fencing to avoid split-brain situation"; s_logger.error(msg); throw new ActiveFencingException(msg); } @@ -831,7 +831,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C if (entry.getKey().longValue() != _mshostId.longValue()) { if (s_logger.isDebugEnabled()) { s_logger.debug("Detected management node left because of invalidated session, id:" + entry.getKey() + ", nodeIP:" + - entry.getValue().getServiceIP()); + entry.getValue().getServiceIP()); } invalidatedNodeList.add(entry.getValue()); } @@ -918,8 +918,8 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C if (profiler.getDuration() >= HeartbeatInterval.value()) { if (s_logger.isDebugEnabled()) s_logger.debug("Peer scan takes too long to finish. profiler: " + profiler.toString() + ", profilerQueryActiveList: " + - profilerQueryActiveList.toString() + ", profilerSyncClusterInfo: " + profilerSyncClusterInfo.toString() + ", profilerInvalidatedNodeList: " + - profilerInvalidatedNodeList.toString() + ", profilerRemovedList: " + profilerRemovedList.toString()); + profilerQueryActiveList.toString() + ", profilerSyncClusterInfo: " + profilerSyncClusterInfo.toString() + ", profilerInvalidatedNodeList: " + + profilerInvalidatedNodeList.toString() + ", profilerRemovedList: " + profilerRemovedList.toString()); } } @@ -970,7 +970,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C } _mshostDao.update(mshost.getId(), getCurrentRunId(), NetUtils.getHostName(), version, _clusterNodeIP, _currentServiceAdapter.getServicePort(), - DateUtil.currentGMTTime()); + DateUtil.currentGMTTime()); } return mshost; @@ -1165,19 +1165,19 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C throw new ConfigurationException(msg); } else { String msg = - "Detected another management node with localhost IP is considered as running in DB, however it is not pingable, we will continue cluster initialization with this management server node"; + "Detected another management node with localhost IP is considered as running in DB, however it is not pingable, we will continue cluster initialization with this management server node"; s_logger.info(msg); } } else { if (pingManagementNode(peer.getMsid())) { String msg = - "Detected that another management node with the same IP " + peer.getServiceIP() + + "Detected that another management node with the same IP " + peer.getServiceIP() + " is already running, please check your cluster configuration"; s_logger.error(msg); throw new ConfigurationException(msg); } else { String msg = - "Detected that another management node with the same IP " + peer.getServiceIP() + + "Detected that another management node with the same IP " + peer.getServiceIP() + " is considered as running in DB, however it is not pingable, we will continue cluster initialization with this management server node"; s_logger.info(msg); } diff --git a/framework/ipc/src/org/apache/cloudstack/framework/serializer/OnwireClassRegistry.java b/framework/ipc/src/org/apache/cloudstack/framework/serializer/OnwireClassRegistry.java index 177ae09a592..83c8a4291e8 100644 --- a/framework/ipc/src/org/apache/cloudstack/framework/serializer/OnwireClassRegistry.java +++ b/framework/ipc/src/org/apache/cloudstack/framework/serializer/OnwireClassRegistry.java @@ -32,6 +32,8 @@ import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; +import org.apache.commons.io.IOUtils; + // // Finding classes in a given package code is taken and modified from // Credit: http://internna.blogspot.com/2007/11/java-5-retrieving-all-classes-from.html @@ -39,7 +41,7 @@ import java.util.jar.JarInputStream; public class OnwireClassRegistry { private List packages = new ArrayList(); - private Map> registry = new HashMap>(); + private final Map> registry = new HashMap>(); public OnwireClassRegistry() { registry.put("Object", Object.class); @@ -166,13 +168,15 @@ public class OnwireClassRegistry { } } } + IOUtils.closeQuietly(jarFile); } } while (jarEntry != null); + IOUtils.closeQuietly(jarFile); return classes; } static String stripFilenameExtension(String file) { return file.substring(0, file.lastIndexOf('.')); } -} +} \ No newline at end of file diff --git a/framework/rest/.gitignore b/framework/rest/.gitignore new file mode 100644 index 00000000000..ea8c4bf7f35 --- /dev/null +++ b/framework/rest/.gitignore @@ -0,0 +1 @@ +/target diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/.nuget/NuGet.targets b/plugins/hypervisors/hyperv/DotNet/ServerResource/.nuget/NuGet.targets index d0ebc7535f3..a56da2432df 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/.nuget/NuGet.targets +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/.nuget/NuGet.targets @@ -2,7 +2,7 @@ $(MSBuildProjectDirectory)\..\ - + false @@ -11,11 +11,10 @@ true - + false - @@ -25,37 +24,34 @@ --> - + $([System.IO.Path]::Combine($(SolutionDir), ".nuget")) $([System.IO.Path]::Combine($(ProjectDir), "packages.config")) - - + + $(SolutionDir).nuget - packages.config + $(ProjectDir)packages.config - + $(NuGetToolsPath)\NuGet.exe @(PackageSource) - - "$(NuGetExePath)" - mono --runtime=v4.0.30319 $(NuGetExePath) + + "$(NuGetExePath)" + mono --runtime=v4.0.30319 $(NuGetExePath) $(TargetDir.Trim('\\')) - + -RequireConsent -NonInteractive - - "$(SolutionDir) " - "$(SolutionDir)" - $(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir) - $(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols + $(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir "$(SolutionDir)\" + $(NuGetCommand) pack "$(ProjectPath)" -Properties Configuration=$(Configuration) $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols @@ -87,22 +83,22 @@ - + Condition="( '$(OS)' != 'Windows_NT' Or '$(BuildWithMono)' == 'true' ) And Exists('$(PackagesConfig)')" /> + + Condition="'$(OS)' == 'Windows_NT' And '$(BuildWithMono)' != 'true' And Exists('$(PackagesConfig)')" /> - - + + + Condition=" '$(OS)' == 'Windows_NT' And '$(BuildWithMono)' != 'true' " /> - + @@ -133,4 +129,4 @@ - \ No newline at end of file + diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentShell.csproj b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentShell.csproj index 39fef1606a2..a4c6b1fc073 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentShell.csproj +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentShell.csproj @@ -70,6 +70,7 @@ ..\packages\NSubstitute.1.6.1.0\lib\NET40\NSubstitute.dll + @@ -101,6 +102,12 @@ + + Component + + + ProjectInstaller.cs + True @@ -137,4 +144,4 @@ --> - + \ No newline at end of file diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/Program.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/Program.cs index 10663708508..e84350020c4 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/Program.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/Program.cs @@ -21,12 +21,15 @@ using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; +using System.Configuration.Install; +using System.Collections; namespace CloudStack.Plugin.AgentShell { static class Program { private static ILog logger = LogManager.GetLogger(typeof(Program)); + private static string serviceName = "CloudStack ServerResource"; /// /// Application entry point allows service to run in console application or as a Windows service. @@ -34,25 +37,174 @@ namespace CloudStack.Plugin.AgentShell /// static void Main(params string[] args) { - string arg1 = string.Empty; - - if (args.Length > 0) - { - arg1 = args[0]; - logger.DebugFormat("CloudStack ServerResource arg is ", arg1); - } - - if (string.Compare(arg1, "--console", true) == 0) - { - logger.InfoFormat("CloudStack ServerResource running as console app"); - new AgentService().RunConsole(args); - } - else + if (args.Length == 0) { logger.InfoFormat("CloudStack ServerResource running as Windows Service"); ServiceBase[] ServicesToRun = new ServiceBase[] { new AgentService() }; ServiceBase.Run(ServicesToRun); } + else if (args.Length == 1) + { + logger.DebugFormat("CloudStack ServerResource arg is ", args[0]); + switch (args[0]) + { + case "--install": + logger.InfoFormat("Installing and running CloudStack ServerResource "); + InstallService(); + StartService(); + break; + case "--uninstall": + logger.InfoFormat("stopping and uninstalling CloudStack ServerResource "); + StopService(); + UninstallService(); + break; + case "--console": + logger.InfoFormat("CloudStack ServerResource running as console app"); + new AgentService().RunConsole(args); + break; + default: + throw new NotImplementedException(); + } + } + } + + private static bool IsInstalled() + { + using (ServiceController controller = + new ServiceController(serviceName)) + { + try + { + ServiceControllerStatus status = controller.Status; + } + catch + { + return false; + } + return true; + } + } + + private static bool IsRunning() + { + using (ServiceController controller = + new ServiceController(serviceName)) + { + if (!IsInstalled()) return false; + return (controller.Status == ServiceControllerStatus.Running); + } + } + + private static AssemblyInstaller GetInstaller() + { + AssemblyInstaller installer = new AssemblyInstaller( + typeof(Program).Assembly, null); + installer.UseNewContext = true; + return installer; + } + + private static void InstallService() + { + if (IsInstalled()) return; + + try + { + using (AssemblyInstaller installer = GetInstaller()) + { + IDictionary state = new Hashtable(); + try + { + installer.Install(state); + installer.Commit(state); + } + catch + { + try + { + installer.Rollback(state); + } + catch { } + throw; + } + } + } + catch (Exception ex) + { + logger.ErrorFormat(" Error occured in installing service " + ex.Message); + throw; + } + } + + private static void UninstallService() + { + if (!IsInstalled()) return; + try + { + using (AssemblyInstaller installer = GetInstaller()) + { + IDictionary state = new Hashtable(); + try + { + installer.Uninstall(state); + } + catch + { + throw; + } + } + } + catch (Exception ex) + { + logger.ErrorFormat(" Error occured in uninstalling service " + ex.Message); + throw; + } + } + + private static void StartService() + { + if (!IsInstalled()) return; + + using (ServiceController controller = + new ServiceController(serviceName)) + { + try + { + if (controller.Status != ServiceControllerStatus.Running) + { + controller.Start(); + controller.WaitForStatus(ServiceControllerStatus.Running, + TimeSpan.FromSeconds(10)); + } + } + catch (Exception ex) + { + logger.ErrorFormat(" Error occured in starting service " + ex.Message); + throw; + } + } + } + + private static void StopService() + { + if (!IsInstalled()) return; + using (ServiceController controller = + new ServiceController(serviceName)) + { + try + { + if (controller.Status != ServiceControllerStatus.Stopped) + { + controller.Stop(); + controller.WaitForStatus(ServiceControllerStatus.Stopped, + TimeSpan.FromSeconds(10)); + } + } + catch (Exception ex) + { + logger.ErrorFormat(" Error occured in stopping service " + ex.Message); + throw; + } + } } } } diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/ProjectInstaller.Designer.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/ProjectInstaller.Designer.cs new file mode 100644 index 00000000000..a10cbb002fd --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/ProjectInstaller.Designer.cs @@ -0,0 +1,76 @@ +// 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. +namespace CloudStack.Plugin.AgentShell +{ + partial class ProjectInstaller + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); + this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); + // + // serviceProcessInstaller1 + // + this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem; + this.serviceProcessInstaller1.Password = null; + this.serviceProcessInstaller1.Username = null; + // + // serviceInstaller1 + // + this.serviceInstaller1.Description = "CloudStack Agent"; + this.serviceInstaller1.DisplayName = "CloudStack ServerResource"; + this.serviceInstaller1.ServiceName = "CloudStack ServerResource"; + this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic; + // + // ProjectInstaller + // + this.Installers.AddRange(new System.Configuration.Install.Installer[] { + this.serviceProcessInstaller1, + this.serviceInstaller1}); + + } + + #endregion + + private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1; + private System.ServiceProcess.ServiceInstaller serviceInstaller1; + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/ProjectInstaller.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/ProjectInstaller.cs new file mode 100644 index 00000000000..78356c64848 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/ProjectInstaller.cs @@ -0,0 +1,35 @@ +// 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. +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration.Install; +using System.Linq; +using System.Threading.Tasks; + +namespace CloudStack.Plugin.AgentShell +{ + [RunInstaller(true)] + public partial class ProjectInstaller : System.Configuration.Install.Installer + { + public ProjectInstaller() + { + InitializeComponent(); + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/CloudStackTypes.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/CloudStackTypes.cs index dfc3e206f06..ce1b1e8c6eb 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/CloudStackTypes.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/CloudStackTypes.cs @@ -31,23 +31,114 @@ namespace HypervResource { public class PrimaryDataStoreTO { - public string path; + private string path; + public string host; + private string poolType; + public Uri uri; + public string _role; + + public string Path + { + get + { + if (this.isLocal) + { + return path; + } + else + { + return this.UncPath; + } + } + set + { + this.path = value; + } + } + + public string UncPath + { + get + { + string uncPath = null; + if (uri.Scheme.Equals("cifs") || uri.Scheme.Equals("networkfilesystem")) + { + uncPath = @"\\" + uri.Host + uri.LocalPath; + } + return uncPath; + } + } + + public string User + { + get + { + var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query); + return System.Web.HttpUtility.UrlDecode(queryDictionary["user"]); + } + } + + public string Password + { + get + { + var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query); + return System.Web.HttpUtility.UrlDecode(queryDictionary["password"]); + } + } + + public string Domain + { + get + { + var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query); + if (queryDictionary["domain"] != null) + { + return System.Web.HttpUtility.UrlDecode(queryDictionary["domain"]); + } + else return uri.Host; + } + } + + public Boolean isLocal + { + get + { + if (poolType.Equals("Filesystem")) + { + return true; + } + else + { + return false; + } + } + } public static PrimaryDataStoreTO ParseJson(dynamic json) { PrimaryDataStoreTO result = null; - if (json == null) { return result; } + dynamic primaryDataStoreTOJson = json[CloudStackTypes.PrimaryDataStoreTO]; if (primaryDataStoreTOJson != null) { result = new PrimaryDataStoreTO() { - path = (string)primaryDataStoreTOJson.path + path = (string)primaryDataStoreTOJson.path, + host = (string)primaryDataStoreTOJson.host, + poolType = (string)primaryDataStoreTOJson.poolType }; + + if (!result.isLocal) + { + // Delete security credentials in original command. Prevents logger from spilling the beans, as it were. + String uriStr = @"cifs://" + result.host + result.path; + result.uri = new Uri(uriStr); + } } return result; } @@ -61,12 +152,23 @@ namespace HypervResource { get { - String result = Path.Combine(this.primaryDataStore.path, this.name); + string fileName = null; + if (this.primaryDataStore.isLocal) + { + fileName = Path.Combine(this.primaryDataStore.Path, this.name); + } + else + { + fileName = @"\\" + this.primaryDataStore.uri.Host + this.primaryDataStore.uri.LocalPath + @"\" + this.name; + fileName = fileName.Replace(@"/", @"\"); + } + if (this.format != null) { - result = result + "." + this.format.ToLowerInvariant(); + fileName = fileName + "." + this.format.ToLowerInvariant(); } - return result; + + return fileName; } } @@ -74,6 +176,7 @@ namespace HypervResource public string format; public string name; public string uuid; + public ulong size; public PrimaryDataStoreTO primaryDataStore; public static VolumeObjectTO ParseJson(dynamic json) @@ -93,7 +196,8 @@ namespace HypervResource dataStore = volumeObjectTOJson.dataStore, format = ((string)volumeObjectTOJson.format), name = (string)volumeObjectTOJson.name, - uuid = (string)volumeObjectTOJson.uuid + uuid = (string)volumeObjectTOJson.uuid, + size = (ulong)volumeObjectTOJson.size }; result.primaryDataStore = PrimaryDataStoreTO.ParseJson(volumeObjectTOJson.dataStore); @@ -116,11 +220,16 @@ namespace HypervResource { logger.Info("No image format in VolumeObjectTO, going to use format from first file that matches " + volInfo.FullFileName); - string[] choices = Directory.GetFiles(volInfo.primaryDataStore.path, volInfo.name + ".vhd*"); + string path = volInfo.primaryDataStore.Path; + if (!volInfo.primaryDataStore.isLocal) + { + path = volInfo.primaryDataStore.UncPath; + } + string[] choices = choices = Directory.GetFiles(path, volInfo.name + ".vhd*"); if (choices.Length != 1) { - String errMsg = "Tried to guess file extension, but cannot find file corresponding to " + Path.Combine(volInfo.primaryDataStore.path, volInfo.name); // format being guessed. + String errMsg = "Tried to guess file extension, but cannot find file corresponding to " + Path.Combine(volInfo.primaryDataStore.Path, volInfo.name); // format being guessed. logger.Debug(errMsg); } else @@ -145,7 +254,16 @@ namespace HypervResource { if (String.IsNullOrEmpty(this.path)) { - return Path.Combine(this.primaryDataStore.path, this.name) + '.' + this.format.ToLowerInvariant(); + string fileName = null; + if (this.primaryDataStore.isLocal) + { + fileName = Path.Combine(this.primaryDataStore.Path, this.name); + } + else + { + fileName = @"\\" + this.primaryDataStore.uri.Host + this.primaryDataStore.uri.LocalPath + @"\" + this.name; + } + return fileName +'.' + this.format.ToLowerInvariant(); } return this.path; } @@ -196,20 +314,23 @@ namespace HypervResource public static S3TO ParseJson(dynamic json) { S3TO result = null; - dynamic s3TOJson = json[CloudStackTypes.S3TO]; - if (s3TOJson != null) + if (json != null) { - result = new S3TO() + dynamic s3TOJson = json[CloudStackTypes.S3TO]; + if (s3TOJson != null) { - bucketName = (string)s3TOJson.bucketName, - secretKey = (string)s3TOJson.secretKey, - accessKey = (string)s3TOJson.accessKey, - endpoint = (string)s3TOJson.endPoint, - httpsFlag = (bool)s3TOJson.httpsFlag - }; - // Delete security credentials in original command. Prevents logger from spilling the beans, as it were. - s3TOJson.secretKey = string.Empty; - s3TOJson.accessKey = string.Empty; + result = new S3TO() + { + bucketName = (string)s3TOJson.bucketName, + secretKey = (string)s3TOJson.secretKey, + accessKey = (string)s3TOJson.accessKey, + endpoint = (string)s3TOJson.endPoint, + httpsFlag = (bool)s3TOJson.httpsFlag + }; + // Delete security credentials in original command. Prevents logger from spilling the beans, as it were. + s3TOJson.secretKey = string.Empty; + s3TOJson.accessKey = string.Empty; + } } return result; } @@ -264,16 +385,19 @@ namespace HypervResource public static NFSTO ParseJson(dynamic json) { NFSTO result = null; - dynamic nfsTOJson = json[CloudStackTypes.NFSTO]; - if (nfsTOJson != null) + if (json != null) { - result = new NFSTO() + dynamic nfsTOJson = json[CloudStackTypes.NFSTO]; + if (nfsTOJson != null) { - _role = (string)nfsTOJson._role, - }; - // Delete security credentials in original command. Prevents logger from spilling the beans, as it were. - String uriStr = (String)nfsTOJson._url; - result.uri = new Uri(uriStr); + result = new NFSTO() + { + _role = (string)nfsTOJson._role, + }; + // Delete security credentials in original command. Prevents logger from spilling the beans, as it were. + String uriStr = (String)nfsTOJson._url; + result.uri = new Uri(uriStr); + } } return result; } diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResource.csproj b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResource.csproj index 05a0f513d8b..a2dc323d5ef 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResource.csproj +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResource.csproj @@ -63,6 +63,7 @@ ..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll + diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResourceController.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResourceController.cs index 0d56fef0acd..f5008123930 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResourceController.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResourceController.cs @@ -23,7 +23,10 @@ using Microsoft.CSharp.RuntimeBinder; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; +using System.Collections; +using System.Collections.Specialized; using System.Collections.Generic; +using System.Configuration; using System.IO; using System.Linq; using System.Net; @@ -78,6 +81,31 @@ namespace HypervResource public ulong ParentPartitionMinMemoryMb; public string LocalSecondaryStoragePath; public string systemVmIso; + + private string getPrimaryKey(string id) + { + return "primary_storage_" + id; + } + + public string getPrimaryStorage(string id) + { + NameValueCollection settings = ConfigurationManager.AppSettings; + return settings.Get(getPrimaryKey(id)); + } + + public void setPrimaryStorage(string id, string path) + { + Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); + KeyValueConfigurationCollection settings = config.AppSettings.Settings; + string key = getPrimaryKey(id); + if (settings[key] != null) + { + settings.Remove(key); + } + settings.Add(key, path); + config.Save(ConfigurationSaveMode.Modified); + ConfigurationManager.RefreshSection("appSettings"); + } } /// @@ -114,6 +142,7 @@ namespace HypervResource private static ILog logger = LogManager.GetLogger(typeof(HypervResourceController)); private static string systemVmIso; + Dictionary contextMap = new Dictionary(); public static void Initialize() { @@ -175,7 +204,8 @@ namespace HypervResource { result = result, details = "success - NOP", - _reconnect = false + _reconnect = false, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.SetupAnswer); @@ -220,7 +250,8 @@ namespace HypervResource object ansContent = new { result = result, - details = details + details = details, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.AttachAnswer); @@ -264,7 +295,8 @@ namespace HypervResource object ansContent = new { result = result, - details = details + details = details, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.DettachAnswer); @@ -307,7 +339,8 @@ namespace HypervResource object ansContent = new { result = result, - details = details + details = details, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.RebootAnswer); @@ -369,7 +402,8 @@ namespace HypervResource object ansContent = new { result = result, - details = details + details = details, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); @@ -484,7 +518,8 @@ namespace HypervResource { result = result, details = details, - volume = volume + volume = volume, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CreateAnswer); } @@ -552,7 +587,8 @@ namespace HypervResource result = result, details = details, templateSize = size, - installPath = newCopyFileName + installPath = newCopyFileName, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.PrimaryStorageDownloadAnswer); } @@ -654,7 +690,8 @@ namespace HypervResource object ansContent = new { result = true, - details = "resource is alive" + details = "resource is alive", + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckHealthAnswer); } @@ -672,7 +709,8 @@ namespace HypervResource object ansContent = new { result = true, - details = "NOP, TODO: implement properly" + details = "NOP, TODO: implement properly", + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckSshAnswer); } @@ -700,7 +738,7 @@ namespace HypervResource } else { - state = EnabledState.ToString(sys.EnabledState); // TODO: V2 changes? + state = EnabledState.ToCloudStackState(sys.EnabledState); // TODO: V2 changes? result = true; } @@ -708,7 +746,8 @@ namespace HypervResource { result = result, details = details, - state = state + state = state, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckVirtualMachineAnswer); } @@ -725,7 +764,8 @@ namespace HypervResource object ansContent = new { result = true, - details = "Current implementation does not delete local path corresponding to storage pool!" + details = "Current implementation does not delete local path corresponding to storage pool!", + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); } @@ -747,7 +787,8 @@ namespace HypervResource object ansContent = new { result = true, - details = "success - NOP" + details = "success - NOP", + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); } @@ -772,7 +813,8 @@ namespace HypervResource ansContent = new { result = result, - details = details + details = details, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); } @@ -815,7 +857,8 @@ namespace HypervResource result = result, details = details, templateInfo = tInfo, - poolInfo = poolInfo + poolInfo = poolInfo, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.ModifyStoragePoolAnswer); @@ -857,7 +900,8 @@ namespace HypervResource object ansContent = new { result = false, - details = "nothing to cleanup in our current implementation" + details = "nothing to cleanup in our current implementation", + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); } @@ -874,7 +918,8 @@ namespace HypervResource object ansContent = new { result = true, - details = (string)null + details = (string)null, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckNetworkAnswer); } @@ -891,7 +936,8 @@ namespace HypervResource object ansContent = new { result = true, - details = (string)null + details = (string)null, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.ReadyAnswer); } @@ -924,7 +970,8 @@ namespace HypervResource { result = result, details = details, - vm = cmd.vm + vm = cmd.vm, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.StartAnswer); } @@ -956,12 +1003,73 @@ namespace HypervResource { result = result, details = details, - vm = cmd.vm + vm = cmd.vm, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.StopAnswer); } } + // POST api/HypervResource/CreateObjectCommand + [HttpPost] + [ActionName(CloudStackTypes.CreateObjectCommand)] + public JContainer CreateObjectCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.CreateObjectCommand + cmd.ToString()); + + bool result = false; + string details = null; + + try + { + VolumeObjectTO volume = VolumeObjectTO.ParseJson(cmd.data); + PrimaryDataStoreTO primary = volume.primaryDataStore; + ulong volumeSize = volume.size; + string volumeName = volume.name + ".vhdx"; + string volumePath = null; + + if (primary.isLocal) + { + volumePath = Path.Combine(primary.Path, volumeName); + } + else + { + volumePath = @"\\" + primary.uri.Host + primary.uri.LocalPath + @"\" + volumeName; + volumePath = volumePath.Replace('/', '\\'); + Utils.ConnectToRemote(primary.UncPath, primary.Domain, primary.User, primary.Password); + } + + wmiCallsV2.CreateDynamicVirtualHardDisk(volumeSize, volumePath); + if (File.Exists(volumePath)) + { + result = true; + } + else + { + details = "Failed to create disk with name " + volumePath; + } + } + catch (Exception ex) + { + // Test by providing wrong key + details = CloudStackTypes.CreateObjectCommand + " failed on exception, " + ex.Message; + logger.Error(details, ex); + } + + object ansContent = new + { + result = result, + details = details, + data = cmd.data, + contextMap = contextMap + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CreateObjectAnswer); + } + } + // POST api/HypervResource/MaintainCommand // TODO: should this be a NOP? [HttpPost] @@ -976,7 +1084,8 @@ namespace HypervResource { result = true, details = "success - NOP for MaintainCommand", - _reconnect = false + _reconnect = false, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.MaintainAnswer); @@ -997,7 +1106,8 @@ namespace HypervResource { result = true, details = "success - NOP for PingRoutingCommand", - _reconnect = false + _reconnect = false, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); @@ -1018,7 +1128,8 @@ namespace HypervResource { result = true, details = "success - NOP for PingCommand", - _reconnect = false + _reconnect = false, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); @@ -1034,7 +1145,6 @@ namespace HypervResource { logger.Info(CloudStackTypes.GetVmStatsCommand + cmd.ToString()); bool result = false; - string details = null; JArray vmNamesJson = cmd.vmNames; string[] vmNames = vmNamesJson.ToObject(); Dictionary vmProcessorInfo = new Dictionary(vmNames.Length); @@ -1061,9 +1171,9 @@ namespace HypervResource object ansContent = new { - vmInfos = vmProcessorInfo, + vmStatsMap = vmProcessorInfo, result = result, - details = details, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.GetVmStatsAnswer); } @@ -1092,14 +1202,24 @@ namespace HypervResource logger.Info(CloudStackTypes.CopyCommand + cmd.ToString()); + string destFile = null; + if (destTemplateObjectTO != null && destTemplateObjectTO.primaryDataStore != null) + { + destFile = destTemplateObjectTO.FullFileName; + if (!destTemplateObjectTO.primaryDataStore.isLocal) + { + PrimaryDataStoreTO primary = destTemplateObjectTO.primaryDataStore; + Utils.ConnectToRemote(primary.UncPath, primary.Domain, primary.User, primary.Password); + } + } + // Already exists? - if (destTemplateObjectTO != null && - File.Exists(destTemplateObjectTO.FullFileName) && + if (destFile != null && File.Exists(destFile) && !String.IsNullOrEmpty(destTemplateObjectTO.checksum)) { // TODO: checksum fails us, because it is of the compressed image. // ASK: should we store the compressed or uncompressed version or is the checksum not calculated correctly? - result = VerifyChecksum(destTemplateObjectTO.FullFileName, destTemplateObjectTO.checksum); + result = VerifyChecksum(destFile, destTemplateObjectTO.checksum); } // Do we have to create a new one? @@ -1112,8 +1232,6 @@ namespace HypervResource // NFS provider download to primary storage? if ((srcTemplateObjectTO.s3DataStoreTO != null || srcTemplateObjectTO.nfsDataStoreTO != null) && destTemplateObjectTO.primaryDataStore != null) { - string destFile = destTemplateObjectTO.FullFileName; - if (File.Exists(destFile)) { logger.Info("Deleting existing file " + destFile); @@ -1187,7 +1305,7 @@ namespace HypervResource { destVolumeObjectTO.format = srcTemplateObjectTO.format; } - string destFile = destVolumeObjectTO.FullFileName; + destFile = destVolumeObjectTO.FullFileName; string srcFile = srcTemplateObjectTO.FullFileName; if (!File.Exists(srcFile)) @@ -1225,7 +1343,8 @@ namespace HypervResource { result = result, details = details, - newData = cmd.destTO + newData = cmd.destTO, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CopyCmdAnswer); } @@ -1338,7 +1457,8 @@ namespace HypervResource result = result, details = details, capacity = capacity, - used = used + used = used, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.GetStorageStatsAnswer); } @@ -1399,7 +1519,8 @@ namespace HypervResource { result = result, hostStats = hostStats, - details = details + details = details, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.GetHostStatsAnswer); } @@ -1415,14 +1536,15 @@ namespace HypervResource logger.Info(CloudStackTypes.PrepareForMigrationCommand + cmd.ToString()); string details = null; - bool result = false; + bool result = true; try { - details = "NOP - failure"; + details = "NOP - success"; } catch (Exception sysEx) { + result = false; details = CloudStackTypes.PrepareForMigrationCommand + " failed due to " + sysEx.Message; logger.Error(details, sysEx); } @@ -1430,7 +1552,8 @@ namespace HypervResource object ansContent = new { result = result, - details = details + details = details, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.PrepareForMigrationAnswer); @@ -1451,7 +1574,10 @@ namespace HypervResource try { - details = "NOP - failure"; + string vm = (string)cmd.vmName; + string destination = (string)cmd.destIp; + wmiCallsV2.MigrateVm(vm, destination); + result = true; } catch (Exception sysEx) { @@ -1462,7 +1588,8 @@ namespace HypervResource object ansContent = new { result = result, - details = details + details = details, + contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.MigrateAnswer); @@ -1553,7 +1680,8 @@ namespace HypervResource poolInfo = pi, guid = pi.uuid, dataCenter = strtRouteCmd.dataCenter, - resourceType = StorageResourceType.STORAGE_POOL.ToString() // TODO: check encoding + resourceType = StorageResourceType.STORAGE_POOL.ToString(), // TODO: check encoding + contextMap = contextMap }; JObject ansObj = Utils.CreateCloudStackObject(CloudStackTypes.StartupStorageCommand, ansContent); cmdArray.Add(ansObj); diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/IWmiCallsV2.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/IWmiCallsV2.cs index 223f7481071..99ce35276b7 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/IWmiCallsV2.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/IWmiCallsV2.cs @@ -38,6 +38,7 @@ namespace HypervResource ComputerSystem DeployVirtualMachine(dynamic jsonObj, string systemVmIso); void DestroyVm(dynamic jsonObj); void DestroyVm(string displayName); + void MigrateVm(string vmName, string destination); void DetachDisk(string displayName, string diskFileName); ComputerSystem GetComputerSystem(string displayName); string GetDefaultDataRoot(); diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCallsV2.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCallsV2.cs index 0a3f008750b..c6c039a9bed 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCallsV2.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCallsV2.cs @@ -36,6 +36,26 @@ namespace HypervResource { public static String CloudStackUserDataKey = "cloudstack-vm-userdata"; + /// + /// Defines the migration types. + /// + public enum MigrationType + { + VirtualSystem = 32768, + Storage = 32769, + Staged = 32770, + VirtualSystemAndStorage = 32771 + }; + + /// + /// Defines migration transport types. + /// + public enum TransportType + { + TCP = 5, + SMB = 32768 + }; + public static void Initialize() { // Trigger assembly load into curren appdomain @@ -266,7 +286,10 @@ namespace HypervResource { string vhdFile = null; string diskName = null; + string isoPath = null; VolumeObjectTO volInfo = VolumeObjectTO.ParseJson(diskDrive.data); + TemplateObjectTO templateInfo = TemplateObjectTO.ParseJson(diskDrive.data); + if (volInfo != null) { // assert @@ -286,13 +309,13 @@ namespace HypervResource throw new ArgumentException(errMsg); } errMsg = vmName + ": Malformed PrimaryDataStore for disk " + diskDrive.ToString(); - if (String.IsNullOrEmpty(volInfo.primaryDataStore.path)) + if (String.IsNullOrEmpty(volInfo.primaryDataStore.Path)) { logger.Error(errMsg); throw new ArgumentException(errMsg); } - errMsg = vmName + ": Missing folder PrimaryDataStore for disk " + diskDrive.ToString() + ", missing path: " + volInfo.primaryDataStore.path; - if (!Directory.Exists(volInfo.primaryDataStore.path)) + errMsg = vmName + ": Missing folder PrimaryDataStore for disk " + diskDrive.ToString() + ", missing path: " + volInfo.primaryDataStore.Path; + if (!Directory.Exists(volInfo.primaryDataStore.Path)) { logger.Error(errMsg); throw new ArgumentException(errMsg); @@ -307,6 +330,13 @@ namespace HypervResource } logger.Debug("Going to create " + vmName + " with attached voluem " + diskName + " at " + vhdFile); } + else if (templateInfo != null && templateInfo.nfsDataStoreTO != null) + { + NFSTO share = templateInfo.nfsDataStoreTO; + Utils.ConnectToRemote(share.UncPath, share.Domain, share.User, share.Password); + // The share is mapped, now attach the iso + isoPath = Path.Combine(share.UncPath.Replace('/', Path.DirectorySeparatorChar), templateInfo.path); + } string driveType = diskDrive.type; @@ -333,6 +363,10 @@ namespace HypervResource logger.DebugFormat("Create disk type {1} (Named: {0}), on vm {2} {3}", diskName, driveResourceType, vmName, string.IsNullOrEmpty(vhdFile) ? " no disk to insert" : ", inserting disk" +vhdFile ); AddDiskDriveToVm(newVm, vhdFile, ideCtrllr, driveResourceType); + if (isoPath != null) + { + AttachIso(vmName, isoPath); + } } String publicIpAddress = ""; @@ -431,7 +465,15 @@ namespace HypervResource System.Threading.Thread.Sleep(90000); SetState(newVm, RequiredState.Reset); // wait for the second boot and then return with sucesss - pingResource(publicIpAddress); + //if publicIPAddress is empty or null don't ping the ip + if (publicIpAddress.Equals("") == true) + { + System.Threading.Thread.Sleep(90000); + } + else + { + pingResource(publicIpAddress); + } } logger.InfoFormat("Started VM {0}", vmName); return newVm; @@ -850,7 +892,46 @@ namespace HypervResource } while (vm != null); } - + + /// + /// Migrates a vm to the given destination host + /// + /// + /// + public void MigrateVm(string vmName, string destination) + { + ComputerSystem vm = GetComputerSystem(vmName); + VirtualSystemMigrationSettingData migrationSettingData = VirtualSystemMigrationSettingData.CreateInstance(); + VirtualSystemMigrationService service = GetVirtualisationSystemMigrationService(); + + IPAddress addr = IPAddress.Parse(destination); + IPHostEntry entry = Dns.GetHostEntry(addr); + string[] destinationHost = new string[] { destination }; + + migrationSettingData.LateBoundObject["MigrationType"] = MigrationType.VirtualSystem; + migrationSettingData.LateBoundObject["TransportType"] = TransportType.TCP; + migrationSettingData.LateBoundObject["DestinationIPAddressList"] = destinationHost; + string migrationSettings = migrationSettingData.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20); + + ManagementPath jobPath; + var ret_val = service.MigrateVirtualSystemToHost(vm.Path, entry.HostName, migrationSettings, null, null, out jobPath); + if (ret_val == ReturnCode.Started) + { + MigrationJobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed migrating VM {0} (GUID {1}) due to {2}", + vm.ElementName, + vm.Name, + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + /// /// Create new storage media resources, e.g. hard disk images and ISO disk images /// see http://msdn.microsoft.com/en-us/library/hh859775(v=vs.85).aspx @@ -1417,7 +1498,7 @@ namespace HypervResource // If the Job is done asynchronously if (ret_val == ReturnCode.Started) { - JobCompleted(jobPath); + StorageJobCompleted(jobPath); } else if (ret_val != ReturnCode.Completed) { @@ -1467,6 +1548,21 @@ namespace HypervResource throw ex; } + public VirtualSystemMigrationService GetVirtualisationSystemMigrationService() + { + + var virtSysMigSvcCollection = VirtualSystemMigrationService.GetInstances(); + foreach (VirtualSystemMigrationService item in virtSysMigSvcCollection) + { + return item; + } + + var errMsg = string.Format("No Hyper-V migration service subsystem on server"); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + /// /// Similar to http://msdn.microsoft.com/en-us/library/hh850031%28v=vs.85%29.aspx /// @@ -1500,6 +1596,58 @@ namespace HypervResource logger.DebugFormat("WMI job succeeded: {0}, Elapsed={1}", jobObj.Description, jobObj.ElapsedTime); } + private static void MigrationJobCompleted(ManagementPath jobPath) + { + MigrationJob jobObj = null; + for (;;) + { + jobObj = new MigrationJob(jobPath); + if (jobObj.JobState != JobState.Starting && jobObj.JobState != JobState.Running) + { + break; + } + logger.InfoFormat("In progress... {0}% completed.", jobObj.PercentComplete); + System.Threading.Thread.Sleep(1000); + } + + if (jobObj.JobState != JobState.Completed) + { + var errMsg = string.Format( + "Hyper-V Job failed, Error Code:{0}, Description: {1}", + jobObj.ErrorCode, + jobObj.ErrorDescription); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + + private static void StorageJobCompleted(ManagementPath jobPath) + { + StorageJob jobObj = null; + for (; ; ) + { + jobObj = new StorageJob(jobPath); + if (jobObj.JobState != JobState.Starting && jobObj.JobState != JobState.Running) + { + break; + } + logger.InfoFormat("In progress... {0}% completed.", jobObj.PercentComplete); + System.Threading.Thread.Sleep(1000); + } + + if (jobObj.JobState != JobState.Completed) + { + var errMsg = string.Format( + "Hyper-V Job failed, Error Code:{0}, Description: {1}", + jobObj.ErrorCode, + jobObj.ErrorDescription); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + public void GetProcessorResources(out uint cores, out uint mhz) { // Processor processors diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_MigrationJob.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_MigrationJob.cs new file mode 100644 index 00000000000..7b7e5f1d088 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_MigrationJob.cs @@ -0,0 +1,1867 @@ +// 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. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_MigrationJob + public class MigrationJob : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_MigrationJob"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public MigrationJob() { + this.InitializeObject(null, null, null); + } + + public MigrationJob(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(MigrationJob.ConstructPath(keyInstanceID)), null); + } + + public MigrationJob(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(MigrationJob.ConstructPath(keyInstanceID)), null); + } + + public MigrationJob(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public MigrationJob(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public MigrationJob(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public MigrationJob(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public MigrationJob(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public MigrationJob(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCancellableNull { + get { + if ((curObj["Cancellable"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates whether the job can be cancelled. The value of this property does not g" + + "uarantee that a request to cancel the job will succeed.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool Cancellable { + get { + if ((curObj["Cancellable"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["Cancellable"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDeleteOnCompletionNull { + get { + if ((curObj["DeleteOnCompletion"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool DeleteOnCompletion { + get { + if ((curObj["DeleteOnCompletion"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["DeleteOnCompletion"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Hostname the destination virtualization platform where the virtual system is migr" + + "ating. It will be NULL for storage migration.")] + public string DestinationHost { + get { + return ((string)(curObj["DestinationHost"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsElapsedTimeNull { + get { + if ((curObj["ElapsedTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime ElapsedTime { + get { + if ((curObj["ElapsedTime"] != null)) { + return ToDateTime(((string)(curObj["ElapsedTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsErrorCodeNull { + get { + if ((curObj["ErrorCode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ErrorCode { + get { + if ((curObj["ErrorCode"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ErrorCode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ErrorDescription { + get { + return ((string)(curObj["ErrorDescription"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ErrorSummaryDescription { + get { + return ((string)(curObj["ErrorSummaryDescription"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsJobRunTimesNull { + get { + if ((curObj["JobRunTimes"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint JobRunTimes { + get { + if ((curObj["JobRunTimes"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["JobRunTimes"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsJobStateNull { + get { + if ((curObj["JobState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort JobState { + get { + if ((curObj["JobState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["JobState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string JobStatus { + get { + return ((string)(curObj["JobStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsJobTypeNull { + get { + if ((curObj["JobType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates the type of Job being tracked by this object.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public JobTypeValues JobType { + get { + if ((curObj["JobType"] == null)) { + return ((JobTypeValues)(System.Convert.ToInt32(308))); + } + return ((JobTypeValues)(System.Convert.ToInt32(curObj["JobType"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLocalOrUtcTimeNull { + get { + if ((curObj["LocalOrUtcTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort LocalOrUtcTime { + get { + if ((curObj["LocalOrUtcTime"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["LocalOrUtcTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMigrationTypeNull { + get { + if ((curObj["MigrationType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The migration type as defined in Msvm_VirtualSystemMigrationSettingData.Migration" + + "Type. This can beused to identify the type of migration the job represents.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MigrationType { + get { + if ((curObj["MigrationType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MigrationType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"For Live Migration this must be set to NULL. For Storage Migration, it will specify the virtual machine's virtual hard drives which moved and where they moved. If not NULL, NewResourceSettingData will contain an array of embedded instances of resource allocation setting data (RASD) which represent VHDs. Destination location will be provided using Connection property of RASD.")] + public string[] NewResourceSettingData { + get { + return ((string[])(curObj["NewResourceSettingData"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"For Live Migration this will be set to NULL. For Storage Migration, it will indicate the new path for virtual machine data (ExternalDataRoot, SnapshotDataRoot and SwapFileDataRoot). This being NULL indicates that virtual machine's data roots are not moving. Otherwise NewSystemSettingData will be instance of Msvm_VirtualSystemGlobalSettingData containing properties ExternalDataRoot, SnapshotDataRoot and SwapFileDataRoot. If not NULL, ExternalDataRoot property will specify new location of virtual machine's current configuration and saved state. If not NULL, SnapshotDataRoot property will specify new location for snapshots data. If not NULL, SwapFileDataRoot property will specify new location of virtual machine's smart paging files ")] + public string NewSystemSettingData { + get { + return ((string)(curObj["NewSystemSettingData"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Notify { + get { + return ((string)(curObj["Notify"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherRecoveryAction { + get { + return ((string)(curObj["OtherRecoveryAction"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Owner { + get { + return ((string)(curObj["Owner"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentCompleteNull { + get { + if ((curObj["PercentComplete"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PercentComplete { + get { + if ((curObj["PercentComplete"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PercentComplete"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPriorityNull { + get { + if ((curObj["Priority"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Priority { + get { + if ((curObj["Priority"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Priority"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRecoveryActionNull { + get { + if ((curObj["RecoveryAction"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RecoveryAction { + get { + if ((curObj["RecoveryAction"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RecoveryAction"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRunDayNull { + get { + if ((curObj["RunDay"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public sbyte RunDay { + get { + if ((curObj["RunDay"] == null)) { + return System.Convert.ToSByte(0); + } + return ((sbyte)(curObj["RunDay"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRunDayOfWeekNull { + get { + if ((curObj["RunDayOfWeek"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public sbyte RunDayOfWeek { + get { + if ((curObj["RunDayOfWeek"] == null)) { + return System.Convert.ToSByte(0); + } + return ((sbyte)(curObj["RunDayOfWeek"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRunMonthNull { + get { + if ((curObj["RunMonth"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public byte RunMonth { + get { + if ((curObj["RunMonth"] == null)) { + return System.Convert.ToByte(0); + } + return ((byte)(curObj["RunMonth"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRunStartIntervalNull { + get { + if ((curObj["RunStartInterval"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime RunStartInterval { + get { + if ((curObj["RunStartInterval"] != null)) { + return ToDateTime(((string)(curObj["RunStartInterval"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsScheduledStartTimeNull { + get { + if ((curObj["ScheduledStartTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime ScheduledStartTime { + get { + if ((curObj["ScheduledStartTime"] != null)) { + return ToDateTime(((string)(curObj["ScheduledStartTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStartTimeNull { + get { + if ((curObj["StartTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime StartTime { + get { + if ((curObj["StartTime"] != null)) { + return ToDateTime(((string)(curObj["StartTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeBeforeRemovalNull { + get { + if ((curObj["TimeBeforeRemoval"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeBeforeRemoval { + get { + if ((curObj["TimeBeforeRemoval"] != null)) { + return ToDateTime(((string)(curObj["TimeBeforeRemoval"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeSubmittedNull { + get { + if ((curObj["TimeSubmitted"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeSubmitted { + get { + if ((curObj["TimeSubmitted"] != null)) { + return ToDateTime(((string)(curObj["TimeSubmitted"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsUntilTimeNull { + get { + if ((curObj["UntilTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime UntilTime { + get { + if ((curObj["UntilTime"] != null)) { + return ToDateTime(((string)(curObj["UntilTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("GUID of the affected virtual system.")] + public string VirtualSystemName { + get { + return ((string)(curObj["VirtualSystemName"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeCancellable() { + if ((this.IsCancellableNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDeleteOnCompletion() { + if ((this.IsDeleteOnCompletionNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeElapsedTime() { + if ((this.IsElapsedTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeErrorCode() { + if ((this.IsErrorCodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeJobRunTimes() { + if ((this.IsJobRunTimesNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeJobState() { + if ((this.IsJobStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeJobType() { + if ((this.IsJobTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLocalOrUtcTime() { + if ((this.IsLocalOrUtcTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMigrationType() { + if ((this.IsMigrationTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentComplete() { + if ((this.IsPercentCompleteNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePriority() { + if ((this.IsPriorityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRecoveryAction() { + if ((this.IsRecoveryActionNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRunDay() { + if ((this.IsRunDayNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRunDayOfWeek() { + if ((this.IsRunDayOfWeekNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRunMonth() { + if ((this.IsRunMonthNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRunStartInterval() { + if ((this.IsRunStartIntervalNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeScheduledStartTime() { + if ((this.IsScheduledStartTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStartTime() { + if ((this.IsStartTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeBeforeRemoval() { + if ((this.IsTimeBeforeRemovalNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeSubmitted() { + if ((this.IsTimeSubmittedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeUntilTime() { + if ((this.IsUntilTimeNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_MigrationJob"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static MigrationJobCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static MigrationJobCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static MigrationJobCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static MigrationJobCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static MigrationJobCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_MigrationJob"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new MigrationJobCollection(clsObject.GetInstances(enumOptions)); + } + + public static MigrationJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static MigrationJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static MigrationJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_MigrationJob", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new MigrationJobCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static MigrationJob CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new MigrationJob(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint GetError(out string Error) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetError", inParams, null); + Error = System.Convert.ToString(outParams.Properties["Error"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Error = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GetErrorEx(out string[] Errors) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetErrorEx", inParams, null); + Errors = ((string[])(outParams.Properties["Errors"].Value)); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Errors = null; + return System.Convert.ToUInt32(0); + } + } + + public uint KillJob(bool DeleteOnKill) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("KillJob"); + inParams["DeleteOnKill"] = ((bool)(DeleteOnKill)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("KillJob", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public enum JobTypeValues { + + Unknown0 = 0, + + Creating_Remote_Virtual_Machine = 300, + + Checking_Virtual_Machine_Compatibility = 301, + + Checking_Virtual_Machine_and_Storage_Compatibility = 302, + + Checking_Storage_Compatibility = 303, + + Checking_Storage_Migration = 304, + + Moving_Virtual_Machine = 305, + + Moving_Virtual_Machine_and_Storage = 306, + + Moving_Storage = 307, + + NULL_ENUM_VALUE = 308, + } + + // Enumerator implementation for enumerating instances of the class. + public class MigrationJobCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public MigrationJobCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new MigrationJob(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new MigrationJobEnumerator(privColObj.GetEnumerator()); + } + + public class MigrationJobEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public MigrationJobEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new MigrationJob(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_StorageJob.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_StorageJob.cs new file mode 100644 index 00000000000..5a101f1bfeb --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_StorageJob.cs @@ -0,0 +1,1863 @@ +// 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. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_StorageJob + public class StorageJob : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_StorageJob"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public StorageJob() { + this.InitializeObject(null, null, null); + } + + public StorageJob(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(StorageJob.ConstructPath(keyInstanceID)), null); + } + + public StorageJob(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(StorageJob.ConstructPath(keyInstanceID)), null); + } + + public StorageJob(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public StorageJob(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public StorageJob(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public StorageJob(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public StorageJob(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public StorageJob(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCancellableNull { + get { + if ((curObj["Cancellable"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates whether the job can be cancelled. The value of this property does not g" + + "uarantee that a request to cancel the job will succeed.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool Cancellable { + get { + if ((curObj["Cancellable"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["Cancellable"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("On failure of the asynchronous operation, this property contains the file path to" + + " the child of the virtual hard drive being affected by this operation.")] + public string Child { + get { + return ((string)(curObj["Child"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDeleteOnCompletionNull { + get { + if ((curObj["DeleteOnCompletion"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool DeleteOnCompletion { + get { + if ((curObj["DeleteOnCompletion"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["DeleteOnCompletion"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsElapsedTimeNull { + get { + if ((curObj["ElapsedTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime ElapsedTime { + get { + if ((curObj["ElapsedTime"] != null)) { + return ToDateTime(((string)(curObj["ElapsedTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsErrorCodeNull { + get { + if ((curObj["ErrorCode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ErrorCode { + get { + if ((curObj["ErrorCode"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ErrorCode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ErrorDescription { + get { + return ((string)(curObj["ErrorDescription"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ErrorSummaryDescription { + get { + return ((string)(curObj["ErrorSummaryDescription"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsJobCompletionStatusCodeNull { + get { + if ((curObj["JobCompletionStatusCode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The HRESULT code that describes the completion status for the asynchronous operat" + + "ion.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint JobCompletionStatusCode { + get { + if ((curObj["JobCompletionStatusCode"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["JobCompletionStatusCode"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsJobRunTimesNull { + get { + if ((curObj["JobRunTimes"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint JobRunTimes { + get { + if ((curObj["JobRunTimes"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["JobRunTimes"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsJobStateNull { + get { + if ((curObj["JobState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort JobState { + get { + if ((curObj["JobState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["JobState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string JobStatus { + get { + return ((string)(curObj["JobStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsJobTypeNull { + get { + if ((curObj["JobType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The type of asynchronous operation being tracked by this instance of Msvm_StorageJob. +Values are: +Unknown +VHD Creation: Creating a virtual hard disk image (VHD). +Floppy Creation: Creating a virtual floppy disk image (VFD). +Compaction: Compacting the size of a virtual hard disk image. +Expansion: Expanding the size of a virtual hard disk image. +Merging: Merging multiple virtual hard disk images into a single image. +Conversion: Converting the type of a virtual hard disk image. +Loopback Mount: Mounting the virtual hard disk on the parent partition. +Get VHD Info: Retrieving information about a virtual hard disk image (VHD). +Validate VHD Image: Validating a virtual hard disk image (VHD).")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public JobTypeValues JobType { + get { + if ((curObj["JobType"] == null)) { + return ((JobTypeValues)(System.Convert.ToInt32(10))); + } + return ((JobTypeValues)(System.Convert.ToInt32(curObj["JobType"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLocalOrUtcTimeNull { + get { + if ((curObj["LocalOrUtcTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort LocalOrUtcTime { + get { + if ((curObj["LocalOrUtcTime"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["LocalOrUtcTime"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Notify { + get { + return ((string)(curObj["Notify"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherRecoveryAction { + get { + return ((string)(curObj["OtherRecoveryAction"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Owner { + get { + return ((string)(curObj["Owner"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("On failure of the asynchronous operation, this property contains the file path to" + + " the parent of the virtual hard drive being affected by this operation.")] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentCompleteNull { + get { + if ((curObj["PercentComplete"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PercentComplete { + get { + if ((curObj["PercentComplete"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PercentComplete"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPriorityNull { + get { + if ((curObj["Priority"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Priority { + get { + if ((curObj["Priority"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Priority"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRecoveryActionNull { + get { + if ((curObj["RecoveryAction"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RecoveryAction { + get { + if ((curObj["RecoveryAction"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RecoveryAction"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRunDayNull { + get { + if ((curObj["RunDay"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public sbyte RunDay { + get { + if ((curObj["RunDay"] == null)) { + return System.Convert.ToSByte(0); + } + return ((sbyte)(curObj["RunDay"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRunDayOfWeekNull { + get { + if ((curObj["RunDayOfWeek"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public sbyte RunDayOfWeek { + get { + if ((curObj["RunDayOfWeek"] == null)) { + return System.Convert.ToSByte(0); + } + return ((sbyte)(curObj["RunDayOfWeek"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRunMonthNull { + get { + if ((curObj["RunMonth"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public byte RunMonth { + get { + if ((curObj["RunMonth"] == null)) { + return System.Convert.ToByte(0); + } + return ((byte)(curObj["RunMonth"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRunStartIntervalNull { + get { + if ((curObj["RunStartInterval"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime RunStartInterval { + get { + if ((curObj["RunStartInterval"] != null)) { + return ToDateTime(((string)(curObj["RunStartInterval"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsScheduledStartTimeNull { + get { + if ((curObj["ScheduledStartTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime ScheduledStartTime { + get { + if ((curObj["ScheduledStartTime"] != null)) { + return ToDateTime(((string)(curObj["ScheduledStartTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStartTimeNull { + get { + if ((curObj["StartTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime StartTime { + get { + if ((curObj["StartTime"] != null)) { + return ToDateTime(((string)(curObj["StartTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeBeforeRemovalNull { + get { + if ((curObj["TimeBeforeRemoval"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeBeforeRemoval { + get { + if ((curObj["TimeBeforeRemoval"] != null)) { + return ToDateTime(((string)(curObj["TimeBeforeRemoval"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeSubmittedNull { + get { + if ((curObj["TimeSubmitted"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeSubmitted { + get { + if ((curObj["TimeSubmitted"] != null)) { + return ToDateTime(((string)(curObj["TimeSubmitted"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsUntilTimeNull { + get { + if ((curObj["UntilTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime UntilTime { + get { + if ((curObj["UntilTime"] != null)) { + return ToDateTime(((string)(curObj["UntilTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeCancellable() { + if ((this.IsCancellableNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDeleteOnCompletion() { + if ((this.IsDeleteOnCompletionNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeElapsedTime() { + if ((this.IsElapsedTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeErrorCode() { + if ((this.IsErrorCodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeJobCompletionStatusCode() { + if ((this.IsJobCompletionStatusCodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeJobRunTimes() { + if ((this.IsJobRunTimesNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeJobState() { + if ((this.IsJobStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeJobType() { + if ((this.IsJobTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLocalOrUtcTime() { + if ((this.IsLocalOrUtcTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentComplete() { + if ((this.IsPercentCompleteNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePriority() { + if ((this.IsPriorityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRecoveryAction() { + if ((this.IsRecoveryActionNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRunDay() { + if ((this.IsRunDayNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRunDayOfWeek() { + if ((this.IsRunDayOfWeekNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRunMonth() { + if ((this.IsRunMonthNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRunStartInterval() { + if ((this.IsRunStartIntervalNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeScheduledStartTime() { + if ((this.IsScheduledStartTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStartTime() { + if ((this.IsStartTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeBeforeRemoval() { + if ((this.IsTimeBeforeRemovalNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeSubmitted() { + if ((this.IsTimeSubmittedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeUntilTime() { + if ((this.IsUntilTimeNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_StorageJob"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static StorageJobCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static StorageJobCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static StorageJobCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static StorageJobCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static StorageJobCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_StorageJob"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new StorageJobCollection(clsObject.GetInstances(enumOptions)); + } + + public static StorageJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static StorageJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static StorageJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_StorageJob", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new StorageJobCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static StorageJob CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new StorageJob(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint GetError(out string Error) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetError", inParams, null); + Error = System.Convert.ToString(outParams.Properties["Error"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Error = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GetErrorEx(out string[] Errors) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetErrorEx", inParams, null); + Errors = ((string[])(outParams.Properties["Errors"].Value)); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Errors = null; + return System.Convert.ToUInt32(0); + } + } + + public uint KillJob(bool DeleteOnKill) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("KillJob"); + inParams["DeleteOnKill"] = ((bool)(DeleteOnKill)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("KillJob", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public enum JobTypeValues { + + Unknown0 = 0, + + VHD_Creation = 1, + + Floppy_Creation = 2, + + Compaction = 3, + + Expansion = 4, + + Merging = 5, + + Conversion = 6, + + Loopback_Mount = 7, + + Get_VHD_Info = 8, + + Validate_VHD_Image = 9, + + NULL_ENUM_VALUE = 10, + } + + // Enumerator implementation for enumerating instances of the class. + public class StorageJobCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public StorageJobCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new StorageJob(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new StorageJobEnumerator(privColObj.GetEnumerator()); + } + + public class StorageJobEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public StorageJobEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new StorageJob(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemMigrationService.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemMigrationService.cs new file mode 100644 index 00000000000..89592b1b900 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemMigrationService.cs @@ -0,0 +1,1581 @@ +// 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. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_VirtualSystemMigrationService + public class VirtualSystemMigrationService : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_VirtualSystemMigrationService"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public VirtualSystemMigrationService() { + this.InitializeObject(null, null, null); + } + + public VirtualSystemMigrationService(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemMigrationService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public VirtualSystemMigrationService(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemMigrationService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public VirtualSystemMigrationService(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualSystemMigrationService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualSystemMigrationService(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualSystemMigrationService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualSystemMigrationService(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public VirtualSystemMigrationService(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsActiveStorageMigrationCountNull { + get { + if ((curObj["ActiveStorageMigrationCount"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The number of currently in-flight storage migrations.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint ActiveStorageMigrationCount { + get { + if ((curObj["ActiveStorageMigrationCount"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["ActiveStorageMigrationCount"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsActiveVirtualSystemMigrationCountNull { + get { + if ((curObj["ActiveVirtualSystemMigrationCount"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The number of currently in-flight virtual system migrations.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint ActiveVirtualSystemMigrationCount { + get { + if ((curObj["ActiveVirtualSystemMigrationCount"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["ActiveVirtualSystemMigrationCount"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledDefaultNull { + get { + if ((curObj["EnabledDefault"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledDefault { + get { + if ((curObj["EnabledDefault"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledDefault"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The list of IP addresses of the host, which can be used for virtual system migra" + + "tion.")] + public string[] MigrationServiceListenerIPAddressList { + get { + return ((string[])(curObj["MigrationServiceListenerIPAddressList"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerContact { + get { + return ((string)(curObj["PrimaryOwnerContact"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerName { + get { + return ((string)(curObj["PrimaryOwnerName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedStateNull { + get { + if ((curObj["RequestedState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RequestedState { + get { + if ((curObj["RequestedState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RequestedState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStartedNull { + get { + if ((curObj["Started"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool Started { + get { + if ((curObj["Started"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["Started"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string StartMode { + get { + return ((string)(curObj["StartMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemCreationClassName { + get { + return ((string)(curObj["SystemCreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemName { + get { + return ((string)(curObj["SystemName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransitioningToStateNull { + get { + if ((curObj["TransitioningToState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransitioningToState { + get { + if ((curObj["TransitioningToState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransitioningToState"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeActiveStorageMigrationCount() { + if ((this.IsActiveStorageMigrationCountNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeActiveVirtualSystemMigrationCount() { + if ((this.IsActiveVirtualSystemMigrationCountNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledDefault() { + if ((this.IsEnabledDefaultNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStarted() { + if ((this.IsStartedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualSystemMigrationService"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static VirtualSystemMigrationServiceCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualSystemMigrationServiceCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualSystemMigrationServiceCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualSystemMigrationServiceCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualSystemMigrationServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_VirtualSystemMigrationService"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new VirtualSystemMigrationServiceCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualSystemMigrationServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualSystemMigrationServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualSystemMigrationServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSystemMigrationService", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualSystemMigrationServiceCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualSystemMigrationService CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new VirtualSystemMigrationService(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint AddNetworkSettings(string[] NetworkSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AddNetworkSettings"); + inParams["NetworkSettings"] = ((string[])(NetworkSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddNetworkSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint CheckSystemCompatibilityInfo(byte[] CompatibilityInfo, out string[] Reasons) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("CheckSystemCompatibilityInfo"); + inParams["CompatibilityInfo"] = ((byte[])(CompatibilityInfo)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CheckSystemCompatibilityInfo", inParams, null); + Reasons = ((string[])(outParams.Properties["Reasons"].Value)); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Reasons = null; + return System.Convert.ToUInt32(0); + } + } + + public uint CheckVirtualSystemIsMigratable(System.Management.ManagementPath ComputerSystem, string DestinationHost, string MigrationSettingData, string[] NewResourceSettingData, string NewSystemSettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("CheckVirtualSystemIsMigratable"); + inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; + inParams["DestinationHost"] = ((string)(DestinationHost)); + inParams["MigrationSettingData"] = ((string)(MigrationSettingData)); + inParams["NewResourceSettingData"] = ((string[])(NewResourceSettingData)); + inParams["NewSystemSettingData"] = ((string)(NewSystemSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CheckVirtualSystemIsMigratable", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint CheckVirtualSystemIsMigratableToHost(System.Management.ManagementPath ComputerSystem, string DestinationHost, string MigrationSettingData, string[] NewResourceSettingData, string NewSystemSettingData, out bool IsMigratable) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("CheckVirtualSystemIsMigratableToHost"); + inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; + inParams["DestinationHost"] = ((string)(DestinationHost)); + inParams["MigrationSettingData"] = ((string)(MigrationSettingData)); + inParams["NewResourceSettingData"] = ((string[])(NewResourceSettingData)); + inParams["NewSystemSettingData"] = ((string)(NewSystemSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CheckVirtualSystemIsMigratableToHost", inParams, null); + IsMigratable = System.Convert.ToBoolean(outParams.Properties["IsMigratable"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + IsMigratable = System.Convert.ToBoolean(0); + return System.Convert.ToUInt32(0); + } + } + + public uint CheckVirtualSystemIsMigratableToSystem(System.Management.ManagementPath ComputerSystem, System.Management.ManagementPath DestinationSystem, string MigrationSettingData, string[] NewResourceSettingData, string NewSystemSettingData, out bool IsMigratable) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("CheckVirtualSystemIsMigratableToSystem"); + inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; + inParams["DestinationSystem"] = ((System.Management.ManagementPath)(DestinationSystem)).Path; + inParams["MigrationSettingData"] = ((string)(MigrationSettingData)); + inParams["NewResourceSettingData"] = ((string[])(NewResourceSettingData)); + inParams["NewSystemSettingData"] = ((string)(NewSystemSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CheckVirtualSystemIsMigratableToSystem", inParams, null); + IsMigratable = System.Convert.ToBoolean(outParams.Properties["IsMigratable"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + IsMigratable = System.Convert.ToBoolean(0); + return System.Convert.ToUInt32(0); + } + } + + public uint GetSystemCompatibilityInfo(System.Management.ManagementPath ComputerSystem, out byte[] CompatibilityInfo) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GetSystemCompatibilityInfo"); + inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetSystemCompatibilityInfo", inParams, null); + CompatibilityInfo = ((byte[])(outParams.Properties["CompatibilityInfo"].Value)); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + CompatibilityInfo = null; + return System.Convert.ToUInt32(0); + } + } + + public uint MigrateVirtualSystemToHost(System.Management.ManagementPath ComputerSystem, string DestinationHost, string MigrationSettingData, string[] NewResourceSettingData, string NewSystemSettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("MigrateVirtualSystemToHost"); + inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; + inParams["DestinationHost"] = ((string)(DestinationHost)); + inParams["MigrationSettingData"] = ((string)(MigrationSettingData)); + inParams["NewResourceSettingData"] = ((string[])(NewResourceSettingData)); + inParams["NewSystemSettingData"] = ((string)(NewSystemSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("MigrateVirtualSystemToHost", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint MigrateVirtualSystemToSystem(System.Management.ManagementPath ComputerSystem, System.Management.ManagementPath DestinationSystem, string MigrationSettingData, string[] NewResourceSettingData, string NewSystemSettingData, out System.Management.ManagementPath Job, out System.Management.ManagementPath NewComputerSystem) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("MigrateVirtualSystemToSystem"); + inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; + inParams["DestinationSystem"] = ((System.Management.ManagementPath)(DestinationSystem)).Path; + inParams["MigrationSettingData"] = ((string)(MigrationSettingData)); + inParams["NewResourceSettingData"] = ((string[])(NewResourceSettingData)); + inParams["NewSystemSettingData"] = ((string)(NewSystemSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("MigrateVirtualSystemToSystem", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + } + NewComputerSystem = null; + if ((outParams.Properties["NewComputerSystem"] != null)) { + NewComputerSystem = new System.Management.ManagementPath(outParams.Properties["NewComputerSystem"].ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + NewComputerSystem = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifyNetworkSettings(string[] NetworkSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyNetworkSettings"); + inParams["NetworkSettings"] = ((string[])(NetworkSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyNetworkSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifyServiceSettings(string ServiceSettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyServiceSettings"); + inParams["ServiceSettingData"] = ((string)(ServiceSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyServiceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RemoveNetworkSettings(System.Management.ManagementPath[] NetworkSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RemoveNetworkSettings"); + if ((NetworkSettings != null)) { + int len = ((System.Array)(NetworkSettings)).Length; + string[] arrProp = new string[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(NetworkSettings)).GetValue(iCounter))).Path; + } + inParams["NetworkSettings"] = arrProp; + } + else { + inParams["NetworkSettings"] = null; + } + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveNetworkSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint StartService() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StartService", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint StopService() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StopService", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class VirtualSystemMigrationServiceCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualSystemMigrationServiceCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new VirtualSystemMigrationService(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualSystemMigrationServiceEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualSystemMigrationServiceEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualSystemMigrationServiceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualSystemMigrationService(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemMigrationSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemMigrationSettingData.cs new file mode 100644 index 00000000000..de5bea5d8b8 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemMigrationSettingData.cs @@ -0,0 +1,915 @@ +// 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. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_VirtualSystemMigrationSettingData + public class VirtualSystemMigrationSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_VirtualSystemMigrationSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public VirtualSystemMigrationSettingData() { + this.InitializeObject(null, null, null); + } + + public VirtualSystemMigrationSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemMigrationSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualSystemMigrationSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemMigrationSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualSystemMigrationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualSystemMigrationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualSystemMigrationSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualSystemMigrationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualSystemMigrationSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public VirtualSystemMigrationSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsBandwidthNull { + get { + if ((curObj["Bandwidth"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Bandwidth { + get { + if ((curObj["Bandwidth"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Bandwidth"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string BandwidthUnit { + get { + return ((string)(curObj["BandwidthUnit"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("For storage migration it will be NULL. For virtual system \nmigration, client can " + + "provide a list of IP addresses of the \ndestination host.")] + public string[] DestinationIPAddressList { + get { + return ((string[])(curObj["DestinationIPAddressList"])); + } + set { + curObj["DestinationIPAddressList"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"If we have a planned computer system at migration destination then DestinationPlannedVirtualSystemId could be set to +the GUID of the destination Planned VM where the VM needs to +migrate. This is useful for cases where user has created a +planned VM at the destination along with resource fixup, and +wants a VM from source to migrate into this planned VM.")] + public string DestinationPlannedVirtualSystemId { + get { + return ((string)(curObj["DestinationPlannedVirtualSystemId"])); + } + set { + curObj["DestinationPlannedVirtualSystemId"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMigrationTypeNull { + get { + if ((curObj["MigrationType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("MigrationType describes the type of migration operation to \nbe performed.\n")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public MigrationTypeValues MigrationType { + get { + if ((curObj["MigrationType"] == null)) { + return ((MigrationTypeValues)(System.Convert.ToInt32(32773))); + } + return ((MigrationTypeValues)(System.Convert.ToInt32(curObj["MigrationType"]))); + } + set { + if ((MigrationTypeValues.NULL_ENUM_VALUE == value)) { + curObj["MigrationType"] = null; + } + else { + curObj["MigrationType"] = value; + } + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherTransportType { + get { + return ((string)(curObj["OtherTransportType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPriorityNull { + get { + if ((curObj["Priority"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Priority { + get { + if ((curObj["Priority"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Priority"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRetainVhdCopiesOnSourceNull { + get { + if ((curObj["RetainVhdCopiesOnSource"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("For storage migration, this could be set to TRUE or FALSE\nto determine wheither, " + + "at the end of a storage migration, when the\nsource host is beeing clean up, the " + + "read only VHDs should be removedor not.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool RetainVhdCopiesOnSource { + get { + if ((curObj["RetainVhdCopiesOnSource"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["RetainVhdCopiesOnSource"])); + } + set { + curObj["RetainVhdCopiesOnSource"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransportTypeNull { + get { + if ((curObj["TransportType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransportType { + get { + if ((curObj["TransportType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransportType"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeBandwidth() { + if ((this.IsBandwidthNull == false)) { + return true; + } + return false; + } + + private void ResetDestinationIPAddressList() { + curObj["DestinationIPAddressList"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetDestinationPlannedVirtualSystemId() { + curObj["DestinationPlannedVirtualSystemId"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeMigrationType() { + if ((this.IsMigrationTypeNull == false)) { + return true; + } + return false; + } + + private void ResetMigrationType() { + curObj["MigrationType"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializePriority() { + if ((this.IsPriorityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRetainVhdCopiesOnSource() { + if ((this.IsRetainVhdCopiesOnSourceNull == false)) { + return true; + } + return false; + } + + private void ResetRetainVhdCopiesOnSource() { + curObj["RetainVhdCopiesOnSource"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeTransportType() { + if ((this.IsTransportTypeNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualSystemMigrationSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static VirtualSystemMigrationSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualSystemMigrationSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualSystemMigrationSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualSystemMigrationSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualSystemMigrationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_VirtualSystemMigrationSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new VirtualSystemMigrationSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualSystemMigrationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualSystemMigrationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualSystemMigrationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSystemMigrationSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualSystemMigrationSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualSystemMigrationSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new VirtualSystemMigrationSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public enum MigrationTypeValues { + + Unknown0 = 0, + + VirtualSystem = 32768, + + Storage = 32769, + + Staged = 32770, + + VirtualSystemAndStorage = 32771, + + StorageDeepCheck = 32772, + + NULL_ENUM_VALUE = 32773, + } + + // Enumerator implementation for enumerating instances of the class. + public class VirtualSystemMigrationSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualSystemMigrationSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new VirtualSystemMigrationSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualSystemMigrationSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualSystemMigrationSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualSystemMigrationSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualSystemMigrationSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/WmiWrappers.csproj b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/WmiWrappers.csproj index da0c0d6ce7c..b4bf04b7057 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/WmiWrappers.csproj +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/WmiWrappers.csproj @@ -123,6 +123,9 @@ Component + + Component + Component @@ -132,6 +135,9 @@ Component + + Component + Component @@ -153,6 +159,12 @@ Component + + Component + + + Component + Component @@ -172,4 +184,4 @@ --> - + \ No newline at end of file diff --git a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/discoverer/HypervServerDiscoverer.java b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/discoverer/HypervServerDiscoverer.java index e3dcd8f634f..2a630c7e6db 100644 --- a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/discoverer/HypervServerDiscoverer.java +++ b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/discoverer/HypervServerDiscoverer.java @@ -339,10 +339,11 @@ public class HypervServerDiscoverer extends DiscovererBase implements Discoverer // TODO: does the resource have to create a connection? return resources; } catch (ConfigurationException e) { - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId, podId, "Unable to add " + uri.getHost(), "Error is " + e.getMessage()); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, podId, "Unable to add " + uri.getHost(), "Error is " + e.getMessage()); s_logger.warn("Unable to instantiate " + uri.getHost(), e); } catch (UnknownHostException e) { - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId, podId, "Unable to add " + uri.getHost(), "Error is " + e.getMessage()); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, podId, "Unable to add " + uri.getHost(), "Error is " + e.getMessage()); + s_logger.warn("Unable to instantiate " + uri.getHost(), e); } catch (Exception e) { String msg = " can't setup agent, due to " + e.toString() + " - " + e.getMessage(); diff --git a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java index e6a5f62a33a..f61e5ff4401 100644 --- a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java +++ b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java @@ -930,15 +930,14 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S String args = " -v " + vmIpAddress; if (s_logger.isDebugEnabled()) { - s_logger.debug("Run command on domain router " + controlIp + ", /root/savepassword.sh " + args + " -p " + - StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); + s_logger.debug("Run command on domain router " + controlIp + ", /opt/cloud/bin/savepassword.sh " + args + " -p " + StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); } args += " -p " + password; try { - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/savepassword.sh " + args); + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/savepassword.sh " + args); if (!result.first()) { s_logger.error("savepassword command on domain router " + controlIp + " failed, message: " + result.second()); diff --git a/plugins/hypervisors/kvm/pom.xml b/plugins/hypervisors/kvm/pom.xml index ebe05e58af7..81cc372116e 100644 --- a/plugins/hypervisors/kvm/pom.xml +++ b/plugins/hypervisors/kvm/pom.xml @@ -43,6 +43,11 @@ libvirt ${cs.libvirt-java.version} + + org.apache.cloudstack + cloud-plugin-network-ovs + ${project.version} + com.ceph rados diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index 834e26e3dd8..3596f8d3c71 100755 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -132,6 +132,13 @@ import com.cloud.agent.api.NetworkRulesSystemVmCommand; import com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand; import com.cloud.agent.api.NetworkUsageAnswer; import com.cloud.agent.api.NetworkUsageCommand; +import com.cloud.agent.api.OvsCreateTunnelAnswer; +import com.cloud.agent.api.OvsCreateTunnelCommand; +import com.cloud.agent.api.OvsDestroyBridgeCommand; +import com.cloud.agent.api.OvsDestroyTunnelCommand; +import com.cloud.agent.api.OvsFetchInterfaceAnswer; +import com.cloud.agent.api.OvsFetchInterfaceCommand; +import com.cloud.agent.api.OvsSetupBridgeCommand; import com.cloud.agent.api.PingCommand; import com.cloud.agent.api.PingRoutingCommand; import com.cloud.agent.api.PingRoutingWithNwGroupsCommand; @@ -207,6 +214,7 @@ import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.CpuModeDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.CpuTuneDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DevicesDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef; +import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef.deviceType; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef.diskProtocol; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.FeaturesDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.FilesystemDef; @@ -293,6 +301,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv private String _ovsPvlanDhcpHostPath; private String _ovsPvlanVmPath; private String _routerProxyPath; + private String _ovsTunnelPath; private String _host; private String _dcId; private String _pod; @@ -598,6 +607,11 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv throw new ConfigurationException("Unable to find the security_group.py"); } + _ovsTunnelPath = Script.findScript(networkScriptsDir, "ovstunnel.py"); + if (_ovsTunnelPath == null) { + throw new ConfigurationException("Unable to find the ovstunnel.py"); + } + _routerProxyPath = Script.findScript("scripts/network/domr/", "router_proxy.sh"); if (_routerProxyPath == null) { throw new ConfigurationException("Unable to find the router_proxy.sh"); @@ -1270,7 +1284,17 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv return execute((SetMonitorServiceCommand)cmd); } else if (cmd instanceof CheckOnHostCommand) { return execute((CheckOnHostCommand)cmd); - } else { + } else if (cmd instanceof OvsFetchInterfaceCommand) { + return execute((OvsFetchInterfaceCommand) cmd); + } else if (cmd instanceof OvsSetupBridgeCommand) { + return execute((OvsSetupBridgeCommand) cmd); + } else if (cmd instanceof OvsDestroyBridgeCommand) { + return execute((OvsDestroyBridgeCommand) cmd); + } else if (cmd instanceof OvsCreateTunnelCommand) { + return execute((OvsCreateTunnelCommand) cmd); + } else if (cmd instanceof OvsDestroyTunnelCommand) { + return execute((OvsDestroyTunnelCommand) cmd); + } else { s_logger.warn("Unsupported command "); return Answer.createUnsupportedCommandAnswer(cmd); } @@ -1279,6 +1303,175 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } } + private OvsFetchInterfaceAnswer execute(OvsFetchInterfaceCommand cmd) { + String label = cmd.getLabel(); + s_logger.debug("Will look for network with name-label:" + label); + try { + String ipadd = Script.runSimpleBashScript("ifconfig " + label + " | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'"); + String mask = Script.runSimpleBashScript("ifconfig " + label + " | grep 'inet addr:' | cut -d: -f4"); + String mac = Script.runSimpleBashScript("ifconfig " + label + " | grep HWaddr | awk -F \" \" '{print $5}'"); + return new OvsFetchInterfaceAnswer(cmd, true, "Interface " + label + + " retrieved successfully", ipadd, mask, mac); + + } catch (Exception e) { + s_logger.warn("Caught execption when fetching interface", e); + return new OvsFetchInterfaceAnswer(cmd, false, "EXCEPTION:" + + e.getMessage()); + } + + } + + private Answer execute(OvsSetupBridgeCommand cmd) { + findOrCreateTunnelNetwork(cmd.getKey()); + configureTunnelNetwork(cmd.getNetworkId(), cmd.getHostId(), + cmd.getKey()); + s_logger.debug("OVS Bridge configured"); + return new Answer(cmd, true, null); + } + + private Answer execute(OvsDestroyBridgeCommand cmd) { + destroyTunnelNetwork(cmd.getKey()); + s_logger.debug("OVS Bridge destroyed"); + return new Answer(cmd, true, null); + } + + private synchronized void destroyTunnelNetwork(int key) { + try { + findOrCreateTunnelNetwork(key); + String bridge = "OVSTunnel" + key; + Script cmd = new Script(_ovsTunnelPath, _timeout, s_logger); + cmd.add("destroy_ovs_bridge"); + cmd.add("--bridge", bridge); + String result = cmd.execute(); + if (result != null) { + // TODO: Should make this error not fatal? + // Can Concurrent VM shutdown/migration/reboot events can cause + // this method + // to be executed on a bridge which has already been removed? + throw new CloudRuntimeException("Unable to remove OVS bridge " + bridge); + } + return; + } catch (Exception e) { + s_logger.warn("destroyTunnelNetwork failed:", e); + return; + } + } + + private synchronized boolean findOrCreateTunnelNetwork(long key) { + try { + String nwName = "OVSTunnel" + key; + if (checkNetwork(nwName)) { + return true; + } + // if not found, create a new one + Map otherConfig = new HashMap(); + otherConfig.put("ovs-host-setup", ""); + Script.runSimpleBashScript("ovs-vsctl -- --may-exist add-br " + + nwName + " -- set bridge " + nwName + + " other_config:ovs_host_setup='-1'"); + s_logger.debug("### KVM network for tunnels created:" + nwName); + } catch (Exception e) { + s_logger.warn("createTunnelNetwork failed", e); + } + return true; + } + + private synchronized boolean configureTunnelNetwork(long networkId, + long hostId, int key) { + try { + findOrCreateTunnelNetwork(key); + String nwName = "OVSTunnel" + key; + String configuredHosts = Script + .runSimpleBashScript("ovs-vsctl get bridge " + nwName + + " other_config:ovs_host_setup"); + boolean configured = false; + if (configuredHosts != null) { + String hostIdsStr[] = configuredHosts.split(","); + for (String hostIdStr : hostIdsStr) { + if (hostIdStr.equals(((Long) hostId).toString())) { + configured = true; + break; + } + } + } + if (!configured) { + Script cmd = new Script(_ovsTunnelPath, _timeout, s_logger); + cmd.add("setup_ovs_bridge"); + cmd.add("--key", String.valueOf(key)); + cmd.add("--cs_host_id", ((Long) hostId).toString()); + cmd.add("--bridge", nwName); + String result = cmd.execute(); + if (result != null) { + throw new CloudRuntimeException( + "Unable to pre-configure OVS bridge " + nwName + + " for network ID:" + networkId); + } + } + } catch (Exception e) { + s_logger.warn("createandConfigureTunnelNetwork failed", e); + return false; + } + return true; + } + + private OvsCreateTunnelAnswer execute(OvsCreateTunnelCommand cmd) { + String bridge = "OVSTunnel" + cmd.getKey(); + try { + if (!findOrCreateTunnelNetwork(cmd.getKey())) { + s_logger.debug("Error during bridge setup"); + return new OvsCreateTunnelAnswer(cmd, false, + "Cannot create network", bridge); + } + + configureTunnelNetwork(cmd.getNetworkId(), cmd.getFrom(), + cmd.getKey()); + Script command = new Script(_ovsTunnelPath, _timeout, s_logger); + command.add("create_tunnel"); + command.add("--bridge", bridge); + command.add("--remote_ip", cmd.getRemoteIp()); + command.add("--key", cmd.getKey().toString()); + command.add("--src_host", cmd.getFrom().toString()); + command.add("--dst_host", cmd.getTo().toString()); + + String result = command.execute(); + if (result != null) { + return new OvsCreateTunnelAnswer(cmd, true, result, null, + bridge); + } else { + return new OvsCreateTunnelAnswer(cmd, false, result, bridge); + } + } catch (Exception e) { + s_logger.debug("Error during tunnel setup"); + s_logger.warn("Caught execption when creating ovs tunnel", e); + return new OvsCreateTunnelAnswer(cmd, false, e.getMessage(), bridge); + } + } + + private Answer execute(OvsDestroyTunnelCommand cmd) { + try { + if (!findOrCreateTunnelNetwork(cmd.getKey())) { + s_logger.warn("Unable to find tunnel network for GRE key:" + + cmd.getKey()); + return new Answer(cmd, false, "No network found"); + } + + String bridge = "OVSTunnel" + cmd.getKey(); + Script command = new Script(_ovsTunnelPath, _timeout, s_logger); + command.add("destroy_tunnel"); + command.add("--bridge", bridge); + command.add("--iface_name", cmd.getInPortName()); + String result = command.execute(); + if (result == null) { + return new Answer(cmd, true, result); + } else { + return new Answer(cmd, false, result); + } + } catch (Exception e) { + s_logger.warn("caught execption when destroy ovs tunnel", e); + return new Answer(cmd, false, e.getMessage()); + } + } + private CheckNetworkAnswer execute(CheckNetworkCommand cmd) { List phyNics = cmd.getPhysicalNetworkInfoList(); String errMsg = null; @@ -1609,13 +1802,13 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv private String getBroadcastUriFromBridge(String brName) { String pif = matchPifFileInDirectory(brName); - Pattern pattern = Pattern.compile("(\\D+)(\\d+)"); + Pattern pattern = Pattern.compile("(\\D+)(\\d+)(\\D*)(\\d*)"); Matcher matcher = pattern.matcher(pif); if (matcher.find()) { if (brName.startsWith("brvx")) { return BroadcastDomainType.Vxlan.toUri(matcher.group(2)).toString(); } else { - return BroadcastDomainType.Vlan.toUri(matcher.group(2)).toString(); + return BroadcastDomainType.Vlan.toUri(matcher.group(4)).toString(); } } else { s_logger.debug("failed to get vNet id from bridge " + brName + "attached to physical interface" + pif); @@ -3024,7 +3217,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } } - private Answer execute(RebootCommand cmd) { + + private Answer execute(RebootCommand cmd) { synchronized (_vms) { _vms.put(cmd.getVmName(), State.Starting); @@ -3105,7 +3299,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } } - protected Answer execute(StopCommand cmd) { + + protected Answer execute(StopCommand cmd) { final String vmName = cmd.getVmName(); State state = null; @@ -3421,7 +3616,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } // pass cmdline info to system vms - if (vmSpec.getType() != VirtualMachine.Type.User) { + if (vmSpec.getType() != VirtualMachine.Type.User) { if ((conn.getVersion() < 1001000)) { // CLOUDSTACK-2823: try passCmdLine some times if kernel < 2.6.34 and qemu < 1.1.0 on hypervisor (for instance, CentOS 6.4) //wait for 5 minutes at most String controlIp = null; @@ -4603,6 +4798,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv List disks = getDisks(conn, vmName); for (DiskDef disk : disks) { + if (disk.getDeviceType() != deviceType.DISK) + break; DomainBlockStats blockStats = dm.blockStats(disk.getDiskLabel()); String path = disk.getDiskPath(); // for example, path = /mnt/pool_uuid/disk_path/ String diskPath = null; diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java index 49cf1b2b45d..9910877f2ea 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java @@ -461,6 +461,7 @@ public class LibvirtVMDef { public void defFileBasedDisk(String filePath, String diskLabel, diskBus bus, diskFmtType diskFmtType) { _diskType = diskType.FILE; _deviceType = deviceType.DISK; + _diskCacheMode = diskCacheMode.NONE; _sourcePath = filePath; _diskLabel = diskLabel; _diskFmtType = diskFmtType; @@ -488,6 +489,7 @@ public class LibvirtVMDef { _diskType = diskType.FILE; _deviceType = deviceType.DISK; + _diskCacheMode = diskCacheMode.NONE; _sourcePath = filePath; _diskLabel = getDevLabel(devId, bus); _diskFmtType = diskFmtType; @@ -501,6 +503,7 @@ public class LibvirtVMDef { _sourcePath = volPath; _diskLabel = "hdc"; _diskFmtType = diskFmtType.RAW; + _diskCacheMode = diskCacheMode.NONE; _bus = diskBus.IDE; } @@ -508,6 +511,7 @@ public class LibvirtVMDef { _diskType = diskType.BLOCK; _deviceType = deviceType.DISK; _diskFmtType = diskFmtType.RAW; + _diskCacheMode = diskCacheMode.NONE; _sourcePath = diskName; _diskLabel = getDevLabel(devId, bus); _bus = bus; @@ -517,6 +521,7 @@ public class LibvirtVMDef { _diskType = diskType.BLOCK; _deviceType = deviceType.DISK; _diskFmtType = diskFmtType.RAW; + _diskCacheMode = diskCacheMode.NONE; _sourcePath = diskName; _diskLabel = diskLabel; _bus = bus; @@ -527,6 +532,7 @@ public class LibvirtVMDef { _diskType = diskType.NETWORK; _deviceType = deviceType.DISK; _diskFmtType = diskFmtType.RAW; + _diskCacheMode = diskCacheMode.NONE; _sourcePath = diskName; _sourceHost = sourceHost; _sourcePort = sourcePort; @@ -542,6 +548,7 @@ public class LibvirtVMDef { _diskType = diskType.NETWORK; _deviceType = deviceType.DISK; _diskFmtType = diskFmtType.RAW; + _diskCacheMode = diskCacheMode.NONE; _sourcePath = diskName; _sourceHost = sourceHost; _sourcePort = sourcePort; diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java index 8ed445f6781..ad3620dd03f 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java @@ -402,7 +402,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer try { resource.configure("VMware", params); } catch (ConfigurationException e) { - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId, podId, "Unable to add " + url.getHost(), "Error is " + e.getMessage()); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, podId, "Unable to add " + url.getHost(), "Error is " + e.getMessage()); s_logger.warn("Unable to instantiate " + url.getHost(), e); } resource.start(); diff --git a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java index 455c85dd12b..747d5d6925e 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java +++ b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java @@ -1474,7 +1474,9 @@ public class VmwareStorageProcessor implements StorageProcessor { vmMo.destroy(); // this.hostService.handleDatastoreAndVmdkDetach(iScsiName, storageHost, storagePort); - this.hostService.removeManagedTargetsFromCluster(managedIqns); + if (managedIqns != null && !managedIqns.isEmpty()) { + this.hostService.removeManagedTargetsFromCluster(managedIqns); + } for (NetworkDetails netDetails : networks) { if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) { diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java index 8ca515fcdc8..705aa4cd14b 100755 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java @@ -253,7 +253,7 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L } if (!support_hvm) { String msg = "Unable to add host " + record.address + " because it doesn't support hvm"; - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId, podId, msg, msg); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, podId, msg, msg); s_logger.debug(msg); throw new RuntimeException(msg); } @@ -331,7 +331,7 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L try { resource.configure("Xen Server", params); } catch (ConfigurationException e) { - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId, podId, "Unable to add " + record.address, "Error is " + e.getMessage()); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, podId, "Unable to add " + record.address, "Error is " + e.getMessage()); s_logger.warn("Unable to instantiate " + record.address, e); continue; } @@ -468,7 +468,7 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L String msg = "Only support XCP 1.0.0, 1.1.0, 1.4.x, 1.5 beta, 1.6.x; XenServer 5.6, XenServer 5.6 FP1, XenServer 5.6 SP2, Xenserver 6.0, 6.0.2, 6.1.0, 6.2.0 but this one is " + prodBrand + " " + prodVersion; - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId, podId, msg, msg); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, podId, msg, msg); s_logger.debug(msg); throw new RuntimeException(msg); } @@ -741,13 +741,23 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L "Unable to eject host " + host.getGuid() + " due to there is no host up in this cluster, please execute xe pool-eject host-uuid=" + host.getGuid() + "in this host " + host.getPrivateIpAddress(); s_logger.warn(msg); - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Unable to eject host " + host.getGuid(), msg); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Unable to eject host " + host.getGuid(), msg); } } - return new DeleteHostAnswer(true); } + @Override + protected HashMap buildConfigParams(HostVO host){ + HashMap params = super.buildConfigParams(host); + DataCenterVO zone = _dcDao.findById(host.getDataCenterId()); + if ( zone != null ) { + boolean securityGroupEnabled = zone.isSecurityGroupEnabled(); + params.put("securitygroupenabled", Boolean.toString(securityGroupEnabled)); + } + return params; + } + @Override public boolean stop() { _resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName()); diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java index 2cc0ec0a6b2..015a96654c2 100644 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java @@ -156,6 +156,18 @@ import com.cloud.agent.api.ModifyStoragePoolAnswer; import com.cloud.agent.api.ModifyStoragePoolCommand; import com.cloud.agent.api.NetworkRulesSystemVmCommand; import com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand; +import com.cloud.agent.api.OvsCreateGreTunnelCommand; +import com.cloud.agent.api.OvsCreateGreTunnelAnswer; +import com.cloud.agent.api.OvsCreateTunnelCommand; +import com.cloud.agent.api.OvsDestroyTunnelCommand; +import com.cloud.agent.api.OvsSetupBridgeCommand; +import com.cloud.agent.api.OvsDestroyBridgeCommand; +import com.cloud.agent.api.OvsCreateTunnelAnswer; +import com.cloud.agent.api.OvsDeleteFlowCommand; +import com.cloud.agent.api.OvsSetTagAndFlowAnswer; +import com.cloud.agent.api.OvsFetchInterfaceAnswer; +import com.cloud.agent.api.OvsSetTagAndFlowCommand; +import com.cloud.agent.api.OvsFetchInterfaceCommand; import com.cloud.agent.api.PingCommand; import com.cloud.agent.api.PingRoutingCommand; import com.cloud.agent.api.PingRoutingWithNwGroupsCommand; @@ -264,18 +276,6 @@ import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.IsolationType; import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetworkSetupInfo; -import com.cloud.network.ovs.OvsCreateGreTunnelAnswer; -import com.cloud.network.ovs.OvsCreateGreTunnelCommand; -import com.cloud.network.ovs.OvsCreateTunnelAnswer; -import com.cloud.network.ovs.OvsCreateTunnelCommand; -import com.cloud.network.ovs.OvsDeleteFlowCommand; -import com.cloud.network.ovs.OvsDestroyBridgeCommand; -import com.cloud.network.ovs.OvsDestroyTunnelCommand; -import com.cloud.network.ovs.OvsFetchInterfaceAnswer; -import com.cloud.network.ovs.OvsFetchInterfaceCommand; -import com.cloud.network.ovs.OvsSetTagAndFlowAnswer; -import com.cloud.network.ovs.OvsSetTagAndFlowCommand; -import com.cloud.network.ovs.OvsSetupBridgeCommand; import com.cloud.network.rules.FirewallRule; import com.cloud.resource.ServerResource; import com.cloud.resource.hypervisor.HypervisorResource; @@ -295,12 +295,16 @@ import com.cloud.utils.StringUtils; import com.cloud.utils.Ternary; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; +import com.cloud.utils.StringUtils; import com.cloud.vm.DiskProfile; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.PowerState; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.snapshot.VMSnapshot; +import com.cloud.utils.ssh.SSHCmdHelper; + + /** * CitrixResourceBase encapsulates the calls to the XenServer Xapi process * to perform the required functionalities for CloudStack. @@ -686,7 +690,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (vmSpec.getLimitCpuUse()) { long utilization = 0; // max CPU cap, default is unlimited - utilization = (int)((speed * 0.99 * vmSpec.getCpus()) / _host.speed * 100); + utilization = (int) ((vmSpec.getMaxSpeed() * 0.99 * vmSpec.getCpus()) / _host.speed * 100); //vm.addToVCPUsParamsLive(conn, "cap", Long.toString(utilization)); currently xenserver doesnot support Xapi to add VCPUs params live. callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "cap", "value", Long.toString(utilization), "vmname", vmSpec.getName()); } @@ -932,8 +936,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } else { vswitchNw = networks.iterator().next(); } - - enableXenServerNetwork(conn, vswitchNw, "vswitch", "vswitch network"); + if (!is_xcp()) + enableXenServerNetwork(conn, vswitchNw, "vswitch", "vswitch network"); _host.vswitchNetwork = vswitchNw; } return _host.vswitchNetwork; @@ -967,7 +971,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe rec.otherConfig = otherConfig; nw = Network.create(conn, rec); // Plug dom0 vif only when creating network - enableXenServerNetwork(conn, nw, nwName, "tunnel network for account " + key); + if (!is_xcp()) + enableXenServerNetwork(conn, nw, nwName, "tunnel network for account " + key); s_logger.debug("### Xen Server network for tunnels created:" + nwName); } else { nw = networks.iterator().next(); @@ -1003,10 +1008,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } if (!configured) { // Plug dom0 vif only if not done before for network and host - enableXenServerNetwork(conn, nw, nwName, "tunnel network for account " + key); - String result = - callHostPlugin(conn, "ovstunnel", "setup_ovs_bridge", "bridge", bridge, "key", String.valueOf(key), "xs_nw_uuid", nw.getUuid(conn), "cs_host_id", - ((Long)hostId).toString()); + if (!is_xcp()) + enableXenServerNetwork(conn, nw, nwName, "tunnel network for account " + key); + String result = callHostPlugin(conn, "ovstunnel", "setup_ovs_bridge", "bridge", bridge, + "key", String.valueOf(key), + "xs_nw_uuid", nw.getUuid(conn), + "cs_host_id", ((Long)hostId).toString()); //Note down the fact that the ovs bridge has been setup String[] res = result.split(":"); if (res.length != 2 || !res[0].equalsIgnoreCase("SUCCESS")) { @@ -1317,23 +1324,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe vmr.VCPUsMax = 32L; } - Map details = vmSpec.getDetails(); - if (details != null) { - String timeoffset = details.get("timeoffset"); - if (timeoffset != null) { - Map platform = vmr.platform; - platform.put("timeoffset", timeoffset); - vmr.platform = platform; - } - - String coresPerSocket = details.get("cpu.corespersocket"); - if (coresPerSocket != null) { - Map platform = vmr.platform; - platform.put("cores-per-socket", coresPerSocket); - vmr.platform = platform; - } - } - vmr.VCPUsAtStartup = (long)vmSpec.getCpus(); vmr.consoles.clear(); @@ -1358,7 +1348,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (vmSpec.getLimitCpuUse()) { // CPU cap is per VM, so need to assign cap based on the number of vcpus - utilization = (int)((speed * 0.99 * vmSpec.getCpus()) / _host.speed * 100); + utilization = (int) ((vmSpec.getMaxSpeed() * 0.99 * vmSpec.getCpus()) / _host.speed * 100); } vcpuParams.put("weight", Integer.toString(cpuWeight)); @@ -1417,6 +1407,36 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } protected void finalizeVmMetaData(VM vm, Connection conn, VirtualMachineTO vmSpec) throws Exception { + + Map details = vmSpec.getDetails(); + if ( details != null ) { + String platformstring = details.get("platform"); + if (platformstring != null && !platformstring.isEmpty() ) { + Map platform = StringUtils.stringToMap(platformstring); + vm.setPlatform(conn, platform); + } else { + String timeoffset = details.get("timeoffset"); + if (timeoffset != null) { + Map platform = vm.getPlatform(conn); + platform.put("timeoffset", timeoffset); + vm.setPlatform(conn, platform); + } + String coresPerSocket = details.get("cpu.corespersocket"); + if (coresPerSocket != null) { + Map platform = vm.getPlatform(conn); + platform.put("cores-per-socket", coresPerSocket); + vm.setPlatform(conn, platform); + } + + String xentoolsversion = details.get("hypervisortoolsversion"); + if ( xentoolsversion == null || !xentoolsversion.equalsIgnoreCase("xenserver61") ) { + Map platform = vm.getPlatform(conn); + platform.remove("device_id"); + vm.setPlatform(conn, platform); + } + + } + } } protected String handleVmStartFailure(Connection conn, String vmName, VM vm, String message, Throwable th) { @@ -3082,7 +3102,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe s_logger.trace("VM " + record.nameLabel + ": powerstate = " + ps + "; vm state=" + state.toString()); } Host host = record.residentOn; - String xstoolsversion = getVMXenToolsVersion(record.platform); + String platformstring = StringUtils.mapToString(record.platform); String host_uuid = null; if (!isRefNull(host)) { try { @@ -3094,7 +3114,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } catch (XmlRpcException e) { s_logger.error("Failed to get host uuid for host " + host.toWireString(), e); } - vmStates.put(record.nameLabel, new Ternary(host_uuid, state, xstoolsversion)); + vmStates.put(record.nameLabel, new Ternary(host_uuid, state, platformstring)); } } @@ -4069,6 +4089,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe @Override public StopAnswer execute(StopCommand cmd) { String vmName = cmd.getVmName(); + String platformstring = null; try { Connection conn = getConnection(); Set vms = VM.getByNameLabel(conn, vmName); @@ -4098,7 +4119,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } for (VM vm : vms) { VM.Record vmr = vm.getRecord(conn); - + platformstring = StringUtils.mapToString(vmr.platform); if (vmr.isControlDomain) { String msg = "Tring to Shutdown control domain"; s_logger.warn(msg); @@ -4108,7 +4129,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (vmr.powerState == VmPowerState.RUNNING && !isRefNull(vmr.residentOn) && !vmr.residentOn.getUuid(conn).equals(_host.uuid)) { String msg = "Stop Vm " + vmName + " failed due to this vm is not running on this host: " + _host.uuid + " but host:" + vmr.residentOn.getUuid(conn); s_logger.warn(msg); - return new StopAnswer(cmd, msg, false); + return new StopAnswer(cmd, msg, platformstring, false); } State state = s_vms.getState(_cluster, vmName); @@ -4136,24 +4157,13 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } catch (Exception e) { String msg = "Catch exception " + e.getClass().getName() + " when stop VM:" + cmd.getVmName() + " due to " + e.toString(); s_logger.debug(msg); - return new StopAnswer(cmd, msg, false); + return new StopAnswer(cmd, msg, platformstring, false); } finally { try { if (vm.getPowerState(conn) == VmPowerState.HALTED) { disconnectManagedVolumes(conn, vm); - Map platform = vm.getPlatform(conn); - Integer timeoffset = null; - try { - if (platform.containsKey("timeoffset")) { - timeoffset = Integer.valueOf(platform.get("timeoffset")); - } - } catch (NumberFormatException e) { - s_logger.error("Error while reading the platform:timeoffset field of the instance", e); - } - String xentoolsversion = getVMXenToolsVersion(platform); - Set vifs = vm.getVIFs(conn); List networks = new ArrayList(); for (VIF vif : vifs) { @@ -4174,11 +4184,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe // network might be destroyed by other host } } - return new StopAnswer(cmd, "Stop VM " + vmName + " Succeed", xentoolsversion, timeoffset, true); + return new StopAnswer(cmd, "Stop VM " + vmName + " Succeed", platformstring ,true); } - } catch (XenAPIException e) { - String msg = "VM destroy failed in Stop " + vmName + " Command due to " + e.toString(); - s_logger.warn(msg, e); } catch (Exception e) { String msg = "VM destroy failed in Stop " + vmName + " Command due to " + e.getMessage(); s_logger.warn(msg, e); @@ -4191,19 +4198,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } - } catch (XenAPIException e) { + } catch (Exception e) { String msg = "Stop Vm " + vmName + " fail due to " + e.toString(); s_logger.warn(msg, e); - return new StopAnswer(cmd, msg, false); - } catch (XmlRpcException e) { - String msg = "Stop Vm " + vmName + " fail due to " + e.getMessage(); - s_logger.warn(msg, e); - return new StopAnswer(cmd, msg, false); - } catch (Exception e) { - s_logger.warn("Unable to stop " + vmName + " due to ", e); - return new StopAnswer(cmd, e); + return new StopAnswer(cmd, msg, platformstring, false); } - return new StopAnswer(cmd, "Stop VM failed", false); + return new StopAnswer(cmd, "Stop VM failed", platformstring, false); } /*Override by subclass*/ @@ -5299,6 +5299,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } com.trilead.ssh2.Session session = sshConnection.openSession(); + + String cmd = "mkdir -p /opt/cloud/bin"; + if (!SSHCmdHelper.sshExecuteCmd(sshConnection, cmd)) { + throw new CloudRuntimeException("Cannot create directory /opt/cloud/bin on XenServer hosts"); + } + SCPClient scp = new SCPClient(sshConnection); List files = getPatchFiles(); @@ -5861,6 +5867,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe private OvsFetchInterfaceAnswer execute(OvsFetchInterfaceCommand cmd) { String label = cmd.getLabel(); + //FIXME: this is a tricky to pass the network checking in XCP. I temporary get default label from Host. + if (is_xcp()) { + label = getLabel(); + } s_logger.debug("Will look for network with name-label:" + label + " on host " + _host.ip); Connection conn = getConnection(); try { @@ -5987,7 +5997,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe details.put("private.network.device", _privateNetworkName); } - details.put("can_bridge_firewall", Boolean.toString(_canBridgeFirewall)); cmd.setHostDetails(details); cmd.setName(hr.nameLabel); cmd.setGuid(_host.uuid); @@ -8216,13 +8225,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe String vm_name = record.nameLabel; VmPowerState ps = record.powerState; final State state = convertToState(ps); - String xstoolsversion = getVMXenToolsVersion(record.platform); Host host = record.residentOn; String host_uuid = null; if (!isRefNull(host)) { host_uuid = host.getUuid(conn); synchronized (_cluster.intern()) { - s_vms.put(_cluster, host_uuid, vm_name, state, xstoolsversion); + s_vms.put(_cluster, host_uuid, vm_name, state, null); } } if (s_logger.isTraceEnabled()) { @@ -8251,19 +8259,19 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe for (final Map.Entry> entry : newStates.entrySet()) { final String vm = entry.getKey(); - String xstoolsversion = entry.getValue().third(); + String platform = entry.getValue().third(); State newState = entry.getValue().second(); String host_uuid = entry.getValue().first(); final Ternary oldState = oldStates.remove(vm); - - // check if xstoolsversion changed - if (xstoolsversion != null && oldState != null) { - if (xstoolsversion != oldState.third() && newState != State.Stopped && newState != State.Stopping) { - s_logger.warn("Detecting a change in xstoolsversion for " + vm); - changes.put(vm, new Ternary(host_uuid, newState, xstoolsversion)); + + // check if platform changed + if (platform != null && oldState != null){ + if (!platform.equals(oldState.third()) && newState != State.Stopped && newState != State.Stopping){ + s_logger.warn("Detecting a change in platform for " + vm); + changes.put(vm, new Ternary(host_uuid, newState, platform)); s_logger.debug("11. The VM " + vm + " is in " + newState + " state"); - s_vms.put(_cluster, host_uuid, vm, newState, xstoolsversion); + s_vms.put(_cluster, host_uuid, vm, newState, platform); continue; } } @@ -8271,10 +8279,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (host_uuid != null && oldState != null) { if (!host_uuid.equals(oldState.first()) && newState != State.Stopped && newState != State.Stopping) { s_logger.warn("Detecting a change in host for " + vm); - changes.put(vm, new Ternary(host_uuid, newState, null)); + changes.put(vm, new Ternary(host_uuid, newState, platform)); s_logger.debug("11. The VM " + vm + " is in " + newState + " state"); - s_vms.put(_cluster, host_uuid, vm, newState, xstoolsversion); + s_vms.put(_cluster, host_uuid, vm, newState, platform); continue; } } @@ -8292,31 +8300,31 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe continue; } if (oldState == null) { - s_vms.put(_cluster, host_uuid, vm, newState, xstoolsversion); + s_vms.put(_cluster, host_uuid, vm, newState, platform); s_logger.warn("Detecting a new state but couldn't find a old state so adding it to the changes: " + vm); - changes.put(vm, new Ternary(host_uuid, newState, null)); + changes.put(vm, new Ternary(host_uuid, newState, platform)); } else if (oldState.second() == State.Starting) { if (newState == State.Running) { s_logger.debug("12. The VM " + vm + " is in " + State.Running + " state"); - s_vms.put(_cluster, host_uuid, vm, newState, xstoolsversion); + s_vms.put(_cluster, host_uuid, vm, newState, platform); } else if (newState == State.Stopped) { s_logger.warn("Ignoring vm " + vm + " because of a lag in starting the vm."); } } else if (oldState.second() == State.Migrating) { if (newState == State.Running) { s_logger.debug("Detected that an migrating VM is now running: " + vm); - s_vms.put(_cluster, host_uuid, vm, newState, xstoolsversion); + s_vms.put(_cluster, host_uuid, vm, newState, platform); } } else if (oldState.second() == State.Stopping) { if (newState == State.Stopped) { s_logger.debug("13. The VM " + vm + " is in " + State.Stopped + " state"); - s_vms.put(_cluster, host_uuid, vm, newState, xstoolsversion); + s_vms.put(_cluster, host_uuid, vm, newState, platform); } else if (newState == State.Running) { s_logger.warn("Ignoring vm " + vm + " because of a lag in stopping the vm. "); } } else if (oldState.second() != newState) { s_logger.debug("14. The VM " + vm + " is in " + newState + " state was " + oldState.second()); - s_vms.put(_cluster, host_uuid, vm, newState, xstoolsversion); + s_vms.put(_cluster, host_uuid, vm, newState, platform); if (newState == State.Stopped) { /* * if (s_vmsKilled.remove(vm)) { s_logger.debug("VM " + vm + " has been killed for storage. "); @@ -8733,4 +8741,18 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe @Override public void setRunLevel(int level) { } + + private boolean is_xcp() { + Connection conn = getConnection(); + String result = callHostPlugin(conn, "ovstunnel", "is_xcp"); + if (result.equals("XCP")) + return true; + return false; + } + + private String getLabel() { + Connection conn = getConnection(); + String result = callHostPlugin(conn, "ovstunnel", "getLabel"); + return result; + } } diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer610Resource.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer610Resource.java index 9a0d5597b9f..b7199c8c89f 100644 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer610Resource.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer610Resource.java @@ -454,18 +454,4 @@ public class XenServer610Resource extends XenServer56FP1Resource { } return "xenserver56"; } - - @Override - protected void finalizeVmMetaData(VM vm, Connection conn, VirtualMachineTO vmSpec) throws Exception { - Map details = vmSpec.getDetails(); - if (details != null) { - String xentoolsversion = details.get("hypervisortoolsversion"); - if (xentoolsversion == null || !xentoolsversion.equalsIgnoreCase("xenserver61")) { - Map platform = vm.getPlatform(conn); - platform.remove("device_id"); - vm.setPlatform(conn, platform); - } - } - } - } diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServerPoolVms.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServerPoolVms.java index 209be87ef92..71c0e394dc4 100644 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServerPoolVms.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServerPoolVms.java @@ -51,9 +51,9 @@ public class XenServerPoolVms { return pv == null ? State.Stopped : pv.second(); // if a VM is absent on the cluster, it is effectively in stopped state. } - public void put(String clusterId, String hostUuid, String name, State state, String xstoolsversion) { - HashMap> vms = getClusterVmState(clusterId); - vms.put(name, new Ternary(hostUuid, state, xstoolsversion)); + public void put(String clusterId, String hostUuid, String name, State state, String platform){ + HashMap> vms= getClusterVmState(clusterId); + vms.put(name, new Ternary(hostUuid, state, platform)); } public void put(String clusterId, String hostUuid, String name, State state) { diff --git a/plugins/hypervisors/xen/test/com/cloud/hypervisor/xen/resource/CitrixResourceBaseTest.java b/plugins/hypervisors/xen/test/com/cloud/hypervisor/xen/resource/CitrixResourceBaseTest.java index 788ad5a0cee..c56cc6d9e25 100644 --- a/plugins/hypervisors/xen/test/com/cloud/hypervisor/xen/resource/CitrixResourceBaseTest.java +++ b/plugins/hypervisors/xen/test/com/cloud/hypervisor/xen/resource/CitrixResourceBaseTest.java @@ -158,6 +158,7 @@ public class CitrixResourceBaseTest { doReturn(1).when(vmSpec).getCpus(); doNothing().when(vm).setVCPUsNumberLive(conn, 1L); doReturn(500).when(vmSpec).getMinSpeed(); + doReturn(500).when(vmSpec).getMaxSpeed(); doReturn(true).when(vmSpec).getLimitCpuUse(); doReturn(null).when(_resource).callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "cap", "value", "99", "vmname", "i-2-3-VM"); Map args = mock(HashMap.class); diff --git a/plugins/network-elements/cisco-vnmc/resources/META-INF/cloudstack/cisco-vnmc/module.properties b/plugins/network-elements/cisco-vnmc/resources/META-INF/cloudstack/cisco-vnmc/module.properties new file mode 100644 index 00000000000..69ffb6fe1d0 --- /dev/null +++ b/plugins/network-elements/cisco-vnmc/resources/META-INF/cloudstack/cisco-vnmc/module.properties @@ -0,0 +1,18 @@ +# 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. +name=cisco-vnmc +parent=network \ No newline at end of file diff --git a/plugins/network-elements/cisco-vnmc/resources/META-INF/cloudstack/cisco-vnmc/spring-cisco-vnmc-context.xml b/plugins/network-elements/cisco-vnmc/resources/META-INF/cloudstack/cisco-vnmc/spring-cisco-vnmc-context.xml new file mode 100644 index 00000000000..62e2ef088e3 --- /dev/null +++ b/plugins/network-elements/cisco-vnmc/resources/META-INF/cloudstack/cisco-vnmc/spring-cisco-vnmc-context.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + diff --git a/plugins/network-elements/f5/resources/META-INF/cloudstack/f5/module.properties b/plugins/network-elements/f5/resources/META-INF/cloudstack/f5/module.properties new file mode 100644 index 00000000000..efdb64a89e7 --- /dev/null +++ b/plugins/network-elements/f5/resources/META-INF/cloudstack/f5/module.properties @@ -0,0 +1,18 @@ +# 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. +name=f5 +parent=network \ No newline at end of file diff --git a/plugins/network-elements/f5/resources/META-INF/cloudstack/f5/spring-f5-context.xml b/plugins/network-elements/f5/resources/META-INF/cloudstack/f5/spring-f5-context.xml new file mode 100644 index 00000000000..6472d689c4f --- /dev/null +++ b/plugins/network-elements/f5/resources/META-INF/cloudstack/f5/spring-f5-context.xml @@ -0,0 +1,34 @@ + + + + + + + + diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ManagementNetworkGuru.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ManagementNetworkGuru.java index e86e98a215b..d3d9366ce4b 100644 --- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ManagementNetworkGuru.java +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ManagementNetworkGuru.java @@ -19,6 +19,8 @@ package org.apache.cloudstack.network.contrail.management; import java.io.File; import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; import java.util.Map; import java.util.Properties; @@ -60,12 +62,29 @@ public class ManagementNetworkGuru extends ContrailGuru { @Override public boolean configure(String name, Map params) throws ConfigurationException { File configFile = PropertiesUtil.findConfigFile(configuration); + FileInputStream inputFile = null; + + try { + if (null == configFile) { + throw new FileNotFoundException("Configuration file was not found!"); + } + inputFile = new FileInputStream(configFile); + } catch (FileNotFoundException e) { + s_logger.error(e.getMessage()); + throw new ConfigurationException(e.getMessage()); + } + final Properties configProps = new Properties(); try { - configProps.load(new FileInputStream(configFile)); - } catch (Exception ex) { - ex.printStackTrace(); - throw new ConfigurationException(ex.getMessage()); + configProps.load(inputFile); + } catch (IOException e) { + s_logger.error(e.getMessage()); + throw new ConfigurationException(e.getMessage()); + } finally { + try { + inputFile.close(); + } catch (IOException e) { + } } _mgmt_cidr = configProps.getProperty("management.cidr"); _mgmt_gateway = configProps.getProperty("management.gateway"); @@ -100,8 +119,8 @@ public class ManagementNetworkGuru extends ContrailGuru { return null; } NetworkVO network = - new NetworkVO(offering.getTrafficType(), Mode.Dhcp, BroadcastDomainType.Lswitch, offering.getId(), Network.State.Allocated, plan.getDataCenterId(), - plan.getPhysicalNetworkId()); + new NetworkVO(offering.getTrafficType(), Mode.Dhcp, BroadcastDomainType.Lswitch, offering.getId(), Network.State.Allocated, plan.getDataCenterId(), + plan.getPhysicalNetworkId()); if (_mgmt_cidr != null) { network.setCidr(_mgmt_cidr); network.setGateway(_mgmt_gateway); diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java index ca44757d07c..e15e2ce8ff6 100644 --- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java @@ -29,14 +29,11 @@ import net.juniper.contrail.api.ApiConnector; import net.juniper.contrail.api.types.ServiceInstance; import net.juniper.contrail.api.types.VirtualNetwork; -import org.apache.log4j.Logger; - -import com.google.gson.Gson; - import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.network.contrail.api.response.ServiceInstanceResponse; import org.apache.cloudstack.network.contrail.model.ServiceInstanceModel; import org.apache.cloudstack.network.contrail.model.VirtualMachineModel; +import org.apache.log4j.Logger; import com.cloud.api.ApiDBUtils; import com.cloud.dc.DataCenter; @@ -61,6 +58,7 @@ import com.cloud.vm.UserVmVO; import com.cloud.vm.VirtualMachineManager; import com.cloud.vm.VirtualMachineName; import com.cloud.vm.dao.UserVmDao; +import com.google.gson.Gson; @Local(value = {ServiceManager.class}) public class ServiceManagerImpl implements ServiceManager { @@ -98,7 +96,7 @@ public class ServiceManagerImpl implements ServiceManager { */ @ActionEvent(eventType = EventTypes.EVENT_VM_CREATE, eventDescription = "createServiceInstance", create = true) private ServiceVirtualMachine createServiceVM(DataCenter zone, Account owner, VirtualMachineTemplate template, ServiceOffering serviceOffering, String name, - ServiceInstance siObj, Network left, Network right) { + ServiceInstance siObj, Network left, Network right) { long id = _vmDao.getNextInSequence(Long.class, "id"); DataCenterDeployment plan = new DataCenterDeployment(zone.getId()); @@ -111,8 +109,8 @@ public class ServiceManagerImpl implements ServiceManager { String instanceName = VirtualMachineName.getVmName(id, owner.getId(), "SRV"); ServiceVirtualMachine svm = - new ServiceVirtualMachine(id, instanceName, name, template.getId(), serviceOffering.getId(), template.getHypervisorType(), template.getGuestOSId(), - zone.getId(), owner.getDomainId(), owner.getAccountId(), false); + new ServiceVirtualMachine(id, instanceName, name, template.getId(), serviceOffering.getId(), template.getHypervisorType(), template.getGuestOSId(), + zone.getId(), owner.getDomainId(), owner.getAccountId(), false); // database synchronization code must be able to distinguish service instance VMs. Map kvmap = new HashMap(); @@ -132,7 +130,7 @@ public class ServiceManagerImpl implements ServiceManager { @Override public ServiceVirtualMachine createServiceInstance(DataCenter zone, Account owner, VirtualMachineTemplate template, ServiceOffering serviceOffering, String name, - Network left, Network right) { + Network left, Network right) { s_logger.debug("createServiceInstance by " + owner.getAccountName()); // TODO: permission model. // service instances need to be able to access the public network. @@ -227,10 +225,12 @@ public class ServiceManagerImpl implements ServiceManager { @Override public ServiceInstanceResponse createServiceInstanceResponse(long instanceId) { s_logger.debug("ServiceInstance response for id: " + instanceId); + UserVmVO vm = _vmDao.findById(instanceId); ServiceInstanceResponse response = new ServiceInstanceResponse(); response.setId(vm.getUuid()); Account owner = _accountService.getAccount(vm.getAccountId()); + if (owner.getType() == Account.ACCOUNT_TYPE_PROJECT) { Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(owner.getAccountId()); response.setProjectId(project.getUuid()); diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VirtualMachineModel.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VirtualMachineModel.java index 32d5d938996..96cea95250d 100644 --- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VirtualMachineModel.java +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VirtualMachineModel.java @@ -27,12 +27,8 @@ import net.juniper.contrail.api.types.Project; import net.juniper.contrail.api.types.ServiceInstance; import net.juniper.contrail.api.types.VirtualMachine; -import org.apache.log4j.Logger; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - import org.apache.cloudstack.network.contrail.management.ContrailManager; +import org.apache.log4j.Logger; import com.cloud.exception.InternalErrorException; import com.cloud.network.dao.NetworkDao; @@ -42,11 +38,13 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicVO; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.dao.NicDao; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; public class VirtualMachineModel extends ModelObjectBase { private static final Logger s_logger = Logger.getLogger(VirtualMachineModel.class); - private String _uuid; + private final String _uuid; private long _instanceId; /* @@ -113,8 +111,12 @@ public class VirtualMachineModel extends ModelObjectBase { throw new CloudRuntimeException("Unable to read service-instance object", ex); } if (siObj == null) { + //If the ServiceInstance object is null, do not call build. It will break in many places. Instead, call update passing the controller as parameter. + //It will then create a new ServiceInstance is that's null. siModel = new ServiceInstanceModel(serviceUuid); - siModel.build(controller, siObj); + siModel.update(controller); + + siObj = siModel.getServiceInstance(); } } _serviceModel = siModel; @@ -197,21 +199,21 @@ public class VirtualMachineModel extends ModelObjectBase { boolean isActiveInstance(VMInstanceVO instance) { switch (instance.getState()) { - case Migrating: - case Starting: - case Running: - case Shutdowned: - case Stopped: - case Stopping: - return true; + case Migrating: + case Starting: + case Running: + case Shutdowned: + case Stopped: + case Stopping: + return true; - case Destroyed: - case Error: - case Expunging: - return false; + case Destroyed: + case Error: + case Expunging: + return false; - default: - s_logger.warn("Unknown VMInstance state " + instance.getState().getDescription()); + default: + s_logger.warn("Unknown VMInstance state " + instance.getState().getDescription()); } return true; } @@ -255,17 +257,17 @@ public class VirtualMachineModel extends ModelObjectBase { String tag; switch (nic.getDeviceId()) { - case 0: - tag = "management"; - break; - case 1: - tag = "left"; - break; - case 2: - tag = "right"; - break; - default: - tag = null; + case 0: + tag = "management"; + break; + case 1: + tag = "left"; + break; + case 2: + tag = "right"; + break; + default: + tag = null; } VMInterfaceModel vmiModel = getVMInterface(nic.getUuid()); diff --git a/plugins/network-elements/juniper-srx/resources/META-INF/cloudstack/srx/module.properties b/plugins/network-elements/juniper-srx/resources/META-INF/cloudstack/srx/module.properties new file mode 100644 index 00000000000..dde649bf753 --- /dev/null +++ b/plugins/network-elements/juniper-srx/resources/META-INF/cloudstack/srx/module.properties @@ -0,0 +1,18 @@ +# 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. +name=srx +parent=network \ No newline at end of file diff --git a/plugins/network-elements/juniper-srx/resources/META-INF/cloudstack/srx/spring-srx-context.xml b/plugins/network-elements/juniper-srx/resources/META-INF/cloudstack/srx/spring-srx-context.xml new file mode 100644 index 00000000000..2e17f7cf4ee --- /dev/null +++ b/plugins/network-elements/juniper-srx/resources/META-INF/cloudstack/srx/spring-srx-context.xml @@ -0,0 +1,35 @@ + + + + + + + + diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java b/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java index ac3e9ab05be..338e0953249 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java @@ -691,7 +691,7 @@ public class JuniperSrxResource implements ServerResource { Long publicVlanTag = null; if (ip.getBroadcastUri() != null && !ip.getBroadcastUri().equals("untagged")) { try { - publicVlanTag = Long.parseLong(ip.getBroadcastUri()); + publicVlanTag = Long.parseLong(BroadcastDomainType.getValue(ip.getBroadcastUri())); } catch (Exception e) { throw new ExecutionException("Could not parse public VLAN tag: " + ip.getBroadcastUri()); } diff --git a/plugins/network-elements/netscaler/resources/META-INF/cloudstack/netscaler/module.properties b/plugins/network-elements/netscaler/resources/META-INF/cloudstack/netscaler/module.properties new file mode 100644 index 00000000000..2f1b641ae1d --- /dev/null +++ b/plugins/network-elements/netscaler/resources/META-INF/cloudstack/netscaler/module.properties @@ -0,0 +1,18 @@ +# 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. +name=netscaler +parent=network \ No newline at end of file diff --git a/plugins/network-elements/netscaler/resources/META-INF/cloudstack/netscaler/spring-netscaler-context.xml b/plugins/network-elements/netscaler/resources/META-INF/cloudstack/netscaler/spring-netscaler-context.xml new file mode 100644 index 00000000000..b70398cd9e0 --- /dev/null +++ b/plugins/network-elements/netscaler/resources/META-INF/cloudstack/netscaler/spring-netscaler-context.xml @@ -0,0 +1,35 @@ + + + + + + + + + diff --git a/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java b/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java index 7dac9a008aa..e8272986c99 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java +++ b/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java @@ -16,6 +16,9 @@ // under the License. package com.cloud.network.resource; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.security.cert.Certificate; import java.util.ArrayList; import java.util.Formatter; import java.util.HashMap; @@ -25,6 +28,15 @@ import java.util.Map; import javax.naming.ConfigurationException; +import com.citrix.netscaler.nitro.resource.config.ssl.sslcertkey; +import com.citrix.netscaler.nitro.resource.config.ssl.sslcertkey_sslvserver_binding; +import com.citrix.netscaler.nitro.resource.config.ssl.sslcertlink; +import com.citrix.netscaler.nitro.resource.config.ssl.sslvserver_sslcertkey_binding; +import com.cloud.network.lb.LoadBalancingRule.LbSslCert; +import com.cloud.utils.security.CertificateHelper; +import com.cloud.utils.ssh.SshHelper; +import com.google.common.collect.Lists; +import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.log4j.Logger; import com.citrix.netscaler.nitro.exception.nitro_exception; @@ -61,8 +73,6 @@ import com.citrix.netscaler.nitro.resource.config.ns.nshardware; import com.citrix.netscaler.nitro.resource.config.ns.nsip; import com.citrix.netscaler.nitro.resource.config.ns.nstimer; import com.citrix.netscaler.nitro.resource.config.ns.nstimer_autoscalepolicy_binding; -import com.citrix.netscaler.nitro.resource.config.ssl.sslcertkey; -import com.citrix.netscaler.nitro.resource.config.ssl.sslvserver_sslcertkey_binding; import com.citrix.netscaler.nitro.resource.stat.lb.lbvserver_stats; import com.citrix.netscaler.nitro.service.nitro_service; import com.citrix.netscaler.nitro.util.filtervalue; @@ -111,7 +121,6 @@ import com.cloud.agent.api.to.LoadBalancerTO.StickinessPolicyTO; import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.host.Host; import com.cloud.host.Host.Type; -import com.cloud.network.lb.LoadBalancingRule.LbSslCert; import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType; import com.cloud.resource.ServerResource; import com.cloud.serializer.GsonHelper; @@ -119,7 +128,7 @@ import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.exception.ExecutionException; import com.cloud.utils.net.NetUtils; -import com.cloud.utils.ssh.SshHelper; +import org.bouncycastle.openssl.PEMWriter; class NitroError { static final int NS_RESOURCE_EXISTS = 273; @@ -665,23 +674,61 @@ public class NetscalerResource implements ServerResource { } - if (sslCert != null && lbProtocol.equals(NetUtils.SSL_PROTO)) { + if (sslCert != null && lbProtocol.equalsIgnoreCase(NetUtils.SSL_PROTO)) { if (sslCert.isRevoked()) { deleteCert = true; } else { - String certName = generateSslCertName(srcIp, srcPort); - String keyName = generateSslKeyName(srcIp, srcPort); - String certKeyName = generateSslCertKeyName(srcIp, srcPort); + // If there is a chain, that should go first to the NS - if (SSL.isSslCertKeyPresent(_netscalerService, certKeyName)) { - SSL.deleteSslCertKey(_netscalerService, certKeyName); + String previousCertKeyName = null; + + if ( sslCert.getChain() != null ) { + List chainList = CertificateHelper.parseChain(sslCert.getChain()); + // go from ROOT to intermediate CAs + for ( Certificate intermediateCert : Lists.reverse(chainList)){ + + String fingerPrint=CertificateHelper.generateFingerPrint(intermediateCert); + String intermediateCertKeyName = generateSslCertKeyName(fingerPrint); + String intermediateCertFileName = intermediateCertKeyName + ".pem"; + + if (! SSL.isSslCertKeyPresent(_netscalerService, intermediateCertKeyName)) { + byte[] certData= intermediateCert.getEncoded(); + StringWriter textWriter = new StringWriter(); + PEMWriter pemWriter = new PEMWriter(textWriter); + pemWriter.writeObject(intermediateCert); + pemWriter.flush(); + + SSL.uploadCert(_ip, _username, _password, intermediateCertFileName, textWriter.toString().getBytes()); + SSL.createSslCertKey(_netscalerService, intermediateCertFileName, null, intermediateCertKeyName, null); + } + + if ( previousCertKeyName != null && ! SSL.certLinkExists(_netscalerService, intermediateCertKeyName, previousCertKeyName)){ + SSL.linkCerts(_netscalerService, intermediateCertKeyName, previousCertKeyName); + } + + previousCertKeyName = intermediateCertKeyName; + } } - SSL.uploadCert(_ip, _username, _password, certName, sslCert.getCert().getBytes()); - SSL.uploadKey(_ip, _username, _password, keyName, sslCert.getKey().getBytes()); + String certFilename = generateSslCertName(sslCert.getFingerprint()) + ".pem"; //netscaler uses ".pem" format for "bundle" files + String keyFilename = generateSslKeyName(sslCert.getFingerprint()) + ".pem"; //netscaler uses ".pem" format for "bundle" files + String certKeyName = generateSslCertKeyName(sslCert.getFingerprint()); + + ByteArrayOutputStream certDataStream = new ByteArrayOutputStream( ); + certDataStream.write(sslCert.getCert().getBytes()); + + if (! SSL.isSslCertKeyPresent(_netscalerService, certKeyName)) { + + SSL.uploadCert(_ip, _username, _password, certFilename, certDataStream.toByteArray()); + SSL.uploadKey(_ip, _username, _password, keyFilename, sslCert.getKey().getBytes()); + SSL.createSslCertKey(_netscalerService, certFilename, keyFilename, certKeyName, sslCert.getPassword()); + } + + if (previousCertKeyName != null && ! SSL.certLinkExists(_netscalerService, certKeyName, previousCertKeyName)){ + SSL.linkCerts(_netscalerService, certKeyName, previousCertKeyName); + } - SSL.createSslCertKey(_netscalerService, certName, keyName, certKeyName, sslCert.getPassword()); SSL.bindCertKeyToVserver(_netscalerService, certKeyName, nsVirtualServerName); } @@ -778,18 +825,50 @@ public class NetscalerResource implements ServerResource { } if (sslCert != null && deleteCert) { - String certName = generateSslCertName(srcIp, srcPort); - String keyName = generateSslKeyName(srcIp, srcPort); - String certKeyName = generateSslCertKeyName(srcIp, srcPort); + String certFilename = generateSslCertName(sslCert.getFingerprint()) + ".pem"; //netscaler uses ".pem" format for "bundle" files + String keyFilename = generateSslKeyName(sslCert.getFingerprint()) + ".pem"; //netscaler uses ".pem" format for "bundle" files + String certKeyName = generateSslCertKeyName(sslCert.getFingerprint()); // unbind before deleting - if (nsVirtualServerExists(nsVirtualServerName)) { + if (nsVirtualServerExists(nsVirtualServerName) && + SSL.isSslCertKeyPresent(_netscalerService, certKeyName) && + SSL.isBoundToVserver(_netscalerService, certKeyName, nsVirtualServerName)) { SSL.unbindCertKeyFromVserver(_netscalerService, certKeyName, nsVirtualServerName); } - SSL.deleteSslCertKey(_netscalerService, certKeyName); - SSL.deleteCertFile(_ip, _username, _password, certName); - SSL.deleteKeyFile(_ip, _username, _password, keyName); + if (SSL.isSslCertKeyPresent(_netscalerService, certKeyName)) { + + SSL.deleteSslCertKey(_netscalerService, certKeyName); + SSL.deleteCertFile(_ip, _username, _password, certFilename); + SSL.deleteKeyFile(_ip, _username, _password, keyFilename); + } + + + /* + * Check and delete intermediate certs: + * we can delete an intermediate cert if no other + * cert references it as the athority + */ + + if ( sslCert.getChain() != null ) { + List chainList = CertificateHelper.parseChain(sslCert.getChain()); + //go from intermediate CAs to ROOT + for ( Certificate intermediateCert : chainList){ + + String fingerPrint=CertificateHelper.generateFingerPrint(intermediateCert); + String intermediateCertKeyName = generateSslCertKeyName(fingerPrint); + String intermediateCertFileName = intermediateCertKeyName + ".pem"; + + if (SSL.isSslCertKeyPresent(_netscalerService, intermediateCertKeyName) && + ! SSL.isCaforCerts(_netscalerService, intermediateCertKeyName)) { + SSL.deleteSslCertKey(_netscalerService, intermediateCertKeyName); + SSL.deleteCertFile(_ip, _username, _password, intermediateCertFileName); + }else { + break;// if this cert has another certificate as a child then stop at this point because we need the whole chain + } + + } + } } } @@ -1718,7 +1797,7 @@ public class NetscalerResource implements ServerResource { return false; } - private static void deleteSslCertKey(nitro_service ns, String certKeyName) throws ExecutionException { + private static void deleteSslCertKey(nitro_service ns, String certKeyName) throws ExecutionException { try { sslcertkey certkey = new sslcertkey(); @@ -1733,21 +1812,23 @@ public class NetscalerResource implements ServerResource { } - private static void deleteCertFile(String nsIp, String username, String password, String certName) throws Exception { - SshHelper.sshExecute(nsIp, SSH_PORT, username, null, password, "shell rm " + SSL_CERT_PATH + certName); + private static void deleteCertFile(String nsIp, String username, String password, String certFilename) throws Exception { + SshHelper.sshExecute(nsIp,SSH_PORT,username,null,password,"shell rm " + SSL_CERT_PATH + certFilename); } - private static void deleteKeyFile(String nsIp, String username, String password, String keyName) throws Exception { - SshHelper.sshExecute(nsIp, SSH_PORT, username, null, password, "shell rm " + SSL_CERT_PATH + keyName); + private static void deleteKeyFile(String nsIp, String username, String password, String keyFilename) throws Exception { + SshHelper.sshExecute(nsIp, SSH_PORT, username, null, password, "shell rm " + SSL_CERT_PATH + keyFilename); } - private static void createSslCertKey(nitro_service ns, String certName, String keyName, String certKeyName, String password) throws ExecutionException { + private static void createSslCertKey(nitro_service ns, String certFilename, String keyFilename, String certKeyName, String password) throws ExecutionException { s_logger.debug("Adding cert to netscaler"); try { sslcertkey certkey = new sslcertkey(); certkey.set_certkey(certKeyName); - certkey.set_cert(SSL_CERT_PATH + certName); - certkey.set_key(SSL_CERT_PATH + keyName); + certkey.set_cert(SSL_CERT_PATH + certFilename); + + if ( keyFilename != null ) + certkey.set_key(SSL_CERT_PATH + keyFilename); if (password != null) { certkey.set_passplain(password); @@ -1813,17 +1894,17 @@ public class NetscalerResource implements ServerResource { } - private static void uploadCert(String nsIp, String user, String password, String certName, byte[] certData) throws ExecutionException { + private static void uploadCert(String nsIp, String user, String password, String certFilename, byte[] certData) throws ExecutionException { try { - SshHelper.scpTo(nsIp, SSH_PORT, user, null, password, SSL_CERT_PATH, certData, certName, null); - } catch (Exception e) { + SshHelper.scpTo(nsIp,SSH_PORT,user,null,password, SSL_CERT_PATH, certData, certFilename, null); + } catch (Exception e){ throw new ExecutionException("Failed to copy private key to device " + e.getMessage()); } } - private static void uploadKey(String nsIp, String user, String password, String keyName, byte[] keyData) throws ExecutionException { + private static void uploadKey(String nsIp, String user, String password, String keyFilename, byte[] keyData) throws ExecutionException { try { - SshHelper.scpTo(nsIp, SSH_PORT, user, null, password, SSL_CERT_PATH, keyData, keyName, null); + SshHelper.scpTo(nsIp, SSH_PORT, user, null, password, SSL_CERT_PATH, keyData, keyFilename, null); } catch (Exception e) { throw new ExecutionException("Failed to copy private key to device " + e.getMessage()); } @@ -1831,7 +1912,7 @@ public class NetscalerResource implements ServerResource { private static void enableSslFeature(nitro_service ns) throws ExecutionException { try { - base_response result = ns.enable_features(new String[] {"SSL"}); + base_response result = ns.enable_features(new String[]{"SSL"}); if (result.errorcode != 0) throw new ExecutionException("Unable to enable SSL on LB"); } catch (nitro_exception e) { @@ -1859,6 +1940,80 @@ public class NetscalerResource implements ServerResource { } } + public static boolean certLinkExists(nitro_service ns, String userCertName, String caCertName) throws ExecutionException { + try { + // check if there is a link from userCertName to caCertName + + sslcertkey userCert = sslcertkey.get(ns,userCertName); + String nsCaCert = userCert.get_linkcertkeyname(); + + if (nsCaCert != null && nsCaCert.equals(caCertName)) + return true; + + } catch (nitro_exception e) { + throw new ExecutionException("Failed to check cert link on load balancer to " + e.getMessage()); + } catch (Exception e) { + throw new ExecutionException("Failed to check cert link on load balancer due to " + e.getMessage()); + } + return false; + } + + public static void linkCerts(nitro_service ns, String userCertName, String caCertName) throws ExecutionException { + try { + + // the assumption is that that both userCertName and caCertName are present on NS + + sslcertkey caCert = sslcertkey.get(ns, caCertName); + sslcertkey userCert = sslcertkey.get(ns, userCertName); + + sslcertkey linkResource = new sslcertkey(); + + // link user cert to CA cert + linkResource.set_certkey(userCert.get_certkey()); + linkResource.set_linkcertkeyname(caCert.get_certkey()); + sslcertkey.link(ns, linkResource); + + } catch (nitro_exception e) { + throw new ExecutionException("Failed to check cert link on load balancer to " + e.getMessage()); + } catch (Exception e) { + throw new ExecutionException("Failed to check cert link on load balancer due to " + e.getMessage()); + } + + } + + public static boolean isCaforCerts(nitro_service ns, String caCertName) throws ExecutionException { + // check if this certificate serves as a CA for other certificates + try { + sslcertlink[] childLinks = sslcertlink.get_filtered(ns,"linkcertkeyname:" + caCertName); + if(childLinks != null && childLinks.length > 0){ + return true; + } + + } catch (nitro_exception e) { + throw new ExecutionException("Failed to check cert link on load balancer to " + e.getMessage()); + } catch (Exception e) { + throw new ExecutionException("Failed to check cert link on load balancer due to " + e.getMessage()); + } + return false; + + } + + public static boolean isBoundToVserver(nitro_service ns, String certKeyName, String nsVirtualServerName) throws ExecutionException { + try { + + sslcertkey_sslvserver_binding[] cert_vs_binding = sslcertkey_sslvserver_binding.get_filtered(ns, certKeyName, "vservername:" + nsVirtualServerName); + if(cert_vs_binding != null && cert_vs_binding.length > 0){ + return true; + } + + } catch (nitro_exception e) { + throw new ExecutionException("Failed to check cert link on load balancer to " + e.getMessage()); + } catch (Exception e) { + throw new ExecutionException("Failed to check cert link on load balancer due to " + e.getMessage()); + } + return false; + + } } private void enableVPXInterfaces(String publicIf, String privateIf, ns ns_obj) { @@ -3588,17 +3743,22 @@ public class NetscalerResource implements ServerResource { return counterName.replace(' ', '_'); } - private String generateSslCertName(String srcIp, long srcPort) { + private String generateSslCertName(String fingerPrint) { // maximum length supported by NS is 31 - return genObjectName("Cloud-Cert", srcIp, srcPort); + // the first 20 characters of the SHA-1 checksum are the unique id + String uniqueId = fingerPrint.replace(":","").substring(0,20); + + return genObjectName("Cloud-Cert", uniqueId); } - private String generateSslKeyName(String srcIp, long srcPort) { - return genObjectName("Cloud-Key", srcIp, srcPort); + private String generateSslKeyName(String fingerPrint) { + String uniqueId = fingerPrint.replace(":","").substring(0,20); + return genObjectName("Cloud-Key", uniqueId); } - private String generateSslCertKeyName(String srcIp, long srcPort) { - return genObjectName("Cloud-CertKey", srcIp, srcPort); + private String generateSslCertKeyName(String fingerPrint){ + String uniqueId = fingerPrint.replace(":","").substring(0,20); + return genObjectName("Cloud-Cert", uniqueId); } private String genObjectName(Object... args) { diff --git a/plugins/network-elements/ovs/resources/META-INF/cloudstack/ovs/spring-ovs-context.xml b/plugins/network-elements/ovs/resources/META-INF/cloudstack/ovs/spring-ovs-context.xml index 9180eebd040..e60d93e08a1 100644 --- a/plugins/network-elements/ovs/resources/META-INF/cloudstack/ovs/spring-ovs-context.xml +++ b/plugins/network-elements/ovs/resources/META-INF/cloudstack/ovs/spring-ovs-context.xml @@ -36,5 +36,7 @@ + + diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateGreTunnelAnswer.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateGreTunnelAnswer.java new file mode 100644 index 00000000000..7913cc845de --- /dev/null +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateGreTunnelAnswer.java @@ -0,0 +1,81 @@ +// 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.agent.api; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.Command; + +public class OvsCreateGreTunnelAnswer extends Answer { + String hostIp; + String remoteIp; + String bridge; + String key; + long from; + long to; + int port; + + public OvsCreateGreTunnelAnswer(Command cmd, boolean success, String details) { + super(cmd, success, details); + } + + public OvsCreateGreTunnelAnswer(Command cmd, boolean success, + String details, String hostIp, String bridge) { + super(cmd, success, details); + OvsCreateGreTunnelCommand c = (OvsCreateGreTunnelCommand) cmd; + this.hostIp = hostIp; + this.bridge = bridge; + this.remoteIp = c.getRemoteIp(); + this.key = c.getKey(); + this.port = -1; + this.from = c.getFrom(); + this.to = c.getTo(); + } + + public OvsCreateGreTunnelAnswer(Command cmd, boolean success, + String details, String hostIp, String bridge, int port) { + this(cmd, success, details, hostIp, bridge); + this.port = port; + } + + public String getHostIp() { + return hostIp; + } + + public String getRemoteIp() { + return remoteIp; + } + + public String getBridge() { + return bridge; + } + + public String getKey() { + return key; + } + + public long getFrom() { + return from; + } + + public long getTo() { + return to; + } + + public int getPort() { + return port; + } +} diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsCreateGreTunnelCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateGreTunnelCommand.java similarity index 59% rename from plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsCreateGreTunnelCommand.java rename to plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateGreTunnelCommand.java index e2cd2d8dd9c..588ff519006 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsCreateGreTunnelCommand.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateGreTunnelCommand.java @@ -14,41 +14,42 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.network.ovs; +package com.cloud.agent.api; import com.cloud.agent.api.Command; public class OvsCreateGreTunnelCommand extends Command { - String remoteIp; - String key; - long from; - long to; + String remoteIp; + String key; + long from; + long to; - @Override - public boolean executeInSequence() { - return true; - } + @Override + public boolean executeInSequence() { + return true; + } - public OvsCreateGreTunnelCommand(String remoteIp, String key, long from, long to) { - this.remoteIp = remoteIp; - this.key = key; - this.from = from; - this.to = to; - } + public OvsCreateGreTunnelCommand(String remoteIp, String key, long from, + long to) { + this.remoteIp = remoteIp; + this.key = key; + this.from = from; + this.to = to; + } - public String getRemoteIp() { - return remoteIp; - } + public String getRemoteIp() { + return remoteIp; + } - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public long getFrom() { - return from; - } + public long getFrom() { + return from; + } - public long getTo() { - return to; - } + public long getTo() { + return to; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateTunnelAnswer.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateTunnelAnswer.java new file mode 100644 index 00000000000..f921042ca62 --- /dev/null +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateTunnelAnswer.java @@ -0,0 +1,85 @@ +// 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.agent.api; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.Command; + +public class OvsCreateTunnelAnswer extends Answer { + Long from; + Long to; + long networkId; + String inPortName; + + // for debug info + String fromIp; + String toIp; + int key; + String bridge; + + public OvsCreateTunnelAnswer(Command cmd, boolean success, String details, + String bridge) { + super(cmd, success, details); + OvsCreateTunnelCommand c = (OvsCreateTunnelCommand) cmd; + from = c.getFrom(); + to = c.getTo(); + networkId = c.getNetworkId(); + inPortName = "[]"; + fromIp = c.getFromIp(); + toIp = c.getRemoteIp(); + key = c.getKey(); + this.bridge = bridge; + } + + public OvsCreateTunnelAnswer(Command cmd, boolean success, String details, + String inPortName, String bridge) { + this(cmd, success, details, bridge); + this.inPortName = inPortName; + } + + public Long getFrom() { + return from; + } + + public Long getTo() { + return to; + } + + public long getNetworkId() { + return networkId; + } + + public String getInPortName() { + return inPortName; + } + + public String getFromIp() { + return fromIp; + } + + public String getToIp() { + return toIp; + } + + public int getKey() { + return key; + } + + public String getBridge() { + return bridge; + } +} diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsSetTagAndFlowCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateTunnelCommand.java similarity index 51% rename from plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsSetTagAndFlowCommand.java rename to plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateTunnelCommand.java index 17121a00c8e..1dc4d8296d3 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsSetTagAndFlowCommand.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateTunnelCommand.java @@ -14,47 +14,57 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.network.ovs; +package com.cloud.agent.api; import com.cloud.agent.api.Command; -public class OvsSetTagAndFlowCommand extends Command { - String vlans; - String vmName; - String seqno; - String tag; - Long vmId; +public class OvsCreateTunnelCommand extends Command { + Integer key; + String remoteIp; + Long from; + Long to; + long networkId; - @Override - public boolean executeInSequence() { - return true; - } + // for debug info + String fromIp; - public String getSeqNo() { - return seqno; - } + @Override + public boolean executeInSequence() { + return true; + } - public String getVlans() { - return vlans; - } + public OvsCreateTunnelCommand(String remoteIp, Integer key, Long from, + Long to, long networkId, String fromIp) { + this.remoteIp = remoteIp; + this.key = key; + this.from = from; + this.to = to; + this.networkId = networkId; + this.fromIp = fromIp; + } - public String getVmName() { - return vmName; - } + public Integer getKey() { + return key; + } - public Long getVmId() { - return vmId; - } + public String getRemoteIp() { + return remoteIp; + } - public String getTag() { - return tag; - } + public Long getFrom() { + return from; + } + + public Long getTo() { + return to; + } + + public long getNetworkId() { + return networkId; + } + + public String getFromIp() { + return fromIp; + } - public OvsSetTagAndFlowCommand(String vmName, String tag, String vlans, String seqno, Long vmId) { - this.vmName = vmName; - this.tag = tag; - this.vlans = vlans; - this.seqno = seqno; - this.vmId = vmId; - } } diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsDeleteFlowCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDeleteFlowCommand.java similarity index 76% rename from plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsDeleteFlowCommand.java rename to plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDeleteFlowCommand.java index 2a6d5d7d81d..3b5e1c23370 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsDeleteFlowCommand.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDeleteFlowCommand.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.network.ovs; +package com.cloud.agent.api; import com.cloud.agent.api.Command; public class OvsDeleteFlowCommand extends Command { - String vmName; + String vmName; - @Override - public boolean executeInSequence() { - return true; - } + @Override + public boolean executeInSequence() { + return true; + } - public String getVmName() { - return vmName; - } + public String getVmName() { + return vmName; + } - public OvsDeleteFlowCommand(String vmName) { - this.vmName = vmName; - } + public OvsDeleteFlowCommand(String vmName) { + this.vmName = vmName; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsDestroyBridgeCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDestroyBridgeCommand.java similarity index 69% rename from plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsDestroyBridgeCommand.java rename to plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDestroyBridgeCommand.java index 7be67765213..21b89af2043 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsDestroyBridgeCommand.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDestroyBridgeCommand.java @@ -15,31 +15,30 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.network.ovs; +package com.cloud.agent.api; import com.cloud.agent.api.Command; public class OvsDestroyBridgeCommand extends Command { - Long networkId; - Integer key; + Long networkId; + Integer key; - public OvsDestroyBridgeCommand(Long networkId, Integer key) { - this.networkId = networkId; - this.key = key; - } + public OvsDestroyBridgeCommand(Long networkId, Integer key) { + this.networkId = networkId; + this.key = key; + } - public Long getNetworkId() { - return networkId; - } + public Long getNetworkId() { + return networkId; + } - public Integer getKey() { - return key; - } - - @Override - public boolean executeInSequence() { - return true; - } + public Integer getKey() { + return key; + } + @Override + public boolean executeInSequence() { + return true; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsDestroyTunnelCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDestroyTunnelCommand.java similarity index 61% rename from plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsDestroyTunnelCommand.java rename to plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDestroyTunnelCommand.java index 527dc7be3c4..d06acf52df4 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsDestroyTunnelCommand.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDestroyTunnelCommand.java @@ -14,37 +14,37 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.network.ovs; +package com.cloud.agent.api; import com.cloud.agent.api.Command; public class OvsDestroyTunnelCommand extends Command { - Long networkId; - Integer key; - String inPortName; + Long networkId; + Integer key; + String inPortName; - public OvsDestroyTunnelCommand(Long networkId, Integer key, String inPortName) { - this.networkId = networkId; - this.inPortName = inPortName; - this.key = key; - } + public OvsDestroyTunnelCommand(Long networkId, Integer key, + String inPortName) { + this.networkId = networkId; + this.inPortName = inPortName; + this.key = key; + } - public Long getNetworkId() { - return networkId; - } + public Long getNetworkId() { + return networkId; + } - public String getInPortName() { - return inPortName; - } + public String getInPortName() { + return inPortName; + } - public Integer getKey() { - return key; - } - - @Override - public boolean executeInSequence() { - return true; - } + public Integer getKey() { + return key; + } + @Override + public boolean executeInSequence() { + return true; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsFetchInterfaceAnswer.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsFetchInterfaceAnswer.java similarity index 52% rename from plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsFetchInterfaceAnswer.java rename to plugins/network-elements/ovs/src/com/cloud/agent/api/OvsFetchInterfaceAnswer.java index 1d091179709..6c7deaaf957 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsFetchInterfaceAnswer.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsFetchInterfaceAnswer.java @@ -15,43 +15,44 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.network.ovs; +package com.cloud.agent.api; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; public class OvsFetchInterfaceAnswer extends Answer { - String ip; - String netmask; - String mac; - String label; + String ip; + String netmask; + String mac; + String label; - public OvsFetchInterfaceAnswer(Command cmd, boolean success, String details) { - super(cmd, success, details); - this.label = ((OvsFetchInterfaceCommand)cmd).getLabel(); - } + public OvsFetchInterfaceAnswer(Command cmd, boolean success, String details) { + super(cmd, success, details); + this.label = ((OvsFetchInterfaceCommand) cmd).getLabel(); + } - public OvsFetchInterfaceAnswer(Command cmd, boolean success, String details, String ip, String netmask, String mac) { - super(cmd, success, details); - this.ip = ip; - this.netmask = netmask; - this.mac = mac; - this.label = ((OvsFetchInterfaceCommand)cmd).getLabel(); - } + public OvsFetchInterfaceAnswer(Command cmd, boolean success, + String details, String ip, String netmask, String mac) { + super(cmd, success, details); + this.ip = ip; + this.netmask = netmask; + this.mac = mac; + this.label = ((OvsFetchInterfaceCommand) cmd).getLabel(); + } - public String getIp() { - return ip; - } + public String getIp() { + return ip; + } - public String getNetmask() { - return netmask; - } + public String getNetmask() { + return netmask; + } - public String getMac() { - return mac; - } + public String getMac() { + return mac; + } - public String getLabel() { - return label; - } + public String getLabel() { + return label; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsFetchInterfaceCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsFetchInterfaceCommand.java similarity index 76% rename from plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsFetchInterfaceCommand.java rename to plugins/network-elements/ovs/src/com/cloud/agent/api/OvsFetchInterfaceCommand.java index c27daf0b572..a305d5bb587 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsFetchInterfaceCommand.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsFetchInterfaceCommand.java @@ -15,24 +15,24 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.network.ovs; +package com.cloud.agent.api; import com.cloud.agent.api.Command; public class OvsFetchInterfaceCommand extends Command { - String label; + String label; - @Override - public boolean executeInSequence() { - return true; - } + @Override + public boolean executeInSequence() { + return true; + } - public OvsFetchInterfaceCommand(String label) { - this.label = label; - } + public OvsFetchInterfaceCommand(String label) { + this.label = label; + } - public String getLabel() { - return label; - } + public String getLabel() { + return label; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsSetTagAndFlowAnswer.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetTagAndFlowAnswer.java similarity index 67% rename from plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsSetTagAndFlowAnswer.java rename to plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetTagAndFlowAnswer.java index db40002b466..ee1fe42e6ae 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsSetTagAndFlowAnswer.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetTagAndFlowAnswer.java @@ -14,27 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.network.ovs; +package com.cloud.agent.api; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; public class OvsSetTagAndFlowAnswer extends Answer { - Long vmId; - Long seqno; + Long vmId; + Long seqno; - public OvsSetTagAndFlowAnswer(Command cmd, boolean success, String details) { - super(cmd, success, details); - OvsSetTagAndFlowCommand c = (OvsSetTagAndFlowCommand)cmd; - this.vmId = c.getVmId(); - this.seqno = Long.parseLong(c.getSeqNo()); - } + public OvsSetTagAndFlowAnswer(Command cmd, boolean success, String details) { + super(cmd, success, details); + OvsSetTagAndFlowCommand c = (OvsSetTagAndFlowCommand) cmd; + this.vmId = c.getVmId(); + this.seqno = Long.parseLong(c.getSeqNo()); + } - public Long getVmId() { - return vmId; - } + public Long getVmId() { + return vmId; + } - public Long getSeqNo() { - return seqno; - } + public Long getSeqNo() { + return seqno; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetTagAndFlowCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetTagAndFlowCommand.java new file mode 100644 index 00000000000..28a936a3e06 --- /dev/null +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetTagAndFlowCommand.java @@ -0,0 +1,61 @@ +// 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.agent.api; + +import com.cloud.agent.api.Command; + +public class OvsSetTagAndFlowCommand extends Command { + String vlans; + String vmName; + String seqno; + String tag; + Long vmId; + + @Override + public boolean executeInSequence() { + return true; + } + + public String getSeqNo() { + return seqno; + } + + public String getVlans() { + return vlans; + } + + public String getVmName() { + return vmName; + } + + public Long getVmId() { + return vmId; + } + + public String getTag() { + return tag; + } + + public OvsSetTagAndFlowCommand(String vmName, String tag, String vlans, + String seqno, Long vmId) { + this.vmName = vmName; + this.tag = tag; + this.vlans = vlans; + this.seqno = seqno; + this.vmId = vmId; + } +} diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsSetupBridgeCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetupBridgeCommand.java similarity index 63% rename from plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsSetupBridgeCommand.java rename to plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetupBridgeCommand.java index 9c9924d8c3c..6968a4c890f 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsSetupBridgeCommand.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetupBridgeCommand.java @@ -15,36 +15,35 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.network.ovs; +package com.cloud.agent.api; import com.cloud.agent.api.Command; public class OvsSetupBridgeCommand extends Command { - Integer key; - Long hostId; - Long networkId; + Integer key; + Long hostId; + Long networkId; - @Override - public boolean executeInSequence() { - return true; - } + @Override + public boolean executeInSequence() { + return true; + } - public OvsSetupBridgeCommand(Integer key, Long hostId, Long networkId) { - this.key = key; - this.hostId = hostId; - this.networkId = networkId; - } + public OvsSetupBridgeCommand(Integer key, Long hostId, Long networkId) { + this.key = key; + this.hostId = hostId; + this.networkId = networkId; + } - public Integer getKey() { - return key; - } + public Integer getKey() { + return key; + } - public Long getHostId() { - return hostId; - } - - public Long getNetworkId() { - return networkId; - } + public Long getHostId() { + return hostId; + } + public Long getNetworkId() { + return networkId; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/StartupOvsCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/StartupOvsCommand.java new file mode 100644 index 00000000000..766aec28e58 --- /dev/null +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/StartupOvsCommand.java @@ -0,0 +1,27 @@ +// 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.agent.api; + +import com.cloud.agent.api.StartupCommand; +import com.cloud.host.Host; + +public class StartupOvsCommand extends StartupCommand { + + public StartupOvsCommand() { + super(Host.Type.L2Networking); + } +} diff --git a/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java b/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java index 18b7a90829f..2641d5488e9 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java +++ b/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java @@ -16,111 +16,635 @@ // under the License. package com.cloud.network.element; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Set; import javax.ejb.Local; import javax.inject.Inject; +import javax.naming.ConfigurationException; +import org.apache.log4j.Logger; + +import com.cloud.agent.api.StartupCommand; +import com.cloud.agent.api.StartupOvsCommand; +import com.cloud.agent.api.to.LoadBalancerTO; import com.cloud.deploy.DeployDestination; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceUnavailableException; +import com.cloud.host.Host; +import com.cloud.host.HostVO; import com.cloud.network.Network; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; +import com.cloud.network.NetworkModel; import com.cloud.network.Networks; +import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.PhysicalNetworkServiceProvider; +import com.cloud.network.PublicIpAddress; +import com.cloud.network.dao.NetworkServiceMapDao; +import com.cloud.network.lb.LoadBalancingRule; +import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy; import com.cloud.network.ovs.OvsTunnelManager; +import com.cloud.network.router.VirtualRouter.Role; +import com.cloud.network.router.VpcVirtualNetworkApplianceManager; +import com.cloud.network.rules.LbStickinessMethod; +import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType; +import com.cloud.network.rules.LoadBalancerContainer; +import com.cloud.network.rules.PortForwardingRule; +import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; +import com.cloud.resource.ResourceManager; +import com.cloud.resource.ResourceStateAdapter; +import com.cloud.resource.ServerResource; +import com.cloud.resource.UnableDeleteHostException; +import com.cloud.utils.Pair; import com.cloud.utils.component.AdapterBase; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.vm.DomainRouterVO; import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; import com.cloud.vm.VirtualMachineProfile; +import com.cloud.vm.dao.DomainRouterDao; +import com.google.gson.Gson; -@Local(value = {NetworkElement.class}) -public class OvsElement extends AdapterBase implements NetworkElement { - @Inject - OvsTunnelManager _ovsTunnelMgr; +@Local(value = { NetworkElement.class, ConnectivityProvider.class, + SourceNatServiceProvider.class, StaticNatServiceProvider.class, + PortForwardingServiceProvider.class, IpDeployer.class }) +public class OvsElement extends AdapterBase implements NetworkElement, + OvsElementService, ConnectivityProvider, ResourceStateAdapter, + PortForwardingServiceProvider, LoadBalancingServiceProvider, + StaticNatServiceProvider, IpDeployer { + @Inject + OvsTunnelManager _ovsTunnelMgr; + @Inject + NetworkModel _networkModel; + @Inject + NetworkServiceMapDao _ntwkSrvcDao; + @Inject + ResourceManager _resourceMgr; + @Inject + DomainRouterDao _routerDao; + @Inject + VpcVirtualNetworkApplianceManager _routerMgr; - @Override - public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - return true; + private static final Logger s_logger = Logger.getLogger(OvsElement.class); + private static final Map> capabilities = setCapabilities(); + + @Override + public Map> getCapabilities() { + return capabilities; + } + + @Override + public Provider getProvider() { + return Provider.Ovs; + } + + protected boolean canHandle(Network network, Service service) { + s_logger.debug("Checking if OvsElement can handle service " + + service.getName() + " on network " + network.getDisplayText()); + if (network.getBroadcastDomainType() != BroadcastDomainType.Vswitch) { + return false; + } + + if (!_networkModel.isProviderForNetwork(getProvider(), network.getId())) { + s_logger.debug("OvsElement is not a provider for network " + + network.getDisplayText()); + return false; + } + + if (!_ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), + service, Network.Provider.Ovs)) { + s_logger.debug("OvsElement can't provide the " + service.getName() + + " service on network " + network.getDisplayText()); + return false; + } + + return true; + } + + @Override + public boolean configure(String name, Map params) + throws ConfigurationException { + super.configure(name, params); + _resourceMgr.registerResourceStateAdapter(name, this); + return true; + } + + @Override + public boolean implement(Network network, NetworkOffering offering, + DeployDestination dest, ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { + s_logger.debug("entering OvsElement implement function for network " + + network.getDisplayText() + " (state " + network.getState() + + ")"); + + if (!canHandle(network, Service.Connectivity)) { + return false; + } + return true; + } + + @Override + public boolean prepare(Network network, NicProfile nic, + VirtualMachineProfile vm, + DeployDestination dest, ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { + if (!canHandle(network, Service.Connectivity)) { + return false; + } + + if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) { + return false; + } + + if (nic.getTrafficType() != Networks.TrafficType.Guest) { + return false; + } + + _ovsTunnelMgr.VmCheckAndCreateTunnel(vm, network, dest); + + return true; + } + + @Override + public boolean release(Network network, NicProfile nic, + VirtualMachineProfile vm, + ReservationContext context) throws ConcurrentOperationException, + ResourceUnavailableException { + if (!canHandle(network, Service.Connectivity)) { + return false; + } + if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) { + return false; + } + + if (nic.getTrafficType() != Networks.TrafficType.Guest) { + return false; + } + + _ovsTunnelMgr.CheckAndDestroyTunnel(vm.getVirtualMachine(), network); + return true; + } + + @Override + public boolean shutdown(Network network, ReservationContext context, + boolean cleanup) throws ConcurrentOperationException, + ResourceUnavailableException { + if (!canHandle(network, Service.Connectivity)) { + return false; + } + return true; + } + + @Override + public boolean destroy(Network network, ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException { + if (!canHandle(network, Service.Connectivity)) { + return false; + } + return true; + } + + @Override + public boolean isReady(PhysicalNetworkServiceProvider provider) { + return true; + } + + @Override + public boolean shutdownProviderInstances( + PhysicalNetworkServiceProvider provider, ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException { + return true; + } + + @Override + public boolean canEnableIndividualServices() { + return true; + } + + @Override + public boolean verifyServicesCombination(Set services) { + if (!services.contains(Service.Connectivity)) { + s_logger.warn("Unable to provide services without Connectivity service enabled for this element"); + return false; + } + + return true; + } + + private static Map> setCapabilities() { + Map> capabilities = new HashMap>(); + + // L2 Support : SDN provisioning + capabilities.put(Service.Connectivity, null); + + // L3 Support : Port Forwarding + capabilities.put(Service.PortForwarding, null); + + // L3 support : StaticNat + capabilities.put(Service.StaticNat, null); + + // L3 support : Load Balancer + // Set capabilities for LB service + Map lbCapabilities = new HashMap(); + lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn,source"); + lbCapabilities.put(Capability.SupportedLBIsolation, "dedicated"); + lbCapabilities.put(Capability.SupportedProtocols, "tcp, udp"); + lbCapabilities.put(Capability.SupportedStickinessMethods, getHAProxyStickinessCapability()); + lbCapabilities.put(Capability.LbSchemes, LoadBalancerContainer.Scheme.Public.toString()); + + capabilities.put(Service.Lb, lbCapabilities); + + return capabilities; + } + + public static String getHAProxyStickinessCapability() { + LbStickinessMethod method; + List methodList = new ArrayList(1); + + method = new LbStickinessMethod(StickinessMethodType.LBCookieBased, "This is loadbalancer cookie based stickiness method."); + method.addParam("cookie-name", false, "Cookie name passed in http header by the LB to the client.", false); + method.addParam("mode", false, + "Valid values: insert, rewrite, prefix. Default value: insert. In the insert mode cookie will be created" + + " by the LB. In other modes, cookie will be created by the server and LB modifies it.", false); + method.addParam( + "nocache", + false, + "This option is recommended in conjunction with the insert mode when there is a cache between the client" + + " and HAProxy, as it ensures that a cacheable response will be tagged non-cacheable if a cookie needs " + + "to be inserted. This is important because if all persistence cookies are added on a cacheable home page" + + " for instance, then all customers will then fetch the page from an outer cache and will all share the " + + "same persistence cookie, leading to one server receiving much more traffic than others. See also the " + + "insert and postonly options. ", + true); + method.addParam( + "indirect", + false, + "When this option is specified in insert mode, cookies will only be added when the server was not reached" + + " after a direct access, which means that only when a server is elected after applying a load-balancing algorithm," + + " or after a redispatch, then the cookie will be inserted. If the client has all the required information" + + " to connect to the same server next time, no further cookie will be inserted. In all cases, when the " + + "indirect option is used in insert mode, the cookie is always removed from the requests transmitted to " + + "the server. The persistence mechanism then becomes totally transparent from the application point of view.", + true); + method.addParam( + "postonly", + false, + "This option ensures that cookie insertion will only be performed on responses to POST requests. It is an" + + " alternative to the nocache option, because POST responses are not cacheable, so this ensures that the " + + "persistence cookie will never get cached.Since most sites do not need any sort of persistence before the" + + " first POST which generally is a login request, this is a very efficient method to optimize caching " + + "without risking to find a persistence cookie in the cache. See also the insert and nocache options.", + true); + method.addParam( + "domain", + false, + "This option allows to specify the domain at which a cookie is inserted. It requires exactly one parameter:" + + " a valid domain name. If the domain begins with a dot, the browser is allowed to use it for any host " + + "ending with that name. It is also possible to specify several domain names by invoking this option multiple" + + " times. Some browsers might have small limits on the number of domains, so be careful when doing that. " + + "For the record, sending 10 domains to MSIE 6 or Firefox 2 works as expected.", + false); + methodList.add(method); + + method = new LbStickinessMethod(StickinessMethodType.AppCookieBased, + "This is App session based sticky method. Define session stickiness on an existing application cookie. " + + "It can be used only for a specific http traffic"); + method.addParam("cookie-name", false, "This is the name of the cookie used by the application and which LB will " + + "have to learn for each new session. Default value: Auto geneared based on ip", false); + method.addParam("length", false, "This is the max number of characters that will be memorized and checked in " + + "each cookie value. Default value:52", false); + method.addParam( + "holdtime", + false, + "This is the time after which the cookie will be removed from memory if unused. The value should be in " + + "the format Example : 20s or 30m or 4h or 5d . only seconds(s), minutes(m) hours(h) and days(d) are valid," + + " cannot use th combinations like 20h30m. Default value:3h ", + false); + method.addParam( + "request-learn", + false, + "If this option is specified, then haproxy will be able to learn the cookie found in the request in case the server does not specify any in response. This is typically what happens with PHPSESSID cookies, or when haproxy's session expires before the application's session and the correct server is selected. It is recommended to specify this option to improve reliability", + true); + method.addParam( + "prefix", + false, + "When this option is specified, haproxy will match on the cookie prefix (or URL parameter prefix). " + + "The appsession value is the data following this prefix. Example : appsession ASPSESSIONID len 64 timeout 3h prefix This will match the cookie ASPSESSIONIDXXXX=XXXXX, the appsession value will be XXXX=XXXXX.", + true); + method.addParam( + "mode", + false, + "This option allows to change the URL parser mode. 2 modes are currently supported : - path-parameters " + + ": The parser looks for the appsession in the path parameters part (each parameter is separated by a semi-colon), " + + "which is convenient for JSESSIONID for example.This is the default mode if the option is not set. - query-string :" + + " In this mode, the parser will look for the appsession in the query string.", + false); + methodList.add(method); + + method = new LbStickinessMethod(StickinessMethodType.SourceBased, "This is source based Stickiness method, " + + "it can be used for any type of protocol."); + method.addParam("tablesize", false, "Size of table to store source ip addresses. example: tablesize=200k or 300m" + + " or 400g. Default value:200k", false); + method.addParam("expire", false, "Entry in source ip table will expire after expire duration. units can be s,m,h,d ." + + " example: expire=30m 20s 50h 4d. Default value:3h", false); + methodList.add(method); + + Gson gson = new Gson(); + String capability = gson.toJson(methodList); + return capability; } - @Override - public Map> getCapabilities() { - return null; - } + @Override + public List> getCommands() { + List> cmdList = new ArrayList>(); + return cmdList; + } - @Override - public Provider getProvider() { - return null; - } + @Override + public HostVO createHostVOForConnectedAgent(HostVO host, + StartupCommand[] cmd) { + return null; + } - @Override - public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException { - //Consider actually implementing the network here - return true; - } + @Override + public HostVO createHostVOForDirectConnectAgent(HostVO host, + StartupCommand[] startup, ServerResource resource, + Map details, List hostTags) { + if (!(startup[0] instanceof StartupOvsCommand)) { + return null; + } + host.setType(Host.Type.L2Networking); + return host; + } - @Override - public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) { - return true; - } + @Override + public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, + boolean isForceDeleteStorage) throws UnableDeleteHostException { + if (!(host.getType() == Host.Type.L2Networking)) { + return null; + } + return new DeleteHostAnswer(true); + } - if (nic.getTrafficType() != Networks.TrafficType.Guest) { - return true; - } + @Override + public IpDeployer getIpDeployer(Network network) { + return this; + } - _ovsTunnelMgr.VmCheckAndCreateTunnel(vm, network, dest); - //_ovsTunnelMgr.applyDefaultFlow(vm.getVirtualMachine(), dest); + @Override + public boolean applyIps(Network network, + List ipAddress, Set services) + throws ResourceUnavailableException { + boolean canHandle = true; + for (Service service : services) { + // check if Ovs can handle services except SourceNat & Firewall + if (!canHandle(network, service) && service != Service.SourceNat && service != Service.Firewall) { + canHandle = false; + break; + } + } + if (canHandle) { + List routers = _routerDao.listByNetworkAndRole( + network.getId(), Role.VIRTUAL_ROUTER); + if (routers == null || routers.isEmpty()) { + s_logger.debug("Virtual router element doesn't need to associate ip addresses on the backend; virtual " + + "router doesn't exist in the network " + + network.getId()); + return true; + } - return true; - } + return _routerMgr.associatePublicIP(network, ipAddress, routers); + } else { + return false; + } + } - @Override - public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) { - return true; - } + @Override + public boolean applyStaticNats(Network network, List rules) + throws ResourceUnavailableException { + if (!canHandle(network, Service.StaticNat)) { + return false; + } + List routers = _routerDao.listByNetworkAndRole( + network.getId(), Role.VIRTUAL_ROUTER); + if (routers == null || routers.isEmpty()) { + s_logger.debug("Ovs element doesn't need to apply static nat on the backend; virtual " + + "router doesn't exist in the network " + network.getId()); + return true; + } - if (nic.getTrafficType() != Networks.TrafficType.Guest) { - return true; - } + return _routerMgr.applyStaticNats(network, rules, routers); + } - _ovsTunnelMgr.CheckAndDestroyTunnel(vm.getVirtualMachine(), network); - return true; - } + @Override + public boolean applyPFRules(Network network, List rules) + throws ResourceUnavailableException { + if (!canHandle(network, Service.PortForwarding)) { + return false; + } + List routers = _routerDao.listByNetworkAndRole( + network.getId(), Role.VIRTUAL_ROUTER); + if (routers == null || routers.isEmpty()) { + s_logger.debug("Ovs element doesn't need to apply firewall rules on the backend; virtual " + + "router doesn't exist in the network " + network.getId()); + return true; + } - @Override - public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { - return true; - } + return _routerMgr.applyFirewallRules(network, rules, routers); + } - @Override - public boolean isReady(PhysicalNetworkServiceProvider provider) { - return true; - } + @Override + public boolean applyLBRules(Network network, List rules) + throws ResourceUnavailableException { + if (canHandle(network, Service.Lb)) { + if (!canHandleLbRules(rules)) { + return false; + } - @Override - public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - return true; - } + List routers = _routerDao.listByNetworkAndRole( + network.getId(), Role.VIRTUAL_ROUTER); + if (routers == null || routers.isEmpty()) { + s_logger.debug("Virtual router elemnt doesn't need to apply firewall rules on the backend; virtual " + + "router doesn't exist in the network " + + network.getId()); + return true; + } - @Override - public boolean canEnableIndividualServices() { - return false; - } + if (!_routerMgr.applyLoadBalancingRules(network, rules, routers)) { + throw new CloudRuntimeException( + "Failed to apply load balancing rules in network " + + network.getId()); + } else { + return true; + } + } else { + return false; + } + } - @Override - public boolean verifyServicesCombination(Set services) { - return true; - } + @Override + public boolean validateLBRule(Network network, LoadBalancingRule rule) { + List rules = new ArrayList(); + rules.add(rule); + if (canHandle(network, Service.Lb) && canHandleLbRules(rules)) { + List routers = _routerDao.listByNetworkAndRole( + network.getId(), Role.VIRTUAL_ROUTER); + if (routers == null || routers.isEmpty()) { + return true; + } + return validateHAProxyLBRule(rule); + } + return true; + } + + @Override + public List updateHealthChecks(Network network, + List lbrules) { + // TODO Auto-generated method stub + return null; + } + + private boolean canHandleLbRules(List rules) { + Map lbCaps = this.getCapabilities().get(Service.Lb); + if (!lbCaps.isEmpty()) { + String schemeCaps = lbCaps.get(Capability.LbSchemes); + if (schemeCaps != null) { + for (LoadBalancingRule rule : rules) { + if (!schemeCaps.contains(rule.getScheme().toString())) { + s_logger.debug("Scheme " + rules.get(0).getScheme() + + " is not supported by the provider " + + this.getName()); + return false; + } + } + } + } + return true; + } + + public static boolean validateHAProxyLBRule(LoadBalancingRule rule) { + String timeEndChar = "dhms"; + + for (LbStickinessPolicy stickinessPolicy : rule.getStickinessPolicies()) { + List> paramsList = stickinessPolicy + .getParams(); + + if (StickinessMethodType.LBCookieBased.getName().equalsIgnoreCase( + stickinessPolicy.getMethodName())) { + + } else if (StickinessMethodType.SourceBased.getName() + .equalsIgnoreCase(stickinessPolicy.getMethodName())) { + String tablesize = "200k"; // optional + String expire = "30m"; // optional + + /* overwrite default values with the stick parameters */ + for (Pair paramKV : paramsList) { + String key = paramKV.first(); + String value = paramKV.second(); + if ("tablesize".equalsIgnoreCase(key)) + tablesize = value; + if ("expire".equalsIgnoreCase(key)) + expire = value; + } + if ((expire != null) + && !containsOnlyNumbers(expire, timeEndChar)) { + throw new InvalidParameterValueException( + "Failed LB in validation rule id: " + rule.getId() + + " Cause: expire is not in timeformat: " + + expire); + } + if ((tablesize != null) + && !containsOnlyNumbers(tablesize, "kmg")) { + throw new InvalidParameterValueException( + "Failed LB in validation rule id: " + + rule.getId() + + " Cause: tablesize is not in size format: " + + tablesize); + + } + } else if (StickinessMethodType.AppCookieBased.getName() + .equalsIgnoreCase(stickinessPolicy.getMethodName())) { + /* + * FORMAT : appsession len timeout + * [request-learn] [prefix] [mode + * ] + */ + /* example: appsession JSESSIONID len 52 timeout 3h */ + String cookieName = null; // optional + String length = null; // optional + String holdTime = null; // optional + + for (Pair paramKV : paramsList) { + String key = paramKV.first(); + String value = paramKV.second(); + if ("cookie-name".equalsIgnoreCase(key)) + cookieName = value; + if ("length".equalsIgnoreCase(key)) + length = value; + if ("holdtime".equalsIgnoreCase(key)) + holdTime = value; + } + + if ((length != null) && (!containsOnlyNumbers(length, null))) { + throw new InvalidParameterValueException( + "Failed LB in validation rule id: " + rule.getId() + + " Cause: length is not a number: " + + length); + } + if ((holdTime != null) + && (!containsOnlyNumbers(holdTime, timeEndChar) && !containsOnlyNumbers( + holdTime, null))) { + throw new InvalidParameterValueException( + "Failed LB in validation rule id: " + rule.getId() + + " Cause: holdtime is not in timeformat: " + + holdTime); + } + } + } + return true; + } + + /* + * This function detects numbers like 12 ,32h ,42m .. etc,. 1) plain number + * like 12 2) time or tablesize like 12h, 34m, 45k, 54m , here last + * character is non-digit but from known characters . + */ + private static boolean containsOnlyNumbers(String str, String endChar) { + if (str == null) + return false; + + String number = str; + if (endChar != null) { + boolean matchedEndChar = false; + if (str.length() < 2) + return false; // atleast one numeric and one char. example: + // 3h + char strEnd = str.toCharArray()[str.length() - 1]; + for (char c : endChar.toCharArray()) { + if (strEnd == c) { + number = str.substring(0, str.length() - 1); + matchedEndChar = true; + break; + } + } + if (!matchedEndChar) + return false; + } + try { + int i = Integer.parseInt(number); + } catch (NumberFormatException e) { + return false; + } + return true; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElementService.java b/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElementService.java new file mode 100644 index 00000000000..c382e627ec6 --- /dev/null +++ b/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElementService.java @@ -0,0 +1,7 @@ +package com.cloud.network.element; + +import com.cloud.utils.component.PluggableService; + +public interface OvsElementService extends PluggableService { + +} diff --git a/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java b/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java index 06909777807..7a671a0359f 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java +++ b/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java @@ -20,8 +20,8 @@ import javax.ejb.Local; import javax.inject.Inject; import org.apache.log4j.Logger; - import org.apache.cloudstack.context.CallContext; +import org.springframework.stereotype.Component; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; @@ -30,86 +30,193 @@ import com.cloud.deploy.DeploymentPlan; import com.cloud.event.ActionEventUtils; import com.cloud.event.EventTypes; import com.cloud.event.EventVO; +import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientVirtualNetworkCapcityException; import com.cloud.network.Network; import com.cloud.network.Network.GuestType; +import com.cloud.network.Network.Service; import com.cloud.network.Network.State; +import com.cloud.network.NetworkProfile; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.PhysicalNetwork; import com.cloud.network.PhysicalNetwork.IsolationMethod; import com.cloud.network.dao.NetworkVO; +import com.cloud.network.dao.PhysicalNetworkVO; import com.cloud.network.ovs.OvsTunnelManager; import com.cloud.offering.NetworkOffering; +import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; import com.cloud.user.Account; +import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineProfile; +@Component @Local(value = NetworkGuru.class) public class OvsGuestNetworkGuru extends GuestNetworkGuru { - private static final Logger s_logger = Logger.getLogger(OvsGuestNetworkGuru.class); + private static final Logger s_logger = Logger + .getLogger(OvsGuestNetworkGuru.class); - @Inject - OvsTunnelManager _ovsTunnelMgr; + @Inject + OvsTunnelManager _ovsTunnelMgr; + @Inject + NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao; - OvsGuestNetworkGuru() { - super(); - _isolationMethods = new IsolationMethod[] {IsolationMethod.GRE, IsolationMethod.L3, IsolationMethod.VLAN}; - } + OvsGuestNetworkGuru() { + super(); + _isolationMethods = new IsolationMethod[] { IsolationMethod.GRE, + IsolationMethod.L3, IsolationMethod.VLAN }; + } - @Override - protected boolean canHandle(NetworkOffering offering, final NetworkType networkType, final PhysicalNetwork physicalNetwork) { - // This guru handles only Guest Isolated network that supports Source - // nat service - if (networkType == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) && offering.getGuestType() == Network.GuestType.Isolated && - isMyIsolationMethod(physicalNetwork)) { - return true; - } else { - s_logger.trace("We only take care of Guest networks of type " + GuestType.Isolated + " in zone of type " + NetworkType.Advanced); - return false; - } - } + @Override + protected boolean canHandle(NetworkOffering offering, + final NetworkType networkType, final PhysicalNetwork physicalNetwork) { + // This guru handles only Guest Isolated network that supports Source + // nat service + if (networkType == NetworkType.Advanced + && isMyTrafficType(offering.getTrafficType()) + && offering.getGuestType() == Network.GuestType.Isolated + && isMyIsolationMethod(physicalNetwork) + && _ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering( + offering.getId(), Service.Connectivity)) { + return true; + } else { + s_logger.trace("We only take care of Guest networks of type " + + GuestType.Isolated + " in zone of type " + + NetworkType.Advanced); + return false; + } + } - @Override - public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, Account owner) { + @Override + public Network design(NetworkOffering offering, DeploymentPlan plan, + Network userSpecified, Account owner) { - if (!_ovsTunnelMgr.isOvsTunnelEnabled()) { - return null; - } + PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan + .getPhysicalNetworkId()); + DataCenter dc = _dcDao.findById(plan.getDataCenterId()); + if (!canHandle(offering, dc.getNetworkType(), physnet)) { + s_logger.debug("Refusing to design this network"); + return null; + } + NetworkVO config = (NetworkVO) super.design(offering, plan, + userSpecified, owner); + if (config == null) { + return null; + } - NetworkVO config = (NetworkVO)super.design(offering, plan, userSpecified, owner); - if (config == null) { - return null; - } + config.setBroadcastDomainType(BroadcastDomainType.Vswitch); - config.setBroadcastDomainType(BroadcastDomainType.Vswitch); + return config; + } - return config; - } + @Override + public Network implement(Network network, NetworkOffering offering, + DeployDestination dest, ReservationContext context) + throws InsufficientVirtualNetworkCapcityException { + assert (network.getState() == State.Implementing) : "Why are we implementing " + + network; - @Override - protected void allocateVnet(Network network, NetworkVO implemented, long dcId, long physicalNetworkId, String reservationId) - throws InsufficientVirtualNetworkCapcityException { - if (network.getBroadcastUri() == null) { - String vnet = _dcDao.allocateVnet(dcId, physicalNetworkId, network.getAccountId(), reservationId, UseSystemGuestVlans.valueIn(network.getAccountId())); - if (vnet == null) { - throw new InsufficientVirtualNetworkCapcityException("Unable to allocate vnet as a part of network " + network + " implement ", DataCenter.class, dcId); - } - implemented.setBroadcastUri(BroadcastDomainType.Vswitch.toUri(vnet)); - ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), network.getAccountId(), EventVO.LEVEL_INFO, - EventTypes.EVENT_ZONE_VLAN_ASSIGN, "Assigned Zone Vlan: " + vnet + " Network Id: " + network.getId(), 0); - } else { - implemented.setBroadcastUri(network.getBroadcastUri()); - } - } + long dcId = dest.getDataCenter().getId(); + NetworkType nwType = dest.getDataCenter().getNetworkType(); + // get physical network id + Long physicalNetworkId = network.getPhysicalNetworkId(); + // physical network id can be null in Guest Network in Basic zone, so + // locate the physical network + if (physicalNetworkId == null) { + physicalNetworkId = _networkModel.findPhysicalNetworkId(dcId, + offering.getTags(), offering.getTrafficType()); + } + PhysicalNetworkVO physnet = _physicalNetworkDao + .findById(physicalNetworkId); - @Override - public Network implement(Network config, NetworkOffering offering, DeployDestination dest, ReservationContext context) - throws InsufficientVirtualNetworkCapcityException { - assert (config.getState() == State.Implementing) : "Why are we implementing " + config; - if (!_ovsTunnelMgr.isOvsTunnelEnabled()) { - return null; - } - NetworkVO implemented = (NetworkVO)super.implement(config, offering, dest, context); - return implemented; - } + if (!canHandle(offering, nwType, physnet)) { + s_logger.debug("Refusing to design this network"); + return null; + } + NetworkVO implemented = (NetworkVO) super.implement(network, offering, + dest, context); + if (network.getGateway() != null) { + implemented.setGateway(network.getGateway()); + } + + if (network.getCidr() != null) { + implemented.setCidr(network.getCidr()); + } + String name = network.getName(); + if (name == null || name.isEmpty()) { + name = ((NetworkVO) network).getUuid(); + } + + // do we need to create switch right now? + + implemented.setBroadcastDomainType(BroadcastDomainType.Vswitch); + + return implemented; + } + + @Override + public void reserve(NicProfile nic, Network network, + VirtualMachineProfile vm, + DeployDestination dest, ReservationContext context) + throws InsufficientVirtualNetworkCapcityException, + InsufficientAddressCapacityException { + // TODO Auto-generated method stub + super.reserve(nic, network, vm, dest, context); + } + + @Override + public boolean release(NicProfile nic, + VirtualMachineProfile vm, + String reservationId) { + // TODO Auto-generated method stub + return super.release(nic, vm, reservationId); + } + + @Override + public void shutdown(NetworkProfile profile, NetworkOffering offering) { + NetworkVO networkObject = _networkDao.findById(profile.getId()); + if (networkObject.getBroadcastDomainType() != BroadcastDomainType.Vswitch + || networkObject.getBroadcastUri() == null) { + s_logger.warn("BroadcastUri is empty or incorrect for guestnetwork " + + networkObject.getDisplayText()); + return; + } + + super.shutdown(profile, offering); + } + + @Override + public boolean trash(Network network, NetworkOffering offering) { + return super.trash(network, offering); + } + + @Override + protected void allocateVnet(Network network, NetworkVO implemented, + long dcId, long physicalNetworkId, String reservationId) + throws InsufficientVirtualNetworkCapcityException { + if (network.getBroadcastUri() == null) { + String vnet = _dcDao.allocateVnet(dcId, physicalNetworkId, + network.getAccountId(), reservationId, + UseSystemGuestVlans.valueIn(network.getAccountId())); + if (vnet == null) { + throw new InsufficientVirtualNetworkCapcityException( + "Unable to allocate vnet as a part of network " + + network + " implement ", DataCenter.class, + dcId); + } + implemented + .setBroadcastUri(BroadcastDomainType.Vswitch.toUri(vnet)); + ActionEventUtils.onCompletedActionEvent( + CallContext.current().getCallingUserId(), + network.getAccountId(), + EventVO.LEVEL_INFO, + EventTypes.EVENT_ZONE_VLAN_ASSIGN, + "Assigned Zone Vlan: " + vnet + " Network Id: " + + network.getId(), 0); + } else { + implemented.setBroadcastUri(network.getBroadcastUri()); + } + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsCreateGreTunnelAnswer.java b/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsCreateGreTunnelAnswer.java deleted file mode 100644 index 7eac7b0411c..00000000000 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsCreateGreTunnelAnswer.java +++ /dev/null @@ -1,79 +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 com.cloud.network.ovs; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; - -public class OvsCreateGreTunnelAnswer extends Answer { - String hostIp; - String remoteIp; - String bridge; - String key; - long from; - long to; - int port; - - public OvsCreateGreTunnelAnswer(Command cmd, boolean success, String details) { - super(cmd, success, details); - } - - public OvsCreateGreTunnelAnswer(Command cmd, boolean success, String details, String hostIp, String bridge) { - super(cmd, success, details); - OvsCreateGreTunnelCommand c = (OvsCreateGreTunnelCommand)cmd; - this.hostIp = hostIp; - this.bridge = bridge; - this.remoteIp = c.getRemoteIp(); - this.key = c.getKey(); - this.port = -1; - this.from = c.getFrom(); - this.to = c.getTo(); - } - - public OvsCreateGreTunnelAnswer(Command cmd, boolean success, String details, String hostIp, String bridge, int port) { - this(cmd, success, details, hostIp, bridge); - this.port = port; - } - - public String getHostIp() { - return hostIp; - } - - public String getRemoteIp() { - return remoteIp; - } - - public String getBridge() { - return bridge; - } - - public String getKey() { - return key; - } - - public long getFrom() { - return from; - } - - public long getTo() { - return to; - } - - public int getPort() { - return port; - } -} diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsCreateTunnelAnswer.java b/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsCreateTunnelAnswer.java deleted file mode 100644 index f90dc44c6df..00000000000 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsCreateTunnelAnswer.java +++ /dev/null @@ -1,83 +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 com.cloud.network.ovs; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; - -public class OvsCreateTunnelAnswer extends Answer { - Long from; - Long to; - long networkId; - String inPortName; - - //for debug info - String fromIp; - String toIp; - int key; - String bridge; - - public OvsCreateTunnelAnswer(Command cmd, boolean success, String details, String bridge) { - super(cmd, success, details); - OvsCreateTunnelCommand c = (OvsCreateTunnelCommand)cmd; - from = c.getFrom(); - to = c.getTo(); - networkId = c.getNetworkId(); - inPortName = "[]"; - fromIp = c.getFromIp(); - toIp = c.getRemoteIp(); - key = c.getKey(); - this.bridge = bridge; - } - - public OvsCreateTunnelAnswer(Command cmd, boolean success, String details, String inPortName, String bridge) { - this(cmd, success, details, bridge); - this.inPortName = inPortName; - } - - public Long getFrom() { - return from; - } - - public Long getTo() { - return to; - } - - public long getNetworkId() { - return networkId; - } - - public String getInPortName() { - return inPortName; - } - - public String getFromIp() { - return fromIp; - } - - public String getToIp() { - return toIp; - } - - public int getKey() { - return key; - } - - public String getBridge() { - return bridge; - } -} diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsCreateTunnelCommand.java b/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsCreateTunnelCommand.java deleted file mode 100644 index 1ececa0b9dd..00000000000 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsCreateTunnelCommand.java +++ /dev/null @@ -1,69 +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 com.cloud.network.ovs; - -import com.cloud.agent.api.Command; - -public class OvsCreateTunnelCommand extends Command { - Integer key; - String remoteIp; - Long from; - Long to; - long networkId; - - // for debug info - String fromIp; - - @Override - public boolean executeInSequence() { - return true; - } - - public OvsCreateTunnelCommand(String remoteIp, Integer key, Long from, Long to, long networkId, String fromIp) { - this.remoteIp = remoteIp; - this.key = key; - this.from = from; - this.to = to; - this.networkId = networkId; - this.fromIp = fromIp; - } - - public Integer getKey() { - return key; - } - - public String getRemoteIp() { - return remoteIp; - } - - public Long getFrom() { - return from; - } - - public Long getTo() { - return to; - } - - public long getNetworkId() { - return networkId; - } - - public String getFromIp() { - return fromIp; - } - -} diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsTunnelManagerImpl.java b/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsTunnelManagerImpl.java index 10815a40c22..553d645bd0d 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsTunnelManagerImpl.java +++ b/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsTunnelManagerImpl.java @@ -29,12 +29,18 @@ import javax.persistence.EntityExistsException; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; - import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; +import com.cloud.agent.api.OvsCreateTunnelAnswer; +import com.cloud.agent.api.OvsCreateTunnelCommand; +import com.cloud.agent.api.OvsDestroyBridgeCommand; +import com.cloud.agent.api.OvsDestroyTunnelCommand; +import com.cloud.agent.api.OvsFetchInterfaceAnswer; +import com.cloud.agent.api.OvsFetchInterfaceCommand; +import com.cloud.agent.api.OvsSetupBridgeCommand; import com.cloud.agent.manager.Commands; import com.cloud.configuration.Config; import com.cloud.deploy.DeployDestination; @@ -72,41 +78,75 @@ import com.cloud.vm.dao.UserVmDao; public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManager { public static final Logger s_logger = Logger.getLogger(OvsTunnelManagerImpl.class.getName()); - boolean _isEnabled; - ScheduledExecutorService _executorPool; - ScheduledExecutorService _cleanupExecutor; + // boolean _isEnabled; + ScheduledExecutorService _executorPool; + ScheduledExecutorService _cleanupExecutor; - @Inject - ConfigurationDao _configDao; - @Inject - NicDao _nicDao; - @Inject - HostDao _hostDao; - @Inject - PhysicalNetworkTrafficTypeDao _physNetTTDao; - @Inject - UserVmDao _userVmDao; - @Inject - DomainRouterDao _routerDao; - @Inject - OvsTunnelNetworkDao _tunnelNetworkDao; - @Inject - OvsTunnelInterfaceDao _tunnelInterfaceDao; - @Inject - AgentManager _agentMgr; + @Inject + ConfigurationDao _configDao; + @Inject + NicDao _nicDao; + @Inject + HostDao _hostDao; + @Inject + PhysicalNetworkTrafficTypeDao _physNetTTDao; + @Inject + UserVmDao _userVmDao; + @Inject + DomainRouterDao _routerDao; + @Inject + OvsTunnelNetworkDao _tunnelNetworkDao; + @Inject + OvsTunnelInterfaceDao _tunnelInterfaceDao; + @Inject + AgentManager _agentMgr; - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _isEnabled = Boolean.parseBoolean(_configDao.getValue(Config.OvsTunnelNetwork.key())); - - if (_isEnabled) { - _executorPool = Executors.newScheduledThreadPool(10, new NamedThreadFactory("OVS")); - _cleanupExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("OVS-Cleanup")); - } + @Override + public boolean configure(String name, Map params) + throws ConfigurationException { + _executorPool = Executors.newScheduledThreadPool(10, new NamedThreadFactory("OVS")); + _cleanupExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("OVS-Cleanup")); return true; } + @DB + protected OvsTunnelInterfaceVO createInterfaceRecord(String ip, + String netmask, String mac, long hostId, String label) { + OvsTunnelInterfaceVO ti = null; + try { + ti = new OvsTunnelInterfaceVO(ip, netmask, mac, hostId, label); + // TODO: Is locking really necessary here? + OvsTunnelInterfaceVO lock = _tunnelInterfaceDao + .acquireInLockTable(Long.valueOf(1)); + if (lock == null) { + s_logger.warn("Cannot lock table ovs_tunnel_account"); + return null; + } + _tunnelInterfaceDao.persist(ti); + _tunnelInterfaceDao.releaseFromLockTable(lock.getId()); + } catch (EntityExistsException e) { + s_logger.debug("A record for the interface for network " + label + + " on host id " + hostId + " already exists"); + } + return ti; + } + + private String handleFetchInterfaceAnswer(Answer[] answers, Long hostId) { + OvsFetchInterfaceAnswer ans = (OvsFetchInterfaceAnswer) answers[0]; + if (ans.getResult()) { + if (ans.getIp() != null && !("".equals(ans.getIp()))) { + OvsTunnelInterfaceVO ti = createInterfaceRecord(ans.getIp(), + ans.getNetmask(), ans.getMac(), hostId, ans.getLabel()); + return ti.getIp(); + } + } + // Fetch interface failed! + s_logger.warn("Unable to fetch the IP address for the GRE tunnel endpoint" + + ans.getDetails()); + return null; + } + @DB protected OvsTunnelNetworkVO createTunnelRecord(long from, long to, long networkId, int key) { OvsTunnelNetworkVO ta = null; @@ -125,37 +165,6 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage return ta; } - @DB - protected OvsTunnelInterfaceVO createInterfaceRecord(String ip, String netmask, String mac, long hostId, String label) { - OvsTunnelInterfaceVO ti = null; - try { - ti = new OvsTunnelInterfaceVO(ip, netmask, mac, hostId, label); - //TODO: Is locking really necessary here? - OvsTunnelInterfaceVO lock = _tunnelInterfaceDao.acquireInLockTable(Long.valueOf(1)); - if (lock == null) { - s_logger.warn("Cannot lock table ovs_tunnel_account"); - return null; - } - _tunnelInterfaceDao.persist(ti); - _tunnelInterfaceDao.releaseFromLockTable(lock.getId()); - } catch (EntityExistsException e) { - s_logger.debug("A record for the interface for network " + label + " on host id " + hostId + " already exists"); - } - return ti; - } - - private String handleFetchInterfaceAnswer(Answer[] answers, Long hostId) { - OvsFetchInterfaceAnswer ans = (OvsFetchInterfaceAnswer)answers[0]; - if (ans.getResult()) { - if (ans.getIp() != null && !("".equals(ans.getIp()))) { - OvsTunnelInterfaceVO ti = createInterfaceRecord(ans.getIp(), ans.getNetmask(), ans.getMac(), hostId, ans.getLabel()); - return ti.getIp(); - } - } - // Fetch interface failed! - s_logger.warn("Unable to fetch the IP address for the GRE tunnel endpoint" + ans.getDetails()); - return null; - } private void handleCreateTunnelAnswer(Answer[] answers) { OvsCreateTunnelAnswer r = (OvsCreateTunnelAnswer)answers[0]; @@ -167,47 +176,67 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage long networkId = r.getNetworkId(); OvsTunnelNetworkVO tunnel = _tunnelNetworkDao.getByFromToNetwork(from, to, networkId); if (tunnel == null) { - throw new CloudRuntimeException(String.format("Unable find tunnelNetwork record" + "(from=%1$s,to=%2$s, account=%3$s", from, to, networkId)); - } - if (!r.getResult()) { - tunnel.setState("FAILED"); - s_logger.warn("Create GRE tunnel failed due to " + r.getDetails() + s); - } else { - tunnel.setState("SUCCESS"); - tunnel.setPortName(r.getInPortName()); - s_logger.warn("Create GRE tunnel " + r.getDetails() + s); - } - _tunnelNetworkDao.update(tunnel.getId(), tunnel); - } + throw new CloudRuntimeException( + String.format("Unable find tunnelNetwork record" + + "(from=%1$s,to=%2$s, account=%3$s", + from, to, networkId)); + } + if (!r.getResult()) { + tunnel.setState("FAILED"); + s_logger.warn("Create GRE tunnel failed due to " + r.getDetails() + + s); + } else { + tunnel.setState("SUCCESS"); + tunnel.setPortName(r.getInPortName()); + s_logger.warn("Create GRE tunnel " + r.getDetails() + s); + } + _tunnelNetworkDao.update(tunnel.getId(), tunnel); + } - private String getGreEndpointIP(Host host, Network nw) throws AgentUnavailableException, OperationTimedoutException { - String endpointIp = null; - // Fetch fefault name for network label from configuration - String physNetLabel = _configDao.getValue(Config.OvsTunnelNetworkDefaultLabel.key()); + private String getGreEndpointIP(Host host, Network nw) + throws AgentUnavailableException, OperationTimedoutException { + String endpointIp = null; + // Fetch fefault name for network label from configuration + String physNetLabel = _configDao.getValue(Config.OvsTunnelNetworkDefaultLabel.key()); Long physNetId = nw.getPhysicalNetworkId(); - PhysicalNetworkTrafficType physNetTT = _physNetTTDao.findBy(physNetId, TrafficType.Guest); + PhysicalNetworkTrafficType physNetTT = + _physNetTTDao.findBy(physNetId, TrafficType.Guest); HypervisorType hvType = host.getHypervisorType(); + String label = null; switch (hvType) { - case XenServer: - String label = physNetTT.getXenNetworkLabel(); - if ((label != null) && (!label.equals(""))) { - physNetLabel = label; - } - break; - default: - throw new CloudRuntimeException("Hypervisor " + hvType.toString() + " unsupported by OVS Tunnel Manager"); + case XenServer: + label = physNetTT.getXenNetworkLabel(); + if ((label!=null) && (!label.equals(""))) { + physNetLabel = label; + } + break; + case KVM: + label = physNetTT.getKvmNetworkLabel(); + if ((label != null) && (!label.equals(""))) { + physNetLabel = label; + } + break; + default: + throw new CloudRuntimeException("Hypervisor " + + hvType.toString() + + " unsupported by OVS Tunnel Manager"); } // Try to fetch GRE endpoint IP address for cloud db // If not found, then find it on the hypervisor - OvsTunnelInterfaceVO tunnelIface = _tunnelInterfaceDao.getByHostAndLabel(host.getId(), physNetLabel); + OvsTunnelInterfaceVO tunnelIface = + _tunnelInterfaceDao.getByHostAndLabel(host.getId(), + physNetLabel); if (tunnelIface == null) { //Now find and fetch configuration for physical interface - //for network with label on target host - Commands fetchIfaceCmds = new Commands(new OvsFetchInterfaceCommand(physNetLabel)); - s_logger.debug("Ask host " + host.getId() + " to retrieve interface for phy net with label:" + physNetLabel); - Answer[] fetchIfaceAnswers = _agentMgr.send(host.getId(), fetchIfaceCmds); + //for network with label on target host + Commands fetchIfaceCmds = + new Commands(new OvsFetchInterfaceCommand(physNetLabel)); + s_logger.debug("Ask host " + host.getId() + + " to retrieve interface for phy net with label:" + + physNetLabel); + Answer[] fetchIfaceAnswers = _agentMgr.send(host.getId(), fetchIfaceCmds); //And finally save it for future use endpointIp = handleFetchInterfaceAnswer(fetchIfaceAnswers, host.getId()); } else { @@ -216,51 +245,56 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage return endpointIp; } - private int getGreKey(Network network) { - int key = 0; - try { - //The GRE key is actually in the host part of the URI + private int getGreKey(Network network) { + int key = 0; + try { + //The GRE key is actually in the host part of the URI // this is not true for lswitch/NiciraNvp! String keyStr = BroadcastDomainType.getValue(network.getBroadcastUri()); // The key is most certainly and int if network is a vlan. // !! not in the case of lswitch/pvlan/(possibly)vswitch // So we now feel quite safe in converting it into a string // by calling the appropriate BroadcastDomainType method - key = Integer.valueOf(keyStr); - return key; - } catch (NumberFormatException e) { - s_logger.debug("Well well, how did '" + key + "' end up in the broadcast URI for the network?"); - throw new CloudRuntimeException(String.format("Invalid GRE key parsed from" + "network broadcast URI (%s)", network.getBroadcastUri().toString())); - } - } + key = Integer.valueOf(keyStr); + return key; + } catch (NumberFormatException e) { + s_logger.debug("Well well, how did '" + key + + "' end up in the broadcast URI for the network?"); + throw new CloudRuntimeException(String.format( + "Invalid GRE key parsed from" + + "network broadcast URI (%s)", network + .getBroadcastUri().toString())); + } + } - @DB + @DB protected void CheckAndCreateTunnel(VirtualMachine instance, Network nw, DeployDestination dest) { - if (!_isEnabled) { - return; - } - s_logger.debug("Creating tunnels with OVS tunnel manager"); - if (instance.getType() != VirtualMachine.Type.User && instance.getType() != VirtualMachine.Type.DomainRouter) { - s_logger.debug("Will not work if you're not" + "an instance or a virtual router"); - return; - } + s_logger.debug("Creating tunnels with OVS tunnel manager"); + if (instance.getType() != VirtualMachine.Type.User + && instance.getType() != VirtualMachine.Type.DomainRouter) { + s_logger.debug("Will not work if you're not" + + "an instance or a virtual router"); + return; + } - long hostId = dest.getHost().getId(); - int key = getGreKey(nw); - // Find active VMs with a NIC on the target network - List vms = _userVmDao.listByNetworkIdAndStates(nw.getId(), State.Running, State.Starting, State.Stopping, State.Unknown, State.Migrating); - // Find routers for the network - List routers = _routerDao.findByNetwork(nw.getId()); - List ins = new ArrayList(); - if (vms != null) { - ins.addAll(vms); - } - if (routers.size() != 0) { - ins.addAll(routers); - } - List toHostIds = new ArrayList(); - List fromHostIds = new ArrayList(); + long hostId = dest.getHost().getId(); + int key = getGreKey(nw); + // Find active VMs with a NIC on the target network + List vms = _userVmDao.listByNetworkIdAndStates(nw.getId(), + State.Running, State.Starting, State.Stopping, State.Unknown, + State.Migrating); + // Find routers for the network + List routers = _routerDao.findByNetwork(nw.getId()); + List ins = new ArrayList(); + if (vms != null) { + ins.addAll(vms); + } + if (routers.size() != 0) { + ins.addAll(routers); + } + List toHostIds = new ArrayList(); + List fromHostIds = new ArrayList(); for (VMInstanceVO v : ins) { Long rh = v.getHostId(); if (rh == null || rh.longValue() == hostId) { @@ -278,13 +312,16 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage } } - ta = _tunnelNetworkDao.getByFromToNetwork(rh.longValue(), hostId, nw.getId()); + ta = _tunnelNetworkDao.getByFromToNetwork(rh.longValue(), + hostId, nw.getId()); // Try and create the tunnel even if a previous attempt failed if (ta == null || ta.getState().equals("FAILED")) { - s_logger.debug("Attempting to create tunnel from:" + rh.longValue() + " to:" + hostId); - if (ta == null) { - this.createTunnelRecord(rh.longValue(), hostId, nw.getId(), key); - } + s_logger.debug("Attempting to create tunnel from:" + + rh.longValue() + " to:" + hostId); + if (ta == null) { + this.createTunnelRecord(rh.longValue(), hostId, + nw.getId(), key); + } if (!fromHostIds.contains(rh)) { fromHostIds.add(rh); } @@ -296,48 +333,60 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage if (myIp == null) throw new GreTunnelException("Unable to retrieve the source " + "endpoint for the GRE tunnel." + "Failure is on host:" + dest.getHost().getId()); boolean noHost = true; - for (Long i : toHostIds) { - HostVO rHost = _hostDao.findById(i); - String otherIp = getGreEndpointIP(rHost, nw); - if (otherIp == null) - throw new GreTunnelException("Unable to retrieve the remote " + "endpoint for the GRE tunnel." + "Failure is on host:" + rHost.getId()); - Commands cmds = new Commands(new OvsCreateTunnelCommand(otherIp, key, Long.valueOf(hostId), i, nw.getId(), myIp)); - s_logger.debug("Ask host " + hostId + " to create gre tunnel to " + i); - Answer[] answers = _agentMgr.send(hostId, cmds); - handleCreateTunnelAnswer(answers); - noHost = false; - } + for (Long i : toHostIds) { + HostVO rHost = _hostDao.findById(i); + String otherIp = getGreEndpointIP(rHost, nw); + if (otherIp == null) + throw new GreTunnelException( + "Unable to retrieve the remote " + + "endpoint for the GRE tunnel." + + "Failure is on host:" + rHost.getId()); + Commands cmds = new Commands( + new OvsCreateTunnelCommand(otherIp, key, + Long.valueOf(hostId), i, nw.getId(), myIp)); + s_logger.debug("Ask host " + hostId + + " to create gre tunnel to " + i); + Answer[] answers = _agentMgr.send(hostId, cmds); + handleCreateTunnelAnswer(answers); + noHost = false; + } - for (Long i : fromHostIds) { - HostVO rHost = _hostDao.findById(i); - String otherIp = getGreEndpointIP(rHost, nw); - Commands cmds = new Commands(new OvsCreateTunnelCommand(myIp, key, i, Long.valueOf(hostId), nw.getId(), otherIp)); - s_logger.debug("Ask host " + i + " to create gre tunnel to " + hostId); - Answer[] answers = _agentMgr.send(i, cmds); - handleCreateTunnelAnswer(answers); - noHost = false; - } - // If no tunnels have been configured, perform the bridge setup anyway - // This will ensure VIF rules will be triggered - if (noHost) { - Commands cmds = new Commands(new OvsSetupBridgeCommand(key, hostId, nw.getId())); - s_logger.debug("Ask host " + hostId + " to configure bridge for network:" + nw.getId()); - Answer[] answers = _agentMgr.send(hostId, cmds); - handleSetupBridgeAnswer(answers); - } - } catch (Exception e) { - // I really thing we should do a better handling of these exceptions - s_logger.warn("Ovs Tunnel network created tunnel failed", e); - } - } + for (Long i : fromHostIds) { + HostVO rHost = _hostDao.findById(i); + String otherIp = getGreEndpointIP(rHost, nw); + Commands cmds = new Commands(new OvsCreateTunnelCommand(myIp, + key, i, Long.valueOf(hostId), nw.getId(), otherIp)); + s_logger.debug("Ask host " + i + " to create gre tunnel to " + + hostId); + Answer[] answers = _agentMgr.send(i, cmds); + handleCreateTunnelAnswer(answers); + noHost = false; + } + // If no tunnels have been configured, perform the bridge setup + // anyway + // This will ensure VIF rules will be triggered + if (noHost) { + Commands cmds = new Commands(new OvsSetupBridgeCommand(key, + hostId, nw.getId())); + s_logger.debug("Ask host " + hostId + + " to configure bridge for network:" + nw.getId()); + Answer[] answers = _agentMgr.send(hostId, cmds); + handleSetupBridgeAnswer(answers); + } + } catch (Exception e) { + // I really thing we should do a better handling of these exceptions + s_logger.warn("Ovs Tunnel network created tunnel failed", e); + } + } + + @Override + public boolean isOvsTunnelEnabled() { + return true; + } @Override - public boolean isOvsTunnelEnabled() { - return _isEnabled; - } - - @Override - public void VmCheckAndCreateTunnel(VirtualMachineProfile vm, Network nw, DeployDestination dest) { + public void VmCheckAndCreateTunnel(VirtualMachineProfile vm, + Network nw, DeployDestination dest) { CheckAndCreateTunnel(vm.getVirtualMachine(), nw, dest); } @@ -346,22 +395,27 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage if (ans.getResult()) { OvsTunnelNetworkVO lock = _tunnelNetworkDao.acquireInLockTable(Long.valueOf(1)); if (lock == null) { - s_logger.warn(String.format("failed to lock" + "ovs_tunnel_account, remove record of " + "tunnel(from=%1$s, to=%2$s account=%3$s) failed", from, to, - network_id)); + s_logger.warn(String.format("failed to lock" + + "ovs_tunnel_account, remove record of " + + "tunnel(from=%1$s, to=%2$s account=%3$s) failed", + from, to, network_id)); return; } _tunnelNetworkDao.removeByFromToNetwork(from, to, network_id); _tunnelNetworkDao.releaseFromLockTable(lock.getId()); - s_logger.debug(String.format("Destroy tunnel(account:%1$s," + "from:%2$s, to:%3$s) successful", network_id, from, to)); + s_logger.debug(String.format("Destroy tunnel(account:%1$s," + + "from:%2$s, to:%3$s) successful", + network_id, from, to)); } else { s_logger.debug(String.format("Destroy tunnel(account:%1$s," + "from:%2$s, to:%3$s) failed", network_id, from, to)); } } @DB - private void handleDestroyBridgeAnswer(Answer ans, long host_id, long network_id) { + private void handleDestroyBridgeAnswer(Answer ans, + long host_id, long network_id) { if (ans.getResult()) { OvsTunnelNetworkVO lock = _tunnelNetworkDao.acquireInLockTable(Long.valueOf(1)); @@ -373,9 +427,11 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage _tunnelNetworkDao.removeByFromNetwork(host_id, network_id); _tunnelNetworkDao.releaseFromLockTable(lock.getId()); - s_logger.debug(String.format("Destroy bridge for" + "network %1$s successful", network_id)); + s_logger.debug(String.format("Destroy bridge for" + + "network %1$s successful", network_id)); } else { - s_logger.debug(String.format("Destroy bridge for" + "network %1$s failed", network_id)); + s_logger.debug(String.format("Destroy bridge for" + + "network %1$s failed", network_id)); } } @@ -386,9 +442,9 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage @Override public void CheckAndDestroyTunnel(VirtualMachine vm, Network nw) { - if (!_isEnabled) { - return; - } + // if (!_isEnabled) { + // return; + // } List userVms = _userVmDao.listByAccountIdAndHostId(vm.getAccountId(), vm.getHostId()); if (vm.getType() == VirtualMachine.Type.User) { @@ -415,15 +471,20 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage handleDestroyBridgeAnswer(ans, vm.getHostId(), nw.getId()); /* Then ask hosts have peer tunnel with me to destroy them */ - List peers = _tunnelNetworkDao.listByToNetwork(vm.getHostId(), nw.getId()); + List peers = + _tunnelNetworkDao.listByToNetwork(vm.getHostId(), + nw.getId()); for (OvsTunnelNetworkVO p : peers) { - // If the tunnel was not successfully created don't bother to remove it - if (p.getState().equals("SUCCESS")) { - cmd = new OvsDestroyTunnelCommand(p.getNetworkId(), key, p.getPortName()); - s_logger.debug("Destroying tunnel to " + vm.getHostId() + " from " + p.getFrom()); - ans = _agentMgr.send(p.getFrom(), cmd); - handleDestroyTunnelAnswer(ans, p.getFrom(), p.getTo(), p.getNetworkId()); - } + // If the tunnel was not successfully created don't bother to remove it + if (p.getState().equals("SUCCESS")) { + cmd = new OvsDestroyTunnelCommand(p.getNetworkId(), key, + p.getPortName()); + s_logger.debug("Destroying tunnel to " + vm.getHostId() + + " from " + p.getFrom()); + ans = _agentMgr.send(p.getFrom(), cmd); + handleDestroyTunnelAnswer(ans, p.getFrom(), + p.getTo(), p.getNetworkId()); + } } } catch (Exception e) { s_logger.warn(String.format("Destroy tunnel(account:%1$s," + "hostId:%2$s) failed", vm.getAccountId(), vm.getHostId()), e); diff --git a/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackImageStoreDriverImpl.java b/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackImageStoreDriverImpl.java index 0450a7a0786..1db10e2eb32 100644 --- a/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackImageStoreDriverImpl.java +++ b/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackImageStoreDriverImpl.java @@ -89,12 +89,17 @@ public class CloudStackImageStoreDriverImpl extends BaseImageStoreDriverImpl { String scheme = "http"; boolean _sslCopy = false; String sslCfg = _configDao.getValue(Config.SecStorageEncryptCopy.toString()); + String _ssvmUrlDomain = _configDao.getValue("secstorage.ssl.cert.domain"); if (sslCfg != null) { _sslCopy = Boolean.parseBoolean(sslCfg); } if (_sslCopy) { hostname = ipAddress.replace(".", "-"); - hostname = hostname + ".realhostip.com"; + if(_ssvmUrlDomain != null && _ssvmUrlDomain.length() > 0){ + hostname = hostname + "." + _ssvmUrlDomain; + } else { + hostname = hostname + ".realhostip.com"; + } scheme = "https"; } return scheme + "://" + hostname + "/userdata/" + uuid; diff --git a/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackImageStoreLifeCycleImpl.java b/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackImageStoreLifeCycleImpl.java index fa07eb8a971..95c90349a03 100644 --- a/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackImageStoreLifeCycleImpl.java +++ b/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackImageStoreLifeCycleImpl.java @@ -26,6 +26,8 @@ import javax.inject.Inject; import org.apache.log4j.Logger; +import com.ibm.wsdl.util.StringUtils; + import org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.HostScope; @@ -84,13 +86,13 @@ public class CloudStackImageStoreLifeCycleImpl implements ImageStoreLifeCycle { DataStoreRole role = (DataStoreRole)dsInfos.get("role"); Map details = (Map)dsInfos.get("details"); - s_logger.info("Trying to add a new data store at " + url + " to data center " + dcId); + s_logger.info("Trying to add a new data store at " + StringUtils.cleanString(url) + " to data center " + dcId); URI uri = null; try { uri = new URI(UriUtils.encodeURIComponent(url)); if (uri.getScheme() == null) { - throw new InvalidParameterValueException("uri.scheme is null " + url + ", add nfs:// (or cifs://) as a prefix"); + throw new InvalidParameterValueException("uri.scheme is null " + StringUtils.cleanString(url) + ", add nfs:// (or cifs://) as a prefix"); } else if (uri.getScheme().equalsIgnoreCase("nfs")) { if (uri.getHost() == null || uri.getHost().equalsIgnoreCase("") || uri.getPath() == null || uri.getPath().equalsIgnoreCase("")) { throw new InvalidParameterValueException("Your host and/or path is wrong. Make sure it's of the format nfs://hostname/path"); diff --git a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/provider/SolidFireHostListener.java b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/provider/SolidFireHostListener.java index 53143141778..d8e4ec61ec8 100644 --- a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/provider/SolidFireHostListener.java +++ b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/provider/SolidFireHostListener.java @@ -82,7 +82,7 @@ public class SolidFireHostListener implements HypervisorHostListener { if (!answer.getResult()) { String msg = "Unable to attach storage pool " + storagePoolId + " to host " + hostId; - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, storagePool.getDataCenterId(), storagePool.getPodId(), msg, msg); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, storagePool.getDataCenterId(), storagePool.getPodId(), msg, msg); throw new CloudRuntimeException("Unable to establish a connection from agent to storage pool " + storagePool.getId() + " due to " + answer.getDetails() + " (" + storagePool.getId() + ")"); diff --git a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/command/LdapImportUsersCmd.java b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/command/LdapImportUsersCmd.java index 129392ea931..d817c334de8 100644 --- a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/command/LdapImportUsersCmd.java +++ b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/command/LdapImportUsersCmd.java @@ -25,10 +25,6 @@ import java.util.UUID; import javax.inject.Inject; -import org.apache.commons.lang.StringUtils; -import org.apache.log4j.Logger; -import org.bouncycastle.util.encoders.Base64; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; @@ -41,6 +37,9 @@ import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.ldap.LdapManager; import org.apache.cloudstack.ldap.LdapUser; import org.apache.cloudstack.ldap.NoLdapUserMatchingQueryException; +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.bouncycastle.util.encoders.Base64; import com.cloud.domain.Domain; import com.cloud.exception.ConcurrentOperationException; @@ -60,29 +59,29 @@ public class LdapImportUsersCmd extends BaseListCmd { private static final String s_name = "ldapuserresponse"; @Parameter(name = ApiConstants.TIMEZONE, - type = CommandType.STRING, - description = "Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.") + type = CommandType.STRING, + description = "Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.") private String timezone; @Parameter(name = ApiConstants.ACCOUNT_TYPE, - type = CommandType.SHORT, - required = true, - description = "Type of the account. Specify 0 for user, 1 for root admin, and 2 for domain admin") + type = CommandType.SHORT, + required = true, + description = "Type of the account. Specify 0 for user, 1 for root admin, and 2 for domain admin") private Short accountType; @Parameter(name = ApiConstants.ACCOUNT_DETAILS, type = CommandType.MAP, description = "details for account used to store specific parameters") private Map details; @Parameter(name = ApiConstants.DOMAIN_ID, - type = CommandType.UUID, - entityType = DomainResponse.class, - description = "Specifies the domain to which the ldap users are to be " - + "imported. If no domain is specified, a domain will created using group parameter. If the group is also not specified, a domain name based on the OU information will be " - + "created. If no OU hierarchy exists, will be defaulted to ROOT domain") + type = CommandType.UUID, + entityType = DomainResponse.class, + description = "Specifies the domain to which the ldap users are to be " + + "imported. If no domain is specified, a domain will created using group parameter. If the group is also not specified, a domain name based on the OU information will be " + + "created. If no OU hierarchy exists, will be defaulted to ROOT domain") private Long domainId; @Parameter(name = ApiConstants.GROUP, type = CommandType.STRING, description = "Specifies the group name from which the ldap users are to be imported. " - + "If no group is specified, all the users will be imported.") + + "If no group is specified, all the users will be imported.") private String groupName; private Domain _domain; @@ -103,11 +102,12 @@ public class LdapImportUsersCmd extends BaseListCmd { @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException, NetworkRuleConflictException { + ResourceAllocationException, NetworkRuleConflictException { List users; try { if (StringUtils.isNotBlank(groupName)) { + users = _ldapManager.getUsersInGroup(groupName); } else { users = _ldapManager.getUsers(); @@ -122,7 +122,7 @@ public class LdapImportUsersCmd extends BaseListCmd { Domain domain = getDomain(user); try { _accountService.createUserAccount(user.getUsername(), generatePassword(), user.getFirstname(), user.getLastname(), user.getEmail(), timezone, - user.getUsername(), accountType, domain.getId(), domain.getNetworkDomain(), details, UUID.randomUUID().toString(), UUID.randomUUID().toString()); + user.getUsername(), accountType, domain.getId(), domain.getNetworkDomain(), details, UUID.randomUUID().toString(), UUID.randomUUID().toString()); addedUsers.add(user); } catch (InvalidParameterValueException ex) { s_logger.error("Failed to create user with username: " + user.getUsername() + " ::: " + ex.getMessage()); @@ -194,7 +194,8 @@ public class LdapImportUsersCmd extends BaseListCmd { final SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG"); final byte bytes[] = new byte[20]; randomGen.nextBytes(bytes); - return Base64.encode(bytes).toString(); + String encodedPassword = new String(Base64.encode(bytes)); + return encodedPassword; } catch (final NoSuchAlgorithmException e) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to generate random password"); } diff --git a/scripts/storage/secondary/cloud-install-sys-tmplt b/scripts/storage/secondary/cloud-install-sys-tmplt index 2e822f3504c..96b11de41d4 100755 --- a/scripts/storage/secondary/cloud-install-sys-tmplt +++ b/scripts/storage/secondary/cloud-install-sys-tmplt @@ -20,9 +20,9 @@ usage() { - printf "Usage: %s: -m -f [-h ] [ -s ][-u ] [-F ] [-e