diff --git a/agent/pom.xml b/agent/pom.xml index 14133226053..c3ac308882a 100644 --- a/agent/pom.xml +++ b/agent/pom.xml @@ -115,5 +115,38 @@ + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-antrun-plugin + + [1.7,) + + run + + + + + + + + + + + + diff --git a/agent/src/com/cloud/agent/dao/impl/PropertiesStorage.java b/agent/src/com/cloud/agent/dao/impl/PropertiesStorage.java index 411d946a294..0c100b37be6 100755 --- a/agent/src/com/cloud/agent/dao/impl/PropertiesStorage.java +++ b/agent/src/com/cloud/agent/dao/impl/PropertiesStorage.java @@ -119,34 +119,33 @@ public class PropertiesStorage implements StorageComponent { return true; } - @Override - public void setName(String name) { - // TODO Auto-generated method stub - - } + @Override + public void setName(String name) { + // TODO Auto-generated method stub - @Override - public void setConfigParams(Map params) { - // TODO Auto-generated method stub - - } + } - @Override - public Map getConfigParams() { - // TODO Auto-generated method stub - return null; - } + @Override + public void setConfigParams(Map params) { + // TODO Auto-generated method stub - @Override - public int getRunLevel() { - // TODO Auto-generated method stub - return 0; - } + } - @Override - public void setRunLevel(int level) { - // TODO Auto-generated method stub - - } + @Override + public Map getConfigParams() { + // TODO Auto-generated method stub + return null; + } + + @Override + public int getRunLevel() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public void setRunLevel(int level) { + // TODO Auto-generated method stub + } } diff --git a/agent/src/com/cloud/agent/dhcp/FakeDhcpSnooper.java b/agent/src/com/cloud/agent/dhcp/FakeDhcpSnooper.java index 73a994e8bd9..432caa63c32 100644 --- a/agent/src/com/cloud/agent/dhcp/FakeDhcpSnooper.java +++ b/agent/src/com/cloud/agent/dhcp/FakeDhcpSnooper.java @@ -18,9 +18,6 @@ package com.cloud.agent.dhcp; import java.net.InetAddress; import java.net.UnknownHostException; - -import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Queue; @@ -32,8 +29,6 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; import com.cloud.utils.Pair; import com.cloud.utils.net.NetUtils; diff --git a/agent/src/com/cloud/agent/mockvm/MockVm.java b/agent/src/com/cloud/agent/mockvm/MockVm.java index 306a6c40786..8a806eea354 100644 --- a/agent/src/com/cloud/agent/mockvm/MockVm.java +++ b/agent/src/com/cloud/agent/mockvm/MockVm.java @@ -71,11 +71,4 @@ public class MockVm { return vncPort; } - public static void main(String[] args) { - long i = 10; - Long l = null; - if (i == l) { - System.out.print("fdfd"); - } - } } diff --git a/agent/src/com/cloud/agent/resource/consoleproxy/ConsoleProxyResource.java b/agent/src/com/cloud/agent/resource/consoleproxy/ConsoleProxyResource.java index 6f49f47a1ed..054acd1caeb 100644 --- a/agent/src/com/cloud/agent/resource/consoleproxy/ConsoleProxyResource.java +++ b/agent/src/com/cloud/agent/resource/consoleproxy/ConsoleProxyResource.java @@ -32,9 +32,12 @@ import java.util.Properties; import javax.naming.ConfigurationException; -import org.apache.cloudstack.managed.context.ManagedContextRunnable; import org.apache.log4j.Logger; +import com.google.gson.Gson; + +import org.apache.cloudstack.managed.context.ManagedContextRunnable; + import com.cloud.agent.Agent.ExitStatus; import com.cloud.agent.api.AgentControlAnswer; import com.cloud.agent.api.Answer; @@ -61,7 +64,6 @@ import com.cloud.resource.ServerResourceBase; import com.cloud.utils.NumbersUtil; import com.cloud.utils.net.NetUtils; import com.cloud.utils.script.Script; -import com.google.gson.Gson; /** * @@ -130,19 +132,6 @@ public class ConsoleProxyResource extends ServerResourceBase implements } } - private boolean copyCertToDirectory(String certificate, String filePath) - throws IOException { - boolean success; - // copy cert to the dir - FileWriter fstream = new FileWriter(filePath); - BufferedWriter out = new BufferedWriter(fstream); - out.write(certificate); - // Close the output stream - out.close(); - success = true; - return success; - } - protected Answer execute(final CheckConsoleProxyLoadCommand cmd) { return executeProxyLoadScan(cmd, cmd.getProxyVmId(), cmd.getProxyVmName(), cmd.getProxyManagementIp(), @@ -204,6 +193,7 @@ public class ConsoleProxyResource extends ServerResourceBase implements return null; } + @Override public Type getType() { return Host.Type.ConsoleProxy; } diff --git a/api/src/com/cloud/agent/api/to/DataStoreTO.java b/api/src/com/cloud/agent/api/to/DataStoreTO.java index b79ba7d64be..199740da471 100644 --- a/api/src/com/cloud/agent/api/to/DataStoreTO.java +++ b/api/src/com/cloud/agent/api/to/DataStoreTO.java @@ -21,6 +21,7 @@ package com.cloud.agent.api.to; import com.cloud.storage.DataStoreRole; public interface DataStoreTO { - public DataStoreRole getRole(); - public String getUuid(); + DataStoreRole getRole(); + String getUuid(); + String getUrl(); } diff --git a/api/src/com/cloud/agent/api/to/NfsTO.java b/api/src/com/cloud/agent/api/to/NfsTO.java index 54683c7f410..ee6c3e3566d 100644 --- a/api/src/com/cloud/agent/api/to/NfsTO.java +++ b/api/src/com/cloud/agent/api/to/NfsTO.java @@ -39,6 +39,7 @@ public class NfsTO implements DataStoreTO { } + @Override public String getUrl() { return _url; } diff --git a/api/src/com/cloud/agent/api/to/S3TO.java b/api/src/com/cloud/agent/api/to/S3TO.java index 350b9ca8b60..0dabb8ff933 100644 --- a/api/src/com/cloud/agent/api/to/S3TO.java +++ b/api/src/com/cloud/agent/api/to/S3TO.java @@ -181,6 +181,11 @@ public final class S3TO implements S3Utils.ClientOptions, DataStoreTO { return this.uuid; } + @Override + public String getUrl() { + return null; + } + public void setUuid(final String uuid) { this.uuid = uuid; } diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index 49f380b3d6d..bda3326cb51 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -114,6 +114,7 @@ public interface Network extends ControlledEntity, StateObject, I private static List supportedProviders = new ArrayList(); public static final Provider VirtualRouter = new Provider("VirtualRouter", false); + public static final Provider JuniperContrail = new Provider("JuniperContrail", false); public static final Provider JuniperSRX = new Provider("JuniperSRX", true); public static final Provider F5BigIp = new Provider("F5BigIp", true); public static final Provider Netscaler = new Provider("Netscaler", true); diff --git a/api/src/com/cloud/network/Site2SiteVpnConnection.java b/api/src/com/cloud/network/Site2SiteVpnConnection.java index 810f9992d93..984b0519ddc 100644 --- a/api/src/com/cloud/network/Site2SiteVpnConnection.java +++ b/api/src/com/cloud/network/Site2SiteVpnConnection.java @@ -35,4 +35,5 @@ public interface Site2SiteVpnConnection extends ControlledEntity, InternalIdenti public State getState(); public Date getCreated(); public Date getRemoved(); + public boolean isPassive(); } diff --git a/api/src/com/cloud/vm/snapshot/VMSnapshotService.java b/api/src/com/cloud/vm/snapshot/VMSnapshotService.java index 83f86bc90db..1ae7edc7a8e 100644 --- a/api/src/com/cloud/vm/snapshot/VMSnapshotService.java +++ b/api/src/com/cloud/vm/snapshot/VMSnapshotService.java @@ -35,7 +35,7 @@ public interface VMSnapshotService { VMSnapshot getVMSnapshotById(Long id); - VMSnapshot creatVMSnapshot(Long vmId, Long vmSnapshotId); + VMSnapshot creatVMSnapshot(Long vmId, Long vmSnapshotId, Boolean quiescevm); VMSnapshot allocVMSnapshot(Long vmId, String vsDisplayName, String vsDescription, Boolean snapshotMemory) throws ResourceAllocationException; diff --git a/api/src/org/apache/cloudstack/api/ApiConstants.java b/api/src/org/apache/cloudstack/api/ApiConstants.java index 32c2c5e9637..d8879109e87 100755 --- a/api/src/org/apache/cloudstack/api/ApiConstants.java +++ b/api/src/org/apache/cloudstack/api/ApiConstants.java @@ -490,6 +490,7 @@ public class ApiConstants { public static final String VM_SNAPSHOT_ID = "vmsnapshotid"; public static final String VM_SNAPSHOT_DISK_IDS = "vmsnapshotdiskids"; public static final String VM_SNAPSHOT_MEMORY = "snapshotmemory"; + public static final String VM_SNAPSHOT_QUIESCEVM = "quiescevm"; public static final String IMAGE_STORE_UUID = "imagestoreuuid"; public static final String GUEST_VM_CIDR = "guestvmcidr"; public static final String NETWORK_CIDR = "networkcidr"; @@ -536,6 +537,7 @@ public class ApiConstants { public static final String RESOURCE_DETAILS = "resourcedetails"; public static final String EXPUNGE = "expunge"; public static final String FOR_DISPLAY = "fordisplay"; + public static final String PASSIVE = "passive"; public enum HostDetails { diff --git a/api/src/org/apache/cloudstack/api/Parameter.java b/api/src/org/apache/cloudstack/api/Parameter.java index 6f64737ab83..89178f200e7 100644 --- a/api/src/org/apache/cloudstack/api/Parameter.java +++ b/api/src/org/apache/cloudstack/api/Parameter.java @@ -22,6 +22,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.BaseCmd.CommandType; @Retention(RetentionPolicy.RUNTIME) @@ -48,4 +49,6 @@ public @interface Parameter { String since() default ""; String retrieveMethod() default "getById"; + + RoleType[] authorized() default {}; } diff --git a/api/src/org/apache/cloudstack/api/command/admin/usage/GetUsageRecordsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/GetUsageRecordsCmd.java index f4960dd0e08..59220eefd4f 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/usage/GetUsageRecordsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/GetUsageRecordsCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.usage; import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.TimeZone; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -33,6 +32,8 @@ import org.apache.cloudstack.api.response.UsageRecordResponse; import org.apache.cloudstack.usage.Usage; import org.apache.log4j.Logger; +import com.cloud.utils.Pair; + @APICommand(name = "listUsageRecords", description="Lists usage records for accounts", responseObject=UsageRecordResponse.class) public class GetUsageRecordsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(GetUsageRecordsCmd.class.getName()); @@ -110,16 +111,18 @@ public class GetUsageRecordsCmd extends BaseListCmd { @Override public void execute(){ - List usageRecords = _usageService.getUsageRecords(this); + Pair, Integer> usageRecords = _usageService.getUsageRecords(this); ListResponse response = new ListResponse(); List usageResponses = new ArrayList(); - for(Usage usageRecord: usageRecords){ - UsageRecordResponse usageResponse = _responseGenerator.createUsageResponse(usageRecord); - usageResponse.setObjectName("usagerecord"); - usageResponses.add(usageResponse); + if (usageRecords != null) { + for(Usage usageRecord: usageRecords.first()){ + UsageRecordResponse usageResponse = _responseGenerator.createUsageResponse(usageRecord); + usageResponse.setObjectName("usagerecord"); + usageResponses.add(usageResponse); + } + response.setResponses(usageResponses, usageRecords.second()); } - - response.setResponses(usageResponses); + response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/org/apache/cloudstack/api/command/user/vmsnapshot/CreateVMSnapshotCmd.java b/api/src/org/apache/cloudstack/api/command/user/vmsnapshot/CreateVMSnapshotCmd.java index 542215a5e8e..252a206d000 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vmsnapshot/CreateVMSnapshotCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vmsnapshot/CreateVMSnapshotCmd.java @@ -53,6 +53,9 @@ public class CreateVMSnapshotCmd extends BaseAsyncCreateCmd { @Parameter(name = ApiConstants.VM_SNAPSHOT_MEMORY, type = CommandType.BOOLEAN, required = false, description = "snapshot memory if true") private Boolean snapshotMemory; + @Parameter(name = ApiConstants.VM_SNAPSHOT_QUIESCEVM, type = CommandType.BOOLEAN, required = false, description = "quiesce vm if true") + private Boolean quiescevm; + public Boolean snapshotMemory() { if (snapshotMemory == null) { return false; @@ -61,6 +64,14 @@ public class CreateVMSnapshotCmd extends BaseAsyncCreateCmd { } } + public Boolean getQuiescevm() { + if (quiescevm == null) { + return false; + } else { + return quiescevm; + } + } + public String getDisplayName() { return displayName; } @@ -97,7 +108,7 @@ public class CreateVMSnapshotCmd extends BaseAsyncCreateCmd { @Override public void execute() { CallContext.current().setEventDetails("VM Id: " + getVmId()); - VMSnapshot result = _vmSnapshotService.creatVMSnapshot(getVmId(),getEntityId()); + VMSnapshot result = _vmSnapshotService.creatVMSnapshot(getVmId(),getEntityId(), getQuiescevm()); if (result != null) { VMSnapshotResponse response = _responseGenerator .createVMSnapshotResponse(result); diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/ListVolumesCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/ListVolumesCmd.java index e90643878ac..f6bdb3cd855 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/ListVolumesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/ListVolumesCmd.java @@ -16,6 +16,7 @@ // under the License. package org.apache.cloudstack.api.command.user.volume; +import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandJobType; import org.apache.cloudstack.api.ApiConstants; @@ -24,6 +25,7 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.HostResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.cloudstack.api.response.ZoneResponse; @@ -66,6 +68,10 @@ public class ListVolumesCmd extends BaseListTaggedResourcesCmd { @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, description="the ID of the availability zone") private Long zoneId; + + @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.UUID, entityType=StoragePoolResponse.class, + description="the ID of the storage pool, available to ROOT admin only", since="4.3", authorized = { RoleType.Admin }) + private Long storageId; ///////////////////////////////////////////////////// @@ -101,6 +107,9 @@ public class ListVolumesCmd extends BaseListTaggedResourcesCmd { return zoneId; } + public Long getStorageId() { + return storageId; + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// diff --git a/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java index a8c6dc2f0be..b5cebf36afe 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java @@ -53,6 +53,9 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { required=true, description="id of the customer gateway") private Long customerGatewayId; + @Parameter(name=ApiConstants.PASSIVE, type=CommandType.BOOLEAN, required=false, description="connection is passive or not") + private Boolean passive; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -65,6 +68,13 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { public Long getCustomerGatewayId() { return customerGatewayId; } + + public boolean isPassive() { + if (passive == null) { + return false; + } + return passive; + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// diff --git a/api/src/org/apache/cloudstack/api/response/Site2SiteVpnConnectionResponse.java b/api/src/org/apache/cloudstack/api/response/Site2SiteVpnConnectionResponse.java index 99075b5f213..b4cf5e7d113 100644 --- a/api/src/org/apache/cloudstack/api/response/Site2SiteVpnConnectionResponse.java +++ b/api/src/org/apache/cloudstack/api/response/Site2SiteVpnConnectionResponse.java @@ -68,6 +68,9 @@ public class Site2SiteVpnConnectionResponse extends BaseResponse implements Cont @SerializedName(ApiConstants.STATE) @Param(description="State of vpn connection") private String state; + @SerializedName(ApiConstants.PASSIVE) @Param(description="State of vpn connection") + private boolean passive; + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the owner") private String accountName; @@ -141,6 +144,10 @@ public class Site2SiteVpnConnectionResponse extends BaseResponse implements Cont this.state = state; } + public void setPassive(boolean passive) { + this.passive = passive; + } + public void setCreated(Date created) { this.created = created; } diff --git a/api/src/org/apache/cloudstack/usage/UsageService.java b/api/src/org/apache/cloudstack/usage/UsageService.java index 383822592bc..e203c3f50c3 100755 --- a/api/src/org/apache/cloudstack/usage/UsageService.java +++ b/api/src/org/apache/cloudstack/usage/UsageService.java @@ -23,6 +23,8 @@ import org.apache.cloudstack.api.command.admin.usage.GenerateUsageRecordsCmd; import org.apache.cloudstack.api.command.admin.usage.GetUsageRecordsCmd; import org.apache.cloudstack.api.response.UsageTypeResponse; +import com.cloud.utils.Pair; + public interface UsageService { /** * Generate Billing Records from the last time it was generated to the @@ -50,7 +52,7 @@ public interface UsageService { * the appropriate page number) * @return a list of usage records */ - List getUsageRecords(GetUsageRecordsCmd cmd); + Pair, Integer> getUsageRecords(GetUsageRecordsCmd cmd); /** * Retrieves the timezone used for usage aggregation. One day is represented as midnight to 11:59:59pm diff --git a/api/test/org/apache/cloudstack/api/command/test/UsageCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/UsageCmdTest.java index 1f218f47e2a..b8dfb0a1e65 100644 --- a/api/test/org/apache/cloudstack/api/command/test/UsageCmdTest.java +++ b/api/test/org/apache/cloudstack/api/command/test/UsageCmdTest.java @@ -16,7 +16,11 @@ // under the License. package org.apache.cloudstack.api.command.test; +import java.util.ArrayList; +import java.util.List; + import junit.framework.TestCase; + import org.apache.cloudstack.api.command.admin.usage.GetUsageRecordsCmd; import org.apache.cloudstack.usage.Usage; import org.apache.cloudstack.usage.UsageService; @@ -26,8 +30,7 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; -import java.util.ArrayList; -import java.util.List; +import com.cloud.utils.Pair; public class UsageCmdTest extends TestCase { @@ -56,7 +59,7 @@ public class UsageCmdTest extends TestCase { UsageService usageService = Mockito.mock(UsageService.class); - List usageRecords = new ArrayList(); + Pair, Integer> usageRecords = new Pair, Integer>(new ArrayList(), new Integer(0)); Mockito.when(usageService.getUsageRecords(getUsageRecordsCmd)).thenReturn( usageRecords); diff --git a/awsapi/src/com/cloud/bridge/persist/dao/BaseDao.java b/awsapi/src/com/cloud/bridge/persist/dao/BaseDao.java index 83679fa002d..3b04b5070e1 100644 --- a/awsapi/src/com/cloud/bridge/persist/dao/BaseDao.java +++ b/awsapi/src/com/cloud/bridge/persist/dao/BaseDao.java @@ -16,18 +16,11 @@ // under the License. package com.cloud.bridge.persist.dao; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; import java.util.Properties; import org.apache.log4j.Logger; -import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; -import org.jasypt.properties.EncryptableProperties; -import com.cloud.bridge.util.ConfigurationHelper; -import com.cloud.bridge.util.EncryptionSecretKeyCheckerUtil; +import com.cloud.utils.db.DbProperties; @@ -43,24 +36,9 @@ public class BaseDao { static{ logger.info("Initializing DB props"); - File propertiesFile = ConfigurationHelper.findConfigurationFile("db.properties"); - Properties EC2Prop = null; - - if (null != propertiesFile) { - if(EncryptionSecretKeyCheckerUtil.useEncryption()){ - StandardPBEStringEncryptor encryptor = EncryptionSecretKeyCheckerUtil.getEncryptor(); - EC2Prop = new EncryptableProperties(encryptor); - } else { - EC2Prop = new Properties(); - } + Properties EC2Prop = DbProperties.getDbProperties(); - try { - EC2Prop.load( new FileInputStream( propertiesFile )); - } 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); - } + if (EC2Prop.size() > 0) { dbHost = EC2Prop.getProperty( "db.cloud.host" ); awsapi_dbName = EC2Prop.getProperty( "db.awsapi.name" ); cloud_dbName = EC2Prop.getProperty( "db.cloud.name" ); diff --git a/awsapi/src/com/cloud/bridge/util/EncryptionSecretKeyCheckerUtil.java b/awsapi/src/com/cloud/bridge/util/EncryptionSecretKeyCheckerUtil.java deleted file mode 100644 index 6f0049f24c4..00000000000 --- a/awsapi/src/com/cloud/bridge/util/EncryptionSecretKeyCheckerUtil.java +++ /dev/null @@ -1,138 +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.bridge.util; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.Properties; - -import org.apache.log4j.Logger; -import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; -import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig; - - -public class EncryptionSecretKeyCheckerUtil { - private static final Logger s_logger = Logger.getLogger(EncryptionSecretKeyCheckerUtil.class); - - private static final String s_keyFile = "/etc/cloudstack/management/key"; - private static final String s_envKey = "CLOUD_SECRET_KEY"; - private static StandardPBEStringEncryptor s_encryptor = new StandardPBEStringEncryptor(); - private static boolean s_useEncryption = false; - - static{ - //Get encryption type from db.properties - final File dbPropsFile = ConfigurationHelper.findConfigurationFile("db.properties"); - final Properties dbProps = new Properties(); - try { - dbProps.load(new FileInputStream(dbPropsFile)); - - final String encryptionType = dbProps.getProperty("db.cloud.encryption.type"); - - s_logger.debug("Encryption Type: "+ encryptionType); - - if(encryptionType != null && !encryptionType.equals("none")){ - - s_encryptor.setAlgorithm("PBEWithMD5AndDES"); - String secretKey = null; - - SimpleStringPBEConfig stringConfig = new SimpleStringPBEConfig(); - - if(encryptionType.equals("file")){ - try { - BufferedReader in = new BufferedReader(new FileReader(s_keyFile)); - secretKey = in.readLine(); - //Check for null or empty secret key - } catch (FileNotFoundException e) { - throw new RuntimeException("File containing secret key not found: "+s_keyFile, e); - } catch (IOException e) { - throw new RuntimeException("Error while reading secret key from: "+s_keyFile, e); - } - - if(secretKey == null || secretKey.isEmpty()){ - throw new RuntimeException("Secret key is null or empty in file "+s_keyFile); - } - - } else if(encryptionType.equals("env")){ - secretKey = System.getenv(s_envKey); - if(secretKey == null || secretKey.isEmpty()){ - throw new RuntimeException("Environment variable "+s_envKey+" is not set or empty"); - } - } else if(encryptionType.equals("web")){ - ServerSocket serverSocket = null; - int port = 8097; - try { - serverSocket = new ServerSocket(port); - } catch (IOException ioex) { - throw new RuntimeException("Error initializing secret key reciever", ioex); - } - s_logger.info("Waiting for admin to send secret key on port "+port); - Socket clientSocket = null; - try { - clientSocket = serverSocket.accept(); - } catch (IOException e) { - throw new RuntimeException("Accept failed on "+port); - } - PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); - BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); - String inputLine, outputLine; - if ((inputLine = in.readLine()) != null) { - secretKey = inputLine; - } - out.close(); - in.close(); - clientSocket.close(); - serverSocket.close(); - } else { - throw new RuntimeException("Invalid encryption type: "+encryptionType); - } - - stringConfig.setPassword(secretKey); - s_encryptor.setConfig(stringConfig); - s_useEncryption = true; - } - } catch (FileNotFoundException e) { - throw new RuntimeException("File db.properties not found", e); - } catch (IOException e) { - throw new RuntimeException("Error while reading db.properties", e); - } - } - - public static StandardPBEStringEncryptor getEncryptor() { - return s_encryptor; - } - - public static boolean useEncryption(){ - return s_useEncryption; - } - - //Initialize encryptor for migration during secret key change - public static void initEncryptorForMigration(String secretKey){ - s_encryptor.setAlgorithm("PBEWithMD5AndDES"); - SimpleStringPBEConfig stringConfig = new SimpleStringPBEConfig(); - stringConfig.setPassword(secretKey); - s_encryptor.setConfig(stringConfig); - s_useEncryption = true; - } -} diff --git a/client/WEB-INF/classes/resources/messages.properties b/client/WEB-INF/classes/resources/messages.properties index 12d2a11a294..d548527267b 100644 --- a/client/WEB-INF/classes/resources/messages.properties +++ b/client/WEB-INF/classes/resources/messages.properties @@ -1176,9 +1176,11 @@ label.virtual.machines=Virtual machines label.virtual.network=Virtual Network label.virtual.router=Virtual Router label.virtual.routers=Virtual Routers -label.vlan.id=VLAN ID -label.vlan.range=VLAN Range -label.vlan=VLAN +label.vlan.id=VLAN/VNI ID +label.vlan.range=VLAN/VNI Range +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=VXLAN diff --git a/client/pom.xml b/client/pom.xml index 8cbdaffe94f..b6b65bad95c 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -90,6 +90,11 @@ cloud-plugin-network-nvp ${project.version} + + org.apache.cloudstack + cloud-plugin-network-contrail + ${project.version} + org.apache.cloudstack cloud-plugin-network-ovs @@ -156,6 +161,11 @@ + + org.apache.cloudstack + cloud-plugin-hypervisor-hyperv + ${project.version} + org.apache.cloudstack cloud-plugin-storage-allocator-random diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in index 428042a5137..8829cc5b987 100644 --- a/client/tomcatconf/commands.properties.in +++ b/client/tomcatconf/commands.properties.in @@ -19,9 +19,9 @@ ### Please standardize naming conventions to camel-case (even for acronyms). ### Account commands -createAccount=3 -deleteAccount=3 -updateAccount=3 +createAccount=7 +deleteAccount=7 +updateAccount=7 disableAccount=7 enableAccount=7 lockAccount=7 @@ -29,8 +29,8 @@ listAccounts=15 markDefaultZoneForAccount=1 #### User commands -createUser=3 -deleteUser=3 +createUser=7 +deleteUser=7 updateUser=15 listUsers=7 lockUser=7 @@ -698,5 +698,6 @@ removeAccountFromAclGroup=7 grantPermissionToAclGroup=7 revokePermissionFromAclGroup=7 - +#### juniper-contrail commands +createServiceInstance=1 diff --git a/core/resources/META-INF/cloudstack/bootstrap/spring-bootstrap-context.xml b/core/resources/META-INF/cloudstack/bootstrap/spring-bootstrap-context.xml index 40fcc71c14e..5ddb66f3a9c 100644 --- a/core/resources/META-INF/cloudstack/bootstrap/spring-bootstrap-context.xml +++ b/core/resources/META-INF/cloudstack/bootstrap/spring-bootstrap-context.xml @@ -25,8 +25,9 @@ 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" - > + > + diff --git a/core/src/com/cloud/agent/api/SetupCommand.java b/core/src/com/cloud/agent/api/SetupCommand.java index ee43c5933da..65700e9453c 100644 --- a/core/src/com/cloud/agent/api/SetupCommand.java +++ b/core/src/com/cloud/agent/api/SetupCommand.java @@ -23,6 +23,8 @@ public class SetupCommand extends Command { HostEnvironment env; boolean multipath; boolean needSetup; + String secondaryStorage; + String systemVmIso; public boolean needSetup() { return needSetup; @@ -36,6 +38,8 @@ public class SetupCommand extends Command { this.env = env; this.multipath = false; this.needSetup = false; + secondaryStorage = null; + systemVmIso = null; } public HostEnvironment getEnvironment() { @@ -53,6 +57,22 @@ public class SetupCommand extends Command { return multipath; } + public void setSecondaryStorage(String secondaryStorage) { + this.secondaryStorage = secondaryStorage; + } + + public String getSecondaryStorage() { + return this.secondaryStorage; + } + + public void setSystemVmIso(String systemVmIso) { + this.systemVmIso = systemVmIso; + } + + public String getSystemVmIso() { + return this.systemVmIso; + } + @Override public boolean executeInSequence() { return true; diff --git a/core/src/com/cloud/agent/api/VMSnapshotTO.java b/core/src/com/cloud/agent/api/VMSnapshotTO.java index c7b42d25bc9..473c39a595d 100644 --- a/core/src/com/cloud/agent/api/VMSnapshotTO.java +++ b/core/src/com/cloud/agent/api/VMSnapshotTO.java @@ -16,6 +16,10 @@ // under the License. package com.cloud.agent.api; +import java.util.List; + +import org.apache.cloudstack.storage.to.VolumeObjectTO; + import com.cloud.vm.snapshot.VMSnapshot; public class VMSnapshotTO { @@ -26,6 +30,7 @@ public class VMSnapshotTO { private Boolean current; private String description; private VMSnapshotTO parent; + private List volumes; public Long getId() { return id; @@ -87,4 +92,11 @@ public class VMSnapshotTO { this.parent = parent; } + public List getVolumes() { + return this.volumes; + } + + public void setVolumes(List volumes) { + this.volumes = volumes; + } } diff --git a/core/src/com/cloud/agent/api/routing/Site2SiteVpnCfgCommand.java b/core/src/com/cloud/agent/api/routing/Site2SiteVpnCfgCommand.java index 83163039f51..d54c29c9c86 100644 --- a/core/src/com/cloud/agent/api/routing/Site2SiteVpnCfgCommand.java +++ b/core/src/com/cloud/agent/api/routing/Site2SiteVpnCfgCommand.java @@ -30,6 +30,7 @@ public class Site2SiteVpnCfgCommand extends NetworkElementCommand { private long ikeLifetime; private long espLifetime; private boolean dpd; + private boolean passive; @Override public boolean executeInSequence() { @@ -41,7 +42,7 @@ public class Site2SiteVpnCfgCommand extends NetworkElementCommand { } public Site2SiteVpnCfgCommand (boolean create, String localPublicIp, String localPublicGateway, String localGuestCidr, String peerGatewayIp, - String peerGuestCidrList, String ikePolicy, String espPolicy, String ipsecPsk, Long ikeLifetime, Long espLifetime, Boolean dpd) { + String peerGuestCidrList, String ikePolicy, String espPolicy, String ipsecPsk, Long ikeLifetime, Long espLifetime, Boolean dpd, boolean passive) { this.create = create; this.setLocalPublicIp(localPublicIp); this.setLocalPublicGateway(localPublicGateway); @@ -54,6 +55,7 @@ public class Site2SiteVpnCfgCommand extends NetworkElementCommand { this.ikeLifetime = ikeLifetime; this.espLifetime = espLifetime; this.dpd = dpd; + this.passive = passive; } public boolean isCreate() { @@ -151,4 +153,12 @@ public class Site2SiteVpnCfgCommand extends NetworkElementCommand { public void setPeerGuestCidrList(String peerGuestCidrList) { this.peerGuestCidrList = peerGuestCidrList; } + + public boolean isPassive() { + return passive; + } + + public void setPassive(boolean passive) { + this.passive = passive; + } } diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java index 874146c6258..4c2ee505117 100755 --- a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java +++ b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java @@ -761,6 +761,9 @@ public class VirtualRoutingResource implements Manager { } else { args += "0"; } + if (cmd.isPassive()) { + args += " -p "; + } } else { args = "-D"; args += " -r "; diff --git a/core/src/com/cloud/storage/resource/StorageSubsystemCommandHandlerBase.java b/core/src/com/cloud/storage/resource/StorageSubsystemCommandHandlerBase.java index b43722a6418..4efeafd9aa1 100644 --- a/core/src/com/cloud/storage/resource/StorageSubsystemCommandHandlerBase.java +++ b/core/src/com/cloud/storage/resource/StorageSubsystemCommandHandlerBase.java @@ -18,6 +18,8 @@ */ package com.cloud.storage.resource; +import org.apache.log4j.Logger; + import org.apache.cloudstack.storage.command.AttachCommand; import org.apache.cloudstack.storage.command.CopyCommand; import org.apache.cloudstack.storage.command.CreateObjectAnswer; @@ -26,7 +28,6 @@ import org.apache.cloudstack.storage.command.DeleteCommand; import org.apache.cloudstack.storage.command.DettachCommand; import org.apache.cloudstack.storage.command.IntroduceObjectCmd; import org.apache.cloudstack.storage.command.StorageSubSystemCommand; -import org.apache.log4j.Logger; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; @@ -67,7 +68,9 @@ public class StorageSubsystemCommandHandlerBase implements StorageSubsystemComma DataStoreTO srcDataStore = srcData.getDataStore(); DataStoreTO destDataStore = destData.getDataStore(); - if (srcData.getObjectType() == DataObjectType.TEMPLATE && srcData.getDataStore().getRole() == DataStoreRole.Image && destData.getDataStore().getRole() == DataStoreRole.Primary) { + if (srcData.getObjectType() == DataObjectType.TEMPLATE + && (srcData.getDataStore().getRole() == DataStoreRole.Image || srcData.getDataStore().getRole() == DataStoreRole.ImageCache) + && destData.getDataStore().getRole() == DataStoreRole.Primary) { //copy template to primary storage return processor.copyTemplateToPrimaryStorage(cmd); } else if (srcData.getObjectType() == DataObjectType.TEMPLATE && srcDataStore.getRole() == DataStoreRole.Primary && destDataStore.getRole() == DataStoreRole.Primary) { diff --git a/core/src/org/apache/cloudstack/storage/to/ImageStoreTO.java b/core/src/org/apache/cloudstack/storage/to/ImageStoreTO.java index ec6c24092d3..c9bcf5b7b47 100644 --- a/core/src/org/apache/cloudstack/storage/to/ImageStoreTO.java +++ b/core/src/org/apache/cloudstack/storage/to/ImageStoreTO.java @@ -83,6 +83,11 @@ public class ImageStoreTO implements DataStoreTO { return uuid; } + @Override + public String getUrl() { + return getUri(); + } + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/core/src/org/apache/cloudstack/storage/to/PrimaryDataStoreTO.java b/core/src/org/apache/cloudstack/storage/to/PrimaryDataStoreTO.java index 91d78a49350..3141c3f1026 100644 --- a/core/src/org/apache/cloudstack/storage/to/PrimaryDataStoreTO.java +++ b/core/src/org/apache/cloudstack/storage/to/PrimaryDataStoreTO.java @@ -16,6 +16,7 @@ // under the License. package org.apache.cloudstack.storage.to; +import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; import com.cloud.agent.api.to.DataStoreTO; @@ -31,8 +32,9 @@ public class PrimaryDataStoreTO implements DataStoreTO { private String host; private String path; private int port; + private final String url; - public PrimaryDataStoreTO(PrimaryDataStoreInfo dataStore) { + public PrimaryDataStoreTO(PrimaryDataStore dataStore) { this.uuid = dataStore.getUuid(); this.name = dataStore.getName(); this.id = dataStore.getId(); @@ -40,6 +42,7 @@ public class PrimaryDataStoreTO implements DataStoreTO { this.setHost(dataStore.getHostAddress()); this.setPath(dataStore.getPath()); this.setPort(dataStore.getPort()); + this.url = dataStore.getUri(); } public long getId() { @@ -51,6 +54,11 @@ public class PrimaryDataStoreTO implements DataStoreTO { return this.uuid; } + @Override + public String getUrl() { + return this.url; + } + public String getName() { return this.name; } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStore.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStore.java similarity index 96% rename from engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStore.java rename to engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStore.java index d8b2a734792..b4d7cb911c8 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStore.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStore.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.cloudstack.storage.datastore; +package org.apache.cloudstack.engine.subsystem.api.storage; import java.util.List; diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VMSnapshotOptions.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VMSnapshotOptions.java new file mode 100644 index 00000000000..84a440d7bfb --- /dev/null +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VMSnapshotOptions.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cloudstack.engine.subsystem.api.storage; + +public class VMSnapshotOptions { + private final boolean quiesceVM; + public VMSnapshotOptions(boolean quiesceVM) { + this.quiesceVM = quiesceVM; + } + + public boolean needQuiesceVM() { + return quiesceVM; + } +} diff --git a/engine/orchestration/src/com/cloud/agent/manager/AgentAttache.java b/engine/orchestration/src/com/cloud/agent/manager/AgentAttache.java index ff35255c7db..9c87812dcc9 100755 --- a/engine/orchestration/src/com/cloud/agent/manager/AgentAttache.java +++ b/engine/orchestration/src/com/cloud/agent/manager/AgentAttache.java @@ -30,6 +30,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.cloudstack.managed.context.ManagedContextRunnable; import org.apache.log4j.Logger; @@ -107,7 +108,8 @@ public abstract class AgentAttache { protected Long _currentSequence; protected Status _status = Status.Connecting; protected boolean _maintenance; - protected long _nextSequence; + protected long _nextSequence; + protected AtomicInteger _outstandingTaskCount; protected AgentManagerImpl _agentMgr; @@ -131,6 +133,7 @@ public abstract class AgentAttache { _requests = new LinkedList(); _agentMgr = agentMgr; _nextSequence = s_rand.nextInt(Short.MAX_VALUE) << 48; + _outstandingTaskCount = new AtomicInteger(0); } public synchronized long getNextSequence() { diff --git a/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java b/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java index 3e684cc9fd4..39d470213a9 100755 --- a/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java +++ b/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java @@ -159,24 +159,28 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl protected ScheduledExecutorService _directAgentExecutor; protected ScheduledExecutorService _monitorExecutor; + private int _directAgentThreadCap; + protected StateMachine2 _statusStateMachine = Status.getStateMachine(); private final Map _pingMap = new ConcurrentHashMap(10007); @Inject ResourceManager _resourceMgr; - protected final ConfigKey Workers = new ConfigKey(Integer.class, "workers", "Advance", "5", + protected final ConfigKey Workers = new ConfigKey(Integer.class, "workers", "Advanced", "5", "Number of worker threads handling remote agent connections.", false); - protected final ConfigKey Port = new ConfigKey(Integer.class, "port", "Advance", "8250", "Port to listen on for remote agent connections.", false); - protected final ConfigKey PingInterval = new ConfigKey(Integer.class, "ping.interval", "Advance", "60", + protected final ConfigKey Port = new ConfigKey(Integer.class, "port", "Advanced", "8250", "Port to listen on for remote agent connections.", false); + protected final ConfigKey PingInterval = new ConfigKey(Integer.class, "ping.interval", "Advanced", "60", "Interval to send application level pings to make sure the connection is still working", false); - protected final ConfigKey PingTimeout = new ConfigKey(Float.class, "ping.timeout", "Advance", "2.5", + protected final ConfigKey PingTimeout = new ConfigKey(Float.class, "ping.timeout", "Advanced", "2.5", "Multiplier to ping.interval before announcing an agent has timed out", true); - protected final ConfigKey AlertWait = new ConfigKey(Integer.class, "alert.wait", "Advance", "1800", + protected final ConfigKey AlertWait = new ConfigKey(Integer.class, "alert.wait", "Advanced", "1800", "Seconds to wait before alerting on a disconnected agent", true); - protected final ConfigKey DirectAgentLoadSize = new ConfigKey(Integer.class, "direct.agent.load.size", "Advance", "16", + protected final ConfigKey DirectAgentLoadSize = new ConfigKey(Integer.class, "direct.agent.load.size", "Advanced", "16", "The number of direct agents to load each time", false); - protected final ConfigKey DirectAgentPoolSize = new ConfigKey(Integer.class, "direct.agent.pool.size", "Advance", "500", + protected final ConfigKey DirectAgentPoolSize = new ConfigKey(Integer.class, "direct.agent.pool.size", "Advanced", "500", "Default size for DirectAgentPool", false); + protected final ConfigKey DirectAgentThreadCap = new ConfigKey(Float.class, "direct.agent.thread.cap", "Advanced", "0.1", + "Percentage (as a value between 0 and 1) of direct.agent.pool.size to be used as upper thread cap for a single direct agent to process requests", false); @Override public boolean configure(final String name, final Map params) throws ConfigurationException { @@ -202,10 +206,10 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl _connection = new NioServer("AgentManager", Port.value(), Workers.value() + 10, this); s_logger.info("Listening on " + Port.value() + " with " + Workers.value() + " workers"); - _directAgentExecutor = new ScheduledThreadPoolExecutor(DirectAgentPoolSize.value(), new NamedThreadFactory("DirectAgent")); s_logger.debug("Created DirectAgentAttache pool with size: " + DirectAgentPoolSize.value()); - + _directAgentThreadCap = Math.round(DirectAgentPoolSize.value() * DirectAgentThreadCap.value()) + 1; // add 1 to always make the value > 0 + _monitorExecutor = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("AgentMonitor")); return true; @@ -1422,6 +1426,10 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl return _directAgentExecutor; } + public int getDirectAgentThreadCap() { + return _directAgentThreadCap; + } + public Long getAgentPingTime(long agentId) { return _pingMap.get(agentId); } @@ -1568,7 +1576,7 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl @Override public ConfigKey[] getConfigKeys() { - return new ConfigKey[] {Workers, Port, PingInterval, PingTimeout, Wait, AlertWait, DirectAgentLoadSize, DirectAgentPoolSize}; + return new ConfigKey[] {Workers, Port, PingInterval, PingTimeout, Wait, AlertWait, DirectAgentLoadSize, DirectAgentPoolSize, DirectAgentThreadCap}; } } diff --git a/engine/orchestration/src/com/cloud/agent/manager/DirectAgentAttache.java b/engine/orchestration/src/com/cloud/agent/manager/DirectAgentAttache.java index 7d3f7659639..0b6a0116214 100755 --- a/engine/orchestration/src/com/cloud/agent/manager/DirectAgentAttache.java +++ b/engine/orchestration/src/com/cloud/agent/manager/DirectAgentAttache.java @@ -132,6 +132,11 @@ public class DirectAgentAttache extends AgentAttache { @Override protected synchronized void runInContext() { try { + if (_outstandingTaskCount.incrementAndGet() > _agentMgr.getDirectAgentThreadCap()) { + s_logger.warn("Task execution for direct attache(" + _id + ") has reached maximum outstanding limit(" + _agentMgr.getDirectAgentThreadCap() + "), bailing out"); + return; + } + ServerResource resource = _resource; if (resource != null) { @@ -156,6 +161,8 @@ public class DirectAgentAttache extends AgentAttache { } } catch (Exception e) { s_logger.warn("Unable to complete the ping task", e); + } finally { + _outstandingTaskCount.decrementAndGet(); } } } @@ -168,10 +175,32 @@ public class DirectAgentAttache extends AgentAttache { _req = req; } + private void bailout() { + long seq = _req.getSequence(); + try { + Command[] cmds = _req.getCommands(); + ArrayList answers = new ArrayList(cmds.length); + for (Command cmd : cmds) { + Answer answer = new Answer(cmd, false, "Bailed out as maximum oustanding task limit reached"); + answers.add(answer); + } + Response resp = new Response(_req, answers.toArray(new Answer[answers.size()])); + processAnswers(seq, resp); + } catch (Exception e) { + s_logger.warn(log(seq, "Exception caught in bailout "), e); + } + } + @Override protected void runInContext() { long seq = _req.getSequence(); try { + if (_outstandingTaskCount.incrementAndGet() > _agentMgr.getDirectAgentThreadCap()) { + s_logger.warn("Task execution for direct attache(" + _id + ") has reached maximum outstanding limit(" + _agentMgr.getDirectAgentThreadCap() + "), bailing out"); + bailout(); + return; + } + ServerResource resource = _resource; Command[] cmds = _req.getCommands(); boolean stopOnError = _req.stopOnError(); @@ -186,7 +215,7 @@ public class DirectAgentAttache extends AgentAttache { if (resource != null) { answer = resource.executeRequest(cmds[i]); if(answer == null) { - s_logger.warn("Resource returned null answer!"); + s_logger.warn("Resource returned null answer!"); answer = new Answer(cmds[i], false, "Resource returned null answer"); } } else { @@ -213,6 +242,8 @@ public class DirectAgentAttache extends AgentAttache { processAnswers(seq, resp); } catch (Exception e) { s_logger.warn(log(seq, "Exception caught "), e); + } finally { + _outstandingTaskCount.decrementAndGet(); } } } 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 5636e0783b4..ddec9fcd7e4 100755 --- a/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java @@ -2187,7 +2187,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } } }); - return false; + return true; } catch ( CloudRuntimeException e ) { s_logger.error("Failed to delete network", e); return false; 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 0821c81f71a..8d841d8fd1b 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java @@ -1222,8 +1222,11 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati public void updateVolumeDiskChain(long volumeId, String path, String chainInfo) { VolumeVO vol = _volsDao.findById(volumeId); boolean needUpdate = false; + // Volume path is not getting updated in the DB, need to find reason and fix the issue. + if (vol.getPath() == null) + return; if(!vol.getPath().equalsIgnoreCase(path)) - needUpdate = true; + needUpdate = true; if(chainInfo != null && (vol.getChainInfo() == null || !chainInfo.equalsIgnoreCase(vol.getChainInfo()))) needUpdate = true; diff --git a/engine/schema/src/com/cloud/network/dao/Site2SiteVpnConnectionVO.java b/engine/schema/src/com/cloud/network/dao/Site2SiteVpnConnectionVO.java index f8eeb8a9912..d99823f2e0a 100644 --- a/engine/schema/src/com/cloud/network/dao/Site2SiteVpnConnectionVO.java +++ b/engine/schema/src/com/cloud/network/dao/Site2SiteVpnConnectionVO.java @@ -66,15 +66,19 @@ public class Site2SiteVpnConnectionVO implements Site2SiteVpnConnection, Interna @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; + @Column(name="passive") + private boolean passive; + public Site2SiteVpnConnectionVO() { } - public Site2SiteVpnConnectionVO(long accountId, long domainId, long vpnGatewayId, long customerGatewayId) { + public Site2SiteVpnConnectionVO(long accountId, long domainId, long vpnGatewayId, long customerGatewayId, boolean passive) { this.uuid = UUID.randomUUID().toString(); this.setVpnGatewayId(vpnGatewayId); this.setCustomerGatewayId(customerGatewayId); this.setState(State.Pending); this.accountId = accountId; this.domainId = domainId; + this.passive = passive; } @Override @@ -140,4 +144,12 @@ public class Site2SiteVpnConnectionVO implements Site2SiteVpnConnection, Interna public long getAccountId() { return accountId; } + + public boolean isPassive() { + return passive; + } + + public void setPassive(boolean passive) { + this.passive = passive; + } } diff --git a/engine/schema/src/com/cloud/storage/VolumeVO.java b/engine/schema/src/com/cloud/storage/VolumeVO.java index df7cfd4a749..1bdd09f9ab6 100755 --- a/engine/schema/src/com/cloud/storage/VolumeVO.java +++ b/engine/schema/src/com/cloud/storage/VolumeVO.java @@ -146,7 +146,7 @@ public class VolumeVO implements Volume { private Storage.ImageFormat format; @Column(name = "display_volume", updatable = true, nullable = false) - protected boolean displayVolume; + protected boolean displayVolume = true; @Column(name = "iscsi_name") private String _iScsiName; diff --git a/engine/schema/src/com/cloud/upgrade/DatabaseCreator.java b/engine/schema/src/com/cloud/upgrade/DatabaseCreator.java index 8260aa125e5..e8f2cc5663b 100755 --- a/engine/schema/src/com/cloud/upgrade/DatabaseCreator.java +++ b/engine/schema/src/com/cloud/upgrade/DatabaseCreator.java @@ -18,7 +18,12 @@ */ package com.cloud.upgrade; -import java.io.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; @@ -33,7 +38,6 @@ import com.cloud.utils.PropertiesUtil; import com.cloud.utils.component.ComponentContext; import com.cloud.utils.component.SystemIntegrityChecker; import com.cloud.utils.db.ScriptRunner; -import com.cloud.utils.db.Transaction; import com.cloud.utils.db.TransactionLegacy; // Creates the CloudStack Database by using the 4.0 schema and apply @@ -173,7 +177,9 @@ public class DatabaseCreator { try { TransactionLegacy.initDataSource(dbPropsFile); - } catch (NullPointerException e) { + } catch (IOException e) { + e.printStackTrace(); + System.exit(1); } initDB(dbPropsFile, rootPassword, databases, dryRun); diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade307to410.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade307to410.java index aeeb6d5863f..3edc890d603 100644 --- a/engine/schema/src/com/cloud/upgrade/dao/Upgrade307to410.java +++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade307to410.java @@ -18,21 +18,16 @@ package com.cloud.upgrade.dao; import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Properties; -import com.cloud.utils.PropertiesUtil; -import com.cloud.utils.crypt.EncryptionSecretKeyChecker; import org.apache.log4j.Logger; +import com.cloud.utils.db.DbProperties; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.Script; -import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; -import org.jasypt.properties.EncryptableProperties; public class Upgrade307to410 implements DbUpgrade { final static Logger s_logger = Logger.getLogger(Upgrade307to410.class); @@ -68,23 +63,7 @@ public class Upgrade307to410 implements DbUpgrade { } private void updateRegionEntries(Connection conn) { - File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); - final Properties dbProps; - if (EncryptionSecretKeyChecker.useEncryption()) { - StandardPBEStringEncryptor encryptor = EncryptionSecretKeyChecker.getEncryptor(); - dbProps = new EncryptableProperties(encryptor); - } else { - dbProps = new Properties(); - } - try { - dbProps.load(new FileInputStream(dbPropsFile)); - } catch (IOException e) { - s_logger.fatal("Unable to load db properties file, pl. check the classpath and file path configuration", e); - return; - } catch (NullPointerException e) { - s_logger.fatal("Unable to locate db properties file within classpath or absolute path: db.properties"); - return; - } + final Properties dbProps = DbProperties.getDbProperties(); int region_id = 1; String regionId = dbProps.getProperty("region.id"); if(regionId != null){ diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade40to41.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade40to41.java index 79ca5e1fdb1..86fe589bb18 100644 --- a/engine/schema/src/com/cloud/upgrade/dao/Upgrade40to41.java +++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade40to41.java @@ -19,9 +19,11 @@ package com.cloud.upgrade.dao; import com.cloud.utils.PropertiesUtil; import com.cloud.utils.crypt.EncryptionSecretKeyChecker; +import com.cloud.utils.db.DbProperties; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.Script; + import org.apache.log4j.Logger; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.jasypt.properties.EncryptableProperties; @@ -81,23 +83,7 @@ public class Upgrade40to41 implements DbUpgrade { } private void updateRegionEntries(Connection conn) { - File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); - final Properties dbProps; - if (EncryptionSecretKeyChecker.useEncryption()) { - StandardPBEStringEncryptor encryptor = EncryptionSecretKeyChecker.getEncryptor(); - dbProps = new EncryptableProperties(encryptor); - } else { - dbProps = new Properties(); - } - try { - dbProps.load(new FileInputStream(dbPropsFile)); - } catch (IOException e) { - s_logger.fatal("Unable to load db properties file, pl. check the classpath and file path configuration", e); - return; - } catch (NullPointerException e) { - s_logger.fatal("Unable to locate db properties file within classpath or absolute path: db.properties"); - return; - } + final Properties dbProps = DbProperties.getDbProperties(); int region_id = 1; String regionId = dbProps.getProperty("region.id"); if(regionId != null){ diff --git a/engine/schema/src/com/cloud/usage/dao/UsageDao.java b/engine/schema/src/com/cloud/usage/dao/UsageDao.java index f571b63ce40..b8335773041 100644 --- a/engine/schema/src/com/cloud/usage/dao/UsageDao.java +++ b/engine/schema/src/com/cloud/usage/dao/UsageDao.java @@ -22,13 +22,14 @@ import com.cloud.usage.UsageVO; import com.cloud.user.AccountVO; import com.cloud.user.UserStatisticsVO; import com.cloud.user.VmDiskStatisticsVO; +import com.cloud.utils.Pair; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.SearchCriteria; public interface UsageDao extends GenericDao { void deleteRecordsForAccount(Long accountId); - List searchAllRecords(SearchCriteria sc, Filter filter); + Pair, Integer> searchAndCountAllRecords(SearchCriteria sc, Filter filter); void saveAccounts(List accounts); void updateAccounts(List accounts); diff --git a/engine/schema/src/com/cloud/usage/dao/UsageDaoImpl.java b/engine/schema/src/com/cloud/usage/dao/UsageDaoImpl.java index e1e843e9ed5..c4d8ec4d6d4 100644 --- a/engine/schema/src/com/cloud/usage/dao/UsageDaoImpl.java +++ b/engine/schema/src/com/cloud/usage/dao/UsageDaoImpl.java @@ -35,6 +35,7 @@ import com.cloud.user.AccountVO; import com.cloud.user.UserStatisticsVO; import com.cloud.user.VmDiskStatisticsVO; import com.cloud.utils.DateUtil; +import com.cloud.utils.Pair; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchCriteria; @@ -93,8 +94,8 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage } @Override - public List searchAllRecords(SearchCriteria sc, Filter filter) { - return listIncludingRemovedBy(sc, filter); + public Pair, Integer> searchAndCountAllRecords(SearchCriteria sc, Filter filter) { + return listAndCountIncludingRemovedBy(sc, filter); } @Override diff --git a/engine/schema/src/com/cloud/vm/snapshot/VMSnapshotVO.java b/engine/schema/src/com/cloud/vm/snapshot/VMSnapshotVO.java index 477148cfa3b..a888c123bd8 100644 --- a/engine/schema/src/com/cloud/vm/snapshot/VMSnapshotVO.java +++ b/engine/schema/src/com/cloud/vm/snapshot/VMSnapshotVO.java @@ -31,6 +31,9 @@ import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; +import javax.persistence.Transient; + +import org.apache.cloudstack.engine.subsystem.api.storage.VMSnapshotOptions; import com.cloud.utils.db.GenericDao; @@ -90,7 +93,18 @@ public class VMSnapshotVO implements VMSnapshot { @Column(name="update_count", updatable = true, nullable=false) protected long updatedCount; - + + @Transient + VMSnapshotOptions options; + + public VMSnapshotOptions getOptions() { + return options; + } + + public void setOptions(VMSnapshotOptions options) { + this.options = options; + } + public Long getParent() { return parent; } diff --git a/engine/storage/datamotion/src/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java b/engine/storage/datamotion/src/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java index a451ca47288..67cc324bc5c 100644 --- a/engine/storage/datamotion/src/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java +++ b/engine/storage/datamotion/src/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java @@ -25,7 +25,6 @@ import javax.inject.Inject; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService; import org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope; import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; import org.apache.cloudstack.engine.subsystem.api.storage.DataMotionStrategy; @@ -46,10 +45,6 @@ import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; import org.apache.cloudstack.framework.async.AsyncCompletionCallback; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.storage.command.CopyCommand; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao; import org.apache.cloudstack.storage.image.datastore.ImageStoreEntity; import com.cloud.agent.api.Answer; @@ -62,19 +57,11 @@ import com.cloud.agent.api.to.NfsTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.configuration.Config; import com.cloud.host.Host; -import com.cloud.host.dao.HostDao; import com.cloud.server.ManagementService; import com.cloud.storage.DataStoreRole; -import com.cloud.storage.StorageManager; import com.cloud.storage.StoragePool; import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.DiskOfferingDao; -import com.cloud.storage.dao.SnapshotDao; -import com.cloud.storage.dao.VMTemplateDao; -import com.cloud.storage.dao.VMTemplatePoolDao; import com.cloud.storage.dao.VolumeDao; -import com.cloud.storage.snapshot.SnapshotManager; -import com.cloud.template.TemplateManager; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.DB; import com.cloud.utils.exception.CloudRuntimeException; @@ -177,7 +164,13 @@ AncientDataMotionStrategy implements DataMotionStrategy { CopyCommand cmd = new CopyCommand(srcForCopy.getTO(), destData.getTO(), _primaryStorageDownloadWait, _mgmtServer.getExecuteInSequence()); EndPoint ep = selector.select(srcForCopy, destData); - answer = ep.sendMessage(cmd); + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(cmd, false, errMsg); + } else { + answer = ep.sendMessage(cmd); + } if (cacheData != null) { if (srcData.getType() == DataObjectType.VOLUME && destData.getType() == DataObjectType.VOLUME) { @@ -255,7 +248,14 @@ AncientDataMotionStrategy implements DataMotionStrategy { } CopyCommand cmd = new CopyCommand(srcData.getTO(), volObj.getTO(), _createVolumeFromSnapshotWait, _mgmtServer.getExecuteInSequence()); - Answer answer = ep.sendMessage(cmd); + Answer answer = null; + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(cmd, false, errMsg); + } else { + answer = ep.sendMessage(cmd); + } return answer; } catch (Exception e) { @@ -273,7 +273,14 @@ AncientDataMotionStrategy implements DataMotionStrategy { CopyCommand cmd = new CopyCommand(template.getTO(), volume.getTO(), 0, _mgmtServer.getExecuteInSequence()); try { EndPoint ep = selector.select(volume.getDataStore()); - Answer answer = ep.sendMessage(cmd); + Answer answer = null; + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(cmd, false, errMsg); + } else { + answer = ep.sendMessage(cmd); + } return answer; } catch (Exception e) { s_logger.debug("Failed to send to storage pool", e); @@ -315,7 +322,13 @@ AncientDataMotionStrategy implements DataMotionStrategy { CopyCommand cmd = new CopyCommand(objOnImageStore.getTO(), destData.getTO(), _copyvolumewait, _mgmtServer.getExecuteInSequence()); EndPoint ep = selector.select(objOnImageStore, destData); - answer = ep.sendMessage(cmd); + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(cmd, false, errMsg); + } else { + answer = ep.sendMessage(cmd); + } if (answer == null || !answer.getResult()) { if (answer != null) { @@ -333,7 +346,14 @@ AncientDataMotionStrategy implements DataMotionStrategy { DataObject cacheData = cacheMgr.createCacheObject(srcData, destScope); CopyCommand cmd = new CopyCommand(cacheData.getTO(), destData.getTO(), _copyvolumewait, _mgmtServer.getExecuteInSequence()); EndPoint ep = selector.select(cacheData, destData); - Answer answer = ep.sendMessage(cmd); + Answer answer = null; + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(cmd, false, errMsg); + } else { + answer = ep.sendMessage(cmd); + } // delete volume on cache store if (cacheData != null) { cacheMgr.deleteCacheObject(cacheData); @@ -348,7 +368,14 @@ AncientDataMotionStrategy implements DataMotionStrategy { StoragePool destPool = (StoragePool)dataStoreMgr.getDataStore(destData.getDataStore().getId(), DataStoreRole.Primary); MigrateVolumeCommand command = new MigrateVolumeCommand(volume.getId(), volume.getPath(), destPool); EndPoint ep = selector.select(volume.getDataStore()); - MigrateVolumeAnswer answer = (MigrateVolumeAnswer) ep.sendMessage(command); + Answer answer = null; + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(command, false, errMsg); + } else { + answer = ep.sendMessage(command); + } if (answer == null || !answer.getResult()) { throw new CloudRuntimeException("Failed to migrate volume " + volume + " to storage pool " + destPool); @@ -356,7 +383,7 @@ AncientDataMotionStrategy implements DataMotionStrategy { // Update the volume details after migration. VolumeVO volumeVo = volDao.findById(volume.getId()); Long oldPoolId = volume.getPoolId(); - volumeVo.setPath(answer.getVolumePath()); + volumeVo.setPath(((MigrateVolumeAnswer)answer).getVolumePath()); volumeVo.setFolder(destPool.getPath()); volumeVo.setPodId(destPool.getPodId()); volumeVo.setPoolId(destPool.getId()); @@ -431,7 +458,14 @@ AncientDataMotionStrategy implements DataMotionStrategy { } CopyCommand cmd = new CopyCommand(srcData.getTO(), destData.getTO(), _createprivatetemplatefromsnapshotwait, _mgmtServer.getExecuteInSequence()); - Answer answer = ep.sendMessage(cmd); + Answer answer = null; + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(cmd, false, errMsg); + } else { + answer = ep.sendMessage(cmd); + } // clean up snapshot copied to staging if (needCache && srcData != null) { @@ -455,11 +489,23 @@ AncientDataMotionStrategy implements DataMotionStrategy { CopyCommand cmd = new CopyCommand(srcData.getTO(), destData.getTO(), _backupsnapshotwait, _mgmtServer.getExecuteInSequence()); cmd.setCacheTO(cacheData.getTO()); EndPoint ep = selector.select(srcData, destData); - answer = ep.sendMessage(cmd); + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(cmd, false, errMsg); + } else { + answer = ep.sendMessage(cmd); + } } else { CopyCommand cmd = new CopyCommand(srcData.getTO(), destData.getTO(), _backupsnapshotwait, _mgmtServer.getExecuteInSequence()); EndPoint ep = selector.select(srcData, destData); - answer = ep.sendMessage(cmd); + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(cmd, false, errMsg); + } else { + answer = ep.sendMessage(cmd); + } } // clean up cache entry in case of failure if (answer == null || !answer.getResult()) { 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 ce6198dc21e..308347d8a38 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 @@ -172,12 +172,26 @@ public class TemplateServiceImpl implements TemplateService { return; } - TemplateOpContext context = new TemplateOpContext(callback, - templateOnStore, null); + try { + TemplateOpContext context = new TemplateOpContext(callback, + templateOnStore, null); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); - caller.setCallback(caller.getTarget().createTemplateCallback(null, null)).setContext(context); - store.getDriver().createAsync(store, templateOnStore, caller); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); + caller.setCallback(caller.getTarget().createTemplateCallback(null, null)).setContext(context); + store.getDriver().createAsync(store, templateOnStore, caller); + } catch (CloudRuntimeException ex) { + // clean up already persisted template_store_ref entry in case of createTemplateCallback is never called + TemplateDataStoreVO templateStoreVO = _vmTemplateStoreDao.findByStoreTemplate(store.getId(), template.getId()); + if (templateStoreVO != null) { + TemplateInfo tmplObj = _templateFactory.getTemplate(template, store); + tmplObj.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); + } + TemplateApiResult result = new TemplateApiResult(template); + result.setResult(ex.getMessage()); + if (callback != null) { + callback.complete(result); + } + } } @Override @@ -441,7 +455,14 @@ public class TemplateServiceImpl implements TemplateService { tmplTO.setId(tInfo.getId()); DeleteCommand dtCommand = new DeleteCommand(tmplTO); EndPoint ep = _epSelector.select(store); - Answer answer = ep.sendMessage(dtCommand); + Answer answer = null; + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(dtCommand, false, errMsg); + } else { + answer = ep.sendMessage(dtCommand); + } if (answer == null || !answer.getResult()) { s_logger.info("Failed to deleted template at store: " + store.getName()); @@ -513,7 +534,14 @@ public class TemplateServiceImpl implements TemplateService { private Map listTemplate(DataStore ssStore) { ListTemplateCommand cmd = new ListTemplateCommand(ssStore.getTO()); EndPoint ep = _epSelector.select(ssStore); - Answer answer = ep.sendMessage(cmd); + Answer answer = null; + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(cmd, false, errMsg); + } else { + answer = ep.sendMessage(cmd); + } if (answer != null && answer.getResult()) { ListTemplateAnswer tanswer = (ListTemplateAnswer) answer; return tanswer.getTemplateInfo(); @@ -718,11 +746,23 @@ public class TemplateServiceImpl implements TemplateService { if (s_logger.isDebugEnabled()) { s_logger.debug("Invoke datastore driver createAsync to create template on destination store"); } - TemplateOpContext context = new TemplateOpContext(null, - (TemplateObject) templateOnStore, future); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); - caller.setCallback(caller.getTarget().copyTemplateCrossZoneCallBack(null, null)).setContext(context); - destStore.getDriver().createAsync(destStore, templateOnStore, caller); + try { + TemplateOpContext context = new TemplateOpContext(null, + (TemplateObject)templateOnStore, future); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); + caller.setCallback(caller.getTarget().copyTemplateCrossZoneCallBack(null, null)).setContext(context); + destStore.getDriver().createAsync(destStore, templateOnStore, caller); + } catch (CloudRuntimeException ex) { + // clean up already persisted template_store_ref entry in case of createTemplateCallback is never called + TemplateDataStoreVO templateStoreVO = _vmTemplateStoreDao.findByStoreTemplate(destStore.getId(), srcTemplate.getId()); + if (templateStoreVO != null) { + TemplateInfo tmplObj = _templateFactory.getTemplate(srcTemplate, destStore); + tmplObj.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); + } + TemplateApiResult res = new TemplateApiResult((TemplateObject)templateOnStore); + res.setResult(ex.getMessage()); + future.complete(res); + } return future; } diff --git a/engine/storage/integration-test/pom.xml b/engine/storage/integration-test/pom.xml index dc4065e5988..4e5fdeb7eb9 100644 --- a/engine/storage/integration-test/pom.xml +++ b/engine/storage/integration-test/pom.xml @@ -185,5 +185,38 @@ + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-antrun-plugin + + [1.7,) + + run + + + + + + + + + + + + diff --git a/engine/storage/integration-test/test/resources/storageContext.xml b/engine/storage/integration-test/test/resources/storageContext.xml index 0dcd6a83407..c9845157afd 100644 --- a/engine/storage/integration-test/test/resources/storageContext.xml +++ b/engine/storage/integration-test/test/resources/storageContext.xml @@ -85,10 +85,7 @@ -<<<<<<< HEAD -======= ->>>>>>> pluggable_vm_snapshot diff --git a/engine/storage/resources/META-INF/cloudstack/core/spring-engine-storage-core-context.xml b/engine/storage/resources/META-INF/cloudstack/core/spring-engine-storage-core-context.xml index 76ec23e37d1..8040d801b3e 100644 --- a/engine/storage/resources/META-INF/cloudstack/core/spring-engine-storage-core-context.xml +++ b/engine/storage/resources/META-INF/cloudstack/core/spring-engine-storage-core-context.xml @@ -38,6 +38,9 @@ + + diff --git a/engine/storage/snapshot/resources/META-INF/cloudstack/storage/spring-engine-storage-snapshot-storage-context.xml b/engine/storage/snapshot/resources/META-INF/cloudstack/storage/spring-engine-storage-snapshot-storage-context.xml index d25aeea0250..72997509130 100644 --- a/engine/storage/snapshot/resources/META-INF/cloudstack/storage/spring-engine-storage-snapshot-storage-context.xml +++ b/engine/storage/snapshot/resources/META-INF/cloudstack/storage/spring-engine-storage-snapshot-storage-context.xml @@ -33,6 +33,4 @@ - diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotServiceImpl.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotServiceImpl.java index 0799721312d..9b73bea5211 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotServiceImpl.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotServiceImpl.java @@ -40,7 +40,7 @@ import org.apache.cloudstack.framework.async.AsyncCompletionCallback; import org.apache.cloudstack.framework.async.AsyncRpcContext; import org.apache.cloudstack.storage.command.CommandResult; import org.apache.cloudstack.storage.command.CopyCmdAnswer; -import org.apache.cloudstack.storage.datastore.PrimaryDataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; import org.apache.log4j.Logger; diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreProviderManager.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreProviderManager.java index 8613668b180..bb7911df811 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreProviderManager.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreProviderManager.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.storage.datastore; import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; +import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; public interface PrimaryDataStoreProviderManager { diff --git a/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java b/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java index 196b08b2f42..ce83790a4f5 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java +++ b/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java @@ -27,15 +27,17 @@ import java.util.List; import javax.inject.Inject; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; + import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; import org.apache.cloudstack.engine.subsystem.api.storage.Scope; +import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; import org.apache.cloudstack.storage.LocalHostEndpoint; import org.apache.cloudstack.storage.RemoteHostEndPoint; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; import com.cloud.host.Host; import com.cloud.host.HostVO; @@ -43,10 +45,10 @@ import com.cloud.host.Status; import com.cloud.host.dao.HostDao; import com.cloud.storage.DataStoreRole; import com.cloud.storage.ScopeType; +import com.cloud.storage.Storage.TemplateType; import com.cloud.utils.db.DB; import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.Transaction; import com.cloud.utils.db.TransactionLegacy; import com.cloud.utils.exception.CloudRuntimeException; @@ -185,6 +187,16 @@ public class DefaultEndPointSelector implements EndPointSelector { selectedStore = destStore; } EndPoint ep = findEndpointForImageStorage(selectedStore); + if (ep != null) { + return ep; + } + // handle special case where it is used in deploying ssvm for S3 + if (srcData instanceof TemplateInfo) { + TemplateInfo tmpl = (TemplateInfo)srcData; + if (tmpl.getTemplateType() == TemplateType.SYSTEM) { + ep = LocalHostEndpoint.getEndpoint(); + } + } return ep; } else if (moveBetweenImages(srcStore, destStore)) { EndPoint ep = findEndpointForImageStorage(destStore); @@ -209,9 +221,7 @@ public class DefaultEndPointSelector implements EndPointSelector { // we can arbitrarily pick one ssvm to do that task List ssAHosts = listUpAndConnectingSecondaryStorageVmHost(dcId); if (ssAHosts == null || ssAHosts.isEmpty()) { - s_logger.info("No running ssvm is found, so command will be sent to LocalHostEndPoint"); - return LocalHostEndpoint.getEndpoint(); // use local host as endpoint in - // case of no ssvm existing + return null; } Collections.shuffle(ssAHosts); HostVO host = ssAHosts.get(0); @@ -232,7 +242,16 @@ public class DefaultEndPointSelector implements EndPointSelector { @Override public EndPoint select(DataObject object) { DataStore store = object.getDataStore(); - return select(store); + EndPoint ep = select(store); + if (ep != null) + return ep; + if (object instanceof TemplateInfo) { + TemplateInfo tmplInfo = (TemplateInfo)object; + if (store.getScope().getScopeType() == ScopeType.ZONE && store.getScope().getScopeId() == null && tmplInfo.getTemplateType() == TemplateType.SYSTEM) { + return LocalHostEndpoint.getEndpoint(); // for bootstrap system vm template downloading to region image store + } + } + return null; } @Override diff --git a/engine/storage/src/org/apache/cloudstack/storage/helper/HypervisorHelper.java b/engine/storage/src/org/apache/cloudstack/storage/helper/HypervisorHelper.java index 40ced1d832c..f22659947ee 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/helper/HypervisorHelper.java +++ b/engine/storage/src/org/apache/cloudstack/storage/helper/HypervisorHelper.java @@ -18,14 +18,15 @@ */ package org.apache.cloudstack.storage.helper; -import com.cloud.agent.api.to.DataTO; -import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; import org.apache.cloudstack.engine.subsystem.api.storage.Scope; -import org.apache.cloudstack.storage.to.SnapshotObjectTO; + +import com.cloud.agent.api.VMSnapshotTO; +import com.cloud.agent.api.to.DataTO; +import com.cloud.vm.VirtualMachine; public interface HypervisorHelper { DataTO introduceObject(DataTO object, Scope scope, Long storeId); boolean forgetObject(DataTO object, Scope scope, Long storeId); - SnapshotObjectTO takeSnapshot(SnapshotObjectTO snapshotObjectTO, Scope scope); - boolean revertSnapshot(SnapshotObjectTO snapshotObjectTO, Scope scope); + VMSnapshotTO quiesceVm(VirtualMachine virtualMachine); + boolean unquiesceVM(VirtualMachine virtualMachine, VMSnapshotTO vmSnapshotTO); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/helper/HypervisorHelperImpl.java b/engine/storage/src/org/apache/cloudstack/storage/helper/HypervisorHelperImpl.java index 81e6f7c69c5..7dbd35cf254 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/helper/HypervisorHelperImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/helper/HypervisorHelperImpl.java @@ -18,30 +18,63 @@ */ package org.apache.cloudstack.storage.helper; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.to.DataTO; -import com.cloud.utils.exception.CloudRuntimeException; +import java.util.List; +import java.util.UUID; + +import javax.inject.Inject; + +import org.apache.log4j.Logger; + import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; import org.apache.cloudstack.engine.subsystem.api.storage.Scope; +import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.storage.command.ForgetObjectCmd; import org.apache.cloudstack.storage.command.IntroduceObjectAnswer; import org.apache.cloudstack.storage.command.IntroduceObjectCmd; -import org.apache.cloudstack.storage.to.SnapshotObjectTO; -import org.apache.log4j.Logger; +import org.apache.cloudstack.storage.vmsnapshot.VMSnapshotHelper; +import org.apache.cloudstack.storage.to.VolumeObjectTO; -import javax.inject.Inject; +import com.cloud.agent.AgentManager; +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.CreateVMSnapshotAnswer; +import com.cloud.agent.api.CreateVMSnapshotCommand; +import com.cloud.agent.api.DeleteVMSnapshotCommand; +import com.cloud.agent.api.VMSnapshotTO; +import com.cloud.agent.api.to.DataTO; +import com.cloud.exception.AgentUnavailableException; +import com.cloud.exception.OperationTimedoutException; +import com.cloud.storage.GuestOSVO; +import com.cloud.storage.dao.GuestOSDao; +import com.cloud.utils.NumbersUtil; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.snapshot.VMSnapshot; public class HypervisorHelperImpl implements HypervisorHelper { private static final Logger s_logger = Logger.getLogger(HypervisorHelperImpl.class); @Inject EndPointSelector selector; - + @Inject + VMSnapshotHelper vmSnapshotHelper; + @Inject + GuestOSDao guestOSDao; + @Inject + ConfigurationDao configurationDao; + @Inject + AgentManager agentMgr; @Override public DataTO introduceObject(DataTO object, Scope scope, Long storeId) { EndPoint ep = selector.select(scope, storeId); IntroduceObjectCmd cmd = new IntroduceObjectCmd(object); - Answer answer = ep.sendMessage(cmd); + Answer answer = null; + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(cmd, false, errMsg); + } else { + answer = ep.sendMessage(cmd); + } if (answer == null || !answer.getResult()) { String errMsg = answer == null ? null : answer.getDetails(); throw new CloudRuntimeException("Failed to introduce object, due to " + errMsg); @@ -54,7 +87,14 @@ public class HypervisorHelperImpl implements HypervisorHelper { public boolean forgetObject(DataTO object, Scope scope, Long storeId) { EndPoint ep = selector.select(scope, storeId); ForgetObjectCmd cmd = new ForgetObjectCmd(object); - Answer answer = ep.sendMessage(cmd); + Answer answer = null; + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(cmd, false, errMsg); + } else { + answer = ep.sendMessage(cmd); + } if (answer == null || !answer.getResult()) { String errMsg = answer == null ? null : answer.getDetails(); if (errMsg != null) { @@ -66,12 +106,52 @@ public class HypervisorHelperImpl implements HypervisorHelper { } @Override - public SnapshotObjectTO takeSnapshot(SnapshotObjectTO snapshotObjectTO, Scope scope) { - return null; //To change body of implemented methods use File | Settings | File Templates. + public VMSnapshotTO quiesceVm(VirtualMachine virtualMachine) { + String value = configurationDao.getValue("vmsnapshot.create.wait"); + int wait = NumbersUtil.parseInt(value, 1800); + Long hostId = vmSnapshotHelper.pickRunningHost(virtualMachine.getId()); + VMSnapshotTO vmSnapshotTO = new VMSnapshotTO(1L, UUID.randomUUID().toString(), VMSnapshot.Type.DiskAndMemory, null, null, false, + null); + GuestOSVO guestOS = guestOSDao.findById(virtualMachine.getGuestOSId()); + List volumeTOs = vmSnapshotHelper.getVolumeTOList(virtualMachine.getId()); + CreateVMSnapshotCommand ccmd = new CreateVMSnapshotCommand(virtualMachine.getInstanceName(),vmSnapshotTO ,volumeTOs, guestOS.getDisplayName(),virtualMachine.getState()); + ccmd.setWait(wait); + try { + Answer answer = agentMgr.send(hostId, ccmd); + if (answer != null && answer.getResult()) { + CreateVMSnapshotAnswer snapshotAnswer = (CreateVMSnapshotAnswer)answer; + vmSnapshotTO.setVolumes(snapshotAnswer.getVolumeTOs()); + } else { + String errMsg = (answer != null) ? answer.getDetails() : null; + throw new CloudRuntimeException("Failed to quiesce vm, due to " + errMsg); + } + } catch (AgentUnavailableException e) { + throw new CloudRuntimeException("Failed to quiesce vm", e); + } catch (OperationTimedoutException e) { + throw new CloudRuntimeException("Failed to quiesce vm", e); + } + return vmSnapshotTO; } @Override - public boolean revertSnapshot(SnapshotObjectTO snapshotObjectTO, Scope scope) { - return false; //To change body of implemented methods use File | Settings | File Templates. + public boolean unquiesceVM(VirtualMachine virtualMachine, VMSnapshotTO vmSnapshotTO) { + Long hostId = vmSnapshotHelper.pickRunningHost(virtualMachine.getId()); + List volumeTOs = vmSnapshotHelper.getVolumeTOList(virtualMachine.getId()); + GuestOSVO guestOS = guestOSDao.findById(virtualMachine.getGuestOSId()); + + DeleteVMSnapshotCommand deleteSnapshotCommand = new DeleteVMSnapshotCommand(virtualMachine.getInstanceName(), vmSnapshotTO, volumeTOs, guestOS.getDisplayName()); + try { + Answer answer = agentMgr.send(hostId, deleteSnapshotCommand); + if (answer != null && answer.getResult()) { + return true; + } else { + String errMsg = (answer != null) ? answer.getDetails() : null; + throw new CloudRuntimeException("Failed to unquiesce vm, due to " + errMsg); + } + } catch (AgentUnavailableException e) { + throw new CloudRuntimeException("Failed to unquiesce vm", e); + } catch (OperationTimedoutException e) { + throw new CloudRuntimeException("Failed to unquiesce vm", e); + } } } diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/vmsnapshot/VMSnapshotHelperImpl.java b/engine/storage/src/org/apache/cloudstack/storage/helper/VMSnapshotHelperImpl.java similarity index 97% rename from engine/storage/snapshot/src/org/apache/cloudstack/storage/vmsnapshot/VMSnapshotHelperImpl.java rename to engine/storage/src/org/apache/cloudstack/storage/helper/VMSnapshotHelperImpl.java index 320a59ce207..1200be89629 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/vmsnapshot/VMSnapshotHelperImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/helper/VMSnapshotHelperImpl.java @@ -16,16 +16,27 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.cloudstack.storage.vmsnapshot; +package org.apache.cloudstack.storage.helper; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; + +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; +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.storage.vmsnapshot.VMSnapshotHelper; import com.cloud.agent.api.VMSnapshotTO; -import com.cloud.agent.api.to.DataTO; -import com.cloud.agent.api.to.VolumeTO; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; -import com.cloud.storage.StoragePool; import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.VolumeDao; import com.cloud.utils.fsm.NoTransitionException; @@ -36,17 +47,6 @@ import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.snapshot.VMSnapshot; import com.cloud.vm.snapshot.VMSnapshotVO; import com.cloud.vm.snapshot.dao.VMSnapshotDao; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.cloudstack.storage.to.VolumeObjectTO; - -import javax.inject.Inject; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; public class VMSnapshotHelperImpl implements VMSnapshotHelper { @Inject diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/BaseImageStoreDriverImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/BaseImageStoreDriverImpl.java index 3a70d8fcc55..bd93e73e0ef 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/BaseImageStoreDriverImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/BaseImageStoreDriverImpl.java @@ -18,17 +18,13 @@ */ package org.apache.cloudstack.storage.image; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.storage.DownloadAnswer; -import com.cloud.agent.api.storage.Proxy; -import com.cloud.agent.api.to.DataObjectType; -import com.cloud.agent.api.to.DataTO; -import com.cloud.storage.VMTemplateStorageResourceAssoc; -import com.cloud.storage.VMTemplateVO; -import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.VMTemplateDao; -import com.cloud.storage.dao.VolumeDao; -import com.cloud.storage.download.DownloadMonitor; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Date; + +import javax.inject.Inject; + +import org.apache.log4j.Logger; import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; @@ -47,13 +43,17 @@ import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO; -import org.apache.log4j.Logger; - -import javax.inject.Inject; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Date; +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.storage.DownloadAnswer; +import com.cloud.agent.api.storage.Proxy; +import com.cloud.agent.api.to.DataObjectType; +import com.cloud.agent.api.to.DataTO; +import com.cloud.storage.VMTemplateStorageResourceAssoc; +import com.cloud.storage.VMTemplateVO; +import com.cloud.storage.VolumeVO; +import com.cloud.storage.dao.VMTemplateDao; +import com.cloud.storage.dao.VolumeDao; +import com.cloud.storage.download.DownloadMonitor; public abstract class BaseImageStoreDriverImpl implements ImageStoreDriver { private static final Logger s_logger = Logger.getLogger(BaseImageStoreDriverImpl.class); @@ -239,7 +239,14 @@ public abstract class BaseImageStoreDriverImpl implements ImageStoreDriver { try { DeleteCommand cmd = new DeleteCommand(data.getTO()); EndPoint ep = _epSelector.select(data); - Answer answer = ep.sendMessage(cmd); + Answer answer = null; + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(cmd, false, errMsg); + } else { + answer = ep.sendMessage(cmd); + } if (answer != null && !answer.getResult()) { result.setResult(answer.getDetails()); } diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/vmsnapshot/VMSnapshotHelper.java b/engine/storage/src/org/apache/cloudstack/storage/vmsnapshot/VMSnapshotHelper.java similarity index 97% rename from engine/storage/snapshot/src/org/apache/cloudstack/storage/vmsnapshot/VMSnapshotHelper.java rename to engine/storage/src/org/apache/cloudstack/storage/vmsnapshot/VMSnapshotHelper.java index 1437f800c21..9ee2f85dd3e 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/vmsnapshot/VMSnapshotHelper.java +++ b/engine/storage/src/org/apache/cloudstack/storage/vmsnapshot/VMSnapshotHelper.java @@ -18,14 +18,14 @@ */ package org.apache.cloudstack.storage.vmsnapshot; +import java.util.List; + +import org.apache.cloudstack.storage.to.VolumeObjectTO; + import com.cloud.agent.api.VMSnapshotTO; -import com.cloud.agent.api.to.DataTO; import com.cloud.utils.fsm.NoTransitionException; import com.cloud.vm.snapshot.VMSnapshot; import com.cloud.vm.snapshot.VMSnapshotVO; -import org.apache.cloudstack.storage.to.VolumeObjectTO; - -import java.util.List; public interface VMSnapshotHelper { boolean vmSnapshotStateTransitTo(VMSnapshot vsnp, VMSnapshot.Event event) throws NoTransitionException; diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/TemplateOnPrimaryDataStoreInfo.java b/engine/storage/src/org/apache/cloudstack/storage/volume/TemplateOnPrimaryDataStoreInfo.java index b8d0857d495..5026f3e145f 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/TemplateOnPrimaryDataStoreInfo.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/TemplateOnPrimaryDataStoreInfo.java @@ -19,7 +19,7 @@ package org.apache.cloudstack.storage.volume; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; -import org.apache.cloudstack.storage.datastore.PrimaryDataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore; public interface TemplateOnPrimaryDataStoreInfo { public String getPath(); diff --git a/engine/storage/storage.ucls b/engine/storage/storage.ucls index 23a7b21fe00..4de955db04d 100644 --- a/engine/storage/storage.ucls +++ b/engine/storage/storage.ucls @@ -103,7 +103,7 @@ diff --git a/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreImpl.java b/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreImpl.java index 2d99c9b6b48..cb502e9e260 100644 --- a/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreImpl.java +++ b/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreImpl.java @@ -23,23 +23,9 @@ import java.util.List; import javax.inject.Inject; +import org.apache.cloudstack.engine.subsystem.api.storage.*; import org.apache.log4j.Logger; -import org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope; -import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreDriver; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider; -import org.apache.cloudstack.engine.subsystem.api.storage.HostScope; -import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreLifeCycle; -import org.apache.cloudstack.engine.subsystem.api.storage.Scope; -import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; -import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory; -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; import org.apache.cloudstack.engine.subsystem.api.storage.disktype.DiskFormat; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; diff --git a/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/manager/PrimaryDataStoreProviderManagerImpl.java b/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/manager/PrimaryDataStoreProviderManagerImpl.java index db14f6d27a3..81919ec7689 100644 --- a/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/manager/PrimaryDataStoreProviderManagerImpl.java +++ b/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/manager/PrimaryDataStoreProviderManagerImpl.java @@ -29,7 +29,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProviderManag import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; import org.apache.cloudstack.storage.datastore.PrimaryDataStoreImpl; -import org.apache.cloudstack.storage.datastore.PrimaryDataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore; import org.apache.cloudstack.storage.datastore.PrimaryDataStoreProviderManager; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; 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 870363afb24..5818aa8d924 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 @@ -18,6 +18,49 @@ */ package org.apache.cloudstack.storage.volume; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +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; +import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; +import org.apache.cloudstack.engine.subsystem.api.storage.DataMotionService; +import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreDriver; +import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; +import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; +import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; +import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; +import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; +import org.apache.cloudstack.engine.subsystem.api.storage.Scope; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService; +import org.apache.cloudstack.framework.async.AsyncCallFuture; +import org.apache.cloudstack.framework.async.AsyncCallbackDispatcher; +import org.apache.cloudstack.framework.async.AsyncCompletionCallback; +import org.apache.cloudstack.framework.async.AsyncRpcContext; +import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.cloudstack.storage.command.CommandResult; +import org.apache.cloudstack.storage.command.CopyCmdAnswer; +import org.apache.cloudstack.storage.command.DeleteCommand; +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 com.cloud.agent.api.Answer; import com.cloud.agent.api.storage.ListVolumeAnswer; import com.cloud.agent.api.storage.ListVolumeCommand; @@ -49,46 +92,6 @@ import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.DB; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.exception.CloudRuntimeException; -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; -import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; -import org.apache.cloudstack.engine.subsystem.api.storage.DataMotionService; -import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreDriver; -import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; -import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; -import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; -import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; -import org.apache.cloudstack.engine.subsystem.api.storage.Scope; -import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService; -import org.apache.cloudstack.framework.async.AsyncCallFuture; -import org.apache.cloudstack.framework.async.AsyncCallbackDispatcher; -import org.apache.cloudstack.framework.async.AsyncCompletionCallback; -import org.apache.cloudstack.framework.async.AsyncRpcContext; -import org.apache.cloudstack.framework.config.dao.ConfigurationDao; -import org.apache.cloudstack.storage.command.CommandResult; -import org.apache.cloudstack.storage.command.CopyCmdAnswer; -import org.apache.cloudstack.storage.command.DeleteCommand; -import org.apache.cloudstack.storage.datastore.PrimaryDataStore; -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 javax.inject.Inject; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; @Component public class VolumeServiceImpl implements VolumeService { @@ -162,12 +165,24 @@ public class VolumeServiceImpl implements VolumeService { DataObject volumeOnStore = dataStore.create(volume); volumeOnStore.processEvent(Event.CreateOnlyRequested); - CreateVolumeContext context = new CreateVolumeContext(null, volumeOnStore, - future); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); - caller.setCallback(caller.getTarget().createVolumeCallback(null, null)).setContext(context); + try { + CreateVolumeContext context = new CreateVolumeContext(null, volumeOnStore, + future); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); + caller.setCallback(caller.getTarget().createVolumeCallback(null, null)).setContext(context); - dataStore.getDriver().createAsync(dataStore, volumeOnStore, caller); + dataStore.getDriver().createAsync(dataStore, volumeOnStore, caller); + } catch (CloudRuntimeException ex) { + // clean up already persisted volume_store_ref entry in case of createVolumeCallback is never called + VolumeDataStoreVO volStoreVO = _volumeStoreDao.findByStoreVolume(dataStore.getId(), volume.getId()); + if (volStoreVO != null) { + VolumeInfo volObj = volFactory.getVolume(volume, dataStore); + volObj.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); + } + VolumeApiResult volResult = new VolumeApiResult((VolumeObject)volumeOnStore); + volResult.setResult(ex.getMessage()); + future.complete(volResult); + } return future; } @@ -438,6 +453,7 @@ public class VolumeServiceImpl implements VolumeService { } catch (Throwable e) { s_logger.debug("failed to create template on storage", e); templateOnPrimaryStoreObj.processEvent(Event.OperationFailed); + dataStore.create(template); // make sure that template_spool_ref entry is still present so that the second thread can acquire the lock VolumeApiResult result = new VolumeApiResult(volume); result.setResult(e.toString()); future.complete(result); @@ -1019,13 +1035,25 @@ public class VolumeServiceImpl implements VolumeService { volumeOnStore.processEvent(Event.CreateOnlyRequested); - CreateVolumeContext context = new CreateVolumeContext(null, volumeOnStore, - future); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); - caller.setCallback(caller.getTarget().registerVolumeCallback(null, null)); - caller.setContext(context); + try { + CreateVolumeContext context = new CreateVolumeContext(null, volumeOnStore, + future); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); + caller.setCallback(caller.getTarget().registerVolumeCallback(null, null)); + caller.setContext(context); - store.getDriver().createAsync(store, volumeOnStore, caller); + store.getDriver().createAsync(store, volumeOnStore, caller); + } catch (CloudRuntimeException ex) { + // clean up already persisted volume_store_ref entry in case of createVolumeCallback is never called + VolumeDataStoreVO volStoreVO = _volumeStoreDao.findByStoreVolume(store.getId(), volume.getId()); + if (volStoreVO != null) { + VolumeInfo volObj = volFactory.getVolume(volume, store); + volObj.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); + } + VolumeApiResult res = new VolumeApiResult((VolumeObject)volumeOnStore); + res.setResult(ex.getMessage()); + future.complete(res); + } return future; } @@ -1255,7 +1283,14 @@ public class VolumeServiceImpl implements VolumeService { tmplTO.setId(tInfo.getId()); DeleteCommand dtCommand = new DeleteCommand(tmplTO); EndPoint ep = _epSelector.select(store); - Answer answer = ep.sendMessage(dtCommand); + Answer answer = null; + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(dtCommand, false, errMsg); + } else { + answer = ep.sendMessage(dtCommand); + } if (answer == null || !answer.getResult()) { s_logger.info("Failed to deleted volume at store: " + store.getName()); @@ -1280,7 +1315,14 @@ public class VolumeServiceImpl implements VolumeService { private Map listVolume(DataStore store) { ListVolumeCommand cmd = new ListVolumeCommand(store.getTO(), store.getUri()); EndPoint ep = _epSelector.select(store); - Answer answer = ep.sendMessage(cmd); + Answer answer = null; + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(cmd, false, errMsg); + } else { + answer = ep.sendMessage(cmd); + } if (answer != null && answer.getResult()) { ListVolumeAnswer tanswer = (ListVolumeAnswer) answer; return tanswer.getTemplateInfo(); diff --git a/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java b/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java index 71bea4f2e4f..1c10a95c328 100644 --- a/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java +++ b/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java @@ -59,6 +59,7 @@ import com.cloud.utils.component.ManagerBase; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.ConnectionConcierge; import com.cloud.utils.db.DB; +import com.cloud.utils.db.DbProperties; import com.cloud.utils.db.Transaction; import com.cloud.utils.db.TransactionCallback; import com.cloud.utils.db.TransactionLegacy; @@ -1029,15 +1030,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C s_logger.info("Start configuring cluster manager : " + name); } - File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); - Properties dbProps = new Properties(); - try { - PropertiesUtil.loadFromFile(dbProps, dbPropsFile); - } catch (FileNotFoundException e) { - throw new ConfigurationException("Unable to find db.properties"); - } catch (IOException e) { - throw new ConfigurationException("Unable to load db.properties content"); - } + Properties dbProps = DbProperties.getDbProperties(); _clusterNodeIP = dbProps.getProperty("cluster.node.IP"); if (_clusterNodeIP == null) { _clusterNodeIP = "127.0.0.1"; diff --git a/framework/cluster/src/com/cloud/cluster/ClusterServiceServletAdapter.java b/framework/cluster/src/com/cloud/cluster/ClusterServiceServletAdapter.java index f80e21f1d34..ebbbe984c5b 100644 --- a/framework/cluster/src/com/cloud/cluster/ClusterServiceServletAdapter.java +++ b/framework/cluster/src/com/cloud/cluster/ClusterServiceServletAdapter.java @@ -16,9 +16,6 @@ // under the License. package com.cloud.cluster; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; import java.rmi.RemoteException; import java.util.Map; import java.util.Properties; @@ -26,14 +23,13 @@ import java.util.Properties; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.log4j.Logger; - import org.apache.cloudstack.framework.config.ConfigDepot; +import org.apache.log4j.Logger; import com.cloud.cluster.dao.ManagementServerHostDao; import com.cloud.utils.NumbersUtil; -import com.cloud.utils.PropertiesUtil; import com.cloud.utils.component.AdapterBase; +import com.cloud.utils.db.DbProperties; public class ClusterServiceServletAdapter extends AdapterBase implements ClusterServiceAdapter { @@ -122,15 +118,7 @@ public class ClusterServiceServletAdapter extends AdapterBase implements Cluster if (_mshostDao != null) return; - File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); - Properties dbProps = new Properties(); - try { - PropertiesUtil.loadFromFile(dbProps, dbPropsFile); - } catch (FileNotFoundException e) { - throw new ConfigurationException("Unable to find db.properties"); - } catch (IOException e) { - throw new ConfigurationException("Unable to load db.properties content"); - } + Properties dbProps = DbProperties.getDbProperties(); _clusterServicePort = NumbersUtil.parseInt(dbProps.getProperty("cluster.servlet.port"), DEFAULT_SERVICE_PORT); if (s_logger.isInfoEnabled()) diff --git a/framework/db/src/com/cloud/utils/db/GenericDaoBase.java b/framework/db/src/com/cloud/utils/db/GenericDaoBase.java index ba5200ea65f..177cd5b6401 100755 --- a/framework/db/src/com/cloud/utils/db/GenericDaoBase.java +++ b/framework/db/src/com/cloud/utils/db/GenericDaoBase.java @@ -1864,4 +1864,11 @@ public abstract class GenericDaoBase extends Compone return sql; } + + @DB() + protected Pair, Integer> listAndCountIncludingRemovedBy(final SearchCriteria sc, final Filter filter) { + List objects = searchIncludingRemoved(sc, filter, null, false); + Integer count = getCount(sc); + return new Pair, Integer>(objects, count); + } } diff --git a/framework/db/src/com/cloud/utils/db/TransactionLegacy.java b/framework/db/src/com/cloud/utils/db/TransactionLegacy.java index a318d83f92b..a874ce10a56 100755 --- a/framework/db/src/com/cloud/utils/db/TransactionLegacy.java +++ b/framework/db/src/com/cloud/utils/db/TransactionLegacy.java @@ -93,12 +93,6 @@ public class TransactionLegacy { } catch (Exception e) { s_logger.error("Unable to register mbean for transaction", e); } - - /* FIXME: We need a better solution for this - * Initialize encryption if we need it for db.properties - */ - EncryptionSecretKeyChecker enc = new EncryptionSecretKeyChecker(); - enc.check(); } private final LinkedList _stack; @@ -1025,30 +1019,23 @@ public class TransactionLegacy { static { // Initialize with assumed db.properties file - initDataSource("db.properties"); + initDataSource(DbProperties.getDbProperties()); } - public static void initDataSource(String propsFileName) { - try { - File dbPropsFile = PropertiesUtil.findConfigFile(propsFileName); - final Properties dbProps; - if (EncryptionSecretKeyChecker.useEncryption()) { - StandardPBEStringEncryptor encryptor = EncryptionSecretKeyChecker.getEncryptor(); - dbProps = new EncryptableProperties(encryptor); - } else { - dbProps = new Properties(); - } - try { - PropertiesUtil.loadFromFile(dbProps, dbPropsFile); - dbProps.load(new FileInputStream(dbPropsFile)); - } catch (IOException e) { - s_logger.fatal("Unable to load db properties file, pl. check the classpath and file path configuration", e); - return; - } catch (NullPointerException e) { - s_logger.fatal("Unable to locate db properties file within classpath or absolute path: " + propsFileName); - return; - } + public static void initDataSource(String propsFileName) throws IOException { + Properties dbProps = new Properties(); + File dbPropsFile = PropertiesUtil.findConfigFile(propsFileName); + if (dbPropsFile != null && dbPropsFile.exists()) { + PropertiesUtil.loadFromFile(dbProps, dbPropsFile); + initDataSource(dbProps); + } + } + public static void initDataSource(Properties dbProps) { + try { + if (dbProps.size() == 0) + return; + // FIXME: If params are missing...default them???? final int cloudMaxActive = Integer.parseInt(dbProps.getProperty("db.cloud.maxActive")); final int cloudMaxIdle = Integer.parseInt(dbProps.getProperty("db.cloud.maxIdle")); diff --git a/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java b/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java index 29a299ff423..d79575273cd 100644 --- a/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java +++ b/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.framework.jobs.impl; -import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.Date; @@ -34,7 +33,6 @@ import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.framework.config.ConfigDepot; import org.apache.cloudstack.framework.config.ConfigKey; @@ -54,25 +52,26 @@ import org.apache.cloudstack.jobs.JobInfo; import org.apache.cloudstack.jobs.JobInfo.Status; import org.apache.cloudstack.managed.context.ManagedContextRunnable; import org.apache.cloudstack.utils.identity.ManagementServerNode; +import org.apache.log4j.Logger; import com.cloud.cluster.ClusterManagerListener; import com.cloud.cluster.ManagementServerHost; import com.cloud.utils.DateUtil; import com.cloud.utils.Predicate; -import com.cloud.utils.PropertiesUtil; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; +import com.cloud.utils.db.DbProperties; import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.TransactionCallback; -import com.cloud.utils.db.TransactionCallbackNoReturn; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.TransactionCallback; +import com.cloud.utils.db.TransactionCallbackNoReturn; import com.cloud.utils.db.TransactionStatus; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.ExceptionUtil; @@ -865,10 +864,7 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager, @Override public boolean configure(String name, Map params) throws ConfigurationException { try { - final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); - final Properties dbProps = new Properties(); - PropertiesUtil.loadFromFile(dbProps, dbPropsFile); - + final Properties dbProps = DbProperties.getDbProperties(); final int cloudMaxActive = Integer.parseInt(dbProps.getProperty("db.cloud.maxActive")); int poolSize = (cloudMaxActive * 2) / 3; diff --git a/parents/checkstyle/pom.xml b/parents/checkstyle/pom.xml new file mode 100644 index 00000000000..48d58bb51d3 --- /dev/null +++ b/parents/checkstyle/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + Apache CloudStack Checkstyle Configuration + checkstyle + + org.apache.cloudstack + cloud-maven-standard + 4.3.0-SNAPSHOT + ../../maven-standard/pom.xml + + diff --git a/parents/checkstyle/src/main/resources/tooling/checkstyle.xml b/parents/checkstyle/src/main/resources/tooling/checkstyle.xml new file mode 100644 index 00000000000..83493d677ba --- /dev/null +++ b/parents/checkstyle/src/main/resources/tooling/checkstyle.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/.gitignore b/plugins/hypervisors/hyperv/DotNet/ServerResource/.gitignore new file mode 100644 index 00000000000..99afc0b89f2 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/.gitignore @@ -0,0 +1,9 @@ +packages +*.suo +*/obj/* +WmiWrappers/bin/* +AgentShell/bin/* +ServerResource*/bin/* +*.user +!.nuget/ + diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/.nuget/NuGet.Config b/plugins/hypervisors/hyperv/DotNet/ServerResource/.nuget/NuGet.Config new file mode 100644 index 00000000000..5181cb81034 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/.nuget/NuGet.Config @@ -0,0 +1,15 @@ + + + + + + + diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/.nuget/NuGet.targets b/plugins/hypervisors/hyperv/DotNet/ServerResource/.nuget/NuGet.targets new file mode 100644 index 00000000000..d0ebc7535f3 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/.nuget/NuGet.targets @@ -0,0 +1,136 @@ + + + + $(MSBuildProjectDirectory)\..\ + + + false + + + false + + + true + + + false + + + + + + + + + + + $([System.IO.Path]::Combine($(SolutionDir), ".nuget")) + $([System.IO.Path]::Combine($(ProjectDir), "packages.config")) + + + + + $(SolutionDir).nuget + packages.config + + + + + $(NuGetToolsPath)\NuGet.exe + @(PackageSource) + + "$(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 + + + + RestorePackages; + $(BuildDependsOn); + + + + + $(BuildDependsOn); + BuildPackage; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentService.Designer.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentService.Designer.cs new file mode 100644 index 00000000000..854427732aa --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentService.Designer.cs @@ -0,0 +1,53 @@ +// 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 AgentService + { + /// + /// 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() + { + components = new System.ComponentModel.Container(); + this.ServiceName = "CloudStack ServerResource"; + } + + #endregion + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentService.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentService.cs new file mode 100644 index 00000000000..e1870973511 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentService.cs @@ -0,0 +1,132 @@ +// 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.Generic; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Linq; +using System.ServiceProcess; +using System.Text; +using System.Threading.Tasks; +using System.Web.Http.SelfHost; +using System.Web.Http; +using log4net; +using HypervResource; + +namespace CloudStack.Plugin.AgentShell +{ + public partial class AgentService : ServiceBase + { + [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)] + static extern bool AllocConsole(); + + [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)] + static extern bool FreeConsole(); + + HttpSelfHostServer server; + + private static ILog logger = LogManager.GetLogger(typeof(AgentService)); + + public AgentService() + { + logger.Info("Starting CloudStack agent"); + InitializeComponent(); + + UriBuilder baseUri = new UriBuilder("http", AgentSettings.Default.private_ip_address, AgentSettings.Default.port); + + var config = new HttpSelfHostConfiguration(baseUri.Uri); + + // Allow ActionName to be applied to methods in ApiController, which allows it to serve multiple POST URLs + config.Routes.MapHttpRoute( + "API Default", "api/{controller}/{action}", + new { action = RouteParameter.Optional } + ); + + // Load controller assemblies that we want to config to route to. + ConfigServerResource(); + AssertControllerAssemblyAvailable(config, typeof(HypervResourceController), "Cannot load Controller of type" + typeof(HypervResourceController)); + + server = new HttpSelfHostServer(config); + } + + public static void ConfigServerResource() + { + // For simplicity, ServerResource config and settings file are tightly coupled. + // An alternative is to pass a dictionary to the server resource and let it find + // required settings. In contrast, the approach below is strongly typed and makes + // use of VisualStudio settings designer. The designer allows us to avoid + // accessing config using their key strings. + HypervResourceControllerConfig rsrcCnf = new HypervResourceControllerConfig(); + rsrcCnf.PrivateIpAddress = AgentSettings.Default.private_ip_address; + rsrcCnf.GatewayIpAddress = AgentSettings.Default.gateway_ip_address; + rsrcCnf.RootDeviceReservedSpaceBytes = AgentSettings.Default.RootDeviceReservedSpaceBytes; + rsrcCnf.RootDeviceName = AgentSettings.Default.RootDeviceName; + rsrcCnf.ParentPartitionMinMemoryMb = AgentSettings.Default.dom0MinMemory; + rsrcCnf.LocalSecondaryStoragePath = AgentSettings.Default.local_secondary_storage_path; + rsrcCnf.systemVmIso = null; + + // Side effect: loads the assembly containing HypervResourceController, which + // allows HttpSelfHostServer to route requests to the controller. + HypervResourceController.Configure(rsrcCnf); + + } + + // TODO: update to examine not the assembly resolver, but the list of available controllers themselves! + private static bool AssertControllerAssemblyAvailable(HttpSelfHostConfiguration config, Type controllerType, string errorMessage) + { + var assemblies = config.Services.GetAssembliesResolver().GetAssemblies(); + foreach (var assembly in assemblies) + { + string name = assembly.GetName().Name; + if (controllerType.Assembly.GetName().Name.Equals(name)) + { + logger.DebugFormat("Controller {0} is available", controllerType.Name); + return true; + } + } + + logger.Error(errorMessage); + throw new AgentShellException(errorMessage); + } + + protected override void OnStart(string[] args) + { + server.OpenAsync().Wait(); + } + + protected override void OnStop() + { + server.CloseAsync().Wait(); + } + + internal void RunConsole(string[] args) + { + OnStart(args); + + AllocConsole(); + + Console.WriteLine("Service running ... press to stop"); + + Console.ReadLine(); + + FreeConsole(); + + OnStop(); + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentSettings.Designer.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentSettings.Designer.cs new file mode 100644 index 00000000000..fc3b69af3e8 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentSettings.Designer.cs @@ -0,0 +1,402 @@ +// 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 { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + public sealed partial class AgentSettings : global::System.Configuration.ApplicationSettingsBase { + + private static AgentSettings defaultInstance = ((AgentSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new AgentSettings()))); + + public static AgentSettings Default { + get { + return defaultInstance; + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("8")] + public int cpus { + get { + return ((int)(this["cpus"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("Routing")] + public string type { + get { + return ((string)(this["type"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("5fe2bad3-d785-394e-9949-89786b8a63d2")] + public global::System.Guid local_storage_uuid { + get { + return ((global::System.Guid)(this["local_storage_uuid"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("hvm")] + public string capabilities { + get { + return ((string)(this["capabilities"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("2130")] + public int Settingcpuspeed { + get { + return ((int)(this["Settingcpuspeed"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("8250")] + public int port { + get { + return ((int)(this["port"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("34359738368")] + public long memory { + get { + return ((long)(this["memory"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("camldonall01.citrite.net")] + public string host { + get { + return ((string)(this["host"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("1")] + public int pod { + get { + return ((int)(this["pod"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("10.1.1.1")] + public string gateway_ip_address { + get { + return ((string)(this["gateway_ip_address"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public global::System.Guid guid { + get { + return ((global::System.Guid)(this["guid"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("2")] + public int cluster { + get { + return ((int)(this["cluster"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("1")] + public int zone { + get { + return ((int)(this["zone"])); + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("c:\\Secondary")] + public string local_secondary_storage_path { + get { + return ((string)(this["local_secondary_storage_path"])); + } + set { + this["local_secondary_storage_path"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("E:\\Disks\\Disks")] + public string local_storage_path { + get { + return ((string)(this["local_storage_path"])); + } + set { + this["local_storage_path"] = value; + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("5")] + public int workers { + get { + return ((int)(this["workers"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("255.255.240.0")] + public string private_ip_netmask { + get { + return ((string)(this["private_ip_netmask"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("4294967296")] + public long RootDeviceReservedSpaceBytes { + get { + return ((long)(this["RootDeviceReservedSpaceBytes"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("../../../../../")] + public string hyperv_plugin_root { + get { + return ((string)(this["hyperv_plugin_root"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("e:\\")] + public string RootDeviceName { + get { + return ((string)(this["RootDeviceName"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("101F742C6B88")] + public string private_mac_address { + get { + return ((string)(this["private_mac_address"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("systemvm.iso")] + public string system_vm_iso { + get { + return ((string)(this["system_vm_iso"])); + } + set { + this["system_vm_iso"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute(".\\var\\test\\storagepool")] + public string testLocalStorePath { + get { + return ((string)(this["testLocalStorePath"])); + } + set { + this["testLocalStorePath"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("testS3Bucket")] + public string testS3Bucket { + get { + return ((string)(this["testS3Bucket"])); + } + set { + this["testS3Bucket"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("testS3Endpoint")] + public string testS3Endpoint { + get { + return ((string)(this["testS3Endpoint"])); + } + set { + this["testS3Endpoint"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("testS3AccessKey")] + public string testS3AccessKey { + get { + return ((string)(this["testS3AccessKey"])); + } + set { + this["testS3AccessKey"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("testS3SecretKey")] + public string testS3SecretKey { + get { + return ((string)(this["testS3SecretKey"])); + } + set { + this["testS3SecretKey"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("206-2-73592258-559a-3b38-8f66-b667aab143eb")] + public string testS3TemplateName { + get { + return ((string)(this["testS3TemplateName"])); + } + set { + this["testS3TemplateName"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("5fe2bad3-d785-394e-9949-89786b8a63d2")] + public string testLocalStoreUUID { + get { + return ((string)(this["testLocalStoreUUID"])); + } + set { + this["testLocalStoreUUID"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("acton-systemvm-02062012.vhd.bz2")] + public string testSystemVMTemplateName { + get { + return ((string)(this["testSystemVMTemplateName"])); + } + set { + this["testSystemVMTemplateName"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("acton-systemvm-02062012")] + public string testSystemVMTemplateNameNoExt { + get { + return ((string)(this["testSystemVMTemplateNameNoExt"])); + } + set { + this["testSystemVMTemplateNameNoExt"] = value; + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("2048")] + public ulong dom0MinMemory { + get { + return ((ulong)(this["dom0MinMemory"])); + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("10.1.1.1")] + public string private_ip_address { + get { + return ((string)(this["private_ip_address"])); + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("cifs://10.1.1.1/secondary?user\\u003dadministrator\\u0026password\\u003d1pass%40w" + + "ord1")] + public string testCifsUrl { + get { + return ((string)(this["testCifsUrl"])); + } + set { + this["testCifsUrl"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("template/tmpl/2/201/61d5316a-3cc4-30cf-a557-78691ff5c143.vhd")] + public string testCifsPath { + get { + return ((string)(this["testCifsPath"])); + } + set { + this["testCifsPath"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("CentOS64")] + public string testKvpVmName { + get { + return ((string)(this["testKvpVmName"])); + } + set { + this["testKvpVmName"] = value; + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentSettings.settings b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentSettings.settings new file mode 100644 index 00000000000..fb5b962fcaa --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentSettings.settings @@ -0,0 +1,130 @@ + + + + + + + + 8 + + + 10.70.176.29 + + + Routing + + + 5fe2bad3-d785-394e-9949-89786b8a63d2 + + + hvm + + + 2130 + + + 8250 + + + 34359738368 + + + camldonall01.citrite.net + + + 1 + + + 10.70.176.1 + + + + + + 2 + + + 1 + + + c:\Secondary + + + E:\Disks\Disks + + + 5 + + + 255.255.240.0 + + + 4294967296 + + + ../../../../../ + + + e:\ + + + 101F742C6B88 + + + .\var\test\storagepool + + + testS3Bucket + + + testS3Endpoint + + + testS3AccessKey + + + testS3SecretKey + + + 206-2-73592258-559a-3b38-8f66-b667aab143eb + + + 5fe2bad3-d785-394e-9949-89786b8a63d2 + + + acton-systemvm-02062012.vhd.bz2 + + + acton-systemvm-02062012 + + + 2048 + + + cifs://10.1.1.1/secondary?user\u003dadministrator\u0026password\u003d1pass%40word1 + + + template/tmpl/2/201/61d5316a-3cc4-30cf-a557-78691ff5c143.vhd + + + CentOS64 + + + diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentShell.csproj b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentShell.csproj new file mode 100644 index 00000000000..39fef1606a2 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentShell.csproj @@ -0,0 +1,140 @@ + + + + + Debug + AnyCPU + {9060B539-62D0-4E71-A6C6-5944828774E9} + WinExe + Properties + CloudStack.Plugin.AgentShell + AgentShell + v4.5 + 512 + ..\ + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\NoUnitTestsDebug\ + DEBUG;TRACE + full + AnyCPU + prompt + MinimumRecommendedRules.ruleset + true + + + bin\NoUnitTests\ + TRACE + true + pdbonly + AnyCPU + prompt + MinimumRecommendedRules.ruleset + true + + + + ..\packages\AWSSDK.1.5.23.0\lib\AWSSDK.dll + + + ..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll + + + ..\packages\log4net.2.0.0\lib\net40-full\log4net.dll + + + ..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll + + + ..\packages\NSubstitute.1.6.1.0\lib\NET40\NSubstitute.dll + + + + + + + ..\packages\Microsoft.AspNet.WebApi.Client.4.0.20710.0\lib\net40\System.Net.Http.Formatting.dll + + + ..\packages\Microsoft.AspNet.WebApi.Core.4.0.20710.0\lib\net40\System.Web.Http.dll + + + ..\packages\Microsoft.AspNet.WebApi.SelfHost.4.0.20918.0\lib\net40\System.Web.Http.SelfHost.dll + + + + + + + + + ..\packages\xunit.1.9.2\lib\net20\xunit.dll + + + + + Component + + + AgentService.cs + + + + + + True + True + AgentSettings.settings + + + + + Designer + + + PublicSettingsSingleFileGenerator + AgentSettings.Designer.cs + Designer + + + + + {c963dfff-65ba-4e71-ada5-526a4da4e0b2} + HypervResource + + + {db824727-bdc3-437c-a364-7a811d8a160f} + WmiWrappers + + + + + + diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentShellException.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentShellException.cs new file mode 100644 index 00000000000..14d9e9783b8 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentShellException.cs @@ -0,0 +1,28 @@ +// 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.Generic; +using System.Linq; +using System.Text; + +namespace CloudStack.Plugin.AgentShell +{ + class AgentShellException : Exception + { + public AgentShellException(string errMsg) : base(errMsg) { } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/App.config b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/App.config new file mode 100644 index 00000000000..68ab80ee555 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/App.config @@ -0,0 +1,145 @@ + + + +
+ +
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 8 + + + Routing + + + 5fe2bad3-d785-394e-9949-89786b8a63d2 + + + hvm + + + 2130 + + + 8250 + + + 34359738368 + + + camldonall01.citrite.net + + + 1 + + + 10.102.192.1 + + + 2 + + + 1 + + + 5 + + + 255.255.252.0 + + + 4294967296 + + + ..\..\..\..\..\ + + + e:\ + + + 101F742C6B88 + + + 2048 + + + 10.102.192.150 + + + + + + + c:\Secondary + + + E:\Disks\Disks + + + .\var\test\storagepool + + + testS3Bucket + + + testS3Endpoint + + + testS3AccessKey + + + testS3SecretKey + + + 206-2-73592258-559a-3b38-8f66-b667aab143eb + + + 5fe2bad3-d785-394e-9949-89786b8a63d2 + + + acton-systemvm-02062012.vhd.bz2 + + + acton-systemvm-02062012 + + + cifs://10.70.1.1/secondary?user\u003dadministrator\u0026password\u003d1pass%40word1 + + + template/tmpl/2/201/61d5316a-3cc4-30cf-a557-78691ff5c143.vhd + + + + \ 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 new file mode 100644 index 00000000000..10663708508 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/Program.cs @@ -0,0 +1,58 @@ +// 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 log4net; +using System; +using System.Collections.Generic; +using System.Linq; +using System.ServiceProcess; +using System.Text; +using System.Threading.Tasks; + +namespace CloudStack.Plugin.AgentShell +{ + static class Program + { + private static ILog logger = LogManager.GetLogger(typeof(Program)); + + /// + /// Application entry point allows service to run in console application or as a Windows service. + /// Add '--console' to the commandline for the former, the latter is the default. + /// + 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 + { + logger.InfoFormat("CloudStack ServerResource running as Windows Service"); + ServiceBase[] ServicesToRun = new ServiceBase[] { new AgentService() }; + ServiceBase.Run(ServicesToRun); + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/Properties/AssemblyInfo.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..bd188bb0ef2 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/Properties/AssemblyInfo.cs @@ -0,0 +1,56 @@ +// 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.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AgentShell")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AgentShell")] +[assembly: AssemblyCopyright("Copyright © 2013")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("a6d8469a-c815-4765-a4a1-4927d4e3c583")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] + + +[assembly: log4net.Config.XmlConfigurator(Watch = true)] diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/packages.config b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/packages.config new file mode 100644 index 00000000000..fb1c846ad3c --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/packages.config @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/App.config b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/App.config new file mode 100644 index 00000000000..1bf17d4791f --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/App.config @@ -0,0 +1,128 @@ + + + + + +
+ + +
+ + + + + + + + + + + + 8 + + + 10.1.1.1 + + + Routing + + + 5fe2bad3-d785-394e-9949-89786b8a63d2 + + + hvm + + + 2130 + + + 8250 + + + 34359738368 + + + camldonall01.citrite.net + + + 1 + + + 10.70.176.1 + + + 2 + + + 1 + + + E:\Disks\Disks + + + 5 + + + 255.255.240.0 + + + 4294967296 + + + ..\..\..\..\..\ + + + e:\ + + + 2048 + + + 101F742C6B88 + + + + + + + c:\Secondary + + + E:\Disks\Disks + + + 5fe2bad3-d785-394e-9949-89786b8a63d2 + + + .\var\test\storagepool + + + cshv3eu + + + s3.amazonaws.com + + + testS3AccessKey + + + testS3SecretKey + + + 206-2-73592258-559a-3b38-8f66-b667aab143eb + + + 206-2-73592258-559a-3b38-8f66-b667aab143eb + + + cifs://10.1.1.1/secondary?user\u003dadministrator\u0026password\u003d1pass%40word1 + + + template/tmpl/2/201/6dda6631-4daa-3150-a49a-d5a4b0a4c4b6.vhd + + + + diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/CloudStackTypes.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/CloudStackTypes.cs new file mode 100644 index 00000000000..ae595fcc215 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/CloudStackTypes.cs @@ -0,0 +1,642 @@ +// 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 log4net; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +// C# versions of certain CloudStack types to simplify JSON serialisation. +// Limit to the number of types, becasue they are written and maintained manually. +// JsonProperty used to identify property name when serialised, which allows +// later adoption of C# naming conventions if requried. +namespace HypervResource +{ + public class PrimaryDataStoreTO + { + public string path; + + 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 + }; + } + return result; + } + } + + public class VolumeObjectTO + { + private static ILog logger = LogManager.GetLogger(typeof(VolumeObjectTO)); + + public string FullFileName + { + get + { + String result = Path.Combine(this.primaryDataStore.path, this.name); + if (this.format != null) + { + result = result + "." + this.format.ToLowerInvariant(); + } + return result; + } + } + + public dynamic dataStore; + public string format; + public string name; + public string uuid; + public PrimaryDataStoreTO primaryDataStore; + + public static VolumeObjectTO ParseJson(dynamic json) + { + VolumeObjectTO result = null; + + if (json == null) + { + return result; + } + + dynamic volumeObjectTOJson = json[CloudStackTypes.VolumeObjectTO]; + if (volumeObjectTOJson != null) + { + result = new VolumeObjectTO() + { + dataStore = volumeObjectTOJson.dataStore, + format = ((string)volumeObjectTOJson.format), + name = (string)volumeObjectTOJson.name, + uuid = (string)volumeObjectTOJson.uuid + }; + result.primaryDataStore = PrimaryDataStoreTO.ParseJson(volumeObjectTOJson.dataStore); + + // Assert + if (result.dataStore == null || result.primaryDataStore == null) + { + String errMsg = "VolumeObjectTO missing primary dataStore in spec " + volumeObjectTOJson.ToString(); + logger.Error(errMsg); + throw new ArgumentNullException(errMsg); + } + + GuessFileExtension(result); + } + return result; + } + + private static void GuessFileExtension(VolumeObjectTO volInfo) + { + if (String.IsNullOrEmpty(volInfo.format)) + { + 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*"); + + 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. + logger.Debug(errMsg); + } + else + { + string[] splitFileName = choices[0].Split(new char[] { '.' }); + volInfo.format = splitFileName[splitFileName.Length - 1]; + } + logger.Debug("Going to use file " + volInfo.FullFileName); + } + } + } + + public class TemplateObjectTO + { + /// + /// Full file name varies depending on whether the TemplateObjectTO has a path or not. + /// If it has a path, we use that. Otherwise, we build it from the name, extension and data store path. + /// + public string FullFileName + { + get + { + if (String.IsNullOrEmpty(this.path)) + { + return Path.Combine(this.primaryDataStore.path, this.name) + '.' + this.format.ToLowerInvariant(); + } + return this.path; + } + } + + public dynamic imageDataStore; + public string format; + public string name; + public string uuid; + public S3TO s3DataStoreTO = null; + public NFSTO nfsDataStoreTO = null; + public PrimaryDataStoreTO primaryDataStore = null; + public string path; + public string checksum; + + public static TemplateObjectTO ParseJson(dynamic json) + { + TemplateObjectTO result = null; + dynamic templateObjectTOJson = json[CloudStackTypes.TemplateObjectTO]; + if (templateObjectTOJson != null) + { + result = new TemplateObjectTO() + { + imageDataStore = templateObjectTOJson.imageDataStore, + format = (string)templateObjectTOJson.format, + name = (string)templateObjectTOJson.name, + uuid = (string)templateObjectTOJson.uuid, + path = (string)templateObjectTOJson.path, + checksum = (string)templateObjectTOJson.checksum + }; + result.s3DataStoreTO = S3TO.ParseJson(templateObjectTOJson.imageDataStore); + result.nfsDataStoreTO = NFSTO.ParseJson(templateObjectTOJson.imageDataStore); + result.primaryDataStore = PrimaryDataStoreTO.ParseJson(templateObjectTOJson.imageDataStore); + } + + return result; + } + } + + public class S3TO + { + public string bucketName; + public string secretKey; + public string accessKey; + public string endpoint; + public bool httpsFlag; + + public static S3TO ParseJson(dynamic json) + { + S3TO result = null; + dynamic s3TOJson = json[CloudStackTypes.S3TO]; + if (s3TOJson != null) + { + 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; + } + } + + public class NFSTO + { + public Uri uri; + public string _role; + public string UncPath + { + get + { + string uncPath = null; + if (uri.Scheme.Equals("cifs")) + { + 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 static NFSTO ParseJson(dynamic json) + { + NFSTO result = null; + dynamic nfsTOJson = json[CloudStackTypes.NFSTO]; + if (nfsTOJson != null) + { + 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; + } + } + + enum VolumeType + { + UNKNOWN, + ROOT, + SWAP, + DATADISK, + ISO + }; + + public enum StoragePoolType + { + /// + /// local directory + /// + Filesystem, + /// + /// NFS or CIFS + /// + NetworkFilesystem, + /// + /// shared LUN, with a clusterfs overlay + /// + IscsiLUN, + /// + /// for e.g., ZFS Comstar + /// + Iscsi, + /// + /// for iso image + /// + ISO, + /// + /// XenServer local LVM SR + /// + LVM, + /// + /// + /// + CLVM, + /// + /// + /// + RBD, + /// + /// + /// + SharedMountPoint, + /// + /// VMware VMFS storage + /// + VMFS, + /// + /// for XenServer, Storage Pool is set up by customers. + /// + PreSetup, + /// + /// XenServer local EXT SR + /// + EXT, + /// + /// + /// + OCFS2 + } + + public enum StorageResourceType + { + STORAGE_POOL, STORAGE_HOST, SECONDARY_STORAGE, LOCAL_SECONDARY_STORAGE + } + + public struct VolumeInfo + { + public long id; + public string type; + public string storagePoolType; + public string storagePoolUuid; + public string name; + public string mountPoint; + public string path; + long size; + string chainInfo; + + public VolumeInfo(long id, string type, string poolType, String poolUuid, String name, String mountPoint, String path, long size, String chainInfo) + { + this.id = id; + this.name = name; + this.path = path; + this.size = size; + this.type = type; + this.storagePoolType = poolType; + this.storagePoolUuid = poolUuid; + this.mountPoint = mountPoint; + this.chainInfo = chainInfo; + } + } + + public struct StoragePoolInfo + { + [JsonProperty("uuid")] + public String uuid; + [JsonProperty("host")] + String host; + [JsonProperty("localPath")] + String localPath; + [JsonProperty("hostPath")] + String hostPath; + [JsonProperty("poolType")] + string poolType; + [JsonProperty("capacityBytes")] + long capacityBytes; + + // Management server copies this field to the 'used_byptes' in the database table 'storage_pool'. + [JsonProperty("availableBytes")] + long availableBytes; + [JsonProperty("details")] + Dictionary details; + + public StoragePoolInfo(String uuid, String host, String hostPath, + String localPath, string poolType, long capacityBytes, + long availableBytes) + { + this.uuid = uuid; + this.host = host; + this.localPath = localPath; + this.hostPath = hostPath; + this.poolType = poolType; + this.capacityBytes = capacityBytes; + this.availableBytes = availableBytes; + details = null; + } + + public StoragePoolInfo(String uuid, String host, String hostPath, + String localPath, string poolType, long capacityBytes, + long availableBytes, Dictionary details) + : this(uuid, host, hostPath, localPath, poolType, capacityBytes, availableBytes) + { + this.details = details; + } + } + + public class VmStatsEntry + { + [JsonProperty("cpuUtilization")] + public double cpuUtilization; + [JsonProperty("networkReadKBs")] + public double networkReadKBs; + [JsonProperty("networkWriteKBs")] + public double networkWriteKBs; + [JsonProperty("numCPUs")] + public int numCPUs; + [JsonProperty("entityType")] + public String entityType; + } + + /// + /// Fully qualified named for a number of types used in CloudStack. Used to specify the intended type for JSON serialised objects. + /// + public class CloudStackTypes + { + public const string Answer = "com.cloud.agent.api.Answer"; + public const string AttachIsoCommand = "com.cloud.agent.api.AttachIsoCommand"; + public const string AttachVolumeAnswer = "com.cloud.agent.api.AttachVolumeAnswer"; + public const string AttachVolumeCommand = "com.cloud.agent.api.AttachVolumeCommand"; + public const string AnsBackupSnapshotAnswerwer = "com.cloud.agent.api.BackupSnapshotAnswer"; + public const string BackupSnapshotCommand = "com.cloud.agent.api.BackupSnapshotCommand"; + public const string BumpUpPriorityCommand = "com.cloud.agent.api.BumpUpPriorityCommand"; + public const string CheckHealthAnswer = "com.cloud.agent.api.CheckHealthAnswer"; + public const string CheckHealthCommand = "com.cloud.agent.api.CheckHealthCommand"; + public const string CheckNetworkAnswer = "com.cloud.agent.api.CheckNetworkAnswer"; + public const string CheckNetworkCommand = "com.cloud.agent.api.CheckNetworkCommand"; + public const string CheckOnHostAnswer = "com.cloud.agent.api.CheckOnHostAnswer"; + public const string CheckOnHostCommand = "com.cloud.agent.api.CheckOnHostCommand"; + public const string CheckRouterAnswer = "com.cloud.agent.api.CheckRouterAnswer"; + public const string CheckRouterCommand = "com.cloud.agent.api.CheckRouterCommand"; + public const string CheckS2SVpnConnectionsAnswer = "com.cloud.agent.api.CheckS2SVpnConnectionsAnswer"; + public const string CheckS2SVpnConnectionsCommand = "com.cloud.agent.api.CheckS2SVpnConnectionsCommand"; + public const string CheckVirtualMachineAnswer = "com.cloud.agent.api.CheckVirtualMachineAnswer"; + public const string CheckVirtualMachineCommand = "com.cloud.agent.api.CheckVirtualMachineCommand"; + public const string CleanupNetworkRulesCmd = "com.cloud.agent.api.CleanupNetworkRulesCmd"; + public const string ClusterSyncAnswer = "com.cloud.agent.api.ClusterSyncAnswer"; + public const string ClusterSyncCommand = "com.cloud.agent.api.ClusterSyncCommand"; + public const string Command = "com.cloud.agent.api.Command"; + public const string CreatePrivateTemplateFromSnapshotCommand = "com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand"; + public const string CreatePrivateTemplateFromVolumeCommand = "com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand"; + public const string CreateStoragePoolCommand = "com.cloud.agent.api.CreateStoragePoolCommand"; + public const string CreateVMSnapshotAnswer = "com.cloud.agent.api.CreateVMSnapshotAnswer"; + public const string CreateVMSnapshotCommand = "com.cloud.agent.api.CreateVMSnapshotCommand"; + public const string CreateVolumeFromSnapshotAnswer = "com.cloud.agent.api.CreateVolumeFromSnapshotAnswer"; + public const string CreateVolumeFromSnapshotCommand = "com.cloud.agent.api.CreateVolumeFromSnapshotCommand"; + public const string DeleteStoragePoolCommand = "com.cloud.agent.api.DeleteStoragePoolCommand"; + public const string DeleteVMSnapshotAnswer = "com.cloud.agent.api.DeleteVMSnapshotAnswer"; + public const string DeleteVMSnapshotCommand = "com.cloud.agent.api.DeleteVMSnapshotCommand"; + public const string GetDomRVersionAnswer = "com.cloud.agent.api.GetDomRVersionAnswer"; + public const string GetDomRVersionCmd = "com.cloud.agent.api.GetDomRVersionCmd"; + public const string GetHostStatsAnswer = "com.cloud.agent.api.GetHostStatsAnswer"; + public const string GetHostStatsCommand = "com.cloud.agent.api.GetHostStatsCommand"; + public const string GetStorageStatsAnswer = "com.cloud.agent.api.GetStorageStatsAnswer"; + public const string GetStorageStatsCommand = "com.cloud.agent.api.GetStorageStatsCommand"; + public const string GetVmDiskStatsAnswer = "com.cloud.agent.api.GetVmDiskStatsAnswer"; + public const string GetVmDiskStatsCommand = "com.cloud.agent.api.GetVmDiskStatsCommand"; + public const string GetVmStatsAnswer = "com.cloud.agent.api.GetVmStatsAnswer"; + public const string GetVmStatsCommand = "com.cloud.agent.api.GetVmStatsCommand"; + public const string GetVncPortAnswer = "com.cloud.agent.api.GetVncPortAnswer"; + public const string GetVncPortCommand = "com.cloud.agent.api.GetVncPortCommand"; + public const string HostStatsEntry = "com.cloud.agent.api.HostStatsEntry"; + public const string MaintainAnswer = "com.cloud.agent.api.MaintainAnswer"; + public const string MaintainCommand = "com.cloud.agent.api.MaintainCommand"; + public const string ManageSnapshotAnswer = "com.cloud.agent.api.ManageSnapshotAnswer"; + public const string ManageSnapshotCommand = "com.cloud.agent.api.ManageSnapshotCommand"; + public const string MigrateAnswer = "com.cloud.agent.api.MigrateAnswer"; + public const string MigrateCommand = "com.cloud.agent.api.MigrateCommand"; + public const string ModifySshKeysCommand = "com.cloud.agent.api.ModifySshKeysCommand"; + public const string ModifyStoragePoolAnswer = "com.cloud.agent.api.ModifyStoragePoolAnswer"; + public const string ModifyStoragePoolCommand = "com.cloud.agent.api.ModifyStoragePoolCommand"; + public const string NetworkRulesSystemVmCommand = "com.cloud.agent.api.NetworkRulesSystemVmCommand"; + public const string NetworkRulesVmSecondaryIpCommand = "com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand"; + public const string PingCommand = "com.cloud.agent.api.PingCommand"; + public const string PingRoutingCommand = "com.cloud.agent.api.PingRoutingCommand"; + public const string PingRoutingWithNwGroupsCommand = "com.cloud.agent.api.PingRoutingWithNwGroupsCommand"; + public const string PingRoutingWithOvsCommand = "com.cloud.agent.api.PingRoutingWithOvsCommand"; + public const string PingTestCommand = "com.cloud.agent.api.PingTestCommand"; + public const string PlugNicAnswer = "com.cloud.agent.api.PlugNicAnswer"; + public const string PlugNicCommand = "com.cloud.agent.api.PlugNicCommand"; + public const string PoolEjectCommand = "com.cloud.agent.api.PoolEjectCommand"; + public const string PrepareForMigrationAnswer = "com.cloud.agent.api.PrepareForMigrationAnswer"; + public const string PrepareForMigrationCommand = "com.cloud.agent.api.PrepareForMigrationCommand"; + public const string PvlanSetupCommand = "com.cloud.agent.api.PvlanSetupCommand"; + public const string ReadyAnswer = "com.cloud.agent.api.ReadyAnswer"; + public const string ReadyCommand = "com.cloud.agent.api.ReadyCommand"; + public const string RebootAnswer = "com.cloud.agent.api.RebootAnswer"; + public const string RebootCommand = "com.cloud.agent.api.RebootCommand"; + public const string RebootRouterCommand = "com.cloud.agent.api.RebootRouterCommand"; + public const string RevertToVMSnapshotAnswer = "com.cloud.agent.api.RevertToVMSnapshotAnswer"; + public const string RevertToVMSnapshotCommand = "com.cloud.agent.api.RevertToVMSnapshotCommand"; + public const string ScaleVmAnswer = "com.cloud.agent.api.ScaleVmAnswer"; + public const string ScaleVmCommand = "com.cloud.agent.api.ScaleVmCommand"; + public const string SecurityGroupRuleAnswer = "com.cloud.agent.api.SecurityGroupRuleAnswer"; + public const string SecurityGroupRulesCmd = "com.cloud.agent.api.SecurityGroupRulesCmd"; + public const string SetupAnswer = "com.cloud.agent.api.SetupAnswer"; + public const string SetupCommand = "com.cloud.agent.api.SetupCommand"; + public const string SetupGuestNetworkAnswer = "com.cloud.agent.api.SetupGuestNetworkAnswer"; + public const string SetupGuestNetworkCommand = "com.cloud.agent.api.SetupGuestNetworkCommand"; + public const string StartAnswer = "com.cloud.agent.api.StartAnswer"; + public const string StartCommand = "com.cloud.agent.api.StartCommand"; + public const string StartupCommand = "com.cloud.agent.api.StartupCommand"; + public const string StartupRoutingCommand = "com.cloud.agent.api.StartupRoutingCommand"; + public const string StartupStorageCommand = "com.cloud.agent.api.StartupStorageCommand"; + public const string StopAnswer = "com.cloud.agent.api.StopAnswer"; + public const string StopCommand = "com.cloud.agent.api.StopCommand"; + public const string StoragePoolInfo = "com.cloud.agent.api.StoragePoolInfo"; + public const string UnPlugNicAnswer = "com.cloud.agent.api.UnPlugNicAnswer"; + public const string UnPlugNicCommand = "com.cloud.agent.api.UnPlugNicCommand"; + public const string UpdateHostPasswordCommand = "com.cloud.agent.api.UpdateHostPasswordCommand"; + public const string UpgradeSnapshotCommand = "com.cloud.agent.api.UpgradeSnapshotCommand"; + public const string VmDiskStatsEntry = "com.cloud.agent.api.VmDiskStatsEntry"; + public const string VmStatsEntry = "com.cloud.agent.api.VmStatsEntry"; + public const string CheckSshAnswer = "com.cloud.agent.api.check.CheckSshAnswer"; + public const string CheckSshCommand = "com.cloud.agent.api.check.CheckSshCommand"; + public const string CheckConsoleProxyLoadCommand = "com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand"; + public const string ConsoleProxyLoadAnswer = "com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer"; + public const string WatchConsoleProxyLoadCommand = "com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand"; + public const string CreateIpAliasCommand = "com.cloud.agent.api.routing.CreateIpAliasCommand"; + public const string DeleteIpAliasCommand = "com.cloud.agent.api.routing.DeleteIpAliasCommand"; + public const string DhcpEntryCommand = "com.cloud.agent.api.routing.DhcpEntryCommand"; + public const string DnsMasqConfigCommand = "com.cloud.agent.api.routing.DnsMasqConfigCommand"; + public const string IpAliasTO = "com.cloud.agent.api.routing.IpAliasTO"; + public const string IpAssocAnswer = "com.cloud.agent.api.routing.IpAssocAnswer"; + public const string IpAssocCommand = "com.cloud.agent.api.routing.IpAssocCommand"; + public const string IpAssocVpcCommand = "com.cloud.agent.api.routing.IpAssocVpcCommand"; + public const string LoadBalancerConfigCommand = "com.cloud.agent.api.routing.LoadBalancerConfigCommand"; + public const string NetworkElementCommand = "com.cloud.agent.api.routing.NetworkElementCommand"; + public const string RemoteAccessVpnCfgCommand = "com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand"; + public const string SavePasswordCommand = "com.cloud.agent.api.routing.SavePasswordCommand"; + public const string SetFirewallRulesAnswer = "com.cloud.agent.api.routing.SetFirewallRulesAnswer"; + public const string SetFirewallRulesCommand = "com.cloud.agent.api.routing.SetFirewallRulesCommand"; + public const string SetNetworkACLAnswer = "com.cloud.agent.api.routing.SetNetworkACLAnswer"; + public const string SetNetworkACLCommand = "com.cloud.agent.api.routing.SetNetworkACLCommand"; + public const string SetPortForwardingRulesAnswer = "com.cloud.agent.api.routing.SetPortForwardingRulesAnswer"; + public const string SetPortForwardingRulesCommand = "com.cloud.agent.api.routing.SetPortForwardingRulesCommand"; + public const string SetPortForwardingRulesVpcCommand = "com.cloud.agent.api.routing.SetPortForwardingRulesVpcCommand"; + public const string SetSourceNatAnswer = "com.cloud.agent.api.routing.SetSourceNatAnswer"; + public const string SetSourceNatCommand = "com.cloud.agent.api.routing.SetSourceNatCommand"; + public const string SetStaticNatRulesAnswer = "com.cloud.agent.api.routing.SetStaticNatRulesAnswer"; + public const string SetStaticNatRulesCommand = "com.cloud.agent.api.routing.SetStaticNatRulesCommand"; + public const string SetStaticRouteAnswer = "com.cloud.agent.api.routing.SetStaticRouteAnswer"; + public const string SetStaticRouteCommand = "com.cloud.agent.api.routing.SetStaticRouteCommand"; + public const string Site2SiteVpnCfgCommand = "com.cloud.agent.api.routing.Site2SiteVpnCfgCommand"; + public const string VmDataCommand = "com.cloud.agent.api.routing.VmDataCommand"; + public const string VpnUsersCfgCommand = "com.cloud.agent.api.routing.VpnUsersCfgCommand"; + public const string CopyVolumeAnswer = "com.cloud.agent.api.storage.CopyVolumeAnswer"; + public const string CopyVolumeCommand = "com.cloud.agent.api.storage.CopyVolumeCommand"; + public const string CreateAnswer = "com.cloud.agent.api.storage.CreateAnswer"; + public const string CreateCommand = "com.cloud.agent.api.storage.CreateCommand"; + public const string CreatePrivateTemplateAnswer = "com.cloud.agent.api.storage.CreatePrivateTemplateAnswer"; + public const string DestroyCommand = "com.cloud.agent.api.storage.DestroyCommand"; + public const string PrimaryStorageDownloadAnswer = "com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer"; + public const string PrimaryStorageDownloadCommand = "com.cloud.agent.api.storage.PrimaryStorageDownloadCommand"; + public const string ResizeVolumeAnswer = "com.cloud.agent.api.storage.ResizeVolumeAnswer"; + public const string ResizeVolumeCommand = "com.cloud.agent.api.storage.ResizeVolumeCommand"; + public const string FirewallRuleTO = "com.cloud.agent.api.to.FirewallRuleTO"; + public const string IpAddressTO = "com.cloud.agent.api.to.IpAddressTO"; + public const string NicTO = "com.cloud.agent.api.to.NicTO"; + public const string PortForwardingRuleTO = "com.cloud.agent.api.to.PortForwardingRuleTO"; + public const string S3TO = "com.cloud.agent.api.to.S3TO"; + public const string NFSTO = "com.cloud.agent.api.to.NfsTO"; + public const string StaticNatRuleTO = "com.cloud.agent.api.to.StaticNatRuleTO"; + public const string StorageFilerTO = "com.cloud.agent.api.to.StorageFilerTO"; + public const string SwiftTO = "com.cloud.agent.api.to.SwiftTO"; + public const string VirtualMachineTO = "com.cloud.agent.api.to.VirtualMachineTO"; + public const string VolumeTO = "com.cloud.agent.api.to.VolumeTO"; + public const string InternalErrorException = "com.cloud.exception.InternalErrorException"; + public const string HostType = "com.cloud.host.Host.Type"; + public const string HypervisorType = "com.cloud.hypervisor.Hypervisor.HypervisorType"; + public const string DnsMasqConfigurator = "com.cloud.network.DnsMasqConfigurator"; + public const string HAProxyConfigurator = "com.cloud.network.HAProxyConfigurator"; + public const string LoadBalancerConfigurator = "com.cloud.network.LoadBalancerConfigurator"; + public const string Networks = "com.cloud.network.Networks"; + public const string BroadcastDomainType = "com.cloud.network.Networks.BroadcastDomainType"; + public const string IsolationType = "com.cloud.network.Networks.IsolationType"; + public const string TrafficType = "com.cloud.network.Networks.TrafficType"; + public const string PhysicalNetworkSetupInfo = "com.cloud.network.PhysicalNetworkSetupInfo"; + public const string OvsCreateGreTunnelAnswer = "com.cloud.network.ovs.OvsCreateGreTunnelAnswer"; + public const string OvsCreateGreTunnelCommand = "com.cloud.network.ovs.OvsCreateGreTunnelCommand"; + public const string OvsCreateTunnelAnswer = "com.cloud.network.ovs.OvsCreateTunnelAnswer"; + public const string OvsCreateTunnelCommand = "com.cloud.network.ovs.OvsCreateTunnelCommand"; + public const string OvsDeleteFlowCommand = "com.cloud.network.ovs.OvsDeleteFlowCommand"; + public const string OvsDestroyBridgeCommand = "com.cloud.network.ovs.OvsDestroyBridgeCommand"; + public const string OvsDestroyTunnelCommand = "com.cloud.network.ovs.OvsDestroyTunnelCommand"; + public const string OvsFetchInterfaceAnswer = "com.cloud.network.ovs.OvsFetchInterfaceAnswer"; + public const string OvsFetchInterfaceCommand = "com.cloud.network.ovs.OvsFetchInterfaceCommand"; + public const string OvsSetTagAndFlowAnswer = "com.cloud.network.ovs.OvsSetTagAndFlowAnswer"; + public const string OvsSetTagAndFlowCommand = "com.cloud.network.ovs.OvsSetTagAndFlowCommand"; + public const string OvsSetupBridgeCommand = "com.cloud.network.ovs.OvsSetupBridgeCommand"; + public const string FirewallRule = "com.cloud.network.rules.FirewallRule"; + public const string ServerResource = "com.cloud.resource.ServerResource"; + public const string HypervisorResource = "com.cloud.resource.hypervisor.HypervisorResource"; + public const string Storage = "com.cloud.storage.Storage"; + public const string ImageFormat = "com.cloud.storage.Storage.ImageFormat"; + public const string StoragePoolType = "com.cloud.storage.Storage.StoragePoolType"; + public const string Volume = "com.cloud.storage.Volume"; + public const string VolumeVO = "com.cloud.storage.VolumeVO"; + public const string StorageSubsystemCommandHandler = "com.cloud.storage.resource.StorageSubsystemCommandHandler"; + public const string StorageSubsystemCommandHandlerBase = "com.cloud.storage.resource.StorageSubsystemCommandHandlerBase"; + public const string TemplateProp = "com.cloud.storage.template.TemplateProp"; + public const string BootloaderType = "com.cloud.template.VirtualMachineTemplate.BootloaderType"; + public const string VolumeObjectTO = "org.apache.cloudstack.storage.to.VolumeObjectTO"; + public const string TemplateObjectTO = "org.apache.cloudstack.storage.to.TemplateObjectTO"; + public const string PrimaryDataStoreTO = "org.apache.cloudstack.storage.to.PrimaryDataStoreTO"; + public const string AttachAnswer = "org.apache.cloudstack.storage.command.AttachAnswer"; + public const string AttachCommand = "org.apache.cloudstack.storage.command.AttachCommand"; + public const string AttachPrimaryDataStoreAnswer = "org.apache.cloudstack.storage.command.AttachPrimaryDataStoreAnswer"; + public const string AttachPrimaryDataStoreCmd = "org.apache.cloudstack.storage.command.AttachPrimaryDataStoreCmd"; + public const string CopyCmdAnswer = "org.apache.cloudstack.storage.command.CopyCmdAnswer"; + public const string CopyCommand = "org.apache.cloudstack.storage.command.CopyCommand"; + public const string CreateObjectAnswer = "org.apache.cloudstack.storage.command.CreateObjectAnswer"; + public const string CreateObjectCommand = "org.apache.cloudstack.storage.command.CreateObjectCommand"; + public const string DeleteCommand = "org.apache.cloudstack.storage.command.DeleteCommand"; + public const string DettachAnswer = "org.apache.cloudstack.storage.command.DettachAnswer"; + public const string DettachCommand = "org.apache.cloudstack.storage.command.DettachCommand"; + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResource.csproj b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResource.csproj new file mode 100644 index 00000000000..05a0f513d8b --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResource.csproj @@ -0,0 +1,103 @@ + + + + + Debug + AnyCPU + {C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2} + Library + Properties + HypervResource + HypervResource + v4.5 + 512 + ..\ + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\NoUnitTestsDebug\ + DEBUG;TRACE + full + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + bin\NoUnitTests\ + TRACE + true + pdbonly + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\AWSSDK.1.5.23.0\lib\AWSSDK.dll + + + ..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll + + + ..\packages\log4net.2.0.0\lib\net40-full\log4net.dll + + + ..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + {db824727-bdc3-437c-a364-7a811d8a160f} + WmiWrappers + + + + + + \ No newline at end of file diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResourceController.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResourceController.cs new file mode 100644 index 00000000000..ed3736b072b --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResourceController.cs @@ -0,0 +1,1459 @@ +// 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 Amazon; +using Amazon.S3; +using Amazon.S3.Model; +using log4net; +using Microsoft.CSharp.RuntimeBinder; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Security.Cryptography; +using System.Security.Principal; +using System.Web.Http; + +namespace HypervResource +{ + + public struct HypervResourceControllerConfig + { + private string privateIpAddress; + private static ILog logger = LogManager.GetLogger(typeof(HypervResourceControllerConfig)); + + public string PrivateIpAddress + { + get + { + return privateIpAddress; + } + set + { + ValidateIpAddress(value); + privateIpAddress = value; + System.Net.NetworkInformation.NetworkInterface nic = HypervResourceController.GetNicInfoFromIpAddress(privateIpAddress, out PrivateNetmask); + PrivateMacAddress = nic.GetPhysicalAddress().ToString(); + } + } + + private static void ValidateIpAddress(string value) + { + // Convert to IP address + IPAddress ipAddress; + if (!IPAddress.TryParse(value, out ipAddress)) + { + String errMsg = "Invalid PrivateIpAddress: " + value; + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + } + public string GatewayIpAddress; + public string PrivateMacAddress; + public string PrivateNetmask; + public string StorageNetmask; + public string StorageMacAddress; + public string StorageIpAddress; + public long RootDeviceReservedSpaceBytes; + public string RootDeviceName; + public ulong ParentPartitionMinMemoryMb; + public string LocalSecondaryStoragePath; + public string systemVmIso; + } + + /// + /// Supports one HTTP GET and multiple HTTP POST URIs + /// + /// + /// + /// POST takes dynamic to allow it to receive JSON without concern for what is the underlying object. + /// E.g. http://stackoverflow.com/questions/14071715/passing-dynamic-json-object-to-web-api-newtonsoft-example + /// and http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object + /// Use ActionName attribute to allow multiple POST URLs, one for each supported command + /// E.g. http://stackoverflow.com/a/12703423/939250 + /// Strictly speaking, this goes against the purpose of an ApiController, which is to provide one GET/POST/PUT/DELETE, etc. + /// However, it reduces the amount of code by removing the need for a switch according to the incoming command type. + /// http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx + /// + /// + /// Exceptions handled on command by command basis rather than globally to allow details of the command + /// to be reflected in the response. Default error handling is in the catch for Exception, but + /// other exception types may be caught where the feedback would be different. + /// NB: global alternatives discussed at + /// http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx + /// + /// + public class HypervResourceController : ApiController + { + public static void Configure(HypervResourceControllerConfig config) + { + HypervResourceController.config = config; + wmiCallsV2 = new WmiCallsV2(); + } + + public static HypervResourceControllerConfig config = new HypervResourceControllerConfig(); + + private static ILog logger = LogManager.GetLogger(typeof(HypervResourceController)); + private static string systemVmIso; + + public static void Initialize() + { + } + + public static IWmiCallsV2 wmiCallsV2 { get; set;} + + // GET api/HypervResource + public string Get() + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + return "HypervResource controller running, use POST to send JSON encoded RPCs"; ; + } + } + + /// + /// NOP - placeholder for future setup, e.g. delete existing VMs or Network ports + /// POST api/HypervResource/SetupCommand + /// + /// + /// + /// TODO: produce test + [HttpPost] + [ActionName(CloudStackTypes.SetupCommand)] + public JContainer SetupCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.SetupCommand + cmd.ToString()); + + string details = null; + bool result = false; + + try + { + NFSTO share = new NFSTO(); + String uriStr = (String)cmd.secondaryStorage; + share.uri = new Uri(uriStr); + + string systemVmIso = (string)cmd.systemVmIso; + string defaultDataPath = wmiCallsV2.GetDefaultDataRoot(); + string isoPath = Path.Combine(defaultDataPath, Path.GetFileName(systemVmIso)); + if (!File.Exists(isoPath)) + { + logger.Info("File " + isoPath + " not found. Copying it from the secondary share."); + Utils.DownloadCifsFileToLocalFile(systemVmIso, share, isoPath); + } + HypervResourceController.systemVmIso = isoPath; + result = true; + } + catch (Exception sysEx) + { + details = CloudStackTypes.SetupCommand + " failed due to " + sysEx.Message; + logger.Error(details, sysEx); + } + + object ansContent = new + { + result = result, + details = "success - NOP", + _reconnect = false + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.SetupAnswer); + } + } + + // POST api/HypervResource/AttachCommand + [HttpPost] + [ActionName(CloudStackTypes.AttachCommand)] + public JContainer AttachCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.AttachCommand + cmd.ToString()); + + string details = null; + bool result = false; + + try + { + string vmName = (string)cmd.vmName; + result = true; + } + catch (Exception sysEx) + { + details = CloudStackTypes.AttachCommand + " failed due to " + sysEx.Message; + logger.Error(details, sysEx); + } + + object ansContent = new + { + result = result, + details = details + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.AttachAnswer); + } + } + + // POST api/HypervResource/DetachCommand + [HttpPost] + [ActionName(CloudStackTypes.DettachCommand)] + public JContainer DetachCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.DettachCommand + cmd.ToString()); + + string details = null; + bool result = false; + + try + { + string vmName = (string)cmd.vmName; + result = true; + } + catch (Exception sysEx) + { + details = CloudStackTypes.DettachCommand + " failed due to " + sysEx.Message; + logger.Error(details, sysEx); + } + + object ansContent = new + { + result = result, + details = details + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.DettachAnswer); + } + } + + // POST api/HypervResource/DestroyCommand + [HttpPost] + [ActionName(CloudStackTypes.DestroyCommand)] + public JContainer DestroyCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.DestroyCommand + cmd.ToString()); + + string details = null; + bool result = false; + + try + { + // Assert + String errMsg = "No 'volume' details in " + CloudStackTypes.DestroyCommand + " " + cmd.ToString(); + if (cmd.volume == null) + { + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + + // Assert + errMsg = "No valide path in DestroyCommand in " + CloudStackTypes.DestroyCommand + " " + (String)cmd.ToString(); + if (cmd.volume.path == null) + { + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + + String path = (string)cmd.volume.path; + if (!File.Exists(path)) + { + logger.Info(CloudStackTypes.DestroyCommand + ", but volume at pass already deleted " + path); + } + + string vmName = (string)cmd.vmName; + if (!string.IsNullOrEmpty(vmName) && File.Exists(path)) + { + // Make sure that this resource is removed from the VM + wmiCallsV2.DetachDisk(vmName, path); + } + + File.Delete(path); + result = true; + } + catch (Exception sysEx) + { + details = CloudStackTypes.DestroyCommand + " failed due to " + sysEx.Message; + logger.Error(details, sysEx); + } + + object ansContent = new + { + result = result, + details = details + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); + } + } + + private static JArray ReturnCloudStackTypedJArray(object ansContent, string ansType) + { + JObject ansObj = Utils.CreateCloudStackObject(ansType, ansContent); + JArray answer = new JArray(ansObj); + logger.Info(ansObj.ToString()); + return answer; + } + + // POST api/HypervResource/CreateCommand + [HttpPost] + [ActionName(CloudStackTypes.CreateCommand)] + public JContainer CreateCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.CreateCommand + cmd.ToString()); + + string details = null; + bool result = false; + VolumeInfo volume = new VolumeInfo(); + + try + { + string diskType = cmd.diskCharacteristics.type; + ulong disksize = cmd.diskCharacteristics.size; + string templateUri = cmd.templateUrl; + + // assert: valid storagepool? + string poolTypeStr = cmd.pool.type; + string poolLocalPath = cmd.pool.path; + string poolUuid = cmd.pool.uuid; + string newVolPath = null; + long volId = cmd.volId; + string newVolName = null; + + if (ValidStoragePool(poolTypeStr, poolLocalPath, poolUuid, ref details)) + { + // No template URI? Its a blank disk. + if (string.IsNullOrEmpty(templateUri)) + { + // assert + VolumeType volType; + if (!Enum.TryParse(diskType, out volType) && volType != VolumeType.DATADISK) + { + details = "Cannot create volumes of type " + (string.IsNullOrEmpty(diskType) ? "NULL" : diskType); + } + else + { + newVolName = cmd.diskCharacteristics.name; + newVolPath = Path.Combine(poolLocalPath, newVolName, diskType.ToLower()); + // TODO: make volume format and block size configurable + wmiCallsV2.CreateDynamicVirtualHardDisk(disksize, newVolPath); + if (File.Exists(newVolPath)) + { + result = true; + } + else + { + details = "Failed to create DATADISK with name " + newVolName; + } + } + } + else + { + // TODO: Does this always work, or do I need to download template at times? + if (templateUri.Contains("/") || templateUri.Contains("\\")) + { + details = "Problem with templateURL " + templateUri + + " the URL should be volume UUID in primary storage created by previous PrimaryStorageDownloadCommand"; + logger.Error(details); + } + else + { + logger.Debug("Template's name in primary store should be " + templateUri); + // HypervPhysicalDisk BaseVol = primaryPool.getPhysicalDisk(tmplturl); + FileInfo srcFileInfo = new FileInfo(templateUri); + newVolName = Guid.NewGuid() + srcFileInfo.Extension; + newVolPath = Path.Combine(poolLocalPath, newVolName); + logger.Debug("New volume will be at " + newVolPath); + string oldVolPath = Path.Combine(poolLocalPath, templateUri); + File.Copy(oldVolPath, newVolPath); + if (File.Exists(newVolPath)) + { + result = true; + } + else + { + details = "Failed to create DATADISK with name " + newVolName; + } + } + volume = new VolumeInfo( + volId, diskType, + poolTypeStr, poolUuid, newVolName, + newVolPath, newVolPath, (long)disksize, null); + } + } + } + catch (Exception sysEx) + { + // TODO: consider this as model for error processing in all commands + details = CloudStackTypes.CreateCommand + " failed due to " + sysEx.Message; + logger.Error(details, sysEx); + } + + object ansContent = new + { + result = result, + details = details, + volume = volume + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CreateAnswer); + } + } + + // POST api/HypervResource/PrimaryStorageDownloadCommand + [HttpPost] + [ActionName(CloudStackTypes.PrimaryStorageDownloadCommand)] + public JContainer PrimaryStorageDownloadCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.PrimaryStorageDownloadCommand + cmd.ToString()); + string details = null; + bool result = false; + long size = 0; + string newCopyFileName = null; + + string poolLocalPath = cmd.localPath; + string poolUuid = cmd.poolUuid; + if (!Directory.Exists(poolLocalPath)) + { + details = "None existent local path " + poolLocalPath; + } + else + { + // Compose name for downloaded file. + string sourceUrl = cmd.url; + if (sourceUrl.ToLower().EndsWith(".vhd")) + { + newCopyFileName = Guid.NewGuid() + ".vhd"; + } + if (sourceUrl.ToLower().EndsWith(".vhdx")) + { + newCopyFileName = Guid.NewGuid() + ".vhdx"; + } + + // assert + if (newCopyFileName == null) + { + details = CloudStackTypes.PrimaryStorageDownloadCommand + " Invalid file extension for hypervisor type in source URL " + sourceUrl; + logger.Error(details); + } + else + { + try + { + FileInfo newFile; + if (CopyURI(sourceUrl, newCopyFileName, poolLocalPath, out newFile, ref details)) + { + size = newFile.Length; + result = true; + } + } + catch (System.Exception ex) + { + details = CloudStackTypes.PrimaryStorageDownloadCommand + " Cannot download source URL " + sourceUrl + " due to " + ex.Message; + logger.Error(details, ex); + } + } + } + + object ansContent = new + { + result = result, + details = details, + templateSize = size, + installPath = newCopyFileName + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.PrimaryStorageDownloadAnswer); + } + } + + private static bool ValidStoragePool(string poolTypeStr, string poolLocalPath, string poolUuid, ref string details) + { + StoragePoolType poolType; + if (!Enum.TryParse(poolTypeStr, out poolType) || poolType != StoragePoolType.Filesystem) + { + details = "Primary storage pool " + poolUuid + " type " + poolType + " local path " + poolLocalPath + " has invalid StoragePoolType"; + logger.Error(details); + return false; + } + else if (!Directory.Exists(poolLocalPath)) + { + details = "Primary storage pool " + poolUuid + " type " + poolType + " local path " + poolLocalPath + " has invalid local path"; + logger.Error(details); + return false; + } + return true; + } + + /// + /// Exceptions to watch out for: + /// Exceptions related to URI creation + /// System.SystemException + /// +-System.ArgumentNullException + /// +-System.FormatException + /// +-System.UriFormatException + /// + /// Exceptions related to NFS URIs + /// System.SystemException + /// +-System.NotSupportedException + /// +-System.ArgumentException + /// +-System.ArgumentNullException + /// +-System.Security.SecurityException; + /// +-System.UnauthorizedAccessException + /// +-System.IO.IOException + /// +-System.IO.PathTooLongException + /// + /// Exceptions related to HTTP URIs + /// System.SystemException + /// +-System.InvalidOperationException + /// +-System.Net.WebException + /// +-System.NotSupportedException + /// +-System.ArgumentNullException + /// + /// + /// + /// + /// + private bool CopyURI(string sourceUri, string newCopyFileName, string poolLocalPath, out FileInfo newFile, ref string details) + { + Uri source = new Uri(sourceUri); + String destFilePath = Path.Combine(poolLocalPath, newCopyFileName); + string[] pathSegments = source.Segments; + String templateUUIDandExtension = pathSegments[pathSegments.Length - 1]; + newFile = new FileInfo(destFilePath); + + // NFS URI assumed to already be mounted locally. Mount location given by settings. + if (source.Scheme.ToLower().Equals("nfs")) + { + String srcDiskPath = Path.Combine(HypervResourceController.config.LocalSecondaryStoragePath, templateUUIDandExtension); + String taskMsg = "Copy NFS url in " + sourceUri + " at " + srcDiskPath + " to pool " + poolLocalPath; + logger.Debug(taskMsg); + File.Copy(srcDiskPath, destFilePath); + } + else if (source.Scheme.ToLower().Equals("http") || source.Scheme.ToLower().Equals("https")) + { + System.Net.WebClient webclient = new WebClient(); + webclient.DownloadFile(source, destFilePath); + } + else + { + details = "Unsupported URI scheme " + source.Scheme.ToLower() + " in source URI " + sourceUri; + logger.Error(details); + return false; + } + + if (!File.Exists(destFilePath)) + { + details = "Filed to copy " + sourceUri + " to primary pool destination " + destFilePath; + logger.Error(details); + return false; + } + return true; + } + + // POST api/HypervResource/CheckHealthCommand + // TODO: create test + [HttpPost] + [ActionName(CloudStackTypes.CheckHealthCommand)] + public JContainer CheckHealthCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.CheckHealthCommand + cmd.ToString()); + object ansContent = new + { + result = true, + details = "resource is alive" + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckHealthAnswer); + } + } + + // POST api/HypervResource/CheckSshCommand + // TODO: create test + [HttpPost] + [ActionName(CloudStackTypes.CheckSshCommand)] + public JContainer CheckSshCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.CheckSshCommand + cmd.ToString()); + object ansContent = new + { + result = true, + details = "NOP, TODO: implement properly" + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckSshAnswer); + } + } + + // POST api/HypervResource/CheckVirtualMachineCommand + [HttpPost] + [ActionName(CloudStackTypes.CheckVirtualMachineCommand)] + public JContainer CheckVirtualMachineCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.CheckVirtualMachineCommand + cmd.ToString()); + string details = null; + bool result = false; + string vmName = cmd.vmName; + string state = null; + + // TODO: Look up the VM, convert Hyper-V state to CloudStack version. + var sys = wmiCallsV2.GetComputerSystem(vmName); + if (sys == null) + { + details = CloudStackTypes.CheckVirtualMachineCommand + " requested unknown VM " + vmName; + logger.Error(details); + } + else + { + state = EnabledState.ToString(sys.EnabledState); // TODO: V2 changes? + result = true; + } + + object ansContent = new + { + result = result, + details = details, + state = state + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckVirtualMachineAnswer); + } + } + + // POST api/HypervResource/DeleteStoragePoolCommand + [HttpPost] + [ActionName(CloudStackTypes.DeleteStoragePoolCommand)] + public JContainer DeleteStoragePoolCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.DeleteStoragePoolCommand + cmd.ToString()); + object ansContent = new + { + result = true, + details = "Current implementation does not delete local path corresponding to storage pool!" + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); + } + } + + /// + /// NOP - legacy command - + /// POST api/HypervResource/CreateStoragePoolCommand + /// + /// + /// + [HttpPost] + [ActionName(CloudStackTypes.CreateStoragePoolCommand)] + public JContainer CreateStoragePoolCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.CreateStoragePoolCommand + cmd.ToString()); + object ansContent = new + { + result = true, + details = "success - NOP" + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); + } + } + + // POST api/HypervResource/ModifyStoragePoolCommand + [HttpPost] + [ActionName(CloudStackTypes.ModifyStoragePoolCommand)] + public JContainer ModifyStoragePoolCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.ModifyStoragePoolCommand + cmd.ToString()); + string details = null; + string localPath; + object ansContent; + + bool result = ValidateStoragePoolCommand(cmd, out localPath, ref details); + if (!result) + { + ansContent = new + { + result = result, + details = details + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); + } + + var tInfo = new Dictionary(); + long capacityBytes; + long availableBytes; + GetCapacityForLocalPath(localPath, out capacityBytes, out availableBytes); + + String uuid = null; + var poolInfo = new + { + uuid = uuid, + host = cmd.pool.host, + localPath = cmd.pool.host, + hostPath = cmd.localPath, + poolType = cmd.pool.type, + capacityBytes = capacityBytes, + availableBytes = availableBytes + }; + + ansContent = new + { + result = result, + details = details, + templateInfo = tInfo, + poolInfo = poolInfo + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.ModifyStoragePoolAnswer); + } + } + + private bool ValidateStoragePoolCommand(dynamic cmd, out string localPath, ref string details) + { + dynamic pool = cmd.pool; + string poolTypeStr = pool.type; + StoragePoolType poolType; + localPath = cmd.localPath; + if (!Enum.TryParse(poolTypeStr, out poolType) || poolType != StoragePoolType.Filesystem) + { + details = "Request to create / modify unsupported pool type: " + (poolTypeStr == null ? "NULL" : poolTypeStr) + "in cmd " + JsonConvert.SerializeObject(cmd); + logger.Error(details); + return false; + } + if (!Directory.Exists(localPath)) + { + details = "Request to create / modify unsupported StoragePoolType.Filesystem with non-existent path:" + (localPath == null ? "NULL" : localPath) + "in cmd " + JsonConvert.SerializeObject(cmd); + logger.Error(details); + return false; + } + return true; + } + + + // POST api/HypervResource/CleanupNetworkRulesCmd + [HttpPost] + [ActionName(CloudStackTypes.CleanupNetworkRulesCmd)] + public JContainer CleanupNetworkRulesCmd([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.CleanupNetworkRulesCmd + cmd.ToString()); + object ansContent = new + { + result = false, + details = "nothing to cleanup in our current implementation" + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); + } + } + + // POST api/HypervResource/CheckNetworkCommand + [HttpPost] + [ActionName(CloudStackTypes.CheckNetworkCommand)] + public JContainer CheckNetworkCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.CheckNetworkCommand + cmd.ToString()); + object ansContent = new + { + result = true, + details = (string)null + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckNetworkAnswer); + } + } + + // POST api/HypervResource/ReadyCommand + [HttpPost] + [ActionName(CloudStackTypes.ReadyCommand)] + public JContainer ReadyCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.ReadyCommand + cmd.ToString()); + object ansContent = new + { + result = true, + details = (string)null + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.ReadyAnswer); + } + + } + + // POST api/HypervResource/StartCommand + [HttpPost] + [ActionName(CloudStackTypes.StartCommand)] + public JContainer StartCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.StartCommand + cmd.ToString()); // TODO: Security hole? VM data printed to log + string details = null; + bool result = false; + + try + { + wmiCallsV2.DeployVirtualMachine(cmd, systemVmIso); + result = true; + } + catch (Exception wmiEx) + { + details = CloudStackTypes.StartCommand + " fail on exception" + wmiEx.Message; + logger.Error(details, wmiEx); + } + + object ansContent = new + { + result = result, + details = details, + vm = cmd.vm + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.StartAnswer); + } + } + + // POST api/HypervResource/StopCommand + [HttpPost] + [ActionName(CloudStackTypes.StopCommand)] + public JContainer StopCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.StopCommand + cmd.ToString()); + string details = null; + bool result = false; + + try + { + wmiCallsV2.DestroyVm(cmd); + result = true; + } + catch (Exception wmiEx) + { + details = CloudStackTypes.StopCommand + " fail on exception" + wmiEx.Message; + logger.Error(details, wmiEx); + } + + object ansContent = new + { + result = result, + details = details, + vm = cmd.vm + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.StopAnswer); + } + } + + // POST api/HypervResource/MaintainCommand + // TODO: should this be a NOP? + [HttpPost] + [ActionName(CloudStackTypes.MaintainCommand)] + public JContainer MaintainCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.MaintainCommand + cmd.ToString()); + + object ansContent = new + { + result = true, + details = "success - NOP for MaintainCommand", + _reconnect = false + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.MaintainAnswer); + } + } + + // POST api/HypervResource/PingRoutingCommand + // TODO: should this be a NOP? + [HttpPost] + [ActionName(CloudStackTypes.PingRoutingCommand)] + public JContainer PingRoutingCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.PingRoutingCommand + cmd.ToString()); + + object ansContent = new + { + result = true, + details = "success - NOP for PingRoutingCommand", + _reconnect = false + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); + } + } + + // POST api/HypervResource/PingCommand + // TODO: should this be a NOP? + [HttpPost] + [ActionName(CloudStackTypes.PingCommand)] + public JContainer PingCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.PingCommand + cmd.ToString()); + + object ansContent = new + { + result = true, + details = "success - NOP for PingCommand", + _reconnect = false + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); + } + } + + // POST api/HypervResource/GetVmStatsCommand + [HttpPost] + [ActionName(CloudStackTypes.GetVmStatsCommand)] + public JContainer GetVmStatsCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + 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); + + var vmsToInspect = new List(); + foreach (var vmName in vmNames) + { + var sys = wmiCallsV2.GetComputerSystem(vmName); + if (sys == null) + { + logger.InfoFormat("GetVmStatsCommand requested unknown VM {0}", vmNames); + continue; + } + var sysInfo = wmiCallsV2.GetVmSettings(sys); + vmsToInspect.Add(sysInfo.Path); + } + + wmiCallsV2.GetSummaryInfo(vmProcessorInfo, vmsToInspect); + + // TODO: Network usage comes from Performance Counter API; however it is only available in kb/s, and not in total terms. + // Curious about these? Use perfmon to inspect them, e.g. http://msdn.microsoft.com/en-us/library/xhcx5a20%28v=vs.100%29.aspx + // Recent post on these counter at http://blogs.technet.com/b/cedward/archive/2011/07/19/hyper-v-networking-optimizations-part-6-of-6-monitoring-hyper-v-network-consumption.aspx + result = true; + + object ansContent = new + { + vmInfos = vmProcessorInfo, + result = result, + details = details, + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.GetVmStatsAnswer); + } + } + + // POST api/HypervResource/CopyCommand + [HttpPost] + [ActionName(CloudStackTypes.CopyCommand)] + public JContainer CopyCommand(dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + // Log command *after* we've removed security details from the command. + + bool result = false; + string details = null; + object newData = null; + + try + { + dynamic timeout = cmd.wait; // TODO: Useful? + + TemplateObjectTO srcTemplateObjectTO = TemplateObjectTO.ParseJson(cmd.srcTO); + TemplateObjectTO destTemplateObjectTO = TemplateObjectTO.ParseJson(cmd.destTO); + VolumeObjectTO destVolumeObjectTO = VolumeObjectTO.ParseJson(cmd.destTO); + + logger.Info(CloudStackTypes.CopyCommand + cmd.ToString()); + + // Already exists? + if (destTemplateObjectTO != null && + File.Exists(destTemplateObjectTO.FullFileName) && + !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); + } + + // Do we have to create a new one? + if (!result) + { + // Create local copy of a template? + if (srcTemplateObjectTO != null && destTemplateObjectTO != null) + { + // S3 download to primary storage? + // 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); + File.Delete(destFile); + } + + if (srcTemplateObjectTO.s3DataStoreTO != null) + { + // Download from S3 to destination data storage + DownloadS3ObjectToFile(srcTemplateObjectTO.path, srcTemplateObjectTO.s3DataStoreTO, destFile); + } + else if (srcTemplateObjectTO.nfsDataStoreTO != null) + { + // Download from S3 to destination data storage + Utils.DownloadCifsFileToLocalFile(srcTemplateObjectTO.path, srcTemplateObjectTO.nfsDataStoreTO, destFile); + } + + // Uncompress, as required + if (srcTemplateObjectTO.path.EndsWith(".bz2")) + { + String uncompressedFile = destFile + ".tmp"; + String compressedFile = destFile; + using (var uncompressedOutStrm = new FileStream(uncompressedFile, FileMode.CreateNew, FileAccess.Write)) + { + using (var compressedInStrm = new FileStream(destFile, FileMode.Open, FileAccess.Read)) + { + using (var bz2UncompressorStrm = new Ionic.BZip2.BZip2InputStream(compressedInStrm, true) /* outer 'using' statement will close FileStream*/ ) + { + int count = 0; + int bufsize = 1024 * 1024; + byte[] buf = new byte[bufsize]; + + // EOF returns -1, see http://dotnetzip.codeplex.com/workitem/16069 + while (0 < (count = bz2UncompressorStrm.Read(buf, 0, bufsize))) + { + uncompressedOutStrm.Write(buf, 0, count); + } + } + } + } + File.Delete(compressedFile); + File.Move(uncompressedFile, compressedFile); + if (File.Exists(uncompressedFile)) + { + String errMsg = "Extra file left around called " + uncompressedFile + " when creating " + destFile; + logger.Error(errMsg); + throw new IOException(errMsg); + } + } + + // assert + if (!File.Exists(destFile)) + { + String errMsg = "Failed to create " + destFile + " , because the file is missing"; + logger.Error(errMsg); + throw new IOException(errMsg); + } + + newData = cmd.destTO; + result = true; + } + else + { + details = "Data store combination not supported"; + } + } + // Create volume from a template? + else if (srcTemplateObjectTO != null && destVolumeObjectTO != null) + { + if (destVolumeObjectTO.format == null) + { + destVolumeObjectTO.format = srcTemplateObjectTO.format; + } + string destFile = destVolumeObjectTO.FullFileName; + string srcFile = srcTemplateObjectTO.FullFileName; + + if (!File.Exists(srcFile)) + { + details = "Local template file missing from " + srcFile; + } + else + { + if (File.Exists(destFile)) + { + logger.Info("Deleting existing file " + destFile); + File.Delete(destFile); + } + + // TODO: thin provision instead of copying the full file. + File.Copy(srcFile, destFile); + newData = cmd.destTO; + result = true; + } + } + else + { + details = "Data store combination not supported"; + } + } + } + catch (Exception ex) + { + // Test by providing wrong key + details = CloudStackTypes.CopyCommand + " failed on exception, " + ex.Message; + logger.Error(details, ex); + } + + object ansContent = new + { + result = result, + details = details, + newData = cmd.destTO + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CopyCmdAnswer); + } + } + + private static bool VerifyChecksum(string destFile, string checksum) + { + string localChecksum = BitConverter.ToString(CalcFileChecksum(destFile)).Replace("-", "").ToLower(); + logger.Debug("Checksum of " + destFile + " is " + checksum); + if (checksum.Equals(localChecksum)) + { + return true; + } + return true; + } + + /// + /// Match implmentation of DownloadManagerImpl.computeCheckSum + /// + /// + /// + private static byte[] CalcFileChecksum(string destFile) + { + // TODO: Add unit test to verify that checksum algorithm has not changed. + using (MD5 md5 = MD5.Create()) + { + using (FileStream stream = File.OpenRead(destFile)) + { + return md5.ComputeHash(stream); + } + } + } + + private static void DownloadS3ObjectToFile(string srcObjectKey, S3TO srcS3TO, string destFile) + { + AmazonS3Config S3Config = new AmazonS3Config + { + ServiceURL = srcS3TO.endpoint, + CommunicationProtocol = Amazon.S3.Model.Protocol.HTTP + }; + + if (srcS3TO.httpsFlag) + { + S3Config.CommunicationProtocol = Protocol.HTTPS; + } + + try + { + using (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(srcS3TO.accessKey, srcS3TO.secretKey, S3Config)) + { + GetObjectRequest getObjectRequest = new GetObjectRequest().WithBucketName(srcS3TO.bucketName).WithKey(srcObjectKey); + + using (S3Response getObjectResponse = client.GetObject(getObjectRequest)) + { + using (Stream s = getObjectResponse.ResponseStream) + { + using (FileStream fs = new FileStream(destFile, FileMode.Create, FileAccess.Write)) + { + byte[] data = new byte[524288]; + int bytesRead = 0; + do + { + bytesRead = s.Read(data, 0, data.Length); + fs.Write(data, 0, bytesRead); + } + while (bytesRead > 0); + fs.Flush(); + } + } + } + } + } + catch (Exception ex) + { + string errMsg = "Download from S3 url" + srcS3TO.endpoint + " said: " + ex.Message; + logger.Error(errMsg, ex); + throw new Exception(errMsg, ex); + } + } + + // POST api/HypervResource/GetStorageStatsCommand + [HttpPost] + [ActionName(CloudStackTypes.GetStorageStatsCommand)] + public JContainer GetStorageStatsCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.GetStorageStatsCommand + cmd.ToString()); + bool result = false; + string details = null; + long capacity = 0; + long available = 0; + long used = 0; + try + { + string localPath = (string)cmd.localPath; + GetCapacityForLocalPath(localPath, out capacity, out available); + used = capacity - available; + result = true; + logger.Debug(CloudStackTypes.GetStorageStatsCommand + " set used bytes to " + used); + } + catch (Exception ex) + { + details = CloudStackTypes.GetStorageStatsCommand + " failed on exception" + ex.Message; + logger.Error(details, ex); + } + + object ansContent = new + { + result = result, + details = details, + capacity = capacity, + used = used + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.GetStorageStatsAnswer); + } + } + + // POST api/HypervResource/GetHostStatsCommand + [HttpPost] + [ActionName(CloudStackTypes.GetHostStatsCommand)] + public JContainer GetHostStatsCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.GetHostStatsCommand + cmd.ToString()); + bool result = false; + string details = null; + object hostStats = null; + + var entityType = "host"; + ulong totalMemoryKBs; + ulong freeMemoryKBs; + double networkReadKBs; + double networkWriteKBs; + double cpuUtilization; + + try + { + long hostId = (long)cmd.hostId; + wmiCallsV2.GetMemoryResources(out totalMemoryKBs, out freeMemoryKBs); + wmiCallsV2.GetProcessorUsageInfo(out cpuUtilization); + + // TODO: can we assume that the host has only one adaptor? + string tmp; + var privateNic = GetNicInfoFromIpAddress(config.PrivateIpAddress, out tmp); + var nicStats = privateNic.GetIPv4Statistics(); //TODO: add IPV6 support, currentl + networkReadKBs = nicStats.BytesReceived; + networkWriteKBs = nicStats.BytesSent; + + // Generate GetHostStatsAnswer + hostStats = new + { + hostId = hostId, + entityType = entityType, + cpuUtilization = cpuUtilization, + networkReadKBs = networkReadKBs, + networkWriteKBs = networkWriteKBs, + totalMemoryKBs = (double)totalMemoryKBs, + freeMemoryKBs = (double)freeMemoryKBs + }; + result = true; + } + catch (Exception ex) + { + details = CloudStackTypes.GetHostStatsCommand + " failed on exception" + ex.Message; + logger.Error(details, ex); + } + + object ansContent = new + { + result = result, + hostStats = hostStats, + details = details + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.GetHostStatsAnswer); + } + } + + // POST api/HypervResource/StartupCommand + [HttpPost] + [ActionName(CloudStackTypes.StartupCommand)] + public JContainer StartupCommand([FromBody]dynamic cmdArray) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(cmdArray.ToString()); + // Log agent configuration + logger.Info("Agent StartupRoutingCommand received " + cmdArray.ToString()); + dynamic strtRouteCmd = cmdArray[0][CloudStackTypes.StartupRoutingCommand]; + + // Insert networking details + strtRouteCmd.privateIpAddress = config.PrivateIpAddress; + strtRouteCmd.privateNetmask = config.PrivateNetmask; + strtRouteCmd.privateMacAddress = config.PrivateMacAddress; + strtRouteCmd.storageIpAddress = config.PrivateIpAddress; + strtRouteCmd.storageNetmask = config.PrivateNetmask; + strtRouteCmd.storageMacAddress = config.PrivateMacAddress; + strtRouteCmd.gatewayIpAddress = config.GatewayIpAddress; + strtRouteCmd.caps = "hvm"; + + // Detect CPUs, speed, memory + uint cores; + uint mhz; + wmiCallsV2.GetProcessorResources(out cores, out mhz); + strtRouteCmd.cpus = cores; + strtRouteCmd.speed = mhz; + ulong memoryKBs; + ulong freeMemoryKBs; + wmiCallsV2.GetMemoryResources(out memoryKBs, out freeMemoryKBs); + strtRouteCmd.memory = memoryKBs * 1024; // Convert to bytes + + // Need 2 Gig for DOM0, see http://technet.microsoft.com/en-us/magazine/hh750394.aspx + strtRouteCmd.dom0MinMemory = config.ParentPartitionMinMemoryMb * 1024 * 1024; // Convert to bytes + + // Insert storage pool details. + // + // Read the localStoragePath for virtual disks from the Hyper-V configuration + // See http://blogs.msdn.com/b/virtual_pc_guy/archive/2010/05/06/managing-the-default-virtual-machine-location-with-hyper-v.aspx + // for discussion of Hyper-V file locations paths. + string localStoragePath = wmiCallsV2.GetDefaultVirtualDiskFolder(); + if (localStoragePath != null) + { + // GUID arbitrary. Host agents deals with storage pool in terms of localStoragePath. + // We use HOST guid. + string poolGuid = strtRouteCmd.guid; + + if (poolGuid == null) + { + poolGuid = Guid.NewGuid().ToString(); + logger.InfoFormat("Setting Startup StoragePool GUID to " + poolGuid); + } + else + { + logger.InfoFormat("Setting Startup StoragePool GUID same as HOST, i.e. " + poolGuid); + } + + long capacity; + long available; + GetCapacityForLocalPath(localStoragePath, out capacity, out available); + + logger.Debug(CloudStackTypes.StartupStorageCommand + " set available bytes to " + available); + + string ipAddr = strtRouteCmd.privateIpAddress; + StoragePoolInfo pi = new StoragePoolInfo( + poolGuid.ToString(), + ipAddr, + localStoragePath, + localStoragePath, + StoragePoolType.Filesystem.ToString(), + capacity, + available); + + // Build StartupStorageCommand using an anonymous type + // See http://stackoverflow.com/a/6029228/939250 + object ansContent = new + { + poolInfo = pi, + guid = pi.uuid, + dataCenter = strtRouteCmd.dataCenter, + resourceType = StorageResourceType.STORAGE_POOL.ToString() // TODO: check encoding + }; + JObject ansObj = Utils.CreateCloudStackObject(CloudStackTypes.StartupStorageCommand, ansContent); + cmdArray.Add(ansObj); + } + + // Convert result to array for type correctness? + logger.Info(CloudStackTypes.StartupCommand + " result is " + cmdArray.ToString()); + return cmdArray; + } + } + + public static System.Net.NetworkInformation.NetworkInterface GetNicInfoFromIpAddress(string ipAddress, out string subnet) + { + System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); + foreach (var nic in nics) + { + subnet = null; + // TODO: use to remove NETMASK and MAC from the config file, and to validate the IPAddress. + var nicProps = nic.GetIPProperties(); + bool found = false; + foreach (var addr in nicProps.UnicastAddresses) + { + if (addr.Address.Equals(IPAddress.Parse(ipAddress))) + { + subnet = addr.IPv4Mask.ToString(); + found = true; + } + } + if (!found) + { + continue; + } + return nic; + } + throw new ArgumentException("No NIC for ipAddress " + ipAddress); + } + + public static void GetCapacityForLocalPath(string localStoragePath, out long capacityBytes, out long availableBytes) + { + // NB: DriveInfo does not work for remote folders (http://stackoverflow.com/q/1799984/939250) + // DriveInfo requires a driver letter... + string fullPath = Path.GetFullPath(localStoragePath); + System.IO.DriveInfo poolInfo = new System.IO.DriveInfo(fullPath); + capacityBytes = poolInfo.TotalSize; + availableBytes = poolInfo.AvailableFreeSpace; + + // Don't allow all of the Root Device to be used for virtual disks + if (poolInfo.RootDirectory.Name.ToLower().Equals(config.RootDeviceName)) + { + availableBytes -= config.RootDeviceReservedSpaceBytes; + availableBytes = availableBytes > 0 ? availableBytes : 0; + capacityBytes -= config.RootDeviceReservedSpaceBytes; + capacityBytes = capacityBytes > 0 ? capacityBytes : 0; + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/IWmiCallsV2.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/IWmiCallsV2.cs new file mode 100644 index 00000000000..125c53ec384 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/IWmiCallsV2.cs @@ -0,0 +1,67 @@ +// 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.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2; +using System.Management; + +namespace HypervResource +{ + public interface IWmiCallsV2 + { + System.Management.ManagementPath AddDiskDriveToVm(ComputerSystem vm, string vhdfile, string cntrllerAddr, string driveResourceType); + ComputerSystem AddUserData(ComputerSystem vm, string userData); + void AttachIso(string displayName, string iso); + void CreateDynamicVirtualHardDisk(ulong MaxInternalSize, string Path); + SyntheticEthernetPortSettingData CreateNICforVm(ComputerSystem vm, string mac); + ComputerSystem CreateVM(string name, long memory_mb, int vcpus); + void DeleteHostKvpItem(ComputerSystem vm, string key); + void DeleteSwitchPort(string elementName); + ComputerSystem DeployVirtualMachine(dynamic jsonObj, string systemVmIso); + void DestroyVm(dynamic jsonObj); + void DestroyVm(string displayName); + void DetachDisk(string displayName, string diskFileName); + ComputerSystem GetComputerSystem(string displayName); + string GetDefaultDataRoot(); + string GetDefaultVirtualDiskFolder(); + ResourceAllocationSettingData GetDvdDriveSettings(VirtualSystemSettingData vmSettings); + EthernetPortAllocationSettingData[] GetEthernetConnections(ComputerSystem vm); + SyntheticEthernetPortSettingData[] GetEthernetPortSettings(ComputerSystem vm); + ResourceAllocationSettingData GetIDEControllerSettings(VirtualSystemSettingData vmSettings, string cntrllerAddr); + ImageManagementService GetImageManagementService(); + KvpExchangeComponentSettingData GetKvpSettings(VirtualSystemSettingData vmSettings); + void GetMemoryResources(out ulong physicalRamKBs, out ulong freeMemoryKBs); + MemorySettingData GetMemSettings(VirtualSystemSettingData vmSettings); + void GetProcessorResources(out uint cores, out uint mhz); + void GetProcessorUsageInfo(out double cpuUtilization); + ProcessorSettingData GetProcSettings(VirtualSystemSettingData vmSettings); + ResourceAllocationSettingData.ResourceAllocationSettingDataCollection GetResourceAllocationSettings(VirtualSystemSettingData vmSettings); + void GetSummaryInfo(System.Collections.Generic.Dictionary vmProcessorInfo, System.Collections.Generic.List vmsToInspect); + SyntheticEthernetPortSettingData GetSyntheticEthernetPortSettings(EthernetSwitchPort port); + VirtualSystemManagementService GetVirtualisationSystemManagementService(); + VirtualEthernetSwitchManagementService GetVirtualSwitchManagementService(); + EthernetSwitchPortVlanSettingData GetVlanSettings(EthernetPortAllocationSettingData ethernetConnection); + System.Collections.Generic.List GetVmElementNames(); + VirtualSystemSettingData GetVmSettings(ComputerSystem vm); + void patchSystemVmIso(string vmName, string systemVmIso); + void SetState(ComputerSystem vm, ushort requiredState); + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/Properties/AssemblyInfo.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..7bbc9b55adb --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/Properties/AssemblyInfo.cs @@ -0,0 +1,53 @@ +// 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.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("HypervResource")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("HypervResource")] +[assembly: AssemblyCopyright("Copyright © 2013")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("f1eb80c1-36fb-438c-a70d-0de5d5e295fb")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/Utils.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/Utils.cs new file mode 100644 index 00000000000..e55f2ad1e99 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/Utils.cs @@ -0,0 +1,131 @@ +// 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 log4net; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Security.Principal; +using System.Text; +using System.Threading.Tasks; + +namespace HypervResource +{ + public class Utils + { + private static ILog s_logger = LogManager.GetLogger(typeof(Utils)); + + /// + /// Associate CloudStack object's content with a fully qualified type name. + /// + /// Fully qualified type name, e.g. "org.apache.cloudstack.storage.to.TemplateObjectTO" + /// Object's data, can be an anonymous object, e.g. + /// + public static JObject CreateCloudStackObject(string objType, object objValue) + { + JToken objContent = JToken.FromObject(objValue); + JProperty objTypeValuePairing = new JProperty(objType, objContent); + + return new JObject(objTypeValuePairing); + } + + + /// + /// Copy file on network share to local volume. + /// + /// + /// Access to the network share is acheived by logging into the domain corresponding to the user credentials provided. + /// Windows impersonation does not suffice, because impersonation is limited to domains with an established trust relationship. + /// We have had to import Win32 API calls to allow login. There are a number of examples online. We follow the + /// one at http://stackoverflow.com/a/2541569/939250 + /// + /// + /// + public static void DownloadCifsFileToLocalFile(string filePathRelativeToShare, NFSTO cifsShareDetails, string destFile) + { + try + { + IntPtr token = IntPtr.Zero; + + bool isSuccess = LogonUser(cifsShareDetails.User, cifsShareDetails.Domain, cifsShareDetails.Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token); + using (WindowsImpersonationContext remoteIdentity = new WindowsIdentity(token).Impersonate()) + { + String dest = ""; + if (filePathRelativeToShare.EndsWith(".iso") || filePathRelativeToShare.EndsWith(".vhd") || filePathRelativeToShare.EndsWith(".vhdx")) + { + dest = Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare); + dest = dest.Replace('/', Path.DirectorySeparatorChar); + } + // if the filePathRelativeToShare string don't have filename and only a dir point then find the vhd files in that folder and use + // In the clean setup, first copy command wont be having the filename it contains onlyu dir path. + // we need to scan the folder point and then copy the file to destination. + else if (!filePathRelativeToShare.EndsWith(".vhd") || !filePathRelativeToShare.EndsWith(".vhdx")) + { + // scan the folder and get the vhd filename. + String uncPath = Path.Combine(cifsShareDetails.UncPath, Path.Combine(filePathRelativeToShare.Split('/'))); + //uncPath = uncPath.Replace("/", "\\"); + DirectoryInfo dir = new DirectoryInfo(uncPath); + FileInfo[] vhdFiles = dir.GetFiles("*.vhd*"); + if (vhdFiles.Length > 0) + { + FileInfo file = vhdFiles[0]; + dest = file.FullName; + } + } + s_logger.Info(CloudStackTypes.CopyCommand + ": copy " + Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare) + " to " + destFile); + + File.Copy(dest, destFile, true); + remoteIdentity.Undo(); + } + } + catch (UnauthorizedAccessException ex) + { + string errMsg = "Invalid user or password for the share " + cifsShareDetails.UncPath; + s_logger.Error(errMsg); + + throw new ArgumentException(errMsg, ex); + } + } + + // from http://stackoverflow.com/a/2541569/939250 + #region imports + [DllImport("advapi32.dll", SetLastError = true)] + private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); + + [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] + private static extern bool CloseHandle(IntPtr handle); + + [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] + public extern static bool DuplicateToken(IntPtr existingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr duplicateTokenHandle); + #endregion + + #region logon consts + // logon types + const int LOGON32_LOGON_INTERACTIVE = 2; + const int LOGON32_LOGON_NETWORK = 3; + const int LOGON32_LOGON_NEW_CREDENTIALS = 9; + + // logon providers + const int LOGON32_PROVIDER_DEFAULT = 0; + const int LOGON32_PROVIDER_WINNT50 = 3; + const int LOGON32_PROVIDER_WINNT40 = 2; + const int LOGON32_PROVIDER_WINNT35 = 1; + #endregion + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCallsV2.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCallsV2.cs new file mode 100644 index 00000000000..18b96cc6ac1 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCallsV2.cs @@ -0,0 +1,2120 @@ +// 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.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2; +using log4net; +using System.Globalization; +using System.Management; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using CloudStack.Plugin.WmiWrappers.ROOT.CIMV2; +using System.IO; +using System.Net.NetworkInformation; +using System.Net; + +namespace HypervResource +{ + public class WmiCallsV2 : IWmiCallsV2 + { + public static String CloudStackUserDataKey = "cloudstack-vm-userdata"; + + public static void Initialize() + { + // Trigger assembly load into curren appdomain + } + + private static ILog logger = LogManager.GetLogger(typeof(WmiCallsV2)); + + /// + /// Returns ping status of the given ip + /// + public static String PingHost(String ip) + { + return "Success"; + } + + /// + /// Returns ComputerSystem lacking any NICs and VOLUMEs + /// + public ComputerSystem AddUserData(ComputerSystem vm, string userData) + { + // Obtain controller for Hyper-V virtualisation subsystem + VirtualSystemManagementService vmMgmtSvc = GetVirtualisationSystemManagementService(); + + // Create object to hold the data. + KvpExchangeDataItem kvpItem = KvpExchangeDataItem.CreateInstance(); + kvpItem.LateBoundObject["Name"] = WmiCallsV2.CloudStackUserDataKey; + kvpItem.LateBoundObject["Data"] = userData; + kvpItem.LateBoundObject["Source"] = 0; + logger.Debug("VM " + vm.Name + " gets userdata " + userData); + + // Update the resource settings for the VM. + System.Management.ManagementBaseObject kvpMgmtObj = kvpItem.LateBoundObject; + System.Management.ManagementPath jobPath; + String kvpStr = kvpMgmtObj.GetText(System.Management.TextFormat.CimDtd20); + uint ret_val = vmMgmtSvc.AddKvpItems(new String[] { kvpStr }, vm.Path, out jobPath); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to update VM {0} (GUID {1}) due to {2} (ModifyVirtualSystem call), existing VM not deleted", + vm.ElementName, + vm.Name, + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + return vm; + } + + /// + /// Returns ComputerSystem lacking any NICs and VOLUMEs + /// + public ComputerSystem CreateVM(string name, long memory_mb, int vcpus) + { + // Obtain controller for Hyper-V virtualisation subsystem + VirtualSystemManagementService vmMgmtSvc = GetVirtualisationSystemManagementService(); + + // Create VM with correct name and default resources + ComputerSystem vm = CreateDefaultVm(vmMgmtSvc, name); + + // Update the resource settings for the VM. + + // Resource settings are referenced through the Msvm_VirtualSystemSettingData object. + VirtualSystemSettingData vmSettings = GetVmSettings(vm); + + // For memory settings, there is no Dynamic Memory, so reservation, limit and quantity are identical. + MemorySettingData memSettings = GetMemSettings(vmSettings); + memSettings.LateBoundObject["VirtualQuantity"] = memory_mb; + memSettings.LateBoundObject["Reservation"] = memory_mb; + memSettings.LateBoundObject["Limit"] = memory_mb; + + // Update the processor settings for the VM, static assignment of 100% for CPU limit + ProcessorSettingData procSettings = GetProcSettings(vmSettings); + procSettings.LateBoundObject["VirtualQuantity"] = vcpus; + procSettings.LateBoundObject["Reservation"] = vcpus; + procSettings.LateBoundObject["Limit"] = 100000; + + ModifyVmResources(vmMgmtSvc, vm, new String[] { + memSettings.LateBoundObject.GetText(TextFormat.CimDtd20), + procSettings.LateBoundObject.GetText(TextFormat.CimDtd20) + }); + logger.InfoFormat("VM with display name {0} has GUID {1}", vm.ElementName, vm.Name); + logger.DebugFormat("Resources for vm {0}: {1} MB memory, {2} vcpus", name, memory_mb, vcpus); + + return vm; + } + + /// + /// Create a (synthetic) nic, and attach it to the vm + /// + /// + /// + /// + /// + public SyntheticEthernetPortSettingData CreateNICforVm(ComputerSystem vm, string mac) + { + logger.DebugFormat("Creating nic for VM {0} (GUID {1})", vm.ElementName, vm.Name); + + // Obtain controller for Hyper-V networking subsystem + var vmNetMgmtSvc = GetVirtualSwitchManagementService(); + + // Create NIC resource by cloning the default NIC + var synthNICsSettings = SyntheticEthernetPortSettingData.GetInstances(vmNetMgmtSvc.Scope, "InstanceID LIKE \"%Default\""); + + // Assert + if (synthNICsSettings.Count != 1) + { + var errMsg = string.Format("Internal error, coudl not find default SyntheticEthernetPort instance"); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + var defaultSynthNICSettings = synthNICsSettings.OfType().First(); + + var newSynthNICSettings = new SyntheticEthernetPortSettingData((ManagementBaseObject)defaultSynthNICSettings.LateBoundObject.Clone()); + + // Assign configuration to new NIC + string normalisedMAC = string.Join("", (mac.Split(new char[] { ':' }))); + newSynthNICSettings.LateBoundObject["ElementName"] = vm.ElementName; + newSynthNICSettings.LateBoundObject["Address"] = normalisedMAC; + newSynthNICSettings.LateBoundObject["StaticMacAddress"] = "TRUE"; + newSynthNICSettings.LateBoundObject["VirtualSystemIdentifiers"] = new string[] { "{" + Guid.NewGuid().ToString() + "}" }; + newSynthNICSettings.CommitObject(); + + // Insert NIC into vm + string[] newResources = new string[] { newSynthNICSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20)}; + ManagementPath[] newResourcePaths = AddVirtualResource(newResources, vm ); + + // assert + if (newResourcePaths.Length != 1) + { + var errMsg = string.Format( + "Failed to properly insert a single NIC on VM {0} (GUID {1}): number of resource created {2}", + vm.ElementName, + vm.Name, + newResourcePaths.Length); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + return new SyntheticEthernetPortSettingData(newResourcePaths[0]); + } + + public const string IDE_HARDDISK_CONTROLLER = "Microsoft:Hyper-V:Emulated IDE Controller"; + public const string SCSI_CONTROLLER = "Microsoft:Hyper-V:Synthetic SCSI Controller"; + public const string IDE_HARDDISK_DRIVE = "Microsoft:Hyper-V:Synthetic Disk Drive"; + public const string IDE_ISO_DRIVE = "Microsoft:Hyper-V:Synthetic DVD Drive"; + + // TODO: names harvested from Msvm_ResourcePool, not clear how to create new instances + public const string IDE_ISO_DISK = "Microsoft:Hyper-V:Virtual CD/DVD Disk"; // For IDE_ISO_DRIVE + public const string IDE_HARDDISK_DISK = "Microsoft:Hyper-V:Virtual Hard Disk"; // For IDE_HARDDISK_DRIVE + + /// + /// Create new VM. By default we start it. + /// + public ComputerSystem DeployVirtualMachine(dynamic jsonObj, string systemVmIso) + { + var vmInfo = jsonObj.vm; + string vmName = vmInfo.name; + var nicInfo = vmInfo.nics; + int vcpus = vmInfo.cpus; + int memSize = vmInfo.maxRam / 1048576; + string errMsg = vmName; + var diskDrives = vmInfo.disks; + var bootArgs = vmInfo.bootArgs; + + // assert + errMsg = vmName + ": missing disk information, array empty or missing, agent expects *at least* one disk for a VM"; + if (diskDrives == null) + { + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + // assert + errMsg = vmName + ": missing NIC information, array empty or missing, agent expects at least an empty array."; + if (nicInfo == null ) + { + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + + + // For existing VMs, return when we spot one of this name not stopped. In the meantime, remove any existing VMs of same name. + ComputerSystem vmWmiObj = null; + while ((vmWmiObj = GetComputerSystem(vmName)) != null) + { + logger.WarnFormat("Create request for existing vm, name {0}", vmName); + if (vmWmiObj.EnabledState == EnabledState.Disabled) + { + logger.InfoFormat("Deleting existing VM with name {0}, before we go on to create a VM with the same name", vmName); + DestroyVm(vmName); + } + else if (vmWmiObj.EnabledState == EnabledState.Enabled) + { + string infoMsg = string.Format("Create VM discovered there exists a VM with name {0}, state {1}", + vmName, + EnabledState.ToString(vmWmiObj.EnabledState)); + logger.Info(infoMsg); + return vmWmiObj; + } + else + { + errMsg = string.Format("Create VM failing, because there exists a VM with name {0}, state {1}", + vmName, + EnabledState.ToString(vmWmiObj.EnabledState)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + + // Create vm carcase + logger.DebugFormat("Going ahead with create VM {0}, {1} vcpus, {2}MB RAM", vmName, vcpus, memSize); + var newVm = CreateVM(vmName, memSize, vcpus); + + // Add a SCSI controller for attaching/detaching data volumes. + AddScsiControllerToVm(newVm); + + foreach (var diskDrive in diskDrives) + { + string vhdFile = null; + string diskName = null; + VolumeObjectTO volInfo = VolumeObjectTO.ParseJson(diskDrive.data); + if (volInfo != null) + { + // assert + errMsg = vmName + ": volume missing primaryDataStore for disk " + diskDrive.ToString(); + if (volInfo.primaryDataStore == null) + { + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + diskName = volInfo.name; + + // assert + errMsg = vmName + ": can't deal with DataStore type for disk " + diskDrive.ToString(); + if (volInfo.primaryDataStore == null) + { + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + errMsg = vmName + ": Malformed PrimaryDataStore for disk " + diskDrive.ToString(); + 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)) + { + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + + vhdFile = volInfo.FullFileName; + if (!System.IO.File.Exists(vhdFile)) + { + errMsg = vmName + ": non-existent volume, missing " + vhdFile + " for drive " + diskDrive.ToString(); + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + logger.Debug("Going to create " + vmName + " with attached voluem " + diskName + " at " + vhdFile); + } + + string driveType = diskDrive.type; + + string ideCtrllr = "0"; + string driveResourceType = null; + switch (driveType) { + case "ROOT": + ideCtrllr = "0"; + driveResourceType = IDE_HARDDISK_DRIVE; + break; + case "ISO": + ideCtrllr = "1"; + driveResourceType = IDE_ISO_DRIVE; + break; + default: + // TODO: double check exception type + errMsg = string.Format("Unknown disk type {0} for disk {1}, vm named {2}", + string.IsNullOrEmpty(driveType) ? "NULL" : driveType, + string.IsNullOrEmpty(diskName) ? "NULL" : diskName, vmName); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + 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); + } + + String publicIpAddress = ""; + // Add the Nics to the VM in the deviceId order. + for (int i = 0; i <= 2; i++) + { + foreach (var nic in nicInfo) + { + + int nicid = nic.deviceId; + string mac = nic.mac; + string vlan = null; + string isolationUri = nic.isolationUri; + if (isolationUri != null && isolationUri.StartsWith("vlan://") && !isolationUri.Equals("vlan://untagged")) + { + vlan = isolationUri.Substring("vlan://".Length); + int tmp; + if (!int.TryParse(vlan, out tmp)) + { + // TODO: double check exception type + errMsg = string.Format("Invalid VLAN value {0} for on vm {1} for nic uuid {2}", isolationUri, vmName, nic.uuid); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + + if (i == 2) + { + publicIpAddress = nic.ip; + } + + if (nicid == i) + { + // Create network adapter + var newAdapter = CreateNICforVm(newVm, mac); + + // connection to vswitch + var portSettings = AttachNicToPort(newVm, newAdapter); + + // set vlan + if (vlan != null) + { + SetPortVlan(vlan, portSettings); + } + + logger.DebugFormat("Created adapter {0} on port {1}, {2}", + newAdapter.Path, portSettings.Path, (vlan == null ? "No VLAN" : "VLAN " + vlan)); + } + } + } + + // pass the boot args for the VM using KVP component. + // We need to pass the boot args to system vm's to get them configured with cloudstack configuration. + // Add new user data + var vm = GetComputerSystem(vmName); + if (bootArgs != null && !String.IsNullOrEmpty((string)bootArgs)) + { + + String bootargs = bootArgs; + AddUserData(vm, bootargs); + + + // Get existing KVP + //var vmSettings = GetVmSettings(vm); + //var kvpInfo = GetKvpSettings(vmSettings); + //logger.DebugFormat("Boot Args presisted on the VM are ", kvpInfo); + //AddUserData(vm, bootargs); + + // Verify key added to subsystem + //kvpInfo = GetKvpSettings(vmSettings); + + // HostExchangesItems are embedded objects in the sense that the object value is stored and not a reference to the object. + //kvpProps = kvpInfo.HostExchangeItems; + + } + // call patch systemvm iso only for systemvms + if (vmName.StartsWith("r-") || vmName.StartsWith("s-") || vmName.StartsWith("v-")) + { + patchSystemVmIso(vmName, systemVmIso); + } + + logger.DebugFormat("Starting VM {0}", vmName); + SetState(newVm, RequiredState.Enabled); + + // we need to reboot to get the hv kvp daemon get started vr gets configured. + if (vmName.StartsWith("r-") || vmName.StartsWith("s-") || vmName.StartsWith("v-")) + { + System.Threading.Thread.Sleep(90000); + SetState(newVm, RequiredState.Reset); + // wait for the second boot and then return with sucesss + pingResource(publicIpAddress); + } + logger.InfoFormat("Started VM {0}", vmName); + return newVm; + } + + public static Boolean pingResource(String ip) + { + PingOptions pingOptions = null; + PingReply pingReply = null; + IPAddress ipAddress = null; + Ping pingSender = new Ping(); + int numberOfPings = 4; + int pingTimeout = 1000; + int byteSize = 32; + byte[] buffer = new byte[byteSize]; + ipAddress = IPAddress.Parse(ip); + pingOptions = new PingOptions(); + for (int i = 0; i < numberOfPings; i++) + { + pingReply = pingSender.Send(ipAddress, pingTimeout, buffer, pingOptions); + if (pingReply.Status == IPStatus.Success) + { + return true; + } + else + { + // wait for the second boot and then return with suces + System.Threading.Thread.Sleep(30000); + } + } + return false; + } + + private EthernetPortAllocationSettingData AttachNicToPort(ComputerSystem newVm, SyntheticEthernetPortSettingData newAdapter) + { + // Get the virtual switch + VirtualEthernetSwitch vSwitch = GetExternalVirtSwitch(); + + // Create port for adapter + var defaultEthernetPortSettings = EthernetPortAllocationSettingData.GetInstances(vSwitch.Scope, "InstanceID LIKE \"%Default\""); + + // assert + if (defaultEthernetPortSettings.Count != 1) + { + var errMsg = string.Format("Internal error, coudl not find default EthernetPortAllocationSettingData instance"); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + var defaultEthernetPortSettingsObj = defaultEthernetPortSettings.OfType().First(); + var newEthernetPortSettings = new EthernetPortAllocationSettingData((ManagementBaseObject)defaultEthernetPortSettingsObj.LateBoundObject.Clone()); + newEthernetPortSettings.LateBoundObject["Parent"] = newAdapter.Path.Path; + newEthernetPortSettings.LateBoundObject["HostResource"] = new string[] { vSwitch.Path.Path }; + + // Insert NIC into vm + string[] newResources = new string[] { newEthernetPortSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; + ManagementPath[] newResourcePaths = AddVirtualResource(newResources, newVm); + + // assert + if (newResourcePaths.Length != 1) + { + var errMsg = string.Format( + "Failed to properly insert a single NIC on VM {0} (GUID {1}): number of resource created {2}", + newVm.ElementName, + newVm.Name, + newResourcePaths.Length); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + return new EthernetPortAllocationSettingData(newResourcePaths[0]); + } + + /// this method is to add a dvd drive and attach the systemvm iso. + /// + public void patchSystemVmIso(String vmName, String systemVmIso) + { + ComputerSystem vmObject = GetComputerSystem(vmName); + AddDiskDriveToVm(vmObject, "", "1", IDE_ISO_DRIVE); + AttachIso(vmName, systemVmIso); + } + + + /// + /// + /// + /// IDE_HARDDISK_DRIVE or IDE_ISO_DRIVE + public ManagementPath AddDiskDriveToVm(ComputerSystem vm, string vhdfile, string cntrllerAddr, string driveResourceType) + { + logger.DebugFormat("Creating DISK for VM {0} (GUID {1}) by attaching {2}", + vm.ElementName, + vm.Name, + vhdfile); + + // Determine disk type for drive and assert drive type valid + string diskResourceSubType = null; + switch(driveResourceType) { + case IDE_HARDDISK_DRIVE: + diskResourceSubType = IDE_HARDDISK_DISK; + break; + case IDE_ISO_DRIVE: + diskResourceSubType = IDE_ISO_DISK; + break; + default: + var errMsg = string.Format( + "Unrecognised disk drive type {0} for VM {1} (GUID {2})", + string.IsNullOrEmpty(driveResourceType) ? "NULL": driveResourceType, + vm.ElementName, + vm.Name); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + ManagementPath newDrivePath = AttachNewDriveToVm(vm, cntrllerAddr, driveResourceType); + + // If there's not disk to insert, we are done. + if (String.IsNullOrEmpty(vhdfile)) + { + logger.DebugFormat("No disk to be added to drive, disk drive {0} is complete", newDrivePath.Path); + } + else + { + InsertDiskImage(vm, vhdfile, diskResourceSubType, newDrivePath); + } + return newDrivePath; + } + + + public void DetachDisk(string displayName, string diskFileName) + { + logger.DebugFormat("Got request to detach virtual disk {0} from vm {1}", diskFileName, displayName); + + ComputerSystem vm = GetComputerSystem(displayName); + if (vm == null) + { + logger.DebugFormat("VM {0} not found", displayName); + return; + } + else + { + RemoveStorageImageFromVm(vm, diskFileName); + } + } + + /// + /// Removes a disk image from a drive, but does not remove the drive itself. + /// + /// + /// + private void RemoveStorageImageFromVm(ComputerSystem vm, string diskFileName) + { + // Obtain StorageAllocationSettingData for disk + StorageAllocationSettingData.StorageAllocationSettingDataCollection storageSettingsObjs = StorageAllocationSettingData.GetInstances(); + + StorageAllocationSettingData imageToRemove = null; + foreach (StorageAllocationSettingData item in storageSettingsObjs) + { + if (item.HostResource == null || item.HostResource.Length != 1) + { + continue; + } + + string hostResource = item.HostResource[0]; + if (!hostResource.Equals(diskFileName)) + { + continue; + } + imageToRemove = item; + } + + // assert + if (imageToRemove == null) + { + var errMsg = string.Format( + "Failed to remove disk image {0} from VM {1} (GUID {2}): the disk image is not attached.", + diskFileName, + vm.ElementName, + vm.Name); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + RemoveStorageResource(imageToRemove.Path, vm); + + logger.InfoFormat("REmoved disk image {0} from VM {1} (GUID {2}): the disk image is not attached.", + diskFileName, + vm.ElementName, + vm.Name); + } + + private ManagementPath AttachNewDriveToVm(ComputerSystem vm, string cntrllerAddr, string driveType) + { + // Disk drives are attached to a 'Parent' IDE controller. We IDE Controller's settings for the 'Path', which our new Disk drive will use to reference it. + VirtualSystemSettingData vmSettings = GetVmSettings(vm); + var ctrller = GetIDEControllerSettings(vmSettings, cntrllerAddr); + + // A description of the drive is created by modifying a clone of the default ResourceAllocationSettingData for that drive type + string defaultDriveQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", driveType); + var newDiskDriveSettings = CloneResourceAllocationSetting(defaultDriveQuery); + + // Set IDE controller and address on the controller for the new drive + newDiskDriveSettings.LateBoundObject["Parent"] = ctrller.Path.ToString(); + newDiskDriveSettings.LateBoundObject["AddressOnParent"] = "0"; + newDiskDriveSettings.CommitObject(); + + // Add this new disk drive to the VM + logger.DebugFormat("Creating disk drive type {0}, parent IDE controller is {1} and address on controller is {2}", + newDiskDriveSettings.ResourceSubType, + newDiskDriveSettings.Parent, + newDiskDriveSettings.AddressOnParent); + string[] newDriveResource = new string[] { newDiskDriveSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; + ManagementPath[] newDrivePaths = AddVirtualResource(newDriveResource, vm); + + // assert + if (newDrivePaths.Length != 1) + { + var errMsg = string.Format( + "Failed to add disk drive type {3} to VM {0} (GUID {1}): number of resource created {2}", + vm.ElementName, + vm.Name, + newDrivePaths.Length, + driveType); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + logger.DebugFormat("New disk drive type {0} WMI path is {1}s", + newDiskDriveSettings.ResourceSubType, + newDrivePaths[0].Path); + return newDrivePaths[0]; + } + + private ManagementPath AddScsiControllerToVm(ComputerSystem vm) + { + // A description of the controller is created by modifying a clone of the default ResourceAllocationSettingData for scsi controller + string scsiQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", SCSI_CONTROLLER); + var scsiSettings = CloneResourceAllocationSetting(scsiQuery); + + scsiSettings.LateBoundObject["ElementName"] = "SCSI Controller"; + scsiSettings.CommitObject(); + + // Insert SCSI controller into vm + string[] newResources = new string[] { scsiSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; + ManagementPath[] newResourcePaths = AddVirtualResource(newResources, vm); + + // assert + if (newResourcePaths.Length != 1) + { + var errMsg = string.Format( + "Failed to add scsi controller to VM {0} (GUID {1}): number of resource created {2}", + vm.ElementName, + vm.Name, + newResourcePaths.Length); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + logger.DebugFormat("New controller type {0} WMI path is {1}s", + scsiSettings.ResourceSubType, + newResourcePaths[0].Path); + return newResourcePaths[0]; + } + + + private void InsertDiskImage(ComputerSystem vm, string diskImagePath, string diskResourceSubType, ManagementPath drivePath) + { + // A description of the disk is created by modifying a clone of the default ResourceAllocationSettingData for that disk type + string defaultDiskQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", diskResourceSubType); + var newDiskSettings = CloneStorageAllocationSetting(defaultDiskQuery); + + // Set file containing the disk image + newDiskSettings.LateBoundObject["Parent"] = drivePath.Path; + + // V2 API uses HostResource to specify image, see http://msdn.microsoft.com/en-us/library/hh859775(v=vs.85).aspx + newDiskSettings.LateBoundObject["HostResource"] = new string[] { diskImagePath }; + newDiskSettings.CommitObject(); + + // Add the new Msvm_StorageAllocationSettingData object as a virtual hard disk to the vm. + string[] newDiskResource = new string[] { newDiskSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; + ManagementPath[] newDiskPaths = AddStorageResource(newDiskResource, vm); + // assert + if (newDiskPaths.Length != 1) + { + var errMsg = string.Format( + "Failed to add disk image type {3} to VM {0} (GUID {1}): number of resource created {2}", + vm.ElementName, + vm.Name, + newDiskPaths.Length, + diskResourceSubType); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + logger.InfoFormat("Created disk {2} for VM {0} (GUID {1}), image {3} ", + vm.ElementName, + vm.Name, + newDiskPaths[0].Path, + diskImagePath); + } + + /// + /// Create Msvm_StorageAllocationSettingData corresponding to the ISO image, and + /// associate this with the VM's DVD drive. + /// + private void AttachIsoToVm(ComputerSystem vm, string isoPath) + { + // Disk drives are attached to a 'Parent' IDE controller. We IDE Controller's settings for the 'Path', which our new Disk drive will use to reference it. + VirtualSystemSettingData vmSettings = GetVmSettings(vm); + var driveWmiObj = GetDvdDriveSettings(vmSettings); + + InsertDiskImage(vm, isoPath, IDE_ISO_DISK, driveWmiObj.Path); + } + + + + private static ResourceAllocationSettingData CloneResourceAllocationSetting(string wmiQuery) + { + var defaultDiskDriveSettingsObjs = ResourceAllocationSettingData.GetInstances(wmiQuery); + + // assert + if (defaultDiskDriveSettingsObjs.Count != 1) + { + var errMsg = string.Format("Failed to find Msvm_ResourceAllocationSettingData for the query {0}", wmiQuery); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + ResourceAllocationSettingData defaultDiskDriveSettings = defaultDiskDriveSettingsObjs.OfType().First(); + return new ResourceAllocationSettingData((ManagementBaseObject)defaultDiskDriveSettings.LateBoundObject.Clone()); + } + + public void AttachIso(string displayName, string iso) + { + logger.DebugFormat("Got request to attach iso {0} to vm {1}", iso, displayName); + + ComputerSystem vm = GetComputerSystem(displayName); + if (vm == null) + { + logger.DebugFormat("VM {0} not found", displayName); + return; + } + else + { + AttachIsoToVm(vm, iso); + } + } + + public void DestroyVm(dynamic jsonObj) + { + string vmToDestroy = jsonObj.vmName; + DestroyVm(vmToDestroy); + } + + /// + /// Remove all VMs and all SwitchPorts with the displayName. VHD gets deleted elsewhere. + /// + /// + public void DestroyVm(string displayName) + { + logger.DebugFormat("Got request to destroy vm {0}", displayName); + + var vm = GetComputerSystem(displayName); + if ( vm == null ) + { + logger.DebugFormat("VM {0} already destroyed (or never existed)", displayName); + return; + } + + // Stop VM + logger.DebugFormat("Stop VM {0} (GUID {1})", vm.ElementName, vm.Name); + SetState(vm, RequiredState.Disabled); + + // Delete SwitchPort + logger.DebugFormat("Remove associated switch ports for VM {0} (GUID {1})", vm.ElementName, vm.Name); + DeleteSwitchPort(vm.ElementName); + + // Delete VM + var virtSysMgmtSvc = GetVirtualisationSystemManagementService(); + ManagementPath jobPath; + + do + { + logger.DebugFormat("Delete VM {0} (GUID {1})", vm.ElementName, vm.Name); + var ret_val = virtSysMgmtSvc.DestroySystem(vm.Path, out jobPath); + + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed Delete 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; + } + vm = GetComputerSystem(displayName); + } + while (vm != null); + } + + /// + /// 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 + /// + /// + /// + private static StorageAllocationSettingData CloneStorageAllocationSetting(string wmiQuery) + { + var defaultDiskImageSettingsObjs = StorageAllocationSettingData.GetInstances(wmiQuery); + + // assert + if (defaultDiskImageSettingsObjs.Count != 1) + { + var errMsg = string.Format("Failed to find Msvm_StorageAllocationSettingData for the query {0}", wmiQuery); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + StorageAllocationSettingData defaultDiskDriveSettings = defaultDiskImageSettingsObjs.OfType().First(); + return new StorageAllocationSettingData((ManagementBaseObject)defaultDiskDriveSettings.LateBoundObject.Clone()); + } + + /// < summary> + /// Removes a storage resource from a computer system. + /// + /// Path that uniquely identifies the resource. + /// VM to which the disk image will be attached. + // Add new + private void RemoveNetworkResource(ManagementPath resourcePath) + { + var virtSwitchMgmtSvc = GetVirtualSwitchManagementService(); + ManagementPath jobPath; + var ret_val = virtSwitchMgmtSvc.RemoveResourceSettings( + new ManagementPath[] { resourcePath }, + out jobPath); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to remove network resources {0} from switch due to {1}", + resourcePath.Path, + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + + /// < summary> + /// Removes a storage resource from a computer system. + /// + /// Path that uniquely identifies the resource. + /// VM to which the disk image will be attached. + private void RemoveStorageResource(ManagementPath resourcePath, ComputerSystem vm) + { + var virtSysMgmtSvc = GetVirtualisationSystemManagementService(); + + ManagementPath jobPath; + var ret_val = virtSysMgmtSvc.RemoveResourceSettings( + new ManagementPath[] { resourcePath }, + out jobPath); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to remove resource {0} from VM {1} (GUID {2}) due to {3}", + resourcePath.Path, + vm.ElementName, + vm.Name, + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + + public void SetState(ComputerSystem vm, ushort requiredState) + { + logger.InfoFormat( + "Changing state of {0} (GUID {1}) to {2}", + vm.ElementName, + vm.Name, + RequiredState.ToString(requiredState)); + + ManagementPath jobPath; + // DateTime is unused + var ret_val = vm.RequestStateChange(requiredState, new DateTime(), out jobPath); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val == 32775) + { // TODO: check + logger.InfoFormat("RequestStateChange returned 32775, which means vm in wrong state for requested state change. Treating as if requested state was reached"); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to change state of VM {0} (GUID {1}) to {2} due to {3}", + vm.ElementName, + vm.Name, + RequiredState.ToString(requiredState), + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + logger.InfoFormat( + "Successfully changed vm state of {0} (GUID {1} to requested state {2}", + vm.ElementName, + vm.Name, + requiredState); + } + + + //TODO: Write method to delete SwitchPort based on Name + /// + /// Delete switch port by removing settings from the switch + /// + /// + /// + public void DeleteSwitchPort(string elementName) + { + // Get NIC path + var condition = string.Format("ElementName=\"{0}\"", elementName); + var virtSwitchMgmtSvc = GetVirtualSwitchManagementService(); + + var switchPortCollection = EthernetSwitchPort.GetInstances(virtSwitchMgmtSvc.Scope, condition); + if (switchPortCollection.Count == 0) + { + return; + } + + foreach (EthernetSwitchPort port in switchPortCollection) + { + var settings = GetSyntheticEthernetPortSettings(port); + RemoveNetworkResource(settings.Path); + } + } + + public SyntheticEthernetPortSettingData GetSyntheticEthernetPortSettings(EthernetSwitchPort port) + { + // An ASSOCIATOR object provides the cross reference from the EthernetSwitchPort and the + // SyntheticEthernetPortSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. + // Instead, we use the System.Management to code the equivalant of + // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vm.path, resultclassName); + // + var wmiObjQuery = new RelatedObjectQuery(port.Path.Path, SyntheticEthernetPortSettingData.CreatedClassName); + + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var wmiObjectSearch = new ManagementObjectSearcher(port.Scope, wmiObjQuery); + var wmiObjCollection = new SyntheticEthernetPortSettingData.SyntheticEthernetPortSettingDataCollection(wmiObjectSearch.Get()); + + // When snapshots are taken into account, there can be multiple settings objects + // take the first one that isn't a snapshot + foreach (SyntheticEthernetPortSettingData wmiObj in wmiObjCollection) + { + return wmiObj; + } + + var errMsg = string.Format("No SyntheticEthernetPortSettingData for port {0}, path {1}", port.ElementName, port.Path.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + /// + /// Adds storage images to coputer system (disk image, iso image). + /// + /// Msvm_StorageAllocationSettings with HostResource configured with image + /// file and Parent set to a controller associated with the ComputerSystem + /// VM to which the disk image will be attached. + // Add new + private ManagementPath[] AddStorageResource(string[] storageSettings, ComputerSystem vm) + { + return AddVirtualResource(storageSettings, vm); + } + + private ManagementPath[] AddVirtualResource(string[] resourceSettings, ComputerSystem vm ) + { + var virtSysMgmtSvc = GetVirtualisationSystemManagementService(); + + ManagementPath jobPath; + ManagementPath[] resourcePaths; + var ret_val = virtSysMgmtSvc.AddResourceSettings( + vm.Path, + resourceSettings, + out jobPath, + out resourcePaths); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to add resources to 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; + } + + return resourcePaths; + } + + private ManagementPath[] AddFeatureSettings(string[] featureSettings, ManagementPath affectedConfiguration) + { + var virtSysMgmtSvc = GetVirtualisationSystemManagementService(); + + ManagementPath jobPath; + ManagementPath[] resultSettings; + var ret_val = virtSysMgmtSvc.AddFeatureSettings( + affectedConfiguration, + featureSettings, + out jobPath, + out resultSettings); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to add features settings {0} to resource {1} due to {2}", + featureSettings, + affectedConfiguration, + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + return resultSettings; + } + + private ManagementPath SetPortVlan(string vlan, EthernetPortAllocationSettingData portPath) + { + logger.DebugFormat("Setting VLAN to {0}", vlan); + + var vmVirtMgmtSvc = GetVirtualisationSystemManagementService(); + EthernetSwitchPortVlanSettingData.GetInstances(); + + // Create NIC resource by cloning the default NIC + var vlanSettings = EthernetSwitchPortVlanSettingData.GetInstances(vmVirtMgmtSvc.Scope, "InstanceID LIKE \"%Default\""); + + // Assert + if (vlanSettings.Count != 1) + { + var errMsg = string.Format("Internal error, could not find default EthernetSwitchPortVlanSettingData instance"); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + var defaultVlanSettings = vlanSettings.OfType().First(); + + var newVlanSettings = new EthernetSwitchPortVlanSettingData((ManagementBaseObject)defaultVlanSettings.LateBoundObject.Clone()); + + // Assign configuration to new NIC + newVlanSettings.LateBoundObject["AccessVlanId"] = vlan; + newVlanSettings.LateBoundObject["OperationMode"] = 1; // Access=1, trunk=2, private=3 ; + newVlanSettings.CommitObject(); + + // Insert NIC into vm + string[] newResources = new string[] { newVlanSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; + ManagementPath[] newResourcePaths = AddFeatureSettings(newResources, portPath.Path); + + // assert + if (newResourcePaths.Length != 1) + { + var errMsg = string.Format( + "Failed to properly set VLAN to {0} for NIC on port {1}", + vlan, + portPath.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + return newResourcePaths[0]; + } + + + /// + /// External VSwitch has an external NIC, and we assume there is only one external NIC and one external vswitch. + /// + /// + /// + /// Throws if there is no vswitch + /// + /// With V1 API, external ethernet port was attached to the land endpoint, which was attached to the switch. + /// e.g. Msvm_ExternalEthernetPort -> SwitchLANEndpoint -> SwitchPort -> VirtualSwitch + /// + /// With V2 API, there are two kinds of lan endpoint: one on the computer system and one on the switch + /// e.g. Msvm_ExternalEthernetPort -> LANEndpoint -> LANEdnpoint -> EthernetSwitchPort -> VirtualEthernetSwitch + /// + public static VirtualEthernetSwitch GetExternalVirtSwitch() + { + // Work back from the first *bound* external NIC we find. + var externNICs = ExternalEthernetPort.GetInstances("IsBound = TRUE"); + + // Assert + if (externNICs.Count == 0 ) + { + var errMsg = "No ExternalEthernetPort available to Hyper-V"; + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + ExternalEthernetPort externNIC = externNICs.OfType().First(); + // A sequence of ASSOCIATOR objects need to be traversed to get from external NIC the vswitch. + // We use ManagementObjectSearcher objects to execute this sequence of questions + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var endpointQuery = new RelatedObjectQuery(externNIC.Path.Path, LANEndpoint.CreatedClassName); + var endpointSearch = new ManagementObjectSearcher(externNIC.Scope, endpointQuery); + var endpointCollection = new LANEndpoint.LANEndpointCollection(endpointSearch.Get()); + + // assert + if (endpointCollection.Count < 1 ) + { + var errMsg = string.Format("No adapter-based LANEndpoint for external NIC {0} on Hyper-V server", externNIC.Name); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + LANEndpoint adapterEndPoint = endpointCollection.OfType().First(); + var switchEndpointQuery = new RelatedObjectQuery(adapterEndPoint.Path.Path, LANEndpoint.CreatedClassName); + var switchEndpointSearch = new ManagementObjectSearcher(externNIC.Scope, switchEndpointQuery); + var switchEndpointCollection = new LANEndpoint.LANEndpointCollection(switchEndpointSearch.Get()); + + // assert + if (endpointCollection.Count < 1) + { + var errMsg = string.Format("No Switch-based LANEndpoint for external NIC {0} on Hyper-V server", externNIC.Name); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + LANEndpoint switchEndPoint = switchEndpointCollection.OfType().First(); + var switchPortQuery = new RelatedObjectQuery(switchEndPoint.Path.Path, EthernetSwitchPort.CreatedClassName); + var switchPortSearch = new ManagementObjectSearcher(switchEndPoint.Scope, switchPortQuery); + var switchPortCollection = new EthernetSwitchPort.EthernetSwitchPortCollection(switchPortSearch.Get()); + + // assert + if (switchPortCollection.Count < 1 ) + { + var errMsg = string.Format("No SwitchPort for external NIC {0} on Hyper-V server", externNIC.Name); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + EthernetSwitchPort switchPort = switchPortCollection.OfType().First(); + var vSwitchQuery = new RelatedObjectQuery(switchPort.Path.Path, VirtualEthernetSwitch.CreatedClassName); + var vSwitchSearch = new ManagementObjectSearcher(externNIC.Scope, vSwitchQuery); + var vSwitchCollection = new VirtualEthernetSwitch.VirtualEthernetSwitchCollection(vSwitchSearch.Get()); + + // assert + if (vSwitchCollection.Count < 1) + { + var errMsg = string.Format("No virtual switch for external NIC {0} on Hyper-V server", externNIC.Name); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + VirtualEthernetSwitch vSwitch = vSwitchCollection.OfType().First(); + return vSwitch; + } + + private static void ModifyVmResources(VirtualSystemManagementService vmMgmtSvc, ComputerSystem vm, string[] resourceSettings) + { + // Resource settings are changed through the management service + System.Management.ManagementPath jobPath; + System.Management.ManagementPath[] results; + + var ret_val = vmMgmtSvc.ModifyResourceSettings( + resourceSettings, + out jobPath, + out results); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to update VM {0} (GUID {1}) due to {2} (ModifyVirtualSystem call), existing VM not deleted", + vm.ElementName, + vm.Name, + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + + public void DeleteHostKvpItem(ComputerSystem vm, string key) + { + // Obtain controller for Hyper-V virtualisation subsystem + VirtualSystemManagementService vmMgmtSvc = GetVirtualisationSystemManagementService(); + + // Create object to hold the data. + KvpExchangeDataItem kvpItem = KvpExchangeDataItem.CreateInstance(); + kvpItem.LateBoundObject["Name"] = WmiCallsV2.CloudStackUserDataKey; + kvpItem.LateBoundObject["Data"] = "dummy"; + kvpItem.LateBoundObject["Source"] = 0; + logger.Debug("VM " + vm.Name + " will have KVP key " + key + " removed."); + + String kvpStr = kvpItem.LateBoundObject.GetText(TextFormat.CimDtd20); + + // Update the resource settings for the VM. + ManagementPath jobPath; + + uint ret_val = vmMgmtSvc.RemoveKvpItems(new String[] { kvpStr }, vm.Path, out jobPath); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to update VM {0} (GUID {1}) due to {2} (ModifyVirtualSystem call), existing VM not deleted", + vm.ElementName, + vm.Name, + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + + private static ComputerSystem CreateDefaultVm(VirtualSystemManagementService vmMgmtSvc, string name) + { + // Tweak default settings by basing new VM on default global setting object + // with designed display name. + + VirtualSystemSettingData vs_gs_data = VirtualSystemSettingData.CreateInstance(); + vs_gs_data.LateBoundObject["ElementName"] = name; + + System.Management.ManagementPath jobPath; + System.Management.ManagementPath defined_sys; + var ret_val = vmMgmtSvc.DefineSystem( + null, + new string[0], + vs_gs_data.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20), + out jobPath, + out defined_sys); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to create VM {0} due to {1} (DefineVirtualSystem call)", + name, ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + logger.DebugFormat(CultureInfo.InvariantCulture, "Created VM {0}", name); + + // Is the defined_system real? + var vm = new ComputerSystem(defined_sys); + + // Assertion + if (vm.ElementName.CompareTo(name) != 0) + { + var errMsg = string.Format( + "New VM created with wrong name (is {0}, should be {1}, GUID {2})", + vm.ElementName, + name, + vm.Name); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + return vm; + } + + public VirtualEthernetSwitchManagementService GetVirtualSwitchManagementService() + { + // VirtualSwitchManagementService is a singleton, most anonymous way of lookup is by asking for the set + // of local instances, which should be size 1. + var virtSwtichSvcCollection = VirtualEthernetSwitchManagementService.GetInstances(); + foreach (VirtualEthernetSwitchManagementService item in virtSwtichSvcCollection) + { + return item; + } + + var errMsg = string.Format("No Hyper-V subsystem on server"); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + /// + /// Always produces a VHDX. + /// + /// + /// + public void CreateDynamicVirtualHardDisk(ulong MaxInternalSize, string Path) + { + // Produce description of the virtual disk in the format of a Msvm_VirtualHardDiskSettings object + + // Example at http://www.getcodesamples.com/src/FC025DDC/76689747, but + // Is there a template we can use to fill in the settings? + var newVirtHDSettings = VirtualHardDiskSettingData.CreateInstance(); + newVirtHDSettings.LateBoundObject["Type"] = 3; // Dynamic + newVirtHDSettings.LateBoundObject["Format"] = 3; // VHDX + newVirtHDSettings.LateBoundObject["Path"] = Path; + newVirtHDSettings.LateBoundObject["MaxInternalSize"] = MaxInternalSize; + newVirtHDSettings.LateBoundObject["BlockSize"] = 0; // Use defaults + newVirtHDSettings.LateBoundObject["LogicalSectorSize"] = 0; // Use defaults + newVirtHDSettings.LateBoundObject["PhysicalSectorSize"] = 0; // Use defaults + + // Optional: newVirtHDSettings.CommitObject(); + + // Add the new vhd object as a virtual hard disk to the vm. + string newVirtHDSettingsString = newVirtHDSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20); + + // Resource settings are changed through the management service + System.Management.ManagementPath jobPath; + var imgMgr = GetImageManagementService(); + var ret_val = imgMgr.CreateVirtualHardDisk(newVirtHDSettingsString, out jobPath); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to CreateVirtualHardDisk size {0}, path {1} due to {2}", + MaxInternalSize, + Path, + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + + public ImageManagementService GetImageManagementService() + { + // VirtualSystemManagementService is a singleton, most anonymous way of lookup is by asking for the set + // of local instances, which should be size 1. + + var coll = ImageManagementService.GetInstances(); + foreach (ImageManagementService item in coll) + { + return item; + } + + var errMsg = string.Format("No Hyper-V subsystem on server"); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + + public VirtualSystemManagementService GetVirtualisationSystemManagementService() + { + // VirtualSystemManagementService is a singleton, most anonymous way of lookup is by asking for the set + // of local instances, which should be size 1. + + var virtSysMgmtSvcCollection = VirtualSystemManagementService.GetInstances(); + foreach (VirtualSystemManagementService item in virtSysMgmtSvcCollection) + { + return item; + } + + var errMsg = string.Format("No Hyper-V 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 + /// + /// + /// + private static void JobCompleted(ManagementPath jobPath) + { + ConcreteJob jobObj = null; + for(;;) + { + jobObj = new ConcreteJob(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; + } + + logger.DebugFormat("WMI job succeeded: {0}, Elapsed={1}", jobObj.Description, jobObj.ElapsedTime); + } + + public void GetProcessorResources(out uint cores, out uint mhz) + { + // Processor processors + cores = 0; + mhz = 0; + Processor.ProcessorCollection procCol = Processor.GetInstances(); + foreach (Processor procInfo in procCol) + { + cores += procInfo.NumberOfCores; + mhz = procInfo.MaxClockSpeed; + } + } + + public void GetProcessorUsageInfo(out double cpuUtilization) + { + PerfFormattedData_Counters_ProcessorInformation.PerfFormattedData_Counters_ProcessorInformationCollection coll = + PerfFormattedData_Counters_ProcessorInformation.GetInstances("Name=\"_Total\""); + cpuUtilization = 100; + // Use the first one + foreach (PerfFormattedData_Counters_ProcessorInformation procInfo in coll) + { + // Idle during a given internal + // See http://library.wmifun.net/cimv2/win32_perfformatteddata_counters_processorinformation.html + cpuUtilization = 100.0 - (double)procInfo.PercentIdleTime; + } + } + + + public void GetMemoryResources(out ulong physicalRamKBs, out ulong freeMemoryKBs) + { + OperatingSystem0 os = new OperatingSystem0(); + physicalRamKBs = os.TotalVisibleMemorySize; + freeMemoryKBs = os.FreePhysicalMemory; + } + + public string GetDefaultVirtualDiskFolder() + { + VirtualSystemManagementServiceSettingData.VirtualSystemManagementServiceSettingDataCollection coll = VirtualSystemManagementServiceSettingData.GetInstances(); + string defaultVirtualHardDiskPath = null; + foreach (VirtualSystemManagementServiceSettingData settings in coll) + { + defaultVirtualHardDiskPath = settings.DefaultVirtualHardDiskPath; + } + + // assert + if (!System.IO.Directory.Exists(defaultVirtualHardDiskPath) ){ + var errMsg = string.Format( + "Hyper-V DefaultVirtualHardDiskPath is invalid!"); + logger.Error(errMsg); + return null; + } + + return defaultVirtualHardDiskPath; + } + + public ComputerSystem GetComputerSystem(string displayName) + { + var wmiQuery = String.Format("ElementName=\"{0}\"", displayName); + ComputerSystem.ComputerSystemCollection vmCollection = ComputerSystem.GetInstances(wmiQuery); + + // Return the first one + foreach (ComputerSystem vm in vmCollection) + { + return vm; + } + return null; + } + + public List GetVmElementNames() + { + List result = new List(); + ComputerSystem.ComputerSystemCollection vmCollection = ComputerSystem.GetInstances(); + + // Return the first one + foreach (ComputerSystem vm in vmCollection) + { + if (vm.Caption.StartsWith("Hosting Computer System") ) + { + continue; + } + result.Add(vm.ElementName); + } + return result; + } + + public ProcessorSettingData GetProcSettings(VirtualSystemSettingData vmSettings) + { + // An ASSOCIATOR object provides the cross reference from the VirtualSystemSettingData and the + // ProcessorSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. + // Instead, we use the System.Management to code the equivalant of + // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vmSettings.path, resultclassName); + // + var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, ProcessorSettingData.CreatedClassName); + + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var wmiObjectSearch = new ManagementObjectSearcher(vmSettings.Scope, wmiObjQuery); + var wmiObjCollection = new ProcessorSettingData.ProcessorSettingDataCollection(wmiObjectSearch.Get()); + + foreach (ProcessorSettingData wmiObj in wmiObjCollection) + { + return wmiObj; + } + + var errMsg = string.Format("No ProcessorSettingData in VirtualSystemSettingData {0}", vmSettings.Path.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + public MemorySettingData GetMemSettings(VirtualSystemSettingData vmSettings) + { + // An ASSOCIATOR object provides the cross reference from the VirtualSystemSettingData and the + // MemorySettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. + // Instead, we use the System.Management to code the equivalant of + // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vmSettings.path, resultclassName); + // + var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, MemorySettingData.CreatedClassName); + + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var wmiObjectSearch = new ManagementObjectSearcher(vmSettings.Scope, wmiObjQuery); + var wmiObjCollection = new MemorySettingData.MemorySettingDataCollection(wmiObjectSearch.Get()); + + foreach (MemorySettingData wmiObj in wmiObjCollection) + { + return wmiObj; + } + + var errMsg = string.Format("No MemorySettingData in VirtualSystemSettingData {0}", vmSettings.Path.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + + public ResourceAllocationSettingData GetDvdDriveSettings(VirtualSystemSettingData vmSettings) + { + var wmiObjCollection = GetResourceAllocationSettings(vmSettings); + + foreach (ResourceAllocationSettingData wmiObj in wmiObjCollection) + { + // DVD drive is '16', see http://msdn.microsoft.com/en-us/library/hh850200(v=vs.85).aspx + if (wmiObj.ResourceType == 16) + { + return wmiObj; + } + } + + var errMsg = string.Format( + "Cannot find the Dvd drive in VirtualSystemSettingData {0}", + vmSettings.Path.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + public ResourceAllocationSettingData GetIDEControllerSettings(VirtualSystemSettingData vmSettings, string cntrllerAddr) + { + var wmiObjCollection = GetResourceAllocationSettings(vmSettings); + + foreach (ResourceAllocationSettingData wmiObj in wmiObjCollection) + { + if (wmiObj.ResourceSubType == IDE_HARDDISK_CONTROLLER && wmiObj.Address == cntrllerAddr) + { + return wmiObj; + } + } + + var errMsg = string.Format( + "Cannot find the Microsoft Emulated IDE Controlle at address {0} in VirtualSystemSettingData {1}", + cntrllerAddr, + vmSettings.Path.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + /// + /// VM resources, typically hardware a described by a generic MSVM_ResourceAllocationSettingData object. The hardware type being + /// described is identified in two ways: in general terms using an enum in the ResourceType field, and in terms of the implementation + /// using text in the ResourceSubType field. + /// See http://msdn.microsoft.com/en-us/library/cc136877%28v=vs.85%29.aspx + /// + /// + /// + public ResourceAllocationSettingData.ResourceAllocationSettingDataCollection GetResourceAllocationSettings(VirtualSystemSettingData vmSettings) + { + // An ASSOCIATOR object provides the cross reference from the VirtualSystemSettingData and the + // ResourceAllocationSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. + // Instead, we use the System.Management to code the equivalant of + // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vmSettings.path, resultclassName); + // + var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, ResourceAllocationSettingData.CreatedClassName); + + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var wmiObjectSearch = new ManagementObjectSearcher(vmSettings.Scope, wmiObjQuery); + var wmiObjCollection = new ResourceAllocationSettingData.ResourceAllocationSettingDataCollection(wmiObjectSearch.Get()); + + if (wmiObjCollection != null) + { + return wmiObjCollection; + } + + var errMsg = string.Format("No ResourceAllocationSettingData in VirtualSystemSettingData {0}", vmSettings.Path.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + public EthernetPortAllocationSettingData[] GetEthernetConnections(ComputerSystem vm) + { + // ComputerSystem -> VirtualSystemSettingData -> EthernetPortAllocationSettingData + VirtualSystemSettingData vmSettings = GetVmSettings(vm); + + // An ASSOCIATOR object provides the cross reference from the VirtualSystemSettingData and the + // EthernetPortAllocationSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. + // Instead, we use the System.Management to code the equivalant of + // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vmSettings.path, resultclassName); + // + var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, EthernetPortAllocationSettingData.CreatedClassName); + + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var wmiObjectSearch = new ManagementObjectSearcher(vmSettings.Scope, wmiObjQuery); + var wmiObjCollection = new EthernetPortAllocationSettingData.EthernetPortAllocationSettingDataCollection(wmiObjectSearch.Get()); + + var result = new List(wmiObjCollection.Count); + foreach (EthernetPortAllocationSettingData item in wmiObjCollection) + { + result.Add(item); + } + return result.ToArray(); + } + + + public EthernetSwitchPortVlanSettingData GetVlanSettings(EthernetPortAllocationSettingData ethernetConnection) + { + // An ASSOCIATOR object provides the cross reference from the VirtualSystemSettingData and the + // EthernetPortAllocationSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. + // Instead, we use the System.Management to code the equivalant of + // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vmSettings.path, resultclassName); + // + var wmiObjQuery = new RelatedObjectQuery(ethernetConnection.Path.Path, EthernetSwitchPortVlanSettingData.CreatedClassName); + + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var wmiObjectSearch = new ManagementObjectSearcher(ethernetConnection.Scope, wmiObjQuery); + var wmiObjCollection = new EthernetSwitchPortVlanSettingData.EthernetSwitchPortVlanSettingDataCollection(wmiObjectSearch.Get()); + + if (wmiObjCollection.Count == 0) + { + return null; + } + + // Assert + if (wmiObjCollection.Count > 1) + { + var errMsg = string.Format("Internal error, morn one VLAN settings for a single ethernetConnection"); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + return wmiObjCollection.OfType().First(); + } + + + public SyntheticEthernetPortSettingData[] GetEthernetPortSettings(ComputerSystem vm) + { + // An ASSOCIATOR object provides the cross reference from the ComputerSettings and the + // SyntheticEthernetPortSettingData, via the VirtualSystemSettingData. + // However, generated wrappers do not expose a ASSOCIATOR OF query as a method. + // Instead, we use the System.Management to code the equivalant of + // + // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vm.path, resultclassName); + // + VirtualSystemSettingData vmSettings = GetVmSettings(vm); + + var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, SyntheticEthernetPortSettingData.CreatedClassName); + + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var wmiObjectSearch = new ManagementObjectSearcher(vm.Scope, wmiObjQuery); + var wmiObjCollection = new SyntheticEthernetPortSettingData.SyntheticEthernetPortSettingDataCollection(wmiObjectSearch.Get()); + + List results = new List(wmiObjCollection.Count); + foreach (SyntheticEthernetPortSettingData item in wmiObjCollection) + { + results.Add(item); + } + + return results.ToArray(); + } + + public string GetDefaultDataRoot() + { + string defaultRootPath = null; + VirtualSystemManagementServiceSettingData vs_mgmt_data = VirtualSystemManagementServiceSettingData.CreateInstance(); + defaultRootPath = vs_mgmt_data.DefaultVirtualHardDiskPath; + if (defaultRootPath == null) { + defaultRootPath = Path.GetPathRoot(Environment.SystemDirectory) + + "\\Users\\Public\\Documents\\Hyper-V\\Virtual hard disks"; + } + + return defaultRootPath; + } + + public VirtualSystemSettingData GetVmSettings(ComputerSystem vm) + { + // An ASSOCIATOR object provides the cross reference from the ComputerSettings and the + // VirtualSystemSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. + // Instead, we use the System.Management to code the equivalant of + // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vm.path, resultclassName); + // + var wmiObjQuery = new RelatedObjectQuery(vm.Path.Path, VirtualSystemSettingData.CreatedClassName); + + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var wmiObjectSearch = new ManagementObjectSearcher(vm.Scope, wmiObjQuery); + var wmiObjCollection = new VirtualSystemSettingData.VirtualSystemSettingDataCollection(wmiObjectSearch.Get()); + + // When snapshots are taken into account, there can be multiple settings objects + // take the first one that isn't a snapshot + foreach (VirtualSystemSettingData wmiObj in wmiObjCollection) + { + if (wmiObj.VirtualSystemType == "Microsoft:Hyper-V:System:Realized" || + wmiObj.VirtualSystemType == "Microsoft:Hyper-V:System:Planned") + { + return wmiObj; + } + } + + var errMsg = string.Format("No VirtualSystemSettingData for VM {0}, path {1}", vm.ElementName, vm.Path.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + public KvpExchangeComponentSettingData GetKvpSettings(VirtualSystemSettingData vmSettings) + { + // An ASSOCIATOR object provides the cross reference from the VirtualSystemSettingData and the + // KvpExchangeComponentSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. + // Instead, we use the System.Management to code the equivalant of + // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vmSettings.path, resultclassName); + // + var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, KvpExchangeComponentSettingData.CreatedClassName); + + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var wmiObjectSearch = new ManagementObjectSearcher(vmSettings.Scope, wmiObjQuery); + var wmiObjCollection = new KvpExchangeComponentSettingData.KvpExchangeComponentSettingDataCollection(wmiObjectSearch.Get()); + + foreach (KvpExchangeComponentSettingData wmiObj in wmiObjCollection) + { + return wmiObj; + } + + var errMsg = string.Format("No KvpExchangeComponentSettingData in VirtualSystemSettingData {0}", vmSettings.Path.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + public void GetSummaryInfo(Dictionary vmProcessorInfo, List vmsToInspect) + { + // Process info available from WMI, + // See http://msdn.microsoft.com/en-us/library/hh850062(v=vs.85).aspx + uint[] requestedInfo = new uint[] { // TODO: correct? + 0, // Name + 1, // ElementName + 4, // Number of processes + 101 // ProcessorLoad + }; + + System.Management.ManagementBaseObject[] sysSummary; + var vmsvc = GetVirtualisationSystemManagementService(); + System.Management.ManagementPath[] vmPaths = vmsToInspect.ToArray(); + vmsvc.GetSummaryInformation(requestedInfo, vmPaths, out sysSummary); + + foreach (var summary in sysSummary) + { + + var summaryInfo = new SummaryInformation(summary); + + logger.Debug("VM " + summaryInfo.Name + "(elementName " + summaryInfo.ElementName + ") has " + + summaryInfo.NumberOfProcessors + " CPUs, and load of " + summaryInfo.ProcessorLoad); + var vmInfo = new VmStatsEntry + { + cpuUtilization = summaryInfo.ProcessorLoad, + numCPUs = summaryInfo.NumberOfProcessors, + networkReadKBs = 1, + networkWriteKBs = 1, + entityType = "vm" + }; + vmProcessorInfo.Add(summaryInfo.ElementName, vmInfo); + } + } + } + + public class WmiException : Exception + { + public WmiException() + { + } + + public WmiException(string message) + : base(message) + { + } + + public WmiException(string message, Exception inner) + : base(message, inner) + { + } + } + + /// + /// Covers V2 API, see + /// http://msdn.microsoft.com/en-us/library/hh850031%28v=vs.85%29.aspx + /// + public static class ReturnCode + { + public const UInt32 Completed = 0; + public const UInt32 Started = 4096; + public const UInt32 Failed = 32768; + public const UInt32 AccessDenied = 32769; + public const UInt32 NotSupported = 32770; + public const UInt32 Unknown = 32771; + public const UInt32 Timeout = 32772; + public const UInt32 InvalidParameter = 32773; + public const UInt32 SystemInUse = 32774; + public const UInt32 InvalidState = 32775; + public const UInt32 IncorrectDataType = 32776; + public const UInt32 SystemNotAvailable = 32777; + public const UInt32 OutofMemory = 32778; + public static string ToString(UInt32 value) + { + string result = "Unknown return code"; + switch (value) + { + case Completed: result = "Completed"; break; + case Started: result = "Started"; break; + case Failed: result = "Failed"; break; + case AccessDenied: result = "AccessDenied"; break; + case NotSupported: result = "NotSupported"; break; + case Unknown: result = "Unknown"; break; + case Timeout: result = "Timeout"; break; + case InvalidParameter: result = "InvalidParameter"; break; + case SystemInUse: result = "SystemInUse"; break; + case InvalidState: result = "InvalidState"; break; + case IncorrectDataType: result = "IncorrectDataType"; break; + case SystemNotAvailable: result = "SystemNotAvailable"; break; + case OutofMemory: result = "OutofMemory"; break; + } + return result; + } + } + + /// + /// Covers V2 API, see + /// http://msdn.microsoft.com/en-us/library/hh850031%28v=vs.85%29.aspx + /// + public static class JobState + { + public const UInt16 New = 2; + public const UInt16 Starting = 3; + public const UInt16 Running = 4; + public const UInt16 Suspended = 5; + public const UInt16 ShuttingDown = 6; + public const UInt16 Completed = 7; + public const UInt16 Terminated = 8; + public const UInt16 Killed = 9; + public const UInt16 Exception = 10; + public const UInt16 Service = 11; + public static string ToString(UInt16 value) + { + string result = "Unknown JobState code"; + switch (value) + { + case New: result = "New"; break; + case Starting: result = "Starting"; break; + case Running: result = "Running"; break; + case Suspended: result = "Suspended"; break; + case ShuttingDown: result = "ShuttingDown"; break; + case Completed: result = "Completed"; break; + case Terminated: result = "Terminated"; break; + case Killed: result = "Killed"; break; + case Exception: result = "Exception"; break; + case Service: result = "Service"; break; + } + return result; + } + } + + /// + /// V2 API (see http://msdn.microsoft.com/en-us/library/hh850279(v=vs.85).aspx) + /// has removed 'Paused' and 'Suspended' as compared to the + /// V1 API (see http://msdn.microsoft.com/en-us/library/cc723874%28v=vs.85%29.aspx) + /// However, Paused and Suspended appear on the VM state transition table + /// (see http://msdn.microsoft.com/en-us/library/hh850116(v=vs.85).aspx#methods) + /// + public class RequiredState + { + public const UInt16 Enabled = 2; // Turns the VM on. + public const UInt16 Disabled = 3; // Turns the VM off. + public const UInt16 ShutDown = 4; + public const UInt16 Offline = 6; + //public const UInt16 Test = 7; + public const UInt16 Defer = 8; + // public const UInt16 Quiesce = 9; + // public const UInt16 Reboot = 10; // A hard reset of the VM. + public const UInt16 Reset = 11; // For future use. + public const UInt16 Paused = 9; // Pauses the VM. + public const UInt16 Suspended = 32779; // Saves the state of the VM. + + public static string ToString(UInt16 value) + { + string result = "Unknown RequiredState code"; + switch (value) + { + case Enabled: result = "Enabled"; break; + case Disabled: result = "Disabled"; break; + case ShutDown: result = "ShutDown"; break; + case Offline: result = "Offline"; break; + case Defer: result = "Defer"; break; + case Reset: result = "Reset"; break; + } + return result; + } + } + + /// + /// V2 API specifies the states below in its state transition graph at + /// http://msdn.microsoft.com/en-us/library/hh850116(v=vs.85).aspx#methods + /// However, the CIM standard has additional possibilities based on the description + /// of EnabledState. + /// The previous V1 API is described by + /// http://msdn.microsoft.com/en-us/library/cc136822%28v=vs.85%29.aspx + /// + public class EnabledState + { + /// + /// The state of the VM could not be determined. + /// + public const UInt16 Unknown = 0; + /// + /// The VM is running. + /// + public const UInt16 Enabled = 2; + /// + /// The VM is turned off. + /// + public const UInt16 Disabled = 3; + /// + /// The VM is paused. + /// + public const UInt16 Paused = 32768; + /// + /// The VM is in a saved state. + /// + public const UInt16 Suspended = 32769; + /// + /// The VM is starting. This is a transitional state between 3 (Disabled) + /// or 32769 (Suspended) and 2 (Enabled) initiated by a call to the + /// RequestStateChange method with a RequestedState parameter of 2 (Enabled). + /// + public const UInt16 Starting = 32770; + /// + /// Starting with Windows Server 2008 R2 this value is not supported. + /// If the VM is performing a snapshot operation, the element at index 1 + /// of the OperationalStatus property array will contain 32768 (Creating Snapshot), + /// 32769 (Applying Snapshot), or 32770 (Deleting Snapshot). + /// + public const UInt16 Snapshotting = 32771; + /// + /// The VM is saving its state. This is a transitional state between 2 (Enabled) + /// and 32769 (Suspended) initiated by a call to the RequestStateChange method + /// with a RequestedState parameter of 32769 (Suspended). + /// + public const UInt16 Saving = 32773; + /// + /// The VM is turning off. This is a transitional state between 2 (Enabled) + /// and 3 (Disabled) initiated by a call to the RequestStateChange method + /// with a RequestedState parameter of 3 (Disabled) or a guest operating system + /// initiated power off. + /// + public const UInt16 Stopping = 32774; + /// + /// The VM is pausing. This is a transitional state between 2 (Enabled) and 32768 (Paused) initiated by a call to the RequestStateChange method with a RequestedState parameter of 32768 (Paused). + /// + public const UInt16 Pausing = 32776; + /// + /// The VM is resuming from a paused state. This is a transitional state between 32768 (Paused) and 2 (Enabled). + /// + public const UInt16 Resuming = 32777; + + public static string ToString(UInt16 value) + { + string result = "Unknown"; + switch (value) + { + case Enabled: result = "Enabled"; break; + case Disabled: result = "Disabled"; break; + case Paused: result = "Paused"; break; + case Suspended: result = "Suspended"; break; + case Starting: result = "Starting"; break; + case Snapshotting: result = "Snapshotting"; break; // NOT used + case Saving: result = "Saving"; break; + case Stopping: result = "Stopping"; break; + case Pausing: result = "Pausing"; break; + case Resuming: result = "Resuming"; break; + } + return result; + } + + public static string ToCloudStackState(UInt16 value) + { + string result = "Unknown"; + switch (value) + { + case Enabled: result = "Running"; break; + case Disabled: result = "Stopped"; break; + case Paused: result = "Unknown"; break; + case Suspended: result = "Unknown"; break; + case Starting: result = "Starting"; break; + case Snapshotting: result = "Unknown"; break; // NOT used + case Saving: result = "Saving"; break; + case Stopping: result = "Stopping"; break; + case Pausing: result = "Unknown"; break; + case Resuming: result = "Starting"; break; + } + return result; + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/packages.config b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/packages.config new file mode 100644 index 00000000000..4c538e4872b --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/packages.config @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/App.config b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/App.config new file mode 100644 index 00000000000..c959ccf1443 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/App.config @@ -0,0 +1,139 @@ + + + + + +
+ + +
+ + + + + + + + + + + 8 + + + 10.1.1.1 + + + Routing + + + 5fe2bad3-d785-394e-9949-89786b8a63d2 + + + hvm + + + 2130 + + + 8250 + + + 34359738368 + + + camldonall01.citrite.net + + + 1 + + + 10.70.176.1 + + + 2 + + + 1 + + + E:\Disks\Disks + + + 5 + + + 255.255.240.0 + + + 4294967296 + + + ..\..\..\..\..\ + + + e:\ + + + 2048 + + + 101F742C6B88 + + + + + + + c:\Secondary + + + E:\Disks\Disks + + + 5fe2bad3-d785-394e-9949-89786b8a63d2 + + + .\var\test\storagepool + + + cshv3eu + + + s3.amazonaws.com + + + testS3AccessKey + + + testS3SecretKey + + + 206-2-73592258-559a-3b38-8f66-b667aab143eb + + + 206-2-73592258-559a-3b38-8f66-b667aab143eb + + + cifs://10.1.1.1/secondary?user\u003dadministrator\u0026password\u003d1pass%40word1 + + + template/tmpl/2/201/6dda6631-4daa-3150-a49a-d5a4b0a4c4b6.vhd + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceController1Test.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceController1Test.cs new file mode 100644 index 00000000000..fd0a4bf2f7e --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceController1Test.cs @@ -0,0 +1,350 @@ +// 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 CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2; +using System.Management; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json; +using System.IO; +using log4net; +using HypervResource; +using CloudStack.Plugin.AgentShell; +using System.Collections.Generic; +using NSubstitute; +using System.Web.Http; +using Xunit; + +namespace ServerResource.Tests +{ + public class HypervResourceController1Test + { + protected static string testCifsUrl = AgentSettings.Default.testCifsUrl; + protected static string testCifsPath = AgentSettings.Default.testCifsPath; + protected static String testPrimaryDataStoreHost = HypervResourceController.config.StorageIpAddress; + protected static String testS3TemplateName = AgentSettings.Default.testS3TemplateName; + protected static String testCifsTemplateName = AgentSettings.Default.testS3TemplateName; + protected static String testSystemVMTemplateName = AgentSettings.Default.testSystemVMTemplateName; + protected static String testSystemVMTemplateNameNoExt = AgentSettings.Default.testSystemVMTemplateNameNoExt; + protected static String testLocalStoreUUID = "5fe2bad3-d785-394e-9949-89786b8a63d2"; + protected static String testLocalStorePath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "storagepool"); + protected static String testSecondaryStoreLocalPath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "secondary"); + + // TODO: differentiate between NFS and HTTP template URLs. + protected static String testSampleTemplateUUID = "TestCopiedLocalTemplate.vhdx"; + protected static String testSampleTemplateURL = testSampleTemplateUUID; + + // test volumes are both a minimal size vhdx. Changing the extension to .vhd makes on corrupt. + protected static String testSampleVolumeWorkingUUID = "TestVolumeLegit.vhdx"; + protected static String testSampleVolumeCorruptUUID = "TestVolumeCorrupt.vhd"; + protected static String testSampleVolumeTempUUID = "TestVolumeTemp.vhdx"; + protected static String testSampleVolumeTempUUIDNoExt = "TestVolumeTemp"; + protected static String testSampleVolumeWorkingURIJSON; + protected static String testSampleVolumeCorruptURIJSON; + protected static String testSampleVolumeTempURIJSON; + + protected static String testSampleTemplateURLJSON; + protected static String testLocalStorePathJSON; + + protected static IWmiCallsV2 wmiCallsV2; + + + private static ILog s_logger = LogManager.GetLogger(typeof(HypervResourceController1Test)); + + /// + /// Test WmiCalls to which incoming HTTP POST requests are dispatched. + /// + /// TODO: revise beyond first approximation + /// First approximation is a quick port of the existing Java tests for Hyper-V server resource. + /// A second approximation would use the AgentShell settings files directly. + /// A third approximation would look to invoke ServerResource methods via an HTTP request + /// + + public HypervResourceController1Test() + { + wmiCallsV2 = Substitute.For(); + //AgentService.ConfigServerResource(); + HypervResourceController.config.PrivateMacAddress = AgentSettings.Default.private_mac_address; + HypervResourceController.config.PrivateNetmask = AgentSettings.Default.private_ip_netmask; + HypervResourceController.config.StorageIpAddress = HypervResourceController.config.PrivateIpAddress; + HypervResourceController.config.StorageMacAddress = HypervResourceController.config.PrivateMacAddress; + HypervResourceController.config.StorageNetmask = HypervResourceController.config.PrivateNetmask; + + + // Used to create existing StoragePool in preparation for the ModifyStoragePool + testLocalStoreUUID = AgentSettings.Default.local_storage_uuid.ToString(); + + // Make sure secondary store is available. + string fullPath = Path.GetFullPath(testSecondaryStoreLocalPath); + s_logger.Info("Test secondary storage in " + fullPath); + DirectoryInfo testSecondarStoreDir = new DirectoryInfo(fullPath); + if (!testSecondarStoreDir.Exists) + { + try + { + testSecondarStoreDir.Create(); + } + catch (System.IO.IOException ex) + { + throw new NotImplementedException("Need to be able to create the folder " + testSecondarStoreDir.FullName + " failed due to " + ex.Message); + } + } + + // Convert to secondary storage string to canonical path + testSecondaryStoreLocalPath = testSecondarStoreDir.FullName; + AgentSettings.Default.local_secondary_storage_path = testSecondaryStoreLocalPath; + + // Make sure local primary storage is available + DirectoryInfo testPoolDir = new DirectoryInfo(testLocalStorePath); + //Assert.True(testPoolDir.Exists, "To simulate local file system Storage Pool, you need folder at " + testPoolDir.FullName); + + // Convert to local primary storage string to canonical path + testLocalStorePath = testPoolDir.FullName; + AgentSettings.Default.local_storage_path = testLocalStorePath; + + // Clean up old test files in local storage folder + FileInfo testVolWorks = new FileInfo(Path.Combine(testLocalStorePath, testSampleVolumeWorkingUUID)); + // Assert.True(testVolWorks.Exists, "Create a working virtual disk at " + testVolWorks.FullName); + + testSampleTemplateURLJSON = JsonConvert.SerializeObject(testSampleTemplateUUID); + s_logger.Info("Created " + testSampleTemplateURLJSON + " in local storage."); + + + // Capture other JSON encoded paths + testSampleVolumeWorkingURIJSON = Newtonsoft.Json.JsonConvert.SerializeObject(testVolWorks.FullName); + testLocalStorePathJSON = JsonConvert.SerializeObject(testLocalStorePath); + + // TODO: may need to initialise the server resource in future. + // s_hypervresource.initialize(); + + // Verify sample template is in place storage pool + s_logger.Info("setUp complete, sample StoragePool at " + testLocalStorePathJSON + + " sample template at " + testSampleTemplateURLJSON); + } + + private String CreateTestDiskImageFromExistingImage(FileInfo srcFile, + String dstPath, + String dstFileName) + { + var newFullname = Path.Combine(dstPath, dstFileName); + var newFileInfo = new FileInfo(newFullname); + if (!newFileInfo.Exists) + { + newFileInfo = srcFile.CopyTo(newFullname); + } + newFileInfo.Refresh(); + Assert.True(newFileInfo.Exists, "Attempted to create " + newFullname + " from " + newFileInfo.FullName); + + return JsonConvert.SerializeObject(newFileInfo.FullName); + } + + [Fact] + public void TestCreateCommand() + { + DirectoryInfo localStorePath = new DirectoryInfo(testLocalStorePath); + if (!localStorePath.Exists) + { + try + { + localStorePath.Create(); + } + catch (System.IO.IOException ex) + { + throw new NotImplementedException("Need to be able to create the folder " + localStorePath.FullName + " failed due to " + ex.Message); + } + } + + FileInfo sampleTemplateFile = new FileInfo(Path.Combine(testLocalStorePath, testSampleTemplateUUID)); + if (!sampleTemplateFile.Exists) + { + //Create a file to write to. + using (StreamWriter sw = sampleTemplateFile.CreateText()) + { + sw.WriteLine("This is fake template file for test"); + } + } + var counter = 0; + wmiCallsV2.When(x => x.CreateDynamicVirtualHardDisk(Arg.Any(), Arg.Any())).Do(x => counter++); + // TODO: Need sample to update the test. + // Arrange + String createCmd = "{\"volId\":10,\"pool\":{\"id\":201,\"uuid\":\"" + testLocalStoreUUID + "\",\"host\":\"" + HypervResourceController.config.StorageIpAddress + "\"" + + ",\"path\":" + testLocalStorePathJSON + ",\"port\":0,\"type\":\"Filesystem\"},\"diskCharacteristics\":{\"size\":0," + + "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-9\",\"useLocalStorage\":true,\"recreatable\":true,\"diskOfferingId\":11," + + "\"volumeId\":10,\"hyperType\":\"Hyperv\"},\"templateUrl\":" + testSampleTemplateURLJSON + ",\"contextMap\":{},\"wait\":0}"; + dynamic jsonCreateCmd = JsonConvert.DeserializeObject(createCmd); + HypervResourceController rsrcServer = new HypervResourceController(); + HypervResourceController.wmiCallsV2 = wmiCallsV2; + + Assert.True(Directory.Exists(testLocalStorePath), testLocalStorePath + " does not exist "); + string filePath = Path.Combine(testLocalStorePath, (string)JsonConvert.DeserializeObject(testSampleTemplateURLJSON)); + Assert.True(File.Exists(filePath), "The template we make volumes from is missing from path " + filePath); + int fileCount = Directory.GetFiles(testLocalStorePath).Length; + s_logger.Debug(" test local store has " + fileCount + "files"); + + // Act + // Test requires there to be a template at the tempalteUrl, which is its location in the local file system. + dynamic jsonResult = rsrcServer.CreateCommand(jsonCreateCmd); + s_logger.Debug("CreateDynamicVirtualHardDisk method is called " + counter + " times"); + + //Assert.Equal(counter, 1); + + JObject ansAsProperty2 = jsonResult[0]; + dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.CreateAnswer); + Assert.NotNull(ans); + Assert.True((bool)ans.result, "Failed to CreateCommand due to " + (string)ans.result); + Assert.Equal(Directory.GetFiles(testLocalStorePath).Length, fileCount + 1); + FileInfo newFile = new FileInfo((string)ans.volume.path); + Assert.True(newFile.Length > 0, "The new file should have a size greater than zero"); + newFile.Delete(); + sampleTemplateFile.Delete(); + } + + [Fact] + public void TestDestroyCommand() + { + testSampleVolumeTempURIJSON = "\"storagepool\""; + // Arrange + String destoryCmd = //"{\"volume\":" + getSampleVolumeObjectTO() + "}"; + "{\"volume\":{\"name\":\"" + testSampleVolumeTempUUIDNoExt + + "\",\"storagePoolType\":\"Filesystem\"," + + "\"mountPoint\":" + + testLocalStorePathJSON + + ",\"path\":" + testSampleVolumeTempURIJSON + + ",\"storagePoolUuid\":\"" + testLocalStoreUUID + + "\"," + + "\"type\":\"ROOT\",\"id\":9,\"size\":0}}"; + + ImageManagementService imgmgr = new ImageManagementService(); + wmiCallsV2.GetImageManagementService().Returns(imgmgr); + + HypervResourceController rsrcServer = new HypervResourceController(); + HypervResourceController.wmiCallsV2 = wmiCallsV2; + + dynamic jsonDestoryCmd = JsonConvert.DeserializeObject(destoryCmd); + + // Act + dynamic destoryAns = rsrcServer.DestroyCommand(jsonDestoryCmd); + + // Assert + JObject ansAsProperty2 = destoryAns[0]; + dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.Answer); + String path = jsonDestoryCmd.volume.path; + Assert.True((bool)ans.result, "DestroyCommand did not succeed " + ans.details); + Assert.True(!File.Exists(path), "Failed to delete file " + path); + } + + [Fact] + public void TestStartCommand() + { + ComputerSystem system = new ComputerSystem(); + wmiCallsV2.DeployVirtualMachine(Arg.Any(), Arg.Any()).Returns(system); + + // Arrange + HypervResourceController rsrcServer = new HypervResourceController(); + HypervResourceController.wmiCallsV2 = wmiCallsV2; + String sample = getSampleStartCommand(); + + + dynamic jsonStartCmd = JsonConvert.DeserializeObject(sample); + + // Act + dynamic startAns = rsrcServer.StartCommand(jsonStartCmd); + + // Assert + Assert.NotNull(startAns[0][CloudStackTypes.StartAnswer]); + Assert.True((bool)startAns[0][CloudStackTypes.StartAnswer].result, "StartCommand did not succeed " + startAns[0][CloudStackTypes.StartAnswer].details); + + Assert.Null((string)startAns[0][CloudStackTypes.StartAnswer].details); + } + + [Fact] + public void TestStopCommand() + { + //string vmName = "Test VM"; + var counter = 0; + wmiCallsV2.When(x => x.DestroyVm(Arg.Any())).Do(x => counter++); + + // Arrange + HypervResourceController rsrcServer = new HypervResourceController(); + HypervResourceController.wmiCallsV2 = wmiCallsV2; + + String sampleStop = "{\"isProxy\":false,\"vmName\":\"i-2-17-VM\",\"contextMap\":{},\"wait\":0}"; + dynamic jsonStopCmd = JsonConvert.DeserializeObject(sampleStop); + + // Act + dynamic stopAns = rsrcServer.StopCommand(jsonStopCmd); + + // Assert VM is gone! + Assert.NotNull(stopAns[0][CloudStackTypes.StopAnswer]); + Assert.True((bool)stopAns[0][CloudStackTypes.StopAnswer].result, "StopCommand did not succeed " + stopAns[0][CloudStackTypes.StopAnswer].details); + + Assert.Null((string)stopAns[0][CloudStackTypes.StopAnswer].details); + Assert.Equal(counter, 1); + } + + public static String getSamplePrimaryDataStoreInfo() + { + String samplePrimaryDataStoreInfo = + "{\"org.apache.cloudstack.storage.to.PrimaryDataStoreTO\":" + + "{\"uuid\":\"" + testLocalStoreUUID + "\"," + + "\"id\":201," + + "\"host\":\"" + testPrimaryDataStoreHost + "\"," + + "\"type\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO + "\"poolType\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO + "\"path\":" + testLocalStorePathJSON + "," + + "\"port\":0}" + + "}"; + return samplePrimaryDataStoreInfo; + } + + public static String getSampleVolumeObjectTO() + { + String sampleVolumeObjectTO = + "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + + "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + + "\"volumeType\":\"ROOT\"," + + "\"format\":\"VHDX\"," + + "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"" + testSampleVolumeTempUUIDNoExt + "\"," + + "\"size\":52428800," + + "\"volumeId\":10," + + // "\"vmName\":\"i-3-5-VM\"," + // TODO: do we have to fill in the vmName? + "\"accountId\":3,\"id\":10}" + + "}"; // end of destTO + return sampleVolumeObjectTO; + } + + public static String getSampleStartCommand() + { + String sample = "{\"vm\":{\"id\":17,\"name\":\"i-2-17-VM\",\"type\":\"User\",\"cpus\":1,\"speed\":500," + + "\"minRam\":536870912,\"maxRam\":536870912,\"arch\":\"x86_64\"," + + "\"os\":\"CentOS 6.0 (64-bit)\",\"bootArgs\":\"\",\"rebootOnCrash\":false," + + "\"enableHA\":false,\"limitCpuUse\":false,\"vncPassword\":\"31f82f29aff646eb\"," + + "\"params\":{},\"uuid\":\"8b030b6a-0243-440a-8cc5-45d08815ca11\"" + + ",\"disks\":[" + + "{\"data\":" + getSampleVolumeObjectTO() + ",\"diskSeq\":0,\"type\":\"ROOT\"}," + + "{\"diskSeq\":1,\"type\":\"ISO\"}" + + "]," + + "\"nics\":[" + + "{\"deviceId\":0,\"networkRateMbps\":100,\"defaultNic\":true,\"uuid\":\"99cb4813-23af-428c-a87a-2d1899be4f4b\"," + + "\"ip\":\"10.1.1.67\",\"netmask\":\"255.255.255.0\",\"gateway\":\"10.1.1.1\"," + + "\"mac\":\"02:00:51:2c:00:0e\",\"dns1\":\"4.4.4.4\",\"broadcastType\":\"Vlan\",\"type\":\"Guest\"," + + "\"broadcastUri\":\"vlan://261\",\"isolationUri\":\"vlan://261\",\"isSecurityGroupEnabled\":false}" + + "]},\"contextMap\":{},\"wait\":0}"; + return sample; + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceControllerTest.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceControllerTest.cs new file mode 100644 index 00000000000..fab1b8243b2 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceControllerTest.cs @@ -0,0 +1,1147 @@ +// 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 CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION; +using System.Management; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json; +using System.IO; +using log4net; +using HypervResource; +using CloudStack.Plugin.AgentShell; +using System.Collections.Generic; +using System.Xml; +using Xunit; + +namespace ServerResource.Tests +{ + public class HypervResourceControllerTest + { + protected static string testCifsUrl = AgentSettings.Default.testCifsUrl; + protected static string testCifsPath = AgentSettings.Default.testCifsPath; + protected static String testPrimaryDataStoreHost = HypervResourceController.config.StorageIpAddress; + protected static String testS3TemplateName = AgentSettings.Default.testS3TemplateName; + protected static String testCifsTemplateName = AgentSettings.Default.testS3TemplateName; + protected static String testSystemVMTemplateName = AgentSettings.Default.testSystemVMTemplateName; + protected static String testSystemVMTemplateNameNoExt = AgentSettings.Default.testSystemVMTemplateNameNoExt; + protected static String testLocalStoreUUID = "5fe2bad3-d785-394e-9949-89786b8a63d2"; + protected static String testLocalStorePath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "storagepool"); + protected static String testSecondaryStoreLocalPath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "secondary"); + + // TODO: differentiate between NFS and HTTP template URLs. + protected static String testSampleTemplateUUID = "TestCopiedLocalTemplate.vhdx"; + protected static String testSampleTemplateURL = testSampleTemplateUUID; + + // test volumes are both a minimal size vhdx. Changing the extension to .vhd makes on corrupt. + protected static String testSampleVolumeWorkingUUID = "TestVolumeLegit.vhdx"; + protected static String testSampleVolumeCorruptUUID = "TestVolumeCorrupt.vhd"; + protected static String testSampleVolumeTempUUID = "TestVolumeTemp.vhdx"; + protected static String testSampleVolumeTempUUIDNoExt = "TestVolumeTemp"; + protected static String testSampleVolumeWorkingURIJSON; + protected static String testSampleVolumeCorruptURIJSON; + protected static String testSampleVolumeTempURIJSON; + + protected static String testSampleTemplateURLJSON; + protected static String testLocalStorePathJSON; + + protected static WmiCallsV2 wmiCallsV2 = new WmiCallsV2(); + + private static ILog s_logger = LogManager.GetLogger(typeof(HypervResourceControllerTest)); + + /// + /// Test WmiCalls to which incoming HTTP POST requests are dispatched. + /// + /// TODO: revise beyond first approximation + /// First approximation is a quick port of the existing Java tests for Hyper-V server resource. + /// A second approximation would use the AgentShell settings files directly. + /// A third approximation would look to invoke ServerResource methods via an HTTP request + /// + public HypervResourceControllerTest() + { + AgentService.ConfigServerResource(); + HypervResourceController.config.PrivateMacAddress = AgentSettings.Default.private_mac_address; + HypervResourceController.config.PrivateNetmask = AgentSettings.Default.private_ip_netmask; + HypervResourceController.config.StorageIpAddress = HypervResourceController.config.PrivateIpAddress; + HypervResourceController.config.StorageMacAddress = HypervResourceController.config.PrivateMacAddress; + HypervResourceController.config.StorageNetmask = HypervResourceController.config.PrivateNetmask; + + + // Used to create existing StoragePool in preparation for the ModifyStoragePool + testLocalStoreUUID = AgentSettings.Default.local_storage_uuid.ToString(); + + // Make sure secondary store is available. + string fullPath = Path.GetFullPath(testSecondaryStoreLocalPath); + s_logger.Info("Test secondary storage in " + fullPath); + DirectoryInfo testSecondarStoreDir = new DirectoryInfo(fullPath); + if (!testSecondarStoreDir.Exists) + { + try + { + testSecondarStoreDir.Create(); + } + catch (System.IO.IOException ex) + { + throw new NotImplementedException("Need to be able to create the folder " + testSecondarStoreDir.FullName + " failed due to " + ex.Message); + } + } + + // Convert to secondary storage string to canonical path + testSecondaryStoreLocalPath = testSecondarStoreDir.FullName; + AgentSettings.Default.local_secondary_storage_path = testSecondaryStoreLocalPath; + + // Make sure local primary storage is available + DirectoryInfo testPoolDir = new DirectoryInfo(testLocalStorePath); + Assert.True(testPoolDir.Exists, "To simulate local file system Storage Pool, you need folder at " + testPoolDir.FullName); + + // Convert to local primary storage string to canonical path + testLocalStorePath = testPoolDir.FullName; + AgentSettings.Default.local_storage_path = testLocalStorePath; + + // Clean up old test files in local storage folder + FileInfo testVolWorks = new FileInfo(Path.Combine(testLocalStorePath, testSampleVolumeWorkingUUID)); + Assert.True(testVolWorks.Exists, "Create a working virtual disk at " + testVolWorks.FullName); + + + // Delete all temporary files in local folder save the testVolWorks + foreach (var file in testPoolDir.GetFiles()) + { + if (file.FullName == testVolWorks.FullName) + { + continue; + } + file.Delete(); + file.Refresh(); + Assert.False(file.Exists, "removed file from previous test called " + file.FullName); + } + + // Recreate starting point files for test, and record JSON encoded paths for each ... + testSampleVolumeTempURIJSON = CreateTestDiskImageFromExistingImage(testVolWorks, testLocalStorePath, testSampleVolumeTempUUID); + s_logger.Info("Created " + testSampleVolumeTempURIJSON); + testSampleVolumeCorruptURIJSON = CreateTestDiskImageFromExistingImage(testVolWorks, testLocalStorePath, testSampleVolumeCorruptUUID); + s_logger.Info("Created " + testSampleVolumeCorruptURIJSON); + CreateTestDiskImageFromExistingImage(testVolWorks, testLocalStorePath, testSampleTemplateUUID); + testSampleTemplateURLJSON = JsonConvert.SerializeObject(testSampleTemplateUUID); + s_logger.Info("Created " + testSampleTemplateURLJSON + " in local storage."); + + // ... including a secondary storage template: + CreateTestDiskImageFromExistingImage(testVolWorks, testSecondarStoreDir.FullName, "af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx"); + s_logger.Info("Created " + "af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx" + " in secondary (NFS) storage."); + + + // Capture other JSON encoded paths + testSampleVolumeWorkingURIJSON = Newtonsoft.Json.JsonConvert.SerializeObject(testVolWorks.FullName); + testLocalStorePathJSON = JsonConvert.SerializeObject(testLocalStorePath); + + // TODO: may need to initialise the server resource in future. + // s_hypervresource.initialize(); + + // Verify sample template is in place storage pool + s_logger.Info("setUp complete, sample StoragePool at " + testLocalStorePathJSON + + " sample template at " + testSampleTemplateURLJSON); + } + + private String CreateTestDiskImageFromExistingImage(FileInfo srcFile, + String dstPath, + String dstFileName) + { + var newFullname = Path.Combine(dstPath, dstFileName); + var newFileInfo = new FileInfo(newFullname); + if (!newFileInfo.Exists) + { + newFileInfo = srcFile.CopyTo(newFullname); + } + newFileInfo.Refresh(); + Assert.True(newFileInfo.Exists, "Attempted to create " + newFullname + " from " + newFileInfo.FullName); + + return JsonConvert.SerializeObject(newFileInfo.FullName); + } + + [Fact(Skip="these are functional tests")] + public void TestPrimaryStorageDownloadCommandHTTP() + { + string downloadURI = "https://s3-eu-west-1.amazonaws.com/cshv3eu/SmallDisk.vhdx"; + corePrimaryStorageDownloadCommandTestCycle(downloadURI); + } + + private void corePrimaryStorageDownloadCommandTestCycle(string downloadURI) + { + // Arrange + HypervResourceController rsrcServer = new HypervResourceController(); + dynamic jsonPSDCmd = JsonConvert.DeserializeObject(samplePrimaryDownloadCommand()); + jsonPSDCmd.url = downloadURI; + + // Act + dynamic jsonResult = rsrcServer.PrimaryStorageDownloadCommand(jsonPSDCmd); + + // Assert + JObject ansAsProperty = jsonResult[0]; + dynamic ans = ansAsProperty.GetValue(CloudStackTypes.PrimaryStorageDownloadAnswer); + Assert.True((bool)ans.result, "PrimaryStorageDownloadCommand did not succeed " + ans.details); + + // Test that URL of downloaded template works for file creation. + dynamic jsonCreateCmd = JsonConvert.DeserializeObject(CreateCommandSample()); + jsonCreateCmd.templateUrl = ans.installPath; + dynamic jsonAns2 = rsrcServer.CreateCommand(jsonCreateCmd); + JObject ansAsProperty2 = jsonAns2[0]; + dynamic ans2 = ansAsProperty2.GetValue(CloudStackTypes.CreateAnswer); + + Assert.True((bool)ans2.result, (string)ans2.details); + + FileInfo newFile = new FileInfo((string)ans2.volume.path); + Assert.True(newFile.Length > 0, "The new file should have a size greater than zero"); + newFile.Delete(); + } + + private string samplePrimaryDownloadCommand() + { + String cmdJson = "{\"localPath\":" + testLocalStorePathJSON + + ",\"poolUuid\":\"" + testLocalStoreUUID + "\",\"poolId\":201," + + "\"secondaryStorageUrl\":\"nfs://10.70.176.36/mnt/cshv3/secondarystorage\"," + + "\"primaryStorageUrl\":\"nfs://" + HypervResourceController.config.StorageIpAddress + "E:\\\\Disks\\\\Disks\"," + + "\"url\":\"nfs://10.70.176.36/mnt/cshv3/secondarystorage/template/tmpl//2/204//af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx\"," + + "\"format\":\"VHDX\",\"accountId\":2,\"name\":\"204-2-5a1db1ac-932b-3e7e-a0e8-5684c72cb862\"" + + ",\"contextMap\":{},\"wait\":10800}"; + return cmdJson; + } + + public string CreateCommandSample() + { + String sample = "{\"volId\":17,\"pool\":{\"id\":201,\"uuid\":\"" + testLocalStoreUUID + "\",\"host\":\"" + HypervResourceController.config.StorageIpAddress + "\"" + + ",\"path\":" + testLocalStorePathJSON + ",\"port\":0,\"type\":\"Filesystem\"},\"diskCharacteristics\":{\"size\":0," + + "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-15\",\"useLocalStorage\":true,\"recreatable\":true,\"diskOfferingId\":11," + + "\"volumeId\":17,\"hyperType\":\"Hyperv\"},\"templateUrl\":" + testSampleTemplateURLJSON + ",\"wait\":0}"; + return sample; + } + + [Fact(Skip="these are functional tests")] + public void TestDestroyCommand() + { + // Arrange + String sampleVolume = getSampleVolumeObjectTO(); + String destoryCmd = //"{\"volume\":" + getSampleVolumeObjectTO() + "}"; + "{\"volume\":{\"name\":\"" + testSampleVolumeTempUUIDNoExt + + "\",\"storagePoolType\":\"Filesystem\"," + + "\"mountPoint\":" + + testLocalStorePathJSON + + ",\"path\":" + testSampleVolumeTempURIJSON + + ",\"storagePoolUuid\":\"" + testLocalStoreUUID + + "\"," + + "\"type\":\"ROOT\",\"id\":9,\"size\":0}}"; + + HypervResourceController rsrcServer = new HypervResourceController(); + dynamic jsonDestoryCmd = JsonConvert.DeserializeObject(destoryCmd); + + // Act + dynamic destoryAns = rsrcServer.DestroyCommand(jsonDestoryCmd); + + // Assert + JObject ansAsProperty2 = destoryAns[0]; + dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.Answer); + String path = jsonDestoryCmd.volume.path; + Assert.True((bool)ans.result, "DestroyCommand did not succeed " + ans.details); + Assert.True(!File.Exists(path), "Failed to delete file " + path); + } + + [Fact(Skip="these are functional tests")] + public void TestCreateCommand() + { + // TODO: Need sample to update the test. + // Arrange + String createCmd = "{\"volId\":10,\"pool\":{\"id\":201,\"uuid\":\"" + testLocalStoreUUID + "\",\"host\":\"" + HypervResourceController.config.StorageIpAddress + "\"" + + ",\"path\":" + testLocalStorePathJSON + ",\"port\":0,\"type\":\"Filesystem\"},\"diskCharacteristics\":{\"size\":0," + + "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-9\",\"useLocalStorage\":true,\"recreatable\":true,\"diskOfferingId\":11," + + "\"volumeId\":10,\"hyperType\":\"Hyperv\"},\"templateUrl\":" + testSampleTemplateURLJSON + ",\"contextMap\":{},\"wait\":0}"; + dynamic jsonCreateCmd = JsonConvert.DeserializeObject(createCmd); + HypervResourceController rsrcServer = new HypervResourceController(); + + Assert.True(Directory.Exists(testLocalStorePath)); + string filePath = Path.Combine(testLocalStorePath, (string)JsonConvert.DeserializeObject(testSampleTemplateURLJSON)); + Assert.True(File.Exists(filePath), "The template we make volumes from is missing from path " + filePath); + int fileCount = Directory.GetFiles(testLocalStorePath).Length; + s_logger.Debug(" test local store has " + fileCount + "files"); + + // Act + // Test requires there to be a template at the tempalteUrl, which is its location in the local file system. + dynamic jsonResult = rsrcServer.CreateCommand(jsonCreateCmd); + + JObject ansAsProperty2 = jsonResult[0]; + dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.CreateAnswer); + Assert.NotNull(ans); + Assert.True((bool)ans.result, "Failed to CreateCommand due to " + (string)ans.result); + Assert.Equal(Directory.GetFiles(testLocalStorePath).Length, fileCount + 1); + FileInfo newFile = new FileInfo((string)ans.volume.path); + Assert.True(newFile.Length > 0, "The new file should have a size greater than zero"); + newFile.Delete(); + } + + /// + /// Possible additional tests: place an ISO in the drive + /// + [Fact(Skip="these are functional tests")] + public void TestStartStopCommand() + { + string vmName = TestStartCommand(); + TestStopCommand(vmName); + } + + public static String getSamplePrimaryDataStoreInfo() + { + String samplePrimaryDataStoreInfo = + "{\"org.apache.cloudstack.storage.to.PrimaryDataStoreTO\":" + + "{\"uuid\":\"" + testLocalStoreUUID + "\"," + + "\"id\":201," + + "\"host\":\"" + testPrimaryDataStoreHost + "\"," + + "\"type\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO + "\"poolType\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO + "\"path\":" + testLocalStorePathJSON + "," + + "\"port\":0}" + + "}"; + return samplePrimaryDataStoreInfo; + } + + public static String getSampleVolumeObjectTO() + { + String sampleVolumeObjectTO = + "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + + "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + + "\"volumeType\":\"ROOT\"," + + "\"format\":\"VHDX\"," + + "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"" + testSampleVolumeTempUUIDNoExt + "\"," + + "\"size\":52428800," + + "\"volumeId\":10," + + // "\"vmName\":\"i-3-5-VM\"," + // TODO: do we have to fill in the vmName? + "\"accountId\":3,\"id\":10}" + + "}"; // end of destTO + return sampleVolumeObjectTO; + } + + public static String getSampleStartCommand() + { + String sample = "{\"vm\":{\"id\":17,\"name\":\"i-2-17-VM\",\"type\":\"User\",\"cpus\":1,\"speed\":500," + + "\"minRam\":536870912,\"maxRam\":536870912,\"arch\":\"x86_64\"," + + "\"os\":\"CentOS 6.0 (64-bit)\",\"bootArgs\":\"\",\"rebootOnCrash\":false," + + "\"enableHA\":false,\"limitCpuUse\":false,\"vncPassword\":\"31f82f29aff646eb\"," + + "\"params\":{},\"uuid\":\"8b030b6a-0243-440a-8cc5-45d08815ca11\"" + + ",\"disks\":[" + + "{\"data\":" + getSampleVolumeObjectTO() + ",\"diskSeq\":0,\"type\":\"ROOT\"}," + + "{\"diskSeq\":1,\"type\":\"ISO\"}" + + "]," + + "\"nics\":[" + + "{\"deviceId\":0,\"networkRateMbps\":100,\"defaultNic\":true,\"uuid\":\"99cb4813-23af-428c-a87a-2d1899be4f4b\"," + + "\"ip\":\"10.1.1.67\",\"netmask\":\"255.255.255.0\",\"gateway\":\"10.1.1.1\"," + + "\"mac\":\"02:00:51:2c:00:0e\",\"dns1\":\"4.4.4.4\",\"broadcastType\":\"Vlan\",\"type\":\"Guest\"," + + "\"broadcastUri\":\"vlan://261\",\"isolationUri\":\"vlan://261\",\"isSecurityGroupEnabled\":false}" + + "]},\"contextMap\":{},\"wait\":0}"; + return sample; + } + + + [Fact(Skip="these are functional tests")] + public void TestCopyCommandFromCifs() + { + // Arrange + string sampleCopyCommandForTemplateDownload = + #region string_literal + // org.apache.cloudstack.storage.command.CopyCommand + "{\"srcTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{\"path\":\"" + testCifsPath + "\"," + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHDX\"," + + "\"accountId\":2," + + "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + + "\"hvm\":true," + + "\"displayText\":\"OS031\"," + + "\"imageDataStore\":" + + "{\"com.cloud.agent.api.to.NfsTO\":" + + "{\"_url\":\"" + testCifsUrl + "\"," + // Unique item here + "\"_role\":\"Image\"}" + + "}," + // end of imageDataStore + "\"hypervisorType\":\"Hyperv\"," + + "\"name\":\"" + testS3TemplateName + "\"}" + + "}," + // end of srcTO + "\"destTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{" + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHDX\"," + + "\"accountId\":2," + + "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + + "\"hvm\":true," + + "\"displayText\":\"Test of CIFS Download\"," + + "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + // end of imageDataStore + "\"name\":\"" + testS3TemplateName + "\"," + + "\"hypervisorType\":\"Hyperv\"}" + + "}," +// end of destTO + "\"wait\":10800}"; // end of CopyCommand + #endregion + + HypervResourceController rsrcServer; + dynamic jsonDownloadCopyCmd; + string dwnldDest; + dynamic jsonCloneCopyCmd; + string newVolName; + CopyCommandTestSetupCifs(null, sampleCopyCommandForTemplateDownload, out rsrcServer, out jsonDownloadCopyCmd, out dwnldDest, out jsonCloneCopyCmd, out newVolName); + + // Act & Assert + DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); + + // Repeat to verify ability to detect existing file. + DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); + + File.Delete(dwnldDest); + } + + [Fact(Skip="these are functional tests")] + public void TestCopyCommand() + { + // Arrange + string sampleCopyCommandToCreateVolumeFromTemplate = + #region string_literal + // org.apache.cloudstack.storage.command.CopyCommand + "{\"srcTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{" + + "\"origUrl\":\"http://people.apache.org/~bhaisaab/vms/ttylinux_pv.vhd\"," + + "\"uuid\":\"9873f1c0-bdcc-11e2-8baa-ea85dab5fcd0\"," + + "\"id\":5," + + "\"format\":\"VHDX\"," + + "\"accountId\":1," + + "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + + "\"hvm\":false," + + "\"displayText\":\"tiny Linux\"," + + "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"" + testS3TemplateName + "\"}" + + "}," + // end of srcTO + "\"destTO\":" + + "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + + "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + + "\"volumeType\":\"ROOT\"," + + "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"ROOT-5\"," + + "\"size\":52428800," + + "\"volumeId\":10," + + "\"vmName\":\"i-3-5-VM\"," + + "\"accountId\":3," + + "\"id\":10 }" + + "}," + // end of destTO + "\"wait\":0}"; // end of Copy Command + #endregion + //"name":"ROOT-8","size":140616708,"volumeId":8,"vmName":"s-8-VM","accountId":1,"id":8}},"contextMap":{},"wait":0} + + string sampleCopyCommandForTemplateDownload = + #region string_literal + // org.apache.cloudstack.storage.command.CopyCommand + "{\"srcTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{\"path\":\"" + testS3TemplateName + ".vhdx" + "\"," + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHDX\"," + + "\"accountId\":2," + + "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + + "\"hvm\":true," + + "\"displayText\":\"OS031\"," + + "\"imageDataStore\":" + + "{\"com.cloud.agent.api.to.S3TO\":" + + "{\"id\":1," + + "\"uuid\":\"95a64c8f-2128-4502-b5b4-0d7aa77406d2\"," + + "\"accessKey\":\"" + AgentSettings.Default.testS3AccessKey + "\"," + + "\"secretKey\":\"" + AgentSettings.Default.testS3SecretKey + "\"," + + "\"endPoint\":\"" + AgentSettings.Default.testS3Endpoint + "\"," + + "\"bucketName\":\"" + AgentSettings.Default.testS3Bucket + "\"," + + "\"httpsFlag\":false," + + "\"created\":\"May 19, 2013 4:17:25 PM\"}" + + "}," + // end of imageDataStore + "\"name\":\"" + testS3TemplateName + "\"}" + + "}," + // end of srcTO + "\"destTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{" + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHDX\"," + + "\"accountId\":2," + + "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + + "\"hvm\":true," + + "\"displayText\":\"OS031\"," + + "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + // end of imageDataStore + "\"name\":\"" + testS3TemplateName + "\"}" + + "}," +// end of destTO + "\"wait\":10800}"; // end of CopyCommand + #endregion + + HypervResourceController rsrcServer; + dynamic jsonDownloadCopyCmd; + string dwnldDest; + dynamic jsonCloneCopyCmd; + string newVolName; + CopyCommandTestSetup(sampleCopyCommandToCreateVolumeFromTemplate, sampleCopyCommandForTemplateDownload, out rsrcServer, out jsonDownloadCopyCmd, out dwnldDest, out jsonCloneCopyCmd, out newVolName); + + // Act & Assert + DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); + CreateVolumeFromTemplate(rsrcServer, jsonCloneCopyCmd, newVolName); + + // Repeat to verify ability to detect existing file. + DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); + + File.Delete(dwnldDest); + File.Delete(newVolName); + } + + private static void CreateVolumeFromTemplate(HypervResourceController rsrcServer, dynamic jsonCloneCopyCmd, string newVolName) + { + dynamic copyResult = rsrcServer.CopyCommand(jsonCloneCopyCmd); + + // Assert + Assert.NotNull(copyResult[0][CloudStackTypes.CopyCmdAnswer]); + Assert.True((bool)copyResult[0][CloudStackTypes.CopyCmdAnswer].result, "CopyCommand did not succeed " + copyResult[0][CloudStackTypes.CopyCmdAnswer].details); + Assert.True(File.Exists(newVolName), "CopyCommand failed to generate " + newVolName); + } + + private static void DownloadTemplateToPrimaryStorage(HypervResourceController rsrcServer, dynamic jsonDownloadCopyCmd, string dwnldDest) + { + dynamic dwnldResult = rsrcServer.CopyCommand(jsonDownloadCopyCmd); + + // Assert + Assert.NotNull(dwnldResult[0][CloudStackTypes.CopyCmdAnswer]); + Assert.True((bool)dwnldResult[0][CloudStackTypes.CopyCmdAnswer].result, "CopyCommand did not succeed " + dwnldResult[0][CloudStackTypes.CopyCmdAnswer].details); + Assert.True(File.Exists(dwnldDest), "CopyCommand failed to generate " + dwnldDest); + } + + [Fact(Skip="these are functional tests")] + public void TestCopyCommandBz2Img() + { + // Arrange + string sampleCopyCommandToCreateVolumeFromTemplate = + #region string_literal + // org.apache.cloudstack.storage.command.CopyCommand + "{\"srcTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{" + + "\"origUrl\":\"http://people.apache.org/~bhaisaab/vms/ttylinux_pv.vhd\"," + + "\"uuid\":\"9873f1c0-bdcc-11e2-8baa-ea85dab5fcd0\"," + + "\"id\":5," + + "\"format\":\"VHD\"," + + "\"accountId\":1," + + "\"checksum\":\"f613f38c96bf039f2e5cbf92fa8ad4f8\"," + + "\"hvm\":false," + + "\"displayText\":\"tiny Linux\"," + + "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"" + testSystemVMTemplateNameNoExt + "\"}" + + "}," + // end of srcTO + "\"destTO\":" + + "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + + "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + + "\"volumeType\":\"ROOT\"," + + "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"ROOT-5\"," + + "\"size\":52428800," + + "\"volumeId\":10," + + "\"vmName\":\"i-3-5-VM\"," + + "\"accountId\":1," + + "\"id\":10}" + + "}," + // end of destTO + "\"wait\":0}"; // end of Copy Command + #endregion + + string sampleCopyCommandForTemplateDownload = + #region string_literal + // org.apache.cloudstack.storage.command.CopyCommand + "{\"srcTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{\"path\":\"" + testSystemVMTemplateName + "\"," + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHD\"," + + "\"accountId\":1," + + "\"checksum\": \"f613f38c96bf039f2e5cbf92fa8ad4f8\"," + + "\"hvm\":true," + + "\"displayText\":\"OS031\"," + + "\"imageDataStore\":" + + "{\"com.cloud.agent.api.to.S3TO\":" + + "{\"id\":1," + + "\"uuid\":\"95a64c8f-2128-4502-b5b4-0d7aa77406d2\"," + + "\"accessKey\":\"" + AgentSettings.Default.testS3AccessKey + "\"," + + "\"secretKey\":\"" + AgentSettings.Default.testS3SecretKey + "\"," + + "\"endPoint\":\"" + AgentSettings.Default.testS3Endpoint + "\"," + + "\"bucketName\":\"" + AgentSettings.Default.testS3Bucket + "\"," + + "\"httpsFlag\":false," + + "\"created\":\"May 19, 2013 4:17:25 PM\"}" + + "}," + // end of imageDataStore + "\"name\":\"" + testSystemVMTemplateNameNoExt + "\"}" + + "}," + // end of srcTO + "\"destTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{" + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHD\"," + + "\"accountId\":1," + + "\"checksum\": \"f613f38c96bf039f2e5cbf92fa8ad4f8\"," + + "\"hvm\":true," + + "\"displayText\":\"OS031\"," + + "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + // end of imageDataStore + "\"name\":\"" + testSystemVMTemplateNameNoExt + "\"}" + + "}," +// end of destTO + "\"wait\":10800}"; // end of CopyCommand + #endregion + + HypervResourceController rsrcServer; + dynamic jsonDownloadCopyCmd; + string dwnldDest; + dynamic jsonCloneCopyCmd; + string newVolName; + CopyCommandTestSetup(sampleCopyCommandToCreateVolumeFromTemplate, sampleCopyCommandForTemplateDownload, out rsrcServer, out jsonDownloadCopyCmd, out dwnldDest, out jsonCloneCopyCmd, out newVolName); + + // Act & Assert + DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); + CreateVolumeFromTemplate(rsrcServer, jsonCloneCopyCmd, newVolName); + + File.Delete(dwnldDest); + File.Delete(newVolName); + } + + private static void CopyCommandTestSetup(string sampleCopyCommandToCreateVolumeFromTemplate, string sampleCopyCommandForTemplateDownload, out HypervResourceController rsrcServer, out dynamic jsonDownloadCopyCmd, out string dwnldDest, out dynamic jsonCloneCopyCmd, out string newVolName) + { + rsrcServer = new HypervResourceController(); + jsonDownloadCopyCmd = JsonConvert.DeserializeObject(sampleCopyCommandForTemplateDownload); + TemplateObjectTO dwnldTemplate = TemplateObjectTO.ParseJson(jsonDownloadCopyCmd.destTO); + dwnldDest = dwnldTemplate.FullFileName; + + jsonCloneCopyCmd = JsonConvert.DeserializeObject(sampleCopyCommandToCreateVolumeFromTemplate); + VolumeObjectTO newVol = VolumeObjectTO.ParseJson(jsonCloneCopyCmd.destTO); + newVol.format = dwnldTemplate.format; + newVolName = dwnldTemplate.FullFileName; + + if (File.Exists(dwnldDest)) + { + File.Delete(dwnldDest); + } + if (File.Exists(newVolName)) + { + File.Delete(newVolName); + } + } + + private static void CopyCommandTestSetupCifs(string sampleCopyCommandToCreateVolumeFromTemplate, string sampleCopyCommandForTemplateDownload, out HypervResourceController rsrcServer, out dynamic jsonDownloadCopyCmd, out string dwnldDest, out dynamic jsonCloneCopyCmd, out string newVolName) + { + rsrcServer = new HypervResourceController(); + jsonDownloadCopyCmd = JsonConvert.DeserializeObject(sampleCopyCommandForTemplateDownload); + TemplateObjectTO dwnldTemplate = TemplateObjectTO.ParseJson(jsonDownloadCopyCmd.destTO); + dwnldDest = dwnldTemplate.FullFileName; + + if (File.Exists(dwnldDest)) + { + File.Delete(dwnldDest); + } + newVolName = null; + jsonCloneCopyCmd = null; + } + + [Fact(Skip="these are functional tests")] + public void TestModifyStoragePoolCommand() + { + // Create dummy folder + String folderName = Path.Combine(".", "Dummy"); + if (!Directory.Exists(folderName)) + { + Directory.CreateDirectory(folderName); + } + + var pool = new + { // From java class StorageFilerTO + type = Enum.GetName(typeof(StoragePoolType), StoragePoolType.Filesystem), + host = "127.0.0.1", + port = -1, + path = folderName, + uuid = Guid.NewGuid().ToString(), + userInfo = string.Empty // Used in future to hold credential + }; + + var cmd = new + { + add = true, + pool = pool, + localPath = folderName + }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.ModifyStoragePoolCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.ModifyStoragePoolAnswer]; + Assert.True((bool)ans.result, (string)ans.details); // always succeeds + + // Clean up + var cmd2 = new + { + pool = pool, + localPath = folderName + }; + JToken tok2 = JToken.FromObject(cmd); + + // Act + dynamic jsonResult2 = controller.DeleteStoragePoolCommand(tok2); + + // Assert + dynamic ans2 = jsonResult2[0][CloudStackTypes.Answer]; + Assert.True((bool)ans2.result, (string)ans2.details); // always succeeds + } + + [Fact(Skip="these are functional tests")] + public void CreateStoragePoolCommand() + { + var cmd = new { localPath = "NULL" }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.CreateStoragePoolCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.Answer]; + Assert.True((bool)ans.result, (string)ans.details); // always succeeds + } + + [Fact(Skip="these are functional tests")] + public void MaintainCommand() + { + // Omit HostEnvironment object, as this is a series of settings currently not used. + var cmd = new { }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.MaintainCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.MaintainAnswer]; + Assert.True((bool)ans.result, (string)ans.details); // always succeeds + } + + [Fact(Skip="these are functional tests")] + public void SetupCommand() + { + // Omit HostEnvironment object, as this is a series of settings currently not used. + var cmd = new { multipath = false, needSetup = true }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.SetupCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.SetupAnswer]; + Assert.True((bool)ans.result, (string)ans.details); // always succeeds + } + + [Fact(Skip="these are functional tests")] + public void TestPassingUserdataToVm() + { + // Sample data + String key = "cloudstack-vm-userdata"; + String value = "username=root;password=1pass@word1"; + + // Find the VM + List vmNames = wmiCallsV2.GetVmElementNames(); + + // Get associated WMI object + var vm = wmiCallsV2.GetComputerSystem(AgentSettings.Default.testKvpVmName); + + // Get existing KVP + var vmSettings = wmiCallsV2.GetVmSettings(vm); + var kvpInfo = wmiCallsV2.GetKvpSettings(vmSettings); + + // HostExchangesItems are embedded objects in the sense that the object value is stored and not a reference to the object. + string[] kvpProps = kvpInfo.HostExchangeItems; + + // If the value already exists, delete it + foreach (var item in kvpProps) + { + String wmiObjectXml = item; + String existingKey; + String existingValue; + ParseKVP(wmiObjectXml, out existingKey, out existingValue); + + if (existingKey == key) + { + wmiCallsV2.DeleteHostKvpItem(vm, existingKey); + break; + } + } + + // Add new user data + wmiCallsV2.AddUserData(vm, value); + + // Verify key added to subsystem + kvpInfo = wmiCallsV2.GetKvpSettings(vmSettings); + + // HostExchangesItems are embedded objects in the sense that the object value is stored and not a reference to the object. + kvpProps = kvpInfo.HostExchangeItems; + + // If the value already exists, delete it + bool userDataInPlace = false; + foreach (var item in kvpProps) + { + String wmiObjectXml = item; + String existingKey; + String existingValue; + ParseKVP(wmiObjectXml, out existingKey, out existingValue); + + if (existingKey == key && existingValue == value) + { +// wmiCallsV2.DeleteHostKvpItem(vm, existingKey); + userDataInPlace = true; + break; + } + } + + Assert.True(userDataInPlace, "User data key / value did no save properly"); + } + + private static void ParseKVP(String wmiObjectXml, out String existingKey, out String existingValue) + { + // Reference: http://blogs.msdn.com/b/virtual_pc_guy/archive/2008/12/05/enumerating-parent-kvp-data.aspx + + // Create XML parser + var xmlDoc = new XmlDocument(); + + // Load WMI object + xmlDoc.LoadXml(wmiObjectXml); + + // Use xpath to get name and value + var namePropXpath = "/INSTANCE/PROPERTY[@NAME='Name']/VALUE"; + var nameNode = xmlDoc.SelectSingleNode(namePropXpath); + existingKey = nameNode.InnerText; + var dataPropXpath = "/INSTANCE/PROPERTY[@NAME='Data']/VALUE"; + var dataNode = xmlDoc.SelectSingleNode(dataPropXpath); + existingValue = dataNode.InnerText; + } + + [Fact(Skip="these are functional tests")] + public void GetVmStatsCommandFail() + { + // Use WMI to find existing VMs + List vmNames = new List(); + vmNames.Add("FakeVM"); + + var cmd = new + { + hostGuid = "FAKEguid", + hostName = AgentSettings.Default.host, + vmNames = vmNames + }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.GetVmStatsCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.GetVmStatsAnswer]; + Assert.True((bool)ans.result, (string)ans.details); // always succeeds, fake VM means no answer for the named VM + } + + [Fact(Skip="these are functional tests")] + public void GetVmStatsCommand() + { + // Use WMI to find existing VMs + List vmNames = wmiCallsV2.GetVmElementNames(); + + var cmd = new + { + hostGuid = "FAKEguid", + hostName = AgentSettings.Default.host, + vmNames = vmNames + }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.GetVmStatsCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.GetVmStatsAnswer]; + Assert.True((bool)ans.result, (string)ans.details); + } + + [Fact(Skip="these are functional tests")] + public void GetStorageStatsCommand() + { + // TODO: Update sample data to unsure it is using correct info. + String sample = String.Format( + #region string_literal +"{{\"" + + "id\":{0}," + + "\"localPath\":{1}," + + "\"pooltype\":\"Filesystem\"," + + "\"contextMap\":{{}}," + + "\"wait\":0}}", + JsonConvert.SerializeObject(AgentSettings.Default.testLocalStoreUUID), + JsonConvert.SerializeObject(AgentSettings.Default.testLocalStorePath) + ); + #endregion + var cmd = JsonConvert.DeserializeObject(sample); + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.GetStorageStatsCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.GetStorageStatsAnswer]; + Assert.True((bool)ans.result, (string)ans.details); + Assert.True((long)ans.used <= (long)ans.capacity); // TODO: verify that capacity is indeed capacity and not used. + } + + // TODO: can we speed up this command? The logic takes over a second. + [Fact(Skip="these are functional tests")] + public void GetHostStatsCommand() + { + // Arrange + long hostIdVal = 5; + HypervResourceController controller = new HypervResourceController(); + string sample = string.Format( + #region string_literal +"{{" + + "\"hostGuid\":\"B4AE5970-FCBF-4780-9F8A-2D2E04FECC34-HypervResource\"," + + "\"hostName\":\"CC-SVR11\"," + + "\"hostId\":{0}," + + "\"contextMap\":{{}}," + + "\"wait\":0}}", + JsonConvert.SerializeObject(hostIdVal)); + #endregion + var cmd = JsonConvert.DeserializeObject(sample); + JToken tok = JToken.FromObject(cmd); + + // Act + dynamic jsonResult = controller.GetHostStatsCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.GetHostStatsAnswer]; + Assert.True((bool)ans.result); + Assert.True(hostIdVal == (long)ans.hostStats.hostId); + Assert.True(0.0 < (double)ans.hostStats.totalMemoryKBs); + Assert.True(0.0 < (double)ans.hostStats.freeMemoryKBs); + Assert.True(0.0 <= (double)ans.hostStats.networkReadKBs); + Assert.True(0.0 <= (double)ans.hostStats.networkWriteKBs); + Assert.True(0.0 <= (double)ans.hostStats.cpuUtilization); + Assert.True(100.0 >= (double)ans.hostStats.cpuUtilization); + Assert.True("host".Equals((string)ans.hostStats.entityType)); + Assert.True(String.IsNullOrEmpty((string)ans.details)); + } + + [Fact(Skip="these are functional tests")] + public void GetHostStatsCommandFail() + { + // Arrange + HypervResourceController controller = new HypervResourceController(); + var cmd = new { GetHostStatsCommand = new { hostId = "badvalueType" } }; + JToken tokFail = JToken.FromObject(cmd); + + // Act + dynamic jsonResult = controller.GetHostStatsCommand(tokFail); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.GetHostStatsAnswer]; + Assert.False((bool)ans.result); + Assert.Null((string)ans.hostStats); + Assert.NotNull(ans.details); + } + + [Fact(Skip="these are functional tests")] + public void TestStartupCommand() + { + // Arrange + HypervResourceController controller = new HypervResourceController(); + String sampleStartupRoutingCommand = + #region string_literal + "[{\"" + CloudStackTypes.StartupRoutingCommand + "\":{" + + "\"cpus\":0," + + "\"speed\":0," + + "\"memory\":0," + + "\"dom0MinMemory\":0," + + "\"poolSync\":false," + + "\"vms\":{}," + + "\"hypervisorType\":\"Hyperv\"," + + "\"hostDetails\":{" + + "\"com.cloud.network.Networks.RouterPrivateIpStrategy\":\"HostLocal\"" + + "}," + + "\"type\":\"Routing\"," + + "\"dataCenter\":\"1\"," + + "\"pod\":\"1\"," + + "\"cluster\":\"1\"," + + "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + + "\"name\":\"localhost\"," + + "\"version\":\"4.2.0\"," + + "\"privateIpAddress\":\"1\"," + + "\"storageIpAddress\":\"1\"," + + "\"contextMap\":{}," + + "\"wait\":0}}]"; + #endregion + + uint cores; + uint mhz; + wmiCallsV2.GetProcessorResources(out cores, out mhz); + ulong memory_mb; + ulong freememory; + wmiCallsV2.GetMemoryResources(out memory_mb, out freememory); + memory_mb *= 1024; + long capacityBytes; + long availableBytes; + HypervResourceController.GetCapacityForLocalPath(wmiCallsV2.GetDefaultVirtualDiskFolder(), + out capacityBytes, out availableBytes); + var DefaultVirtualDiskFolder = JsonConvert.SerializeObject(wmiCallsV2.GetDefaultVirtualDiskFolder()); + string expected = + #region string_literal + "[{\"" + CloudStackTypes.StartupRoutingCommand + "\":{" + + "\"cpus\":" + cores + "," + + "\"speed\":" + mhz + "," + + "\"memory\":" + memory_mb + "," + + "\"dom0MinMemory\":" + (AgentSettings.Default.dom0MinMemory * 1024 * 1024) + "," + + "\"poolSync\":false," + + "\"vms\":{}," + + "\"hypervisorType\":\"Hyperv\"," + + "\"hostDetails\":{" + + "\"com.cloud.network.Networks.RouterPrivateIpStrategy\":\"HostLocal\"" + + "}," + + "\"type\":\"Routing\"," + + "\"dataCenter\":\"1\"," + + "\"pod\":\"1\"," + + "\"cluster\":\"1\"," + + "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + + "\"name\":\"localhost\"," + + "\"version\":\"4.2.0\"," + + "\"privateIpAddress\":\"" + AgentSettings.Default.private_ip_address + "\"," + + "\"storageIpAddress\":\"" + AgentSettings.Default.private_ip_address + "\"," + + "\"contextMap\":{}," + + "\"wait\":0," + + "\"privateNetmask\":\"" + AgentSettings.Default.private_ip_netmask + "\"," + + "\"privateMacAddress\":\"" + AgentSettings.Default.private_mac_address + "\"," + + "\"storageNetmask\":\"" + AgentSettings.Default.private_ip_netmask + "\"," + + "\"storageMacAddress\":\"" + AgentSettings.Default.private_mac_address + "\"," + + "\"gatewayIpAddress\":\"" + AgentSettings.Default.gateway_ip_address + "\"" + + ",\"caps\":\"hvm\"" + + "}}," + + "{\"com.cloud.agent.api.StartupStorageCommand\":{" + + "\"poolInfo\":{" + + "\"uuid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + + "\"host\":\"" + AgentSettings.Default.private_ip_address + "\"," + + "\"localPath\":" + DefaultVirtualDiskFolder + "," + + "\"hostPath\":" + DefaultVirtualDiskFolder + "," + + "\"poolType\":\"Filesystem\"," + + "\"capacityBytes\":" + capacityBytes + "," + + "\"availableBytes\":" + availableBytes + "," + + "\"details\":null" + + "}," + + "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + + "\"dataCenter\":\"1\"," + + "\"resourceType\":\"STORAGE_POOL\"" + + "}}]"; + #endregion + + dynamic jsonArray = JsonConvert.DeserializeObject(sampleStartupRoutingCommand); + + // Act + dynamic jsonResult = controller.StartupCommand(jsonArray); + + // Assert + string actual = JsonConvert.SerializeObject(jsonResult); + Assert.Equal(expected, actual); + } + + + private static string TestStartCommand() + { + // Arrange + HypervResourceController rsrcServer = new HypervResourceController(); + String sample = getSampleStartCommand(); + + + dynamic jsonStartCmd = JsonConvert.DeserializeObject(sample); + + // Act + dynamic startAns = rsrcServer.StartCommand(jsonStartCmd); + + // Assert + Assert.NotNull(startAns[0][CloudStackTypes.StartAnswer]); + Assert.True((bool)startAns[0][CloudStackTypes.StartAnswer].result, "StartCommand did not succeed " + startAns[0][CloudStackTypes.StartAnswer].details); + string vmCmdName = jsonStartCmd.vm.name.Value; + var vm = wmiCallsV2.GetComputerSystem(vmCmdName); + var vmSettings = wmiCallsV2.GetVmSettings(vm); + var memSettings = wmiCallsV2.GetMemSettings(vmSettings); + var procSettings = wmiCallsV2.GetProcSettings(vmSettings); + dynamic jsonObj = JsonConvert.DeserializeObject(sample); + var vmInfo = jsonObj.vm; + string vmName = vmInfo.name; + var nicInfo = vmInfo.nics; + int vcpus = vmInfo.cpus; + int memSize = vmInfo.maxRam / 1048576; + Assert.True((long)memSettings.VirtualQuantity == memSize); + Assert.True((long)memSettings.Reservation == memSize); + Assert.True((long)memSettings.Limit == memSize); + Assert.True((int)procSettings.VirtualQuantity == vcpus); + Assert.True((int)procSettings.Reservation == vcpus); + Assert.True((int)procSettings.Limit == 100000); + + // examine NIC for correctness + var nicSettingsViaVm = wmiCallsV2.GetEthernetPortSettings(vm); + Assert.True(nicSettingsViaVm.Length > 0, "Should be at least one ethernet port on VM"); + string expectedMac = (string)jsonStartCmd.vm.nics[0].mac; + string strippedExpectedMac = expectedMac.Replace(":", string.Empty); + Assert.Equal(nicSettingsViaVm[0].Address.ToLower(), strippedExpectedMac.ToLower()); + + // Assert switchport has correct VLAN + var ethernetConnections = wmiCallsV2.GetEthernetConnections(vm); + var vlanSettings = wmiCallsV2.GetVlanSettings(ethernetConnections[0]); + string isolationUri = (string)jsonStartCmd.vm.nics[0].isolationUri; + string vlan = isolationUri.Replace("vlan://", string.Empty); + Assert.Equal(vlanSettings.AccessVlanId.ToString(), vlan); + + return vmName; + } + + private static void TestStopCommand(string vmName) + { + // Arrange + HypervResourceController rsrcServer = new HypervResourceController(); + String sampleStop = "{\"isProxy\":false,\"vmName\":\"i-2-17-VM\",\"contextMap\":{},\"wait\":0}"; + dynamic jsonStopCmd = JsonConvert.DeserializeObject(sampleStop); + + // Act + dynamic stopAns = rsrcServer.StopCommand(jsonStopCmd); + + // Assert VM is gone! + Assert.NotNull(stopAns[0][CloudStackTypes.StopAnswer]); + Assert.True((bool)stopAns[0][CloudStackTypes.StopAnswer].result, "StopCommand did not succeed " + stopAns[0][CloudStackTypes.StopAnswer].details); + var finalVm = wmiCallsV2.GetComputerSystem(vmName); + Assert.True(wmiCallsV2.GetComputerSystem(vmName) == null); + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/Properties/AssemblyInfo.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..c8820467b3c --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/Properties/AssemblyInfo.cs @@ -0,0 +1,52 @@ +// 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.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ServerResource.Tests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ServerResource.Tests")] +[assembly: AssemblyCopyright("Copyright © 2013")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("727beb1c-6e7c-49b2-8fbd-f03dbe481b08")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/ServerResource.Tests.csproj b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/ServerResource.Tests.csproj new file mode 100644 index 00000000000..eec595e65ad --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/ServerResource.Tests.csproj @@ -0,0 +1,135 @@ + + + + Debug + AnyCPU + + + 2.0 + {925FD1DE-6211-4E10-9949-3751B8ABDF59} + Library + Properties + ServerResource.Tests + ServerResource.Tests + v4.5 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + ..\ + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\NoUnitTestsDebug\ + DEBUG;TRACE + full + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + bin\NoUnitTests\ + TRACE + true + pdbonly + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\AWSSDK.1.5.23.0\lib\AWSSDK.dll + + + ..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll + + + ..\packages\log4net.2.0.0\lib\net40-full\log4net.dll + + + + ..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll + + + ..\packages\NSubstitute.1.6.1.0\lib\NET40\NSubstitute.dll + + + + + + + + + + + + + + + + + + + + ..\packages\xunit.1.9.2\lib\net20\xunit.dll + + + + + + + + + + Designer + + + + + Designer + + + + + {9060b539-62d0-4e71-a6c6-5944828774e9} + AgentShell + + + {c963dfff-65ba-4e71-ada5-526a4da4e0b2} + HypervResource + + + {db824727-bdc3-437c-a364-7a811d8a160f} + WmiWrappers + + + + + + + + + + diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/packages.config b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/packages.config new file mode 100644 index 00000000000..4c538e4872b --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/packages.config @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.sln b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.sln new file mode 100644 index 00000000000..fa0eb3001db --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.sln @@ -0,0 +1,61 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServerResource.Tests", "ServerResource.Tests\ServerResource.Tests.csproj", "{925FD1DE-6211-4E10-9949-3751B8ABDF59}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgentShell", "AgentShell\AgentShell.csproj", "{9060B539-62D0-4E71-A6C6-5944828774E9}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WmiWrappers", "WmiWrappers\WmiWrappers.csproj", "{DB824727-BDC3-437C-A364-7A811D8A160F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HypervResource", "HypervResource\HypervResource.csproj", "{C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{3481E04E-4BB9-4E0B-94A9-DB70A4F4D218}" + ProjectSection(SolutionItems) = preProject + .nuget\NuGet.Config = .nuget\NuGet.Config + .nuget\NuGet.exe = .nuget\NuGet.exe + .nuget\NuGet.targets = .nuget\NuGet.targets + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + NoUnitTests|Any CPU = NoUnitTests|Any CPU + NoUnitTestsDebug|Any CPU = NoUnitTestsDebug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {925FD1DE-6211-4E10-9949-3751B8ABDF59}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {925FD1DE-6211-4E10-9949-3751B8ABDF59}.Debug|Any CPU.Build.0 = Debug|Any CPU + {925FD1DE-6211-4E10-9949-3751B8ABDF59}.NoUnitTests|Any CPU.ActiveCfg = NoUnitTests|Any CPU + {925FD1DE-6211-4E10-9949-3751B8ABDF59}.NoUnitTestsDebug|Any CPU.ActiveCfg = NoUnitTestsDebug|Any CPU + {925FD1DE-6211-4E10-9949-3751B8ABDF59}.Release|Any CPU.ActiveCfg = Release|Any CPU + {925FD1DE-6211-4E10-9949-3751B8ABDF59}.Release|Any CPU.Build.0 = Release|Any CPU + {9060B539-62D0-4E71-A6C6-5944828774E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9060B539-62D0-4E71-A6C6-5944828774E9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9060B539-62D0-4E71-A6C6-5944828774E9}.NoUnitTests|Any CPU.ActiveCfg = NoUnitTests|Any CPU + {9060B539-62D0-4E71-A6C6-5944828774E9}.NoUnitTests|Any CPU.Build.0 = NoUnitTests|Any CPU + {9060B539-62D0-4E71-A6C6-5944828774E9}.NoUnitTestsDebug|Any CPU.ActiveCfg = NoUnitTestsDebug|Any CPU + {9060B539-62D0-4E71-A6C6-5944828774E9}.NoUnitTestsDebug|Any CPU.Build.0 = NoUnitTestsDebug|Any CPU + {9060B539-62D0-4E71-A6C6-5944828774E9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9060B539-62D0-4E71-A6C6-5944828774E9}.Release|Any CPU.Build.0 = Release|Any CPU + {DB824727-BDC3-437C-A364-7A811D8A160F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DB824727-BDC3-437C-A364-7A811D8A160F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DB824727-BDC3-437C-A364-7A811D8A160F}.NoUnitTests|Any CPU.ActiveCfg = NoUnitTests|Any CPU + {DB824727-BDC3-437C-A364-7A811D8A160F}.NoUnitTests|Any CPU.Build.0 = NoUnitTests|Any CPU + {DB824727-BDC3-437C-A364-7A811D8A160F}.NoUnitTestsDebug|Any CPU.ActiveCfg = NoUnitTestsDebug|Any CPU + {DB824727-BDC3-437C-A364-7A811D8A160F}.NoUnitTestsDebug|Any CPU.Build.0 = NoUnitTestsDebug|Any CPU + {DB824727-BDC3-437C-A364-7A811D8A160F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DB824727-BDC3-437C-A364-7A811D8A160F}.Release|Any CPU.Build.0 = Release|Any CPU + {C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}.NoUnitTests|Any CPU.ActiveCfg = NoUnitTests|Any CPU + {C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}.NoUnitTests|Any CPU.Build.0 = NoUnitTests|Any CPU + {C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}.NoUnitTestsDebug|Any CPU.ActiveCfg = NoUnitTestsDebug|Any CPU + {C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}.NoUnitTestsDebug|Any CPU.Build.0 = NoUnitTestsDebug|Any CPU + {C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/Properties/AssemblyInfo.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..8d12d056411 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/Properties/AssemblyInfo.cs @@ -0,0 +1,53 @@ +// 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.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("WmiWrappers")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("WmiWrappers")] +[assembly: AssemblyCopyright("Copyright © 2013")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("e78f4bad-16a9-4e0e-8f46-083c093492db")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.CIMV2.Win32_OperatingSystem.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.CIMV2.Win32_OperatingSystem.cs new file mode 100644 index 00000000000..ce1e22ffe9c --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.CIMV2.Win32_OperatingSystem.cs @@ -0,0 +1,2452 @@ +// 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.CIMV2 { + 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.Win32_OperatingSystem + public class OperatingSystem0 : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\CIMV2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Win32_OperatingSystem"; + + // 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 OperatingSystem0() { + this.InitializeObject(null, new System.Management.ManagementPath(OperatingSystem0.ConstructPath()), null); + } + + public OperatingSystem0(System.Management.ManagementScope mgmtScope) { + this.InitializeObject(mgmtScope, new System.Management.ManagementPath(OperatingSystem0.ConstructPath()), null); + } + + public OperatingSystem0(System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, new System.Management.ManagementPath(OperatingSystem0.ConstructPath()), getOptions); + } + + public OperatingSystem0(System.Management.ManagementScope mgmtScope, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, new System.Management.ManagementPath(OperatingSystem0.ConstructPath()), getOptions); + } + + public OperatingSystem0(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public OperatingSystem0(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public OperatingSystem0(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 OperatingSystem0(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\\CIMV2"; + } + } + + [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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The BootDevice property indicates the name of the disk drive from which the Win32" + + " operating system boots. \nExample: \\\\Device\\Harddisk0.")] + public string BootDevice { + get { + return ((string)(curObj["BootDevice"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The BuildNumber property indicates the build number of the operating system. It " + + "can be used for more precise versioning information than product release version" + + " numbers\nExample: 1381")] + public string BuildNumber { + get { + return ((string)(curObj["BuildNumber"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The BuildType property indicates the type of build used for the operating system." + + " Examples are retail build and checked build.")] + public string BuildType { + get { + return ((string)(curObj["BuildType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Caption property is a short textual description (one-line string) of the obje" + + "ct.")] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The CodeSet property indicates the code page value used by the operating system. A code page contains a character table used by the operating system to translate strings for different languages. The American National Standards Institute (ANSI) lists values that represent defined code pages. If the operating system does not use an ANSI code page, this member will be set to 0. The CodeSet string can use up to six characters to define the code page value. +Example: 1255.")] + public string CodeSet { + get { + return ((string)(curObj["CodeSet"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The CountryCode property indicates the code for the country/regionused by the operating system. Values are based on international phone dialing prefixes (also referred to as IBM country/region codes). The CountryCode string can use up to six characters to define the country/region code value. +Example: 1 for the United States)")] + public string CountryCode { + get { + return ((string)(curObj["CountryCode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("CreationClassName indicates the name of the class or the subclass used in the cre" + + "ation of an instance. When used with the other key properties of this class, thi" + + "s property allows all instances of this class and its subclasses to be uniquely " + + "identified.")] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("CSCreationClassName contains the scoping computer system\'s creation class name.")] + public string CSCreationClassName { + get { + return ((string)(curObj["CSCreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The CSDVersion property contains a null-terminated string, that indicates the latest Service Pack installed on the computer system. If no Service Pack is installed, the string is NULL. For computer systems running Windows 95, this property contains a null-terminated string that provides arbitrary additional information about the operating system. +Example: Service Pack 3.")] + public string CSDVersion { + get { + return ((string)(curObj["CSDVersion"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("CSName contains the scoping computer system\'s name.")] + public string CSName { + get { + return ((string)(curObj["CSName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCurrentTimeZoneNull { + get { + if ((curObj["CurrentTimeZone"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("CurrentTimeZone indicates the number of minutes the operating system is offset fr" + + "om Greenwich Mean Time. Either the number is positive, negative or zero.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public short CurrentTimeZone { + get { + if ((curObj["CurrentTimeZone"] == null)) { + return System.Convert.ToInt16(0); + } + return ((short)(curObj["CurrentTimeZone"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDataExecutionPrevention_32BitApplicationsNull { + get { + if ((curObj["DataExecutionPrevention_32BitApplications"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("If true, indicates that 32-bit applications are running with Data Execution Preve" + + "ntion (DEP) applied. (false if DataExecutionPrevention_Available = false)")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool DataExecutionPrevention_32BitApplications { + get { + if ((curObj["DataExecutionPrevention_32BitApplications"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["DataExecutionPrevention_32BitApplications"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDataExecutionPrevention_AvailableNull { + get { + if ((curObj["DataExecutionPrevention_Available"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"If true, indicates that the hardware supports Windows Data Execution Prevention (DEP) technology. DEP ensures that all memory locations are marked with a non-executable attribute unless the memory location explicitly contains executable code. This can help mitigate certain types of buffer overrun security exploits. If DEP is available, 64-bit applications are automatically protected. To determine if DEP has been enabled for 32-bit applications and drivers, use the DataExecutionPrevention_ properties ")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool DataExecutionPrevention_Available { + get { + if ((curObj["DataExecutionPrevention_Available"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["DataExecutionPrevention_Available"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDataExecutionPrevention_DriversNull { + get { + if ((curObj["DataExecutionPrevention_Drivers"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("If true, indicates that drivers are running with Data Execution Prevention (DEP) " + + "applied. (false if DataExecutionPrevention_Available = false)")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool DataExecutionPrevention_Drivers { + get { + if ((curObj["DataExecutionPrevention_Drivers"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["DataExecutionPrevention_Drivers"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDataExecutionPrevention_SupportPolicyNull { + get { + if ((curObj["DataExecutionPrevention_SupportPolicy"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The DataExecutionPrevention_SupportPolicy indicates which one of four Data Execution Prevention (DEP) settings is applied. Each setting varies by the extent to which DEP is applied to 32-bit applications. Note that DEP is always applied to the Windows kernel. Always On (not available in the user interface) indicates that DEP is enabled for all 32-bit applications on the machine with no exceptions. OptOut indicates DEP is on by default for all 32-bit applications and that a user or administrator must explicitly remove support for a 32-bit application by adding to an exceptions list. OptIn indicates DEP is on for a limited number of binaries, the kernel, and all Windows services but it is off by default for all 32-bit applications; a user or administrator must explicitly choose the AlwaysOn (not available in the user interface) or OptOut setting before DEP can be applied to 32-bit applications. AlwaysOff (not available in the user interface) indicates DEP is turned off for all 32-bit applications on the machine. ")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public DataExecutionPrevention_SupportPolicyValues DataExecutionPrevention_SupportPolicy { + get { + if ((curObj["DataExecutionPrevention_SupportPolicy"] == null)) { + return ((DataExecutionPrevention_SupportPolicyValues)(System.Convert.ToInt32(4))); + } + return ((DataExecutionPrevention_SupportPolicyValues)(System.Convert.ToInt32(curObj["DataExecutionPrevention_SupportPolicy"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDebugNull { + get { + if ((curObj["Debug"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The Debug property indicates whether the operating system is a checked (debug) build. Checked builds provide error checking, argument verification, and system debugging code. Additional code in a checked binary generates a kernel debugger error message and breaks into the debugger. This helps immediately determine the cause and location of the error. Performance suffers in the checked build due to the additional code that is executed. +Values: TRUE or FALSE, A value of TRUE indicates the debugging version of User.exe is installed.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool Debug { + get { + if ((curObj["Debug"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["Debug"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Description property provides a description of the Windows operating system. " + + "Some user interfaces (those that allow editing of this description) limit its le" + + "ngth to 48 characters.")] + public string Description { + get { + return ((string)(curObj["Description"])); + } + set { + curObj["Description"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDistributedNull { + get { + if ((curObj["Distributed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Boolean indicating whether the operating system is distributed across several com" + + "puter system nodes. If so, these nodes should be grouped as a cluster.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool Distributed { + get { + if ((curObj["Distributed"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["Distributed"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEncryptionLevelNull { + get { + if ((curObj["EncryptionLevel"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The EncryptionLevel property specifies if the encryption level for secure transac" + + "tions is 40-bit, 128-bit, or n-bit encryption.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public EncryptionLevelValues EncryptionLevel { + get { + if ((curObj["EncryptionLevel"] == null)) { + return ((EncryptionLevelValues)(System.Convert.ToInt32(3))); + } + return ((EncryptionLevelValues)(System.Convert.ToInt32(curObj["EncryptionLevel"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsForegroundApplicationBoostNull { + get { + if ((curObj["ForegroundApplicationBoost"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The ForegroundApplicationBoost property indicates the increase in priority given to the foreground application. On computer systems running Windows NT 4.0 and Windows 2000, application boost is implemented by giving an application more execution time slices (quantum lengths). A ForegroundApplicationBoost value of 0 indicates the system boosts the quantum length by 6; if 1, then 12; and if 2 then 18. On Windows NT 3.51 and earlier, application boost is implemented by increasing the scheduling priority. For these systems, the scheduling priority is increased by the value of this property. The default value is 2.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ForegroundApplicationBoostValues ForegroundApplicationBoost { + get { + if ((curObj["ForegroundApplicationBoost"] == null)) { + return ((ForegroundApplicationBoostValues)(System.Convert.ToInt32(3))); + } + return ((ForegroundApplicationBoostValues)(System.Convert.ToInt32(curObj["ForegroundApplicationBoost"]))); + } + set { + if ((ForegroundApplicationBoostValues.NULL_ENUM_VALUE == value)) { + curObj["ForegroundApplicationBoost"] = null; + } + else { + curObj["ForegroundApplicationBoost"] = value; + } + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFreePhysicalMemoryNull { + get { + if ((curObj["FreePhysicalMemory"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Number of kilobytes of physical memory currently unused and available")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong FreePhysicalMemory { + get { + if ((curObj["FreePhysicalMemory"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["FreePhysicalMemory"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFreeSpaceInPagingFilesNull { + get { + if ((curObj["FreeSpaceInPagingFiles"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The total number of KBytes that can be mapped into the OperatingSystem\'s paging f" + + "iles without causing any other pages to be swapped out. 0 indicates that there a" + + "re no paging files.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong FreeSpaceInPagingFiles { + get { + if ((curObj["FreeSpaceInPagingFiles"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["FreeSpaceInPagingFiles"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFreeVirtualMemoryNull { + get { + if ((curObj["FreeVirtualMemory"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Number of kilobytes of virtual memory currently unused and available. For example" + + ", this may be calculated by adding the amount of free RAM to the amount of free " + + "paging space (i.e., adding the properties, FreePhysicalMemory and FreeSpaceInPag" + + "ingFiles).")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong FreeVirtualMemory { + get { + if ((curObj["FreeVirtualMemory"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["FreeVirtualMemory"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The InstallDate property is datetime value indicating when the object was install" + + "ed. A lack of a value does not indicate that the object is not installed.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLargeSystemCacheNull { + get { + if ((curObj["LargeSystemCache"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The LargeSystemCache property indicates whether to optimize memory for applicatio" + + "ns (value=0) or for system performance (value=1).")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public LargeSystemCacheValues LargeSystemCache { + get { + if ((curObj["LargeSystemCache"] == null)) { + return ((LargeSystemCacheValues)(System.Convert.ToInt32(2))); + } + return ((LargeSystemCacheValues)(System.Convert.ToInt32(curObj["LargeSystemCache"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastBootUpTimeNull { + get { + if ((curObj["LastBootUpTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Time when the operating system was last booted")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime LastBootUpTime { + get { + if ((curObj["LastBootUpTime"] != null)) { + return ToDateTime(((string)(curObj["LastBootUpTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLocalDateTimeNull { + get { + if ((curObj["LocalDateTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Operating system\'s notion of the local date and time of day.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime LocalDateTime { + get { + if ((curObj["LocalDateTime"] != null)) { + return ToDateTime(((string)(curObj["LocalDateTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The Locale property indicates the language identifier used by the operating system. A language identifier is a standard international numeric abbreviation for a country or region. Each language has a unique language identifier (LANGID), a 16-bit value that consists of a primary language identifier and a secondary language identifier.")] + public string Locale { + get { + return ((string)(curObj["Locale"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Manufacturer property indicates the name of the operating system manufacturer" + + ". For Win32 systems this value will be Microsoft Corporation.")] + public string Manufacturer { + get { + return ((string)(curObj["Manufacturer"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxNumberOfProcessesNull { + get { + if ((curObj["MaxNumberOfProcesses"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Maximum number of process contexts the operating system can support. If there is no fixed maximum, the value should be 0. On systems that have a fixed maximum, this object can help diagnose failures that occur when the maximum is reached. If unknown, enter -1.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxNumberOfProcesses { + get { + if ((curObj["MaxNumberOfProcesses"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxNumberOfProcesses"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxProcessMemorySizeNull { + get { + if ((curObj["MaxProcessMemorySize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Maximum number of kilobytes of memory that can be allocated to a process. For operating systems with no virtual memory, this value is typically equal to the total amount of physical memory minus memory used by the BIOS and OS. For some operating systems, this value may be infinity - in which case, 0 should be entered. In other cases, this value could be a constant - for example, 2G or 4G.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxProcessMemorySize { + get { + if ((curObj["MaxProcessMemorySize"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxProcessMemorySize"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The MUILanguages property indicates the MUI Languages installed in the system. \n " + + "Example: en-us.")] + public string[] MUILanguages { + get { + return ((string[])(curObj["MUILanguages"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Name of the operating system instance within a computer system.")] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNumberOfLicensedUsersNull { + get { + if ((curObj["NumberOfLicensedUsers"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Number of user licenses for the operating system. If unlimited, enter 0. If unkno" + + "wn, enter -1.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint NumberOfLicensedUsers { + get { + if ((curObj["NumberOfLicensedUsers"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["NumberOfLicensedUsers"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNumberOfProcessesNull { + get { + if ((curObj["NumberOfProcesses"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Number of process contexts currently loaded or running on the operating system.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint NumberOfProcesses { + get { + if ((curObj["NumberOfProcesses"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["NumberOfProcesses"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNumberOfUsersNull { + get { + if ((curObj["NumberOfUsers"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Number of user sessions for which the operating system is currently storing state" + + " information")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint NumberOfUsers { + get { + if ((curObj["NumberOfUsers"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["NumberOfUsers"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingSystemSKUNull { + get { + if ((curObj["OperatingSystemSKU"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The OperatingSystemSKU property identifies the SKU of the operating system.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint OperatingSystemSKU { + get { + if ((curObj["OperatingSystemSKU"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["OperatingSystemSKU"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Organization property indicates the registered user\'s (of the operating syste" + + "m) company name.\nExample: Microsoft Corporation.")] + public string Organization { + get { + return ((string)(curObj["Organization"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The OSArchitecture property indicates the Architecture of the operating system.Ex" + + "ample: 32-bit, 64-bit Intel, 64-bit AMD ")] + public string OSArchitecture { + get { + return ((string)(curObj["OSArchitecture"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOSLanguageNull { + get { + if ((curObj["OSLanguage"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The OSLanguage property indicates which language version of the operating system " + + "is installed.\nExample: 0x0807 (German, Switzerland)")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint OSLanguage { + get { + if ((curObj["OSLanguage"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["OSLanguage"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOSProductSuiteNull { + get { + if ((curObj["OSProductSuite"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The OSProductSuite property identifies installed and licensed system product addi" + + "tions to the operating system.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public OSProductSuiteValues OSProductSuite { + get { + if ((curObj["OSProductSuite"] == null)) { + return ((OSProductSuiteValues)(System.Convert.ToInt32(256))); + } + return ((OSProductSuiteValues)(System.Convert.ToInt32(curObj["OSProductSuite"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOSTypeNull { + get { + if ((curObj["OSType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("A integer indicating the type of operating system.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public OSTypeValues OSType { + get { + if ((curObj["OSType"] == null)) { + return ((OSTypeValues)(System.Convert.ToInt32(63))); + } + return ((OSTypeValues)(System.Convert.ToInt32(curObj["OSType"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"A string describing the manufacturer and operating system type - used when the operating system property, OSType, is set to 1 (""Other""). The format of the string inserted in OtherTypeDescription should be similar in format to the Values strings defined for OSType. OtherTypeDescription should be set to NULL when OSType is any value other than 1.")] + public string OtherTypeDescription { + get { + return ((string)(curObj["OtherTypeDescription"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPAEEnabledNull { + get { + if ((curObj["PAEEnabled"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool PAEEnabled { + get { + if ((curObj["PAEEnabled"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["PAEEnabled"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The PlusProductID property contains the product identification number for the Win" + + "dows Plus! operating system enhancement software (if installed).")] + public string PlusProductID { + get { + return ((string)(curObj["PlusProductID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The PlusVersionNumber property contains the version number of the Windows Plus! o" + + "perating system enhancement software (if installed).")] + public string PlusVersionNumber { + get { + return ((string)(curObj["PlusVersionNumber"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPortableOperatingSystemNull { + get { + if ((curObj["PortableOperatingSystem"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The PortableOperatingSystem property indicates if theOperating System is booting from a supported locally connected storagedevice. +Values: TRUE or FALSE, A value of TRUE indicates the OperatingSystem was booted from a supported locally connected storage device. +")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool PortableOperatingSystem { + get { + if ((curObj["PortableOperatingSystem"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["PortableOperatingSystem"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryNull { + get { + if ((curObj["Primary"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Primary property determines whether this is the primary operating system.\nVal" + + "ues: TRUE or FALSE. A value of TRUE indicates this is the primary operating syst" + + "em.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool Primary { + get { + if ((curObj["Primary"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["Primary"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsProductTypeNull { + get { + if ((curObj["ProductType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The ProductType property indicates additional information about the system. This " + + "member can be one of the following values: \n1 - Work Station \n2 - Domain Control" + + "ler \n3 - Server")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ProductTypeValues ProductType { + get { + if ((curObj["ProductType"] == null)) { + return ((ProductTypeValues)(System.Convert.ToInt32(0))); + } + return ((ProductTypeValues)(System.Convert.ToInt32(curObj["ProductType"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The RegisteredUser property indicates the name of the registered user of the oper" + + "ating system.\nExample: Jane Doe")] + public string RegisteredUser { + get { + return ((string)(curObj["RegisteredUser"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The SerialNumber property indicates the operating system product serial identific" + + "ation number.\nExample:10497-OEM-0031416-71674.")] + public string SerialNumber { + get { + return ((string)(curObj["SerialNumber"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsServicePackMajorVersionNull { + get { + if ((curObj["ServicePackMajorVersion"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The ServicePackMajorVersion property indicates the major version number of the service pack installed on the computer system. If no service pack has been installed, the value is zero. ServicePackMajorVersion is valid for computers running Windows 2000 and later (NULL otherwise).")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ServicePackMajorVersion { + get { + if ((curObj["ServicePackMajorVersion"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ServicePackMajorVersion"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsServicePackMinorVersionNull { + get { + if ((curObj["ServicePackMinorVersion"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The ServicePackMinorVersion property indicates the minor version number of the service pack installed on the computer system. If no service pack has been installed, the value is zero. ServicePackMinorVersion is valid for computers running Windows 2000 and later (NULL otherwise).")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ServicePackMinorVersion { + get { + if ((curObj["ServicePackMinorVersion"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ServicePackMinorVersion"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSizeStoredInPagingFilesNull { + get { + if ((curObj["SizeStoredInPagingFiles"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The total number of kilobytes that can be stored in the operating system\'s paging" + + " files. Note that this number does not represent the actual physical size of the" + + " paging file on disk. 0 indicates that there are no paging files.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong SizeStoredInPagingFiles { + get { + if ((curObj["SizeStoredInPagingFiles"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["SizeStoredInPagingFiles"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The Status property is a string indicating the current status of the object. Various operational and non-operational statuses can be defined. Operational statuses are ""OK"", ""Degraded"" and ""Pred Fail"". ""Pred Fail"" indicates that an element may be functioning properly but predicting a failure in the near future. An example is a SMART-enabled hard drive. Non-operational statuses can also be specified. These are ""Error"", ""Starting"", ""Stopping"" and ""Service"". The latter, ""Service"", could apply during mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is on-line, yet the managed element is neither ""OK"" nor in one of the other states.")] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSuiteMaskNull { + get { + if ((curObj["SuiteMask"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The SuiteMask property indicates a set of bit flags that identify the product suites available on the system. This member can be a combination of the following values: +0 - Windows Server 2003, Small Business Edition +1 - Windows Server 2003, Enterprise Edition +2 - Windows Server 2003, Backoffice Edition +3 - Windows Server 2003, Communications Edition +4 - Microsoft Terminal Services +5 - Windows Server 2003, Small Business Edition Restricted +6 - Windows XP Embedded +7 - Windows Server 2003, Datacenter Edition +8 - Single User +9 - Windows XP Home Edition +10 - Windows Server 2003, Web Edition")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public SuiteMaskValues SuiteMask { + get { + if ((curObj["SuiteMask"] == null)) { + return ((SuiteMaskValues)(System.Convert.ToInt32(20))); + } + return ((SuiteMaskValues)(System.Convert.ToInt32(curObj["SuiteMask"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The SystemDevice property indicates the physical disk partition the operating sys" + + "tem is installed on.")] + public string SystemDevice { + get { + return ((string)(curObj["SystemDevice"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The SystemDirectory property indicates the system directory of the operating syst" + + "em.\nExample: C:\\WINDOWS\\SYSTEM32")] + public string SystemDirectory { + get { + return ((string)(curObj["SystemDirectory"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The SystemDrive property contains the letter of the disk drive that the operating" + + " system resides on.\nExample: C:")] + public string SystemDrive { + get { + return ((string)(curObj["SystemDrive"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTotalSwapSpaceSizeNull { + get { + if ((curObj["TotalSwapSpaceSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Total swap space in kilobytes. This value may be NULL (unspecified) if swap space is not distinguished from page files. However, some operating systems distinguish these concepts. For example, in UNIX, whole processes can be 'swapped out' when the free page list falls and remains below a specified amount.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong TotalSwapSpaceSize { + get { + if ((curObj["TotalSwapSpaceSize"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["TotalSwapSpaceSize"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTotalVirtualMemorySizeNull { + get { + if ((curObj["TotalVirtualMemorySize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Number of kilobytes of virtual memory. For example, this may be calculated by add" + + "ing the amount of total RAM to the amount of paging space (i.e., adding the amou" + + "nt of memory in/aggregated by the computer system to the property, SizeStoredInP" + + "agingFiles.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong TotalVirtualMemorySize { + get { + if ((curObj["TotalVirtualMemorySize"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["TotalVirtualMemorySize"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTotalVisibleMemorySizeNull { + get { + if ((curObj["TotalVisibleMemorySize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The total amount of physical memory (in Kbytes) available to the OperatingSystem." + + " This value does not necessarily indicate the true amount of physical memory, bu" + + "t what is reported to the OperatingSystem as available to it.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong TotalVisibleMemorySize { + get { + if ((curObj["TotalVisibleMemorySize"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["TotalVisibleMemorySize"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Version property indicates the version number of the operating system.\nExampl" + + "e: 4.0")] + public string Version { + get { + return ((string)(curObj["Version"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The WindowsDirectory property indicates the Windows directory of the operating sy" + + "stem.\nExample: C:\\WINDOWS")] + public string WindowsDirectory { + get { + return ((string)(curObj["WindowsDirectory"])); + } + } + + 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 ShouldSerializeCurrentTimeZone() { + if ((this.IsCurrentTimeZoneNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDataExecutionPrevention_32BitApplications() { + if ((this.IsDataExecutionPrevention_32BitApplicationsNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDataExecutionPrevention_Available() { + if ((this.IsDataExecutionPrevention_AvailableNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDataExecutionPrevention_Drivers() { + if ((this.IsDataExecutionPrevention_DriversNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDataExecutionPrevention_SupportPolicy() { + if ((this.IsDataExecutionPrevention_SupportPolicyNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDebug() { + if ((this.IsDebugNull == false)) { + return true; + } + return false; + } + + private void ResetDescription() { + curObj["Description"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeDistributed() { + if ((this.IsDistributedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEncryptionLevel() { + if ((this.IsEncryptionLevelNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeForegroundApplicationBoost() { + if ((this.IsForegroundApplicationBoostNull == false)) { + return true; + } + return false; + } + + private void ResetForegroundApplicationBoost() { + curObj["ForegroundApplicationBoost"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeFreePhysicalMemory() { + if ((this.IsFreePhysicalMemoryNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeFreeSpaceInPagingFiles() { + if ((this.IsFreeSpaceInPagingFilesNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeFreeVirtualMemory() { + if ((this.IsFreeVirtualMemoryNull == 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 ShouldSerializeLargeSystemCache() { + if ((this.IsLargeSystemCacheNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastBootUpTime() { + if ((this.IsLastBootUpTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLocalDateTime() { + if ((this.IsLocalDateTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxNumberOfProcesses() { + if ((this.IsMaxNumberOfProcessesNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxProcessMemorySize() { + if ((this.IsMaxProcessMemorySizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeNumberOfLicensedUsers() { + if ((this.IsNumberOfLicensedUsersNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeNumberOfProcesses() { + if ((this.IsNumberOfProcessesNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeNumberOfUsers() { + if ((this.IsNumberOfUsersNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingSystemSKU() { + if ((this.IsOperatingSystemSKUNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOSLanguage() { + if ((this.IsOSLanguageNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOSProductSuite() { + if ((this.IsOSProductSuiteNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOSType() { + if ((this.IsOSTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePAEEnabled() { + if ((this.IsPAEEnabledNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePortableOperatingSystem() { + if ((this.IsPortableOperatingSystemNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimary() { + if ((this.IsPrimaryNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeProductType() { + if ((this.IsProductTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeServicePackMajorVersion() { + if ((this.IsServicePackMajorVersionNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeServicePackMinorVersion() { + if ((this.IsServicePackMinorVersionNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSizeStoredInPagingFiles() { + if ((this.IsSizeStoredInPagingFilesNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSuiteMask() { + if ((this.IsSuiteMaskNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTotalSwapSpaceSize() { + if ((this.IsTotalSwapSpaceSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTotalVirtualMemorySize() { + if ((this.IsTotalVirtualMemorySizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTotalVisibleMemorySize() { + if ((this.IsTotalVisibleMemorySizeNull == 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() { + return "ROOT\\CIMV2:Win32_OperatingSystem=@"; + } + + 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; + } + + [Browsable(true)] + public static OperatingSystem0 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 OperatingSystem0(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint Reboot() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + bool EnablePrivileges = PrivateLateBoundObject.Scope.Options.EnablePrivileges; + PrivateLateBoundObject.Scope.Options.EnablePrivileges = true; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reboot", inParams, null); + PrivateLateBoundObject.Scope.Options.EnablePrivileges = EnablePrivileges; + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SetDateTime(System.DateTime LocalDateTime) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + bool EnablePrivileges = PrivateLateBoundObject.Scope.Options.EnablePrivileges; + PrivateLateBoundObject.Scope.Options.EnablePrivileges = true; + inParams = PrivateLateBoundObject.GetMethodParameters("SetDateTime"); + inParams["LocalDateTime"] = ToDmtfDateTime(((System.DateTime)(LocalDateTime))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetDateTime", inParams, null); + PrivateLateBoundObject.Scope.Options.EnablePrivileges = EnablePrivileges; + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint Shutdown() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + bool EnablePrivileges = PrivateLateBoundObject.Scope.Options.EnablePrivileges; + PrivateLateBoundObject.Scope.Options.EnablePrivileges = true; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Shutdown", inParams, null); + PrivateLateBoundObject.Scope.Options.EnablePrivileges = EnablePrivileges; + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint Win32Shutdown(int Flags, int Reserved) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + bool EnablePrivileges = PrivateLateBoundObject.Scope.Options.EnablePrivileges; + PrivateLateBoundObject.Scope.Options.EnablePrivileges = true; + inParams = PrivateLateBoundObject.GetMethodParameters("Win32Shutdown"); + inParams["Flags"] = ((int)(Flags)); + inParams["Reserved"] = ((int)(Reserved)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Win32Shutdown", inParams, null); + PrivateLateBoundObject.Scope.Options.EnablePrivileges = EnablePrivileges; + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint Win32ShutdownTracker(string Comment, int Flags, uint ReasonCode, uint Timeout) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + bool EnablePrivileges = PrivateLateBoundObject.Scope.Options.EnablePrivileges; + PrivateLateBoundObject.Scope.Options.EnablePrivileges = true; + inParams = PrivateLateBoundObject.GetMethodParameters("Win32ShutdownTracker"); + inParams["Comment"] = ((string)(Comment)); + inParams["Flags"] = ((int)(Flags)); + inParams["ReasonCode"] = ((uint)(ReasonCode)); + inParams["Timeout"] = ((uint)(Timeout)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Win32ShutdownTracker", inParams, null); + PrivateLateBoundObject.Scope.Options.EnablePrivileges = EnablePrivileges; + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public enum DataExecutionPrevention_SupportPolicyValues { + + Always_Off = 0, + + Always_On = 1, + + Opt_In = 2, + + Opt_Out = 3, + + NULL_ENUM_VALUE = 4, + } + + public enum EncryptionLevelValues { + + Val_40_bit = 0, + + Val_128_bit = 1, + + N_bit = 2, + + NULL_ENUM_VALUE = 3, + } + + public enum ForegroundApplicationBoostValues { + + None = 0, + + Minimum = 1, + + Maximum = 2, + + NULL_ENUM_VALUE = 3, + } + + public enum LargeSystemCacheValues { + + Optimize_for_Applications = 0, + + Optimize_for_System_Performance = 1, + + NULL_ENUM_VALUE = 2, + } + + public enum OSProductSuiteValues { + + Small_Business = 1, + + Enterprise = 2, + + BackOffice = 4, + + Communication_Server = 8, + + Terminal_Server = 16, + + Small_Business_Restricted_ = 32, + + Embedded_NT = 64, + + Data_Center = 128, + + NULL_ENUM_VALUE = 256, + } + + public enum OSTypeValues { + + Unknown0 = 0, + + Other0 = 1, + + MACOS = 2, + + ATTUNIX = 3, + + DGUX = 4, + + DECNT = 5, + + Digital_Unix = 6, + + OpenVMS = 7, + + HPUX = 8, + + AIX = 9, + + MVS = 10, + + OS400 = 11, + + OS_2 = 12, + + JavaVM = 13, + + MSDOS = 14, + + WIN3x = 15, + + WIN95 = 16, + + WIN98 = 17, + + WINNT = 18, + + WINCE = 19, + + NCR3000 = 20, + + NetWare = 21, + + OSF = 22, + + DC_OS = 23, + + Reliant_UNIX = 24, + + SCO_UnixWare = 25, + + SCO_OpenServer = 26, + + Sequent = 27, + + IRIX = 28, + + Solaris = 29, + + SunOS = 30, + + U6000 = 31, + + ASERIES = 32, + + TandemNSK = 33, + + TandemNT = 34, + + BS2000 = 35, + + LINUX = 36, + + Lynx = 37, + + XENIX = 38, + + VM_ESA = 39, + + Interactive_UNIX = 40, + + BSDUNIX = 41, + + FreeBSD = 42, + + NetBSD = 43, + + GNU_Hurd = 44, + + OS9 = 45, + + MACH_Kernel = 46, + + Inferno = 47, + + QNX = 48, + + EPOC = 49, + + IxWorks = 50, + + VxWorks = 51, + + MiNT = 52, + + BeOS = 53, + + HP_MPE = 54, + + NextStep = 55, + + PalmPilot = 56, + + Rhapsody = 57, + + Windows_2000 = 58, + + Dedicated = 59, + + OS_390 = 60, + + VSE = 61, + + TPF = 62, + + NULL_ENUM_VALUE = 63, + } + + public enum ProductTypeValues { + + Work_Station = 1, + + Domain_Controller = 2, + + Server = 3, + + NULL_ENUM_VALUE = 0, + } + + public enum SuiteMaskValues { + + Windows_Server_2003_Small_Business_Edition = 0, + + Windows_Server_2003_Enterprise_Edition = 1, + + Windows_Server_2003_Backoffice_Edition = 2, + + Windows_Server_2003_Communications_Edition = 3, + + Microsoft_Terminal_Services = 4, + + Windows_Server_2003_Small_Business_Edition_Restricted = 5, + + Windows_XP_Embedded = 6, + + Windows_Server_2003_Datacenter_Edition = 7, + + Single_User = 8, + + Windows_XP_Home_Edition = 9, + + Windows_Server_2003_Web_Edition = 10, + + NULL_ENUM_VALUE = 20, + } + + // 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.CIMV2.Win32_Processor.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.CIMV2.Win32_Processor.cs new file mode 100644 index 00000000000..09ef22b4288 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.CIMV2.Win32_Processor.cs @@ -0,0 +1,2540 @@ +// 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.CIMV2 +{ + 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.Win32_Processor + public class Processor : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\CIMV2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Win32_Processor"; + + // 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 Processor() { + this.InitializeObject(null, null, null); + } + + public Processor(string keyDeviceID) { + this.InitializeObject(null, new System.Management.ManagementPath(Processor.ConstructPath(keyDeviceID)), null); + } + + public Processor(System.Management.ManagementScope mgmtScope, string keyDeviceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(Processor.ConstructPath(keyDeviceID)), null); + } + + public Processor(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public Processor(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public Processor(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public Processor(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public Processor(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 Processor(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\\CIMV2"; + } + } + + [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 IsAddressWidthNull { + get { + if ((curObj["AddressWidth"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Processor address width in bits.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort AddressWidth { + get { + if ((curObj["AddressWidth"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["AddressWidth"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsArchitectureNull { + get { + if ((curObj["Architecture"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Architecture property specifies the processor architecture used by this platf" + + "orm. It returns one of the following integer values:\n0 - x86 \n1 - MIPS \n2" + + " - Alpha \n3 - PowerPC \n6 - ia64 \n9 - x64 \n")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ArchitectureValues Architecture { + get { + if ((curObj["Architecture"] == null)) { + return ((ArchitectureValues)(System.Convert.ToInt32(10))); + } + return ((ArchitectureValues)(System.Convert.ToInt32(curObj["Architecture"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAvailabilityNull { + get { + if ((curObj["Availability"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The availability and status of the device. For example, the Availability property indicates that the device is running and has full power (value=3), or is in a warning (4), test (5), degraded (10) or power save state (values 13-15 and 17). Regarding the power saving states, these are defined as follows: Value 13 (""Power Save - Unknown"") indicates that the device is known to be in a power save mode, but its exact status in this mode is unknown; 14 (""Power Save - Low Power Mode"") indicates that the device is in a power save state but still functioning, and may exhibit degraded performance; 15 (""Power Save - Standby"") describes that the device is not functioning but could be brought to full power 'quickly'; and value 17 (""Power Save - Warning"") indicates that the device is in a warning state, though also in a power save mode.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public AvailabilityValues Availability { + get { + if ((curObj["Availability"] == null)) { + return ((AvailabilityValues)(System.Convert.ToInt32(0))); + } + return ((AvailabilityValues)(System.Convert.ToInt32(curObj["Availability"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Caption property is a short textual description (one-line string) of the obje" + + "ct.")] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConfigManagerErrorCodeNull { + get { + if ((curObj["ConfigManagerErrorCode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates the Win32 Configuration Manager error code. The following values may b" + + "e returned: \n0 This device is working properly. \n1 This device is not " + + "configured correctly. \n2 Windows cannot load the driver for this device. \n3" + + " The driver for this device might be corrupted, or your system may be runni" + + "ng low on memory or other resources. \n4 This device is not working properly" + + ". One of its drivers or your registry might be corrupted. \n5 The driver for" + + " this device needs a resource that Windows cannot manage. \n6 The boot confi" + + "guration for this device conflicts with other devices. \n7 Cannot filter. \n8" + + " The driver loader for the device is missing. \n9 This device is not wo" + + "rking properly because the controlling firmware is reporting the resources for t" + + "he device incorrectly. \n10 This device cannot start. \n11 This device fai" + + "led. \n12 This device cannot find enough free resources that it can use. \n13 " + + " Windows cannot verify this device\'s resources. \n14 This device cannot wo" + + "rk properly until you restart your computer. \n15 This device is not working " + + "properly because there is probably a re-enumeration problem. \n16 Windows can" + + "not identify all the resources this device uses. \n17 This device is asking f" + + "or an unknown resource type. \n18 Reinstall the drivers for this device. \n19 " + + " Your registry might be corrupted. \n20 Failure using the VxD loader. \n21 " + + " System failure: Try changing the driver for this device. If that does not wo" + + "rk, see your hardware documentation. Windows is removing this device. \n22 Th" + + "is device is disabled. \n23 System failure: Try changing the driver for this " + + "device. If that doesn\'t work, see your hardware documentation. \n24 This devi" + + "ce is not present, is not working properly, or does not have all its drivers ins" + + "talled. \n25 Windows is still setting up this device. \n26 Windows is stil" + + "l setting up this device. \n27 This device does not have valid log configurat" + + "ion. \n28 The drivers for this device are not installed. \n29 This device " + + "is disabled because the firmware of the device did not give it the required reso" + + "urces. \n30 This device is using an Interrupt Request (IRQ) resource that ano" + + "ther device is using. \n31 This device is not working properly because Window" + + "s cannot load the drivers required for this device.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ConfigManagerErrorCodeValues ConfigManagerErrorCode { + get { + if ((curObj["ConfigManagerErrorCode"] == null)) { + return ((ConfigManagerErrorCodeValues)(System.Convert.ToInt32(32))); + } + return ((ConfigManagerErrorCodeValues)(System.Convert.ToInt32(curObj["ConfigManagerErrorCode"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConfigManagerUserConfigNull { + get { + if ((curObj["ConfigManagerUserConfig"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates whether the device is using a user-defined configuration.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool ConfigManagerUserConfig { + get { + if ((curObj["ConfigManagerUserConfig"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["ConfigManagerUserConfig"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCpuStatusNull { + get { + if ((curObj["CpuStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The CpuStatus property specifies the current status of the processor. Changes in " + + "status arise from processor usage, not the physical condition of the processor.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public CpuStatusValues CpuStatus { + get { + if ((curObj["CpuStatus"] == null)) { + return ((CpuStatusValues)(System.Convert.ToInt32(8))); + } + return ((CpuStatusValues)(System.Convert.ToInt32(curObj["CpuStatus"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("CreationClassName indicates the name of the class or the subclass used in the cre" + + "ation of an instance. When used with the other key properties of this class, thi" + + "s property allows all instances of this class and its subclasses to be uniquely " + + "identified.")] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCurrentClockSpeedNull { + get { + if ((curObj["CurrentClockSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current speed (in MHz) of this processor.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint CurrentClockSpeed { + get { + if ((curObj["CurrentClockSpeed"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["CurrentClockSpeed"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCurrentVoltageNull { + get { + if ((curObj["CurrentVoltage"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The CurrentVoltage specifies the voltage of the processor. bits 0-6 of the field contain the processor's current voltage times 10. This value is only set when SMBIOS designates a voltage value. For specific values, see VoltageCaps. +Example: field value for a processor voltage of 1.8 volts would be 92h = 80h + (1.8 x 10) = 80h + 18 = 80h + 12h.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CurrentVoltage { + get { + if ((curObj["CurrentVoltage"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CurrentVoltage"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDataWidthNull { + get { + if ((curObj["DataWidth"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Processor data width in bits.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DataWidth { + get { + if ((curObj["DataWidth"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DataWidth"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Description property provides a textual description of the object. ")] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The DeviceID property contains a string uniquely identifying the processor with o" + + "ther devices on the system.")] + public string DeviceID { + get { + return ((string)(curObj["DeviceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsErrorClearedNull { + get { + if ((curObj["ErrorCleared"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("ErrorCleared is a boolean property indicating that the error reported in LastErro" + + "rCode property is now cleared.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool ErrorCleared { + get { + if ((curObj["ErrorCleared"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["ErrorCleared"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("ErrorDescription is a free-form string supplying more information about the error" + + " recorded in LastErrorCode property, and information on any corrective actions t" + + "hat may be taken.")] + public string ErrorDescription { + get { + return ((string)(curObj["ErrorDescription"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsExtClockNull { + get { + if ((curObj["ExtClock"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The ExtClock property specifies the external clock frequency. If the frequency is" + + " unknown this property is set to null.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint ExtClock { + get { + if ((curObj["ExtClock"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["ExtClock"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFamilyNull { + get { + if ((curObj["Family"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The processor family type. For example, values include \"Pentium(R) processor with" + + " MMX(TM) technology\" (14) and \"68040\" (96).")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public FamilyValues Family { + get { + if ((curObj["Family"] == null)) { + return ((FamilyValues)(System.Convert.ToInt32(0))); + } + return ((FamilyValues)(System.Convert.ToInt32(curObj["Family"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The InstallDate property is datetime value indicating when the object was install" + + "ed. A lack of a value does not indicate that the object is not installed.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsL2CacheSizeNull { + get { + if ((curObj["L2CacheSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The L2CacheSize property specifies the size of the processor\'s Level 2 cache. A L" + + "evel 2 cache is an external memory area that has a faster access times than the " + + "main RAM memory.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint L2CacheSize { + get { + if ((curObj["L2CacheSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["L2CacheSize"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsL2CacheSpeedNull { + get { + if ((curObj["L2CacheSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The L2CacheSpeed property specifies the clockspeed of the processor\'s Level 2 cac" + + "he. A Level 2 cache is an external memory area that has a faster access times th" + + "an the main RAM memory.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint L2CacheSpeed { + get { + if ((curObj["L2CacheSpeed"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["L2CacheSpeed"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsL3CacheSizeNull { + get { + if ((curObj["L3CacheSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The L3CacheSize property specifies the size of the processor\'s Level 3 cache. A L" + + "evel 3 cache is an external memory area that has a faster access times than the " + + "main RAM memory.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint L3CacheSize { + get { + if ((curObj["L3CacheSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["L3CacheSize"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsL3CacheSpeedNull { + get { + if ((curObj["L3CacheSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The L3CacheSpeed property specifies the clockspeed of the processor\'s Level 3 cac" + + "he. A Level 3 cache is an external memory area that has a faster access times th" + + "an the main RAM memory.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint L3CacheSpeed { + get { + if ((curObj["L3CacheSpeed"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["L3CacheSpeed"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastErrorCodeNull { + get { + if ((curObj["LastErrorCode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("LastErrorCode captures the last error code reported by the logical device.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint LastErrorCode { + get { + if ((curObj["LastErrorCode"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["LastErrorCode"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLevelNull { + get { + if ((curObj["Level"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Level property further defines the processor type. The value depends on the " + + "architecture of the processor.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Level { + get { + if ((curObj["Level"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Level"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLoadPercentageNull { + get { + if ((curObj["LoadPercentage"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The LoadPercentage property specifies each processor\'s load capacity averaged ove" + + "r the last second. The term \'processor loading\' refers to the total computing bu" + + "rden each processor carries at one time.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort LoadPercentage { + get { + if ((curObj["LoadPercentage"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["LoadPercentage"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Manufacturer property specifies the name of the processor\'s manufacturer.\nExa" + + "mple: GenuineSilicon")] + public string Manufacturer { + get { + return ((string)(curObj["Manufacturer"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxClockSpeedNull { + get { + if ((curObj["MaxClockSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum speed (in MHz) of this processor.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxClockSpeed { + get { + if ((curObj["MaxClockSpeed"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxClockSpeed"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Name property defines the label by which the object is known. When subclassed" + + ", the Name property can be overridden to be a Key property.")] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNumberOfCoresNull { + get { + if ((curObj["NumberOfCores"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The NumberOfCores property contains a Processor\'s total number of cores. e.g dual" + + " core machine will have NumberOfCores = 2.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint NumberOfCores { + get { + if ((curObj["NumberOfCores"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["NumberOfCores"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNumberOfLogicalProcessorsNull { + get { + if ((curObj["NumberOfLogicalProcessors"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The NumberOfLogicalProcessors property specifies the total number of logical proc" + + "essors.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint NumberOfLogicalProcessors { + get { + if ((curObj["NumberOfLogicalProcessors"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["NumberOfLogicalProcessors"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("A string describing the processor family type - used when the family property is " + + "set to 1 (\"Other\"). This string should be set to NULL when the family property i" + + "s any value other than 1.")] + public string OtherFamilyDescription { + get { + return ((string)(curObj["OtherFamilyDescription"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates the Win32 Plug and Play device ID of the logical device. Example: *PNP" + + "030b")] + public string PNPDeviceID { + get { + return ((string)(curObj["PNPDeviceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Indicates the specific power-related capabilities of the logical device. The array values, 0=""Unknown"", 1=""Not Supported"" and 2=""Disabled"" are self-explanatory. The value, 3=""Enabled"" indicates that the power management features are currently enabled but the exact feature set is unknown or the information is unavailable. ""Power Saving Modes Entered Automatically"" (4) describes that a device can change its power state based on usage or other criteria. ""Power State Settable"" (5) indicates that the SetPowerState method is supported. ""Power Cycling Supported"" (6) indicates that the SetPowerState method can be invoked with the PowerState input variable set to 5 (""Power Cycle""). ""Timed Power On Supported"" (7) indicates that the SetPowerState method can be invoked with the PowerState input variable set to 5 (""Power Cycle"") and the Time parameter set to a specific date and time, or interval, for power-on.")] + public PowerManagementCapabilitiesValues[] PowerManagementCapabilities { + get { + System.Array arrEnumVals = ((System.Array)(curObj["PowerManagementCapabilities"])); + PowerManagementCapabilitiesValues[] enumToRet = new PowerManagementCapabilitiesValues[arrEnumVals.Length]; + int counter = 0; + for (counter = 0; (counter < arrEnumVals.Length); counter = (counter + 1)) { + enumToRet[counter] = ((PowerManagementCapabilitiesValues)(System.Convert.ToInt32(arrEnumVals.GetValue(counter)))); + } + return enumToRet; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerManagementSupportedNull { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Boolean indicating that the Device can be power managed - ie, put into a power save state. This boolean does not indicate that power management features are currently enabled, or if enabled, what features are supported. Refer to the PowerManagementCapabilities array for this information. If this boolean is false, the integer value 1, for the string, ""Not Supported"", should be the only entry in the PowerManagementCapabilities array.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool PowerManagementSupported { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["PowerManagementSupported"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The ProcessorId property contains processor-specific information that describes the processor's features. For x86 class CPUs, the field's format depends on the processor's support of the CPUID instruction. If the instruction is supported, the ProcessorId property contains two DWORD-formatted values. The first (offsets 08h-0Bh) is the EAX value returned by a CPUID instruction with input EAX set to 1. The second (offsets 0Ch-0Fh) is the EDX value returned by that instruction. Only the first two bytes of the ProcessorID property are significant (all others are set to 0) and contain (in WORD-format) the contents of the DX register at CPU reset.")] + public string ProcessorId { + get { + return ((string)(curObj["ProcessorId"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsProcessorTypeNull { + get { + if ((curObj["ProcessorType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The ProcessorType property specifies the processor\'s primary function.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ProcessorTypeValues ProcessorType { + get { + if ((curObj["ProcessorType"] == null)) { + return ((ProcessorTypeValues)(System.Convert.ToInt32(0))); + } + return ((ProcessorTypeValues)(System.Convert.ToInt32(curObj["ProcessorType"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRevisionNull { + get { + if ((curObj["Revision"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Revision property specifies the system\'s architecture-dependent revision leve" + + "l. The meaning of this value depends on the architecture of the processor. It co" + + "ntains the same values as the \"Version\" member, but in a numerical format.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Revision { + get { + if ((curObj["Revision"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Revision"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("A free form string describing the role of the processor - for example, \"Central P" + + "rocessor\"\' or \"Math Processor\"")] + public string Role { + get { + return ((string)(curObj["Role"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSecondLevelAddressTranslationExtensionsNull { + get { + if ((curObj["SecondLevelAddressTranslationExtensions"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The SecondLevelAddressTranslationExtensions property determines whether the proce" + + "ssor supports address translation extensions used for virtualization.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool SecondLevelAddressTranslationExtensions { + get { + if ((curObj["SecondLevelAddressTranslationExtensions"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["SecondLevelAddressTranslationExtensions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The SocketDesignation property contains the type of chip socket used on the circu" + + "it.\nExample: J202")] + public string SocketDesignation { + get { + return ((string)(curObj["SocketDesignation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The Status property is a string indicating the current status of the object. Various operational and non-operational statuses can be defined. Operational statuses are ""OK"", ""Degraded"" and ""Pred Fail"". ""Pred Fail"" indicates that an element may be functioning properly but predicting a failure in the near future. An example is a SMART-enabled hard drive. Non-operational statuses can also be specified. These are ""Error"", ""Starting"", ""Stopping"" and ""Service"". The latter, ""Service"", could apply during mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is on-line, yet the managed element is neither ""OK"" nor in one of the other states.")] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStatusInfoNull { + get { + if ((curObj["StatusInfo"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("StatusInfo is a string indicating whether the logical device is in an enabled (va" + + "lue = 3), disabled (value = 4) or some other (1) or unknown (2) state. If this p" + + "roperty does not apply to the logical device, the value, 5 (\"Not Applicable\"), s" + + "hould be used.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public StatusInfoValues StatusInfo { + get { + if ((curObj["StatusInfo"] == null)) { + return ((StatusInfoValues)(System.Convert.ToInt32(0))); + } + return ((StatusInfoValues)(System.Convert.ToInt32(curObj["StatusInfo"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Stepping is a free-form string indicating the revision level of the processor wit" + + "hin the processor family.")] + public string Stepping { + get { + return ((string)(curObj["Stepping"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The scoping System\'s CreationClassName.")] + public string SystemCreationClassName { + get { + return ((string)(curObj["SystemCreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The scoping System\'s Name.")] + public string SystemName { + get { + return ((string)(curObj["SystemName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("A globally unique identifier for the processor. This identifier may only be uniq" + + "ue within a processor family.")] + public string UniqueId { + get { + return ((string)(curObj["UniqueId"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsUpgradeMethodNull { + get { + if ((curObj["UpgradeMethod"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("CPU socket information including data on how this Processor can be upgraded (if u" + + "pgrades are supported). This property is an integer enumeration.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public UpgradeMethodValues UpgradeMethod { + get { + if ((curObj["UpgradeMethod"] == null)) { + return ((UpgradeMethodValues)(System.Convert.ToInt32(0))); + } + return ((UpgradeMethodValues)(System.Convert.ToInt32(curObj["UpgradeMethod"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Version property specifies an architecture-dependent processor revision numbe" + + "r. Note: This member is not used in Windows 95.\nExample: Model 2, Stepping 12.")] + public string Version { + get { + return ((string)(curObj["Version"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualizationFirmwareEnabledNull { + get { + if ((curObj["VirtualizationFirmwareEnabled"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The VirtualizationFirmwareEnabled property determines whether the Firmware has en" + + "abled virtualization extensions.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool VirtualizationFirmwareEnabled { + get { + if ((curObj["VirtualizationFirmwareEnabled"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["VirtualizationFirmwareEnabled"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVMMonitorModeExtensionsNull { + get { + if ((curObj["VMMonitorModeExtensions"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The VMMonitorModeExtensions property determines whether the processor supports In" + + "tel or AMD Virtual Machine Monitor extensions.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool VMMonitorModeExtensions { + get { + if ((curObj["VMMonitorModeExtensions"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["VMMonitorModeExtensions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVoltageCapsNull { + get { + if ((curObj["VoltageCaps"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The VoltageCaps property specifies the voltage capabilities of the processor. Bits 0-3 of the field represent specific voltages that the processor socket can accept. All other bits should be set to zero. The socket is configurable if multiple bits are being set. For a range of voltages see CurrentVoltage. If the property is NULL, then the voltage capabilities are unknown.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public VoltageCapsValues VoltageCaps { + get { + if ((curObj["VoltageCaps"] == null)) { + return ((VoltageCapsValues)(System.Convert.ToInt32(8))); + } + return ((VoltageCapsValues)(System.Convert.ToInt32(curObj["VoltageCaps"]))); + } + } + + 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 ShouldSerializeAddressWidth() { + if ((this.IsAddressWidthNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeArchitecture() { + if ((this.IsArchitectureNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAvailability() { + if ((this.IsAvailabilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConfigManagerErrorCode() { + if ((this.IsConfigManagerErrorCodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConfigManagerUserConfig() { + if ((this.IsConfigManagerUserConfigNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeCpuStatus() { + if ((this.IsCpuStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeCurrentClockSpeed() { + if ((this.IsCurrentClockSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeCurrentVoltage() { + if ((this.IsCurrentVoltageNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDataWidth() { + if ((this.IsDataWidthNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeErrorCleared() { + if ((this.IsErrorClearedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeExtClock() { + if ((this.IsExtClockNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeFamily() { + if ((this.IsFamilyNull == 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 ShouldSerializeL2CacheSize() { + if ((this.IsL2CacheSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeL2CacheSpeed() { + if ((this.IsL2CacheSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeL3CacheSize() { + if ((this.IsL3CacheSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeL3CacheSpeed() { + if ((this.IsL3CacheSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastErrorCode() { + if ((this.IsLastErrorCodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLevel() { + if ((this.IsLevelNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLoadPercentage() { + if ((this.IsLoadPercentageNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxClockSpeed() { + if ((this.IsMaxClockSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeNumberOfCores() { + if ((this.IsNumberOfCoresNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeNumberOfLogicalProcessors() { + if ((this.IsNumberOfLogicalProcessorsNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerManagementSupported() { + if ((this.IsPowerManagementSupportedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeProcessorType() { + if ((this.IsProcessorTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRevision() { + if ((this.IsRevisionNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSecondLevelAddressTranslationExtensions() { + if ((this.IsSecondLevelAddressTranslationExtensionsNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStatusInfo() { + if ((this.IsStatusInfoNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeUpgradeMethod() { + if ((this.IsUpgradeMethodNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualizationFirmwareEnabled() { + if ((this.IsVirtualizationFirmwareEnabledNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVMMonitorModeExtensions() { + if ((this.IsVMMonitorModeExtensionsNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVoltageCaps() { + if ((this.IsVoltageCapsNull == 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 keyDeviceID) { + string strPath = "ROOT\\CIMV2:Win32_Processor"; + strPath = string.Concat(strPath, string.Concat(".DeviceID=", string.Concat("\"", string.Concat(keyDeviceID, "\"")))); + 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 ProcessorCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ProcessorCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ProcessorCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ProcessorCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ProcessorCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\CIMV2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Win32_Processor"; + pathObj.NamespacePath = "root\\CIMV2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new ProcessorCollection(clsObject.GetInstances(enumOptions)); + } + + public static ProcessorCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ProcessorCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ProcessorCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\CIMV2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Win32_Processor", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ProcessorCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static Processor 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 Processor(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint Reset() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reset", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SetPowerState(ushort PowerState, System.DateTime Time) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); + inParams["PowerState"] = ((ushort)(PowerState)); + inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public enum ArchitectureValues { + + X86 = 0, + + MIPS = 1, + + Alpha = 2, + + PowerPC = 3, + + Ia64 = 6, + + X64 = 9, + + NULL_ENUM_VALUE = 10, + } + + public enum AvailabilityValues { + + Other0 = 1, + + Unknown0 = 2, + + Running_Full_Power = 3, + + Warning = 4, + + In_Test = 5, + + Not_Applicable = 6, + + Power_Off = 7, + + Off_Line = 8, + + Off_Duty = 9, + + Degraded = 10, + + Not_Installed = 11, + + Install_Error = 12, + + Power_Save_Unknown = 13, + + Power_Save_Low_Power_Mode = 14, + + Power_Save_Standby = 15, + + Power_Cycle = 16, + + Power_Save_Warning = 17, + + Paused = 18, + + Not_Ready = 19, + + Not_Configured = 20, + + Quiesced = 21, + + NULL_ENUM_VALUE = 0, + } + + public enum ConfigManagerErrorCodeValues { + + This_device_is_working_properly_ = 0, + + This_device_is_not_configured_correctly_ = 1, + + Windows_cannot_load_the_driver_for_this_device_ = 2, + + The_driver_for_this_device_might_be_corrupted_or_your_system_may_be_running_low_on_memory_or_other_resources_ = 3, + + This_device_is_not_working_properly_One_of_its_drivers_or_your_registry_might_be_corrupted_ = 4, + + The_driver_for_this_device_needs_a_resource_that_Windows_cannot_manage_ = 5, + + The_boot_configuration_for_this_device_conflicts_with_other_devices_ = 6, + + Cannot_filter_ = 7, + + The_driver_loader_for_the_device_is_missing_ = 8, + + This_device_is_not_working_properly_because_the_controlling_firmware_is_reporting_the_resources_for_the_device_incorrectly_ = 9, + + This_device_cannot_start_ = 10, + + This_device_failed_ = 11, + + This_device_cannot_find_enough_free_resources_that_it_can_use_ = 12, + + Windows_cannot_verify_this_device_s_resources_ = 13, + + This_device_cannot_work_properly_until_you_restart_your_computer_ = 14, + + This_device_is_not_working_properly_because_there_is_probably_a_re_enumeration_problem_ = 15, + + Windows_cannot_identify_all_the_resources_this_device_uses_ = 16, + + This_device_is_asking_for_an_unknown_resource_type_ = 17, + + Reinstall_the_drivers_for_this_device_ = 18, + + Failure_using_the_VxD_loader_ = 19, + + Your_registry_might_be_corrupted_ = 20, + + System_failure_Try_changing_the_driver_for_this_device_If_that_does_not_work_see_your_hardware_documentation_Windows_is_removing_this_device_ = 21, + + This_device_is_disabled_ = 22, + + System_failure_Try_changing_the_driver_for_this_device_If_that_doesn_t_work_see_your_hardware_documentation_ = 23, + + This_device_is_not_present_is_not_working_properly_or_does_not_have_all_its_drivers_installed_ = 24, + + Windows_is_still_setting_up_this_device_ = 25, + + Windows_is_still_setting_up_this_device_0 = 26, + + This_device_does_not_have_valid_log_configuration_ = 27, + + The_drivers_for_this_device_are_not_installed_ = 28, + + This_device_is_disabled_because_the_firmware_of_the_device_did_not_give_it_the_required_resources_ = 29, + + This_device_is_using_an_Interrupt_Request_IRQ_resource_that_another_device_is_using_ = 30, + + This_device_is_not_working_properly_because_Windows_cannot_load_the_drivers_required_for_this_device_ = 31, + + NULL_ENUM_VALUE = 32, + } + + public enum CpuStatusValues { + + Unknown0 = 0, + + CPU_Enabled = 1, + + CPU_Disabled_by_User_via_BIOS_Setup = 2, + + CPU_Disabled_By_BIOS_POST_Error_ = 3, + + CPU_is_Idle = 4, + + Reserved = 5, + + Reserved0 = 6, + + Other0 = 7, + + NULL_ENUM_VALUE = 8, + } + + public enum FamilyValues { + + Other0 = 1, + + Unknown0 = 2, + + Val_8086 = 3, + + Val_80286 = 4, + + Val_80386 = 5, + + Val_80486 = 6, + + Val_8087 = 7, + + Val_80287 = 8, + + Val_80387 = 9, + + Val_80487 = 10, + + Pentium_R_brand = 11, + + Pentium_R_Pro = 12, + + Pentium_R_II = 13, + + Pentium_R_processor_with_MMX_TM_technology = 14, + + Celeron_TM_ = 15, + + Pentium_R_II_Xeon_TM_ = 16, + + Pentium_R_III = 17, + + M1_Family = 18, + + M2_Family = 19, + + K5_Family = 24, + + K6_Family = 25, + + K6_2 = 26, + + K6_3 = 27, + + AMD_Athlon_TM_Processor_Family = 28, + + AMD_R_Duron_TM_Processor = 29, + + AMD29000_Family = 30, + + K6_2_ = 31, + + Power_PC_Family = 32, + + Power_PC_601 = 33, + + Power_PC_603 = 34, + + Power_PC_603_ = 35, + + Power_PC_604 = 36, + + Power_PC_620 = 37, + + Power_PC_X704 = 38, + + Power_PC_750 = 39, + + Alpha_Family = 48, + + Alpha_21064 = 49, + + Alpha_21066 = 50, + + Alpha_21164 = 51, + + Alpha_21164PC = 52, + + Alpha_21164a = 53, + + Alpha_21264 = 54, + + Alpha_21364 = 55, + + MIPS_Family = 64, + + MIPS_R4000 = 65, + + MIPS_R4200 = 66, + + MIPS_R4400 = 67, + + MIPS_R4600 = 68, + + MIPS_R10000 = 69, + + SPARC_Family = 80, + + SuperSPARC = 81, + + MicroSPARC_II = 82, + + MicroSPARC_IIep = 83, + + UltraSPARC = 84, + + UltraSPARC_II = 85, + + UltraSPARC_IIi = 86, + + UltraSPARC_III0 = 87, + + UltraSPARC_IIIi = 88, + + Val_68040 = 96, + + Val_68xxx_Family = 97, + + Val_68000 = 98, + + Val_68010 = 99, + + Val_68020 = 100, + + Val_68030 = 101, + + Hobbit_Family = 112, + + Crusoe_TM_TM5000_Family = 120, + + Crusoe_TM_TM3000_Family = 121, + + Efficeon_TM_TM8000_Family = 122, + + Weitek = 128, + + Itanium_TM_Processor = 130, + + AMD_Athlon_TM_64_Processor_Family = 131, + + AMD_Opteron_TM_Family = 132, + + PA_RISC_Family = 144, + + PA_RISC_8500 = 145, + + PA_RISC_8000 = 146, + + PA_RISC_7300LC = 147, + + PA_RISC_7200 = 148, + + PA_RISC_7100LC = 149, + + PA_RISC_7100 = 150, + + V30_Family = 160, + + Pentium_R_III_Xeon_TM_ = 176, + + Pentium_R_III_Processor_with_Intel_R_SpeedStep_TM_Technology = 177, + + Pentium_R_4 = 178, + + Intel_R_Xeon_TM_ = 179, + + AS400_Family = 180, + + Intel_R_Xeon_TM_processor_MP = 181, + + AMD_AthlonXP_TM_Family = 182, + + AMD_AthlonMP_TM_Family = 183, + + Intel_R_Itanium_R_2 = 184, + + Intel_Pentium_M_Processor = 185, + + K7 = 190, + + IBM390_Family = 200, + + G4 = 201, + + G5 = 202, + + G6 = 203, + + Z_Architecture_base = 204, + + I860 = 250, + + I960 = 251, + + SH_3 = 260, + + SH_4 = 261, + + ARM = 280, + + StrongARM = 281, + + Val_6x86 = 300, + + MediaGX = 301, + + MII = 302, + + WinChip = 320, + + DSP = 350, + + Video_Processor = 500, + + NULL_ENUM_VALUE = 0, + } + + public enum PowerManagementCapabilitiesValues { + + Unknown0 = 0, + + Not_Supported = 1, + + Disabled = 2, + + Enabled = 3, + + Power_Saving_Modes_Entered_Automatically = 4, + + Power_State_Settable = 5, + + Power_Cycling_Supported = 6, + + Timed_Power_On_Supported = 7, + + NULL_ENUM_VALUE = 8, + } + + public enum ProcessorTypeValues { + + Other0 = 1, + + Unknown0 = 2, + + Central_Processor = 3, + + Math_Processor = 4, + + DSP_Processor = 5, + + Video_Processor = 6, + + NULL_ENUM_VALUE = 0, + } + + public enum StatusInfoValues { + + Other0 = 1, + + Unknown0 = 2, + + Enabled = 3, + + Disabled = 4, + + Not_Applicable = 5, + + NULL_ENUM_VALUE = 0, + } + + public enum UpgradeMethodValues { + + Other0 = 1, + + Unknown0 = 2, + + Daughter_Board = 3, + + ZIF_Socket = 4, + + Replacement_Piggy_Back = 5, + + None = 6, + + LIF_Socket = 7, + + Slot_1 = 8, + + Slot_2 = 9, + + Val_370_Pin_Socket = 10, + + Slot_A = 11, + + Slot_M = 12, + + Socket_423 = 13, + + Socket_A_Socket_462_ = 14, + + Socket_478 = 15, + + Socket_754 = 16, + + Socket_940 = 17, + + Socket_939 = 18, + + NULL_ENUM_VALUE = 0, + } + + public enum VoltageCapsValues { + + Val_5 = 1, + + Val_3_3 = 2, + + Val_2_9 = 4, + + NULL_ENUM_VALUE = 8, + } + + // Enumerator implementation for enumerating instances of the class. + public class ProcessorCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ProcessorCollection(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 Processor(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ProcessorEnumerator(privColObj.GetEnumerator()); + } + + public class ProcessorEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ProcessorEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new Processor(((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_ComputerSystem.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ComputerSystem.cs new file mode 100644 index 00000000000..76057138f71 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ComputerSystem.cs @@ -0,0 +1,1818 @@ +// 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_ComputerSystem + public class ComputerSystem : 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. + private static string CreatedClassName = "Msvm_ComputerSystem"; + + // 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 ComputerSystem() { + this.InitializeObject(null, null, null); + } + + public ComputerSystem(string keyCreationClassName, string keyName) { + this.InitializeObject(null, new System.Management.ManagementPath(ComputerSystem.ConstructPath(keyCreationClassName, keyName)), null); + } + + public ComputerSystem(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ComputerSystem.ConstructPath(keyCreationClassName, keyName)), null); + } + + public ComputerSystem(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public ComputerSystem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public ComputerSystem(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public ComputerSystem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public ComputerSystem(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 ComputerSystem(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(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 ushort[] Dedicated { + get { + return ((ushort[])(curObj["Dedicated"])); + } + } + + [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 IsFailedOverReplicationTypeNull { + get { + if ((curObj["FailedOverReplicationType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Type of failover that was performed for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public FailedOverReplicationTypeValues FailedOverReplicationType { + get { + if ((curObj["FailedOverReplicationType"] == null)) { + return ((FailedOverReplicationTypeValues)(System.Convert.ToInt32(4))); + } + return ((FailedOverReplicationTypeValues)(System.Convert.ToInt32(curObj["FailedOverReplicationType"]))); + } + } + + [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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] IdentifyingDescriptions { + get { + return ((string[])(curObj["IdentifyingDescriptions"])); + } + } + + [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 IsLastApplicationConsistentReplicationTimeNull { + get { + if ((curObj["LastApplicationConsistentReplicationTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The time at which the last application consistent replication is received on reco" + + "very for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime LastApplicationConsistentReplicationTime { + get { + if ((curObj["LastApplicationConsistentReplicationTime"] != null)) { + return ToDateTime(((string)(curObj["LastApplicationConsistentReplicationTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastReplicationTimeNull { + get { + if ((curObj["LastReplicationTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The time at which the last replication is received on recovery for the virtual ma" + + "chine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime LastReplicationTime { + get { + if ((curObj["LastReplicationTime"] != null)) { + return ToDateTime(((string)(curObj["LastReplicationTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastReplicationTypeNull { + get { + if ((curObj["LastReplicationType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Type of the last replication that was received for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public LastReplicationTypeValues LastReplicationType { + get { + if ((curObj["LastReplicationType"] == null)) { + return ((LastReplicationTypeValues)(System.Convert.ToInt32(4))); + } + return ((LastReplicationTypeValues)(System.Convert.ToInt32(curObj["LastReplicationType"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastSuccessfulBackupTimeNull { + get { + if ((curObj["LastSuccessfulBackupTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The time at which the last successful backup has completed for the virtual machin" + + "e.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime LastSuccessfulBackupTime { + get { + if ((curObj["LastSuccessfulBackupTime"] != null)) { + return ToDateTime(((string)(curObj["LastSuccessfulBackupTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string NameFormat { + get { + return ((string)(curObj["NameFormat"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNumberOfNumaNodesNull { + get { + if ((curObj["NumberOfNumaNodes"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The number of non-uniform memory access (NUMA) nodes of the computer system. When Msvm_ComputerSystem represents the hosting computer system, this property contains the count of physical NUMA nodes. When Msvm_ComputerSystem represents a virtual computer system, this property contains the number of virtual NUMA nodes that are presented to the guest OS through the ACPI System Resource Affinity Table (SRAT).")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort NumberOfNumaNodes { + get { + if ((curObj["NumberOfNumaNodes"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["NumberOfNumaNodes"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOnTimeInMillisecondsNull { + get { + if ((curObj["OnTimeInMilliseconds"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"For the virtual system, this property describes the total up time, in milliseconds, since the machine was last turned on, reset, or restored. This time excludes the time the virtual system was in the paused state. For the host system, this property is set to NULL.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong OnTimeInMilliseconds { + get { + if ((curObj["OnTimeInMilliseconds"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["OnTimeInMilliseconds"])); + } + } + + [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[] OtherDedicatedDescriptions { + get { + return ((string[])(curObj["OtherDedicatedDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherIdentifyingInfo { + get { + return ((string[])(curObj["OtherIdentifyingInfo"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] PowerManagementCapabilities { + get { + return ((ushort[])(curObj["PowerManagementCapabilities"])); + } + } + + [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 IsProcessIDNull { + get { + if ((curObj["ProcessID"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The identifier of the process under which this virtual machine is running. This v" + + "alue can be used to uniquely identify the instance of Vmwp.exe on the system tha" + + "t is running the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint ProcessID { + get { + if ((curObj["ProcessID"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["ProcessID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReplicationHealthNull { + get { + if ((curObj["ReplicationHealth"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Replication health for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ReplicationHealthValues ReplicationHealth { + get { + if ((curObj["ReplicationHealth"] == null)) { + return ((ReplicationHealthValues)(System.Convert.ToInt32(4))); + } + return ((ReplicationHealthValues)(System.Convert.ToInt32(curObj["ReplicationHealth"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReplicationModeNull { + get { + if ((curObj["ReplicationMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Identifies replication type for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ReplicationModeValues ReplicationMode { + get { + if ((curObj["ReplicationMode"] == null)) { + return ((ReplicationModeValues)(System.Convert.ToInt32(4))); + } + return ((ReplicationModeValues)(System.Convert.ToInt32(curObj["ReplicationMode"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReplicationStateNull { + get { + if ((curObj["ReplicationState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Replication state for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ReplicationStateValues ReplicationState { + get { + if ((curObj["ReplicationState"] == null)) { + return ((ReplicationStateValues)(System.Convert.ToInt32(12))); + } + return ((ReplicationStateValues)(System.Convert.ToInt32(curObj["ReplicationState"]))); + } + } + + [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 IsResetCapabilityNull { + get { + if ((curObj["ResetCapability"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResetCapability { + get { + if ((curObj["ResetCapability"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResetCapability"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Roles { + get { + return ((string[])(curObj["Roles"])); + } + } + + [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 IsTimeOfLastConfigurationChangeNull { + get { + if ((curObj["TimeOfLastConfigurationChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The date and time when the virtual machine configuration file was last modified. " + + "The configuration file is modified during certain virtual machine operations, as" + + " well as when any of the virtual machine or device settings are added, modified," + + " or removed.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastConfigurationChange { + get { + if ((curObj["TimeOfLastConfigurationChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastConfigurationChange"]))); + } + 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 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 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 ShouldSerializeFailedOverReplicationType() { + if ((this.IsFailedOverReplicationTypeNull == 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 ShouldSerializeLastApplicationConsistentReplicationTime() { + if ((this.IsLastApplicationConsistentReplicationTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastReplicationTime() { + if ((this.IsLastReplicationTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastReplicationType() { + if ((this.IsLastReplicationTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastSuccessfulBackupTime() { + if ((this.IsLastSuccessfulBackupTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeNumberOfNumaNodes() { + if ((this.IsNumberOfNumaNodesNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOnTimeInMilliseconds() { + if ((this.IsOnTimeInMillisecondsNull == 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 ShouldSerializeProcessID() { + if ((this.IsProcessIDNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReplicationHealth() { + if ((this.IsReplicationHealthNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReplicationMode() { + if ((this.IsReplicationModeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReplicationState() { + if ((this.IsReplicationStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResetCapability() { + if ((this.IsResetCapabilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastConfigurationChange() { + if ((this.IsTimeOfLastConfigurationChangeNull == 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 strPath = "ROOT\\virtualization\\v2:Msvm_ComputerSystem"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); + 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 ComputerSystemCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ComputerSystemCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ComputerSystemCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ComputerSystemCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ComputerSystemCollection 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_ComputerSystem"; + 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 ComputerSystemCollection(clsObject.GetInstances(enumOptions)); + } + + public static ComputerSystemCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ComputerSystemCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ComputerSystemCollection 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_ComputerSystem", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ComputerSystemCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static ComputerSystem 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 ComputerSystem(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint RequestReplicationStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestReplicationStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestReplicationStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.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"] = RequestedState; + inParams["TimeoutPeriod"] = null; // ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) + { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint SetPowerState(uint PowerState, System.DateTime Time) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); + inParams["PowerState"] = ((uint)(PowerState)); + inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public enum FailedOverReplicationTypeValues { + + None = 0, + + Regular = 1, + + Application_consistent = 2, + + Planned = 3, + + NULL_ENUM_VALUE = 4, + } + + public enum LastReplicationTypeValues { + + None = 0, + + Regular = 1, + + Application_consistent = 2, + + Planned = 3, + + NULL_ENUM_VALUE = 4, + } + + public enum ReplicationHealthValues { + + Not_applicable = 0, + + Ok = 1, + + Warning = 2, + + Critical = 3, + + NULL_ENUM_VALUE = 4, + } + + public enum ReplicationModeValues { + + None = 0, + + Primary = 1, + + Recovery = 2, + + Test_Replica = 3, + + NULL_ENUM_VALUE = 4, + } + + public enum ReplicationStateValues { + + Disabled = 0, + + Ready_for_replication = 1, + + Waiting_to_complete_initial_replication = 2, + + Replicating = 3, + + Synced_replication_complete = 4, + + Recovered = 5, + + Committed = 6, + + Suspended = 7, + + Critical = 8, + + Waiting_to_start_resynchronization = 9, + + Resynchronizing = 10, + + Resynchronization_suspended = 11, + + NULL_ENUM_VALUE = 12, + } + + // Enumerator implementation for enumerating instances of the class. + public class ComputerSystemCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ComputerSystemCollection(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 ComputerSystem(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ComputerSystemEnumerator(privColObj.GetEnumerator()); + } + + public class ComputerSystemEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ComputerSystemEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new ComputerSystem(((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_ConcreteJob.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ConcreteJob.cs new file mode 100644 index 00000000000..823e41482bc --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ConcreteJob.cs @@ -0,0 +1,1843 @@ +// 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. + // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. + // 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_ConcreteJob + public class ConcreteJob : 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. + private static string CreatedClassName = "Msvm_ConcreteJob"; + + // 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 ConcreteJob() { + this.InitializeObject(null, null, null); + } + + public ConcreteJob(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(ConcreteJob.ConstructPath(keyInstanceID)), null); + } + + public ConcreteJob(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ConcreteJob.ConstructPath(keyInstanceID)), null); + } + + public ConcreteJob(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public ConcreteJob(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public ConcreteJob(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public ConcreteJob(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public ConcreteJob(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 ConcreteJob(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(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.TimeSpan ElapsedTime { + get { + if ((curObj["ElapsedTime"] != null)) { + return ToTimeSpan(((string)(curObj["ElapsedTime"]))); + } + else { + return new System.TimeSpan(0, 0, 0, 0, 0); + } + } + } + + [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 ushort JobType { + get { + if ((curObj["JobType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(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(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.TimeSpan RunStartInterval { + get { + if ((curObj["RunStartInterval"] != null)) { + return ToTimeSpan(((string)(curObj["RunStartInterval"]))); + } + else { + return new System.TimeSpan(0, 0, 0, 0, 0); + } + } + } + + [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.TimeSpan TimeBeforeRemoval { + get { + if ((curObj["TimeBeforeRemoval"] != null)) { + return ToTimeSpan(((string)(curObj["TimeBeforeRemoval"]))); + } + else { + return new System.TimeSpan(0, 0, 0, 0, 0); + } + } + } + + [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; + } + + // Converts a given time interval in DMTF format to System.TimeSpan object. + static System.TimeSpan ToTimeSpan(string dmtfTimespan) { + int days = 0; + int hours = 0; + int minutes = 0; + int seconds = 0; + long ticks = 0; + if ((dmtfTimespan == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtfTimespan.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtfTimespan.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtfTimespan.Substring(21, 4) != ":000")) { + throw new System.ArgumentOutOfRangeException(); + } + try { + string tempString = string.Empty; + tempString = dmtfTimespan.Substring(0, 8); + days = int.Parse(tempString); + tempString = dmtfTimespan.Substring(8, 2); + hours = int.Parse(tempString); + tempString = dmtfTimespan.Substring(10, 2); + minutes = int.Parse(tempString); + tempString = dmtfTimespan.Substring(12, 2); + seconds = int.Parse(tempString); + tempString = dmtfTimespan.Substring(15, 6); + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); + System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); + timespan = timespan.Add(tsTemp); + return timespan; + } + + // Converts a given System.TimeSpan object to DMTF Time interval format. + static string ToDmtfTimeInterval(System.TimeSpan timespan) { + string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); + System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; + if ((timespan.Days > maxTimeSpan.Days)) { + throw new System.ArgumentOutOfRangeException(); + } + System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; + if ((timespan.Days < minTimeSpan.Days)) { + throw new System.ArgumentOutOfRangeException(); + } + dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); + dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); + dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); + dmtftimespan = string.Concat(dmtftimespan, "."); + System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); + long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicroSec = ((long)(microsec)).ToString(); + if ((strMicroSec.Length > 6)) { + strMicroSec = strMicroSec.Substring(0, 6); + } + dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); + dmtftimespan = string.Concat(dmtftimespan, ":000"); + return dmtftimespan; + } + + 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 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_ConcreteJob"; + 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 ConcreteJobCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ConcreteJobCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ConcreteJobCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ConcreteJobCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ConcreteJobCollection 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_ConcreteJob"; + 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 ConcreteJobCollection(clsObject.GetInstances(enumOptions)); + } + + public static ConcreteJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ConcreteJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ConcreteJobCollection 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_ConcreteJob", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ConcreteJobCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static ConcreteJob 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 ConcreteJob(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.TimeSpan TimeoutPeriod) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfTimeInterval(((System.TimeSpan)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", 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 ConcreteJobCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ConcreteJobCollection(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 ConcreteJob(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ConcreteJobEnumerator(privColObj.GetEnumerator()); + } + + public class ConcreteJobEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ConcreteJobEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new ConcreteJob(((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_EthernetPortAllocationSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetPortAllocationSettingData.cs new file mode 100644 index 00000000000..f281def4b10 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetPortAllocationSettingData.cs @@ -0,0 +1,1164 @@ +// 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_EthernetPortAllocationSettingData + public class EthernetPortAllocationSettingData : 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_EthernetPortAllocationSettingData"; + + // 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 EthernetPortAllocationSettingData() { + this.InitializeObject(null, null, null); + } + + public EthernetPortAllocationSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(EthernetPortAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(EthernetPortAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public EthernetPortAllocationSettingData(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 EthernetPortAllocationSettingData(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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDesiredVLANEndpointModeNull { + get { + if ((curObj["DesiredVLANEndpointMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DesiredVLANEndpointMode { + get { + if ((curObj["DesiredVLANEndpointMode"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DesiredVLANEndpointMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"EnabledState is an integer enumeration that indicates whether the allocation request is enabled or disabled. When an allocation request is marked as Disabled (3), then the allocation is not processed. The EnabledState for an active configuration is always marked as Enabled (2).")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public EnabledStateValues EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return ((EnabledStateValues)(System.Convert.ToInt32(0))); + } + return ((EnabledStateValues)(System.Convert.ToInt32(curObj["EnabledState"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEndpointMode { + get { + return ((string)(curObj["OtherEndpointMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The list of friendly names corresponding to each entry in the RequiredFeatures.")] + public string[] RequiredFeatureHints { + get { + return ((string[])(curObj["RequiredFeatureHints"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The list of feature identifers representing all the features that are required fo" + + "r a port.")] + public string[] RequiredFeatures { + get { + return ((string[])(curObj["RequiredFeatures"])); + } + set { + curObj["RequiredFeatures"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("This property specifies the network resource pool from which a connection will be" + + " allocated to test replica system when it is created.")] + public string TestReplicaPoolID { + get { + return ((string)(curObj["TestReplicaPoolID"])); + } + set { + curObj["TestReplicaPoolID"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("This property specifies the friendly name of the virtual network switch to which " + + "a connection will be allocated for the test replica system when it is created.")] + public string TestReplicaSwitchName { + get { + return ((string)(curObj["TestReplicaSwitchName"])); + } + set { + curObj["TestReplicaSwitchName"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + 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 ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDesiredVLANEndpointMode() { + if ((this.IsDesiredVLANEndpointModeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private void ResetRequiredFeatures() { + curObj["RequiredFeatures"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private void ResetTestReplicaPoolID() { + curObj["TestReplicaPoolID"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetTestReplicaSwitchName() { + curObj["TestReplicaSwitchName"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == 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_EthernetPortAllocationSettingData"; + 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 EthernetPortAllocationSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static EthernetPortAllocationSettingDataCollection 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_EthernetPortAllocationSettingData"; + 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 EthernetPortAllocationSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static EthernetPortAllocationSettingDataCollection 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_EthernetPortAllocationSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new EthernetPortAllocationSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static EthernetPortAllocationSettingData 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 EthernetPortAllocationSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public enum EnabledStateValues { + + Enabled = 2, + + Disabled = 3, + + NULL_ENUM_VALUE = 0, + } + + // Enumerator implementation for enumerating instances of the class. + public class EthernetPortAllocationSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public EthernetPortAllocationSettingDataCollection(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 EthernetPortAllocationSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new EthernetPortAllocationSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class EthernetPortAllocationSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public EthernetPortAllocationSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new EthernetPortAllocationSettingData(((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_EthernetSwitchPort.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPort.cs new file mode 100644 index 00000000000..5bc97f864bb --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPort.cs @@ -0,0 +1,2119 @@ +// 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_EthernetSwitchPort + public class EthernetSwitchPort : 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_EthernetSwitchPort"; + + // 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 EthernetSwitchPort() { + this.InitializeObject(null, null, null); + } + + public EthernetSwitchPort(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(EthernetSwitchPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); + } + + public EthernetSwitchPort(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(EthernetSwitchPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); + } + + public EthernetSwitchPort(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public EthernetSwitchPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public EthernetSwitchPort(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public EthernetSwitchPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public EthernetSwitchPort(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 EthernetSwitchPort(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 IsActiveMaximumTransmissionUnitNull { + get { + if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong ActiveMaximumTransmissionUnit { + get { + if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["ActiveMaximumTransmissionUnit"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AdditionalAvailability { + get { + return ((ushort[])(curObj["AdditionalAvailability"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutoSenseNull { + get { + if ((curObj["AutoSense"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutoSense { + get { + if ((curObj["AutoSense"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutoSense"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAvailabilityNull { + get { + if ((curObj["Availability"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Availability { + get { + if ((curObj["Availability"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Availability"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] Capabilities { + get { + return ((ushort[])(curObj["Capabilities"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] CapabilityDescriptions { + get { + return ((string[])(curObj["CapabilityDescriptions"])); + } + } + + [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 DeviceID { + get { + return ((string)(curObj["DeviceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] EnabledCapabilities { + get { + return ((ushort[])(curObj["EnabledCapabilities"])); + } + } + + [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 IsErrorClearedNull { + get { + if ((curObj["ErrorCleared"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool ErrorCleared { + get { + if ((curObj["ErrorCleared"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["ErrorCleared"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ErrorDescription { + get { + return ((string)(curObj["ErrorDescription"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFullDuplexNull { + get { + if ((curObj["FullDuplex"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool FullDuplex { + get { + if ((curObj["FullDuplex"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["FullDuplex"])); + } + } + + [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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] IdentifyingDescriptions { + get { + return ((string[])(curObj["IdentifyingDescriptions"])); + } + } + + [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 IsIOVOffloadUsageNull { + get { + if ((curObj["IOVOffloadUsage"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current I/O virtualization (IOV) offload usage on this port. The usage is the" + + "amount of IOV resources in use on the port.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint IOVOffloadUsage { + get { + if ((curObj["IOVOffloadUsage"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["IOVOffloadUsage"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastErrorCodeNull { + get { + if ((curObj["LastErrorCode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint LastErrorCode { + get { + if ((curObj["LastErrorCode"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["LastErrorCode"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLinkTechnologyNull { + get { + if ((curObj["LinkTechnology"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort LinkTechnology { + get { + if ((curObj["LinkTechnology"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["LinkTechnology"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxDataSizeNull { + get { + if ((curObj["MaxDataSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxDataSize { + get { + if ((curObj["MaxDataSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxDataSize"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxQuiesceTimeNull { + get { + if ((curObj["MaxQuiesceTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxQuiesceTime { + get { + if ((curObj["MaxQuiesceTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxQuiesceTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxSpeedNull { + get { + if ((curObj["MaxSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxSpeed { + get { + if ((curObj["MaxSpeed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxSpeed"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] NetworkAddresses { + get { + return ((string[])(curObj["NetworkAddresses"])); + } + } + + [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[] OtherEnabledCapabilities { + get { + return ((string[])(curObj["OtherEnabledCapabilities"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherIdentifyingInfo { + get { + return ((string[])(curObj["OtherIdentifyingInfo"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherLinkTechnology { + get { + return ((string)(curObj["OtherLinkTechnology"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherNetworkPortType { + get { + return ((string)(curObj["OtherNetworkPortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherPortType { + get { + return ((string)(curObj["OtherPortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PermanentAddress { + get { + return ((string)(curObj["PermanentAddress"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPortNumberNull { + get { + if ((curObj["PortNumber"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PortNumber { + get { + if ((curObj["PortNumber"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PortNumber"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPortTypeNull { + get { + if ((curObj["PortType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PortType { + get { + if ((curObj["PortType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] PowerManagementCapabilities { + get { + return ((ushort[])(curObj["PowerManagementCapabilities"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerManagementSupportedNull { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool PowerManagementSupported { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["PowerManagementSupported"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerOnHoursNull { + get { + if ((curObj["PowerOnHours"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PowerOnHours { + get { + if ((curObj["PowerOnHours"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PowerOnHours"])); + } + } + + [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 IsRequestedSpeedNull { + get { + if ((curObj["RequestedSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong RequestedSpeed { + get { + if ((curObj["RequestedSpeed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["RequestedSpeed"])); + } + } + + [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 IsSpeedNull { + get { + if ((curObj["Speed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Speed { + get { + if ((curObj["Speed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Speed"])); + } + } + + [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 IsStatusInfoNull { + get { + if ((curObj["StatusInfo"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort StatusInfo { + get { + if ((curObj["StatusInfo"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["StatusInfo"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSupportedMaximumTransmissionUnitNull { + get { + if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong SupportedMaximumTransmissionUnit { + get { + if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["SupportedMaximumTransmissionUnit"])); + } + } + + [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 IsTotalPowerOnHoursNull { + get { + if ((curObj["TotalPowerOnHours"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong TotalPowerOnHours { + get { + if ((curObj["TotalPowerOnHours"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["TotalPowerOnHours"])); + } + } + + [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"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsUsageRestrictionNull { + get { + if ((curObj["UsageRestriction"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort UsageRestriction { + get { + if ((curObj["UsageRestriction"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["UsageRestriction"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVMQOffloadUsageNull { + get { + if ((curObj["VMQOffloadUsage"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current VMQ offloading usage on this port. The usage is the amount of VMQ res" + + "ources in use on the port.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint VMQOffloadUsage { + get { + if ((curObj["VMQOffloadUsage"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["VMQOffloadUsage"])); + } + } + + 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 ShouldSerializeActiveMaximumTransmissionUnit() { + if ((this.IsActiveMaximumTransmissionUnitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutoSense() { + if ((this.IsAutoSenseNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAvailability() { + if ((this.IsAvailabilityNull == 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 ShouldSerializeErrorCleared() { + if ((this.IsErrorClearedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeFullDuplex() { + if ((this.IsFullDuplexNull == 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 ShouldSerializeIOVOffloadUsage() { + if ((this.IsIOVOffloadUsageNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastErrorCode() { + if ((this.IsLastErrorCodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLinkTechnology() { + if ((this.IsLinkTechnologyNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxDataSize() { + if ((this.IsMaxDataSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxQuiesceTime() { + if ((this.IsMaxQuiesceTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxSpeed() { + if ((this.IsMaxSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePortNumber() { + if ((this.IsPortNumberNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePortType() { + if ((this.IsPortTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerManagementSupported() { + if ((this.IsPowerManagementSupportedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerOnHours() { + if ((this.IsPowerOnHoursNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedSpeed() { + if ((this.IsRequestedSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSpeed() { + if ((this.IsSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStatusInfo() { + if ((this.IsStatusInfoNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSupportedMaximumTransmissionUnit() { + if ((this.IsSupportedMaximumTransmissionUnitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTotalPowerOnHours() { + if ((this.IsTotalPowerOnHoursNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeUsageRestriction() { + if ((this.IsUsageRestrictionNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVMQOffloadUsage() { + if ((this.IsVMQOffloadUsageNull == 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 keyDeviceID, string keySystemCreationClassName, string keySystemName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_EthernetSwitchPort"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",DeviceID=", string.Concat("\"", string.Concat(keyDeviceID, "\"")))); + 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 EthernetSwitchPortCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static EthernetSwitchPortCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static EthernetSwitchPortCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static EthernetSwitchPortCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static EthernetSwitchPortCollection 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_EthernetSwitchPort"; + 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 EthernetSwitchPortCollection(clsObject.GetInstances(enumOptions)); + } + + public static EthernetSwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static EthernetSwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static EthernetSwitchPortCollection 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_EthernetSwitchPort", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new EthernetSwitchPortCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static EthernetSwitchPort 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 EthernetSwitchPort(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint EnableDevice(bool Enabled) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("EnableDevice"); + inParams["Enabled"] = ((bool)(Enabled)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("EnableDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint OnlineDevice(bool Online) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("OnlineDevice"); + inParams["Online"] = ((bool)(Online)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("OnlineDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint QuiesceDevice(bool Quiesce) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("QuiesceDevice"); + inParams["Quiesce"] = ((bool)(Quiesce)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("QuiesceDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + 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) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint Reset() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reset", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RestoreProperties() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RestoreProperties", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SaveProperties() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SaveProperties", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SetPowerState(ushort PowerState, System.DateTime Time) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); + inParams["PowerState"] = ((ushort)(PowerState)); + inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", 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 EthernetSwitchPortCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public EthernetSwitchPortCollection(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 EthernetSwitchPort(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new EthernetSwitchPortEnumerator(privColObj.GetEnumerator()); + } + + public class EthernetSwitchPortEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public EthernetSwitchPortEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new EthernetSwitchPort(((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_EthernetSwitchPortVlanSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPortVlanSettingData.cs new file mode 100644 index 00000000000..f95567cf954 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPortVlanSettingData.cs @@ -0,0 +1,1022 @@ +// 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_EthernetSwitchPortVlanSettingData + public class EthernetSwitchPortVlanSettingData : 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_EthernetSwitchPortVlanSettingData"; + + // 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 EthernetSwitchPortVlanSettingData() { + this.InitializeObject(null, null, null); + } + + public EthernetSwitchPortVlanSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(EthernetSwitchPortVlanSettingData.ConstructPath(keyInstanceID)), null); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(EthernetSwitchPortVlanSettingData.ConstructPath(keyInstanceID)), null); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public EthernetSwitchPortVlanSettingData(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 EthernetSwitchPortVlanSettingData(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 IsAccessVlanIdNull { + get { + if ((curObj["AccessVlanId"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The vlan ID in access mode.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort AccessVlanId { + get { + if ((curObj["AccessVlanId"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["AccessVlanId"])); + } + set { + curObj["AccessVlanId"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [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)] + 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 IsNativeVlanIdNull { + get { + if ((curObj["NativeVlanId"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The vlan ID in trunk mode.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort NativeVlanId { + get { + if ((curObj["NativeVlanId"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["NativeVlanId"])); + } + set { + curObj["NativeVlanId"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperationModeNull { + get { + if ((curObj["OperationMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The vlan operation modes.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public OperationModeValues OperationMode { + get { + if ((curObj["OperationMode"] == null)) { + return ((OperationModeValues)(System.Convert.ToInt32(0))); + } + return ((OperationModeValues)(System.Convert.ToInt32(curObj["OperationMode"]))); + } + set { + if ((OperationModeValues.NULL_ENUM_VALUE == value)) { + curObj["OperationMode"] = null; + } + else { + curObj["OperationMode"] = value; + } + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryVlanIdNull { + get { + if ((curObj["PrimaryVlanId"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The primary vlan ID in private mode.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryVlanId { + get { + if ((curObj["PrimaryVlanId"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryVlanId"])); + } + set { + curObj["PrimaryVlanId"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The prune vlan ID bitmap in trunk mode.")] + public ushort[] PruneVlanIdArray { + get { + return ((ushort[])(curObj["PruneVlanIdArray"])); + } + set { + curObj["PruneVlanIdArray"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPvlanModeNull { + get { + if ((curObj["PvlanMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The private vlan modes.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public PvlanModeValues PvlanMode { + get { + if ((curObj["PvlanMode"] == null)) { + return ((PvlanModeValues)(System.Convert.ToInt32(0))); + } + return ((PvlanModeValues)(System.Convert.ToInt32(curObj["PvlanMode"]))); + } + set { + if ((PvlanModeValues.NULL_ENUM_VALUE == value)) { + curObj["PvlanMode"] = null; + } + else { + curObj["PvlanMode"] = value; + } + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSecondaryVlanIdNull { + get { + if ((curObj["SecondaryVlanId"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The secondary vlan ID in private mode.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort SecondaryVlanId { + get { + if ((curObj["SecondaryVlanId"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["SecondaryVlanId"])); + } + set { + curObj["SecondaryVlanId"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The secondary vlan ID bitmap in private mode.")] + public ushort[] SecondaryVlanIdArray { + get { + return ((ushort[])(curObj["SecondaryVlanIdArray"])); + } + set { + curObj["SecondaryVlanIdArray"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The trunk vlan ID bitmap in trunk mode.")] + public ushort[] TrunkVlanIdArray { + get { + return ((ushort[])(curObj["TrunkVlanIdArray"])); + } + set { + curObj["TrunkVlanIdArray"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + 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 ShouldSerializeAccessVlanId() { + if ((this.IsAccessVlanIdNull == false)) { + return true; + } + return false; + } + + private void ResetAccessVlanId() { + curObj["AccessVlanId"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeNativeVlanId() { + if ((this.IsNativeVlanIdNull == false)) { + return true; + } + return false; + } + + private void ResetNativeVlanId() { + curObj["NativeVlanId"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeOperationMode() { + if ((this.IsOperationModeNull == false)) { + return true; + } + return false; + } + + private void ResetOperationMode() { + curObj["OperationMode"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializePrimaryVlanId() { + if ((this.IsPrimaryVlanIdNull == false)) { + return true; + } + return false; + } + + private void ResetPrimaryVlanId() { + curObj["PrimaryVlanId"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetPruneVlanIdArray() { + curObj["PruneVlanIdArray"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializePvlanMode() { + if ((this.IsPvlanModeNull == false)) { + return true; + } + return false; + } + + private void ResetPvlanMode() { + curObj["PvlanMode"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeSecondaryVlanId() { + if ((this.IsSecondaryVlanIdNull == false)) { + return true; + } + return false; + } + + private void ResetSecondaryVlanId() { + curObj["SecondaryVlanId"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetSecondaryVlanIdArray() { + curObj["SecondaryVlanIdArray"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetTrunkVlanIdArray() { + curObj["TrunkVlanIdArray"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + [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_EthernetSwitchPortVlanSettingData"; + 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 EthernetSwitchPortVlanSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static EthernetSwitchPortVlanSettingDataCollection 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_EthernetSwitchPortVlanSettingData"; + 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 EthernetSwitchPortVlanSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static EthernetSwitchPortVlanSettingDataCollection 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_EthernetSwitchPortVlanSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new EthernetSwitchPortVlanSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static EthernetSwitchPortVlanSettingData 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 EthernetSwitchPortVlanSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public enum OperationModeValues { + + Access = 1, + + Trunk = 2, + + Private = 3, + + NULL_ENUM_VALUE = 0, + } + + public enum PvlanModeValues { + + Isolated = 1, + + Community = 2, + + Promiscuous = 3, + + NULL_ENUM_VALUE = 0, + } + + // Enumerator implementation for enumerating instances of the class. + public class EthernetSwitchPortVlanSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public EthernetSwitchPortVlanSettingDataCollection(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 EthernetSwitchPortVlanSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new EthernetSwitchPortVlanSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class EthernetSwitchPortVlanSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public EthernetSwitchPortVlanSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new EthernetSwitchPortVlanSettingData(((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_ExternalEthernetPort.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ExternalEthernetPort.cs new file mode 100644 index 00000000000..1b6828621d0 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ExternalEthernetPort.cs @@ -0,0 +1,2087 @@ +// 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_ExternalEthernetPort + public class ExternalEthernetPort : 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. + private static string CreatedClassName = "Msvm_ExternalEthernetPort"; + + // 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 ExternalEthernetPort() { + this.InitializeObject(null, null, null); + } + + public ExternalEthernetPort(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(ExternalEthernetPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); + } + + public ExternalEthernetPort(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ExternalEthernetPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); + } + + public ExternalEthernetPort(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public ExternalEthernetPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public ExternalEthernetPort(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public ExternalEthernetPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public ExternalEthernetPort(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 ExternalEthernetPort(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 IsActiveMaximumTransmissionUnitNull { + get { + if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong ActiveMaximumTransmissionUnit { + get { + if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["ActiveMaximumTransmissionUnit"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AdditionalAvailability { + get { + return ((ushort[])(curObj["AdditionalAvailability"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutoSenseNull { + get { + if ((curObj["AutoSense"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutoSense { + get { + if ((curObj["AutoSense"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutoSense"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAvailabilityNull { + get { + if ((curObj["Availability"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Availability { + get { + if ((curObj["Availability"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Availability"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] Capabilities { + get { + return ((ushort[])(curObj["Capabilities"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] CapabilityDescriptions { + get { + return ((string[])(curObj["CapabilityDescriptions"])); + } + } + + [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 DeviceID { + get { + return ((string)(curObj["DeviceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] EnabledCapabilities { + get { + return ((ushort[])(curObj["EnabledCapabilities"])); + } + } + + [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 IsErrorClearedNull { + get { + if ((curObj["ErrorCleared"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool ErrorCleared { + get { + if ((curObj["ErrorCleared"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["ErrorCleared"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ErrorDescription { + get { + return ((string)(curObj["ErrorDescription"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFullDuplexNull { + get { + if ((curObj["FullDuplex"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool FullDuplex { + get { + if ((curObj["FullDuplex"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["FullDuplex"])); + } + } + + [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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] IdentifyingDescriptions { + get { + return ((string[])(curObj["IdentifyingDescriptions"])); + } + } + + [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 IsIsBoundNull { + get { + if ((curObj["IsBound"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("If this property is true, then this Ethernet port can be connected to the switche" + + "s and thus can provide connectivity to virtual machine. If this property is fals" + + "e, then this Ethernet is not being used by the virtual machine networking archit" + + "ecture.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool IsBound { + get { + if ((curObj["IsBound"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["IsBound"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastErrorCodeNull { + get { + if ((curObj["LastErrorCode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint LastErrorCode { + get { + if ((curObj["LastErrorCode"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["LastErrorCode"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLinkTechnologyNull { + get { + if ((curObj["LinkTechnology"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort LinkTechnology { + get { + if ((curObj["LinkTechnology"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["LinkTechnology"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxDataSizeNull { + get { + if ((curObj["MaxDataSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxDataSize { + get { + if ((curObj["MaxDataSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxDataSize"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxQuiesceTimeNull { + get { + if ((curObj["MaxQuiesceTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxQuiesceTime { + get { + if ((curObj["MaxQuiesceTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxQuiesceTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxSpeedNull { + get { + if ((curObj["MaxSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxSpeed { + get { + if ((curObj["MaxSpeed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxSpeed"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] NetworkAddresses { + get { + return ((string[])(curObj["NetworkAddresses"])); + } + } + + [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[] OtherEnabledCapabilities { + get { + return ((string[])(curObj["OtherEnabledCapabilities"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherIdentifyingInfo { + get { + return ((string[])(curObj["OtherIdentifyingInfo"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherLinkTechnology { + get { + return ((string)(curObj["OtherLinkTechnology"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherNetworkPortType { + get { + return ((string)(curObj["OtherNetworkPortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherPortType { + get { + return ((string)(curObj["OtherPortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PermanentAddress { + get { + return ((string)(curObj["PermanentAddress"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPortNumberNull { + get { + if ((curObj["PortNumber"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PortNumber { + get { + if ((curObj["PortNumber"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PortNumber"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPortTypeNull { + get { + if ((curObj["PortType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PortType { + get { + if ((curObj["PortType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] PowerManagementCapabilities { + get { + return ((ushort[])(curObj["PowerManagementCapabilities"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerManagementSupportedNull { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool PowerManagementSupported { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["PowerManagementSupported"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerOnHoursNull { + get { + if ((curObj["PowerOnHours"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PowerOnHours { + get { + if ((curObj["PowerOnHours"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PowerOnHours"])); + } + } + + [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 IsRequestedSpeedNull { + get { + if ((curObj["RequestedSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong RequestedSpeed { + get { + if ((curObj["RequestedSpeed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["RequestedSpeed"])); + } + } + + [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 IsSpeedNull { + get { + if ((curObj["Speed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Speed { + get { + if ((curObj["Speed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Speed"])); + } + } + + [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 IsStatusInfoNull { + get { + if ((curObj["StatusInfo"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort StatusInfo { + get { + if ((curObj["StatusInfo"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["StatusInfo"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSupportedMaximumTransmissionUnitNull { + get { + if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong SupportedMaximumTransmissionUnit { + get { + if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["SupportedMaximumTransmissionUnit"])); + } + } + + [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 IsTotalPowerOnHoursNull { + get { + if ((curObj["TotalPowerOnHours"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong TotalPowerOnHours { + get { + if ((curObj["TotalPowerOnHours"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["TotalPowerOnHours"])); + } + } + + [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"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsUsageRestrictionNull { + get { + if ((curObj["UsageRestriction"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort UsageRestriction { + get { + if ((curObj["UsageRestriction"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["UsageRestriction"])); + } + } + + 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 ShouldSerializeActiveMaximumTransmissionUnit() { + if ((this.IsActiveMaximumTransmissionUnitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutoSense() { + if ((this.IsAutoSenseNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAvailability() { + if ((this.IsAvailabilityNull == 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 ShouldSerializeErrorCleared() { + if ((this.IsErrorClearedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeFullDuplex() { + if ((this.IsFullDuplexNull == 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 ShouldSerializeIsBound() { + if ((this.IsIsBoundNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastErrorCode() { + if ((this.IsLastErrorCodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLinkTechnology() { + if ((this.IsLinkTechnologyNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxDataSize() { + if ((this.IsMaxDataSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxQuiesceTime() { + if ((this.IsMaxQuiesceTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxSpeed() { + if ((this.IsMaxSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePortNumber() { + if ((this.IsPortNumberNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePortType() { + if ((this.IsPortTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerManagementSupported() { + if ((this.IsPowerManagementSupportedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerOnHours() { + if ((this.IsPowerOnHoursNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedSpeed() { + if ((this.IsRequestedSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSpeed() { + if ((this.IsSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStatusInfo() { + if ((this.IsStatusInfoNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSupportedMaximumTransmissionUnit() { + if ((this.IsSupportedMaximumTransmissionUnitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTotalPowerOnHours() { + if ((this.IsTotalPowerOnHoursNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeUsageRestriction() { + if ((this.IsUsageRestrictionNull == 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 keyDeviceID, string keySystemCreationClassName, string keySystemName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_ExternalEthernetPort"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",DeviceID=", string.Concat("\"", string.Concat(keyDeviceID, "\"")))); + 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 ExternalEthernetPortCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ExternalEthernetPortCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ExternalEthernetPortCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ExternalEthernetPortCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ExternalEthernetPortCollection 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_ExternalEthernetPort"; + 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 ExternalEthernetPortCollection(clsObject.GetInstances(enumOptions)); + } + + public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ExternalEthernetPortCollection 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_ExternalEthernetPort", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ExternalEthernetPortCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static ExternalEthernetPort 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 ExternalEthernetPort(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint EnableDevice(bool Enabled) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("EnableDevice"); + inParams["Enabled"] = ((bool)(Enabled)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("EnableDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint OnlineDevice(bool Online) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("OnlineDevice"); + inParams["Online"] = ((bool)(Online)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("OnlineDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint QuiesceDevice(bool Quiesce) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("QuiesceDevice"); + inParams["Quiesce"] = ((bool)(Quiesce)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("QuiesceDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + 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) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint Reset() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reset", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RestoreProperties() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RestoreProperties", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SaveProperties() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SaveProperties", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SetPowerState(ushort PowerState, System.DateTime Time) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); + inParams["PowerState"] = ((ushort)(PowerState)); + inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", 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 ExternalEthernetPortCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ExternalEthernetPortCollection(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 ExternalEthernetPort(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ExternalEthernetPortEnumerator(privColObj.GetEnumerator()); + } + + public class ExternalEthernetPortEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ExternalEthernetPortEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new ExternalEthernetPort(((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_ImageManagementService.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ImageManagementService.cs new file mode 100644 index 00000000000..1ebbeb00f91 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ImageManagementService.cs @@ -0,0 +1,1525 @@ +// 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_ImageManagementService + public class ImageManagementService : 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. + private static string CreatedClassName = "Msvm_ImageManagementService"; + + // 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 ImageManagementService() { + this.InitializeObject(null, null, null); + } + + public ImageManagementService(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(ImageManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public ImageManagementService(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ImageManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public ImageManagementService(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public ImageManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public ImageManagementService(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public ImageManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public ImageManagementService(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 ImageManagementService(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(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)] + 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 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_ImageManagementService"; + 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 ImageManagementServiceCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ImageManagementServiceCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ImageManagementServiceCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ImageManagementServiceCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ImageManagementServiceCollection 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_ImageManagementService"; + 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 ImageManagementServiceCollection(clsObject.GetInstances(enumOptions)); + } + + public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ImageManagementServiceCollection 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_ImageManagementService", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ImageManagementServiceCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static ImageManagementService 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 ImageManagementService(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint AttachVirtualHardDisk(bool AssignDriveLetter, string Path, bool ReadOnly, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AttachVirtualHardDisk"); + inParams["AssignDriveLetter"] = ((bool)(AssignDriveLetter)); + inParams["Path"] = ((string)(Path)); + inParams["ReadOnly"] = ((bool)(ReadOnly)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AttachVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 CompactVirtualHardDisk(ushort Mode, string Path, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("CompactVirtualHardDisk"); + inParams["Mode"] = ((ushort)(Mode)); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CompactVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 ConvertVirtualHardDisk(string SourcePath, string VirtualDiskSettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ConvertVirtualHardDisk"); + inParams["SourcePath"] = ((string)(SourcePath)); + inParams["VirtualDiskSettingData"] = ((string)(VirtualDiskSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ConvertVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 CreateVirtualFloppyDisk(string Path, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("CreateVirtualFloppyDisk"); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateVirtualFloppyDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 CreateVirtualHardDisk(string VirtualDiskSettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("CreateVirtualHardDisk"); + inParams["VirtualDiskSettingData"] = ((string)(VirtualDiskSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 GetVirtualHardDiskSettingData(string Path, out System.Management.ManagementPath Job, out string SettingData) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GetVirtualHardDiskSettingData"); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetVirtualHardDiskSettingData", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + SettingData = System.Convert.ToString(outParams.Properties["SettingData"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + SettingData = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GetVirtualHardDiskState(string Path, out System.Management.ManagementPath Job, out string State) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GetVirtualHardDiskState"); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetVirtualHardDiskState", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + State = System.Convert.ToString(outParams.Properties["State"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + State = null; + return System.Convert.ToUInt32(0); + } + } + + public uint MergeVirtualHardDisk(string DestinationPath, string SourcePath, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("MergeVirtualHardDisk"); + inParams["DestinationPath"] = ((string)(DestinationPath)); + inParams["SourcePath"] = ((string)(SourcePath)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("MergeVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 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((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ResizeVirtualHardDisk(ulong MaxInternalSize, string Path, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ResizeVirtualHardDisk"); + inParams["MaxInternalSize"] = ((ulong)(MaxInternalSize)); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ResizeVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 SetParentVirtualHardDisk(string ChildPath, bool IgnoreIDMismatch, string LeafPath, string ParentPath, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetParentVirtualHardDisk"); + inParams["ChildPath"] = ((string)(ChildPath)); + inParams["IgnoreIDMismatch"] = ((bool)(IgnoreIDMismatch)); + inParams["LeafPath"] = ((string)(LeafPath)); + inParams["ParentPath"] = ((string)(ParentPath)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetParentVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 SetVirtualHardDiskSettingData(string VirtualDiskSettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetVirtualHardDiskSettingData"); + inParams["VirtualDiskSettingData"] = ((string)(VirtualDiskSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetVirtualHardDiskSettingData", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 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); + } + } + + public uint ValidateVirtualHardDisk(string Path, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ValidateVirtualHardDisk"); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ValidateVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class ImageManagementServiceCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ImageManagementServiceCollection(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 ImageManagementService(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ImageManagementServiceEnumerator(privColObj.GetEnumerator()); + } + + public class ImageManagementServiceEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ImageManagementServiceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new ImageManagementService(((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_KvpExchangeComponent.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeComponent.cs new file mode 100644 index 00000000000..976da28136f --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeComponent.cs @@ -0,0 +1,1615 @@ +// 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_KvpExchangeComponent + public class KvpExchangeComponent : 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. + private static string CreatedClassName = "Msvm_KvpExchangeComponent"; + + // 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 KvpExchangeComponent() { + this.InitializeObject(null, null, null); + } + + public KvpExchangeComponent(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(KvpExchangeComponent.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); + } + + public KvpExchangeComponent(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(KvpExchangeComponent.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); + } + + public KvpExchangeComponent(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public KvpExchangeComponent(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public KvpExchangeComponent(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public KvpExchangeComponent(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public KvpExchangeComponent(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 KvpExchangeComponent(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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AdditionalAvailability { + get { + return ((ushort[])(curObj["AdditionalAvailability"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAvailabilityNull { + get { + if ((curObj["Availability"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Availability { + get { + if ((curObj["Availability"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Availability"])); + } + } + + [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 DeviceID { + get { + return ((string)(curObj["DeviceID"])); + } + } + + [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 IsErrorClearedNull { + get { + if ((curObj["ErrorCleared"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool ErrorCleared { + get { + if ((curObj["ErrorCleared"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["ErrorCleared"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ErrorDescription { + get { + return ((string)(curObj["ErrorDescription"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"An array of embedded Msvm_KvpExchangeDataItem instances which contain the set of key-value pairs that components running within the guest operating system have pushed up to be available for access by external clients. This array will not contain any intrinsic items that are pushed by the integration component directly.")] + public string[] GuestExchangeItems { + get { + return ((string[])(curObj["GuestExchangeItems"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"An array of embedded Msvm_KvpExchangeDataItem instances which contain the set of key-value pairs that the guest operating system has pushed up to be available for access by external clients. This array will not contain any data items pushed by other components running within the guest operating system.")] + public string[] GuestIntrinsicExchangeItems { + get { + return ((string[])(curObj["GuestIntrinsicExchangeItems"])); + } + } + + [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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] IdentifyingDescriptions { + get { + return ((string[])(curObj["IdentifyingDescriptions"])); + } + } + + [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 IsLastErrorCodeNull { + get { + if ((curObj["LastErrorCode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint LastErrorCode { + get { + if ((curObj["LastErrorCode"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["LastErrorCode"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxQuiesceTimeNull { + get { + if ((curObj["MaxQuiesceTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxQuiesceTime { + get { + if ((curObj["MaxQuiesceTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxQuiesceTime"])); + } + } + + [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[] OtherIdentifyingInfo { + get { + return ((string[])(curObj["OtherIdentifyingInfo"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] PowerManagementCapabilities { + get { + return ((ushort[])(curObj["PowerManagementCapabilities"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerManagementSupportedNull { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool PowerManagementSupported { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["PowerManagementSupported"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerOnHoursNull { + get { + if ((curObj["PowerOnHours"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PowerOnHours { + get { + if ((curObj["PowerOnHours"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PowerOnHours"])); + } + } + + [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(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 IsStatusInfoNull { + get { + if ((curObj["StatusInfo"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort StatusInfo { + get { + if ((curObj["StatusInfo"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["StatusInfo"])); + } + } + + [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 IsTotalPowerOnHoursNull { + get { + if ((curObj["TotalPowerOnHours"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong TotalPowerOnHours { + get { + if ((curObj["TotalPowerOnHours"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["TotalPowerOnHours"])); + } + } + + [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 ShouldSerializeAvailability() { + if ((this.IsAvailabilityNull == 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 ShouldSerializeErrorCleared() { + if ((this.IsErrorClearedNull == 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 ShouldSerializeLastErrorCode() { + if ((this.IsLastErrorCodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxQuiesceTime() { + if ((this.IsMaxQuiesceTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerManagementSupported() { + if ((this.IsPowerManagementSupportedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerOnHours() { + if ((this.IsPowerOnHoursNull == 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 ShouldSerializeStatusInfo() { + if ((this.IsStatusInfoNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTotalPowerOnHours() { + if ((this.IsTotalPowerOnHoursNull == 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 keyDeviceID, string keySystemCreationClassName, string keySystemName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_KvpExchangeComponent"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",DeviceID=", string.Concat("\"", string.Concat(keyDeviceID, "\"")))); + 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 KvpExchangeComponentCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static KvpExchangeComponentCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static KvpExchangeComponentCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static KvpExchangeComponentCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static KvpExchangeComponentCollection 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_KvpExchangeComponent"; + 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 KvpExchangeComponentCollection(clsObject.GetInstances(enumOptions)); + } + + public static KvpExchangeComponentCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static KvpExchangeComponentCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static KvpExchangeComponentCollection 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_KvpExchangeComponent", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new KvpExchangeComponentCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static KvpExchangeComponent 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 KvpExchangeComponent(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint EnableDevice(bool Enabled) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("EnableDevice"); + inParams["Enabled"] = ((bool)(Enabled)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("EnableDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint OnlineDevice(bool Online) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("OnlineDevice"); + inParams["Online"] = ((bool)(Online)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("OnlineDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint QuiesceDevice(bool Quiesce) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("QuiesceDevice"); + inParams["Quiesce"] = ((bool)(Quiesce)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("QuiesceDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + 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((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint Reset() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reset", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RestoreProperties() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RestoreProperties", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SaveProperties() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SaveProperties", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SetPowerState(ushort PowerState, System.DateTime Time) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); + inParams["PowerState"] = ((ushort)(PowerState)); + inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", 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 KvpExchangeComponentCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public KvpExchangeComponentCollection(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 KvpExchangeComponent(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new KvpExchangeComponentEnumerator(privColObj.GetEnumerator()); + } + + public class KvpExchangeComponentEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public KvpExchangeComponentEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new KvpExchangeComponent(((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_KvpExchangeComponentSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeComponentSettingData.cs new file mode 100644 index 00000000000..4e704e02354 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeComponentSettingData.cs @@ -0,0 +1,1054 @@ +// 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_KvpExchangeComponentSettingData + public class KvpExchangeComponentSettingData : 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_KvpExchangeComponentSettingData"; + + // 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 KvpExchangeComponentSettingData() { + this.InitializeObject(null, null, null); + } + + public KvpExchangeComponentSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(KvpExchangeComponentSettingData.ConstructPath(keyInstanceID)), null); + } + + public KvpExchangeComponentSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(KvpExchangeComponentSettingData.ConstructPath(keyInstanceID)), null); + } + + public KvpExchangeComponentSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public KvpExchangeComponentSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public KvpExchangeComponentSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public KvpExchangeComponentSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public KvpExchangeComponentSettingData(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 KvpExchangeComponentSettingData(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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The enabled and disabled states of an element. +Valid values are 2 (enabled) and 3 (disabled). The default value is 2 (enabled). +This is a read-only property, but it can be changed using the ModifyVirtualSystemResources method of the Msvm_VirtualSystemManagementService class.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("An array of Msvm_KvpExchangeDataItem instances.\nThis is a read-only property, but" + + " it can be changed using the AddKvpItems, ModifyKvpItems, and RemoveKvpItems met" + + "hods of the Msvm_VirtualSystemManagementService class.")] + public string[] HostExchangeItems { + get { + return ((string[])(curObj["HostExchangeItems"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"An array of Msvm_KvpExchangeDataItem instances containing the key/value pairs that are stored in the configuration file but not exchanged with the guest OS. This allows applications to store VM-specific data that does not need to be visible to the guest OS. The items are formatted the same as the items in the HostExchangeItems property except the Source property of the Msvm_KvpExchangeDataItem instance is set to 4. Each configuration file is limited to 128 key/value pairs, where each value field is allowed to be up to 16 KB in size and the key field is allowed to be up to512 bytes.")] + public string[] HostOnlyItems { + get { + return ((string[])(curObj["HostOnlyItems"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + 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 ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == 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_KvpExchangeComponentSettingData"; + 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 KvpExchangeComponentSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static KvpExchangeComponentSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static KvpExchangeComponentSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static KvpExchangeComponentSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static KvpExchangeComponentSettingDataCollection 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_KvpExchangeComponentSettingData"; + 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 KvpExchangeComponentSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static KvpExchangeComponentSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static KvpExchangeComponentSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static KvpExchangeComponentSettingDataCollection 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_KvpExchangeComponentSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new KvpExchangeComponentSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static KvpExchangeComponentSettingData 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 KvpExchangeComponentSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class KvpExchangeComponentSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public KvpExchangeComponentSettingDataCollection(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 KvpExchangeComponentSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new KvpExchangeComponentSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class KvpExchangeComponentSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public KvpExchangeComponentSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new KvpExchangeComponentSettingData(((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_KvpExchangeDataItem.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeDataItem.cs new file mode 100644 index 00000000000..f076f790277 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeDataItem.cs @@ -0,0 +1,670 @@ +// 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_KvpExchangeDataItem + public class KvpExchangeDataItem : 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. + private static string CreatedClassName = "Msvm_KvpExchangeDataItem"; + + // 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 KvpExchangeDataItem() { + this.InitializeObject(null, null, null); + } + + public KvpExchangeDataItem(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public KvpExchangeDataItem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public KvpExchangeDataItem(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public KvpExchangeDataItem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public KvpExchangeDataItem(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 KvpExchangeDataItem(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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Data { + get { + return ((string)(curObj["Data"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSourceNull { + get { + if ((curObj["Source"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Source { + get { + if ((curObj["Source"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Source"])); + } + } + + 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 ShouldSerializeSource() { + if ((this.IsSourceNull == 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 strPath = "ROOT\\virtualization\\v2:Msvm_KvpExchangeDataItem"; + 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 KvpExchangeDataItemCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static KvpExchangeDataItemCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static KvpExchangeDataItemCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static KvpExchangeDataItemCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static KvpExchangeDataItemCollection 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_KvpExchangeDataItem"; + 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 KvpExchangeDataItemCollection(clsObject.GetInstances(enumOptions)); + } + + public static KvpExchangeDataItemCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static KvpExchangeDataItemCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static KvpExchangeDataItemCollection 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_KvpExchangeDataItem", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new KvpExchangeDataItemCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static KvpExchangeDataItem 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 KvpExchangeDataItem(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class KvpExchangeDataItemCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public KvpExchangeDataItemCollection(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 KvpExchangeDataItem(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new KvpExchangeDataItemEnumerator(privColObj.GetEnumerator()); + } + + public class KvpExchangeDataItemEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public KvpExchangeDataItemEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new KvpExchangeDataItem(((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_LANEndpoint.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_LANEndpoint.cs new file mode 100644 index 00000000000..9f09a069498 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_LANEndpoint.cs @@ -0,0 +1,1422 @@ +// 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_LANEndpoint + public class LANEndpoint : 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_LANEndpoint"; + + // 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 LANEndpoint() { + this.InitializeObject(null, null, null); + } + + public LANEndpoint(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(LANEndpoint.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public LANEndpoint(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(LANEndpoint.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public LANEndpoint(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public LANEndpoint(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public LANEndpoint(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public LANEndpoint(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public LANEndpoint(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 LANEndpoint(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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] AliasAddresses { + get { + return ((string[])(curObj["AliasAddresses"])); + } + } + + [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(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConnectedNull { + get { + if ((curObj["Connected"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("This property is set to TRUE if the LAN endpoint is connected to a switch port.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool Connected { + get { + if ((curObj["Connected"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["Connected"])); + } + } + + [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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] GroupAddresses { + get { + return ((string[])(curObj["GroupAddresses"])); + } + } + + [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)] + public string LANID { + get { + return ((string)(curObj["LANID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLANTypeNull { + get { + if ((curObj["LANType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort LANType { + get { + if ((curObj["LANType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["LANType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string MACAddress { + get { + return ((string)(curObj["MACAddress"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxDataSizeNull { + get { + if ((curObj["MaxDataSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxDataSize { + get { + if ((curObj["MaxDataSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxDataSize"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string NameFormat { + get { + return ((string)(curObj["NameFormat"])); + } + } + + [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 OtherLANType { + get { + return ((string)(curObj["OtherLANType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherTypeDescription { + get { + return ((string)(curObj["OtherTypeDescription"])); + } + } + + [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 IsProtocolIFTypeNull { + get { + if ((curObj["ProtocolIFType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ProtocolIFType { + get { + if ((curObj["ProtocolIFType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ProtocolIFType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsProtocolTypeNull { + get { + if ((curObj["ProtocolType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ProtocolType { + get { + if ((curObj["ProtocolType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ProtocolType"])); + } + } + + [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(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 ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConnected() { + if ((this.IsConnectedNull == 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 ShouldSerializeLANType() { + if ((this.IsLANTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxDataSize() { + if ((this.IsMaxDataSizeNull == 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 ShouldSerializeProtocolIFType() { + if ((this.IsProtocolIFTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeProtocolType() { + if ((this.IsProtocolTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == 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_LANEndpoint"; + 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 LANEndpointCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static LANEndpointCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static LANEndpointCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static LANEndpointCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static LANEndpointCollection 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_LANEndpoint"; + 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 LANEndpointCollection(clsObject.GetInstances(enumOptions)); + } + + public static LANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static LANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static LANEndpointCollection 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_LANEndpoint", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new LANEndpointCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static LANEndpoint 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 LANEndpoint(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + 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) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class LANEndpointCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public LANEndpointCollection(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 LANEndpoint(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new LANEndpointEnumerator(privColObj.GetEnumerator()); + } + + public class LANEndpointEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public LANEndpointEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new LANEndpoint(((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_MemorySettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_MemorySettingData.cs new file mode 100644 index 00000000000..99200dd1b21 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_MemorySettingData.cs @@ -0,0 +1,1163 @@ +// 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_MemorySettingData + public class MemorySettingData : 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_MemorySettingData"; + + // 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 MemorySettingData() { + this.InitializeObject(null, null, null); + } + + public MemorySettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(MemorySettingData.ConstructPath(keyInstanceID)), null); + } + + public MemorySettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(MemorySettingData.ConstructPath(keyInstanceID)), null); + } + + public MemorySettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public MemorySettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public MemorySettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public MemorySettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public MemorySettingData(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 MemorySettingData(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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDynamicMemoryEnabledNull { + get { + if ((curObj["DynamicMemoryEnabled"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates if dynamic memory is enabled.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool DynamicMemoryEnabled { + get { + if ((curObj["DynamicMemoryEnabled"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["DynamicMemoryEnabled"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsIsVirtualizedNull { + get { + if ((curObj["IsVirtualized"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Indicates whether this device is virtualized or passed through, possibly using partitioning. When set to False, the underlying or host resource is utilized. At least one item shall be present in the DeviceID property. When set to True, the resource is virtualized and may not map directly to an underlying/host resource. Some implementations may support specific assignment for virtualized resources, in which case the host resource(s) are exposed using the DeviceID property. This property is always set to True.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool IsVirtualized { + get { + if ((curObj["IsVirtualized"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["IsVirtualized"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxMemoryBlocksPerNumaNodeNull { + get { + if ((curObj["MaxMemoryBlocksPerNumaNode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum amount of memory that can be observed within the VM as belonging to a" + + " single NUMA node.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxMemoryBlocksPerNumaNode { + get { + if ((curObj["MaxMemoryBlocksPerNumaNode"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxMemoryBlocksPerNumaNode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSwapFilesInUseNull { + get { + if ((curObj["SwapFilesInUse"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates if smart paging is active.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool SwapFilesInUse { + get { + if ((curObj["SwapFilesInUse"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["SwapFilesInUse"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTargetMemoryBufferNull { + get { + if ((curObj["TargetMemoryBuffer"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint TargetMemoryBuffer { + get { + if ((curObj["TargetMemoryBuffer"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["TargetMemoryBuffer"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + 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 ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDynamicMemoryEnabled() { + if ((this.IsDynamicMemoryEnabledNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeIsVirtualized() { + if ((this.IsIsVirtualizedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxMemoryBlocksPerNumaNode() { + if ((this.IsMaxMemoryBlocksPerNumaNodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSwapFilesInUse() { + if ((this.IsSwapFilesInUseNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTargetMemoryBuffer() { + if ((this.IsTargetMemoryBufferNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == 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_MemorySettingData"; + 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 MemorySettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static MemorySettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static MemorySettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static MemorySettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static MemorySettingDataCollection 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_MemorySettingData"; + 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 MemorySettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static MemorySettingDataCollection 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_MemorySettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new MemorySettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static MemorySettingData 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 MemorySettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class MemorySettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public MemorySettingDataCollection(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 MemorySettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new MemorySettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class MemorySettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public MemorySettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new MemorySettingData(((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_ProcessorSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ProcessorSettingData.cs new file mode 100644 index 00000000000..c21c71cc6d4 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ProcessorSettingData.cs @@ -0,0 +1,1134 @@ +// 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_ProcessorSettingData + public class ProcessorSettingData : 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_ProcessorSettingData"; + + // 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 ProcessorSettingData() { + this.InitializeObject(null, null, null); + } + + public ProcessorSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(ProcessorSettingData.ConstructPath(keyInstanceID)), null); + } + + public ProcessorSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ProcessorSettingData.ConstructPath(keyInstanceID)), null); + } + + public ProcessorSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public ProcessorSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public ProcessorSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public ProcessorSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public ProcessorSettingData(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 ProcessorSettingData(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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitCPUIDNull { + get { + if ((curObj["LimitCPUID"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates whether the virtual machine should lower the CPU identifier. Some older" + + " operating systems may require you to limit processor functionality in this way " + + "in order to run.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool LimitCPUID { + get { + if ((curObj["LimitCPUID"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["LimitCPUID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitProcessorFeaturesNull { + get { + if ((curObj["LimitProcessorFeatures"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Indicates whether the VM should limit the CPU features exposed to the operating system. Limiting the processor features enables the VM to be migrated to different host computer systems with different processors. Migrating VMs between computers with processors from different vendors is not supported.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool LimitProcessorFeatures { + get { + if ((curObj["LimitProcessorFeatures"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["LimitProcessorFeatures"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxNumaNodesPerSocketNull { + get { + if ((curObj["MaxNumaNodesPerSocket"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum number of NUMA nodes that can be observed within the VM as belonging " + + "to a single processor socket.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxNumaNodesPerSocket { + get { + if ((curObj["MaxNumaNodesPerSocket"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxNumaNodesPerSocket"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxProcessorsPerNumaNodeNull { + get { + if ((curObj["MaxProcessorsPerNumaNode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum number of virtual processors that can be observed within the VM as be" + + "longing to a single virtual NUMA node.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxProcessorsPerNumaNode { + get { + if ((curObj["MaxProcessorsPerNumaNode"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxProcessorsPerNumaNode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + 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 ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimitCPUID() { + if ((this.IsLimitCPUIDNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimitProcessorFeatures() { + if ((this.IsLimitProcessorFeaturesNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxNumaNodesPerSocket() { + if ((this.IsMaxNumaNodesPerSocketNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxProcessorsPerNumaNode() { + if ((this.IsMaxProcessorsPerNumaNodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == 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_ProcessorSettingData"; + 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 ProcessorSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ProcessorSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ProcessorSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ProcessorSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ProcessorSettingDataCollection 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_ProcessorSettingData"; + 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 ProcessorSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ProcessorSettingDataCollection 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_ProcessorSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ProcessorSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static ProcessorSettingData 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 ProcessorSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class ProcessorSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ProcessorSettingDataCollection(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 ProcessorSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ProcessorSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class ProcessorSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ProcessorSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new ProcessorSettingData(((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_ResourceAllocationSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ResourceAllocationSettingData.cs new file mode 100644 index 00000000000..a75837e15ec --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ResourceAllocationSettingData.cs @@ -0,0 +1,1010 @@ +// 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_ResourceAllocationSettingData + public class ResourceAllocationSettingData : 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_ResourceAllocationSettingData"; + + // 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 ResourceAllocationSettingData() { + this.InitializeObject(null, null, null); + } + + public ResourceAllocationSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(ResourceAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ResourceAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public ResourceAllocationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public ResourceAllocationSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public ResourceAllocationSettingData(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 ResourceAllocationSettingData(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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"A free-form string array of identifiers of this resource presented to the virtual computer system's operating system. These values are only used if the ResourceType property is set to 6 (Parallel SCSI HBA) and the ResourceSubType property is set to ""Microsoft Synthetic SCSI Controller"". This property is set to ""GUID"". +This is a read-only property, but it can be changed using the ModifyVirtualSystemResources method of the Msvm_VirtualSystemManagementService class. +Windows Server 2008: The VirtualSystemIdentifiers property is not supported until Windows Server 2008 R2.")] + public string[] VirtualSystemIdentifiers { + get { + return ((string[])(curObj["VirtualSystemIdentifiers"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + 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 ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == 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_ResourceAllocationSettingData"; + 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 ResourceAllocationSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ResourceAllocationSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ResourceAllocationSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ResourceAllocationSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ResourceAllocationSettingDataCollection 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_ResourceAllocationSettingData"; + 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 ResourceAllocationSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ResourceAllocationSettingDataCollection 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_ResourceAllocationSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ResourceAllocationSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static ResourceAllocationSettingData 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 ResourceAllocationSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class ResourceAllocationSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ResourceAllocationSettingDataCollection(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 ResourceAllocationSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ResourceAllocationSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class ResourceAllocationSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ResourceAllocationSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new ResourceAllocationSettingData(((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_StorageAllocationSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_StorageAllocationSettingData.cs new file mode 100644 index 00000000000..8553fedd525 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_StorageAllocationSettingData.cs @@ -0,0 +1,1214 @@ +// 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_StorageAllocationSettingData + public class StorageAllocationSettingData : 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. + private static string CreatedClassName = "Msvm_StorageAllocationSettingData"; + + // 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 StorageAllocationSettingData() { + this.InitializeObject(null, null, null); + } + + public StorageAllocationSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(StorageAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public StorageAllocationSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(StorageAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public StorageAllocationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public StorageAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public StorageAllocationSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public StorageAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public StorageAllocationSettingData(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 StorageAllocationSettingData(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 IsAccessNull { + get { + if ((curObj["Access"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Access { + get { + if ((curObj["Access"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Access"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string HostExtentName { + get { + return ((string)(curObj["HostExtentName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHostExtentNameFormatNull { + get { + if ((curObj["HostExtentNameFormat"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HostExtentNameFormat { + get { + if ((curObj["HostExtentNameFormat"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HostExtentNameFormat"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHostExtentNameNamespaceNull { + get { + if ((curObj["HostExtentNameNamespace"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HostExtentNameNamespace { + get { + if ((curObj["HostExtentNameNamespace"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HostExtentNameNamespace"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHostExtentStartingAddressNull { + get { + if ((curObj["HostExtentStartingAddress"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong HostExtentStartingAddress { + get { + if ((curObj["HostExtentStartingAddress"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["HostExtentStartingAddress"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHostResourceBlockSizeNull { + get { + if ((curObj["HostResourceBlockSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong HostResourceBlockSize { + get { + if ((curObj["HostResourceBlockSize"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["HostResourceBlockSize"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherHostExtentNameFormat { + get { + return ((string)(curObj["OtherHostExtentNameFormat"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherHostExtentNameNamespace { + get { + return ((string)(curObj["OtherHostExtentNameNamespace"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualResourceBlockSizeNull { + get { + if ((curObj["VirtualResourceBlockSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualResourceBlockSize { + get { + if ((curObj["VirtualResourceBlockSize"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualResourceBlockSize"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + 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 ShouldSerializeAccess() { + if ((this.IsAccessNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHostExtentNameFormat() { + if ((this.IsHostExtentNameFormatNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHostExtentNameNamespace() { + if ((this.IsHostExtentNameNamespaceNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHostExtentStartingAddress() { + if ((this.IsHostExtentStartingAddressNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHostResourceBlockSize() { + if ((this.IsHostResourceBlockSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualResourceBlockSize() { + if ((this.IsVirtualResourceBlockSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == 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_StorageAllocationSettingData"; + 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 StorageAllocationSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static StorageAllocationSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static StorageAllocationSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static StorageAllocationSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static StorageAllocationSettingDataCollection 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_StorageAllocationSettingData"; + 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 StorageAllocationSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static StorageAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static StorageAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static StorageAllocationSettingDataCollection 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_StorageAllocationSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new StorageAllocationSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static StorageAllocationSettingData 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 StorageAllocationSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class StorageAllocationSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public StorageAllocationSettingDataCollection(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 StorageAllocationSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new StorageAllocationSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class StorageAllocationSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public StorageAllocationSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new StorageAllocationSettingData(((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_SummaryInformation.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SummaryInformation.cs new file mode 100644 index 00000000000..a9523b79851 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SummaryInformation.cs @@ -0,0 +1,1537 @@ +// 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. + // + // + // + // + // If the embedded property is strongly typed then, to strongly type the property to the type of + // the embedded object, you have to do the following things. + // 1. Generate Managed class for the WMI class of the embedded property. This can be done with MgmtClassGen.exe tool or from Server Explorer. + // 2. Include the namespace of the generated class. + // 3. Change the property get/set functions so as return the instance of the Managed class. + // Below is a sample code. + // + // VB Code + // + // + // + // Property name + // Managed class name of Embedded Property + // + // + // + // + // + // + // C# Code + // + // + // + // Managed class name of Embedded property + // Property name + // + // + // + // + // + // + // + // + // + // + // An Early Bound class generated for the WMI class.Msvm_SummaryInformation + public class SummaryInformation : 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. + private static string CreatedClassName = "Msvm_SummaryInformation"; + + // 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 SummaryInformation() { + this.InitializeObject(null, null, null); + } + + public SummaryInformation(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public SummaryInformation(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public SummaryInformation(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public SummaryInformation(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public SummaryInformation(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 SummaryInformation(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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The identifier of the physical graphics processing unit (GPU) allocated to this v" + + "irtual machine (VM). This property only applies to VMs that use RemoteFX.")] + public string AllocatedGPU { + get { + return ((string)(curObj["AllocatedGPU"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsApplicationHealthNull { + get { + if ((curObj["ApplicationHealth"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The current application health status for the virtual system. This property may be one of the following values: ""OK""; ""Application Critical""; ""Disabled"".For more information, see the documentation for the StatusDescriptions property of the Msvm_HeartbeatComponent class. This property is not valid for instances of Msvm_SummaryInformation representing a virtual system snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ApplicationHealthValues ApplicationHealth { + get { + if ((curObj["ApplicationHealth"] == null)) { + return ((ApplicationHealthValues)(System.Convert.ToInt32(0))); + } + return ((ApplicationHealthValues)(System.Convert.ToInt32(curObj["ApplicationHealth"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("An array of Msvm_ConcreteJob instances representing any asynchronous operations r" + + "elated to the virtual system which are currently executing. This property is not" + + " valid for instances of Msvm_SummaryInformation representing a virtual system sn" + + "apshot.")] + public System.Management.ManagementBaseObject[] AsynchronousTasks { + get { + return ((System.Management.ManagementBaseObject[])(curObj["AsynchronousTasks"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAvailableMemoryBufferNull { + get { + if ((curObj["AvailableMemoryBuffer"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The available memory buffer percentage in the virtual system.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public int AvailableMemoryBuffer { + get { + if ((curObj["AvailableMemoryBuffer"] == null)) { + return System.Convert.ToInt32(0); + } + return ((int)(curObj["AvailableMemoryBuffer"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCreationTimeNull { + get { + if ((curObj["CreationTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The time at which the virtual system or snapshot was created.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime CreationTime { + get { + if ((curObj["CreationTime"] != null)) { + return ToDateTime(((string)(curObj["CreationTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The friendly name for the virtual system or snapshot.")] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current state of the virtual system or snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The name of the guest operating system, if available. If this information is not " + + "available, the value of this property is NULL. This property is not valid for in" + + "stances of Msvm_SummaryInformation representing a virtual system snapshot.")] + public string GuestOperatingSystem { + get { + return ((string)(curObj["GuestOperatingSystem"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current health state for the virtual system. This property is not valid for i" + + "nstances of Msvm_SummaryInformation representing a virtual system snapshot.")] + [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 IsHeartbeatNull { + get { + if ((curObj["Heartbeat"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The current heartbeat status for the virtual system. This property may be one of the following values: ""OK""; ""Error""; ""No Contact""; or ""Lost Communication"". For more information, see the documentation for the StatusDescriptions property of the Msvm_HeartbeatComponent class. This property is not valid for instances of Msvm_SummaryInformation representing a virtual system snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Heartbeat { + get { + if ((curObj["Heartbeat"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Heartbeat"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsIntegrationServicesVersionStateNull { + get { + if ((curObj["IntegrationServicesVersionState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Whether or not the integration services installed in the virtual machine are up t" + + "o date")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public IntegrationServicesVersionStateValues IntegrationServicesVersionState { + get { + if ((curObj["IntegrationServicesVersionState"] == null)) { + return ((IntegrationServicesVersionStateValues)(System.Convert.ToInt32(3))); + } + return ((IntegrationServicesVersionStateValues)(System.Convert.ToInt32(curObj["IntegrationServicesVersionState"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMemoryAvailableNull { + get { + if ((curObj["MemoryAvailable"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The memory available percentage in the virtual system.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public int MemoryAvailable { + get { + if ((curObj["MemoryAvailable"] == null)) { + return System.Convert.ToInt32(0); + } + return ((int)(curObj["MemoryAvailable"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMemorySpansPhysicalNumaNodesNull { + get { + if ((curObj["MemorySpansPhysicalNumaNodes"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates whether or not the memory of the one or more of the virtual non-uniform" + + " memory access (NUMA) nodes of the virtual machine spans multiple physical NUMA " + + "nodes of the hosting computer system.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool MemorySpansPhysicalNumaNodes { + get { + if ((curObj["MemorySpansPhysicalNumaNodes"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["MemorySpansPhysicalNumaNodes"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMemoryUsageNull { + get { + if ((curObj["MemoryUsage"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current memory usage of the virtual system. This property is not valid for in" + + "stances of Msvm_SummaryInformation representing a virtual system snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MemoryUsage { + get { + if ((curObj["MemoryUsage"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MemoryUsage"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The unique name for the virtual system or snapshot.")] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The notes associated with the virtual system or snapshot.")] + public string Notes { + get { + return ((string)(curObj["Notes"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNumberOfProcessorsNull { + get { + if ((curObj["NumberOfProcessors"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The total number of virtual processors allocated to the virtual system or snapsho" + + "t.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort NumberOfProcessors { + get { + if ((curObj["NumberOfProcessors"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["NumberOfProcessors"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current status of the element.")] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("A string that describes the enabled or disabled state of the element when the Ena" + + "bledState property is set to 1 (\"Other\"). This property must be set to null when" + + " EnabledState is any value other than 1.")] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsProcessorLoadNull { + get { + if ((curObj["ProcessorLoad"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current processor usage of the virtual system. This property is not valid for" + + " instances of Msvm_SummaryInformation representing a virtual system snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ProcessorLoad { + get { + if ((curObj["ProcessorLoad"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ProcessorLoad"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("An array of the previous 100 samples of the processor usage for the virtual syste" + + "m. This property is not valid for instances of Msvm_SummaryInformation represent" + + "ing a virtual system snapshot.")] + public ushort[] ProcessorLoadHistory { + get { + return ((ushort[])(curObj["ProcessorLoadHistory"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReplicationHealthNull { + get { + if ((curObj["ReplicationHealth"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Replication health for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ReplicationHealthValues ReplicationHealth { + get { + if ((curObj["ReplicationHealth"] == null)) { + return ((ReplicationHealthValues)(System.Convert.ToInt32(4))); + } + return ((ReplicationHealthValues)(System.Convert.ToInt32(curObj["ReplicationHealth"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReplicationModeNull { + get { + if ((curObj["ReplicationMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Identifies replication type for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ReplicationModeValues ReplicationMode { + get { + if ((curObj["ReplicationMode"] == null)) { + return ((ReplicationModeValues)(System.Convert.ToInt32(4))); + } + return ((ReplicationModeValues)(System.Convert.ToInt32(curObj["ReplicationMode"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReplicationStateNull { + get { + if ((curObj["ReplicationState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Replication state for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ReplicationStateValues ReplicationState { + get { + if ((curObj["ReplicationState"] == null)) { + return ((ReplicationStateValues)(System.Convert.ToInt32(12))); + } + return ((ReplicationStateValues)(System.Convert.ToInt32(curObj["ReplicationState"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("An array of Msvm_VirtualSystemSettingData instances representing the snapshots fo" + + "r the virtual system. This property is not valid for instances of Msvm_SummaryIn" + + "formation representing a virtual system snapshot.")] + public System.Management.ManagementBaseObject[] Snapshots { + get { + return ((System.Management.ManagementBaseObject[])(curObj["Snapshots"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Strings that describe the various OperationalStatus array values.")] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSwapFilesInUseNull { + get { + if ((curObj["SwapFilesInUse"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indecates if smart paging is active.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool SwapFilesInUse { + get { + if ((curObj["SwapFilesInUse"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["SwapFilesInUse"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Reference to the CIM_ComputerSystem instance representing the test replica virtua" + + "l system for the virtual machine. This property is not valid for instances of Ms" + + "vm_SummaryInformation representing a virtual system snapshot.")] + public System.Management.ManagementPath TestReplicaSystem { + get { + if ((curObj["TestReplicaSystem"] != null)) { + return new System.Management.ManagementPath(curObj["TestReplicaSystem"].ToString()); + } + return null; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("An array containing a small, thumbnail-sized image of the desktop for the virtual" + + " system or snapshot in RGB565 format.")] + public byte[] ThumbnailImage { + get { + return ((byte[])(curObj["ThumbnailImage"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsUpTimeNull { + get { + if ((curObj["UpTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The amount of time since the virtual system was last booted. This property is not" + + " valid for instances of Msvm_SummaryInformation representing a virtual system sn" + + "apshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong UpTime { + get { + if ((curObj["UpTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["UpTime"])); + } + } + + 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 ShouldSerializeApplicationHealth() { + if ((this.IsApplicationHealthNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAvailableMemoryBuffer() { + if ((this.IsAvailableMemoryBufferNull == 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 ShouldSerializeCreationTime() { + if ((this.IsCreationTimeNull == 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; + } + + private bool ShouldSerializeHeartbeat() { + if ((this.IsHeartbeatNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeIntegrationServicesVersionState() { + if ((this.IsIntegrationServicesVersionStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMemoryAvailable() { + if ((this.IsMemoryAvailableNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMemorySpansPhysicalNumaNodes() { + if ((this.IsMemorySpansPhysicalNumaNodesNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMemoryUsage() { + if ((this.IsMemoryUsageNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeNumberOfProcessors() { + if ((this.IsNumberOfProcessorsNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeProcessorLoad() { + if ((this.IsProcessorLoadNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReplicationHealth() { + if ((this.IsReplicationHealthNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReplicationMode() { + if ((this.IsReplicationModeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReplicationState() { + if ((this.IsReplicationStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSwapFilesInUse() { + if ((this.IsSwapFilesInUseNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeUpTime() { + if ((this.IsUpTimeNull == 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 strPath = "ROOT\\virtualization\\v2:Msvm_SummaryInformation"; + 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 SummaryInformationCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static SummaryInformationCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static SummaryInformationCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static SummaryInformationCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static SummaryInformationCollection 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_SummaryInformation"; + 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 SummaryInformationCollection(clsObject.GetInstances(enumOptions)); + } + + public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static SummaryInformationCollection 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_SummaryInformation", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new SummaryInformationCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static SummaryInformation 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 SummaryInformation(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public enum ApplicationHealthValues { + + OK = 2, + + Application_Critical = 32782, + + Disabled = 32896, + + NULL_ENUM_VALUE = 0, + } + + public enum IntegrationServicesVersionStateValues { + + Unknown0 = 0, + + UpToDate = 1, + + Mismatch = 2, + + NULL_ENUM_VALUE = 3, + } + + public enum ReplicationHealthValues { + + Not_applicable = 0, + + Ok = 1, + + Warning = 2, + + Critical = 3, + + NULL_ENUM_VALUE = 4, + } + + public enum ReplicationModeValues { + + None = 0, + + Primary = 1, + + Recovery = 2, + + Test_Replica = 3, + + NULL_ENUM_VALUE = 4, + } + + public enum ReplicationStateValues { + + Disabled = 0, + + Ready_for_replication = 1, + + Waiting_to_complete_initial_replication = 2, + + Replicating = 3, + + Synced_replication_complete = 4, + + Recovered = 5, + + Committed = 6, + + Suspended = 7, + + Critical = 8, + + Waiting_to_start_resynchronization = 9, + + Resynchronizing = 10, + + Resynchronization_suspended = 11, + + NULL_ENUM_VALUE = 12, + } + + // Enumerator implementation for enumerating instances of the class. + public class SummaryInformationCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public SummaryInformationCollection(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 SummaryInformation(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new SummaryInformationEnumerator(privColObj.GetEnumerator()); + } + + public class SummaryInformationEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public SummaryInformationEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new SummaryInformation(((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_SyntheticEthernetPortSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SyntheticEthernetPortSettingData.cs new file mode 100644 index 00000000000..caa74fe5ac0 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SyntheticEthernetPortSettingData.cs @@ -0,0 +1,1083 @@ +// 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_SyntheticEthernetPortSettingData + public class SyntheticEthernetPortSettingData : 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_SyntheticEthernetPortSettingData"; + + // 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 SyntheticEthernetPortSettingData() { + this.InitializeObject(null, null, null); + } + + public SyntheticEthernetPortSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(SyntheticEthernetPortSettingData.ConstructPath(keyInstanceID)), null); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(SyntheticEthernetPortSettingData.ConstructPath(keyInstanceID)), null); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public SyntheticEthernetPortSettingData(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 SyntheticEthernetPortSettingData(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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDesiredVLANEndpointModeNull { + get { + if ((curObj["DesiredVLANEndpointMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DesiredVLANEndpointMode { + get { + if ((curObj["DesiredVLANEndpointMode"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DesiredVLANEndpointMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEndpointMode { + get { + return ((string)(curObj["OtherEndpointMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStaticMacAddressNull { + get { + if ((curObj["StaticMacAddress"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates a static MAC address.\nThis is a read-only property, but it can be chang" + + "ed using the ModifyVirtualSystemResources method of the Msvm_VirtualSystemManage" + + "mentService class.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool StaticMacAddress { + get { + if ((curObj["StaticMacAddress"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["StaticMacAddress"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"A free-form string array of identifiers of this resource presented to the virtual computer system's operating system. The indexes and values per index are defined on a per resource basis (that is, for each enumerated ResourceType value). This property is set to ""GUID"". +This is a read-only property, but it can be changed using the ModifyVirtualSystemResources method of the sd class.")] + public string[] VirtualSystemIdentifiers { + get { + return ((string[])(curObj["VirtualSystemIdentifiers"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + 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 ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDesiredVLANEndpointMode() { + if ((this.IsDesiredVLANEndpointModeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStaticMacAddress() { + if ((this.IsStaticMacAddressNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == 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_SyntheticEthernetPortSettingData"; + 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 SyntheticEthernetPortSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static SyntheticEthernetPortSettingDataCollection 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_SyntheticEthernetPortSettingData"; + 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 SyntheticEthernetPortSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static SyntheticEthernetPortSettingDataCollection 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_SyntheticEthernetPortSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new SyntheticEthernetPortSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static SyntheticEthernetPortSettingData 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 SyntheticEthernetPortSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class SyntheticEthernetPortSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public SyntheticEthernetPortSettingDataCollection(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 SyntheticEthernetPortSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new SyntheticEthernetPortSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class SyntheticEthernetPortSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public SyntheticEthernetPortSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new SyntheticEthernetPortSettingData(((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_VirtualEthernetSwitch.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitch.cs new file mode 100644 index 00000000000..1d54ea7be21 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitch.cs @@ -0,0 +1,1386 @@ +// 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_VirtualEthernetSwitch + public class VirtualEthernetSwitch : 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_VirtualEthernetSwitch"; + + // 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 VirtualEthernetSwitch() { + this.InitializeObject(null, null, null); + } + + public VirtualEthernetSwitch(string keyCreationClassName, string keyName) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualEthernetSwitch.ConstructPath(keyCreationClassName, keyName)), null); + } + + public VirtualEthernetSwitch(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualEthernetSwitch.ConstructPath(keyCreationClassName, keyName)), null); + } + + public VirtualEthernetSwitch(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualEthernetSwitch(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualEthernetSwitch(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualEthernetSwitch(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualEthernetSwitch(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 VirtualEthernetSwitch(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(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 ushort[] Dedicated { + get { + return ((ushort[])(curObj["Dedicated"])); + } + } + + [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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] IdentifyingDescriptions { + get { + return ((string[])(curObj["IdentifyingDescriptions"])); + } + } + + [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 IsMaxIOVOffloadsNull { + get { + if ((curObj["MaxIOVOffloads"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum number of SR-IOV Virtual Function offloads available on this switch.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxIOVOffloads { + get { + if ((curObj["MaxIOVOffloads"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxIOVOffloads"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxVMQOffloadsNull { + get { + if ((curObj["MaxVMQOffloads"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum number of VMQ offloads allowed for a port on this switch.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxVMQOffloads { + get { + if ((curObj["MaxVMQOffloads"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxVMQOffloads"])); + } + set { + curObj["MaxVMQOffloads"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string NameFormat { + get { + return ((string)(curObj["NameFormat"])); + } + } + + [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[] OtherDedicatedDescriptions { + get { + return ((string[])(curObj["OtherDedicatedDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherIdentifyingInfo { + get { + return ((string[])(curObj["OtherIdentifyingInfo"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] PowerManagementCapabilities { + get { + return ((ushort[])(curObj["PowerManagementCapabilities"])); + } + } + + [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 IsResetCapabilityNull { + get { + if ((curObj["ResetCapability"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResetCapability { + get { + if ((curObj["ResetCapability"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResetCapability"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Roles { + get { + return ((string[])(curObj["Roles"])); + } + } + + [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 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 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 ShouldSerializeMaxIOVOffloads() { + if ((this.IsMaxIOVOffloadsNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxVMQOffloads() { + if ((this.IsMaxVMQOffloadsNull == false)) { + return true; + } + return false; + } + + private void ResetMaxVMQOffloads() { + curObj["MaxVMQOffloads"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + 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 ShouldSerializeResetCapability() { + if ((this.IsResetCapabilityNull == 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 strPath = "ROOT\\virtualization\\v2:Msvm_VirtualEthernetSwitch"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); + 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 VirtualEthernetSwitchCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualEthernetSwitchCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualEthernetSwitchCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualEthernetSwitchCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualEthernetSwitchCollection 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_VirtualEthernetSwitch"; + 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 VirtualEthernetSwitchCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualEthernetSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualEthernetSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualEthernetSwitchCollection 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_VirtualEthernetSwitch", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualEthernetSwitchCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualEthernetSwitch 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 VirtualEthernetSwitch(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + 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) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint SetPowerState(uint PowerState, System.DateTime Time) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); + inParams["PowerState"] = ((uint)(PowerState)); + inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", 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 VirtualEthernetSwitchCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualEthernetSwitchCollection(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 VirtualEthernetSwitch(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualEthernetSwitchEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualEthernetSwitchEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualEthernetSwitchEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualEthernetSwitch(((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_VirtualEthernetSwitchManagementService.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitchManagementService.cs new file mode 100644 index 00000000000..639e0070f52 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitchManagementService.cs @@ -0,0 +1,1515 @@ +// 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_VirtualEthernetSwitchManagementService + public class VirtualEthernetSwitchManagementService : 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. + private static string CreatedClassName = "Msvm_VirtualEthernetSwitchManagementService"; + + // 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 VirtualEthernetSwitchManagementService() { + this.InitializeObject(null, null, null); + } + + public VirtualEthernetSwitchManagementService(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualEthernetSwitchManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualEthernetSwitchManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualEthernetSwitchManagementService(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 VirtualEthernetSwitchManagementService(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(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)] + 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 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_VirtualEthernetSwitchManagementService"; + 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 VirtualEthernetSwitchManagementServiceCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualEthernetSwitchManagementServiceCollection 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_VirtualEthernetSwitchManagementService"; + 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 VirtualEthernetSwitchManagementServiceCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualEthernetSwitchManagementServiceCollection 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_VirtualEthernetSwitchManagementService", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualEthernetSwitchManagementServiceCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualEthernetSwitchManagementService 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 VirtualEthernetSwitchManagementService(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint AddFeatureSettings(System.Management.ManagementPath AffectedConfiguration, string[] FeatureSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingFeatureSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AddFeatureSettings"); + inParams["AffectedConfiguration"] = ((System.Management.ManagementPath)(AffectedConfiguration)).Path; + inParams["FeatureSettings"] = ((string[])(FeatureSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddFeatureSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + ResultingFeatureSettings = null; + if ((outParams.Properties["ResultingFeatureSettings"] != null)) { + int len = ((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingFeatureSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingFeatureSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint AddResourceSettings(System.Management.ManagementPath AffectedConfiguration, string[] ResourceSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingResourceSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AddResourceSettings"); + inParams["AffectedConfiguration"] = ((System.Management.ManagementPath)(AffectedConfiguration)).Path; + inParams["ResourceSettings"] = ((string[])(ResourceSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddResourceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + ResultingResourceSettings = null; + if ((outParams.Properties["ResultingResourceSettings"] != null)) { + int len = ((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingResourceSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingResourceSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint DefineSystem(System.Management.ManagementPath ReferenceConfiguration, string[] ResourceSettings, string SystemSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath ResultingSystem) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("DefineSystem"); + inParams["ReferenceConfiguration"] = ((System.Management.ManagementPath)(ReferenceConfiguration)).Path; + inParams["ResourceSettings"] = ((string[])(ResourceSettings)); + inParams["SystemSettings"] = ((string)(SystemSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DefineSystem", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + ResultingSystem = null; + if ((outParams.Properties["ResultingSystem"] != null)) { + ResultingSystem = new System.Management.ManagementPath(outParams.Properties["ResultingSystem"].ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingSystem = null; + return System.Convert.ToUInt32(0); + } + } + + public uint DestroySystem(System.Management.ManagementPath AffectedSystem, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("DestroySystem"); + inParams["AffectedSystem"] = ((System.Management.ManagementPath)(AffectedSystem)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DestroySystem", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifyFeatureSettings(string[] FeatureSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingFeatureSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyFeatureSettings"); + inParams["FeatureSettings"] = ((string[])(FeatureSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyFeatureSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + ResultingFeatureSettings = null; + if ((outParams.Properties["ResultingFeatureSettings"] != null)) { + int len = ((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingFeatureSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingFeatureSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifyResourceSettings(string[] ResourceSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingResourceSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyResourceSettings"); + inParams["ResourceSettings"] = ((string[])(ResourceSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyResourceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + ResultingResourceSettings = null; + if ((outParams.Properties["ResultingResourceSettings"] != null)) { + int len = ((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingResourceSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingResourceSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifySystemSettings(string SystemSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifySystemSettings"); + inParams["SystemSettings"] = ((string)(SystemSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifySystemSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RemoveFeatureSettings(System.Management.ManagementPath[] FeatureSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RemoveFeatureSettings"); + if ((FeatureSettings != null)) { + int len = ((System.Array)(FeatureSettings)).Length; + string[] arrProp = new string[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(FeatureSettings)).GetValue(iCounter))).Path; + } + inParams["FeatureSettings"] = arrProp; + } + else { + inParams["FeatureSettings"] = null; + } + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveFeatureSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RemoveResourceSettings(System.Management.ManagementPath[] ResourceSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RemoveResourceSettings"); + if ((ResourceSettings != null)) { + int len = ((System.Array)(ResourceSettings)).Length; + string[] arrProp = new string[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(ResourceSettings)).GetValue(iCounter))).Path; + } + inParams["ResourceSettings"] = arrProp; + } + else { + inParams["ResourceSettings"] = null; + } + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveResourceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) + { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.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) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.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 VirtualEthernetSwitchManagementServiceCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualEthernetSwitchManagementServiceCollection(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 VirtualEthernetSwitchManagementService(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualEthernetSwitchManagementServiceEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualEthernetSwitchManagementServiceEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualEthernetSwitchManagementServiceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualEthernetSwitchManagementService(((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_VirtualHardDiskSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualHardDiskSettingData.cs new file mode 100644 index 00000000000..0a8aec37e58 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualHardDiskSettingData.cs @@ -0,0 +1,1051 @@ +// 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_VirtualHardDiskSettingData + public class VirtualHardDiskSettingData : 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. + private static string CreatedClassName = "Msvm_VirtualHardDiskSettingData"; + + // 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 VirtualHardDiskSettingData() { + this.InitializeObject(null, null, null); + } + + public VirtualHardDiskSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualHardDiskSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualHardDiskSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualHardDiskSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualHardDiskSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualHardDiskSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualHardDiskSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualHardDiskSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualHardDiskSettingData(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 VirtualHardDiskSettingData(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 IsBlockSizeNull { + get { + if ((curObj["BlockSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The block size used by the virtual hard disk")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint BlockSize { + get { + if ((curObj["BlockSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["BlockSize"])); + } + set { + curObj["BlockSize"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + set { + curObj["Caption"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + set { + curObj["Description"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + set { + curObj["ElementName"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFormatNull { + get { + if ((curObj["Format"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The format for the virtual hard disk.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public FormatValues Format { + get { + if ((curObj["Format"] == null)) { + return ((FormatValues)(System.Convert.ToInt32(0))); + } + return ((FormatValues)(System.Convert.ToInt32(curObj["Format"]))); + } + set { + if ((FormatValues.NULL_ENUM_VALUE == value)) { + curObj["Format"] = null; + } + else { + curObj["Format"] = value; + } + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + set { + curObj["InstanceID"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLogicalSectorSizeNull { + get { + if ((curObj["LogicalSectorSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The logical sector size used by the virtual hard disk")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint LogicalSectorSize { + get { + if ((curObj["LogicalSectorSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["LogicalSectorSize"])); + } + set { + curObj["LogicalSectorSize"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxInternalSizeNull { + get { + if ((curObj["MaxInternalSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum size of the virtual hard disk as viewable by the virtual machine, in " + + "bytes. The specified size will be rounded up to the next largest multiple of the" + + " sector size.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxInternalSize { + get { + if ((curObj["MaxInternalSize"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxInternalSize"])); + } + set { + curObj["MaxInternalSize"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The parent of the virtual hard disk. If the virtual hard disk does not have a par" + + "ent, then this field is empty.")] + public string ParentPath { + get { + return ((string)(curObj["ParentPath"])); + } + set { + curObj["ParentPath"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The path of the virtual hard disk.")] + public string Path0 { + get { + return ((string)(curObj["Path"])); + } + set { + curObj["Path"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPhysicalSectorSizeNull { + get { + if ((curObj["PhysicalSectorSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The physical sector size used by the virtual hard disk")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint PhysicalSectorSize { + get { + if ((curObj["PhysicalSectorSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["PhysicalSectorSize"])); + } + set { + curObj["PhysicalSectorSize"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTypeNull { + get { + if ((curObj["Type"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The type of virtual hard disk.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public TypeValues Type { + get { + if ((curObj["Type"] == null)) { + return ((TypeValues)(System.Convert.ToInt32(0))); + } + return ((TypeValues)(System.Convert.ToInt32(curObj["Type"]))); + } + set { + if ((TypeValues.NULL_ENUM_VALUE == value)) { + curObj["Type"] = null; + } + else { + curObj["Type"] = value; + } + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + 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 ShouldSerializeBlockSize() { + if ((this.IsBlockSizeNull == false)) { + return true; + } + return false; + } + + private void ResetBlockSize() { + curObj["BlockSize"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetCaption() { + curObj["Caption"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetDescription() { + curObj["Description"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetElementName() { + curObj["ElementName"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeFormat() { + if ((this.IsFormatNull == false)) { + return true; + } + return false; + } + + private void ResetFormat() { + curObj["Format"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeLogicalSectorSize() { + if ((this.IsLogicalSectorSizeNull == false)) { + return true; + } + return false; + } + + private void ResetLogicalSectorSize() { + curObj["LogicalSectorSize"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeMaxInternalSize() { + if ((this.IsMaxInternalSizeNull == false)) { + return true; + } + return false; + } + + private void ResetMaxInternalSize() { + curObj["MaxInternalSize"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetParentPath() { + curObj["ParentPath"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetPath0() { + curObj["Path"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializePhysicalSectorSize() { + if ((this.IsPhysicalSectorSizeNull == false)) { + return true; + } + return false; + } + + private void ResetPhysicalSectorSize() { + curObj["PhysicalSectorSize"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeType() { + if ((this.IsTypeNull == false)) { + return true; + } + return false; + } + + private void ResetType() { + curObj["Type"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + [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_VirtualHardDiskSettingData"; + 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 VirtualHardDiskSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualHardDiskSettingDataCollection 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_VirtualHardDiskSettingData"; + 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 VirtualHardDiskSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualHardDiskSettingDataCollection 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_VirtualHardDiskSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualHardDiskSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualHardDiskSettingData 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 VirtualHardDiskSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public enum FormatValues { + + VHD = 2, + + VHDX = 3, + + NULL_ENUM_VALUE = 0, + } + + public enum TypeValues { + + Fixed = 2, + + Dynamic = 3, + + Differencing = 4, + + NULL_ENUM_VALUE = 0, + } + + // Enumerator implementation for enumerating instances of the class. + public class VirtualHardDiskSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualHardDiskSettingDataCollection(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 VirtualHardDiskSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualHardDiskSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualHardDiskSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualHardDiskSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualHardDiskSettingData(((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_VirtualSystemManagementService.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementService.cs new file mode 100644 index 00000000000..ba014b1e322 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementService.cs @@ -0,0 +1,1916 @@ +// 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_VirtualSystemManagementService + public class VirtualSystemManagementService : 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. + private static string CreatedClassName = "Msvm_VirtualSystemManagementService"; + + // 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 VirtualSystemManagementService() { + this.InitializeObject(null, null, null); + } + + public VirtualSystemManagementService(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public VirtualSystemManagementService(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public VirtualSystemManagementService(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualSystemManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualSystemManagementService(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualSystemManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualSystemManagementService(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 VirtualSystemManagementService(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(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)] + 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 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_VirtualSystemManagementService"; + 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 VirtualSystemManagementServiceCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualSystemManagementServiceCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualSystemManagementServiceCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualSystemManagementServiceCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualSystemManagementServiceCollection 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_VirtualSystemManagementService"; + 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 VirtualSystemManagementServiceCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualSystemManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualSystemManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualSystemManagementServiceCollection 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_VirtualSystemManagementService", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualSystemManagementServiceCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualSystemManagementService 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 VirtualSystemManagementService(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint AddFeatureSettings(System.Management.ManagementPath AffectedConfiguration, string[] FeatureSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingFeatureSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AddFeatureSettings"); + inParams["AffectedConfiguration"] = ((System.Management.ManagementPath)(AffectedConfiguration)).Path; + inParams["FeatureSettings"] = ((string[])(FeatureSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddFeatureSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + ResultingFeatureSettings = null; + if ((outParams.Properties["ResultingFeatureSettings"] != null && outParams.Properties["ResultingFeatureSettings"].Value != null)) + { + int len = ((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingFeatureSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingFeatureSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint AddFibreChannelChap(string[] FcPortSettings, byte SecretEncoding, byte[] SharedSecret) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AddFibreChannelChap"); + inParams["FcPortSettings"] = ((string[])(FcPortSettings)); + inParams["SecretEncoding"] = ((byte)(SecretEncoding)); + inParams["SharedSecret"] = ((byte[])(SharedSecret)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddFibreChannelChap", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint AddKvpItems(string[] DataItems, System.Management.ManagementPath TargetSystem, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AddKvpItems"); + inParams["DataItems"] = ((string[])(DataItems)); + inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddKvpItems", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 AddResourceSettings(System.Management.ManagementPath AffectedConfiguration, string[] ResourceSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingResourceSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AddResourceSettings"); + inParams["AffectedConfiguration"] = ((System.Management.ManagementPath)(AffectedConfiguration)).Path; + inParams["ResourceSettings"] = ((string[])(ResourceSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddResourceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + ResultingResourceSettings = null; + if ((outParams.Properties["ResultingResourceSettings"] != null && outParams.Properties["ResultingResourceSettings"].Value != null)) + { + int len = ((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingResourceSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingResourceSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint DefineSystem(string ReferenceConfigurationPath, string[] ResourceSettings, string SystemSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath ResultingSystem) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("DefineSystem"); + inParams["ReferenceConfiguration"] = ReferenceConfigurationPath; + inParams["ResourceSettings"] = ResourceSettings; + inParams["SystemSettings"] = SystemSettings; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DefineSystem", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + ResultingSystem = null; + if ((outParams.Properties["ResultingSystem"] != null && outParams.Properties["ResultingSystem"].Value != null)) + { + ResultingSystem = new System.Management.ManagementPath((string)outParams.Properties["ResultingSystem"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingSystem = null; + return System.Convert.ToUInt32(0); + } + } + + public uint DestroySystem(System.Management.ManagementPath AffectedSystem, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("DestroySystem"); + inParams["AffectedSystem"] = ((System.Management.ManagementPath)(AffectedSystem)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DestroySystem", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 ExportSystemDefinition(System.Management.ManagementPath ComputerSystem, string ExportDirectory, string ExportSettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ExportSystemDefinition"); + inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; + inParams["ExportDirectory"] = ((string)(ExportDirectory)); + inParams["ExportSettingData"] = ((string)(ExportSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ExportSystemDefinition", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 FormatError(string[] Errors, out string ErrorMessage) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("FormatError"); + inParams["Errors"] = ((string[])(Errors)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("FormatError", inParams, null); + ErrorMessage = System.Convert.ToString(outParams.Properties["ErrorMessage"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + ErrorMessage = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GenerateWwpn(uint NumberOfWwpns, out string[] GeneratedWwpn) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GenerateWwpn"); + inParams["NumberOfWwpns"] = ((uint)(NumberOfWwpns)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GenerateWwpn", inParams, null); + GeneratedWwpn = ((string[])(outParams.Properties["GeneratedWwpn"].Value)); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + GeneratedWwpn = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GetCurrentWwpnFromGenerator(out string CurrentWwpn) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetCurrentWwpnFromGenerator", inParams, null); + CurrentWwpn = System.Convert.ToString(outParams.Properties["CurrentWwpn"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + CurrentWwpn = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GetDefinitionFileSummaryInformation(string[] DefinitionFiles, out System.Management.ManagementBaseObject[] SummaryInformation) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GetDefinitionFileSummaryInformation"); + inParams["DefinitionFiles"] = ((string[])(DefinitionFiles)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetDefinitionFileSummaryInformation", inParams, null); + SummaryInformation = ((System.Management.ManagementBaseObject[])(outParams.Properties["SummaryInformation"].Value)); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + SummaryInformation = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GetSizeOfSystemFiles(System.Management.ManagementPath Vssd, out ulong Size) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GetSizeOfSystemFiles"); + inParams["Vssd"] = ((System.Management.ManagementPath)(Vssd)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetSizeOfSystemFiles", inParams, null); + Size = System.Convert.ToUInt64(outParams.Properties["Size"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Size = System.Convert.ToUInt64(0); + return System.Convert.ToUInt32(0); + } + } + + public uint GetSummaryInformation(uint[] RequestedInformation, System.Management.ManagementPath[] SettingData, out System.Management.ManagementBaseObject[] SummaryInformation) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GetSummaryInformation"); + inParams["RequestedInformation"] = ((uint[])(RequestedInformation)); + if ((SettingData != null)) { + int len = ((System.Array)(SettingData)).Length; + string[] arrProp = new string[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(SettingData)).GetValue(iCounter))).Path; + } + inParams["SettingData"] = arrProp; + } + else { + inParams["SettingData"] = null; + } + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetSummaryInformation", inParams, null); + SummaryInformation = ((System.Management.ManagementBaseObject[])(outParams.Properties["SummaryInformation"].Value)); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + SummaryInformation = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GetVirtualSystemThumbnailImage(ushort HeightPixels, System.Management.ManagementPath TargetSystem, ushort WidthPixels, out byte[] ImageData) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GetVirtualSystemThumbnailImage"); + inParams["HeightPixels"] = ((ushort)(HeightPixels)); + inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; + inParams["WidthPixels"] = ((ushort)(WidthPixels)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetVirtualSystemThumbnailImage", inParams, null); + ImageData = ((byte[])(outParams.Properties["ImageData"].Value)); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + ImageData = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ImportSnapshotDefinitions(System.Management.ManagementPath PlannedSystem, string SnapshotFolder, out System.Management.ManagementPath[] ImportedSnapshots, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ImportSnapshotDefinitions"); + inParams["PlannedSystem"] = ((System.Management.ManagementPath)(PlannedSystem)).Path; + inParams["SnapshotFolder"] = ((string)(SnapshotFolder)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ImportSnapshotDefinitions", inParams, null); + ImportedSnapshots = null; + if ((outParams.Properties["ImportedSnapshots"] != null && outParams.Properties["ImportedSnapshots"].Value != null)) + { + int len = ((System.Array)(outParams.Properties["ImportedSnapshots"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ImportedSnapshots"].Value)).GetValue(iCounter).ToString()); + } + ImportedSnapshots = arrToRet; + } + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + ImportedSnapshots = null; + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ImportSystemDefinition(bool GenerateNewSystemIdentifier, string SnapshotFolder, string SystemDefinitionFile, out System.Management.ManagementPath ImportedSystem, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ImportSystemDefinition"); + inParams["GenerateNewSystemIdentifier"] = ((bool)(GenerateNewSystemIdentifier)); + inParams["SnapshotFolder"] = ((string)(SnapshotFolder)); + inParams["SystemDefinitionFile"] = ((string)(SystemDefinitionFile)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ImportSystemDefinition", inParams, null); + ImportedSystem = null; + if ((outParams.Properties["ImportedSystem"] != null && outParams.Properties["ImportedSystem"].Value != null)) + { + ImportedSystem = new System.Management.ManagementPath(outParams.Properties["ImportedSystem"].ToString()); + } + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + ImportedSystem = null; + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifyDiskMergeSettings(string SettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyDiskMergeSettings"); + inParams["SettingData"] = ((string)(SettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyDiskMergeSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 ModifyFeatureSettings(string[] FeatureSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingFeatureSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyFeatureSettings"); + inParams["FeatureSettings"] = ((string[])(FeatureSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyFeatureSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + ResultingFeatureSettings = null; + if ((outParams.Properties["ResultingFeatureSettings"] != null && outParams.Properties["ResultingFeatureSettings"].Value != null)) + { + int len = ((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingFeatureSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingFeatureSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifyKvpItems(string[] DataItems, System.Management.ManagementPath TargetSystem, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyKvpItems"); + inParams["DataItems"] = ((string[])(DataItems)); + inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyKvpItems", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 ModifyResourceSettings(string[] ResourceSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingResourceSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyResourceSettings"); + inParams["ResourceSettings"] = ((string[])(ResourceSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyResourceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + ResultingResourceSettings = null; + if ((outParams.Properties["ResultingResourceSettings"] != null && outParams.Properties["ResultingResourceSettings"].Value != null)) + { + int len = ((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingResourceSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingResourceSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifyServiceSettings(string SettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyServiceSettings"); + inParams["SettingData"] = ((string)(SettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyServiceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 ModifySystemSettings(string SystemSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifySystemSettings"); + inParams["SystemSettings"] = ((string)(SystemSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifySystemSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 RealizePlannedSystem(System.Management.ManagementPath PlannedSystem, out System.Management.ManagementPath Job, out System.Management.ManagementPath ResultingSystem) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RealizePlannedSystem"); + inParams["PlannedSystem"] = ((System.Management.ManagementPath)(PlannedSystem)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RealizePlannedSystem", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + ResultingSystem = null; + if ((outParams.Properties["ResultingSystem"] != null)) { + ResultingSystem = new System.Management.ManagementPath(outParams.Properties["ResultingSystem"].ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingSystem = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RemoveFeatureSettings(System.Management.ManagementPath[] FeatureSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RemoveFeatureSettings"); + if ((FeatureSettings != null)) { + int len = ((System.Array)(FeatureSettings)).Length; + string[] arrProp = new string[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(FeatureSettings)).GetValue(iCounter))).Path; + } + inParams["FeatureSettings"] = arrProp; + } + else { + inParams["FeatureSettings"] = null; + } + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveFeatureSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 RemoveFibreChannelChap(string[] FcPortSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RemoveFibreChannelChap"); + inParams["FcPortSettings"] = ((string[])(FcPortSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveFibreChannelChap", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RemoveKvpItems(string[] DataItems, System.Management.ManagementPath TargetSystem, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RemoveKvpItems"); + inParams["DataItems"] = ((string[])(DataItems)); + inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveKvpItems", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 RemoveResourceSettings(System.Management.ManagementPath[] ResourceSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RemoveResourceSettings"); + if ((ResourceSettings != null)) { + int len = ((System.Array)(ResourceSettings)).Length; + string[] arrProp = new string[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(ResourceSettings)).GetValue(iCounter))).Path; + } + inParams["ResourceSettings"] = arrProp; + } + else { + inParams["ResourceSettings"] = null; + } + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveResourceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 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((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint SetGuestNetworkAdapterConfiguration(System.Management.ManagementPath ComputerSystem, string[] NetworkConfiguration, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetGuestNetworkAdapterConfiguration"); + inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; + inParams["NetworkConfiguration"] = ((string[])(NetworkConfiguration)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetGuestNetworkAdapterConfiguration", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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 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); + } + } + + public uint ValidatePlannedSystem(System.Management.ManagementPath PlannedSystem, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ValidatePlannedSystem"); + inParams["PlannedSystem"] = ((System.Management.ManagementPath)(PlannedSystem)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ValidatePlannedSystem", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != 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); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class VirtualSystemManagementServiceCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualSystemManagementServiceCollection(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 VirtualSystemManagementService(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualSystemManagementServiceEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualSystemManagementServiceEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualSystemManagementServiceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualSystemManagementService(((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_VirtualSystemManagementServiceSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementServiceSettingData.cs new file mode 100644 index 00000000000..390140f2b5e --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementServiceSettingData.cs @@ -0,0 +1,809 @@ +// 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_VirtualSystemManagementServiceSettingData + public class VirtualSystemManagementServiceSettingData : 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_VirtualSystemManagementServiceSettingData"; + + // 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 VirtualSystemManagementServiceSettingData() { + this.InitializeObject(null, null, null); + } + + public VirtualSystemManagementServiceSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemManagementServiceSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemManagementServiceSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualSystemManagementServiceSettingData(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 VirtualSystemManagementServiceSettingData(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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Used by OEMs to allow BIOS-locked Windows operating systems to run in the virtual machine. This string must be exactly 32 characters in length. +This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] + public string BiosLockString { + get { + return ((string)(curObj["BiosLockString"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The WorldWideNodeName address for dynamically generated WorldWideName addresses u" + + "sed for Synthetic HBAs.\nThis is a read-only property, but it can be changed usin" + + "g the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService cl" + + "ass.")] + public string CurrentWWNNAddress { + get { + return ((string)(curObj["CurrentWWNNAddress"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The default external data root. By default, \"root\\ProgramData\\Microsoft\\Windows\\V" + + "irtualization\".\nThis is a read-only property, but it can be changed using the Mo" + + "difyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] + public string DefaultExternalDataRoot { + get { + return ((string)(curObj["DefaultExternalDataRoot"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The default virtual hard disk path. By default, \"root\\Users\\Public\\Documents\\Virt" + + "ual Hard Disks\".\nThis is a read-only property, but it can be changed using the M" + + "odifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] + public string DefaultVirtualHardDiskPath { + get { + return ((string)(curObj["DefaultVirtualHardDiskPath"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHbaLunTimeoutNull { + get { + if ((curObj["HbaLunTimeout"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"This property describes the amount of time that the Synthetic FC virtual device will wait for a LUN to appear before starting a virtual machine. +This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint HbaLunTimeout { + get { + if ((curObj["HbaLunTimeout"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["HbaLunTimeout"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum MAC address for dynamically generated MAC addresses.\nThis is a read-o" + + "nly property, but it can be changed using the ModifyServiceSettings method of th" + + "e Msvm_VirtualSystemManagementService class.")] + public string MaximumMacAddress { + get { + return ((string)(curObj["MaximumMacAddress"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum WorldWidePortName address for dynamically generated WorldWideName add" + + "resses used for Synthetic HBAs.\nThis is a read-only property, but it can be chan" + + "ged using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementSe" + + "rvice class.")] + public string MaximumWWPNAddress { + get { + return ((string)(curObj["MaximumWWPNAddress"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The minimum MAC address for dynamically generated MAC addresses.\nThis is a read-o" + + "nly property, but it can be changed using the ModifyServiceSettings method of th" + + "e Msvm_VirtualSystemManagementService class.")] + public string MinimumMacAddress { + get { + return ((string)(curObj["MinimumMacAddress"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The minimum WorldWidePortName address for dynamically generated WorldWideName add" + + "resses used for Synthetic HBAs.\nThis is a read-only property, but it can be chan" + + "ged using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementSe" + + "rvice class.")] + public string MinimumWWPNAddress { + get { + return ((string)(curObj["MinimumWWPNAddress"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNumaSpanningEnabledNull { + get { + if ((curObj["NumaSpanningEnabled"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Reserved for future use.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool NumaSpanningEnabled { + get { + if ((curObj["NumaSpanningEnabled"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["NumaSpanningEnabled"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Controls memory allocation for the VMs on non-uniform memory access (NUMA) system" + + "s.\nThis is a read-only property, but it can be changed using the ModifyServiceSe" + + "ttings method of the Msvm_VirtualSystemManagementService class.")] + public string PrimaryOwnerContact { + get { + return ((string)(curObj["PrimaryOwnerContact"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Describes how the primary system owner can be reached (for example, phone number or e-mail address). By default, empty. This name may not exceed 256 characters in length. +This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] + public string PrimaryOwnerName { + get { + return ((string)(curObj["PrimaryOwnerName"])); + } + } + + 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 ShouldSerializeHbaLunTimeout() { + if ((this.IsHbaLunTimeoutNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeNumaSpanningEnabled() { + if ((this.IsNumaSpanningEnabledNull == 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_VirtualSystemManagementServiceSettingData"; + 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 VirtualSystemManagementServiceSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualSystemManagementServiceSettingDataCollection 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_VirtualSystemManagementServiceSettingData"; + 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 VirtualSystemManagementServiceSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualSystemManagementServiceSettingDataCollection 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_VirtualSystemManagementServiceSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualSystemManagementServiceSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualSystemManagementServiceSettingData 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 VirtualSystemManagementServiceSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class VirtualSystemManagementServiceSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualSystemManagementServiceSettingDataCollection(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 VirtualSystemManagementServiceSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualSystemManagementServiceSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualSystemManagementServiceSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualSystemManagementServiceSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualSystemManagementServiceSettingData(((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_VirtualSystemSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemSettingData.cs new file mode 100644 index 00000000000..4877957ad6b --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemSettingData.cs @@ -0,0 +1,1690 @@ +// 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_VirtualSystemSettingData + public class VirtualSystemSettingData : 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_VirtualSystemSettingData"; + + // 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 VirtualSystemSettingData() { + this.InitializeObject(null, null, null); + } + + public VirtualSystemSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualSystemSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualSystemSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualSystemSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualSystemSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualSystemSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualSystemSettingData(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 VirtualSystemSettingData(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(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Any additional information provided to the recovery action. The meaning of this property is defined by the action in AutomaticRecoveryAction. If AutomaticRecoveryAction is 0 (""None"") or 1 (""Restart""), this value is NULL. If AutomaticRecoveryAction is 2 (""Revert to Snapshot""), this is the object path to a snapshot that should be applied on failure of the virtual machine worker process. +This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] + public string AdditionalRecoveryInformation { + get { + return ((string)(curObj["AdditionalRecoveryInformation"])); + } + set { + curObj["AdditionalRecoveryInformation"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAllowFullSCSICommandSetNull { + get { + if ((curObj["AllowFullSCSICommandSet"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Indicates whether SCSI commands from the guest operating system are passed to pass-through disks. If TRUE, SCSI commands emitted by the guest operating system to pass-through disks are not filtered.It is recommended that SCSI filtering remains enabled for production deployments. +This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class. +Windows Server 2008: The AllowFullSCSICommandSet property is not supported.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AllowFullSCSICommandSet { + get { + if ((curObj["AllowFullSCSICommandSet"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AllowFullSCSICommandSet"])); + } + set { + curObj["AllowFullSCSICommandSet"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAllowReducedFcRedundancyNull { + get { + if ((curObj["AllowReducedFcRedundancy"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Indicates whether live migration of a virtual machine that is configured with a virtual FC adapter is allowed to a destination machine, without doing any checks for the existence of paths to the storage devices on the destination +The default value of this property is FALSE. If set to TRUE, the VM can be live migrated to a target machine which may have no or reduced paths to the target FC devices. The guest operating system may lose connectivity to storage and may behave in an unpredictable manner. + This property should be cleared after a live migration")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AllowReducedFcRedundancy { + get { + if ((curObj["AllowReducedFcRedundancy"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AllowReducedFcRedundancy"])); + } + set { + curObj["AllowReducedFcRedundancy"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticRecoveryActionNull { + get { + if ((curObj["AutomaticRecoveryAction"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort AutomaticRecoveryAction { + get { + if ((curObj["AutomaticRecoveryAction"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["AutomaticRecoveryAction"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticShutdownActionNull { + get { + if ((curObj["AutomaticShutdownAction"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort AutomaticShutdownAction { + get { + if ((curObj["AutomaticShutdownAction"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["AutomaticShutdownAction"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticStartupActionNull { + get { + if ((curObj["AutomaticStartupAction"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort AutomaticStartupAction { + get { + if ((curObj["AutomaticStartupAction"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["AutomaticStartupAction"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticStartupActionDelayNull { + get { + if ((curObj["AutomaticStartupActionDelay"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime AutomaticStartupActionDelay { + get { + if ((curObj["AutomaticStartupActionDelay"] != null)) { + return ToDateTime(((string)(curObj["AutomaticStartupActionDelay"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticStartupActionSequenceNumberNull { + get { + if ((curObj["AutomaticStartupActionSequenceNumber"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort AutomaticStartupActionSequenceNumber { + get { + if ((curObj["AutomaticStartupActionSequenceNumber"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["AutomaticStartupActionSequenceNumber"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The serial number of the base board for the virtual computer system.\nThis is a re" + + "ad-only property, but it can be changed using the ModifyVirtualSystem method of " + + "the Msvm_VirtualSystemManagementService class.")] + public string BaseBoardSerialNumber { + get { + return ((string)(curObj["BaseBoardSerialNumber"])); + } + set { + curObj["BaseBoardSerialNumber"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The globally-unique identifier for the BIOS of the virtual computer system.\nThis " + + "is a read-only property, but it can be changed using the ModifyVirtualSystem met" + + "hod of the Msvm_VirtualSystemManagementService class.")] + public string BIOSGUID { + get { + return ((string)(curObj["BIOSGUID"])); + } + set { + curObj["BIOSGUID"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsBIOSNumLockNull { + get { + if ((curObj["BIOSNumLock"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"This property is set to TRUE if the num lock key is set to on by the BIOS, FALSE if the num lock key is set to off by the BIOS. +This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool BIOSNumLock { + get { + if ((curObj["BIOSNumLock"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["BIOSNumLock"])); + } + set { + curObj["BIOSNumLock"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The serial number of the BIOS for the virtual computer system.\nThis is a read-onl" + + "y property, but it can be changed using the ModifyVirtualSystem method of the Ms" + + "vm_VirtualSystemManagementService class.")] + public string BIOSSerialNumber { + get { + return ((string)(curObj["BIOSSerialNumber"])); + } + set { + curObj["BIOSSerialNumber"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The boot order set within the BIOS of the virtual computer system. This property is an array of values, max length 4, where each value indicates a device to boot from. The virtual computer system will first attempt to boot from the device indicated by the first value within the array. If that device does not contain a boot sector, the virtual computer system will attempt to boot from the next device specified by the BootOrder property and so on. If no device specified within the BootOrder contains a boot sector the virtual computer system will fail to boot. The default value for a virtual computer system is [0, 1, 2, 3, 4]. +Value definitions: +0 (Floppy): The virtual computer system will attempt to boot from the floppy disk within the floppy drive. +1 (CD-ROM): The virtual computer system will attempt to boot from the first CD or DVD disk found with a boot sector. +2 (IDE Hard Drive): The virtual computer system will attempt to boot from the first hard drive found attached to an IDE controller with a boot sector. +3 (PXE Boot): The virtual computer system will attempt to PXE boot from the network. +4 (SCSI Hard Drive): The virtual computer system will attempt to boot from the first hard drive found attached to a SCSI controller with a boot sector. +5-65535: Reserved +This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] + public ushort[] BootOrder { + get { + return ((ushort[])(curObj["BootOrder"])); + } + set { + curObj["BootOrder"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The asset tag of the chassis for the virtual computer system.\nThis is a read-only" + + " property, but it can be changed using the ModifyVirtualSystem method of the Msv" + + "m_VirtualSystemManagementService class.")] + public string ChassisAssetTag { + get { + return ((string)(curObj["ChassisAssetTag"])); + } + set { + curObj["ChassisAssetTag"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The serial number of the chassis for the virtual computer system.\nThis is a read-" + + "only property, but it can be changed using the ModifyVirtualSystem method of the" + + " Msvm_VirtualSystemManagementService class.")] + public string ChassisSerialNumber { + get { + return ((string)(curObj["ChassisSerialNumber"])); + } + set { + curObj["ChassisSerialNumber"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ConfigurationDataRoot { + get { + return ((string)(curObj["ConfigurationDataRoot"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ConfigurationFile { + get { + return ((string)(curObj["ConfigurationFile"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ConfigurationID { + get { + return ((string)(curObj["ConfigurationID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCreationTimeNull { + get { + if ((curObj["CreationTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime CreationTime { + get { + if ((curObj["CreationTime"] != null)) { + return ToDateTime(((string)(curObj["CreationTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDebugChannelIdNull { + get { + if ((curObj["DebugChannelId"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The channel identifier used to debug the virtual system using the VUD unified deb" + + "ugger.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint DebugChannelId { + get { + if ((curObj["DebugChannelId"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["DebugChannelId"])); + } + set { + curObj["DebugChannelId"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDebugPortNull { + get { + if ((curObj["DebugPort"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The tcpip port used to debug the virtual system using synthetic debugging.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint DebugPort { + get { + if ((curObj["DebugPort"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["DebugPort"])); + } + set { + curObj["DebugPort"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDebugPortEnabledNull { + get { + if ((curObj["DebugPortEnabled"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Whether the virtual system is using synthetic debugging.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public DebugPortEnabledValues DebugPortEnabled { + get { + if ((curObj["DebugPortEnabled"] == null)) { + return ((DebugPortEnabledValues)(System.Convert.ToInt32(3))); + } + return ((DebugPortEnabledValues)(System.Convert.ToInt32(curObj["DebugPortEnabled"]))); + } + set { + if ((DebugPortEnabledValues.NULL_ENUM_VALUE == value)) { + curObj["DebugPortEnabled"] = null; + } + else { + curObj["DebugPortEnabled"] = value; + } + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsIncrementalBackupEnabledNull { + get { + if ((curObj["IncrementalBackupEnabled"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates whether the Hyper-V VSS writer supports taking incremental backup of th" + + "is Virtual machine.\nThis is a read-write property.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool IncrementalBackupEnabled { + get { + if ((curObj["IncrementalBackupEnabled"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["IncrementalBackupEnabled"])); + } + set { + curObj["IncrementalBackupEnabled"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsIsSavedNull { + get { + if ((curObj["IsSaved"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"This property is set to TRUE if the configuration has a reference to a saved state file, FALSE if not. Note that this does not indicate the presence of such a file, only that the configuration specifies one. +This is a read-only property, it cannot be changed.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool IsSaved { + get { + if ((curObj["IsSaved"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["IsSaved"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string LogDataRoot { + get { + return ((string)(curObj["LogDataRoot"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Notes { + get { + return ((string[])(curObj["Notes"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The object path for the snapshot Msvm_VirtualSystemSettingData from which this ob" + + "ject is based. This property will be NULL if this object is not based off a snap" + + "shot.")] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string RecoveryFile { + get { + return ((string)(curObj["RecoveryFile"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SnapshotDataRoot { + get { + return ((string)(curObj["SnapshotDataRoot"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SuspendDataRoot { + get { + return ((string)(curObj["SuspendDataRoot"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SwapFileDataRoot { + get { + return ((string)(curObj["SwapFileDataRoot"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The version of the virtual system in a format of \"major.minor\", for example \"2.0\"" + + ".\nWindows Server 2008: The Version property is not supported.")] + public string Version { + get { + return ((string)(curObj["Version"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualNumaEnabledNull { + get { + if ((curObj["VirtualNumaEnabled"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Indicates whether virtual non-uniform memory access (NUMA) nodes are projected into the virtual machine. If FALSE, the virtual machine will have a single node. If TRUE, the number of virtual NUMA nodes projected into the virtual machine is determined from the values of the Msvm_ProcessorSettingData.MaxProcessorsPerNumaNode and Msvm_MemorySettingData.MaxMemoryBlocksPerNumaNode properties. +")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool VirtualNumaEnabled { + get { + if ((curObj["VirtualNumaEnabled"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["VirtualNumaEnabled"])); + } + set { + curObj["VirtualNumaEnabled"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The name of the CIM_ComputerSystem to which this setting data belongs")] + public string VirtualSystemIdentifier { + get { + return ((string)(curObj["VirtualSystemIdentifier"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualSystemType { + get { + return ((string)(curObj["VirtualSystemType"])); + } + } + + 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 void ResetAdditionalRecoveryInformation() { + curObj["AdditionalRecoveryInformation"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeAllowFullSCSICommandSet() { + if ((this.IsAllowFullSCSICommandSetNull == false)) { + return true; + } + return false; + } + + private void ResetAllowFullSCSICommandSet() { + curObj["AllowFullSCSICommandSet"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeAllowReducedFcRedundancy() { + if ((this.IsAllowReducedFcRedundancyNull == false)) { + return true; + } + return false; + } + + private void ResetAllowReducedFcRedundancy() { + curObj["AllowReducedFcRedundancy"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeAutomaticRecoveryAction() { + if ((this.IsAutomaticRecoveryActionNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticShutdownAction() { + if ((this.IsAutomaticShutdownActionNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticStartupAction() { + if ((this.IsAutomaticStartupActionNull == 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 ShouldSerializeAutomaticStartupActionDelay() { + if ((this.IsAutomaticStartupActionDelayNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticStartupActionSequenceNumber() { + if ((this.IsAutomaticStartupActionSequenceNumberNull == false)) { + return true; + } + return false; + } + + private void ResetBaseBoardSerialNumber() { + curObj["BaseBoardSerialNumber"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetBIOSGUID() { + curObj["BIOSGUID"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeBIOSNumLock() { + if ((this.IsBIOSNumLockNull == false)) { + return true; + } + return false; + } + + private void ResetBIOSNumLock() { + curObj["BIOSNumLock"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetBIOSSerialNumber() { + curObj["BIOSSerialNumber"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetBootOrder() { + curObj["BootOrder"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetChassisAssetTag() { + curObj["ChassisAssetTag"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetChassisSerialNumber() { + curObj["ChassisSerialNumber"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeCreationTime() { + if ((this.IsCreationTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDebugChannelId() { + if ((this.IsDebugChannelIdNull == false)) { + return true; + } + return false; + } + + private void ResetDebugChannelId() { + curObj["DebugChannelId"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeDebugPort() { + if ((this.IsDebugPortNull == false)) { + return true; + } + return false; + } + + private void ResetDebugPort() { + curObj["DebugPort"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeDebugPortEnabled() { + if ((this.IsDebugPortEnabledNull == false)) { + return true; + } + return false; + } + + private void ResetDebugPortEnabled() { + curObj["DebugPortEnabled"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeIncrementalBackupEnabled() { + if ((this.IsIncrementalBackupEnabledNull == false)) { + return true; + } + return false; + } + + private void ResetIncrementalBackupEnabled() { + curObj["IncrementalBackupEnabled"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeIsSaved() { + if ((this.IsIsSavedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualNumaEnabled() { + if ((this.IsVirtualNumaEnabledNull == false)) { + return true; + } + return false; + } + + private void ResetVirtualNumaEnabled() { + curObj["VirtualNumaEnabled"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + [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_VirtualSystemSettingData"; + 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 VirtualSystemSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualSystemSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualSystemSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualSystemSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualSystemSettingDataCollection 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_VirtualSystemSettingData"; + 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 VirtualSystemSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualSystemSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualSystemSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualSystemSettingDataCollection 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_VirtualSystemSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualSystemSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualSystemSettingData 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 VirtualSystemSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public enum DebugPortEnabledValues { + + Val__Off = 0, + + On = 1, + + OnAutoAssigned = 2, + + NULL_ENUM_VALUE = 3, + } + + // Enumerator implementation for enumerating instances of the class. + public class VirtualSystemSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualSystemSettingDataCollection(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 VirtualSystemSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualSystemSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualSystemSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualSystemSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualSystemSettingData(((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/Readme.txt b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/Readme.txt new file mode 100644 index 00000000000..0fc8d7cbc23 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/Readme.txt @@ -0,0 +1,20 @@ +Classes were generated on a hyper-v server using the Visual Studio GUI, but you can do the same using +mgmtclassgen.exe. Below are some examples: + +mgmtclassgen.exe Msvm_ComputerSystem /N root\virtualization /L CS /O CloudStack.Plugin.WmiWrappers /P ComputerSystem.cs +mgmtclassgen.exe Msvm_VirtualSystemManagementService /N root\virtualization /L CS /O CloudStack.Plugin.WmiWrappers /P VirtualSystemManagementService.cs +mgmtclassgen.exe Msvm_VirtualSystemGlobalSettingData /N root\virtualization /L CS /O CloudStack.Plugin.WmiWrappers /P VirtualSystemGlobalSettingData.cs + + +BUT, you have to tweak the generated code, because it does not deal with NULL method parameters properly. +E.g. when a method completes immediately, the returned out parameters include a "Job" property that has a NULL value. +The generated code will attempt to call ToString() on this NULL value. + +ALSO, you have to tweak the generated code to expose useful details such as the WMI name for the class. +E.g. the generated code creates a wrapper called class ComputerSystem for WMI objects of class Msvm_ComputerSystem. +Thus, there is a mismatch in the class name and the corresponding WMI class, and the WMI class name is a private +constant static member. The tweak involves making this member public. + + + + diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/WmiWrappers.csproj b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/WmiWrappers.csproj new file mode 100644 index 00000000000..da0c0d6ce7c --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/WmiWrappers.csproj @@ -0,0 +1,175 @@ + + + + + Debug + AnyCPU + {DB824727-BDC3-437C-A364-7A811D8A160F} + Library + Properties + CloudStack.Plugin.WmiWrappers + WmiWrappers + v4.5 + 512 + ..\ + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\NoUnitTestsDebug\ + DEBUG;TRACE + full + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + bin\NoUnitTests\ + TRACE + true + pdbonly + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\AWSSDK.1.5.23.0\lib\AWSSDK.dll + + + ..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll + + + ..\packages\log4net.2.0.0\lib\net40-full\log4net.dll + + + ..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll + + + ..\packages\NSubstitute.1.6.1.0\lib\NET40\NSubstitute.dll + + + + + + + + + + + ..\packages\xunit.1.9.2\lib\net20\xunit.dll + + + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + + + + + + + + + + diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/root.CIMV2.Win32_PerfFormattedData_Counters_ProcessorInformation.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/root.CIMV2.Win32_PerfFormattedData_Counters_ProcessorInformation.cs new file mode 100644 index 00000000000..0cf3735712e --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/root.CIMV2.Win32_PerfFormattedData_Counters_ProcessorInformation.cs @@ -0,0 +1,1754 @@ +// 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.CIMV2 { + 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.Win32_PerfFormattedData_Counters_ProcessorInformation + public class PerfFormattedData_Counters_ProcessorInformation : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "root\\CIMV2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Win32_PerfFormattedData_Counters_ProcessorInformation"; + + // 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 PerfFormattedData_Counters_ProcessorInformation() { + this.InitializeObject(null, null, null); + } + + public PerfFormattedData_Counters_ProcessorInformation(string keyName) { + this.InitializeObject(null, new System.Management.ManagementPath(PerfFormattedData_Counters_ProcessorInformation.ConstructPath(keyName)), null); + } + + public PerfFormattedData_Counters_ProcessorInformation(System.Management.ManagementScope mgmtScope, string keyName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(PerfFormattedData_Counters_ProcessorInformation.ConstructPath(keyName)), null); + } + + public PerfFormattedData_Counters_ProcessorInformation(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public PerfFormattedData_Counters_ProcessorInformation(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public PerfFormattedData_Counters_ProcessorInformation(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public PerfFormattedData_Counters_ProcessorInformation(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public PerfFormattedData_Counters_ProcessorInformation(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 PerfFormattedData_Counters_ProcessorInformation(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\\CIMV2"; + } + } + + [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 IsAverageIdleTimeNull { + get { + if ((curObj["AverageIdleTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Average Idle Time is the average idle duration in 100ns units observed between th" + + "e last two samples.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong AverageIdleTime { + get { + if ((curObj["AverageIdleTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["AverageIdleTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsC1TransitionsPersecNull { + get { + if ((curObj["C1TransitionsPersec"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"C1 Transitions/sec is the rate that the CPU enters the C1 low-power idle state. The CPU enters the C1 state when it is sufficiently idle and exits this state on any interrupt. This counter displays the difference between the values observed in the last two samples, divided by the duration of the sample interval.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong C1TransitionsPersec { + get { + if ((curObj["C1TransitionsPersec"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["C1TransitionsPersec"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsC2TransitionsPersecNull { + get { + if ((curObj["C2TransitionsPersec"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"C2 Transitions/sec is the rate that the CPU enters the C2 low-power idle state. The CPU enters the C2 state when it is sufficiently idle and exits this state on any interrupt. This counter displays the difference between the values observed in the last two samples, divided by the duration of the sample interval.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong C2TransitionsPersec { + get { + if ((curObj["C2TransitionsPersec"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["C2TransitionsPersec"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsC3TransitionsPersecNull { + get { + if ((curObj["C3TransitionsPersec"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"C3 Transitions/sec is the rate that the CPU enters the C3 low-power idle state. The CPU enters the C3 state when it is sufficiently idle and exits this state on any interrupt. This counter displays the difference between the values observed in the last two samples, divided by the duration of the sample interval.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong C3TransitionsPersec { + get { + if ((curObj["C3TransitionsPersec"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["C3TransitionsPersec"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("A short textual description (one-line string) for the statistic or metric.")] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsClockInterruptsPersecNull { + get { + if ((curObj["ClockInterruptsPersec"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Clock Interrupts/sec is the average rate, in incidents per second, at which the processor received and serviced clock tick interrupts. This counter displays the difference between the values observed in the last two samples, divided by the duration of the sample interval.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint ClockInterruptsPersec { + get { + if ((curObj["ClockInterruptsPersec"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["ClockInterruptsPersec"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("A textual description of the statistic or metric.")] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDPCRateNull { + get { + if ((curObj["DPCRate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"DPC Rate is the rate at which deferred procedure calls (DPCs) were added to the processors DPC queues between the timer ticks of the processor clock. DPCs are interrupts that run at alower priority than standard interrupts. Each processor has its own DPC queue. This counter measures the rate that DPCs were added to the queue, not the number of DPCs in the queue. This counter displays the last observed value only; it is not an average.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint DPCRate { + get { + if ((curObj["DPCRate"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["DPCRate"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDPCsQueuedPersecNull { + get { + if ((curObj["DPCsQueuedPersec"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"DPCs Queued/sec is the average rate, in incidents per second, at which deferred procedure calls (DPCs) were added to the processor's DPC queue. DPCs are interrupts that run at a lower priority than standard interrupts. Each processor has its own DPC queue. This counter measures the rate that DPCs are added to the queue, not the number of DPCs in the queue. This counter displays the difference between the values observed in the last two samples, divided by the duration of the sample interval.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint DPCsQueuedPersec { + get { + if ((curObj["DPCsQueuedPersec"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["DPCsQueuedPersec"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFrequency_ObjectNull { + get { + if ((curObj["Frequency_Object"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Frequency_Object { + get { + if ((curObj["Frequency_Object"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Frequency_Object"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFrequency_PerfTimeNull { + get { + if ((curObj["Frequency_PerfTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Frequency_PerfTime { + get { + if ((curObj["Frequency_PerfTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Frequency_PerfTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFrequency_Sys100NSNull { + get { + if ((curObj["Frequency_Sys100NS"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Frequency_Sys100NS { + get { + if ((curObj["Frequency_Sys100NS"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Frequency_Sys100NS"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsIdleBreakEventsPersecNull { + get { + if ((curObj["IdleBreakEventsPersec"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Idle Break Events/sec is the average rate, in incidents per second, at which the " + + "processor wakes from idle. This counter displays the difference between the val" + + "ues observed in the last two samples, divided by the duration of the sample inte" + + "rval.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong IdleBreakEventsPersec { + get { + if ((curObj["IdleBreakEventsPersec"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["IdleBreakEventsPersec"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInterruptsPersecNull { + get { + if ((curObj["InterruptsPersec"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Interrupts/sec is the average rate, in incidents per second, at which the processor received and serviced hardware interrupts. It does not include deferred procedure calls (DPCs), which are counted separately. This value is an indirect indicator of the activity of devices that generate interrupts, such as the system clock, the mouse, disk drivers, data communication lines, network interface cards, and other peripheral devices. These devices normally interrupt the processor when they have completed a task or require attention. Normal thread execution is suspended. The system clock typically interrupts the processor every 10 milliseconds, creating a background of interrupt activity. This counter displays the difference between the values observed in the last two samples, divided by the duration of the sample interval.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint InterruptsPersec { + get { + if ((curObj["InterruptsPersec"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["InterruptsPersec"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Name property defines the label by which the statistic or metric is known. Wh" + + "en subclassed, the property can be overridden to be a Key property. ")] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsParkingStatusNull { + get { + if ((curObj["ParkingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Parking Status represents whether a processor is parked or not.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint ParkingStatus { + get { + if ((curObj["ParkingStatus"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["ParkingStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentC1TimeNull { + get { + if ((curObj["PercentC1Time"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"% C1 Time is the percentage of time the processor spends in the C1 low-power idle state. % C1 Time is a subset of the total processor idle time. C1 low-power idle state enables the processor to maintain its entire context and quickly return to the running state. Not all systems support the % C1 state.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PercentC1Time { + get { + if ((curObj["PercentC1Time"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PercentC1Time"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentC2TimeNull { + get { + if ((curObj["PercentC2Time"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"% C2 Time is the percentage of time the processor spends in the C2 low-power idle state. % C2 Time is a subset of the total processor idle time. C2 low-power idle state enables the processor to maintain the context of the system caches. The C2 power state is a lower power and higher exit latency state than C1. Not all systems support the C2 state.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PercentC2Time { + get { + if ((curObj["PercentC2Time"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PercentC2Time"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentC3TimeNull { + get { + if ((curObj["PercentC3Time"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"% C3 Time is the percentage of time the processor spends in the C3 low-power idle state. % C3 Time is a subset of the total processor idle time. When the processor is in the C3 low-power idle state it is unable to maintain the coherency of its caches. The C3 power state is a lower power and higher exit latency state than C2. Not all systems support the C3 state.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PercentC3Time { + get { + if ((curObj["PercentC3Time"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PercentC3Time"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentDPCTimeNull { + get { + if ((curObj["PercentDPCTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"% DPC Time is the percentage of time that the processor spent receiving and servicing deferred procedure calls (DPCs) during the sample interval. DPCs are interrupts that run at a lower priority than standard interrupts. % DPC Time is a component of % Privileged Time because DPCs are executed in privileged mode. They are counted separately and are not a component of the interrupt counters. This counter displays the average busy time as a percentage of the sample time.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PercentDPCTime { + get { + if ((curObj["PercentDPCTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PercentDPCTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentIdleTimeNull { + get { + if ((curObj["PercentIdleTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("% Idle Time is the percentage of time the processor is idle during the sample int" + + "erval")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PercentIdleTime { + get { + if ((curObj["PercentIdleTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PercentIdleTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentInterruptTimeNull { + get { + if ((curObj["PercentInterruptTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"% Interrupt Time is the time the processor spends receiving and servicing hardware interrupts during sample intervals. This value is an indirect indicator of the activity of devices that generate interrupts, such as the system clock, the mouse, disk drivers, data communication lines, network interface cards and other peripheral devices. These devices normally interrupt the processor when they have completed a task or require attention. Normal thread execution is suspended during interrupts. Most system clocks interrupt the processor every 10 milliseconds, creating a background of interrupt activity. suspends normal thread execution during interrupts. This counter displays the average busy time as a percentage of the sample time.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PercentInterruptTime { + get { + if ((curObj["PercentInterruptTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PercentInterruptTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentofMaximumFrequencyNull { + get { + if ((curObj["PercentofMaximumFrequency"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("% of Maximum Frequency is the percentage of the current processor\'s maximum frequ" + + "ency.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint PercentofMaximumFrequency { + get { + if ((curObj["PercentofMaximumFrequency"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["PercentofMaximumFrequency"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentPerformanceLimitNull { + get { + if ((curObj["PercentPerformanceLimit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"% Performance Limit is the performance the processor guarantees it can provide, as a percentage of the nominal performance of the processor. Performance can be limited by Windows power policy, or by the platform as a result of a power budget, overheating, or other hardware issues.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint PercentPerformanceLimit { + get { + if ((curObj["PercentPerformanceLimit"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["PercentPerformanceLimit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentPriorityTimeNull { + get { + if ((curObj["PercentPriorityTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"% Priority Time is the percentage of elapsed time that the processor spends executing threads that are not low priority. It is calculated by measuring the percentage of time that the processor spends executing low priority threads or the idle thread and then subtracting that value from 100%. (Each processor has an idle thread to which time is accumulated when no other threads are ready to run). This counter displays the average percentage of busy time observed during the sample interval excluding low priority background work. It should be noted that the accounting calculation of whether the processor is idle is performed at an internal sampling interval of the system clock tick. % Priority Time can therefore underestimate the processor utilization as the processor may be spending a lot of time servicing threads between the system clock sampling interval. Workload based timer applications are one example of applications which are more likely to be measured inaccurately as timers are signaled just after the sample is taken.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PercentPriorityTime { + get { + if ((curObj["PercentPriorityTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PercentPriorityTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentPrivilegedTimeNull { + get { + if ((curObj["PercentPrivilegedTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"% Privileged Time is the percentage of elapsed time that the process threads spent executing code in privileged mode. When a Windows system service in called, the service will often run in privileged mode to gain access to system-private data. Such data is protected from access by threads executing in user mode. Calls to the system can be explicit or implicit, such as page faults or interrupts. Unlike some early operating systems, Windows uses process boundaries for subsystem protection in addition to the traditional protection of user and privileged modes. Some work done by Windows on behalf of the application might appear in other subsystem processes in addition to the privileged time in the process.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PercentPrivilegedTime { + get { + if ((curObj["PercentPrivilegedTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PercentPrivilegedTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentPrivilegedUtilityNull { + get { + if ((curObj["PercentPrivilegedUtility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Privileged Utility is the amount of work a processor is completing while executing in privileged mode, as a percentage of the amount of work the processor could complete if it were running at its nominal performance and never idle. On some processors, Privileged Utility may exceed 100%.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PercentPrivilegedUtility { + get { + if ((curObj["PercentPrivilegedUtility"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PercentPrivilegedUtility"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentProcessorPerformanceNull { + get { + if ((curObj["PercentProcessorPerformance"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Processor Performance is the average performance of the processor while it is exe" + + "cuting instructions, as a percentage of the nominal performance of the processor" + + ". On some processors, Processor Performance may exceed 100%.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PercentProcessorPerformance { + get { + if ((curObj["PercentProcessorPerformance"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PercentProcessorPerformance"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentProcessorTimeNull { + get { + if ((curObj["PercentProcessorTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"% Processor Time is the percentage of elapsed time that the processor spends to execute a non-Idle thread. It is calculated by measuring the percentage of time that the processor spends executing the idle thread and then subtracting that value from 100%. (Each processor has an idle thread to which time is accumulated when no other threads are ready to run). This counter is the primary indicator of processor activity, and displays the average percentage of busy time observed during the sample interval. It should be noted that the accounting calculation of whether the processor is idle is performed at an internal sampling interval of the system clock tick. On todays fast processors, % Processor Time can therefore underestimate the processor utilization as the processor may be spending a lot of time servicing threads between the system clock sampling interval. Workload based timer applications are one example of applications which are more likely to be measured inaccurately as timers are signaled just after the sample is taken.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PercentProcessorTime { + get { + if ((curObj["PercentProcessorTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PercentProcessorTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentProcessorUtilityNull { + get { + if ((curObj["PercentProcessorUtility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Processor Utility is the amount of work a processor is completing, as a percentag" + + "e of the amount of work the processor could complete if it were running at its n" + + "ominal performance and never idle. On some processors, Processor Utility may exc" + + "eed 100%.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PercentProcessorUtility { + get { + if ((curObj["PercentProcessorUtility"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PercentProcessorUtility"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentUserTimeNull { + get { + if ((curObj["PercentUserTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"% User Time is the percentage of elapsed time the processor spends in the user mode. User mode is a restricted processing mode designed for applications, environment subsystems, and integral subsystems. The alternative, privileged mode, is designed for operating system components and allows direct access to hardware and all memory. The operating system switches application threads to privileged mode to access operating system services. This counter displays the average busy time as a percentage of the sample time.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PercentUserTime { + get { + if ((curObj["PercentUserTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PercentUserTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPerformanceLimitFlagsNull { + get { + if ((curObj["PerformanceLimitFlags"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Performance Limit Flags indicate reasons why the processor performance was limite" + + "d.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint PerformanceLimitFlags { + get { + if ((curObj["PerformanceLimitFlags"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["PerformanceLimitFlags"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsProcessorFrequencyNull { + get { + if ((curObj["ProcessorFrequency"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Processor Frequency is the frequency of the current processor in megahertz.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint ProcessorFrequency { + get { + if ((curObj["ProcessorFrequency"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["ProcessorFrequency"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsProcessorStateFlagsNull { + get { + if ((curObj["ProcessorStateFlags"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Processor State Flags")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint ProcessorStateFlags { + get { + if ((curObj["ProcessorStateFlags"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["ProcessorStateFlags"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimestamp_ObjectNull { + get { + if ((curObj["Timestamp_Object"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Timestamp_Object { + get { + if ((curObj["Timestamp_Object"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Timestamp_Object"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimestamp_PerfTimeNull { + get { + if ((curObj["Timestamp_PerfTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Timestamp_PerfTime { + get { + if ((curObj["Timestamp_PerfTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Timestamp_PerfTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimestamp_Sys100NSNull { + get { + if ((curObj["Timestamp_Sys100NS"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Timestamp_Sys100NS { + get { + if ((curObj["Timestamp_Sys100NS"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Timestamp_Sys100NS"])); + } + } + + 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 ShouldSerializeAverageIdleTime() { + if ((this.IsAverageIdleTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeC1TransitionsPersec() { + if ((this.IsC1TransitionsPersecNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeC2TransitionsPersec() { + if ((this.IsC2TransitionsPersecNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeC3TransitionsPersec() { + if ((this.IsC3TransitionsPersecNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeClockInterruptsPersec() { + if ((this.IsClockInterruptsPersecNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDPCRate() { + if ((this.IsDPCRateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDPCsQueuedPersec() { + if ((this.IsDPCsQueuedPersecNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeFrequency_Object() { + if ((this.IsFrequency_ObjectNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeFrequency_PerfTime() { + if ((this.IsFrequency_PerfTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeFrequency_Sys100NS() { + if ((this.IsFrequency_Sys100NSNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeIdleBreakEventsPersec() { + if ((this.IsIdleBreakEventsPersecNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeInterruptsPersec() { + if ((this.IsInterruptsPersecNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeParkingStatus() { + if ((this.IsParkingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentC1Time() { + if ((this.IsPercentC1TimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentC2Time() { + if ((this.IsPercentC2TimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentC3Time() { + if ((this.IsPercentC3TimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentDPCTime() { + if ((this.IsPercentDPCTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentIdleTime() { + if ((this.IsPercentIdleTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentInterruptTime() { + if ((this.IsPercentInterruptTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentofMaximumFrequency() { + if ((this.IsPercentofMaximumFrequencyNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentPerformanceLimit() { + if ((this.IsPercentPerformanceLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentPriorityTime() { + if ((this.IsPercentPriorityTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentPrivilegedTime() { + if ((this.IsPercentPrivilegedTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentPrivilegedUtility() { + if ((this.IsPercentPrivilegedUtilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentProcessorPerformance() { + if ((this.IsPercentProcessorPerformanceNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentProcessorTime() { + if ((this.IsPercentProcessorTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentProcessorUtility() { + if ((this.IsPercentProcessorUtilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentUserTime() { + if ((this.IsPercentUserTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePerformanceLimitFlags() { + if ((this.IsPerformanceLimitFlagsNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeProcessorFrequency() { + if ((this.IsProcessorFrequencyNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeProcessorStateFlags() { + if ((this.IsProcessorStateFlagsNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimestamp_Object() { + if ((this.IsTimestamp_ObjectNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimestamp_PerfTime() { + if ((this.IsTimestamp_PerfTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimestamp_Sys100NS() { + if ((this.IsTimestamp_Sys100NSNull == 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 keyName) { + string strPath = "root\\CIMV2:Win32_PerfFormattedData_Counters_ProcessorInformation"; + strPath = string.Concat(strPath, string.Concat(".Name=", string.Concat("\"", string.Concat(keyName, "\"")))); + 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 PerfFormattedData_Counters_ProcessorInformationCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\CIMV2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Win32_PerfFormattedData_Counters_ProcessorInformation"; + pathObj.NamespacePath = "root\\CIMV2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new PerfFormattedData_Counters_ProcessorInformationCollection(clsObject.GetInstances(enumOptions)); + } + + public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\CIMV2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Win32_PerfFormattedData_Counters_ProcessorInformation", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new PerfFormattedData_Counters_ProcessorInformationCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static PerfFormattedData_Counters_ProcessorInformation 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 PerfFormattedData_Counters_ProcessorInformation(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class PerfFormattedData_Counters_ProcessorInformationCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public PerfFormattedData_Counters_ProcessorInformationCollection(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 PerfFormattedData_Counters_ProcessorInformation(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new PerfFormattedData_Counters_ProcessorInformationEnumerator(privColObj.GetEnumerator()); + } + + public class PerfFormattedData_Counters_ProcessorInformationEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public PerfFormattedData_Counters_ProcessorInformationEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new PerfFormattedData_Counters_ProcessorInformation(((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/buildagent.sh b/plugins/hypervisors/hyperv/buildagent.sh new file mode 100755 index 00000000000..e5bff6e3153 --- /dev/null +++ b/plugins/hypervisors/hyperv/buildagent.sh @@ -0,0 +1,28 @@ +#!/bin/bash +# 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. +export EnableNuGetPackageRestore=true +wget http://nuget.org/nuget.exe +mv nuget.exe ./DotNet/ServerResource/.nuget/NuGet.exe +chmod a+x ./DotNet/ServerResource/.nuget/NuGet.exe +if [ "$1" == "true" ] ; then + echo " skipping tests" + xbuild /p:Configuration="NoUnitTests" /p:BuildWithMono="true" ./DotNet/ServerResource/ServerResource.sln +else + echo " running tests " + xbuild /p:BuildWithMono="true" ./DotNet/ServerResource/ServerResource.sln +fi diff --git a/plugins/hypervisors/hyperv/conf/agent.properties b/plugins/hypervisors/hyperv/conf/agent.properties new file mode 100644 index 00000000000..4e61451b0ff --- /dev/null +++ b/plugins/hypervisors/hyperv/conf/agent.properties @@ -0,0 +1,35 @@ +#Storage +#Tue Feb 12 10:08:17 GMT 2013 +local.storage.path=E\:\\Disks\\Disks +cpus=8 +resource=com.cloud.hypervisor.hyperv.resource.HypervResource +type=Routing +ipaddress=10.70.176.29 +private.mac.address=101F742C6B88 +# If localhost is used, mac address is blank. +#private.ip.address=127.0.0.1 +#private.mac.address= +local.storage.uuid=5fe2bad3-d785-394e-9949-89786b8a63d2 +capabilities=hvm +cpuspeed=2130 +port=8250 +hyperv.python.module.script=cloudstackcmds.py +memory=34359738368 +host=camldonall01.citrite.net +pod=1 +gateway.ip.address=10.70.176.1 +guid=16f85622-4508-415e-b13a-49a39bb14e4d +#guid=generate_from_private.ip.address +cluster=2 +zone=1 +local.secondary.storage.path=c\:\\Secondary +workers=5 +agent.executable=C\:\\cygwin\\home\\Administrator\\github\\cshv3\\plugins\\hypervisors\\hyperv\\DotNET\\ServerResource\\AgentShell\\bin\\Debug\\AgentShell.exe +private.ip.netmask=255.255.240.0 +HypervResource.id=5 +hyperv.python.module.dir=C\:\\cygwin\\home\\Administrator\\github\\cshv3\\plugins\\hypervisors\\hyperv\\scripts\\hyperv\\ +DefaultVirtualDiskFolder=E\:\\Disks\\ +TestCoreCount=8 +TestCoreMhz=2133 +TestMemoryMb=34350288896 +TestDom0MinMemoryMb=2147483648 diff --git a/plugins/hypervisors/hyperv/conf/developer.properties.template b/plugins/hypervisors/hyperv/conf/developer.properties.template new file mode 100644 index 00000000000..a70a136f38c --- /dev/null +++ b/plugins/hypervisors/hyperv/conf/developer.properties.template @@ -0,0 +1,55 @@ +# 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. + +#instance=AH +#private.macaddr.start=00:16:3e:77:01:01 +#private.ipaddr.start=192.168.166.128 + +#instance=KM +#private.macaddr.start=00:16:3e:77:02:01 +#private.ipaddr.start=192.168.167.128 + +#instance=KY +#private.macaddr.start=00:16:3e:77:03:01 +#private.ipaddr.start=192.168.168.128 + +#instance=WC +#private.macaddr.start=00:16:3e:77:04:01 +#private.ipaddr.start=192.168.169.128 + +#instance=CV +#private.macaddr.start=00:16:3e:77:05:01 +#private.ipaddr.start=192.168.170.128 + +#instance=KS +#private.macaddr.start=00:16:3e:77:06:01 +#private.ipaddr.start=192.168.171.128 + +#instance=ES +#private.macaddr.start=00:16:3e:77:07:01 +#private.ipaddr.start=192.168.172.128 + +#instance=RC +#private.macaddr.start=00:16:3e:77:08:01 +#private.ipaddr.start=192.168.173.128 + +#instance=AX +#private.macaddr.start=00:16:3e:77:09:01 +#private.ipaddr.start=192.168.174.128 + +private.macaddr.start=@private.macaddr.start@ +private.ipaddr.start=@private.ipaddr.start@ diff --git a/plugins/hypervisors/hyperv/conf/environment.properties.in b/plugins/hypervisors/hyperv/conf/environment.properties.in new file mode 100644 index 00000000000..514161a13fc --- /dev/null +++ b/plugins/hypervisors/hyperv/conf/environment.properties.in @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# management server compile-time environment parameters + +paths.pid=@PIDDIR@ +paths.script=@COMMONLIBDIR@ diff --git a/plugins/hypervisors/hyperv/conf/log4j-cloud.xml b/plugins/hypervisors/hyperv/conf/log4j-cloud.xml new file mode 100644 index 00000000000..1e97ce9e218 --- /dev/null +++ b/plugins/hypervisors/hyperv/conf/log4j-cloud.xml @@ -0,0 +1,93 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/hypervisors/hyperv/conf/log4j-cloud.xml.in b/plugins/hypervisors/hyperv/conf/log4j-cloud.xml.in new file mode 100644 index 00000000000..fdbba19e903 --- /dev/null +++ b/plugins/hypervisors/hyperv/conf/log4j-cloud.xml.in @@ -0,0 +1,93 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/hypervisors/hyperv/conf/log4j.xml b/plugins/hypervisors/hyperv/conf/log4j.xml new file mode 100644 index 00000000000..1e97ce9e218 --- /dev/null +++ b/plugins/hypervisors/hyperv/conf/log4j.xml @@ -0,0 +1,93 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/hypervisors/hyperv/pom.xml b/plugins/hypervisors/hyperv/pom.xml new file mode 100644 index 00000000000..19aa28a10fa --- /dev/null +++ b/plugins/hypervisors/hyperv/pom.xml @@ -0,0 +1,163 @@ + + + 4.0.0 + cloud-plugin-hypervisor-hyperv + Apache CloudStack Plugin - Hypervisor Hyper-V + + org.apache.cloudstack + cloudstack-plugins + 4.3.0-SNAPSHOT + ../../pom.xml + + + false + true + + + + org.apache.cloudstack + cloud-agent + ${project.version} + + + org.apache.cloudstack + cloud-core + ${project.version} + + + org.mortbay.jetty + jetty + 6.1.26 + + + org.apache.cloudstack + cloud-utils + ${project.version} + tests + test + + + + install + src + test + + + resources + + + conf + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + java + com.cloud.agent.AgentShell + + + + org.apache.maven.plugins + maven-jar-plugin + + + + test-jar + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + **/HypervDirectConnectResourceTest.* + + + none + + ${skipTests} + + + + + + + + hyperv-agent + + + hyperv-agent + + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + compile + + exec + + + + + bash + + ./buildagent.sh + ${skipTests} + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + none + + + **/HypervDirectConnectResourceTest.java + + ${skipFunctionalTests} + + + + + + + diff --git a/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/hyperv-compute/module.properties b/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/hyperv-compute/module.properties new file mode 100644 index 00000000000..439b7d503a3 --- /dev/null +++ b/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/hyperv-compute/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=hyperv-compute +parent=compute \ No newline at end of file diff --git a/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/hyperv-compute/spring-hyperv-compute-context.xml b/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/hyperv-compute/spring-hyperv-compute-context.xml new file mode 100644 index 00000000000..63521618df5 --- /dev/null +++ b/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/hyperv-compute/spring-hyperv-compute-context.xml @@ -0,0 +1,24 @@ + + + + + + + + diff --git a/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/hyperv-discoverer/module.properties b/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/hyperv-discoverer/module.properties new file mode 100644 index 00000000000..be51dd6f1d6 --- /dev/null +++ b/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/hyperv-discoverer/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=hyperv-discoverer +parent=discoverer \ No newline at end of file diff --git a/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/hyperv-discoverer/spring-hyperv-discoverer-context.xml b/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/hyperv-discoverer/spring-hyperv-discoverer-context.xml new file mode 100644 index 00000000000..ee394f08877 --- /dev/null +++ b/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/hyperv-discoverer/spring-hyperv-discoverer-context.xml @@ -0,0 +1,25 @@ + + + + + + + + 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 new file mode 100644 index 00000000000..f011ce03fa3 --- /dev/null +++ b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/discoverer/HypervServerDiscoverer.java @@ -0,0 +1,690 @@ +// 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.hypervisor.hyperv.discoverer; + +import java.io.File; +import java.io.IOException; +import java.net.InetAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.UnknownHostException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.UUID; + +import javax.ejb.Local; +import javax.inject.Inject; +import javax.naming.ConfigurationException; + +import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; +import org.apache.cloudstack.utils.identity.ManagementServerNode; +import org.apache.log4j.Logger; + +import com.cloud.agent.AgentManager; +import com.cloud.agent.Listener; +import com.cloud.agent.api.AgentControlAnswer; +import com.cloud.agent.api.AgentControlCommand; +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.Command; +import com.cloud.agent.api.ReadyCommand; +import com.cloud.agent.api.SetupAnswer; +import com.cloud.agent.api.SetupCommand; +import com.cloud.agent.api.StartupCommand; +import com.cloud.agent.api.StartupRoutingCommand; +import com.cloud.alert.AlertManager; +import com.cloud.configuration.Config; +import com.cloud.dc.ClusterDetailsDao; +import com.cloud.dc.ClusterVO; +import com.cloud.dc.DataCenterVO; +import com.cloud.dc.HostPodVO; +import com.cloud.dc.dao.ClusterDao; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.dc.dao.HostPodDao; +import com.cloud.exception.AgentUnavailableException; +import com.cloud.exception.ConnectionException; +import com.cloud.exception.DiscoveryException; +import com.cloud.exception.OperationTimedoutException; +import com.cloud.host.Host; +import com.cloud.host.HostEnvironment; +import com.cloud.host.HostVO; +import com.cloud.host.Status; +import com.cloud.host.dao.HostDao; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.hypervisor.hyperv.resource.HypervDirectConnectResource; +import com.cloud.resource.Discoverer; +import com.cloud.resource.DiscovererBase; +import com.cloud.resource.ResourceManager; +import com.cloud.resource.ResourceStateAdapter; +import com.cloud.resource.ServerResource; +import com.cloud.resource.UnableDeleteHostException; +import com.cloud.storage.JavaStorageLayer; +import com.cloud.storage.StorageLayer; +import com.cloud.utils.FileUtil; +import com.cloud.utils.NumbersUtil; +import com.cloud.utils.db.GlobalLock; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.script.Script; + +/** + * Methods to discover and managem a Hyper-V agent. Prepares a + * HypervDirectConnectResource corresponding to the agent on a Hyper-V + * hypervisor and manages its lifecycle. + */ +@Local(value = Discoverer.class) +public class HypervServerDiscoverer extends DiscovererBase implements + Discoverer, Listener, ResourceStateAdapter { + private static final Logger s_logger = Logger.getLogger(HypervServerDiscoverer.class); + + private String _instance; + private String _mountParent; + private int _timeout; + Random _rand = new Random(System.currentTimeMillis()); + + Map _storageMounts = new HashMap(); + StorageLayer _storage; + + @Inject + private HostDao _hostDao = null; + @Inject + private ClusterDao _clusterDao; + @Inject + private ClusterDetailsDao _clusterDetailsDao; + @Inject + private ResourceManager _resourceMgr; + @Inject + private HostPodDao _podDao; + @Inject + private DataCenterDao _dcDao; + @Inject + DataStoreManager _dataStoreMgr; + + // TODO: AgentManager and AlertManager not being used to transmit info, + // may want to reconsider. + @Inject + private AgentManager _agentMgr; + @Inject + private AlertManager _alertMgr; + + // Listener interface methods + + @Override + public final boolean processAnswers(final long agentId, final long seq, + final Answer[] answers) { + return false; + } + + @Override + public final boolean processCommands(final long agentId, final long seq, + final Command[] commands) { + return false; + } + + @Override + public final AgentControlAnswer processControlCommand(final long agentId, + final AgentControlCommand cmd) { + return null; + } + + @Override + public final void processConnect(final Host agent, + final StartupCommand cmd, final boolean forRebalance) + throws ConnectionException { + // Limit the commands we can process + if (!(cmd instanceof StartupRoutingCommand)) { + return; + } + + StartupRoutingCommand startup = (StartupRoutingCommand) cmd; + + // assert + if (startup.getHypervisorType() != HypervisorType.Hyperv) { + s_logger.debug("Not Hyper-V hypervisor, so moving on."); + return; + } + + long agentId = agent.getId(); + HostVO host = _hostDao.findById(agentId); + + // Our Hyper-V machines are not participating in pools, and the pool id + // we provide them is not persisted. + // This means the pool id can vary. + ClusterVO cluster = _clusterDao.findById(host.getClusterId()); + if (cluster.getGuid() == null) { + cluster.setGuid(startup.getPool()); + _clusterDao.update(cluster.getId(), cluster); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Setting up host " + agentId); + } + + String secondaryStorageUri = getSecondaryStorageStoreUrl(cluster.getDataCenterId()); + if (secondaryStorageUri == null) { + s_logger.debug("Secondary storage uri for dc " + cluster.getDataCenterId() + " couldn't be obtained"); + } else { + prepareSecondaryStorageStore(secondaryStorageUri); + } + + HostEnvironment env = new HostEnvironment(); + SetupCommand setup = new SetupCommand(env); + setup.setSecondaryStorage(secondaryStorageUri); + setup.setSystemVmIso("systemvm/" + getSystemVMIsoFileNameOnDatastore()); + if (!host.isSetup()) { + setup.setNeedSetup(true); + } + + try { + SetupAnswer answer = (SetupAnswer) _agentMgr.send(agentId, setup); + if (answer != null && answer.getResult()) { + host.setSetup(true); + // TODO: clean up magic numbers below + host.setLastPinged((System.currentTimeMillis() >> 10) - 5 * 60); + _hostDao.update(host.getId(), host); + if (answer.needReconnect()) { + throw new ConnectionException(false, + "Reinitialize agent after setup."); + } + return; + } else { + String reason = answer.getDetails(); + if (reason == null) { + reason = " details were null"; + } + s_logger.warn("Unable to setup agent " + agentId + " due to " + + reason); + } + // Error handling borrowed from XcpServerDiscoverer, may need to be + // updated. + } catch (AgentUnavailableException e) { + s_logger.warn("Unable to setup agent " + agentId + + " because it became unavailable.", e); + } catch (OperationTimedoutException e) { + s_logger.warn("Unable to setup agent " + agentId + + " because it timed out", e); + } + throw new ConnectionException(true, "Reinitialize agent after setup."); + } + + @Override + public final boolean processDisconnect(final long agentId, + final Status state) { + return false; + } + + @Override + public final boolean isRecurring() { + return false; + } + + @Override + public final int getTimeout() { + return 0; + } + + @Override + public final boolean processTimeout(final long agentId, final long seq) { + return false; + } + + // End Listener implementation + + // Returns server component used by server manager to operate the plugin. + // Server component is a ServerResource. If a connected agent is used, the + // ServerResource is + // ignored in favour of another created in response to + @Override + public final Map> find( + final long dcId, final Long podId, final Long clusterId, + final URI uri, final String username, final String password, + final List hostTags) throws DiscoveryException { + + if (s_logger.isInfoEnabled()) { + s_logger.info("Discover host. dc(zone): " + dcId + ", pod: " + + podId + ", cluster: " + clusterId + ", uri host: " + + uri.getHost()); + } + + // Assertions + if (podId == null) { + if (s_logger.isInfoEnabled()) { + s_logger.info("No pod is assigned, skipping the discovery in" + + " Hyperv discoverer"); + } + return null; + } + ClusterVO cluster = _clusterDao.findById(clusterId); // ClusterVO exists + // in the + // database + if (cluster == null) { + if (s_logger.isInfoEnabled()) { + s_logger.info("No cluster in database for cluster id " + + clusterId); + } + return null; + } + if (cluster.getHypervisorType() != HypervisorType.Hyperv) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Cluster " + clusterId + + "is not for Hyperv hypervisors"); + } + return null; + } + if (!uri.getScheme().equals("http")) { + String msg = "urlString is not http so we're not taking care of" + + " the discovery for this: " + uri; + s_logger.debug(msg); + return null; + } + + try { + String hostname = uri.getHost(); + InetAddress ia = InetAddress.getByName(hostname); + String agentIp = ia.getHostAddress(); + String uuidSeed = agentIp; + String guidWithTail = calcServerResourceGuid(uuidSeed) + + "-HypervResource"; + + if (_resourceMgr.findHostByGuid(guidWithTail) != null) { + s_logger.debug("Skipping " + agentIp + " because " + + guidWithTail + " is already in the database."); + return null; + } + + s_logger.info("Creating" + + HypervDirectConnectResource.class.getName() + + " HypervDummyResourceBase for zone/pod/cluster " + dcId + + "/" + podId + "/" + clusterId); + + // Some Hypervisors organise themselves in pools. + // The startup command tells us what pool they are using. + // In the meantime, we have to place a GUID corresponding to the + // pool in the database + // This GUID may change. + if (cluster.getGuid() == null) { + cluster.setGuid(UUID.nameUUIDFromBytes( + String.valueOf(clusterId).getBytes()).toString()); + _clusterDao.update(clusterId, cluster); + } + + // Settings required by all server resources managing a hypervisor + Map params = new HashMap(); + params.put("zone", Long.toString(dcId)); + params.put("pod", Long.toString(podId)); + params.put("cluster", Long.toString(clusterId)); + params.put("guid", guidWithTail); + params.put("ipaddress", agentIp); + params.put("sec.storage.url", getSecondaryStorageStoreUrl(dcId)); + + // Hyper-V specific settings + Map details = new HashMap(); + details.put("url", uri.getHost()); + details.put("username", username); + details.put("password", password); + details.put("cluster.guid", cluster.getGuid()); + + params.putAll(details); + + HypervDirectConnectResource resource = + new HypervDirectConnectResource(); + resource.configure(agentIp, params); + + // Assert + // TODO: test by using bogus URL and bogus virtual path in URL + ReadyCommand ping = new ReadyCommand(); + Answer pingAns = resource.executeRequest(ping); + if (pingAns == null || !pingAns.getResult()) { + String errMsg = + "Agent not running, or no route to agent on at " + + uri; + s_logger.debug(errMsg); + throw new DiscoveryException(errMsg); + } + + Map> resources = + new HashMap>(); + resources.put(resource, details); + + // 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()); + 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()); + s_logger.warn("Unable to instantiate " + uri.getHost(), e); + } catch (Exception e) { + String msg = " can't setup agent, due to " + e.toString() + " - " + + e.getMessage(); + s_logger.warn(msg); + } + return null; + } + + + private void prepareSecondaryStorageStore(String storageUrl) { + String mountPoint = getMountPoint(storageUrl); + + GlobalLock lock = GlobalLock.getInternLock("prepare.systemvm"); + try { + if(lock.lock(3600)) { + try { + File patchFolder = new File(mountPoint + "/systemvm"); + if(!patchFolder.exists()) { + if(!patchFolder.mkdirs()) { + String msg = "Unable to create systemvm folder on secondary storage. location: " + patchFolder.toString(); + s_logger.error(msg); + throw new CloudRuntimeException(msg); + } + } + + File srcIso = getSystemVMPatchIsoFile(); + File destIso = new File(mountPoint + "/systemvm/" + getSystemVMIsoFileNameOnDatastore()); + if(!destIso.exists()) { + s_logger.info("Copy System VM patch ISO file to secondary storage. source ISO: " + + srcIso.getAbsolutePath() + ", destination: " + destIso.getAbsolutePath()); + try { + FileUtil.copyfile(srcIso, destIso); + } catch(IOException e) { + s_logger.error("Unexpected exception ", e); + + String msg = "Unable to copy systemvm ISO on secondary storage. src location: " + srcIso.toString() + ", dest location: " + destIso; + s_logger.error(msg); + throw new CloudRuntimeException(msg); + } + } else { + if(s_logger.isTraceEnabled()) { + s_logger.trace("SystemVM ISO file " + destIso.getPath() + " already exists"); + } + } + } finally { + lock.unlock(); + } + } + } finally { + lock.releaseRef(); + } + } + + private String getMountPoint(String storageUrl) { + String mountPoint = null; + synchronized(_storageMounts) { + mountPoint = _storageMounts.get(storageUrl); + if(mountPoint != null) { + return mountPoint; + } + + URI uri; + try { + uri = new URI(storageUrl); + } catch (URISyntaxException e) { + s_logger.error("Invalid storage URL format ", e); + throw new CloudRuntimeException("Unable to create mount point due to invalid storage URL format " + storageUrl); + } + + mountPoint = mount(File.separator + File.separator + uri.getHost() + uri.getPath(), _mountParent, + uri.getScheme(), uri.getQuery()); + if(mountPoint == null) { + s_logger.error("Unable to create mount point for " + storageUrl); + return "/mnt/sec"; + } + + _storageMounts.put(storageUrl, mountPoint); + return mountPoint; + } + } + + protected String mount(String path, String parent, String scheme, String query) { + String mountPoint = setupMountPoint(parent); + if (mountPoint == null) { + s_logger.warn("Unable to create a mount point"); + return null; + } + + Script script = null; + String result = null; + if (scheme.equals("cifs")) { + Script command = new Script(true, "mount", _timeout, s_logger); + command.add("-t", "cifs"); + command.add(path); + command.add(mountPoint); + + if (query != null) { + query = query.replace('&', ','); + command.add("-o", query); + } + result = command.execute(); + } + + if (result != null) { + s_logger.warn("Unable to mount " + path + " due to " + result); + File file = new File(mountPoint); + if (file.exists()) { + file.delete(); + } + return null; + } + + // Change permissions for the mountpoint + script = new Script(true, "chmod", _timeout, s_logger); + script.add("-R", "777", mountPoint); + result = script.execute(); + if (result != null) { + s_logger.warn("Unable to set permissions for " + mountPoint + " due to " + result); + } + return mountPoint; + } + + private String setupMountPoint(String parent) { + String mountPoint = null; + long mshostId = ManagementServerNode.getManagementServerId(); + for (int i = 0; i < 10; i++) { + String mntPt = parent + File.separator + String.valueOf(mshostId) + "." + Integer.toHexString(_rand.nextInt(Integer.MAX_VALUE)); + File file = new File(mntPt); + if (!file.exists()) { + if (_storage.mkdir(mntPt)) { + mountPoint = mntPt; + break; + } + } + s_logger.error("Unable to create mount: " + mntPt); + } + + return mountPoint; + } + + private String getSystemVMIsoFileNameOnDatastore() { + String version = this.getClass().getPackage().getImplementationVersion(); + String fileName = "systemvm-" + version + ".iso"; + return fileName.replace(':', '-'); + } + + private File getSystemVMPatchIsoFile() { + // locate systemvm.iso + URL url = this.getClass().getClassLoader().getResource("vms/systemvm.iso"); + File isoFile = null; + if (url != null) { + isoFile = new File(url.getPath()); + } + + if(isoFile == null || !isoFile.exists()) { + isoFile = new File("/usr/share/cloudstack-common/vms/systemvm.iso"); + } + + assert(isoFile != null); + if(!isoFile.exists()) { + s_logger.error("Unable to locate systemvm.iso in your setup at " + isoFile.toString()); + } + return isoFile; + } + + private String getSecondaryStorageStoreUrl(long zoneId) { + String secUrl = null; + DataStore secStore = _dataStoreMgr.getImageStore(zoneId); + if (secStore != null) { + secUrl = secStore.getUri(); + } + + if (secUrl == null) { + s_logger.warn("Secondary storage uri couldn't be retrieved"); + } + + return secUrl; + } + + /** + * Encapsulate GUID calculation in public method to allow access to test + * programs. Works by converting a string to a GUID using + * UUID.nameUUIDFromBytes + * + * @param uuidSeed + * string to use to generate GUID + * + * @return GUID in form of a string. + */ + public static String calcServerResourceGuid(final String uuidSeed) { + String guid = UUID.nameUUIDFromBytes(uuidSeed.getBytes()).toString(); + return guid; + } + + // Adapter implementation: (facilitates plug in loading) + // Required because Discoverer extends Adapter + // Overrides Adapter.configure to always return true + // Inherit Adapter.getName + // Inherit Adapter.stop + // Inherit Adapter.start + @Override + public final boolean configure(final String name, final Map params) throws ConfigurationException { + super.configure(name, params); + + _mountParent = (String) params.get(Config.MountParent.key()); + if (_mountParent == null) { + _mountParent = File.separator + "mnt"; + } + + if (_instance != null) { + _mountParent = _mountParent + File.separator + _instance; + } + + String value = (String)params.get("scripts.timeout"); + _timeout = NumbersUtil.parseInt(value, 30) * 1000; + + _storage = (StorageLayer)params.get(StorageLayer.InstanceConfigKey); + if (_storage == null) { + _storage = new JavaStorageLayer(); + _storage.configure("StorageLayer", params); + } + + // TODO: allow timeout on we HTTPRequests to be configured + _agentMgr.registerForHostEvents(this, true, false, true); + _resourceMgr.registerResourceStateAdapter(this.getClass() + .getSimpleName(), this); + return true; + } + + // end of Adapter + + @Override + public void postDiscovery(final List hosts, final long msId) + throws DiscoveryException { + } + + @Override + public final Hypervisor.HypervisorType getHypervisorType() { + return Hypervisor.HypervisorType.Hyperv; + } + + // TODO: verify that it is okay to return true on null hypervisor + @Override + public final boolean matchHypervisor(final String hypervisor) { + if (hypervisor == null) { + return true; + } + return Hypervisor.HypervisorType.Hyperv.toString().equalsIgnoreCase( + hypervisor); + } + + // end of Discoverer + + // ResourceStateAdapter + @Override + public final HostVO createHostVOForConnectedAgent(final HostVO host, + final StartupCommand[] cmd) { + return null; + } + + // TODO: add test for method + @Override + public final HostVO createHostVOForDirectConnectAgent(final HostVO host, + final StartupCommand[] startup, final ServerResource resource, + final Map details, final List hostTags) { + StartupCommand firstCmd = startup[0]; + if (!(firstCmd instanceof StartupRoutingCommand)) { + return null; + } + + StartupRoutingCommand ssCmd = ((StartupRoutingCommand) firstCmd); + if (ssCmd.getHypervisorType() != HypervisorType.Hyperv) { + return null; + } + + s_logger.info("Host: " + host.getName() + + " connected with hypervisor type: " + HypervisorType.Hyperv + + ". Checking CIDR..."); + + HostPodVO pod = _podDao.findById(host.getPodId()); + DataCenterVO dc = _dcDao.findById(host.getDataCenterId()); + + _resourceMgr.checkCIDR(pod, dc, ssCmd.getPrivateIpAddress(), + ssCmd.getPrivateNetmask()); + + return _resourceMgr.fillRoutingHostVO(host, ssCmd, + HypervisorType.Hyperv, details, hostTags); + } + + // TODO: add test for method + @Override + public final DeleteHostAnswer deleteHost(final HostVO host, + final boolean isForced, final boolean isForceDeleteStorage) + throws UnableDeleteHostException { + // assert + if (host.getType() != Host.Type.Routing + || host.getHypervisorType() != HypervisorType.Hyperv) { + return null; + } + _resourceMgr.deleteRoutingHost(host, isForced, isForceDeleteStorage); + return new DeleteHostAnswer(true); + } + + @Override + public final boolean stop() { + _resourceMgr.unregisterResourceStateAdapter(this.getClass() + .getSimpleName()); + return super.stop(); + } + // end of ResourceStateAdapter + +} diff --git a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/guru/HypervGuru.java b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/guru/HypervGuru.java new file mode 100644 index 00000000000..8b79cae3f7d --- /dev/null +++ b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/guru/HypervGuru.java @@ -0,0 +1,68 @@ +// 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.hypervisor.hyperv.guru; + +import javax.ejb.Local; +import javax.inject.Inject; + +import com.cloud.agent.api.to.VirtualMachineTO; +import com.cloud.hypervisor.HypervisorGuru; +import com.cloud.hypervisor.HypervisorGuruBase; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.storage.GuestOSVO; +import com.cloud.storage.dao.GuestOSDao; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineProfile; + +/** + * Implementation of Hypervisor guru for Hyper-V. + **/ +@Local(value = HypervisorGuru.class) +public class HypervGuru extends HypervisorGuruBase implements HypervisorGuru { + + @Inject + private GuestOSDao _guestOsDao; + + @Override + public final HypervisorType getHypervisorType() { + return HypervisorType.Hyperv; + } + /** + * Prevent direct creation. + */ + protected HypervGuru() { + super(); + } + + @Override + public final VirtualMachineTO implement( + VirtualMachineProfile vm) { + VirtualMachineTO to = toVirtualMachineTO(vm); + + // Determine the VM's OS description + GuestOSVO guestOS = _guestOsDao.findById(vm.getVirtualMachine() + .getGuestOSId()); + to.setOs(guestOS.getDisplayName()); + + return to; + } + + @Override + public final boolean trackVmHostChange() { + return false; + } +} 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 new file mode 100644 index 00000000000..a8a09f6f98a --- /dev/null +++ b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java @@ -0,0 +1,1745 @@ +// 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.hypervisor.hyperv.resource; + +import java.io.File; +import java.io.IOException; +import java.net.ConnectException; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.channels.SocketChannel; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.UUID; + +import javax.ejb.Local; +import javax.inject.Inject; +import javax.naming.ConfigurationException; + +import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; +import org.apache.cloudstack.utils.identity.ManagementServerNode; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.util.EntityUtils; +import org.apache.log4j.Logger; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.CheckRouterAnswer; +import com.cloud.agent.api.CheckRouterCommand; +import com.cloud.agent.api.CheckS2SVpnConnectionsAnswer; +import com.cloud.agent.api.CheckS2SVpnConnectionsCommand; +import com.cloud.agent.api.Command; +import com.cloud.agent.api.GetDomRVersionAnswer; +import com.cloud.agent.api.GetDomRVersionCmd; +import com.cloud.agent.api.NetworkUsageAnswer; +import com.cloud.agent.api.NetworkUsageCommand; +import com.cloud.agent.api.PingCommand; +import com.cloud.agent.api.PingRoutingCommand; +import com.cloud.agent.api.PingTestCommand; +import com.cloud.agent.api.StartCommand; +import com.cloud.agent.api.StartupCommand; +import com.cloud.agent.api.StartupRoutingCommand; +import com.cloud.agent.api.StartupRoutingCommand.VmState; +import com.cloud.agent.api.StartupStorageCommand; +import com.cloud.agent.api.UnsupportedAnswer; +import com.cloud.agent.api.check.CheckSshAnswer; +import com.cloud.agent.api.check.CheckSshCommand; +import com.cloud.agent.api.routing.CreateIpAliasCommand; +import com.cloud.agent.api.routing.DeleteIpAliasCommand; +import com.cloud.agent.api.routing.DhcpEntryCommand; +import com.cloud.agent.api.routing.DnsMasqConfigCommand; +import com.cloud.agent.api.routing.IpAliasTO; +import com.cloud.agent.api.routing.IpAssocAnswer; +import com.cloud.agent.api.routing.IpAssocCommand; +import com.cloud.agent.api.routing.LoadBalancerConfigCommand; +import com.cloud.agent.api.routing.NetworkElementCommand; +import com.cloud.agent.api.routing.SavePasswordCommand; +import com.cloud.agent.api.routing.SetFirewallRulesAnswer; +import com.cloud.agent.api.routing.SetFirewallRulesCommand; +import com.cloud.agent.api.routing.SetPortForwardingRulesAnswer; +import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; +import com.cloud.agent.api.routing.SetSourceNatAnswer; +import com.cloud.agent.api.routing.SetSourceNatCommand; +import com.cloud.agent.api.routing.SetStaticNatRulesAnswer; +import com.cloud.agent.api.routing.SetStaticNatRulesCommand; +import com.cloud.agent.api.routing.SetStaticRouteAnswer; +import com.cloud.agent.api.routing.SetStaticRouteCommand; +import com.cloud.agent.api.routing.Site2SiteVpnCfgCommand; +import com.cloud.agent.api.routing.VmDataCommand; +import com.cloud.agent.api.to.DhcpTO; +import com.cloud.agent.api.to.FirewallRuleTO; +import com.cloud.agent.api.to.IpAddressTO; +import com.cloud.agent.api.to.PortForwardingRuleTO; +import com.cloud.agent.api.to.StaticNatRuleTO; +import com.cloud.agent.api.to.VirtualMachineTO; +import com.cloud.configuration.Config; +import com.cloud.dc.DataCenter.NetworkType; +import com.cloud.host.Host.Type; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.network.HAProxyConfigurator; +import com.cloud.network.LoadBalancerConfigurator; +import com.cloud.network.Networks.RouterPrivateIpStrategy; +import com.cloud.network.rules.FirewallRule; +import com.cloud.resource.ServerResource; +import com.cloud.resource.ServerResourceBase; +import com.cloud.serializer.GsonHelper; +import com.cloud.storage.JavaStorageLayer; +import com.cloud.storage.StorageLayer; +import com.cloud.utils.FileUtil; +import com.cloud.utils.NumbersUtil; +import com.cloud.utils.Pair; +import com.cloud.utils.StringUtils; +import com.cloud.utils.db.GlobalLock; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.net.NetUtils; +import com.cloud.utils.script.Script; +import com.cloud.utils.ssh.SshHelper; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineName; +import com.google.gson.Gson; + +/** + * Implementation of dummy resource to be returned from discoverer. + **/ +@Local(value = ServerResource.class) +public class HypervDirectConnectResource extends ServerResourceBase implements ServerResource { + public static final int DEFAULT_AGENT_PORT = 8250; + private static final Logger s_logger = Logger + .getLogger(HypervDirectConnectResource.class.getName()); + + private static final Gson s_gson = GsonHelper.getGson(); + private String _zoneId; + private String _podId; + private String _clusterId; + private String _guid; + private String _agentIp; + private int _port = DEFAULT_AGENT_PORT; + protected final long _ops_timeout = 900000; // 15 minutes time out to time + + protected final int _retry = 24; + protected final int _sleep = 10000; + protected final int DEFAULT_DOMR_SSHPORT = 3922; + + private String _clusterGuid; + + // Used by initialize to assert object configured before + // initialize called. + private boolean _configureCalled = false; + + private String _username; + private String _password; + + @Override + public final Type getType() { + return Type.Routing; + } + + @Override + public final StartupCommand[] initialize() { + // assert + if (!_configureCalled) { + String errMsg = + this.getClass().getName() + + " requires configure() be called before" + + " initialize()"; + s_logger.error(errMsg); + } + + // Create default StartupRoutingCommand, then customise + StartupRoutingCommand defaultStartRoutCmd = + new StartupRoutingCommand(0, 0, 0, 0, null, + Hypervisor.HypervisorType.Hyperv, + RouterPrivateIpStrategy.HostLocal, + new HashMap()); + + // Identity within the data centre is decided by CloudStack kernel, + // and passed via ServerResource.configure() + defaultStartRoutCmd.setDataCenter(_zoneId); + defaultStartRoutCmd.setPod(_podId); + defaultStartRoutCmd.setCluster(_clusterId); + defaultStartRoutCmd.setGuid(_guid); + defaultStartRoutCmd.setName(_name); + defaultStartRoutCmd.setPrivateIpAddress(_agentIp); + defaultStartRoutCmd.setStorageIpAddress(_agentIp); + defaultStartRoutCmd.setPool(_clusterGuid); + + s_logger.debug("Generated StartupRoutingCommand for _agentIp \"" + + _agentIp + "\""); + + // TODO: does version need to be hard coded. + defaultStartRoutCmd.setVersion("4.2.0"); + + // Specifics of the host's resource capacity and network configuration + // comes from the host itself. CloudStack sanity checks network + // configuration + // and uses capacity info for resource allocation. + Command[] startCmds = + requestStartupCommand(new Command[] {defaultStartRoutCmd}); + + // TODO: may throw, is this okay? + StartupRoutingCommand startCmd = (StartupRoutingCommand) startCmds[0]; + + // Assert that host identity is consistent with existing values. + if (startCmd == null) { + String errMsg = + String.format("Host %s (IP %s)" + + "did not return a StartupRoutingCommand", + _name, _agentIp); + s_logger.error(errMsg); + // TODO: valid to return null, or should we throw? + return null; + } + if (!startCmd.getDataCenter().equals( + defaultStartRoutCmd.getDataCenter())) { + String errMsg = + String.format( + "Host %s (IP %s) changed zone/data center. Was " + + defaultStartRoutCmd.getDataCenter() + + " NOW its " + startCmd.getDataCenter(), + _name, _agentIp); + s_logger.error(errMsg); + // TODO: valid to return null, or should we throw? + return null; + } + if (!startCmd.getPod().equals(defaultStartRoutCmd.getPod())) { + String errMsg = + String.format("Host %s (IP %s) changed pod. Was " + + defaultStartRoutCmd.getPod() + " NOW its " + + startCmd.getPod(), _name, _agentIp); + s_logger.error(errMsg); + // TODO: valid to return null, or should we throw? + return null; + } + if (!startCmd.getCluster().equals(defaultStartRoutCmd.getCluster())) { + String errMsg = + String.format("Host %s (IP %s) changed cluster. Was " + + defaultStartRoutCmd.getCluster() + " NOW its " + + startCmd.getCluster(), _name, _agentIp); + s_logger.error(errMsg); + // TODO: valid to return null, or should we throw? + return null; + } + if (!startCmd.getGuid().equals(defaultStartRoutCmd.getGuid())) { + String errMsg = + String.format("Host %s (IP %s) changed guid. Was " + + defaultStartRoutCmd.getGuid() + " NOW its " + + startCmd.getGuid(), _name, _agentIp); + s_logger.error(errMsg); + // TODO: valid to return null, or should we throw? + return null; + } + if (!startCmd.getPrivateIpAddress().equals( + defaultStartRoutCmd.getPrivateIpAddress())) { + String errMsg = + String.format("Host %s (IP %s) IP address. Was " + + defaultStartRoutCmd.getPrivateIpAddress() + + " NOW its " + startCmd.getPrivateIpAddress(), + _name, _agentIp); + s_logger.error(errMsg); + // TODO: valid to return null, or should we throw? + return null; + } + if (!startCmd.getName().equals(defaultStartRoutCmd.getName())) { + String errMsg = + String.format( + "Host %s (IP %s) name. Was " + startCmd.getName() + + " NOW its " + + defaultStartRoutCmd.getName(), _name, + _agentIp); + s_logger.error(errMsg); + // TODO: valid to return null, or should we throw? + return null; + } + + // Host will also supply details of an existing StoragePool if it has + // been configured with one. + // + // NB: if the host was configured + // with a local storage pool, CloudStack may not be able to use it + // unless + // it is has service offerings configured to recognise this storage + // type. + StartupStorageCommand storePoolCmd = null; + if (startCmds.length > 1) { + storePoolCmd = (StartupStorageCommand) startCmds[1]; + // TODO: is this assertion required? + if (storePoolCmd == null) { + String frmtStr = + "Host %s (IP %s) sent incorrect Command, " + + "second parameter should be a " + + "StartupStorageCommand"; + String errMsg = String.format(frmtStr, _name, _agentIp); + s_logger.error(errMsg); + // TODO: valid to return null, or should we throw? + return null; + } + s_logger.info("Host " + _name + " (IP " + _agentIp + + ") already configured with a storeage pool, details " + + s_gson.toJson(startCmds[1])); + } else { + s_logger.info("Host " + _name + " (IP " + _agentIp + + ") already configured with a storeage pool, details "); + } + return new StartupCommand[] {startCmd, storePoolCmd}; + } + + @Override + public final PingCommand getCurrentStatus(final long id) { + PingCommand pingCmd = new PingRoutingCommand(getType(), id, null); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Ping host " + _name + " (IP " + _agentIp + ")"); + } + + Answer pingAns = this.executeRequest(pingCmd); + + if (pingAns == null || !pingAns.getResult()) { + s_logger.info("Cannot ping host " + _name + " (IP " + _agentIp + + "), pingAns (blank means null) is:" + pingAns); + return null; + } + return pingCmd; + } + + // TODO: Is it valid to return NULL, or should we throw on error? + // Returns StartupCommand with fields revised with values known only to the + // host + public final Command[] requestStartupCommand(final Command[] cmd) { + // Set HTTP POST destination URI + // Using java.net.URI, see + // http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URI.html + URI agentUri = null; + try { + String cmdName = StartupCommand.class.getName(); + agentUri = + new URI("http", null, _agentIp, _port, + "/api/HypervResource/" + cmdName, null, null); + } catch (URISyntaxException e) { + // TODO add proper logging + String errMsg = "Could not generate URI for Hyper-V agent"; + s_logger.error(errMsg, e); + return null; + } + String incomingCmd = postHttpRequest(s_gson.toJson(cmd), agentUri); + + if (incomingCmd == null) { + return null; + } + Command[] result = null; + try { + result = s_gson.fromJson(incomingCmd, Command[].class); + } catch (Exception ex) { + String errMsg = "Failed to deserialize Command[] " + incomingCmd; + s_logger.error(errMsg, ex); + } + s_logger.debug("requestStartupCommand received response " + + s_gson.toJson(result)); + if (result.length > 0) { + return result; + } + return null; + } + + // TODO: Is it valid to return NULL, or should we throw on error? + @Override + public final Answer executeRequest(final Command cmd) { + // Set HTTP POST destination URI + // Using java.net.URI, see + // http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URI.html + URI agentUri = null; + Class clazz = cmd.getClass(); + Answer answer = null; + try { + String cmdName = cmd.getClass().getName(); + agentUri = + new URI("http", null, _agentIp, _port, + "/api/HypervResource/" + cmdName, null, null); + } catch (URISyntaxException e) { + // TODO add proper logging + String errMsg = "Could not generate URI for Hyper-V agent"; + s_logger.error(errMsg, e); + return null; + } + + if (clazz == CheckSshCommand.class) { + answer = execute((CheckSshCommand) cmd); + } else if (clazz == GetDomRVersionCmd.class) { + answer = execute((GetDomRVersionCmd)cmd); + } else if (cmd instanceof NetworkUsageCommand) { + answer = execute((NetworkUsageCommand) cmd); + } else if (clazz == IpAssocCommand.class) { + answer = execute((IpAssocCommand) cmd); + } else if (clazz == DnsMasqConfigCommand.class) { + return execute((DnsMasqConfigCommand) cmd); + } else if (clazz == CreateIpAliasCommand.class) { + return execute((CreateIpAliasCommand) cmd); + } else if (clazz == DhcpEntryCommand.class) { + answer = execute((DhcpEntryCommand) cmd); + } else if (clazz == VmDataCommand.class) { + answer = execute((VmDataCommand) cmd); + } else if (clazz == SavePasswordCommand.class) { + answer = execute((SavePasswordCommand) cmd); + } else if (clazz == SetFirewallRulesCommand.class) { + answer = execute((SetFirewallRulesCommand)cmd); + } else if (clazz == LoadBalancerConfigCommand.class) { + answer = execute((LoadBalancerConfigCommand) cmd); + } else if (clazz == DeleteIpAliasCommand.class) { + return execute((DeleteIpAliasCommand) cmd); + } else if (clazz == PingTestCommand.class) { + answer = execute((PingTestCommand) cmd); + } else if (clazz == SetStaticNatRulesCommand.class) { + answer = execute((SetStaticNatRulesCommand) cmd); + } else if (clazz == CheckRouterCommand.class) { + answer = execute((CheckRouterCommand) cmd); + } else if (clazz == SetPortForwardingRulesCommand.class) { + answer = execute((SetPortForwardingRulesCommand) cmd); + } else if (clazz == SetSourceNatCommand.class) { + answer = execute((SetSourceNatCommand) cmd); + } else if (clazz == Site2SiteVpnCfgCommand.class) { + answer = execute((Site2SiteVpnCfgCommand) cmd); + } else if (clazz == CheckS2SVpnConnectionsCommand.class) { + answer = execute((CheckS2SVpnConnectionsCommand) cmd); + } else if (clazz == SetStaticRouteCommand.class) { + answer = execute((SetStaticRouteCommand) cmd); + } + else { + // Else send the cmd to hyperv agent. + String ansStr = postHttpRequest(s_gson.toJson(cmd), agentUri); + if (ansStr == null) { + return Answer.createUnsupportedCommandAnswer(cmd); + } + // Only Answer instances are returned by remote agents. + // E.g. see Response.getAnswers() + Answer[] result = s_gson.fromJson(ansStr, Answer[].class); + s_logger.debug("executeRequest received response " + + s_gson.toJson(result)); + if (result.length > 0) { + return result[0]; + } + } + return answer; + } + + private SetStaticRouteAnswer execute(SetStaticRouteCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource SetStaticRouteCommand: " + s_gson.toJson(cmd)); + } + + boolean endResult = true; + + String controlIp = getRouterSshControlIp(cmd); + String args = ""; + String[] results = new String[cmd.getStaticRoutes().length]; + int i = 0; + + // Extract and build the arguments for the command to be sent to the VR. + String[][] rules = cmd.generateSRouteRules(); + StringBuilder sb = new StringBuilder(); + String[] srRules = rules[0]; + for (int j = 0; j < srRules.length; j++) { + sb.append(srRules[j]).append(','); + } + args += " -a " + sb.toString(); + + // Send over the command for execution, via ssh, to the VR. + try { + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + "/opt/cloud/bin/vpc_staticroute.sh " + args); + + if (s_logger.isDebugEnabled()) + s_logger.debug("Executing script on domain router " + controlIp + ": /opt/cloud/bin/vpc_staticroute.sh " + args); + + if (!result.first()) { + s_logger.error("SetStaticRouteCommand failure on setting one rule. args: " + args); + results[i++] = "Failed"; + endResult = false; + } else { + results[i++] = null; + } + } catch (Throwable e) { + s_logger.error("SetStaticRouteCommand(args: " + args + ") failed on setting one rule due to " + e); + results[i++] = "Failed"; + endResult = false; + } + return new SetStaticRouteAnswer(cmd, endResult, results); + + } + + protected CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Executing resource CheckS2SVpnConnectionsCommand: " + s_gson.toJson(cmd)); + s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/checkbatchs2svpn.sh "); + } + + Pair result; + try { + String controlIp = getRouterSshControlIp(cmd); + String cmdline = "/opt/cloud/bin/checkbatchs2svpn.sh "; + for (String ip : cmd.getVpnIps()) { + cmdline += " " + ip; + } + + result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, cmdline); + + if (!result.first()) { + s_logger.error("check site-to-site vpn connections command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + + result.second()); + + return new CheckS2SVpnConnectionsAnswer(cmd, false, result.second()); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("check site-to-site vpn connections command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); + } + } catch (Throwable e) { + String msg = "CheckS2SVpnConnectionsCommand failed due to " + e; + s_logger.error(msg, e); + return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed"); + } + return new CheckS2SVpnConnectionsAnswer(cmd, true, result.second()); + } + + protected Answer execute(Site2SiteVpnCfgCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource Site2SiteVpnCfgCommand " + s_gson.toJson(cmd)); + } + + String routerIp = getRouterSshControlIp(cmd); + + String args = ""; + if (cmd.isCreate()) { + args += " -A"; + args += " -l "; + args += cmd.getLocalPublicIp(); + args += " -n "; + args += cmd.getLocalGuestCidr(); + args += " -g "; + args += cmd.getLocalPublicGateway(); + args += " -r "; + args += cmd.getPeerGatewayIp(); + args += " -N "; + args += cmd.getPeerGuestCidrList(); + args += " -e "; + args += "\"" + cmd.getEspPolicy() + "\""; + args += " -i "; + args += "\"" + cmd.getIkePolicy() + "\""; + args += " -t "; + args += Long.toString(cmd.getIkeLifetime()); + args += " -T "; + args += Long.toString(cmd.getEspLifetime()); + args += " -s "; + args += "\"" + cmd.getIpsecPsk() + "\""; + args += " -d "; + if (cmd.getDpd()) { + args += "1"; + } else { + args += "0"; + } + } else { + args += " -D"; + args += " -r "; + args += cmd.getPeerGatewayIp(); + args += " -n "; + args += cmd.getLocalGuestCidr(); + args += " -N "; + args += cmd.getPeerGuestCidrList(); + } + + Pair result; + try { + result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + "/opt/cloud/bin/ipsectunnel.sh " + args); + + if (!result.first()) { + s_logger.error("Setup site2site VPN " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); + + return new Answer(cmd, false, "Setup site2site VPN falied due to " + result.second()); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("setup site 2 site vpn on router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); + } + } catch (Throwable e) { + String msg = "Setup site2site VPN falied due to " + e.getMessage(); + s_logger.error(msg, e); + return new Answer(cmd, false, "Setup site2site VPN failed due to " + e.getMessage()); + } + return new Answer(cmd, true, result.second()); + } + + protected SetSourceNatAnswer execute(SetSourceNatCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource SetSourceNatCommand " + s_gson.toJson(cmd)); + } + + String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); + String routerIp = getRouterSshControlIp(cmd); + IpAddressTO pubIp = cmd.getIpAddress(); + try { + int ethDeviceNum = findRouterEthDeviceIndex(routerName, routerIp, pubIp.getVifMacAddress()); + String args = ""; + args += " -A "; + args += " -l "; + args += pubIp.getPublicIp(); + + args += " -c "; + args += "eth" + ethDeviceNum; + + Pair result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + "/opt/cloud/bin/vpc_snat.sh " + args); + + if (!result.first()) { + String msg = "SetupGuestNetworkCommand on domain router " + routerIp + " failed. message: " + result.second(); + s_logger.error(msg); + + return new SetSourceNatAnswer(cmd, false, msg); + } + + return new SetSourceNatAnswer(cmd, true, "success"); + } catch (Exception e) { + String msg = "Ip SNAT failure due to " + e.toString(); + s_logger.error(msg, e); + return new SetSourceNatAnswer(cmd, false, msg); + } + } + + // + // find mac address of a specified ethx device + // ip address show ethx | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2 + // returns + // eth0:xx.xx.xx.xx + + // + // list IP with eth devices + // ifconfig ethx |grep -B1 "inet addr" | awk '{ if ( $1 == "inet" ) { print $2 } else if ( $2 == "Link" ) { printf "%s:" ,$1 } }' + // | awk -F: '{ print $1 ": " $3 }' + // + // returns + // eth0:xx.xx.xx.xx + // + // + + private int findRouterEthDeviceIndex(String domrName, String routerIp, String mac) throws Exception { + + s_logger.info("findRouterEthDeviceIndex. mac: " + mac); + + // TODO : this is a temporary very inefficient solution, will refactor it later + Pair result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + "ls /proc/sys/net/ipv4/conf"); + + // when we dynamically plug in a new NIC into virtual router, it may take time to show up in guest OS + // we use a waiting loop here as a workaround to synchronize activities in systems + long startTick = System.currentTimeMillis(); + while (System.currentTimeMillis() - startTick < 15000) { + if (result.first()) { + String[] tokens = result.second().split("\\s+"); + for (String token : tokens) { + if (!("all".equalsIgnoreCase(token) || "default".equalsIgnoreCase(token) || "lo".equalsIgnoreCase(token))) { + String cmd = String.format("ip address show %s | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2", token); + + if (s_logger.isDebugEnabled()) + s_logger.debug("Run domr script " + cmd); + Pair result2 = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + // TODO need to find the dev index inside router based on IP address + cmd); + if (s_logger.isDebugEnabled()) + s_logger.debug("result: " + result2.first() + ", output: " + result2.second()); + + if (result2.first() && result2.second().trim().equalsIgnoreCase(mac.trim())) + return Integer.parseInt(token.substring(3)); + } + } + } + + s_logger.warn("can not find intereface associated with mac: " + mac + ", guest OS may still at loading state, retry..."); + + try { + Thread.currentThread().sleep(1000); + } catch (InterruptedException e) { + } + } + + return -1; + } + + protected Answer execute(SetPortForwardingRulesCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource SetPortForwardingRulesCommand: " + s_gson.toJson(cmd)); + } + + String controlIp = getRouterSshControlIp(cmd); + String args = ""; + String[] results = new String[cmd.getRules().length]; + int i = 0; + + boolean endResult = true; + for (PortForwardingRuleTO rule : cmd.getRules()) { + args += rule.revoked() ? " -D " : " -A "; + args += " -P " + rule.getProtocol().toLowerCase(); + args += " -l " + rule.getSrcIp(); + args += " -p " + rule.getStringSrcPortRange(); + args += " -r " + rule.getDstIp(); + args += " -d " + rule.getStringDstPortRange(); + + try { + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/firewall.sh " + args); + + if (s_logger.isDebugEnabled()) + s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall.sh " + args); + + if (!result.first()) { + s_logger.error("SetPortForwardingRulesCommand failure on setting one rule. args: " + args); + results[i++] = "Failed"; + endResult = false; + } else { + results[i++] = null; + } + } catch (Throwable e) { + s_logger.error("SetPortForwardingRulesCommand(args: " + args + ") failed on setting one rule due to " + e.getMessage()); + results[i++] = "Failed"; + endResult = false; + } + } + + return new SetPortForwardingRulesAnswer(cmd, results, endResult); + } + + protected Answer execute(CheckRouterCommand cmd) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Executing resource CheckRouterCommand: " + s_gson.toJson(cmd)); + s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/checkrouter.sh "); + } + + Pair result; + try { + + String controlIp = getRouterSshControlIp(cmd); + result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + "/opt/cloud/bin/checkrouter.sh "); + + if (!result.first()) { + s_logger.error("check router command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); + + return new CheckRouterAnswer(cmd, "CheckRouter failed due to " + result.second()); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("check router command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); + } + } catch (Throwable e) { + String msg = "CheckRouterCommand failed due to " + e.getMessage(); + s_logger.error(msg, e); + return new CheckRouterAnswer(cmd, msg); + } + return new CheckRouterAnswer(cmd, result.second(), true); + } + + protected Answer execute(SetStaticNatRulesCommand cmd) { + + if (cmd.getVpcId() != null) { + //return SetVPCStaticNatRules(cmd); + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource SetFirewallRuleCommand: " + s_gson.toJson(cmd)); + } + + String args = null; + String[] results = new String[cmd.getRules().length]; + int i = 0; + boolean endResult = true; + for (StaticNatRuleTO rule : cmd.getRules()) { + // 1:1 NAT needs instanceip;publicip;domrip;op + args = rule.revoked() ? " -D " : " -A "; + + args += " -l " + rule.getSrcIp(); + args += " -r " + rule.getDstIp(); + + if (rule.getProtocol() != null) { + args += " -P " + rule.getProtocol().toLowerCase(); + } + + args += " -d " + rule.getStringSrcPortRange(); + args += " -G "; + + try { + String controlIp = getRouterSshControlIp(cmd); + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/firewall.sh " + args); + + if (s_logger.isDebugEnabled()) + s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall.sh " + args); + + if (!result.first()) { + s_logger.error("SetStaticNatRulesCommand failure on setting one rule. args: " + args); + results[i++] = "Failed"; + endResult = false; + } else { + results[i++] = null; + } + } catch (Throwable e) { + s_logger.error("SetStaticNatRulesCommand (args: " + args + ") failed on setting one rule due to " + e.getMessage()); + results[i++] = "Failed"; + endResult = false; + } + } + return new SetStaticNatRulesAnswer(cmd, results, endResult); + } + + protected Answer execute(PingTestCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource PingTestCommand: " + s_gson.toJson(cmd)); + } + String controlIp = cmd.getRouterIp(); + String args = " -c 1 -n -q " + cmd.getPrivateIp(); + try { + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/bin/ping" + args); + if (result.first()) + return new Answer(cmd); + } catch (Exception e) { + s_logger.error("Unable to execute ping command on DomR (" + controlIp + "), domR may not be ready yet. failure due to " + + e.getMessage()); + } + return new Answer(cmd, false, "PingTestCommand failed"); + } + + protected Answer execute(final DeleteIpAliasCommand cmd) { + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + List revokedIpAliasTOs = cmd.getDeleteIpAliasTos(); + List activeIpAliasTOs = cmd.getCreateIpAliasTos(); + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing deleteIpAlias command: " + s_gson.toJson(cmd)); + } + String args = ""; + for (IpAliasTO ipAliasTO : revokedIpAliasTOs) { + args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-"; + } + args = args + "- "; + for (IpAliasTO ipAliasTO : activeIpAliasTOs) { + args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-"; + } + if (s_logger.isDebugEnabled()) { + s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/deleteIpAlias " + args); + } + + try { + String controlIp = getRouterSshControlIp(cmd); + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + "/root/deleteIpAlias.sh " + args); + + if (!result.first()) { + s_logger.error("deleteIpAlias command on domr " + controlIp + " failed, message: " + result.second()); + + return new Answer(cmd, false, "deleteIpAlias failed due to " + result.second()); + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("deleteIpAlias command on domain router " + controlIp + " completed"); + } + + } catch (Throwable e) { + String msg = "deleteIpAlias failed due to " + e.getMessage(); + s_logger.error(msg, e); + return new Answer(cmd, false, msg); + } + + return new Answer(cmd); + } + + protected Answer execute(final LoadBalancerConfigCommand cmd) { + + if (cmd.getVpcId() != null) { + //return VPCLoadBalancerConfig(cmd); + } + + File keyFile = getSystemVMKeyFile(); + + String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + String controlIp = getRouterSshControlIp(cmd); + + assert (controlIp != null); + + LoadBalancerConfigurator cfgtr = new HAProxyConfigurator(); + String[] config = cfgtr.generateConfiguration(cmd); + + String[][] rules = cfgtr.generateFwRules(cmd); + String tmpCfgFilePath = "/tmp/" + routerIp.replace('.', '_') + ".cfg"; + String tmpCfgFileContents = ""; + for (int i = 0; i < config.length; i++) { + tmpCfgFileContents += config[i]; + tmpCfgFileContents += "\n"; + } + + try { + SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", keyFile, null, "/tmp/", tmpCfgFileContents.getBytes(), routerIp.replace('.', '_') + ".cfg", null); + + try { + String[] addRules = rules[LoadBalancerConfigurator.ADD]; + String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; + String[] statRules = rules[LoadBalancerConfigurator.STATS]; + + String args = ""; + args += "-i " + routerIp; + args += " -f " + tmpCfgFilePath; + + StringBuilder sb = new StringBuilder(); + if (addRules.length > 0) { + for (int i = 0; i < addRules.length; i++) { + sb.append(addRules[i]).append(','); + } + + args += " -a " + sb.toString(); + } + + sb = new StringBuilder(); + if (removeRules.length > 0) { + for (int i = 0; i < removeRules.length; i++) { + sb.append(removeRules[i]).append(','); + } + + args += " -d " + sb.toString(); + } + + sb = new StringBuilder(); + if (statRules.length > 0) { + for (int i = 0; i < statRules.length; i++) { + sb.append(statRules[i]).append(','); + } + + args += " -s " + sb.toString(); + } + + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "scp " + tmpCfgFilePath + + " /etc/haproxy/haproxy.cfg.new"); + + if (!result.first()) { + s_logger.error("Unable to copy haproxy configuration file"); + return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to uanble to copy haproxy configuration file"); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Run command on domain router " + routerIp + ", /root/loadbalancer.sh " + args); + } + + result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/loadbalancer.sh " + args); + + if (!result.first()) { + String msg = "LoadBalancerConfigCommand on domain router " + routerIp + " failed. message: " + result.second(); + s_logger.error(msg); + + return new Answer(cmd, false, msg); + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("LoadBalancerConfigCommand on domain router " + routerIp + " completed"); + } + } finally { + SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "rm " + tmpCfgFilePath); + } + + return new Answer(cmd); + } catch (Throwable e) { + s_logger.error("Unexpected exception: " + e.toString(), e); + return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to " + e.getMessage()); + } + } + + protected Answer execute(SavePasswordCommand cmd) { + if (s_logger.isInfoEnabled()) { + + s_logger.info("Executing resource SavePasswordCommand. vmName: " + cmd.getVmName() + ", vmIp: " + cmd.getVmIpAddress() + ", password: " + + StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); + } + + String controlIp = getRouterSshControlIp(cmd); + final String password = cmd.getPassword(); + final String vmIpAddress = cmd.getVmIpAddress(); + + // Run save_password_to_domr.sh + 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())); + } + + args += " -p " + password; + + try { + + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/savepassword.sh " + args); + + if (!result.first()) { + s_logger.error("savepassword command on domain router " + controlIp + " failed, message: " + result.second()); + + return new Answer(cmd, false, "SavePassword failed due to " + result.second()); + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("savepassword command on domain router " + controlIp + " completed"); + } + + } catch (Throwable e) { + String msg = "SavePasswordCommand failed due to " + e; + s_logger.error(msg, e); + return new Answer(cmd, false, msg); + } + return new Answer(cmd); + } + + protected SetFirewallRulesAnswer execute(SetFirewallRulesCommand cmd) { + String controlIp = getRouterSshControlIp(cmd); + String[] results = new String[cmd.getRules().length]; + FirewallRuleTO[] allrules = cmd.getRules(); + FirewallRule.TrafficType trafficType = allrules[0].getTrafficType(); + String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT); + + String[][] rules = cmd.generateFwRules(); + String args = ""; + args += " -F "; + if (trafficType == FirewallRule.TrafficType.Egress){ + args+= " -E "; + if (egressDefault.equals("true")) { + args+= " -P 1 "; + } else if (egressDefault.equals("System")) { + args+= " -P 2 "; + } else { + args+= " -P 0 "; + } + } + + StringBuilder sb = new StringBuilder(); + String[] fwRules = rules[0]; + if (fwRules.length > 0) { + for (int i = 0; i < fwRules.length; i++) { + sb.append(fwRules[i]).append(','); + } + args += " -a " + sb.toString(); + } + + try { + Pair result = null; + + if (trafficType == FirewallRule.TrafficType.Egress){ + result = SshHelper.sshExecute(controlIp, + DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), + null, "/root/firewallRule_egress.sh " + args); + } else { + result = SshHelper.sshExecute(controlIp, + DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), + null, "/root/firewall_rule.sh " + args); + } + + if (s_logger.isDebugEnabled()) { + if (trafficType == FirewallRule.TrafficType.Egress){ + s_logger.debug("Executing script on domain router " + controlIp + + ": /root/firewallRule_egress.sh " + args); + } else { + s_logger.debug("Executing script on domain router " + controlIp + + ": /root/firewall_rule.sh " + args); + } + } + + + if (!result.first()) { + s_logger.error("SetFirewallRulesCommand failure on setting one rule. args: " + + args); + //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails + for (int i=0; i < results.length; i++) { + results[i] = "Failed"; + } + + return new SetFirewallRulesAnswer(cmd, false, results); + } + } catch (Throwable e) { + s_logger.error("SetFirewallRulesCommand(args: " + args + + ") failed on setting one rule due to " + ,e); + //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails + for (int i=0; i < results.length; i++) { + results[i] = "Failed"; + } + return new SetFirewallRulesAnswer(cmd, false, results); + } + + return new SetFirewallRulesAnswer(cmd, true, results); + } + + + protected Answer execute(VmDataCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource VmDataCommand: " + s_gson.toJson(cmd)); + } + + String routerPrivateIpAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + String controlIp = getRouterSshControlIp(cmd); + + String vmIpAddress = cmd.getVmIpAddress(); + List vmData = cmd.getVmData(); + String[] vmDataArgs = new String[vmData.size() * 2 + 4]; + vmDataArgs[0] = "routerIP"; + vmDataArgs[1] = routerPrivateIpAddress; + vmDataArgs[2] = "vmIP"; + vmDataArgs[3] = vmIpAddress; + int i = 4; + for (String[] vmDataEntry : vmData) { + String folder = vmDataEntry[0]; + String file = vmDataEntry[1]; + String contents = (vmDataEntry[2] != null) ? vmDataEntry[2] : "none"; + + vmDataArgs[i] = folder + "," + file; + vmDataArgs[i + 1] = contents; + i += 2; + } + + String content = encodeDataArgs(vmDataArgs); + String tmpFileName = UUID.randomUUID().toString(); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Run vm_data command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", data: " + content); + } + + try { + SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/tmp", content.getBytes(), tmpFileName, null); + + try { + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + "/root/userdata.py " + tmpFileName); + + if (!result.first()) { + s_logger.error("vm_data command on domain router " + controlIp + " failed. messge: " + result.second()); + return new Answer(cmd, false, "VmDataCommand failed due to " + result.second()); + } + } finally { + + SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "rm /tmp/" + tmpFileName); + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("vm_data command on domain router " + controlIp + " completed"); + } + + } catch (Throwable e) { + String msg = "VmDataCommand failed due to " + e; + s_logger.error(msg, e); + return new Answer(cmd, false, msg); + } + return new Answer(cmd); + } + + private String encodeDataArgs(String[] dataArgs) { + StringBuilder sb = new StringBuilder(); + + for (String arg : dataArgs) { + sb.append(arg); + sb.append("\n"); + } + + return sb.toString(); + } + + + protected Answer execute(DhcpEntryCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource DhcpEntryCommand: " + s_gson.toJson(cmd)); + } + + // ssh -p 3922 -o StrictHostKeyChecking=no -i $cert root@$domr "/root/edithosts.sh $mac $ip $vm $dfltrt $ns $staticrt" >/dev/null + + String args = " -m " + cmd.getVmMac(); + if (cmd.getVmIpAddress() != null) { + args += " -4 " + cmd.getVmIpAddress(); + } + args += " -h " + cmd.getVmName(); + + if (cmd.getDefaultRouter() != null) { + args += " -d " + cmd.getDefaultRouter(); + } + + if (cmd.getDefaultDns() != null) { + args += " -n " + cmd.getDefaultDns(); + } + + if (cmd.getStaticRoutes() != null) { + args += " -s " + cmd.getStaticRoutes(); + } + + if (cmd.getVmIp6Address() != null) { + args += " -6 " + cmd.getVmIp6Address(); + args += " -u " + cmd.getDuid(); + } + + if (!cmd.isDefault()) { + args += " -N"; + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/edithosts.sh " + args); + } + + try { + String controlIp = getRouterSshControlIp(cmd); + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + "/root/edithosts.sh " + args); + + if (!result.first()) { + s_logger.error("dhcp_entry command on domR " + controlIp + " failed, message: " + result.second()); + + return new Answer(cmd, false, "DhcpEntry failed due to " + result.second()); + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("dhcp_entry command on domain router " + controlIp + " completed"); + } + + } catch (Throwable e) { + String msg = "DhcpEntryCommand failed due to " + e; + s_logger.error(msg, e); + return new Answer(cmd, false, msg); + } + + return new Answer(cmd); + } + + protected Answer execute(final CreateIpAliasCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing createIpAlias command: " + s_gson.toJson(cmd)); + } + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + List ipAliasTOs = cmd.getIpAliasList(); + String args=""; + for (IpAliasTO ipaliasto : ipAliasTOs) { + args = args + ipaliasto.getAlias_count()+":"+ipaliasto.getRouterip()+":"+ipaliasto.getNetmask()+"-"; + } + if (s_logger.isDebugEnabled()) { + s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/createIpAlias " + args); + } + + try { + String controlIp = getRouterSshControlIp(cmd); + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + "/root/createIpAlias.sh " + args); + + if (!result.first()) { + s_logger.error("CreateIpAlias command on domr " + controlIp + " failed, message: " + result.second()); + + return new Answer(cmd, false, "createipAlias failed due to " + result.second()); + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("createIpAlias command on domain router " + controlIp + " completed"); + } + + } catch (Throwable e) { + String msg = "createIpAlias failed due to " + e; + s_logger.error(msg, e); + return new Answer(cmd, false, msg); + } + + return new Answer(cmd); + } + + protected Answer execute(final DnsMasqConfigCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing dnsmasqConfig command: " + s_gson.toJson(cmd)); + } + String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + String controlIp = getRouterSshControlIp(cmd); + + assert(controlIp != null); + + List dhcpTos = cmd.getIps(); + String args =""; + for(DhcpTO dhcpTo : dhcpTos) { + args = args + dhcpTo.getRouterIp()+":"+dhcpTo.getGateway()+":"+dhcpTo.getNetmask()+":"+dhcpTo.getStartIpOfSubnet()+"-"; + } + + try { + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/dnsmasq.sh " + args); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Run command on domain router " + routerIp + ", /root/dnsmasq.sh"); + } + + if (!result.first()) { + s_logger.error("Unable update dnsmasq config file"); + return new Answer(cmd, false, "dnsmasq config update failed due to: " + result.second()); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("dnsmasq config command on domain router " + routerIp + " completed"); + } + }catch (Throwable e) { + String msg = "Dnsmasqconfig command failed due to " + e.getMessage(); + s_logger.error(msg, e); + return new Answer(cmd, false, msg); + } + + return new Answer(cmd); + } + + protected Answer execute(IpAssocCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource IPAssocCommand: " + s_gson.toJson(cmd)); + } + + int i = 0; + String[] results = new String[cmd.getIpAddresses().length]; + + try { + + IpAddressTO[] ips = cmd.getIpAddresses(); + String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); + String controlIp = getRouterSshControlIp(cmd); + for (IpAddressTO ip : ips) { + assignPublicIpAddress(routerName, controlIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getBroadcastUri(), ip.getVlanGateway(), ip.getVlanNetmask(),ip.getVifMacAddress()); + results[i++] = ip.getPublicIp() + " - success"; + } + + for (; i < cmd.getIpAddresses().length; i++) { + results[i++] = IpAssocAnswer.errorResult; + } + } catch (Throwable e) { + s_logger.error("Unexpected exception: " + e.toString() + " will shortcut rest of IPAssoc commands", e); + + for (; i < cmd.getIpAddresses().length; i++) { + results[i++] = IpAssocAnswer.errorResult; + } + } + + return new IpAssocAnswer(cmd, results); + } + + protected void assignPublicIpAddress(final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, final boolean firstIP, + final boolean sourceNat, final String vlanId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress) throws Exception { + + boolean addVif = false; + boolean removeVif = false; + if (add) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Plug new NIC to associate" + privateIpAddress + " to " + publicIpAddress); + } + addVif = true; + } else if (!add && firstIP) { + removeVif = true; + } + + String args = null; + + if (add) { + args = " -A "; + } else { + args = " -D "; + } + + if (sourceNat) { + args += " -s "; + } + if (firstIP) { + args += " -f "; + } + String cidrSize = Long.toString(NetUtils.getCidrSize(vlanNetmask)); + args += " -l "; + args += publicIpAddress + "/" + cidrSize; + + args += " -c "; + args += "eth" +"2"; // currently hardcoding to eth 2 (which is default public ipd)//publicNicInfo.first(); + + args += " -g "; + args += vlanGateway; + + if (addVif) { + args += " -n "; + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Run command on domain router " + privateIpAddress + ", /opt/cloud/bin/ipassoc.sh " + args); + } + + Pair result = SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/ipassoc.sh " + args); + + if (!result.first()) { + s_logger.error("ipassoc command on domain router " + privateIpAddress + " failed. message: " + result.second()); + throw new Exception("ipassoc failed due to " + result.second()); + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("ipassoc command on domain router " + privateIpAddress + " completed"); + } + } + + protected Answer execute(GetDomRVersionCmd cmd) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Executing resource GetDomRVersionCmd: " + s_gson.toJson(cmd)); + s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/get_template_version.sh "); + } + + Pair result; + try { + String controlIp = getRouterSshControlIp(cmd); + result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + "/opt/cloud/bin/get_template_version.sh "); + + if (!result.first()) { + s_logger.error("GetDomRVersionCmd on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); + + return new GetDomRVersionAnswer(cmd, "GetDomRVersionCmd failed due to " + result.second()); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("GetDomRVersionCmd on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); + } + } catch (Throwable e) { + String msg = "GetDomRVersionCmd failed due to " + e; + s_logger.error(msg, e); + return new GetDomRVersionAnswer(cmd, msg); + } + String[] lines = result.second().split("&"); + if (lines.length != 2) { + return new GetDomRVersionAnswer(cmd, result.second()); + } + return new GetDomRVersionAnswer(cmd, result.second(), lines[0], lines[1]); + } + + + private static String getRouterSshControlIp(NetworkElementCommand cmd) { + String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + String routerGuestIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP); + String zoneNetworkType = cmd.getAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE); + + if(routerGuestIp != null && zoneNetworkType != null && NetworkType.valueOf(zoneNetworkType) == NetworkType.Basic) { + if(s_logger.isDebugEnabled()) + s_logger.debug("In Basic zone mode, use router's guest IP for SSH control. guest IP : " + routerGuestIp); + + return routerGuestIp; + } + + if(s_logger.isDebugEnabled()) + s_logger.debug("Use router's private IP for SSH control. IP : " + routerIp); + return routerIp; + } + + protected Answer execute(NetworkUsageCommand cmd) { + if ( cmd.isForVpc() ) { + //return VPCNetworkUsage(cmd); + } + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource NetworkUsageCommand "+ s_gson.toJson(cmd)); + } + if(cmd.getOption()!=null && cmd.getOption().equals("create") ){ + String result = networkUsage(cmd.getPrivateIP(), "create", null); + NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "true", 0L, 0L); + return answer; + } + long[] stats = getNetworkStats(cmd.getPrivateIP()); + + NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], stats[1]); + return answer; + } + private long[] getNetworkStats(String privateIP) { + String result = networkUsage(privateIP, "get", null); + long[] stats = new long[2]; + if (result != null) { + try { + String[] splitResult = result.split(":"); + int i = 0; + while (i < splitResult.length - 1) { + stats[0] += (new Long(splitResult[i++])).longValue(); + stats[1] += (new Long(splitResult[i++])).longValue(); + } + } catch (Throwable e) { + s_logger.warn("Unable to parse return from script return of network usage command: " + e.toString(), e); + } + } + return stats; + } + + + protected CheckSshAnswer execute(CheckSshCommand cmd) { + String vmName = cmd.getName(); + String privateIp = cmd.getIp(); + int cmdPort = cmd.getPort(); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort); + } + + try { + String result = connect(cmd.getName(), privateIp, cmdPort); + if (result != null) { + s_logger.error("Can not ping System vm " + vmName + "due to:" + result); + return new CheckSshAnswer(cmd, "Can not ping System vm " + vmName + "due to:" + result); + } + } catch (Exception e) { + s_logger.error("Can not ping System vm " + vmName + "due to exception"); + return new CheckSshAnswer(cmd, e); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Ping command port succeeded for vm " + vmName); + } + + if (VirtualMachineName.isValidRouterName(vmName)) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Execute network usage setup command on " + vmName); + } + networkUsage(privateIp, "create", null); + } + + return new CheckSshAnswer(cmd); + } + + + protected String networkUsage(final String privateIpAddress, final String option, final String ethName) { + String args = null; + if (option.equals("get")) { + args = "-g"; + } else if (option.equals("create")) { + args = "-c"; + } else if (option.equals("reset")) { + args = "-r"; + } else if (option.equals("addVif")) { + args = "-a"; + args += ethName; + } else if (option.equals("deleteVif")) { + args = "-d"; + args += ethName; + } + + try { + if (s_logger.isTraceEnabled()) { + s_logger.trace("Executing /opt/cloud/bin/netusage.sh " + args + " on DomR " + privateIpAddress); + } + + Pair result = SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/netusage.sh " + args); + + if (!result.first()) { + return null; + } + + return result.second(); + } catch (Throwable e) { + s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIpAddress + "), domR may not be ready yet. failure due to " + + e); + } + + return null; + } + + public File getSystemVMKeyFile() { + URL url = this.getClass().getClassLoader().getResource("scripts/vm/systemvm/id_rsa.cloud"); + File keyFile = null; + if ( url != null ){ + keyFile = new File(url.getPath()); + } + if (keyFile == null || !keyFile.exists()) { + keyFile = new File("/usr/share/cloudstack-common/scripts/vm/systemvm/id_rsa.cloud"); + } + assert(keyFile != null); + if(!keyFile.exists()) { + s_logger.error("Unable to locate id_rsa.cloud in your setup at " + keyFile.toString()); + } + return keyFile; + } + + + public static String postHttpRequest(final String jsonCmd, + final URI agentUri) { + // Using Apache's HttpClient for HTTP POST + // Java-only approach discussed at on StackOverflow concludes with + // comment to use Apache HttpClient + // http://stackoverflow.com/a/2793153/939250, but final comment is to + // use Apache. + s_logger.debug("POST request to" + agentUri.toString() + + " with contents" + jsonCmd); + + // Create request + HttpClient httpClient = new DefaultHttpClient(); + String result = null; + + // TODO: are there timeout settings and worker thread settings to tweak? + try { + HttpPost request = new HttpPost(agentUri); + + // JSON encode command + // Assumes command sits comfortably in a string, i.e. not used for + // large data transfers + StringEntity cmdJson = new StringEntity(jsonCmd); + request.addHeader("content-type", "application/json"); + request.setEntity(cmdJson); + s_logger.debug("Sending cmd to " + agentUri.toString() + + " cmd data:" + jsonCmd); + HttpResponse response = httpClient.execute(request); + + // Unsupported commands will not route. + if (response.getStatusLine().getStatusCode() + == HttpStatus.SC_NOT_FOUND) { + String errMsg = + "Failed to send : HTTP error code : " + + response.getStatusLine().getStatusCode(); + s_logger.error(errMsg); + String unsupportMsg = + "Unsupported command " + + agentUri.getPath() + + ". Are you sure you got the right type of" + + " server?"; + Answer ans = new UnsupportedAnswer(null, unsupportMsg); + s_logger.error(ans); + result = s_gson.toJson(new Answer[] {ans}); + } else if (response.getStatusLine().getStatusCode() + != HttpStatus.SC_OK) { + String errMsg = + "Failed send to " + agentUri.toString() + + " : HTTP error code : " + + response.getStatusLine().getStatusCode(); + s_logger.error(errMsg); + return null; + } else { + result = EntityUtils.toString(response.getEntity()); + s_logger.debug("POST response is" + result); + } + } catch (ClientProtocolException protocolEx) { + // Problem with HTTP message exchange + s_logger.error(protocolEx); + } catch (IOException connEx) { + // Problem with underlying communications + s_logger.error(connEx); + } finally { + httpClient.getConnectionManager().shutdown(); + } + return result; + } + + @Override + protected final String getDefaultScriptsDir() { + // TODO Auto-generated method stub + return null; + } + + // NB: 'params' can come from one of two places. + // For a new host, HypervServerDiscoverer.find(). + // For an existing host, DiscovererBase.reloadResource(). + // In the later case, the params Map is populated with predefined keys + // and custom keys from the database that were passed out by the find() + // call. + // the custom keys go by the variable name 'details'. + // Thus, in find(), you see that 'details' are added to the params Map. + @Override + public final boolean configure(final String name, + final Map params) throws ConfigurationException { + /* todo: update, make consistent with the xen server equivalent. */ + _guid = (String) params.get("guid"); + _zoneId = (String) params.get("zone"); + _podId = (String) params.get("pod"); + _clusterId = (String) params.get("cluster"); + _agentIp = (String) params.get("ipaddress"); // was agentIp + _name = name; + + _clusterGuid = (String) params.get("cluster.guid"); + _username = (String) params.get("url"); + _password = (String) params.get("password"); + _username = (String) params.get("username"); + + _configureCalled = true; + return true; + } + + @Override + public void setName(final String name) { + // TODO Auto-generated method stub + } + + @Override + public void setConfigParams(final Map params) { + // TODO Auto-generated method stub + } + + @Override + public final Map getConfigParams() { + // TODO Auto-generated method stub + return null; + } + + @Override + public final int getRunLevel() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public void setRunLevel(final int level) { + // TODO Auto-generated method stub + } + + protected String connect(final String vmName, final String ipAddress, final int port) { + long startTick = System.currentTimeMillis(); + + // wait until we have at least been waiting for _ops_timeout time or + // at least have tried _retry times, this is to coordinate with system + // VM patching/rebooting time that may need + int retry = _retry; + while (System.currentTimeMillis() - startTick <= _ops_timeout || --retry > 0) { + SocketChannel sch = null; + try { + s_logger.info("Trying to connect to " + ipAddress); + sch = SocketChannel.open(); + sch.configureBlocking(true); + sch.socket().setSoTimeout(5000); + // we need to connect to the public ip address to check the status of the VM +/* + InetSocketAddress addr = new InetSocketAddress(ipAddress, port); + sch.connect(addr);*/ + return null; + } catch (IOException e) { + s_logger.info("Could not connect to " + ipAddress + " due to " + e.toString()); + if (e instanceof ConnectException) { + // if connection is refused because of VM is being started, + // we give it more sleep time + // to avoid running out of retry quota too quickly + try { + Thread.sleep(5000); + } catch (InterruptedException ex) { + } + } + } finally { + if (sch != null) { + try { + sch.close(); + } catch (IOException e) { + } + } + } + + try { + Thread.sleep(1000); + } catch (InterruptedException ex) { + } + } + + s_logger.info("Unable to logon to " + ipAddress); + + return "Unable to connect"; + } + +} diff --git a/plugins/hypervisors/hyperv/test/com/cloud/hypervisor/hyperv/test/HypervDirectConnectResourceTest.java b/plugins/hypervisors/hyperv/test/com/cloud/hypervisor/hyperv/test/HypervDirectConnectResourceTest.java new file mode 100644 index 00000000000..1f90da9aded --- /dev/null +++ b/plugins/hypervisors/hyperv/test/com/cloud/hypervisor/hyperv/test/HypervDirectConnectResourceTest.java @@ -0,0 +1,938 @@ +// 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.hypervisor.hyperv.test; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.google.common.io.Files; +import com.google.gson.Gson; + +import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.Command; +import com.cloud.agent.api.CreateStoragePoolCommand; +import com.cloud.agent.api.DeleteStoragePoolCommand; +import com.cloud.agent.api.GetHostStatsAnswer; +import com.cloud.agent.api.GetHostStatsCommand; +import com.cloud.agent.api.GetStorageStatsAnswer; +import com.cloud.agent.api.GetStorageStatsCommand; +import com.cloud.agent.api.GetVmStatsAnswer; +import com.cloud.agent.api.GetVmStatsCommand; +import com.cloud.agent.api.ModifyStoragePoolCommand; +import com.cloud.agent.api.StartAnswer; +import com.cloud.agent.api.StartCommand; +import com.cloud.agent.api.StartupCommand; +import com.cloud.agent.api.StartupRoutingCommand; +import com.cloud.agent.api.StartupRoutingCommand.VmState; +import com.cloud.agent.api.StartupStorageCommand; +import com.cloud.agent.api.StopAnswer; +import com.cloud.agent.api.StopCommand; +import com.cloud.agent.api.storage.CreateAnswer; +import com.cloud.agent.api.storage.CreateCommand; +import com.cloud.agent.api.storage.DestroyCommand; +import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer; +import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.hypervisor.hyperv.resource.HypervDirectConnectResource; +import com.cloud.network.Networks.RouterPrivateIpStrategy; +import com.cloud.serializer.GsonHelper; +import com.cloud.storage.Storage; +import com.cloud.storage.Storage.StoragePoolType; +import com.cloud.utils.PropertiesUtil; +import com.cloud.utils.exception.CloudRuntimeException; + +/** + * Functional test suit for Hyper-V plugin. + * + * mvn clean build -DskipTests=false + **/ +public class HypervDirectConnectResourceTest { + + private static final Logger s_logger = Logger + .getLogger(HypervDirectConnectResourceTest.class.getName()); + + // TODO: make this a config parameter + private static final String sampleLegitDiskImageURL = "http://s3-eu-west-1.amazonaws.com/cshv3eu/SmallDisk.vhdx"; + private static final Gson s_gson = GsonHelper.getGson(); + private static final HypervDirectConnectResource s_hypervresource = + new HypervDirectConnectResource(); + + private static String s_testLocalStoreUUID = + "5fe2bad3-d785-394e-9949-89786b8a63d2"; + private static String s_testLocalStorePath = "." + File.separator + + "var" + File.separator + "test" + File.separator + "storagepool"; + private static String s_testSecondaryStoreLocalPath = "." + + File.separator + + "var" + File.separator + "test" + File.separator + "secondary"; + + // TODO: differentiate between NFS and HTTP template URLs. + private static String s_testSampleTemplateUUID = + "TestCopiedLocalTemplate.vhdx"; + private static String s_testSampleTemplateURL = s_testSampleTemplateUUID; + + // test volumes are both a minimal size vhdx. Changing the extension to .vhd + // makes on corrupt. + private static String s_testSampleVolumeWorkingUUID = + "TestVolumeLegit.vhdx"; + private static String s_testSampleVolumeWorkingUUIDNoExt = + "TestVolumeLegit"; + private static String s_testSampleVolumeCorruptUUID = + "TestVolumeCorrupt.vhd"; + private static String s_testSampleVolumeTempUUID = + "TestVolumeTemp.vhdx"; + private static String s_testSampleVolumeWorkingURIJSON; + private static String s_testSampleVolumeCorruptURIJSON; + private static String s_testSampleVolumeTempURIJSON; + + private static String s_testSampleTemplateURLJSON; + private static String s_testLocalStorePathJSON; + private static String s_agentExecutable; + private static Process s_agentProc; + private static String s_testPrimaryDataStoreHost; + + public HypervDirectConnectResourceTest() { + } + + /** + * Prep test environment. + **/ + @Before + public final void setUp() throws ConfigurationException { + // Obtain script locations from agent.properties + final Map params = + PropertiesUtil.toMap(loadProperties()); + // Used to create existing StoragePool in preparation for the + // ModifyStoragePool + params.put("local.storage.uuid", s_testLocalStoreUUID); + + // Make sure secondary store is available. + File testSecondarStoreDir = new File(s_testSecondaryStoreLocalPath); + if (!testSecondarStoreDir.exists()) { + testSecondarStoreDir.mkdirs(); + } + Assert.assertTrue("Need to be able to create the folder " + + s_testSecondaryStoreLocalPath, + testSecondarStoreDir.exists()); + try { + params.put("local.secondary.storage.path", + testSecondarStoreDir.getCanonicalPath()); + } catch (IOException e1) { + // TODO Auto-generated catch block + Assert.fail("No canonical path for " + + testSecondarStoreDir.getAbsolutePath()); + } + + // Clean up old test files in local storage folder: + File testPoolDir = new File(s_testLocalStorePath); + if (!testPoolDir.exists()) { + testPoolDir.mkdirs(); + } + Assert.assertTrue( + "To simulate local file system Storage Pool, " + + " you need folder at " + + testPoolDir.getPath(), testPoolDir.exists() + && testPoolDir.isDirectory()); + try { + s_testLocalStorePath = testPoolDir.getCanonicalPath(); + } catch (IOException e) { + Assert.fail("No canonical path for " + + testPoolDir.getAbsolutePath()); + } + params.put("local.storage.path", s_testLocalStorePath); + + File testVolWorks = + new File(s_testLocalStorePath + File.separator + + s_testSampleVolumeWorkingUUID); + if (!testVolWorks.exists()) { + ReadableByteChannel rbc; + try { + URL sampleLegitDiskImageURL = new URL("http://s3-eu-west-1.amazonaws.com/cshv3eu/SmallDisk.vhdx"); + rbc = Channels.newChannel(sampleLegitDiskImageURL.openStream()); + FileOutputStream fos = new FileOutputStream(testVolWorks); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + Assert.assertTrue( + "Need to put a sample working virtual disk at " + + testVolWorks.getPath(), testVolWorks.exists()); + try { + s_testSampleVolumeWorkingURIJSON = + s_gson.toJson(testVolWorks.getCanonicalPath()); + } catch (IOException e) { + Assert.fail("No canonical path for " + + testPoolDir.getAbsolutePath()); + } + + FilenameFilter vhdsFilt = new FilenameFilter() { + @Override + public boolean accept(final File directory, final String fileName) { + return fileName.endsWith(".vhdx") || fileName.endsWith(".vhd"); + } + }; + for (File file : testPoolDir.listFiles(vhdsFilt)) { + if (file.getName().equals(testVolWorks.getName())) { + continue; + } + Assert.assertTrue("Should have deleted file " + file.getPath(), + file.delete()); + s_logger.info("Cleaned up by delete file " + file.getPath()); + } + + s_testSampleVolumeTempURIJSON = + createTestDiskImageFromExistingImage(testVolWorks, + s_testLocalStorePath, s_testSampleVolumeTempUUID); + s_logger.info("Created " + s_testSampleVolumeTempURIJSON); + s_testSampleVolumeCorruptURIJSON = + createTestDiskImageFromExistingImage(testVolWorks, + s_testLocalStorePath, s_testSampleVolumeCorruptUUID); + s_logger.info("Created " + s_testSampleVolumeCorruptURIJSON); + createTestDiskImageFromExistingImage(testVolWorks, + s_testLocalStorePath, + s_testSampleTemplateUUID); + s_testSampleTemplateURLJSON = s_testSampleTemplateUUID; + s_logger.info("Created " + s_testSampleTemplateURLJSON + + " in local storage."); + + // Create secondary storage template: + createTestDiskImageFromExistingImage(testVolWorks, + testSecondarStoreDir.getAbsolutePath(), + "af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx"); + s_logger.info("Created " + "af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx" + + " in secondary (NFS) storage."); + + s_testLocalStorePathJSON = s_gson.toJson(s_testLocalStorePath); + + String agentIp = (String) params.get("ipaddress"); + s_logger.info("Test using agent IP address " + agentIp); + params.put("agentIp", agentIp); + setTestJsonResult(params); + s_hypervresource.configure("hypervresource", params); + // Verify sample template is in place storage pool + s_logger.info("setUp complete, sample StoragePool at " + + s_testLocalStorePathJSON + + " sample template at " + s_testSampleTemplateURLJSON); + + s_agentExecutable = (String) params.get("agent.executable"); + s_testPrimaryDataStoreHost = (String) params.get("ipaddress"); + agentCreation(); + } + + private String createTestDiskImageFromExistingImage(final File srcFile, + final String dstPath, + final String dstFileName) { + String newFileURIJSON = null; + File testVolTemp = new File(dstPath + File.separator + dstFileName); + try { + Files.copy(srcFile, testVolTemp); + } catch (IOException e) { + ; // NOP + } + Assert.assertTrue( + "Should be a temporary file created from the valid volume) at " + + testVolTemp.getPath(), testVolTemp.exists()); + try { + newFileURIJSON = s_gson.toJson(testVolTemp.getCanonicalPath()); + } catch (IOException e) { + Assert.fail("No file at " + testVolTemp.getAbsolutePath()); + } + return newFileURIJSON; + } + + @Test + public final void testGetVmStatsCommand() { + // Sample GetVmStatsCommand + List vmNames = new ArrayList(); + vmNames.add("i-2-11-VM"); + GetVmStatsCommand cmd = + new GetVmStatsCommand(vmNames, "1", "localhost"); + + s_hypervresource.executeRequest(cmd); + GetVmStatsAnswer ans = + (GetVmStatsAnswer) s_hypervresource.executeRequest(cmd); + Assert.assertTrue(ans.getDetails(), ans.getResult()); + } + + public final void testStartupCommand() { + StartupRoutingCommand defaultStartRoutCmd = new StartupRoutingCommand( + 0, 0, 0, 0, null, Hypervisor.HypervisorType.Hyperv, + RouterPrivateIpStrategy.HostLocal, + new HashMap()); + + // Identity within the data centre is decided by CloudStack kernel, + // and passed via ServerResource.configure() + defaultStartRoutCmd.setDataCenter("1"); + defaultStartRoutCmd.setPod("1"); + defaultStartRoutCmd.setCluster("1"); + defaultStartRoutCmd.setGuid("1"); + defaultStartRoutCmd.setName("1"); + defaultStartRoutCmd.setPrivateIpAddress("1"); + defaultStartRoutCmd.setStorageIpAddress("1"); + defaultStartRoutCmd.setCpus(12); + + // TODO: does version need to be hard coded. + defaultStartRoutCmd.setVersion("4.2.0"); + + StartupCommand scmd = defaultStartRoutCmd; + + Command[] cmds = {scmd}; + String cmdsStr = s_gson.toJson(cmds); + s_logger.debug("Commands[] toJson is " + cmdsStr); + + Command[] result = s_gson.fromJson(cmdsStr, Command[].class); + s_logger.debug("Commands[] fromJson is " + s_gson.toJson(result)); + s_logger.debug("Commands[] first element has type" + + result[0].toString()); + } + + // @Test + public final void testJson() { + StartupStorageCommand sscmd = null; + com.cloud.agent.api.StoragePoolInfo pi = + new com.cloud.agent.api.StoragePoolInfo( + "test123", "192.168.0.1", "c:\\", "c:\\", + StoragePoolType.Filesystem, 100L, 50L); + + sscmd = new StartupStorageCommand(); + sscmd.setPoolInfo(pi); + sscmd.setGuid(pi.getUuid()); + sscmd.setDataCenter("foo"); + sscmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL); + s_logger.debug("StartupStorageCommand fromJson is " + + s_gson.toJson(sscmd)); + } + + @Test + public final void testBadGetVmStatsCommand() { + // Sample GetVmStatsCommand + List vmNames = new ArrayList(); + vmNames.add("FakeVM"); + GetVmStatsCommand vmStatsCmd = + new GetVmStatsCommand(vmNames, "1", "localhost"); + GetVmStatsAnswer ans = + (GetVmStatsAnswer) s_hypervresource.executeRequest(vmStatsCmd); + Assert.assertTrue(ans.getDetails(), ans.getResult()); + } + + @Test + public final void testCreateStoragePoolCommand() { + String folderName = "." + File.separator + "Dummy"; + StoragePoolVO pool = createTestStoragePoolVO(folderName); + + CreateStoragePoolCommand cmd = new CreateStoragePoolCommand(true, pool); + s_logger.debug("TestCreateStoragePoolCommand sending " + + s_gson.toJson(cmd)); + + Answer ans = s_hypervresource.executeRequest(cmd); + Assert.assertTrue(ans.getResult()); + } + + @Test + public final void testModifyStoragePoolCommand() { + // Create dummy folder + String folderName = "." + File.separator + "Dummy"; + StoragePoolVO pool = createTestStoragePoolVO(folderName); + + ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand( + true, pool, folderName); + Answer ans = s_hypervresource.executeRequest(cmd); + Assert.assertTrue(ans.getResult()); + + DeleteStoragePoolCommand delCmd = + new DeleteStoragePoolCommand(pool, folderName); + Answer ans2 = s_hypervresource.executeRequest(delCmd); + Assert.assertTrue(ans2.getResult()); + } + + // Check + @Test + public final void testModifyStoragePoolCommand2() { + // Should return existing pool + // Create dummy folder + String folderName = "." + File.separator + "Dummy"; + File folder = new File(folderName); + if (!folder.exists()) { + if (!folder.mkdir()) { + Assert.assertTrue(false); + } + } + + // Use same spec for pool + s_logger.info("Createing pool at : " + folderName); + + StoragePoolVO pool = new StoragePoolVO(StoragePoolType.Filesystem, + "127.0.0.1", -1, folderName); + pool.setUuid(s_testLocalStoreUUID); + + ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand( + true, pool, folderName); + Answer ans = s_hypervresource.executeRequest(cmd); + Assert.assertTrue(ans.getResult()); + + DeleteStoragePoolCommand delCmd = + new DeleteStoragePoolCommand(pool, folderName); + Answer ans2 = s_hypervresource.executeRequest(delCmd); + Assert.assertTrue(ans2.getResult()); + } + + public final StoragePoolVO createTestStoragePoolVO( + final String folderName) { + File folder = new File(folderName); + if (!folder.exists()) { + if (!folder.mkdir()) { + Assert.assertTrue(false); + } + } + + // Use same spec for pool + s_logger.info("Createing pool at : " + folderName); + + StoragePoolVO pool = new StoragePoolVO(StoragePoolType.Filesystem, + "127.0.0.1", -1, folderName); + return pool; + } + + @Test + public final void testInitialize() { + StartupCommand[] startCmds = s_hypervresource.initialize(); + Command[] cmds = new Command[] {startCmds[0], startCmds[1]}; + String result = s_gson.toJson(cmds); + if (result == null) { + result = "NULL"; + } + s_logger.debug("TestInitialize returned " + result); + s_logger.debug("TestInitialize expected " + _setTestJsonResultStr); + Assert.assertTrue("StartupCommand[] not what we expected", + _setTestJsonResultStr.equals(result)); + return; + } + + @Test + public final void testPrimaryStorageDownloadCommandHTTP() { + PrimaryStorageDownloadCommand cmd = samplePrimaryDownloadCommand(); + cmd.setUrl("http://s3-eu-west-1.amazonaws.com/cshv3eu/SmallDisk.vhdx"); + corePrimaryStorageDownloadCommandTestCycle(cmd); + } + + private void corePrimaryStorageDownloadCommandTestCycle( + final PrimaryStorageDownloadCommand cmd) { + PrimaryStorageDownloadAnswer ans = + (PrimaryStorageDownloadAnswer) s_hypervresource + .executeRequest(cmd); + if (!ans.getResult()) { + s_logger.error(ans.getDetails()); + } else { + s_logger.debug(ans.getDetails()); + } + + Assert.assertTrue(ans.getDetails(), ans.getResult()); + // Test that returned URL works. + // CreateCommand createCmd = CreateCommandSample(); + // CreateCommand testCreateCmd = new + // CreateCommand(createCmd.getDiskCharacteristics(), + // ans.getInstallPath(), createCmd.getPool()); + // CreateAnswer ans2 = + // (CreateAnswer)s_hypervresource.executeRequest(testCreateCmd); + // Assert.assertTrue(ans2.getDetails(), ans2.getResult()); + } + + private PrimaryStorageDownloadCommand samplePrimaryDownloadCommand() { + String cmdJson = + "{\"localPath\":" + + s_testLocalStorePathJSON + + ",\"poolUuid\":\"" + + s_testLocalStoreUUID + + "\",\"poolId\":201," + + "\"secondaryStorageUrl\":" + + "\"nfs://10.70.176.36/mnt/cshv3/secondarystorage\"," + + "\"primaryStorageUrl\":" + + "\"nfs://10.70.176.29E:\\\\Disks\\\\Disks\"," + + "\"url\":" + + "\"nfs://10.70.176.36/mnt/cshv3/secondarystorage/template/tmpl//2/204//af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx\"," + + "\"format\":\"VHDX\",\"accountId\":2," + + "\"name\":" + + "\"204-2-5a1db1ac-932b-3e7e-a0e8-5684c72cb862\"" + + ",\"contextMap\":{},\"wait\":10800}"; + PrimaryStorageDownloadCommand cmd = s_gson.fromJson(cmdJson, + PrimaryStorageDownloadCommand.class); + return cmd; + } + + public final CreateCommand createCommandSample() { + String sample = + "{\"volId\":17,\"pool\":{\"id\":201,\"uuid\":\"" + + s_testLocalStoreUUID + + "\",\"host\":\"10.70.176.29\"" + + ",\"path\":" + + s_testLocalStorePathJSON + + ",\"port\":0,\"type\":\"Filesystem\"}," + + "\"diskCharacteristics\":{\"size\":0," + + "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-15\"," + + "\"useLocalStorage\":true,\"recreatable\":true," + + "\"diskOfferingId\":11," + + "\"volumeId\":17,\"hyperType\":\"Hyperv\"}," + + "\"templateUrl\":" + + s_testSampleTemplateURLJSON + ",\"wait\":0}"; + CreateCommand cmd = s_gson.fromJson(sample, CreateCommand.class); + return cmd; + } + + @Test + public final void testCreateCommand() { + String sample = + "{\"volId\":10,\"pool\":{\"id\":201,\"uuid\":\"" + + s_testLocalStoreUUID + + "\",\"host\":\"10.70.176.29\"" + + ",\"path\":" + + s_testLocalStorePathJSON + + ",\"port\":0,\"type\":\"Filesystem\"}," + + "\"diskCharacteristics\":{\"size\":0," + + "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-9\"," + + "\"useLocalStorage\":true,\"recreatable\":true," + + "\"diskOfferingId\":11," + + "\"volumeId\":10,\"hyperType\":\"Hyperv\"}," + + "\"templateUrl\":" + + s_testSampleTemplateURLJSON + + ",\"contextMap\":{},\"wait\":0}"; + + File destDir = new File(s_testLocalStorePath); + Assert.assertTrue(destDir.isDirectory()); + File testSampleTemplateURLFile = + new File(s_testLocalStorePath + + File.separator + + s_gson.fromJson(s_testSampleTemplateURLJSON, + String.class)); + Assert.assertTrue( + "The template that create should make" + + " volumes from is missing from path " + + testSampleTemplateURLFile.getPath(), + testSampleTemplateURLFile.exists()); + + int fileCount = destDir.listFiles().length; + s_logger.debug(" test local store has " + fileCount + "files"); + // Test requires there to be a template at the tempalteUrl, which is its + // location in the local file system. + CreateCommand cmd = s_gson.fromJson(sample, CreateCommand.class); + CreateAnswer ans = (CreateAnswer) s_hypervresource.executeRequest(cmd); + Assert.assertTrue(ans.getDetails(), ans.getResult()); + Assert.assertTrue("CreateCommand should add a file to the folder", + fileCount + 1 == destDir.listFiles().length); + File newFile = new File(ans.getVolume().getPath()); + Assert.assertTrue("The new file should have a size greater than zero", + newFile.length() > 0); + newFile.delete(); + } + + @Test + public final void testStartCommandCorruptDiskImage() { + String sampleStart = + "{\"vm\":{\"id\":16,\"name\":\"i-3-17-VM\"," + + "\"type\":\"User\",\"cpus\":1,\"speed\":500," + + "\"minRam\":536870912,\"maxRam\":536870912," + + "\"arch\":\"x86_64\"," + + "\"os\":\"CentOS 6.0 (64-bit)\"," + + "\"bootArgs\":\"\",\"rebootOnCrash\":false," + + "\"enableHA\":false," + + "\"limitCpuUse\":false," + + "\"vncPassword\":\"31f82f29aff646eb\"," + + "\"params\":{}," + + "\"uuid\":\"8b030b6a-0243-440a-8cc5-45d08815ca11\"" + + ",\"disks\":[" + + "{\"id\":18,\"name\":\"" + + s_testSampleVolumeCorruptUUID + + "\"," + + "\"mountPoint\":" + + s_testSampleVolumeCorruptURIJSON + + "," + + "\"path\":" + + s_testSampleVolumeCorruptURIJSON + + ",\"size\":0," + + "\"type\":\"ROOT\"," + + "\"storagePoolType\":\"Filesystem\"," + + "\"storagePoolUuid\":\"" + + s_testLocalStoreUUID + + "\"" + + ",\"deviceId\":0}," + + "{\"id\":16,\"name\":\"Hyper-V Sample2\",\"size\":0," + + "\"type\":\"ISO\",\"storagePoolType\":\"ISO\"," + + "\"deviceId\":3}]," + + "\"nics\":[" + + "{\"deviceId\":0,\"networkRateMbps\":100," + + "\"defaultNic\":true," + + "\"uuid\":\"99cb4813-23af-428c-a87a-2d1899be4f4b\"," + + "\"ip\":\"10.1.1.67\",\"netmask\":\"255.255.255.0\"," + + "\"gateway\":\"10.1.1.1\"," + + "\"mac\":\"02:00:51:2c:00:0e\",\"dns1\":\"4.4.4.4\"," + + "\"broadcastType\":\"Vlan\",\"type\":\"Guest\"," + + "\"broadcastUri\":\"vlan://261\"," + + "\"isolationUri\":\"vlan://261\"," + + "\"isSecurityGroupEnabled\":false}" + + "]},\"contextMap\":{},\"wait\":0}"; + + StartCommand cmd = s_gson.fromJson(sampleStart, StartCommand.class); + StartAnswer ans = + (StartAnswer) s_hypervresource.executeRequest(cmd); + Assert.assertFalse(ans.getDetails(), ans.getResult()); + } + + @Test + public final void testStartStopCommand() { + String sample = getSampleStartCommand(); + StartAnswer sans = simpleVmStart(sample); + Assert.assertTrue(sans.getDetails(), sans.getResult()); + StopAnswer stopAns = simpleVmStop(); + Assert.assertTrue(stopAns.getDetails(), stopAns.getResult()); + } + + @Test + public final void testStartStartCommand() { + String sample = getSampleStartCommand(); + + StartAnswer sans = simpleVmStart(sample); + Assert.assertTrue(sans.getDetails(), sans.getResult()); + simpleVmStart(sample); + + StopAnswer ans = simpleVmStop(); + Assert.assertTrue(ans.getDetails(), ans.getResult()); + } + + private StopAnswer simpleVmStop() { + String sampleStop = + "{\"isProxy\":false,\"vmName\":\"i-2-17-VM\"," + + "\"contextMap\":{},\"wait\":0}"; + StopCommand cmd = s_gson.fromJson(sampleStop, StopCommand.class); + StopAnswer ans = (StopAnswer) s_hypervresource.executeRequest(cmd); + return ans; + } + + private StartAnswer simpleVmStart(final String sample) { + StartCommand cmd = s_gson.fromJson(sample, StartCommand.class); + s_logger.info("StartCommand sample " + s_gson.toJson(cmd)); + StartAnswer ans = + (StartAnswer) s_hypervresource.executeRequest(cmd); + return ans; + } + + @Test + public final void testDestroyCommand() { + // TODO: how does the command vary when we are only deleting a vm versus + // deleting a volume? + +// String sample2 = "{\"volume\":" + getSampleVolumeObjectTO() + "}"; + + String sample2 = + "{\"volume\":{\"name\":\"" + s_testSampleVolumeWorkingUUIDNoExt + + "\",\"storagePoolType\":\"Filesystem\"," + + "\"mountPoint\":" + + s_testLocalStorePathJSON + + ",\"path\":" + s_testSampleVolumeTempURIJSON + + ",\"storagePoolUuid\":\"" + s_testLocalStoreUUID + + "\"," + + "\"type\":\"ROOT\",\"id\":9,\"size\":0}}"; + DestroyCommand cmd = s_gson.fromJson(sample2, DestroyCommand.class); + Answer ans = s_hypervresource.executeRequest(cmd); + Assert.assertTrue(ans.getDetails(), ans.getResult()); + } + + @Test + public final void testGetStorageStatsCommand() { + // TODO: Update sample data to unsure it is using correct info. + String sample = + "{\"id\":\"" + + s_testLocalStoreUUID + + "\",\"localPath\":" + + s_testLocalStorePathJSON + + "," + + "\"pooltype\":\"Filesystem\"," + + "\"contextMap\":{},\"wait\":0}"; + + s_logger.info("Sample JSON: " + sample); + + GetStorageStatsCommand cmd = + s_gson.fromJson(sample, GetStorageStatsCommand.class); + s_hypervresource.executeRequest(cmd); + GetStorageStatsAnswer ans = + (GetStorageStatsAnswer) s_hypervresource.executeRequest(cmd); + Assert.assertTrue(ans.getDetails(), ans.getResult()); + Assert.assertTrue(ans.getByteUsed() != ans.getCapacityBytes()); + } + + @After + public final void agentTerminate() { + // Write carriage return line feed to script's stdin + OutputStream scriptInput = s_agentProc.getOutputStream(); + OutputStreamWriter siw = new OutputStreamWriter(scriptInput); + try { + BufferedWriter writer = new BufferedWriter(siw); + writer.write("\r\n"); + writer.flush(); + writer.close(); + } catch (IOException ex) { + s_logger.debug("Error closing agent at " + s_agentExecutable + + " message " + ex.getMessage()); + } + } + + private void agentCreation() { + // Launch script + try { + List exeArgs = new ArrayList(); + + exeArgs.add(s_agentExecutable); + exeArgs.add("--console"); + + // when we launch from the shell, we need to use Cygwin's path to + // the exe + ProcessBuilder builder = new ProcessBuilder(exeArgs); + builder.redirectErrorStream(true); + s_agentProc = builder.start(); + Thread.sleep(4000); + } catch (Exception ex) { + s_logger.debug("Error calling starting aget at " + + s_agentExecutable + + " message " + ex.getMessage()); + } + } + + @Test + public final void testGetHostStatsCommand() { + // Arrange + long hostIdVal = 123; + GetHostStatsCommand cmd = new GetHostStatsCommand("1", "testHost", + hostIdVal); + + // Act + GetHostStatsAnswer ans = (GetHostStatsAnswer) s_hypervresource + .executeRequest(cmd); + + // Assert + Assert.assertTrue(ans.getResult()); + Assert.assertTrue(0.0 < ans.getTotalMemoryKBs()); + Assert.assertTrue(0.0 < ans.getFreeMemoryKBs()); + Assert.assertTrue(0.0 <= ans.getNetworkReadKBs()); + Assert.assertTrue(0.0 <= ans.getNetworkWriteKBs()); + Assert.assertTrue(0.0 <= ans.getCpuUtilization()); + Assert.assertTrue(100 >= ans.getCpuUtilization()); + Assert.assertTrue(ans.getEntityType().equals("host")); + Assert.assertTrue(ans.getDetails() == null); + } + + public static Properties loadProperties() throws ConfigurationException { + Properties properties = new Properties(); + final File file = PropertiesUtil.findConfigFile("agent.properties"); + if (file == null) { + throw new ConfigurationException( + "Unable to find agent.properties."); + } + + s_logger.info("agent.properties found at " + file.getAbsolutePath()); + + try { + properties.load(new FileInputStream(file)); + } catch (final FileNotFoundException ex) { + throw new CloudRuntimeException("Cannot find the file: " + + file.getAbsolutePath(), ex); + } catch (final IOException ex) { + throw new CloudRuntimeException("IOException in reading " + + file.getAbsolutePath(), ex); + } + return properties; + } + + private String _setTestJsonResultStr = null; + + public final void setTestJsonResult(final Map params) { + File dir = new File((String) params.get("DefaultVirtualDiskFolder")); + long usableCapacity = dir.getUsableSpace() - 4294967296L; + long totalSpace = dir.getTotalSpace() - 4294967296L; + + // TODO: add test to verify capacity statistics change + _setTestJsonResultStr = + String.format( + "[{\"com.cloud.agent.api.StartupRoutingCommand\":{" + + "\"cpus\":%s," + + "\"speed\":%s," + + "\"memory\":%s," + + "\"dom0MinMemory\":%s," + + "\"poolSync\":false," + + "\"vms\":{}," + + "\"caps\":\"hvm\"," + + "\"hypervisorType\":\"Hyperv\"," + + "\"hostDetails\":{" + + "\"com.cloud.network.Networks.RouterPrivateIpStrategy\":" + + "\"HostLocal\"" + + "}," + + "\"type\":\"Routing\"," + + "\"dataCenter\":%s," + + "\"pod\":%s," + + "\"cluster\":%s," + + "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + + "\"name\":\"hypervresource\"," + + "\"version\":\"4.2.0\"," + + "\"privateIpAddress\":%s," + + "\"privateMacAddress\":%s," + + "\"privateNetmask\":%s," + + "\"storageIpAddress\":%s," + + "\"storageNetmask\":%s," + + "\"storageMacAddress\":%s," + + "\"gatewayIpAddress\":%s," + + "\"contextMap\":{}," + + "\"wait\":0" + + "}}," + + "{\"com.cloud.agent.api.StartupStorageCommand\":{" + + "\"totalSize\":0," + + "\"poolInfo\":{" + + "\"uuid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + + "\"host\":%s," + + "\"localPath\":%s," + + "\"hostPath\":%s," + + "\"poolType\":\"Filesystem\"," + + "\"capacityBytes\":%s," + + "\"availableBytes\":%s" + + "}," + + "\"resourceType\":\"STORAGE_POOL\"," + + "\"hostDetails\":{}," + + "\"type\":\"Storage\"," + + "\"dataCenter\":\"1\"," + + "\"guid\":" + + "\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + + "\"contextMap\":{}," + + "\"wait\":0" + + "}}]", + params.get("TestCoreCount"), + params.get("TestCoreMhz"), + params.get("TestMemoryMb"), + params.get("TestDom0MinMemoryMb"), + s_gson.toJson(params.get("zone")), + s_gson.toJson(params.get("pod")), + s_gson.toJson(params.get("cluster")), + s_gson.toJson(params.get("ipaddress")), + s_gson.toJson(params + .get("private.mac.address")), + s_gson.toJson(params.get( + "private.ip.netmask")), + s_gson.toJson(params.get("ipaddress")), + s_gson.toJson(params.get( + "private.ip.netmask")), + s_gson.toJson(params + .get("private.mac.address")), + s_gson.toJson(params.get( + "gateway.ip.address")), + s_gson.toJson(params.get("ipaddress")), + s_gson.toJson(params + .get("DefaultVirtualDiskFolder")), + s_gson.toJson(params + .get("DefaultVirtualDiskFolder")), + s_gson.toJson(totalSpace), + s_gson.toJson(usableCapacity) + ); + } + + public static String getSamplePrimaryDataStoreInfo() { + String samplePrimaryDataStoreInfo = + "{\"org.apache.cloudstack.storage.to.PrimaryDataStoreTO\":" + + "{\"uuid\":\"" + s_testLocalStoreUUID + "\"," + + "\"id\":201," + + "\"host\":\"" + s_testPrimaryDataStoreHost + "\"," + + "\"type\":\"Filesystem\"," // Not used in + // PrimaryDataStoreTO + + "\"poolType\":\"Filesystem\"," // Not used in + // PrimaryDataStoreTO + + "\"path\":" + s_testLocalStorePathJSON + "," + + "\"port\":0}" + + "}"; + return samplePrimaryDataStoreInfo; + } + + public static String getSampleVolumeObjectTO() { + String sampleVolumeObjectTO = + "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + + "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + + "\"volumeType\":\"ROOT\"," + + "\"format\":\"VHDX\"," + + "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + + "," + + "\"name\":\"" + s_testSampleVolumeWorkingUUIDNoExt + "\"," + + "\"size\":52428800," + + "\"volumeId\":10," + // "\"vmName\":\"i-3-5-VM\"," + // TODO: required? + + "\"accountId\":3,\"id\":10}" + + "}"; // end of destTO + return sampleVolumeObjectTO; + } + + public static String getSampleStartCommand() { + String sample = + "{\"vm\":{\"id\":17,\"name\":\"i-2-17-VM\"," + + "\"type\":\"User\",\"cpus\":1,\"speed\":500," + + "\"minRam\":536870912,\"maxRam\":536870912," + + "\"arch\":\"x86_64\"," + + "\"os\":\"CentOS 6.0 (64-bit)\"," + + "\"bootArgs\":\"\",\"rebootOnCrash\":false," + + "\"enableHA\":false,\"limitCpuUse\":false," + + "\"vncPassword\":\"31f82f29aff646eb\"," + + "\"params\":{}," + + "\"uuid\":\"8b030b6a-0243-440a-8cc5-45d08815ca11\"" + + ",\"disks\":[" + + "{\"data\":" + + getSampleVolumeObjectTO() + + ",\"diskSeq\":0,\"type\":\"ROOT\"}," + + "{\"diskSeq\":1,\"type\":\"ISO\"}" + + "]," + + "\"nics\":[" + + "{\"deviceId\":0,\"networkRateMbps\":100," + + "\"defaultNic\":true," + + "\"uuid\":\"99cb4813-23af-428c-a87a-2d1899be4f4b\"," + + "\"ip\":\"10.1.1.67\"," + + "\"netmask\":\"255.255.255.0\"," + + "\"gateway\":\"10.1.1.1\"," + + "\"mac\":\"02:00:51:2c:00:0e\",\"dns1\":\"4.4.4.4\"," + + "\"broadcastType\":\"Vlan\",\"type\":\"Guest\"," + + "\"broadcastUri\":\"vlan://261\"," + + "\"isolationUri\":\"vlan://261\"," + + "\"isSecurityGroupEnabled\":false}" + + "]},\"contextMap\":{},\"wait\":0}"; + return sample; + } +} 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 8d3a0e9cdf1..e3f60f2357f 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 @@ -1055,7 +1055,7 @@ ServerResource { String fname = interfaces[i].getName(); s_logger.debug("matchPifFileInDirectory: file name '"+fname+"'"); if (fname.startsWith("eth") || fname.startsWith("bond") - || fname.startsWith("vlan") || fname.startsWith("em") + || fname.startsWith("vlan") || fname.startsWith("vxlan") || fname.startsWith("em") || fname.matches("^p\\d+p\\d+.*")) { return fname; } diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java index 8ef855e3df6..9402d0fdee9 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java @@ -20,13 +20,10 @@ import java.io.File; import java.io.FileInputStream; import java.io.BufferedInputStream; import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.Map; -import java.util.HashMap; import org.apache.log4j.Logger; import org.apache.commons.codec.binary.Base64; import org.apache.cloudstack.utils.qemu.QemuImg; @@ -37,7 +34,6 @@ import org.libvirt.Connect; import org.libvirt.LibvirtException; import org.libvirt.Secret; import org.libvirt.StoragePool; -import org.libvirt.StoragePoolInfo; import org.libvirt.StorageVol; import org.libvirt.StoragePoolInfo.StoragePoolState; import com.ceph.rados.Rados; @@ -48,7 +44,6 @@ import com.ceph.rbd.RbdImage; import com.ceph.rbd.RbdException; import com.ceph.rbd.jna.RbdSnapInfo; -import com.cloud.agent.api.ManageSnapshotCommand; import com.cloud.hypervisor.kvm.resource.LibvirtConnection; import com.cloud.hypervisor.kvm.resource.LibvirtSecretDef; import com.cloud.hypervisor.kvm.resource.LibvirtSecretDef.usage; @@ -63,7 +58,6 @@ import com.cloud.exception.InternalErrorException; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StorageLayer; import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.script.OutputInterpreter; import com.cloud.utils.script.Script; public class LibvirtStorageAdaptor implements StorageAdaptor { @@ -72,8 +66,6 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { private StorageLayer _storageLayer; private String _mountPoint = "/mnt"; private String _manageSnapshotPath; - private String _lockfile = "KVMFILELOCK" + File.separator + ".lock"; - private static final int ACQUIRE_GLOBAL_FILELOCK_TIMEOUT_FOR_KVM = 300; // 300 seconds private String rbdTemplateSnapName = "cloudstack-base-snap"; private int rbdFeatures = (1<<0); /* Feature 1<<0 means layering in RBD format 2 */ @@ -434,6 +426,8 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { disk.setFormat(PhysicalDiskFormat.DIR); } else if (volumeUuid.endsWith("tar") || volumeUuid.endsWith(("TAR"))) { disk.setFormat(PhysicalDiskFormat.TAR); + } else if (volumeUuid.endsWith("raw") || volumeUuid.endsWith(("RAW"))) { + disk.setFormat(PhysicalDiskFormat.RAW); } else { disk.setFormat(pool.getDefaultFormat()); } @@ -1222,10 +1216,6 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { return deleteStoragePool(pool.getUuid()); } - // refreshPool and deleteVol are used to fix CLOUDSTACK-2729/CLOUDSTACK-2780 - // They are caused by a libvirt bug (https://bugzilla.redhat.com/show_bug.cgi?id=977706) - // However, we also need to fix the issues in CloudStack source code. - // A file lock is used to prevent deleting a volume from a KVM storage pool when refresh it. private void refreshPool(StoragePool pool) throws LibvirtException { pool.refresh(0); return; @@ -1235,28 +1225,4 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { vol.delete(0); } - private boolean lock(String path, int wait) { - File lockFile = new File(path); - lockFile.getParentFile().mkdir(); - boolean havelock = false; - try { - while (wait > 0) { - if (lockFile.createNewFile()) { - havelock = true; - break; - } - s_logger.debug("lockFile " + _lockfile + " already exists, waiting 1000 ms"); - Thread.sleep(1000); - wait--; - } - } catch (IOException e) { - } catch (InterruptedException e) { - } - return havelock; - } - - private void unlock(String path) { - File lockFile = new File(path); - lockFile.delete(); - } } diff --git a/plugins/hypervisors/simulator/src/org/apache/cloudstack/storage/datastore/driver/SimulatorImageStoreDriverImpl.java b/plugins/hypervisors/simulator/src/org/apache/cloudstack/storage/datastore/driver/SimulatorImageStoreDriverImpl.java index e18f8e59b82..26f8a40e1d5 100644 --- a/plugins/hypervisors/simulator/src/org/apache/cloudstack/storage/datastore/driver/SimulatorImageStoreDriverImpl.java +++ b/plugins/hypervisors/simulator/src/org/apache/cloudstack/storage/datastore/driver/SimulatorImageStoreDriverImpl.java @@ -20,14 +20,12 @@ package org.apache.cloudstack.storage.datastore.driver; -import com.cloud.agent.api.storage.DownloadAnswer; -import com.cloud.agent.api.to.DataObjectType; -import com.cloud.agent.api.to.DataStoreTO; -import com.cloud.agent.api.to.NfsTO; -import com.cloud.storage.Storage; -import com.cloud.storage.VMTemplateStorageResourceAssoc; -import com.cloud.storage.dao.VMTemplateDao; -import com.cloud.storage.dao.VolumeDao; +import java.util.UUID; + +import javax.inject.Inject; + +import org.apache.log4j.Logger; + import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; @@ -39,10 +37,15 @@ import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao; import org.apache.cloudstack.storage.image.BaseImageStoreDriverImpl; import org.apache.cloudstack.storage.image.store.ImageStoreImpl; -import org.apache.log4j.Logger; -import javax.inject.Inject; -import java.util.UUID; +import com.cloud.agent.api.storage.DownloadAnswer; +import com.cloud.agent.api.to.DataObjectType; +import com.cloud.agent.api.to.DataStoreTO; +import com.cloud.agent.api.to.NfsTO; +import com.cloud.storage.Storage; +import com.cloud.storage.VMTemplateStorageResourceAssoc; +import com.cloud.storage.dao.VMTemplateDao; +import com.cloud.storage.dao.VolumeDao; public class SimulatorImageStoreDriverImpl extends BaseImageStoreDriverImpl { private static final Logger s_logger = Logger.getLogger(SimulatorImageStoreDriverImpl.class); @@ -71,9 +74,9 @@ public class SimulatorImageStoreDriverImpl extends BaseImageStoreDriverImpl { @Override public void createAsync(DataStore dataStore, DataObject data, AsyncCompletionCallback callback) { if (data.getType() == DataObjectType.TEMPLATE) { - this.createTemplate(data, callback); + createTemplate(data, callback); } else if (data.getType() == DataObjectType.VOLUME) { - this.createVolume(data, callback); + createVolume(data, callback); } } @@ -108,6 +111,11 @@ public class SimulatorImageStoreDriverImpl extends BaseImageStoreDriverImpl { @Override public String createEntityExtractUrl(DataStore store, String installPath, Storage.ImageFormat format, DataObject dataObject) { EndPoint ep = _epSelector.select(store); + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + return null; + } // Create Symlink at ssvm String path = installPath; String uuid = UUID.randomUUID().toString() + "." + format.getFileExtension(); diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareHostService.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareHostService.java index d0147d194a6..d5a228411ce 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareHostService.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareHostService.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.hypervisor.vmware.manager; +import java.util.List; + import com.cloud.agent.api.Command; import com.cloud.hypervisor.vmware.mo.DatastoreMO; import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost; @@ -33,4 +35,5 @@ public interface VmwareHostService { String iqn, String initiatorChapName, String initiatorChapSecret, String mutualChapName, String mutualChapSecret) throws Exception; void createVmdk(Command cmd, DatastoreMO dsMo, String volumeDatastorePath, Long volumeSize) throws Exception; void handleDatastoreAndVmdkDetach(String iqn, String storageHost, int storagePort) throws Exception; + void removeManagedTargetsFromCluster(List managedIqns) throws Exception; } diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java index 423abe67a47..a205fb6ae12 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java @@ -1559,6 +1559,9 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } else { args += "0"; } + if (cmd.isPassive()) { + args += " -p "; + } } else { args += " -D"; args += " -r "; @@ -2982,7 +2985,9 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa VolumeObjectTO volumeTO = (VolumeObjectTO)vol.getData(); PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)volumeTO.getDataStore(); - + Map details = vol.getDetails(); + boolean isManaged = details != null && Boolean.parseBoolean(details.get(DiskTO.MANAGED)); + Pair volumeDsDetails = dataStoresDetails.get(primaryStore.getUuid()); if(volumeDsDetails == null) throw new Exception("Primary datastore " + primaryStore.getUuid() + " is not mounted on host."); @@ -2994,17 +2999,25 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa String disks[] = diskInfo.getDiskChain(); for(int i = 0; i < disks.length; i++) { DatastoreFile file = new DatastoreFile(disks[i]); - if(file.getDir() != null && file.getDir().isEmpty()) { + if (!isManaged && file.getDir() != null && file.getDir().isEmpty()) { s_logger.info("Perform run-time datastore folder upgrade. sync " + disks[i] + " to VM folder"); disks[i] = VmwareStorageLayoutHelper.syncVolumeToVmDefaultFolder( dcMo, vmMo.getName(), dsMo, file.getFileBaseName()); } } return disks; - } - - String datastoreDiskPath = VmwareStorageLayoutHelper.syncVolumeToVmDefaultFolder( - dcMo, vmMo.getName(), dsMo, volumeTO.getPath()); + } + + final String datastoreDiskPath; + + if (isManaged) { + datastoreDiskPath = dsMo.getDatastorePath(dsMo.getName() + ".vmdk"); + } + else { + datastoreDiskPath = VmwareStorageLayoutHelper.syncVolumeToVmDefaultFolder( + dcMo, vmMo.getName(), dsMo, volumeTO.getPath()); + } + if(!dsMo.fileExists(datastoreDiskPath)) { s_logger.warn("Volume " + volumeTO.getId() + " does not seem to exist on datastore, out of sync? path: " + datastoreDiskPath); } @@ -3220,7 +3233,10 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if(diskInfoBuilder != null) { VolumeObjectTO volume = (VolumeObjectTO)vol.getData(); - VirtualMachineDiskInfo diskInfo = diskInfoBuilder.getDiskInfoByBackingFileBaseName(volume.getPath()); + Map details = vol.getDetails(); + boolean isManaged = details != null && Boolean.parseBoolean(details.get(DiskTO.MANAGED)); + + VirtualMachineDiskInfo diskInfo = diskInfoBuilder.getDiskInfoByBackingFileBaseName(isManaged ? new DatastoreFile(volume.getPath()).getFileBaseName() : volume.getPath()); if(diskInfo != null) { s_logger.info("Found existing disk info from volume path: " + volume.getPath()); return diskInfo; @@ -3418,7 +3434,16 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)volumeTO.getDataStore(); String poolUuid = primaryStore.getUuid(); if(poolMors.get(poolUuid) == null) { - ManagedObjectReference morDataStore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, poolUuid); + boolean isManaged = false; + String iScsiName = null; + Map details = vol.getDetails(); + + if (details != null) { + isManaged = Boolean.parseBoolean(details.get(DiskTO.MANAGED)); + iScsiName = details.get(DiskTO.IQN); + } + + ManagedObjectReference morDataStore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, isManaged ? VmwareResource.getDatastoreName(iScsiName) : poolUuid); if (morDataStore == null) { String msg = "Failed to get the mounted datastore for the volume's pool " + poolUuid; s_logger.error(msg); @@ -4531,7 +4556,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), dsMo.getName()); if (!dsMo.fileExists(volumeDatastorePath)) { - createVmdk(cmd, dsMo, VmwareResource.getDatastoreName(cmd.get_iScsiName()), cmd.getVolumeSize()); + createVmdk(cmd, dsMo, volumeDatastorePath, cmd.getVolumeSize()); } } else { @@ -4589,6 +4614,35 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } } + @Override + public void removeManagedTargetsFromCluster(List iqns) throws Exception { + List lstManagedTargets = new ArrayList(); + + VmwareContext context = getServiceContext(); + VmwareHypervisorHost hyperHost = getHyperHost(context); + ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); + ClusterMO cluster = new ClusterMO(context, morCluster); + List> lstHosts = cluster.getClusterHosts(); + HostMO host = new HostMO(context, lstHosts.get(0).first()); + HostStorageSystemMO hostStorageSystem = host.getHostStorageSystemMO(); + + for (HostHostBusAdapter hba : hostStorageSystem.getStorageDeviceInfo().getHostBusAdapter()) { + if (hba instanceof HostInternetScsiHba) { + List lstTargets = ((HostInternetScsiHba)hba).getConfiguredStaticTarget(); + + if (lstTargets != null) { + for (HostInternetScsiHbaStaticTarget target : lstTargets) { + if (iqns.contains(target.getIScsiName())) { + lstManagedTargets.add(target); + } + } + } + } + } + + addRemoveInternetScsiTargetsToAllHosts(false, lstManagedTargets, lstHosts); + } + private void addRemoveInternetScsiTargetsToAllHosts(final boolean add, final List lstTargets, final List> lstHosts) throws Exception { VmwareContext context = getServiceContext(); diff --git a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageResourceHandler.java b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageResourceHandler.java index c84813f0b30..81f7bd9a7fa 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageResourceHandler.java +++ b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageResourceHandler.java @@ -360,4 +360,8 @@ public class VmwareSecondaryStorageResourceHandler implements SecondaryStorageRe public void handleDatastoreAndVmdkDetach(String iqn, String storageHost, int storagePort) throws Exception { throw new OperationNotSupportedException(); } + + public void removeManagedTargetsFromCluster(List managedIqns) throws Exception { + throw new OperationNotSupportedException(); + } } 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 71ba4e9ff87..fbbbc13c6b3 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java +++ b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java @@ -23,6 +23,7 @@ import java.io.OutputStreamWriter; import java.net.URI; import java.rmi.RemoteException; import java.util.HashMap; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; @@ -36,7 +37,6 @@ import org.apache.cloudstack.storage.command.DeleteCommand; import org.apache.cloudstack.storage.command.DettachCommand; import org.apache.cloudstack.storage.command.ForgetObjectCmd; import org.apache.cloudstack.storage.command.IntroduceObjectCmd; -import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; import org.apache.cloudstack.storage.to.SnapshotObjectTO; import org.apache.cloudstack.storage.to.TemplateObjectTO; import org.apache.cloudstack.storage.to.VolumeObjectTO; @@ -79,6 +79,7 @@ import com.cloud.vm.VirtualMachine.State; import com.google.gson.Gson; import com.vmware.vim25.ManagedObjectReference; import com.vmware.vim25.VirtualDisk; +import com.vmware.vim25.VirtualDiskFlatVer2BackingInfo; public class VmwareStorageProcessor implements StorageProcessor { private static final Logger s_logger = Logger.getLogger(VmwareStorageProcessor.class); @@ -192,7 +193,7 @@ public class VmwareStorageProcessor implements StorageProcessor { NfsTO nfsImageStore = (NfsTO)srcStore; DataTO destData = cmd.getDestTO(); DataStoreTO destStore = destData.getDataStore(); - PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)destStore; + DataStoreTO primaryStore = destStore; String secondaryStorageUrl = nfsImageStore.getUrl(); assert (secondaryStorageUrl != null); @@ -308,8 +309,8 @@ public class VmwareStorageProcessor implements StorageProcessor { TemplateObjectTO template = (TemplateObjectTO)srcData; DataTO destData = cmd.getDestTO(); VolumeObjectTO volume = (VolumeObjectTO)destData; - PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)volume.getDataStore(); - PrimaryDataStoreTO srcStore = (PrimaryDataStoreTO)template.getDataStore(); + DataStoreTO primaryStore = volume.getDataStore(); + DataStoreTO srcStore = template.getDataStore(); try { VmwareContext context = hostService.getServiceContext(null); @@ -448,20 +449,22 @@ public class VmwareStorageProcessor implements StorageProcessor { try { NfsTO srcStore = (NfsTO)srcVolume.getDataStore(); - PrimaryDataStoreTO destStore = (PrimaryDataStoreTO)destVolume.getDataStore(); + DataStoreTO destStore = destVolume.getDataStore(); VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); String uuid = destStore.getUuid(); ManagedObjectReference morDatastore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, uuid); if (morDatastore == null) { + URI uri = new URI(destStore.getUrl()); + morDatastore = hyperHost.mountDatastore( false, - destStore.getHost(), 0, destStore.getPath(), + uri.getHost(), 0, uri.getPath(), destStore.getUuid().replace("-", "")); if (morDatastore == null) { - throw new Exception("Unable to mount storage pool on host. storeUrl: " + destStore.getHost() + ":/" + destStore.getPath()); + throw new Exception("Unable to mount storage pool on host. storeUrl: " + uri.getHost() + ":/" + uri.getPath()); } } @@ -549,7 +552,7 @@ public class VmwareStorageProcessor implements StorageProcessor { VmwareContext context = hostService.getServiceContext(cmd); try { - PrimaryDataStoreTO primaryStorage = (PrimaryDataStoreTO)srcVolume.getDataStore(); + DataStoreTO primaryStorage = srcVolume.getDataStore(); NfsTO destStore = (NfsTO)destVolume.getDataStore(); VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); @@ -996,7 +999,7 @@ public class VmwareStorageProcessor implements StorageProcessor { @Override public Answer backupSnapshot(CopyCommand cmd) { SnapshotObjectTO srcSnapshot = (SnapshotObjectTO)cmd.getSrcTO(); - PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)srcSnapshot.getDataStore(); + DataStoreTO primaryStore = srcSnapshot.getDataStore(); SnapshotObjectTO destSnapshot = (SnapshotObjectTO)cmd.getDestTO(); DataStoreTO destStore = destSnapshot.getDataStore(); if (!(destStore instanceof NfsTO)) { @@ -1178,7 +1181,7 @@ public class VmwareStorageProcessor implements StorageProcessor { private Answer attachVolume(Command cmd, DiskTO disk, boolean isAttach, boolean isManaged, String vmName, String iScsiName, String storageHost, int storagePort) { VolumeObjectTO volumeTO = (VolumeObjectTO)disk.getData(); - PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)volumeTO.getDataStore(); + DataStoreTO primaryStore = volumeTO.getDataStore(); try { VmwareHypervisorHost hyperHost = hostService.getHyperHost(hostService.getServiceContext(null), null); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); @@ -1194,7 +1197,7 @@ public class VmwareStorageProcessor implements StorageProcessor { Map details = disk.getDetails(); morDs = hostService.getVmfsDatastore(hyperHost, VmwareResource.getDatastoreName(iScsiName), storageHost, storagePort, - VmwareResource.trimIqn(iScsiName), details.get(DiskTO.CHAP_INITIATOR_USERNAME), details.get(DiskTO.CHAP_INITIATOR_SECRET), + VmwareResource.trimIqn(iScsiName), details.get(DiskTO.CHAP_INITIATOR_USERNAME), details.get(DiskTO.CHAP_INITIATOR_SECRET), details.get(DiskTO.CHAP_TARGET_USERNAME), details.get(DiskTO.CHAP_TARGET_SECRET)); DatastoreMO dsMo = new DatastoreMO(hostService.getServiceContext(null), morDs); @@ -1202,7 +1205,7 @@ public class VmwareStorageProcessor implements StorageProcessor { String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), dsMo.getName()); if (!dsMo.fileExists(volumeDatastorePath)) { - hostService.createVmdk(cmd, dsMo, VmwareResource.getDatastoreName(iScsiName), volumeTO.getSize()); + hostService.createVmdk(cmd, dsMo, volumeDatastorePath, volumeTO.getSize()); } } else { @@ -1380,7 +1383,7 @@ public class VmwareStorageProcessor implements StorageProcessor { public Answer createVolume(CreateObjectCommand cmd) { VolumeObjectTO volume = (VolumeObjectTO)cmd.getData(); - PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)volume.getDataStore(); + DataStoreTO primaryStore = volume.getDataStore(); try { VmwareContext context = hostService.getServiceContext(null); @@ -1457,11 +1460,11 @@ public class VmwareStorageProcessor implements StorageProcessor { VmwareContext context = hostService.getServiceContext(null); VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, null); VolumeObjectTO vol = (VolumeObjectTO)cmd.getData(); - PrimaryDataStoreTO store = (PrimaryDataStoreTO)vol.getDataStore(); + DataStoreTO store = vol.getDataStore(); ManagedObjectReference morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, store.getUuid()); if (morDs == null) { - String msg = "Unable to find datastore based on volume mount point " + store.getPath(); + String msg = "Unable to find datastore based on volume mount point " + store.getUuid(); s_logger.error(msg); throw new Exception(msg); } @@ -1498,6 +1501,14 @@ public class VmwareStorageProcessor implements StorageProcessor { vmMo.safePowerOff(_shutdown_waitMs); } + // call this before calling detachAllDisksExcept + // when expunging a VM, we need to see if any of its disks are serviced by managed storage + // if there is one or more disk serviced by managed storage, remove the iSCSI connection(s) + // don't remove the iSCSI connection(s) until the supported disk(s) is/are removed from the VM + // (removeManagedTargetsFromCluster should be called after detachAllDisksExcept and vm.destroy) + List virtualDisks = vmMo.getVirtualDisks(); + List managedIqns = getManagedIqnsFromVirtualDisks(virtualDisks); + List detachedDisks = vmMo.detachAllDisksExcept(vol.getPath(), diskInfo != null ? diskInfo.getDiskDeviceBusName() : null); VmwareStorageLayoutHelper.moveVolumeToRootFolder(new DatacenterMO(context, morDc), detachedDisks); @@ -1505,6 +1516,9 @@ public class VmwareStorageProcessor implements StorageProcessor { // vmMo.tearDownDevices(new Class[] { VirtualDisk.class, VirtualEthernetCard.class }); vmMo.destroy(); + // this.hostService.handleDatastoreAndVmdkDetach(iScsiName, storageHost, storagePort); + this.hostService.removeManagedTargetsFromCluster(managedIqns); + for (NetworkDetails netDetails : networks) { if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) { if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) { @@ -1555,6 +1569,40 @@ public class VmwareStorageProcessor implements StorageProcessor { } } + private List getManagedIqnsFromVirtualDisks(List virtualDisks) { + List managedIqns = new ArrayList(); + + if (virtualDisks != null) { + for (VirtualDisk virtualDisk : virtualDisks) { + if (virtualDisk.getBacking() instanceof VirtualDiskFlatVer2BackingInfo) { + VirtualDiskFlatVer2BackingInfo backingInfo = (VirtualDiskFlatVer2BackingInfo)virtualDisk.getBacking(); + String path = backingInfo.getFileName(); + + path = new DatastoreFile(path).getFileBaseName(); + + String search = "-"; + int index = path.indexOf(search); + + if (index > -1) { + path = path.substring(index + search.length()); + + index = path.lastIndexOf(search); + + if (index > -1) { + path = path.substring(0, index); + + if (path.startsWith("iqn.")) { + managedIqns.add(path); + } + } + } + } + } + } + + return managedIqns; + } + private Long restoreVolumeFromSecStorage(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName, String secStorageUrl, String secStorageDir, String backupName) throws Exception { @@ -1627,7 +1675,7 @@ public class VmwareStorageProcessor implements StorageProcessor { DataTO srcData = cmd.getSrcTO(); SnapshotObjectTO snapshot = (SnapshotObjectTO)srcData; DataTO destData = cmd.getDestTO(); - PrimaryDataStoreTO pool = (PrimaryDataStoreTO)destData.getDataStore(); + DataStoreTO pool = destData.getDataStore(); DataStoreTO imageStore = srcData.getDataStore(); 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 3323a15ba9d..ccb27ea400b 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 @@ -1072,7 +1072,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe throw new CloudRuntimeException("Unable to support this type of network broadcast domain: " + nic.getBroadcastUri()); } - protected VIF createVif(Connection conn, String vmName, VM vm, NicTO nic) throws XmlRpcException, XenAPIException { + protected VIF createVif(Connection conn, String vmName, VM vm, VirtualMachineTO vmSpec, NicTO nic) throws XmlRpcException, XenAPIException { assert(nic.getUuid() != null) : "Nic should have a uuid value"; if (s_logger.isDebugEnabled()) { @@ -1087,6 +1087,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe vifr.otherConfig = new HashMap(); vifr.otherConfig.put("nicira-iface-id", nic.getUuid()); vifr.otherConfig.put("nicira-vm-id", vm.getUuid(conn)); + // Provide XAPI with the cloudstack vm and nic uids. + vifr.otherConfig.put("cloudstack-nic-id", nic.getUuid()); + if (vmSpec != null) { + vifr.otherConfig.put("cloudstack-vm-id", vmSpec.getUuid()); + } vifr.network = getNetwork(conn, nic); @@ -1716,7 +1721,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } for (NicTO nic : vmSpec.getNics()) { - createVif(conn, vmName, vm, nic); + createVif(conn, vmName, vm, vmSpec, nic); } startVM(conn, host, vm, vmName); @@ -2422,7 +2427,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe nic.setDeviceId(Integer.parseInt(vifDeviceNum)); - correctVif = createVif(conn, vmName, router, nic); + correctVif = createVif(conn, vmName, router, null, nic); correctVif.plug(conn); // Add iptables rule for network usage networkUsage(conn, privateIpAddress, "addVif", "eth" + correctVif.getDevice(conn)); @@ -8391,7 +8396,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } String deviceId = getLowestAvailableVIFDeviceNum(conn, vm); nic.setDeviceId(Integer.parseInt(deviceId)); - vif = createVif(conn, vmName, vm, nic); + vif = createVif(conn, vmName, vm, null, nic); vif.plug(conn); return new PlugNicAnswer(cmd, true, "success"); } catch (Exception e) { @@ -8519,6 +8524,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } else { args += "0"; } + if (cmd.isPassive()) { + args += " -p "; + } } else { args += " -D"; args += " -r "; diff --git a/plugins/network-elements/juniper-contrail/pom.xml b/plugins/network-elements/juniper-contrail/pom.xml new file mode 100644 index 00000000000..22167fed199 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/pom.xml @@ -0,0 +1,136 @@ + + + 4.0.0 + cloud-plugin-network-contrail + Apache CloudStack Plugin - Network Juniper Contrail + + org.apache.cloudstack + cloudstack-plugins + 4.3.0-SNAPSHOT + ../../pom.xml + + + + juniper-contrail + http://juniper.github.io/contrail-maven/snapshots + + + + + + org.apache.cloudstack + cloud-api + ${project.version} + + + org.apache.cloudstack + cloud-server + ${project.version} + + + org.apache.cloudstack + cloud-plugin-hypervisor-xen + ${project.version} + test + + + org.apache.cloudstack + cloud-plugin-network-internallb + ${project.version} + test + + + org.apache.cloudstack + cloud-engine-orchestration + ${project.version} + test + + + org.apache.cloudstack + cloud-engine-api + ${project.version} + + + org.apache.cloudstack + cloud-engine-schema + ${project.version} + + + org.apache.cloudstack + cloud-framework-config + ${project.version} + + + org.apache.cloudstack + cloud-framework-events + ${project.version} + + + com.google.guava + guava + ${cs.guava.version} + + + net.juniper.contrail + juniper-contrail-api + 1.0-SNAPSHOT + + + mysql + mysql-connector-java + ${cs.mysql.version} + provided + + + org.apache.commons + commons-exec + 1.1 + + + org.mockito + mockito-all + 1.9.5 + + + + install + src + test + + + test/resources + + + + + org.apache.maven.plugins + maven-surefire-plugin + + always + -Xmx1024m + + **/NetworkProviderTest.java + **/PublicNetworkTest.java + + + + + + diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/api/command/CreateServiceInstanceCmd.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/api/command/CreateServiceInstanceCmd.java new file mode 100644 index 00000000000..62ab317ed30 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/api/command/CreateServiceInstanceCmd.java @@ -0,0 +1,182 @@ +// 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.network.contrail.api.command; + +import javax.inject.Inject; + +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.network.contrail.api.response.ServiceInstanceResponse; +import org.apache.cloudstack.network.contrail.management.ServiceManager; +import org.apache.cloudstack.network.contrail.management.ServiceVirtualMachine; +import org.apache.cloudstack.api.APICommand; +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.DomainResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.ZoneResponse; + +import com.cloud.dc.DataCenter; +import com.cloud.event.EventTypes; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.Network; +import com.cloud.offering.ServiceOffering; +import com.cloud.template.VirtualMachineTemplate; +import com.cloud.user.Account; + +@APICommand(name = "createServiceInstance", + description="Creates a system virtual-machine that implements network services", + responseObject=ServiceInstanceResponse.class) +public class CreateServiceInstanceCmd extends BaseAsyncCreateCmd { + private static final String s_name = "createserviceinstanceresponse"; + + /// API parameters + @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, + required = true, description = "Availability zone for the service instance") + private Long zoneId; + + //Owner information + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, + description="An optional account for the virtual machine. Must be used with domainId.") + private String accountName; + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="An optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.") + private Long domainId; + + @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, + description = "Project ID for the service instance") + private Long projectId; + + @Parameter(name = "leftnetworkid", type = CommandType.UUID, entityType = NetworkResponse.class, + required = true, description = "The left (inside) network for service instance") + private Long leftNetworkId; + + @Parameter(name = "rightnetworkid", type = CommandType.UUID, entityType = NetworkResponse.class, + required = true, description = "The right (outside) network ID for the service instance") + private Long rightNetworkId; + + @Parameter(name = ApiConstants.TEMPLATE_ID, type = CommandType.UUID, entityType = TemplateResponse.class, + required = true, description = "The template ID that specifies the image for the service appliance") + private Long templateId; + + @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.UUID, + entityType = ServiceOfferingResponse.class, required = true, + description = "The service offering ID that defines the resources consumed by the service appliance") + private Long serviceOfferingId; + + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING) + private String name; + + /// Implementation + @Inject ServiceManager _vrouterService; + @Override + public void create() throws ResourceAllocationException { + // Parameter validation + try { + DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId); + if (zone == null) { + throw new InvalidParameterValueException("Unable to find zone ID " + zoneId); + } + + Account owner = _accountService.getActiveAccountById(getEntityOwnerId()); + + VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, templateId); + if (template == null) { + throw new InvalidParameterValueException("Invalid template ID " + templateId); + } + + ServiceOffering serviceOffering = _entityMgr.findById(ServiceOffering.class, serviceOfferingId); + if (serviceOffering == null) { + throw new InvalidParameterValueException("Invalid service offering ID " + serviceOfferingId); + } + + Network left = _networkService.getNetwork(leftNetworkId); + if (left == null) { + throw new InvalidParameterValueException("Invalid ID for left network " + leftNetworkId); + } + + Network right = _networkService.getNetwork(rightNetworkId); + if (right == null) { + throw new InvalidParameterValueException("Invalid ID for right network " + rightNetworkId); + } + + ServiceVirtualMachine svm = _vrouterService.createServiceInstance(zone, owner, template, serviceOffering, + name, left, right); + if (svm == null) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Unable to create service instance"); + } + setEntityId(svm.getId()); + setEntityUuid(svm.getUuid()); + } catch (Exception ex) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); + } + } + + @Override + public String getEventType() { + return EventTypes.EVENT_VM_CREATE; + } + + @Override + public String getEventDescription() { + return "Create service instance"; + } + + @Override + public void execute() throws ResourceUnavailableException, + InsufficientCapacityException, ServerApiException, + ConcurrentOperationException, ResourceAllocationException, + NetworkRuleConflictException { + try { + _vrouterService.startServiceInstance(getEntityId()); + ServiceInstanceResponse response = _vrouterService.createServiceInstanceResponse(getEntityId()); + response.setObjectName("serviceinstance"); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } catch (Exception ex) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); + } + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); + if (accountId == null) { + return CallContext.current().getCallingAccount().getId(); + } + + return accountId; + } + +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/api/response/ServiceInstanceResponse.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/api/response/ServiceInstanceResponse.java new file mode 100644 index 00000000000..6b17351c1f9 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/api/response/ServiceInstanceResponse.java @@ -0,0 +1,83 @@ +// 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.network.contrail.api.response; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.response.ControlledEntityResponse; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +public class ServiceInstanceResponse extends BaseResponse implements + ControlledEntityResponse { + + @SerializedName(ApiConstants.ID) @Param(description="the ID of the virtual machine") + private String id; + + @SerializedName(ApiConstants.NAME) @Param(description="the name of the virtual machine") + private String name; + + @SerializedName("displayname") @Param(description="user generated name. The name of the virtual machine is returned if no displayname exists.") + private String displayName; + + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account associated with the virtual machine") + private String accountName; + + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the vm") + private String projectId; + + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the vm") + private String projectName; + + @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the ID of the domain in which the virtual machine exists") + private String domainId; + + @SerializedName(ApiConstants.DOMAIN) @Param(description="the name of the domain in which the virtual machine exists") + private String domainName; + + public void setId(String id) { + this.id = id; + } + + @Override + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + @Override + public void setProjectId(String projectId) { + this.projectId = projectId; + } + + @Override + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + @Override + public void setDomainName(String domainName) { + this.domainName = domainName; + } + +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailElement.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailElement.java new file mode 100644 index 00000000000..28680dfb8fd --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailElement.java @@ -0,0 +1,28 @@ +// 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.network.contrail.management; + +import com.cloud.utils.component.PluggableService; + +// Network Provider plugin +public interface ContrailElement extends PluggableService { + /** + * TODO: + * define APIs to configure the Network Virtualization service. + */ +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailElementImpl.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailElementImpl.java new file mode 100644 index 00000000000..dfbe7d34dbb --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailElementImpl.java @@ -0,0 +1,349 @@ +// 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.network.contrail.management; + +import java.io.IOException; +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.cloudstack.network.contrail.api.command.CreateServiceInstanceCmd; +import org.apache.cloudstack.network.contrail.model.InstanceIpModel; +import org.apache.cloudstack.network.contrail.model.VMInterfaceModel; +import org.apache.cloudstack.network.contrail.model.VirtualMachineModel; +import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; + +import com.cloud.deploy.DeployDestination; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceUnavailableException; +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.Networks.TrafficType; +import com.cloud.network.PhysicalNetworkServiceProvider; +import com.cloud.network.PublicIpAddress; +import com.cloud.network.element.DhcpServiceProvider; +import com.cloud.network.element.IpDeployer; +import com.cloud.network.element.NetworkACLServiceProvider; +import com.cloud.network.element.SourceNatServiceProvider; +import com.cloud.network.element.StaticNatServiceProvider; +import com.cloud.network.element.VpcProvider; +import com.cloud.network.rules.StaticNat; +import com.cloud.network.vpc.NetworkACLItem; +import com.cloud.network.vpc.PrivateGateway; +import com.cloud.network.vpc.StaticRouteProfile; +import com.cloud.network.vpc.Vpc; +import com.cloud.offering.NetworkOffering; +import com.cloud.utils.component.AdapterBase; +import com.cloud.vm.NicProfile; +import com.cloud.vm.NicVO; +import com.cloud.vm.ReservationContext; +import com.cloud.vm.VMInstanceVO; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineProfile; +import com.cloud.vm.dao.NicDao; +import com.cloud.network.IpAddress; + +@Component +@Local(value = {ContrailElement.class, StaticNatServiceProvider.class}) +public class ContrailElementImpl extends AdapterBase + implements ContrailElement, IpDeployer, StaticNatServiceProvider { + + private static final Map> _capabilities = InitCapabilities(); + + @Inject ContrailManager _manager; + @Inject NicDao _nicDao; + @Inject ServerDBSync _dbSync; + private static final Logger s_logger = + Logger.getLogger(ContrailElement.class); + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + s_logger.debug("configure"); + return true; + } + + // PluggableService + @Override + public List> getCommands() { + List> cmdList = new ArrayList>(); + cmdList.add(CreateServiceInstanceCmd.class); + return cmdList; + } + + // NetworkElement API + @Override + public Provider getProvider() { + return Provider.JuniperContrail; + } + + private static Map> InitCapabilities() { + Map> capabilities = new HashMap>(); + capabilities.put(Service.Connectivity, null); + capabilities.put(Service.Dhcp, new HashMap()); + capabilities.put(Service.StaticNat, null); + capabilities.put(Service.SourceNat, null); + + return capabilities; + } + + @Override + public Map> getCapabilities() { + return _capabilities; + } + + /** + * Network add/update. + */ + @Override + public boolean implement(Network network, NetworkOffering offering, + DeployDestination dest, ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { + s_logger.debug("NetworkElement implement: " + network.getName() + ", traffic type: " + network.getTrafficType()); + if (network.getTrafficType() == TrafficType.Guest) { + s_logger.debug("ignore network " + network.getName()); + return true; + } + VirtualNetworkModel vnModel = _manager.getDatabase().lookupVirtualNetwork(network.getUuid(), + _manager.getCanonicalName(network), network.getTrafficType()); + + if (vnModel == null) { + vnModel = new VirtualNetworkModel(network, network.getUuid(), + _manager.getCanonicalName(network), network.getTrafficType()); + vnModel.setProperties(_manager.getModelController(), network); + } + try { + if (!vnModel.verify(_manager.getModelController())) { + vnModel.update(_manager.getModelController()); + } + _manager.getDatabase().getVirtualNetworks().add(vnModel); + } catch (Exception ex) { + s_logger.warn("virtual-network update: ", ex); + } + return true; + } + + @Override + public boolean prepare(Network network, NicProfile nicProfile, + VirtualMachineProfile vm, + DeployDestination dest, ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { + + s_logger.debug("NetworkElement prepare: " + network.getName() + ", traffic type: " + network.getTrafficType()); + + if (network.getTrafficType() == TrafficType.Guest) { + s_logger.debug("ignore network " + network.getName()); + return true; + } + + s_logger.debug("network: " + network.getId()); + + VirtualNetworkModel vnModel = _manager.getDatabase().lookupVirtualNetwork(network.getUuid(), + _manager.getCanonicalName(network), network.getTrafficType()); + + if (vnModel == null) { + // There is no notification after a physical network is associated with the VRouter NetworkOffering + // this may be the first time we see this network. + return false; + } + + VirtualMachineModel vmModel = _manager.getDatabase().lookupVirtualMachine(vm.getUuid()); + if (vmModel == null) { + VMInstanceVO vmVo = (VMInstanceVO) vm.getVirtualMachine(); + vmModel = new VirtualMachineModel(vmVo, vm.getUuid()); + vmModel.setProperties(_manager.getModelController(), vmVo); + } + + NicVO nic = _nicDao.findById(nicProfile.getId()); + assert nic != null; + + VMInterfaceModel vmiModel = vmModel.getVMInterface(nic.getUuid()); + if (vmiModel == null) { + vmiModel = new VMInterfaceModel(nic.getUuid()); + vmiModel.addToVirtualMachine(vmModel); + vmiModel.addToVirtualNetwork(vnModel); + } + + try { + vmiModel.build(_manager.getModelController(), (VMInstanceVO) vm.getVirtualMachine(), nic); + } catch (IOException ex) { + s_logger.warn("vm interface set", ex); + return false; + } + + InstanceIpModel ipModel = vmiModel.getInstanceIp(); + if (ipModel == null) { + ipModel = new InstanceIpModel(vm.getInstanceName(), nic.getDeviceId()); + ipModel.addToVMInterface(vmiModel); + } + ipModel.setAddress(nicProfile.getIp4Address()); + + try { + vmModel.update(_manager.getModelController()); + } catch (Exception ex) { + s_logger.warn("virtual-machine-update", ex); + return false; + } + _manager.getDatabase().getVirtualMachines().add(vmModel); + + return true; + } + + @Override + public boolean release(Network network, NicProfile nicProfile, + VirtualMachineProfile vm, + ReservationContext context) throws ConcurrentOperationException, + ResourceUnavailableException { + if (network.getTrafficType() == TrafficType.Guest) { + return true; + } else if (!_manager.isManagedPhysicalNetwork(network)) { + s_logger.debug("release ignore network " + network.getId()); + return true; + } + + NicVO nic = _nicDao.findById(nicProfile.getId()); + assert nic != null; + + VirtualMachineModel vmModel = _manager.getDatabase().lookupVirtualMachine(vm.getUuid()); + if (vmModel == null) { + s_logger.debug("vm " + vm.getInstanceName() + " not in local database"); + return true; + } + VMInterfaceModel vmiModel = vmModel.getVMInterface(nic.getUuid()); + if (vmiModel != null) { + try { + vmiModel.destroy(_manager.getModelController()); + } catch (IOException ex) { + s_logger.warn("virtual-machine-interface delete", ex); + } + vmModel.removeSuccessor(vmiModel); + } + + if (!vmModel.hasDescendents()) { + _manager.getDatabase().getVirtualMachines().remove(vmModel); + try { + vmModel.delete(_manager.getModelController()); + } catch (IOException e) { + return false; + } + } + + return true; + } + + /** + * Network disable + */ + @Override + public boolean shutdown(Network network, ReservationContext context, + boolean cleanup) throws ConcurrentOperationException, + ResourceUnavailableException { + s_logger.debug("NetworkElement shutdown"); + return true; + } + + /** + * Network delete + */ + @Override + public boolean destroy(Network network, ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException { + s_logger.debug("NetworkElement destroy"); + return true; + } + + @Override + public boolean isReady(PhysicalNetworkServiceProvider provider) { + return true; + } + + @Override + public boolean shutdownProviderInstances( + PhysicalNetworkServiceProvider provider, ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException { + s_logger.debug("NetworkElement shutdown ProviderInstances"); + return true; + } + + @Override + public boolean canEnableIndividualServices() { + return true; + } + + @Override + public boolean verifyServicesCombination(Set services) { + // TODO Auto-generated method stub + s_logger.debug("NetworkElement verifyServices"); + s_logger.debug("Services: " + services); + return true; + } + + + @Override + public IpDeployer getIpDeployer(Network network) { + return this; + } + + @Override + public boolean applyIps(Network network, + List ipAddress, Set services) + throws ResourceUnavailableException { + + for (PublicIpAddress ip: ipAddress) { + if (ip.isSourceNat()) { + continue; + } + if (isFloatingIpCreate(ip)) { + if (_manager.createFloatingIp(ip)) { + s_logger.debug("Successfully created floating ip: " + ip.getAddress().addr()); + } + } else { + if (_manager.deleteFloatingIp(ip)) { + s_logger.debug("Successfully deleted floating ip: " + ip.getAddress().addr()); + } + } + } + return true; + } + + @Override + public boolean applyStaticNats(Network config, + List rules) + throws ResourceUnavailableException { + return true; + } + + private boolean isFloatingIpCreate(PublicIpAddress ip) { + if (ip.getState() == IpAddress.State.Allocated && ip.getAssociatedWithVmId() != null && !ip.isSourceNat()) { + return true; + } + return false; + } +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailGuru.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailGuru.java new file mode 100644 index 00000000000..ca53f416f89 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailGuru.java @@ -0,0 +1,333 @@ +// 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.network.contrail.management; + + +import java.io.IOException; + +import javax.inject.Inject; + +import net.juniper.contrail.api.types.MacAddressesType; +import net.juniper.contrail.api.types.VirtualMachineInterface; + +import org.apache.cloudstack.network.contrail.model.InstanceIpModel; +import org.apache.cloudstack.network.contrail.model.VMInterfaceModel; +import org.apache.cloudstack.network.contrail.model.VirtualMachineModel; +import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; + +import com.cloud.deploy.DeployDestination; +import com.cloud.deploy.DeploymentPlan; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientAddressCapacityException; +import com.cloud.exception.InsufficientVirtualNetworkCapcityException; +import com.cloud.network.Network; +import com.cloud.network.Network.State; +import com.cloud.network.NetworkProfile; +import com.cloud.network.Networks.AddressFormat; +import com.cloud.network.Networks.BroadcastDomainType; +import com.cloud.network.Networks.Mode; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.network.guru.NetworkGuru; +import com.cloud.offering.NetworkOffering; +import com.cloud.user.Account; +import com.cloud.utils.component.AdapterBase; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.net.NetUtils; +import com.cloud.vm.Nic.ReservationStrategy; +import com.cloud.vm.NicProfile; +import com.cloud.vm.ReservationContext; +import com.cloud.vm.VMInstanceVO; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineProfile; +import com.cloud.vm.dao.NicDao; +import com.cloud.vm.NicVO; + +@Component +public class ContrailGuru extends AdapterBase implements NetworkGuru { + @Inject NetworkDao _networkDao; + @Inject ContrailManager _manager; + @Inject NicDao _nicDao; + + private static final Logger s_logger = Logger.getLogger(ContrailGuru.class); + private static final TrafficType[] _trafficTypes = {TrafficType.Guest}; + + private boolean canHandle(NetworkOffering offering) { + return (offering.getName().equals(ContrailManager.offeringName)); + } + + @Override + public String getName() { + return "ContrailGuru"; + } + + @Override + public Network design(NetworkOffering offering, DeploymentPlan plan, + Network userSpecified, Account owner) { + if (!canHandle(offering)) { + return null; + } + NetworkVO network = new NetworkVO(offering.getTrafficType(), Mode.Dhcp, BroadcastDomainType.Lswitch, + offering.getId(), State.Allocated, plan.getDataCenterId(), plan.getPhysicalNetworkId()); + if (userSpecified.getCidr() != null) { + network.setCidr(userSpecified.getCidr()); + network.setGateway(userSpecified.getGateway()); + } + s_logger.debug("Allocated network " + userSpecified.getName() + + (network.getCidr() == null ? "" : " subnet: " + network.getCidr())); + return network; + } + + @Override + public Network implement(Network network, NetworkOffering offering, + DeployDestination destination, ReservationContext context) + throws InsufficientVirtualNetworkCapcityException { + s_logger.debug("Implement network: " + network.getName() + ", traffic type: " + network.getTrafficType()); + + VirtualNetworkModel vnModel = _manager.getDatabase().lookupVirtualNetwork( + network.getUuid(), _manager.getCanonicalName(network), network.getTrafficType()); + if (vnModel == null) { + vnModel = new VirtualNetworkModel(network, network.getUuid(), + _manager.getCanonicalName(network), network.getTrafficType()); + vnModel.setProperties(_manager.getModelController(), network); + } + + try { + if (!vnModel.verify(_manager.getModelController())) { + vnModel.update(_manager.getModelController()); + } + } catch (Exception ex) { + s_logger.warn("virtual-network update: ", ex); + return network; + } + _manager.getDatabase().getVirtualNetworks().add(vnModel); + return network; + } + + /** + * Allocate the NicProfile object. + * At this point the UUID of the nic is not yet known. We defer allocating the VMI and instance-ip objects + * until the reserve API is called because of this reason. + */ + @Override + public NicProfile allocate(Network network, NicProfile profile, + VirtualMachineProfile vm) + throws InsufficientVirtualNetworkCapcityException, + InsufficientAddressCapacityException, ConcurrentOperationException { + s_logger.debug("allocate NicProfile on " + network.getName()); + + if (profile != null && profile.getRequestedIpv4() != null) { + throw new CloudRuntimeException("Does not support custom ip allocation at this time: " + profile); + } + if (profile == null) { + profile = new NicProfile(ReservationStrategy.Create, null, null, null, null); + } + + profile.setStrategy(ReservationStrategy.Start); + + return profile; + } + + /** + * Allocate the ip address (and mac) for the specified VM device. + */ + @Override + public void reserve(NicProfile nic, Network network, + VirtualMachineProfile vm, + DeployDestination dest, ReservationContext context) + throws InsufficientVirtualNetworkCapcityException, + InsufficientAddressCapacityException, ConcurrentOperationException { + s_logger.debug("reserve NicProfile on network id: " + network.getId() + + " " + network.getName()); + s_logger.debug("deviceId: " + nic.getDeviceId()); + + NicVO nicVO = _nicDao.findById(nic.getId()); + assert nicVO != null; + + VirtualNetworkModel vnModel = _manager.getDatabase().lookupVirtualNetwork( + network.getUuid(), _manager.getCanonicalName(network), network.getTrafficType()); + /* Network must have been implemented */ + assert vnModel != null; + + VirtualMachineModel vmModel = _manager.getDatabase().lookupVirtualMachine(vm.getUuid()); + if (vmModel == null) { + VMInstanceVO vmVo = (VMInstanceVO) vm.getVirtualMachine(); + vmModel = new VirtualMachineModel(vmVo, vm.getUuid()); + vmModel.setProperties(_manager.getModelController(), vmVo); + } + + VMInterfaceModel vmiModel = vmModel.getVMInterface(nicVO.getUuid()); + if (vmiModel == null) { + vmiModel = new VMInterfaceModel(nicVO.getUuid()); + vmiModel.addToVirtualMachine(vmModel); + vmiModel.addToVirtualNetwork(vnModel); + } + try { + vmiModel.build(_manager.getModelController(), (VMInstanceVO) vm.getVirtualMachine(), nicVO); + vmiModel.setActive(); + } catch (IOException ex) { + s_logger.error("virtual-machine-interface set", ex); + return; + } + + InstanceIpModel ipModel = vmiModel.getInstanceIp(); + if (ipModel == null) { + ipModel = new InstanceIpModel(vm.getInstanceName(), nic.getDeviceId()); + ipModel.addToVMInterface(vmiModel); + } else { + s_logger.debug("Reuse existing instance-ip object on " + ipModel.getName()); + } + if (nic.getIp4Address() != null) { + s_logger.debug("Nic using existing IP address " + nic.getIp4Address()); + ipModel.setAddress(nic.getIp4Address()); + } + + try { + vmModel.update(_manager.getModelController()); + } catch (Exception ex) { + s_logger.warn("virtual-machine update", ex); + return; + } + + _manager.getDatabase().getVirtualMachines().add(vmModel); + + VirtualMachineInterface vmi = vmiModel.getVMInterface(); + // allocate mac address + if (nic.getMacAddress() == null) { + MacAddressesType macs = vmi.getMacAddresses(); + if (macs == null) { + s_logger.debug("no mac address is allocated for Nic " + nicVO.getUuid()); + } else { + s_logger.info("VMI " + _manager.getVifNameByVmUuid(vm.getUuid(), nicVO.getDeviceId()) + " got mac address: " + + macs.getMacAddress().get(0)); + nic.setMacAddress(macs.getMacAddress().get(0)); + } + } + + if (nic.getIp4Address() == null) { + s_logger.debug("Allocated IP address " + ipModel.getAddress()); + nic.setIp4Address(ipModel.getAddress()); + nic.setNetmask(NetUtils.cidr2Netmask(network.getCidr())); + nic.setGateway(network.getGateway()); + nic.setFormat(AddressFormat.Ip4); + } + } + + /** + * When a VM is stopped this API is called to release transient resources. + */ + @Override + public boolean release(NicProfile nic, + VirtualMachineProfile vm, + String reservationId) { + + s_logger.debug("release NicProfile " + nic.getId()); + + return true; + } + + /** + * Release permanent resources of a Nic (VMI and addresses). + */ + @Override + public void deallocate(Network network, NicProfile nic, + VirtualMachineProfile vm) { + s_logger.debug("deallocate NicProfile " + nic.getId() + " on " + network.getName()); + NicVO nicVO = _nicDao.findById(nic.getId()); + assert nicVO != null; + + VirtualMachineModel vmModel = _manager.getDatabase().lookupVirtualMachine(vm.getUuid()); + if (vmModel == null) { + return; + } + VMInterfaceModel vmiModel = vmModel.getVMInterface(nicVO.getUuid()); + if (vmiModel == null) { + return; + } + try { + vmiModel.destroy(_manager.getModelController()); + } catch (IOException ex) { + return; + } + vmModel.removeSuccessor(vmiModel); + + if (!vmModel.hasDescendents()) { + _manager.getDatabase().getVirtualMachines().remove(vmModel); + try { + vmModel.delete(_manager.getModelController()); + } catch (IOException ex) { + s_logger.warn("virtual-machine delete", ex); + return; + } + } + + } + + @Override + public void updateNicProfile(NicProfile profile, Network network) { + // TODO Auto-generated method stub + s_logger.debug("update NicProfile " + profile.getId() + " on " + network.getName()); + } + + @Override + public void shutdown(NetworkProfile network, NetworkOffering offering) { + s_logger.debug("NetworkGuru shutdown"); + VirtualNetworkModel vnModel = _manager.getDatabase().lookupVirtualNetwork(network.getUuid(), + _manager.getCanonicalName(network), network.getTrafficType()); + if (vnModel == null) { + return; + } + try { + vnModel.delete(_manager.getModelController()); + } catch (IOException e) { + s_logger.warn("virtual-network delete", e); + } + } + + @Override + public boolean trash(Network network, NetworkOffering offering) { + // TODO Auto-generated method stub + s_logger.debug("NetworkGuru trash"); + return true; + } + + @Override + public void updateNetworkProfile(NetworkProfile networkProfile) { + // TODO Auto-generated method stub + s_logger.debug("NetworkGuru updateNetworkProfile"); + } + + @Override + public TrafficType[] getSupportedTrafficType() { + return _trafficTypes; + } + + @Override + public boolean isMyTrafficType(TrafficType type) { + for (TrafficType t : _trafficTypes) { + if (t == type) { + return true; + } + } + return false; + } + +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManager.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManager.java new file mode 100644 index 00000000000..b96b00c9e96 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManager.java @@ -0,0 +1,93 @@ +// 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.network.contrail.management; + +import java.util.List; +import java.io.IOException; + +import org.apache.cloudstack.network.contrail.model.ModelController; +import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; + +import net.juniper.contrail.api.ApiConnector; +import net.juniper.contrail.api.types.FloatingIp; +import net.juniper.contrail.api.types.VirtualNetwork; + +import com.cloud.network.Network; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.PublicIpAddress; +import com.cloud.offering.NetworkOffering; +import com.cloud.network.dao.IPAddressVO; +import com.cloud.network.dao.PhysicalNetworkVO; +import com.cloud.network.dao.NetworkVO; +import com.cloud.domain.DomainVO; +import com.cloud.projects.ProjectVO; + +public interface ContrailManager { + public static final String offeringName = "Juniper Contrail offering"; + public static final String offeringDisplayText = "Juniper Contrail network offering"; + public static final int DB_SYNC_INTERVAL_DEFAULT = 600000; + public static final String VNC_ROOT_DOMAIN = "default-domain"; + public static final String VNC_DEFAULT_PROJECT = "default-project"; + public static final String managementNetworkName = "ip-fabric"; + + public NetworkOffering getOffering(); + public void syncNetworkDB(short syncMode) throws IOException; + + public boolean isManagedPhysicalNetwork(Network network); + + /** + * Lookup the virtual network that implements the CloudStack network object. + * @param net_id internal identifier of the NetworkVO object. + * @return the uuid of the virtual network that corresponds to the + * specified CloudStack network. + */ + public String findVirtualNetworkId(Network net) throws IOException; + public void findInfrastructureNetworks(PhysicalNetworkVO phys, List dbList); + public String getPhysicalNetworkName(PhysicalNetworkVO phys_net); + public String getCanonicalName(Network net); + public String getDomainCanonicalName(DomainVO domain); + public String getProjectCanonicalName(ProjectVO project); + public String getFQN(Network net); + public String getDomainName(long domainId); + public String getProjectName(long accountId); + public String getDefaultPublicNetworkFQN(); + public String getProjectId(long domainId, long accountId) throws IOException; + public net.juniper.contrail.api.types.Project getVncProject(long domainId, long accountId) throws IOException; + public boolean isSystemRootDomain(net.juniper.contrail.api.types.Domain vnc); + public boolean isSystemRootDomain(DomainVO domain); + public boolean isSystemDefaultProject(net.juniper.contrail.api.types.Project project); + public boolean isSystemDefaultProject(ProjectVO project); + public boolean isSystemDefaultNetwork(VirtualNetwork vnet); + public boolean isSystemDefaultNetwork(NetworkVO dbNet); + public String getVifNameByVmName(String vm_name, Integer device_id); + public String getVifNameByVmUuid(String vm_uuid, Integer device_id); + + public ApiConnector getApiConnector(); + public ModelDatabase getDatabase(); + public ModelController getModelController(); + public List findJuniperManagedNetworks(List types); + public List findJuniperManagedPublicIps(); + public VirtualNetwork findDefaultVirtualNetwork(TrafficType trafficType) + throws IOException; + public List getFloatingIps(); + public VirtualNetworkModel lookupPublicNetworkModel(); + public void createPublicNetworks(); + public boolean createFloatingIp(PublicIpAddress ip); + public boolean deleteFloatingIp(PublicIpAddress ip); +} + diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManagerImpl.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManagerImpl.java new file mode 100644 index 00000000000..ae9bba9b7e5 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManagerImpl.java @@ -0,0 +1,769 @@ +// 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.network.contrail.management; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Timer; +import java.util.TimerTask; + +import javax.inject.Inject; +import javax.naming.ConfigurationException; + +import net.juniper.contrail.api.ApiConnector; +import net.juniper.contrail.api.ApiConnectorFactory; +import net.juniper.contrail.api.ApiPropertyBase; +import net.juniper.contrail.api.ObjectReference; +import net.juniper.contrail.api.types.FloatingIp; +import net.juniper.contrail.api.types.FloatingIpPool; +import net.juniper.contrail.api.types.VirtualNetwork; + +import org.apache.cloudstack.network.contrail.model.FloatingIpModel; +import org.apache.cloudstack.network.contrail.model.FloatingIpPoolModel; +import org.apache.cloudstack.network.contrail.model.ModelController; +import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; + +import com.cloud.configuration.ConfigurationManager; +import com.cloud.configuration.ConfigurationService; +import com.cloud.dc.DataCenter; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.dc.dao.VlanDao; +import com.cloud.domain.Domain; +import com.cloud.domain.DomainVO; +import com.cloud.domain.dao.DomainDao; +import com.cloud.exception.InternalErrorException; +import com.cloud.projects.ProjectVO; +import com.cloud.user.dao.AccountDao; +import com.cloud.user.Account; +import com.cloud.network.Network; +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.PublicIpAddress; +import com.cloud.network.dao.IPAddressDao; +import com.cloud.network.dao.IPAddressVO; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.network.dao.PhysicalNetworkDao; +import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; +import com.cloud.network.dao.PhysicalNetworkVO; +import com.cloud.offering.NetworkOffering.State; +import com.cloud.offering.NetworkOffering; +import com.cloud.offering.NetworkOffering.Availability; +import com.cloud.offerings.NetworkOfferingVO; +import com.cloud.offerings.dao.NetworkOfferingDao; +import com.cloud.projects.dao.ProjectDao; +import com.cloud.utils.component.ComponentLifecycle; +import com.cloud.utils.component.ManagerBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; +import com.google.common.collect.ImmutableList; + +import java.util.Properties; + +import com.cloud.utils.PropertiesUtil; +import com.cloud.vm.VMInstanceVO; +import com.cloud.vm.dao.NicDao; +import com.cloud.vm.dao.UserVmDao; +import com.cloud.vm.dao.VMInstanceDao; + +import java.io.File; +import java.io.FileInputStream; + +@Component +public class ContrailManagerImpl extends ManagerBase implements ContrailManager { + @Inject public ConfigurationService _configService; + @Inject NetworkOfferingDao _networkOfferingDao; + + @Inject DomainDao _domainDao; + @Inject NetworkDao _networksDao; + @Inject VMInstanceDao _vmInstanceDao; + @Inject ProjectDao _projectDao; + @Inject AccountDao _accountDao; + @Inject DataCenterDao _dcDao; + @Inject PhysicalNetworkDao _physicalNetworkDao; + @Inject PhysicalNetworkServiceProviderDao _physProviderDao; + @Inject NicDao _nicDao; + @Inject ServerDBSync _dbSync; + @Inject ServerEventHandler _eventHandler; + @Inject IPAddressDao _ipAddressDao; + @Inject VlanDao _vlanDao; + @Inject UserVmDao _vmDao; + + private static final Logger s_logger = Logger.getLogger(ContrailManager.class); + + private ApiConnector _api; + + private NetworkOffering _offering; + private Timer _dbSyncTimer; + private int _dbSyncInterval = DB_SYNC_INTERVAL_DEFAULT; + private final String configuration = "contrail.properties"; + private ModelDatabase _database; + private ModelController _controller; + + ContrailManagerImpl() { + setRunLevel(ComponentLifecycle.RUN_LEVEL_COMPONENT); + _database = new ModelDatabase(); + } + + @Override + public boolean start() { + /* Start background task */ + _dbSyncTimer = new Timer("DBSyncTimer"); + try { + _dbSyncTimer.schedule(new DBSyncTask(), 0, _dbSyncInterval); + } catch (Exception ex) { + s_logger.debug("Unable to start DB Sync timer " + ex.getMessage()); + s_logger.debug("timer start", ex); + } + return true; + } + @Override + public boolean stop() { + _dbSyncTimer.cancel(); + return true; + } + + public ModelDatabase getDatabase() { + return _database; + } + + private NetworkOffering LocateOffering() { + List offerList = _configService.listNetworkOfferings(TrafficType.Guest, false); + for (NetworkOffering offer: offerList) { + if (offer.getName().equals(offeringName)) { + if (offer.getState() != State.Enabled) { + return EnableNetworkOffering(offer.getId()); + } + return offer; + } + } + Map> serviceProviderMap = new HashMap>(); + // Map> serviceCapabilityMap = new HashMap>(); + Set providerSet = new HashSet(); + providerSet.add(Provider.JuniperContrail); + final Service[] services = { + Service.Connectivity, + Service.Dhcp, + Service.NetworkACL, + Service.StaticNat, + Service.SourceNat + }; + for (Service svc: services) { + serviceProviderMap.put(svc, providerSet); + } + ConfigurationManager configMgr = (ConfigurationManager) _configService; + NetworkOfferingVO voffer = configMgr.createNetworkOffering(offeringName, offeringDisplayText, + TrafficType.Guest, null, false, Availability.Optional, null, serviceProviderMap, true, + Network.GuestType.Isolated, false, null, false, null, false, true, null, true, null, false); + + voffer.setState(State.Enabled); + long id = voffer.getId(); + _networkOfferingDao.update(id, voffer); + return _networkOfferingDao.findById(id); + } + + private NetworkOffering EnableNetworkOffering(long id) { + NetworkOfferingVO offering = _networkOfferingDao.createForUpdate(id); + offering.setState(State.Enabled); + _networkOfferingDao.update(id, offering); + return _networkOfferingDao.findById(id); + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + + File configFile = PropertiesUtil.findConfigFile(configuration); + final Properties configProps = new Properties(); + try { + configProps.load(new FileInputStream(configFile)); + String value = configProps.getProperty("management.db_sync_interval"); + if (value != null) { + _dbSyncInterval = Integer.valueOf(value); + } + + String hostname = configProps.getProperty("api.hostname"); + String portStr = configProps.getProperty("api.port"); + int port = 0; + if (portStr != null && portStr.length() > 0) { + port = Integer.parseInt(portStr); + } + _api = ApiConnectorFactory.build(hostname, port); + } catch (IOException ex) { + s_logger.warn("Unable to read " + configuration, ex); + throw new ConfigurationException(); + } + + _controller = new ModelController(this, _api, _vmDao, _networksDao, _nicDao, _vlanDao, _ipAddressDao); + + _offering = LocateOffering(); + + _eventHandler.subscribe(); + + initializeDefaultVirtualNetworkModels(); + + return true; + } + + @Override + public NetworkOffering getOffering() { + return _offering; + } + + @Override + public String getPhysicalNetworkName(PhysicalNetworkVO phys_net) { + String physname = phys_net.getName(); + physname = physname.replaceAll("\\s", ""); + physname.replace("_", ""); + return physname; + } + + @Override + public String getDomainCanonicalName(DomainVO domain) { + if (domain.getId() == Domain.ROOT_DOMAIN) { + return VNC_ROOT_DOMAIN; + } + return domain.getName(); + } + + @Override + public String getProjectCanonicalName(ProjectVO project) { + return project.getName(); + } + + @Override + public String getCanonicalName(Network net) { + String netname; + if (net.getTrafficType() == TrafficType.Guest) { + return net.getName(); + } else if (net.getTrafficType() == TrafficType.Management || net.getTrafficType() == TrafficType.Storage) { + return managementNetworkName; + } else if (net.getTrafficType() == TrafficType.Control) { + return "__link_local__"; + } else { + DataCenter zone = _dcDao.findById(net.getDataCenterId()); + String zonename = zone.getName(); + zonename = zonename.replaceAll("\\s", ""); + zonename = zonename.replace("-", "_"); + netname = "__" + zonename + "_" + net.getTrafficType().toString() + "__"; + } + return netname; + } + + @Override + public String getDomainName(long domainId) { + if (domainId != Domain.ROOT_DOMAIN) { + DomainVO domain = _domainDao.findById(domainId); + return domain.getName(); + } + return VNC_ROOT_DOMAIN; + } + + @Override + public String getProjectName(long accountId) { + Account account = _accountDao.findById(accountId); + if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { + ProjectVO project = _projectDao.findByProjectAccountId(account.getId()); + if (project != null) { + return project.getName(); + } + } + return VNC_DEFAULT_PROJECT; + } + + @Override + public String getDefaultPublicNetworkFQN() { + String name = VNC_ROOT_DOMAIN + ":" + VNC_DEFAULT_PROJECT + ":" + "__default_Public__"; + return name; + } + + private ProjectVO getProject(long accountId) { + Account account = _accountDao.findById(accountId); + if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { + return _projectDao.findByProjectAccountId(account.getId()); + } + return null; + } + + @Override + public String getProjectId(long domainId, long accountId) throws IOException { + ProjectVO project = getProject(accountId); + if (project != null) { + return project.getUuid(); + } + DomainVO domain = _domainDao.findById(domainId); + if (domain.getId() != Domain.ROOT_DOMAIN) { + net.juniper.contrail.api.types.Domain vncDomain = (net.juniper.contrail.api.types.Domain) + _api.findById(net.juniper.contrail.api.types.Domain.class, domain.getUuid()); + return _api.findByName(net.juniper.contrail.api.types.Project.class, vncDomain, VNC_DEFAULT_PROJECT); + } + return null; + } + + @Override + public net.juniper.contrail.api.types.Project getVncProject(long domainId, long accountId) throws IOException { + String projectId = getProjectId(domainId, accountId); + if (projectId == null) { + return null; + } + return (net.juniper.contrail.api.types.Project) + _api.findById(net.juniper.contrail.api.types.Project.class, projectId); + } + + @Override + public String getFQN(Network net) { + // domain, project, name + String fqname = getDomainName(net.getDomainId()); + fqname += ":" + getProjectName(net.getAccountId()) + ":"; + return fqname + getCanonicalName(net); + } + + public void findInfrastructureNetworks(PhysicalNetworkVO phys, List dbList) { + final TrafficType[] ttypes = { + TrafficType.Control, // maps to __link_local__ + TrafficType.Management, // maps to ip-fabric + TrafficType.Public, + TrafficType.Storage // maps to ip-fabric + }; + + for (int i = 0; i < ttypes.length; i++) { + List phys_nets; + phys_nets = _networksDao.listByZoneAndTrafficType(phys.getDataCenterId(), ttypes[i]); + dbList.addAll(phys_nets); + } + + } + + public void syncNetworkDB(short syncMode) throws IOException { + if (_dbSync.syncAll(syncMode) == ServerDBSync.SYNC_STATE_OUT_OF_SYNC) { + if (syncMode == DBSyncGeneric.SYNC_MODE_CHECK) { + s_logger.info("# Cloudstack DB & VNC are out of sync #"); + } else { + s_logger.info("# Cloudstack DB & VNC were out of sync, performed re-sync operation #"); + } + } else { + s_logger.info("# Cloudstack DB & VNC are in sync #"); + } + } + + public class DBSyncTask extends TimerTask { + private short _syncMode = DBSyncGeneric.SYNC_MODE_UPDATE; + @Override + public void run() { + try { + s_logger.debug("DB Sync task is running"); + syncNetworkDB(_syncMode); + // Change to check mode + _syncMode = DBSyncGeneric.SYNC_MODE_CHECK; + } catch (Exception ex) { + s_logger.debug(ex); + s_logger.info("Unable to sync network db"); + } + } + } + + + @Override + public boolean isManagedPhysicalNetwork(Network network) { + List net_list = _physicalNetworkDao.listByZone(network.getDataCenterId()); + for (PhysicalNetworkVO phys : net_list) { + if(_physProviderDao.findByServiceProvider(phys.getId(), Network.Provider.JuniperContrail.getName()) != null) { + return true; + } + } + return false; + } + + public String findVirtualNetworkId(Network net) throws IOException { + if (net.getTrafficType() == TrafficType.Guest) { + return net.getUuid(); + } + String netname = getDomainName(net.getDomainId()) + ":" + getProjectName(net.getAccountId()) + ":"; + + if (net.getTrafficType() == TrafficType.Control) { + netname += "__link_local__"; + } else if (net.getTrafficType() == TrafficType.Management || net.getTrafficType() == TrafficType.Storage) { + netname += managementNetworkName; + } else { + netname = getFQN(net); + } + List fqn = ImmutableList.copyOf(StringUtils.split(netname, ':')); + return _api.findByName(VirtualNetwork.class, fqn); + } + + @Override + public VirtualNetwork findDefaultVirtualNetwork(TrafficType trafficType) throws IOException { + if (trafficType == TrafficType.Guest || + trafficType == TrafficType.Public) { + return null; + } + String netname = VNC_ROOT_DOMAIN + ":" + VNC_DEFAULT_PROJECT + ":"; + if (trafficType == TrafficType.Control) { + netname += "__link_local__"; + } else if (trafficType == TrafficType.Management || trafficType == TrafficType.Storage) { + netname += managementNetworkName; + } + return (VirtualNetwork)_api.findByFQN(VirtualNetwork.class, netname); + } + + /* + * Returns list of networks managed by Juniper VRouter filtered by traffic types + */ + @Override + public List findJuniperManagedNetworks(List types) { + + SearchBuilder searchBuilder = _networksDao.createSearchBuilder(); + searchBuilder.and("trafficType", searchBuilder.entity().getTrafficType(), Op.IN); + searchBuilder.and("networkOfferingId", searchBuilder.entity().getNetworkOfferingId(), Op.EQ); + + SearchCriteria sc = searchBuilder.create(); + sc.setParameters("networkOfferingId", getOffering().getId()); + + if (types == null || types.isEmpty()) { + types = new ArrayList(); + types.add(TrafficType.Control); + types.add(TrafficType.Management); + types.add(TrafficType.Public); + types.add(TrafficType.Storage); + types.add(TrafficType.Guest); + } + sc.setParameters("trafficType", types.toArray()); + + List dbNets = _networksDao.search(sc, null); + if (dbNets == null) { + s_logger.debug("no juniper managed networks for the given traffic types: " + types.toString()); + dbNets = new ArrayList(); + } + + List phys_list = _physicalNetworkDao.listAll(); + final String provider = Network.Provider.JuniperContrail.getName(); + for (Iterator iter = phys_list.iterator(); iter.hasNext(); ) { + PhysicalNetworkVO phys = iter.next(); + if (_physProviderDao.findByServiceProvider(phys.getId(), provider) != null) { + List infraNets = new ArrayList(); + findInfrastructureNetworks(phys, infraNets); + for (NetworkVO net:infraNets) { + if (types == null || types.isEmpty()) { + dbNets.add(net); + continue; + } + for(TrafficType type:types) { + if (net.getTrafficType() == type) { + dbNets.add(net); + break; + } + } + } + } + } + return dbNets; + } + + /* + * Returns list of public ip addresses managed by Juniper VRouter + */ + @Override + public List findJuniperManagedPublicIps() { + + List dbNets = findJuniperManagedNetworks(null); + + if (dbNets == null || dbNets.isEmpty()) { + s_logger.debug("Juniper managed networks is empty"); + return null; + } + + SearchBuilder searchBuilder = _ipAddressDao.createSearchBuilder(); + searchBuilder.and("sourceNat", searchBuilder.entity().isSourceNat(), Op.EQ); + searchBuilder.and("network", searchBuilder.entity().getAssociatedWithNetworkId(), Op.IN); + searchBuilder.and("oneToOneNat", searchBuilder.entity().isOneToOneNat(), Op.EQ); + searchBuilder.and("associatedWithVmId", searchBuilder.entity().getAssociatedWithVmId(), Op.NNULL); + + List netIds = new ArrayList(); + for (NetworkVO net:dbNets) { + netIds.add(net.getId()); + } + + SearchCriteria sc = searchBuilder.create(); + sc.setParameters("oneToOneNat", true); + sc.setParameters("sourceNat", false); + sc.setParameters("network", netIds.toArray()); + + List publicIps = _ipAddressDao.search(sc, null); + if (publicIps == null) { + s_logger.debug("no public ips"); + return null; + } + + return publicIps; + } + + private void initializeDefaultVirtualNetworkModels() { + List types = new ArrayList(); + types.add(TrafficType.Management); + types.add(TrafficType.Storage); + types.add(TrafficType.Control); + + List dbNets = findJuniperManagedNetworks(types); + for (NetworkVO net:dbNets) { + + VirtualNetworkModel vnModel = getDatabase().lookupVirtualNetwork(null, getCanonicalName(net), net.getTrafficType()); + if (vnModel == null) { + vnModel = new VirtualNetworkModel(net, null, getCanonicalName(net), net.getTrafficType()); + vnModel.build(getModelController(), net); + try { + if (!vnModel.verify(getModelController())) { + vnModel.update(getModelController()); + } + } catch (Exception ex) { + s_logger.warn("virtual-network update: ", ex); + } + getDatabase().getVirtualNetworks().add(vnModel); + } + } + } + + @Override + public boolean isSystemDefaultNetwork(VirtualNetwork vnet) { + List fqn = vnet.getQualifiedName(); + if (fqn.size() < 3) { + return false; + } + List default_parent = vnet.getDefaultParent(); + int index = 0; + for (Iterator iter = default_parent.iterator(); iter.hasNext(); index++) { + String piece = iter.next(); + if (!piece.equals(fqn.get(index))) { + return false; + } + } + List default_networks = ImmutableList.of("__link_local__", "default-virtual-network", managementNetworkName); + for (Iterator iter = default_networks.iterator(); iter.hasNext();) { + String name = iter.next(); + if (name.equals(fqn.get(index))) { + return true; + } + } + return false; + } + + @Override + public boolean isSystemDefaultNetwork(NetworkVO net) { + if (net.getTrafficType() == TrafficType.Management || net.getTrafficType() == TrafficType.Storage + || net.getTrafficType() == TrafficType.Control) { + return true; + } + return false; + } + + @Override + public boolean isSystemRootDomain(net.juniper.contrail.api.types.Domain domain) { + if (domain.getName().compareTo(VNC_ROOT_DOMAIN) == 0) { + return true; + } + return false; + } + + @Override + public boolean isSystemRootDomain(DomainVO domain) { + if (domain.getId() == Domain.ROOT_DOMAIN || domain.getName().compareTo("ROOT") == 0 || + domain.getParent() == null) { + return true; + } + return false; + } + + @Override + public boolean isSystemDefaultProject(net.juniper.contrail.api.types.Project project) { + if (project.getName().compareTo(VNC_DEFAULT_PROJECT) == 0) { + return true; + } + return false; + } + + @Override + public boolean isSystemDefaultProject(ProjectVO project) { + return false; + } + + @Override + public String getVifNameByVmName(String vm_name, Integer device_id) { + String vif_name = vm_name + "-" + device_id.toString(); + return vif_name; + } + + @Override + public String getVifNameByVmUuid(String vm_uuid, Integer device_id) { + VMInstanceVO vm = _vmInstanceDao.findByUuid(vm_uuid); + if (vm != null) { + return vm.getInstanceName() + "-" + device_id.toString(); + } + return null; + } + + @Override + public ModelController getModelController() { + return _controller; + } + + @Override + public ApiConnector getApiConnector() { + return _api; + } + + public VirtualNetworkModel lookupPublicNetworkModel() { + List types = new ArrayList(); + types.add(TrafficType.Public); + List dbNets = findJuniperManagedNetworks(types); + if (dbNets == null) { + return null; + } + NetworkVO net = dbNets.get(0); + + VirtualNetworkModel vnModel = getDatabase().lookupVirtualNetwork(net.getUuid(), getCanonicalName(net), TrafficType.Public); + return vnModel; + } + + @Override + public void createPublicNetworks() { + List types = new ArrayList(Arrays.asList(TrafficType.Public)); + List dbNets = findJuniperManagedNetworks(types); + if (dbNets == null) { + return; + } + for (NetworkVO net: dbNets) { + VirtualNetworkModel vnModel = _database.lookupVirtualNetwork(net.getUuid(), getCanonicalName(net), + TrafficType.Public); + if (vnModel != null) { + continue; + } + vnModel = new VirtualNetworkModel(net, net.getUuid(), getCanonicalName(net), net.getTrafficType()); + vnModel.build(_controller, net); + try { + vnModel.update(_controller); + } catch (InternalErrorException ex) { + s_logger.warn("virtual-network update", ex); + continue; + } catch (IOException ex) { + s_logger.warn("virtual-network update", ex); + continue; + } + _database.getVirtualNetworks().add(vnModel); + + // Add the Contrail NetworkElement to the Public network. + Map providerMap = new HashMap(); + providerMap.put(Service.Connectivity.getName(), Provider.JuniperContrail.getName()); + _networksDao.update(net.getId(), net, providerMap); + } + } + + public boolean createFloatingIp(PublicIpAddress ip) { + VirtualNetworkModel vnModel = lookupPublicNetworkModel(); + assert vnModel != null : "public network vn model is null"; + FloatingIpPoolModel fipPoolModel = vnModel.getFipPoolModel(); + + /* create only, no updates */ + if (fipPoolModel == null) { + fipPoolModel = new FloatingIpPoolModel(); + fipPoolModel.addToVirtualNetwork(vnModel); + fipPoolModel.build(getModelController()); + try { + fipPoolModel.update(getModelController()); + vnModel.setFipPoolModel(fipPoolModel); + } catch (Exception ex) { + s_logger.warn("floating-ip-pool create: ", ex); + return false; + } + } + + FloatingIpModel fipModel = fipPoolModel.getFloatingIpModel(ip.getUuid()); + /* create only, no updates*/ + if (fipModel == null) { + fipModel = new FloatingIpModel(ip.getUuid()); + fipModel.addToFloatingIpPool(fipPoolModel); + fipModel.build(getModelController(), ip); + try { + fipModel.update(getModelController()); + } catch (Exception ex) { + s_logger.warn("floating-ip create: ", ex); + return false; + } + } + return true; + } + + public boolean deleteFloatingIp(PublicIpAddress ip) { + VirtualNetworkModel vnModel = lookupPublicNetworkModel(); + assert vnModel != null : "public network model is null"; + FloatingIpPoolModel fipPoolModel = vnModel.getFipPoolModel(); + FloatingIpModel fipModel = fipPoolModel.getFloatingIpModel(ip.getUuid()); + if (fipModel != null) { + try { + fipModel.destroy(getModelController()); + } catch (IOException ex) { + s_logger.warn("floating ip delete", ex); + return false; + } + fipPoolModel.removeSuccessor(fipModel); + if (!fipPoolModel.hasDescendents()) { + try { + fipPoolModel.delete(getModelController()); + vnModel.setFipPoolModel(null); + } catch (IOException e) { + return false; + } + } + } + return true; + } + + @SuppressWarnings("unchecked") + @Override + public List getFloatingIps() { + String fipPoolName = getDefaultPublicNetworkFQN() + ":PublicIpPool"; + FloatingIpPool fipPool = null; + try { + fipPool = (FloatingIpPool)_api.findByFQN(FloatingIpPool.class, fipPoolName); + } catch (Exception ex) { + s_logger.debug(ex); + } + if (fipPool == null) { + return null; + } + List> ips = fipPool.getFloatingIps(); + if (ips != null) { + try { + return (List) _api.getObjects(FloatingIp.class, ips); + } catch(IOException ex) { + s_logger.debug(ex); + return null; + } + } + return null; + } +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/DBSyncGeneric.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/DBSyncGeneric.java new file mode 100644 index 00000000000..7be9c559857 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/DBSyncGeneric.java @@ -0,0 +1,322 @@ +// 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.network.contrail.management; + +import java.lang.reflect.Method; +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; + +import org.apache.cloudstack.api.Identity; + +import net.juniper.contrail.api.ApiObjectBase; + +import org.apache.log4j.Logger; + +public class DBSyncGeneric { + + private static final Logger s_logger = Logger.getLogger(DBSyncGeneric.class); + + /* for each synchronization VNC class, following methods + * needs to be defined. + * For e.q : VirtualNetwork class should have createMethodPrefix+"VirtualNetwork" etc + */ + private final String createMethodPrefix = "create"; + private final String deleteMethodPrefix = "delete"; + private final String compareMethodPrefix = "compare"; + private final String filterMethodPrefix = "filter"; + private final String equalMethodPrefix = "equal"; + private final String syncMethodPrefix = "sync"; + /* default db, vnc comparators are implemented based on uuid values, + * if user defined comparators are required, then only add these methods + */ + private final String dbComparatorMethodPrefix = "dbComparator"; + private final String vncComparatorMethodPrefix = "vncComparator"; + + /* sync methods implementation object, if implemented in seperate class + * set the scope object + */ + private Object _scope; + private HashMap _methodMap; + private short _syncMode; + + public static final short SYNC_MODE_UPDATE = 0; + public static final short SYNC_MODE_CHECK = 1; + + public DBSyncGeneric(Object scope) { + this._scope = scope; + this._syncMode = SYNC_MODE_UPDATE; + setMethodMap(); + } + + public DBSyncGeneric() { + this._scope = this; + this._syncMode = SYNC_MODE_UPDATE; + setMethodMap(); + } + + public void setSyncMode(short mode) { + this._syncMode = mode; + } + + public short getSyncMode() { + return this._syncMode; + } + + public void setScope(Object scope) { + this._scope = scope; + setMethodMap(); + } + + public void setMethodMap() { + _methodMap = new HashMap(); + Method methods[] = _scope.getClass().getMethods(); + for (int i = 0; i < methods.length; i++) { + _methodMap.put(methods[i].getName(), methods[i]); + } + } + + public static String getClassName(Class cls) { + String clsname = cls.getName(); + int loc = clsname.lastIndexOf('.'); + if (loc > 0) { + clsname = clsname.substring(loc + 1); + } + return clsname; + } + + /* + * This API can be used to sync a particular vnc class + */ + public Boolean sync(Class cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { + String syncMethod = syncMethodPrefix + getClassName(cls); + Method method = _methodMap.get(syncMethod); + if (method == null) throw new NoSuchMethodException(getClassName(_scope.getClass()) + ":" + syncMethod); + return (Boolean)method.invoke(_scope, parameters); + } + + private void create(Class cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { + String createMethod = createMethodPrefix + getClassName(cls); + Method method = _methodMap.get(createMethod); + if (method == null) throw new NoSuchMethodException(getClassName(_scope.getClass()) + ":" + createMethod); + method.invoke(_scope, parameters); + } + + private void delete(Class cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { + String deleteMethod = deleteMethodPrefix + getClassName(cls); + Method method = _methodMap.get(deleteMethod); + if (method == null) throw new NoSuchMethodException(getClassName(_scope.getClass()) + ":" + deleteMethod); + method.invoke(_scope, parameters); + } + + private Integer compare(Class cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { + String compareMethod = compareMethodPrefix + getClassName(cls); + Method method = _methodMap.get(compareMethod); + if (method == null) throw new NoSuchMethodException(getClassName(_scope.getClass()) + ":" + compareMethod); + return (Integer)method.invoke(_scope, parameters); + } + + private Boolean filter(Class cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { + String filterMethod = filterMethodPrefix + getClassName(cls); + Method method = _methodMap.get(filterMethod); + if (method == null) { + s_logger.debug("Method not implemented: " + getClassName(_scope.getClass()) + ":" + filterMethod); + return false; + } + return (Boolean)method.invoke(_scope, parameters); + } + + private Boolean equal(Class cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { + String equalMethod = equalMethodPrefix + getClassName(cls); + Method method = _methodMap.get(equalMethod); + if (method == null) { + s_logger.debug("Method not implemented: " + getClassName(_scope.getClass()) + ":" + equalMethod); + return true; + } + return (Boolean)method.invoke(_scope, parameters); + } + + @SuppressWarnings("rawtypes") + private Comparator dbComparator(Class cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { + String dbComparatorMethod = dbComparatorMethodPrefix + getClassName(cls); + Method method = _methodMap.get(dbComparatorMethod); + if (method == null) return dbComparatorDefault(); + return (Comparator)method.invoke(_scope, parameters); + } + + @SuppressWarnings("rawtypes") + private Comparator vncComparator(Class cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { + String vncComparatorMethod = vncComparatorMethodPrefix + getClassName(cls); + Method method = _methodMap.get(vncComparatorMethod); + if (method == null) return vncComparatorDefault(); + return (Comparator)method.invoke(_scope, parameters); + } + + + @SuppressWarnings("rawtypes") + public Comparator dbComparatorDefault() { + Comparator comparator = new Comparator() { + public int compare(Identity u1, Identity u2) { + return u1.getUuid().compareTo(u2.getUuid()); + } + }; + return comparator; + } + + @SuppressWarnings("rawtypes") + public Comparator vncComparatorDefault() { + Comparator comparator = new Comparator() { + public int compare(ApiObjectBase u1, ApiObjectBase u2) { + return u1.getUuid().compareTo(u2.getUuid()); + } + }; + return comparator; + } + + + public static class SyncStats { + public int create; + public int delete; + public int equal; + public int diff; + public int filter; + public StringBuffer logMsg; + SyncStats() { + logMsg = new StringBuffer(); + } + void log(String str) { + logMsg.append(str); + logMsg.append('\n'); + } + public boolean isSynchronized() { + return create == 0 && delete == 0 && diff == 0; + } + public String toString() { + StringBuffer str = new StringBuffer(); + str.append("create: " + create); + str.append(", delete: " + delete); + if (filter > 0) { + str.append(", filter: " + filter); + } + str.append(", equal: " + equal); + str.append(", diff:" + diff); + return str.toString(); + } + } + + public void syncCollections(Class cls, Collection lhsList, Collection rhsList, boolean modifyMode, + SyncStats stats) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { + java.util.Iterator lhsIter = lhsList.iterator(); + java.util.Iterator rhsIter = rhsList.iterator(); + + Object lhsItem = lhsIter.hasNext() ? lhsIter.next() : null; + Object rhsItem = rhsIter.hasNext() ? rhsIter.next() : null; + + while (lhsItem != null && rhsItem != null) { + Integer cmp = this.compare(cls, lhsItem, rhsItem, stats.logMsg); + if (cmp < 0) { + // Create + if (modifyMode) { + this.create(cls, lhsItem, stats.logMsg); + } + stats.create++; + lhsItem = lhsIter.hasNext() ? lhsIter.next() : null; + } else if (cmp > 0) { + // Delete + if (!this.filter(cls, rhsItem, stats.logMsg)) { + if (modifyMode) { + this.delete(cls, rhsItem, stats.logMsg); + } + stats.delete++; + } else { + stats.filter++; + } + rhsItem = rhsIter.hasNext() ? rhsIter.next() : null; + } else { + // Equal + if (this.equal(cls, lhsItem, rhsItem, stats.logMsg)) { + stats.equal++; + } else { + stats.diff++; + } + lhsItem = lhsIter.hasNext() ? lhsIter.next() : null; + rhsItem = rhsIter.hasNext() ? rhsIter.next() : null; + } + } + + while (lhsItem != null) { + // Create + if (modifyMode) { + this.create(cls, lhsItem, stats.logMsg); + } + stats.create++; + lhsItem = lhsIter.hasNext() ? lhsIter.next() : null; + } + + while (rhsItem != null) { + // Delete + if (!this.filter(cls, rhsItem, stats.logMsg)) { + if (modifyMode) { + this.delete(cls, rhsItem, stats.logMsg); + } + stats.delete++; + } else { + stats.filter++; + } + rhsItem = rhsIter.hasNext() ? rhsIter.next() : null; + } + } + + @SuppressWarnings("unchecked") + public boolean syncGeneric(Class cls, List dbList, List vncList) throws Exception { + SyncStats stats = new SyncStats(); + stats.log("Sync log for <" + getClassName(cls) + ">"); + + s_logger.debug("Generic db sync : " + getClassName(cls)); + + java.util.Collections.sort(dbList, this.dbComparator(cls)); + java.util.Collections.sort(vncList, this.vncComparator(cls)); + + syncCollections(cls, dbList, vncList, _syncMode != SYNC_MODE_CHECK, stats); + + if (_syncMode != SYNC_MODE_CHECK) { + s_logger.debug("Sync stats<" + getClassName(cls) + ">: " + stats.toString()); + s_logger.debug(stats.logMsg); + s_logger.debug("Generic db sync : " + getClassName(cls) + " done"); + } else { + s_logger.debug("Sync state checking stats<" + getClassName(cls) + ">: " + stats.toString()); + if (!stats.isSynchronized()) { + s_logger.debug("DB and VNC objects out of sync is detected : " + getClassName(cls)); + s_logger.debug("Log message: \n" + stats.logMsg); + } else { + s_logger.debug("DB and VNC objects are in sync : " + getClassName(cls)); + } + } + + /* return value of this method indicates state of the db & vnc before sync + * false: out of sync, true: in sync; + * it does not indicate whether sync operation is performed or not; + * Actual sync is done only if _syncMode is UPDATE + */ + return stats.isSynchronized(); + } + +} + diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/EventUtils.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/EventUtils.java new file mode 100644 index 00000000000..dd18ca65e21 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/EventUtils.java @@ -0,0 +1,120 @@ +// 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.network.contrail.management; + +import com.cloud.event.ActionEvent; +import com.cloud.event.Event; +import com.cloud.event.EventCategory; +import com.cloud.event.EventTypes; +import com.cloud.server.ManagementServer; +import com.cloud.utils.component.ComponentContext; +import com.cloud.utils.component.ComponentMethodInterceptor; + +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.framework.messagebus.MessageBusBase; +import org.apache.cloudstack.framework.messagebus.MessageBus; +import org.apache.log4j.Logger; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +@Component +public class EventUtils { + private static final Logger s_logger = Logger.getLogger(EventUtils.class); + + protected static MessageBus _messageBus = null; + + public EventUtils() { + } + + private static void publishOnMessageBus(String eventCategory, + String eventType, String details, Event.State state) { + + if (state != com.cloud.event.Event.State.Completed) { + return; + } + + try { + _messageBus = (MessageBus)ComponentContext.getComponent(MessageBusBase.class); + } catch(NoSuchBeanDefinitionException nbe) { + return; // no provider is configured to provide events bus, so just return + } + + org.apache.cloudstack.framework.events.Event event = new org.apache.cloudstack.framework.events.Event( + ManagementServer.Name, + eventCategory, + eventType, + EventTypes.getEntityForEvent(eventType), null); + + Map eventDescription = new HashMap(); + eventDescription.put("event", eventType); + eventDescription.put("status", state.toString()); + eventDescription.put("details", details); + event.setDescription(eventDescription); + try { + _messageBus.publish(EventTypes.getEntityForEvent(eventType), eventType, null, event); + } catch (Exception e) { + s_logger.warn("Failed to publish action event on the the event bus."); + } + + } + + public static class EventInterceptor implements ComponentMethodInterceptor { + + private static final Logger s_logger = Logger.getLogger(EventInterceptor.class); + + public EventInterceptor() { + + } + + @Override + public Object interceptStart(Method method, Object target) { + return null; + } + + @Override + public void interceptComplete(Method method, Object target, Object event) { + ActionEvent actionEvent = method.getAnnotation(ActionEvent.class); + if (actionEvent != null) { + CallContext ctx = CallContext.current(); + if (!actionEvent.create()) { + publishOnMessageBus(EventCategory.ACTION_EVENT.getName(), + actionEvent.eventType(), ctx.getEventDetails(), com.cloud.event.Event.State.Completed); + } + } + } + + @Override + public void interceptException(Method method, Object target, Object event) { + s_logger.debug("interceptException"); + } + + @Override + public boolean needToIntercept(Method method) { + ActionEvent actionEvent = method.getAnnotation(ActionEvent.class); + if (actionEvent != null) { + return true; + } + + return false; + } + } +} 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 new file mode 100644 index 00000000000..e4570232e57 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ManagementNetworkGuru.java @@ -0,0 +1,114 @@ +// 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.network.contrail.management; + +import java.io.File; +import java.io.FileInputStream; +import java.util.Map; +import java.util.Properties; + +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; + +import com.cloud.deploy.DeploymentPlan; +import com.cloud.network.Network; +import com.cloud.network.Networks.BroadcastDomainType; +import com.cloud.network.Networks.Mode; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.dao.NetworkVO; +import com.cloud.offering.NetworkOffering; +import com.cloud.user.Account; +import com.cloud.utils.PropertiesUtil; + +/** + * ManagementNetworkGuru + * + * Replace the default management network strategy (PodBasedNetworkGuru) by using a Isolated network for management + * traffic. + */ +@Component +public class ManagementNetworkGuru extends ContrailGuru { + private static final Logger s_logger = Logger.getLogger(ManagementNetworkGuru.class); + private static final TrafficType[] _trafficTypes = {TrafficType.Management}; + + private final String configuration = "contrail.properties"; + private String _mgmt_cidr; + private String _mgmt_gateway; + + @Override + public String getName() { + return "ManagementNetworkGuru"; + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + File configFile = PropertiesUtil.findConfigFile(configuration); + final Properties configProps = new Properties(); + try { + configProps.load(new FileInputStream(configFile)); + } catch (Exception ex) { + ex.printStackTrace(); + throw new ConfigurationException(ex.getMessage()); + } + _mgmt_cidr = configProps.getProperty("management.cidr"); + _mgmt_gateway = configProps.getProperty("management.gateway"); + s_logger.info("Management network " + _mgmt_cidr + " gateway: " + _mgmt_gateway); + return true; + } + + @Override + public TrafficType[] getSupportedTrafficType() { + return _trafficTypes; + } + + @Override + public boolean isMyTrafficType(TrafficType type) { + for (TrafficType t : _trafficTypes) { + if (t == type) { + return true; + } + } + return false; + } + + private boolean canHandle(NetworkOffering offering) { + TrafficType type = offering.getTrafficType(); + return (isMyTrafficType(type)); + } + + @Override + public Network design(NetworkOffering offering, DeploymentPlan plan, + Network userSpecified, Account owner) { + + if (!canHandle(offering)) { + return null; + } + NetworkVO network = 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); + } + s_logger.debug("Allocated network " + userSpecified.getName() + + (network.getCidr() == null ? "" : " subnet: " + network.getCidr())); + return network; + } + +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ModelDatabase.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ModelDatabase.java new file mode 100644 index 00000000000..f705f076df7 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ModelDatabase.java @@ -0,0 +1,89 @@ +// 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.network.contrail.management; + +import java.util.TreeSet; + +import org.apache.cloudstack.network.contrail.model.ModelObjectBase; +import org.apache.cloudstack.network.contrail.model.ServiceInstanceModel; +import org.apache.cloudstack.network.contrail.model.VirtualMachineModel; +import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; + +import com.cloud.network.Networks.TrafficType; + +public class ModelDatabase { + TreeSet _serviceInstanceTable; + TreeSet _vmTable; + TreeSet _vnTable; + + ModelDatabase() { + initDb(); + } + + public void initDb() { + _serviceInstanceTable = new TreeSet(new ModelObjectBase.UuidComparator()); + _vmTable = new TreeSet(new ModelObjectBase.UuidComparator()); + _vnTable = new TreeSet(new ModelObjectBase.UuidComparator()); + } + + public TreeSet getServiceInstances() { + return _serviceInstanceTable; + } + + public ServiceInstanceModel lookupServiceInstance(String uuid) { + ServiceInstanceModel siKey = new ServiceInstanceModel(uuid); + ServiceInstanceModel current = _serviceInstanceTable.ceiling(siKey); + if (current != null && current.getUuid().equals(uuid)) { + return current; + } + return null; + } + + public TreeSet getVirtualMachines() { + return _vmTable; + } + + public VirtualMachineModel lookupVirtualMachine(String uuid) { + VirtualMachineModel vmKey = new VirtualMachineModel(null, uuid); + VirtualMachineModel current = _vmTable.ceiling(vmKey); + if (current != null && current.getUuid().equals(uuid)) { + return current; + } + return null; + } + + public TreeSet getVirtualNetworks() { + return _vnTable; + } + + public VirtualNetworkModel lookupVirtualNetwork(String uuid, String name, TrafficType ttype) { + VirtualNetworkModel vnKey = new VirtualNetworkModel(null, uuid, name, ttype); + VirtualNetworkModel current = _vnTable.ceiling(vnKey); + if (current != null) { + if (ttype == TrafficType.Management || ttype == TrafficType.Storage + || ttype == TrafficType.Control) { + if (current.getName().equals(name)) { + return current; + } + } else if (current.getUuid().equals(uuid)) { + return current; + } + } + return null; + } +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerDBSync.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerDBSync.java new file mode 100644 index 00000000000..fea9a951e68 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerDBSync.java @@ -0,0 +1,39 @@ +// 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.network.contrail.management; + +import java.io.IOException; + +import com.cloud.domain.DomainVO; +import com.cloud.projects.ProjectVO; + +public interface ServerDBSync { + + + public final static short SYNC_STATE_IN_SYNC = 0; + public final static short SYNC_STATE_OUT_OF_SYNC = 1; + public final static short SYNC_STATE_UNKNOWN = -1; + /* + * API for syncing all classes of vnc objects with cloudstack + * Sync cloudstack and vnc objects. + */ + public short syncAll(short syncMode); + public void syncClass(Class cls); + public void createProject(ProjectVO project, StringBuffer syncLogMesg) throws IOException; + public void createDomain(DomainVO domain, StringBuffer logMesg)throws IOException; +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java new file mode 100644 index 00000000000..8cb4e8d0b32 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java @@ -0,0 +1,965 @@ +// 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.network.contrail.management; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.concurrent.locks.ReentrantLock; +import java.lang.reflect.Method; + +import net.juniper.contrail.api.types.FloatingIp; +import net.juniper.contrail.api.types.FloatingIpPool; +import net.juniper.contrail.api.types.ServiceInstance; +import net.juniper.contrail.api.types.VirtualNetwork; +import net.juniper.contrail.api.types.VirtualMachine; +import net.juniper.contrail.api.types.VirtualMachineInterface; +import net.juniper.contrail.api.types.InstanceIp; +import net.juniper.contrail.api.ApiConnector; +import net.juniper.contrail.api.ApiObjectBase; +import net.juniper.contrail.api.ApiPropertyBase; +import net.juniper.contrail.api.ObjectReference; + +import org.apache.cloudstack.network.contrail.model.FloatingIpModel; +import org.apache.cloudstack.network.contrail.model.FloatingIpPoolModel; +import org.apache.cloudstack.network.contrail.model.ServiceInstanceModel; +import org.apache.cloudstack.network.contrail.model.VMInterfaceModel; +import org.apache.cloudstack.network.contrail.model.VirtualMachineModel; +import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; + +import com.cloud.dc.dao.VlanDao; +import com.cloud.domain.DomainVO; +import com.cloud.domain.dao.DomainDao; +import com.cloud.exception.InternalErrorException; +import com.cloud.projects.ProjectVO; +import com.cloud.projects.dao.ProjectDao; +import com.cloud.network.IpAddress; +import com.cloud.network.Networks.TrafficType; +import com.cloud.vm.dao.NicDao; +import com.cloud.vm.dao.VMInstanceDao; +import com.cloud.vm.VMInstanceVO; +import com.cloud.vm.NicVO; +import com.cloud.network.addr.PublicIp; +import com.cloud.network.dao.IPAddressVO; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.network.dao.PhysicalNetworkDao; +import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; + +import javax.inject.Inject; + +@Component +public class ServerDBSyncImpl implements ServerDBSync { + + @Inject DomainDao _domainDao; + @Inject ProjectDao _projectDao; + @Inject NetworkDao _networksDao; + @Inject VMInstanceDao _vmInstanceDao; + @Inject NicDao _nicDao; + @Inject VlanDao _vlanDao; + @Inject PhysicalNetworkDao _physicalNetworkDao; + @Inject PhysicalNetworkServiceProviderDao _physProviderDao; + @Inject ContrailManager _manager; + DBSyncGeneric _dbSync; + Class[] _vncClasses; + // Read-Write (true) or Read-Only mode. + boolean _rw_mode; + private final ReentrantLock _lockSyncMode = new ReentrantLock(); + + ServerDBSyncImpl() { + _vncClasses = new Class[] { + net.juniper.contrail.api.types.Domain.class, + net.juniper.contrail.api.types.Project.class, + VirtualNetwork.class, + VirtualMachine.class, + ServiceInstance.class, + FloatingIp.class + }; + _dbSync = new DBSyncGeneric(this); + } + + private static final Logger s_logger = Logger.getLogger(ServerDBSync.class); + + /* + * API for syncing all classes of vnc objects with cloudstack + * + * Sync cloudstack and vnc objects. + * Order has to be maintained + */ + @Override + public short syncAll(short syncMode) { + short syncState = SYNC_STATE_IN_SYNC; + + /* vnc classes need to be synchronized with cloudstack */ + s_logger.debug("syncing cloudstack db with vnc"); + try { + for(Class cls : _vncClasses) { + + /* lock the sync mode*/ + _lockSyncMode.lock(); + _rw_mode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; + _dbSync.setSyncMode(syncMode); + + if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { + s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); + } else { + s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); + } + + if (_dbSync.sync(cls) == false) { + if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { + s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); + } else { + s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); + } + syncState = SYNC_STATE_OUT_OF_SYNC; + } + if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { + s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); + } else { + s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); + } + /* unlock the sync mode */ + _lockSyncMode.unlock(); + } + } catch(Exception ex) { + s_logger.warn("DB Synchronization", ex); + syncState = SYNC_STATE_UNKNOWN; + if (_lockSyncMode.isLocked()) { + _lockSyncMode.unlock(); + } + } + + return syncState; + } + + @Override + public void syncClass(Class cls) { + + s_logger.debug("syncClass: " + cls.getName()); + try { + s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); + _lockSyncMode.lock(); + _dbSync.setSyncMode(DBSyncGeneric.SYNC_MODE_UPDATE); + _dbSync.sync(cls); + _lockSyncMode.unlock(); + s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); + } catch(Exception ex) { + s_logger.warn("Sync error: " + cls.getName(), ex); + if (_lockSyncMode.isLocked()) { + _lockSyncMode.unlock(); + } + } + } + + public void deleteChildren(List> childs, Class childCls, StringBuffer syncLogMesg) throws Exception { + final ApiConnector api = _manager.getApiConnector(); + if (childs == null) { + syncLogMesg.append("no children of type: " + childCls.getName() + "\n"); + return; + } + + syncLogMesg.append("delete children of type : " + DBSyncGeneric.getClassName(childCls) + "\n"); + String deleteChildMethod = "delete" + DBSyncGeneric.getClassName(childCls); + Method method = null; + Method methods[] = this.getClass().getMethods(); + for (int i = 0; i < methods.length; i++) { + if(methods[i].getName().equalsIgnoreCase(deleteChildMethod)) { + method = methods[i]; + break; + } + } + int count = 0; + for (ObjectReference childRef: childs) { + @SuppressWarnings("unchecked") + ApiObjectBase child = (ApiObjectBase) api.findById((Class)childCls, childRef.getUuid()); + if (method != null) { + method.invoke(this, child, syncLogMesg); + } else { + deleteDefault(child, childCls, syncLogMesg); + } + count ++; + } + syncLogMesg.append("deleted children count : " + count + "\n"); + } + + public void deleteDefault(ApiObjectBase vnc, Class cls, StringBuffer syncLogMesg) throws IOException { + final ApiConnector api = _manager.getApiConnector(); + api.delete(vnc); + syncLogMesg.append(cls.getCanonicalName() + "# VNC: " + vnc.getName() + " deleted\n"); + } + + /* + * Domain Synchronization methods + */ + public boolean syncDomain() throws Exception { + final ApiConnector api = _manager.getApiConnector(); + try { + List dbList = _domainDao.listAll(); + @SuppressWarnings("unchecked") + List vncList = (List) api.list(net.juniper.contrail.api.types.Domain.class, null); + return _dbSync.syncGeneric(net.juniper.contrail.api.types.Domain.class, dbList, vncList); + } catch (Exception ex) { + s_logger.warn("syncDomain", ex); + throw ex; + } + } + + @Override + public void createDomain(DomainVO db, StringBuffer syncLogMesg) throws IOException { + final ApiConnector api = _manager.getApiConnector(); + net.juniper.contrail.api.types.Domain vnc = new net.juniper.contrail.api.types.Domain(); + vnc.setName(db.getName()); + vnc.setUuid(db.getUuid()); + if (!api.create(vnc)) { + s_logger.error("Unable to create domain " + vnc.getName()); + syncLogMesg.append("Error: Virtual domain# VNC : Unable to create domain: " + + vnc.getName() + "\n"); + return; + } + syncLogMesg.append("Domain# VNC: " + vnc.getName() + " created \n"); + } + + public void deleteDomain(net.juniper.contrail.api.types.Domain vnc, StringBuffer syncLogMesg) throws IOException { + final ApiConnector api = _manager.getApiConnector(); + api.read(vnc); + syncLogMesg.append("Domain# DB: none; VNC: " + vnc.getName() + "(" + + vnc.getUuid() + "); action: delete\n"); + + /* delete all projects under this domain */ + try { + deleteChildren(vnc.getProjects(), net.juniper.contrail.api.types.Project.class, syncLogMesg); + } catch (Exception ex) { + s_logger.warn("deleteDomain", ex); + } + + api.delete(vnc); + syncLogMesg.append("Domain# VNC: " + vnc.getName() + " deleted\n"); + } + + public Integer compareDomain(DomainVO db, net.juniper.contrail.api.types.Domain vnc, StringBuffer syncLogMesg) { + if (_manager.isSystemRootDomain(db) && _manager.isSystemRootDomain(vnc)) { + return _manager.getDomainCanonicalName(db).compareTo(vnc.getName()); + } else if (_manager.isSystemRootDomain(db)) { + return -1; + } else if (_manager.isSystemRootDomain(vnc)) { + return 1; + } + return db.getUuid().compareTo(vnc.getUuid()); + } + + public Boolean filterDomain(net.juniper.contrail.api.types.Domain vnc, StringBuffer syncLogMesg) { + if (_manager.isSystemRootDomain(vnc)) { + return true; + } + return false; + } + + public Boolean equalDomain(DomainVO db, net.juniper.contrail.api.types.Domain vnc, StringBuffer syncLogMesg) { + syncLogMesg.append("Domain# DB: " + db.getName() + "; VNC: " + + vnc.getName() + "; action: equal, no action\n"); + return true; + } + + public Comparator dbComparatorDomain() { + Comparator comparator = new Comparator() { + public int compare(DomainVO u1, DomainVO u2) { + if (_manager.isSystemRootDomain(u1)) { + return -1; + } + if (_manager.isSystemRootDomain(u2)) { + return 1; + } + return u1.getUuid().compareTo(u2.getUuid()); + } + }; + return comparator; + } + + public Comparator vncComparatorDomain() { + Comparator comparator = new Comparator () { + public int compare(net.juniper.contrail.api.types.Domain u1, net.juniper.contrail.api.types.Domain u2) { + if (_manager.isSystemRootDomain(u1)) { + return -1; + } + if (_manager.isSystemRootDomain(u2)) { + return 1; + } + return u1.getUuid().compareTo(u2.getUuid()); + } + }; + return comparator; + } + + /* + * Project Synchronization methods + */ + @SuppressWarnings("unchecked") + public boolean syncProject() throws Exception { + final ApiConnector api = _manager.getApiConnector(); + try { + List dbList = _projectDao.listAll(); + List vncList = (List) api.list(net.juniper.contrail.api.types.Project.class, null); + return _dbSync.syncGeneric(net.juniper.contrail.api.types.Project.class, dbList, vncList); + } catch (Exception ex) { + s_logger.warn("syncProject", ex); + throw ex; + } + } + + @Override + public void createProject(ProjectVO db, StringBuffer syncLogMesg) throws IOException { + final ApiConnector api = _manager.getApiConnector(); + net.juniper.contrail.api.types.Project vnc = new net.juniper.contrail.api.types.Project(); + vnc.setName(db.getName()); + vnc.setUuid(db.getUuid()); + if (!api.create(vnc)) { + s_logger.error("Unable to create project: " + vnc.getName()); + syncLogMesg.append("Error: Virtual project# VNC : Unable to create project: " + + vnc.getName() + "\n"); + return; + } + syncLogMesg.append("Project# VNC: " + vnc.getName() + " created \n"); + } + + public void deleteProject(net.juniper.contrail.api.types.Project vnc, StringBuffer syncLogMesg) throws IOException { + final ApiConnector api = _manager.getApiConnector(); + api.read(vnc); + syncLogMesg.append("Project# DB: none; VNC: " + vnc.getName() + "(" + + vnc.getUuid() + "); action: delete\n"); + + try { + deleteChildren(vnc.getVirtualNetworks(), VirtualNetwork.class, syncLogMesg); + deleteChildren(vnc.getSecurityGroups(), net.juniper.contrail.api.types.SecurityGroup.class, syncLogMesg); + deleteChildren(vnc.getNetworkIpams(), net.juniper.contrail.api.types.NetworkIpam.class, syncLogMesg); + deleteChildren(vnc.getNetworkPolicys(), net.juniper.contrail.api.types.NetworkPolicy.class, syncLogMesg); + } catch (Exception ex) { + s_logger.warn("deleteProject", ex); + } + + api.delete(vnc); + syncLogMesg.append("Project# VNC: " + vnc.getName() + " deleted\n"); + } + + public Integer compareProject(ProjectVO db, net.juniper.contrail.api.types.Project vnc, StringBuffer syncLogMesg) { + if (_manager.isSystemDefaultProject(db) && _manager.isSystemDefaultProject(vnc)) { + return _manager.getProjectCanonicalName(db).compareTo(vnc.getName()); + } else if (_manager.isSystemDefaultProject(db)) { + return -1; + } else if (_manager.isSystemDefaultProject(vnc)) { + return 1; + } + return db.getUuid().compareTo(vnc.getUuid()); + } + + public Boolean filterProject(net.juniper.contrail.api.types.Project vnc, StringBuffer syncLogMesg) { + if (_manager.isSystemDefaultProject(vnc)) { + syncLogMesg.append("VNC: " + vnc.getName() + " filtered; action: don't delete\n"); + return true; + } + return false; + } + + public Boolean equalProject(ProjectVO db, net.juniper.contrail.api.types.Project vnc, StringBuffer syncLogMesg) { + syncLogMesg.append("Project# DB: " + db.getName() + "; VNC: " + + vnc.getName() + "; action: equal, no action\n"); + return true; + } + + public Comparator dbComparatorProject() { + Comparator comparator = new Comparator() { + public int compare(ProjectVO u1, ProjectVO u2) { + if (_manager.isSystemDefaultProject(u1)) { + return -1; + } + if (_manager.isSystemDefaultProject(u2)) { + return 1; + } + return u1.getUuid().compareTo(u2.getUuid()); + } + }; + return comparator; + } + + public Comparator vncComparatorProject() { + Comparator comparator = new Comparator () { + public int compare(net.juniper.contrail.api.types.Project u1, net.juniper.contrail.api.types.Project u2) { + if (_manager.isSystemDefaultProject(u1)) { + return -1; + } + if (_manager.isSystemDefaultProject(u2)) { + return 1; + } + return u1.getUuid().compareTo(u2.getUuid()); + } + }; + return comparator; + } + + /* + * Security Groups + */ + + public void deleteSecurityGroup(net.juniper.contrail.api.types.SecurityGroup vnc, StringBuffer syncLogMesg) throws IOException { + final ApiConnector api = _manager.getApiConnector(); + api.delete(vnc); + syncLogMesg.append("SecurityGroup# VNC: " + vnc.getName() + " deleted\n"); + } + + /* + * Virtual Network Synchronization methods + */ + @SuppressWarnings({ "unchecked" }) + public boolean syncVirtualNetwork() throws Exception { + final ApiConnector api = _manager.getApiConnector(); + try { + + List types = new ArrayList(); + types.add(TrafficType.Public); + types.add(TrafficType.Guest); + List dbNets = _manager.findJuniperManagedNetworks(types); + + List vList = (List) api.list(VirtualNetwork.class, null); + List vncList = new ArrayList(); + for (VirtualNetwork vn:vList) { + if (!_manager.isSystemDefaultNetwork(vn)) { + vncList.add(vn); + } + } + s_logger.debug("sync VN - DB size: " + dbNets.size() + " VNC Size: " + vncList.size()); + return _dbSync.syncGeneric(VirtualNetwork.class, dbNets, vncList); + } catch (Exception ex) { + s_logger.warn("sync virtual-networks", ex); + throw ex; + } + } + + public Comparator dbComparatorVirtualNetwork() { + Comparator comparator = new Comparator() { + public int compare(NetworkVO u1, NetworkVO u2) { + if (_manager.isSystemDefaultNetwork(u1) && _manager.isSystemDefaultNetwork(u2)) { + return _manager.getCanonicalName(u1).compareTo(_manager.getCanonicalName(u2)); + } else if (_manager.isSystemDefaultNetwork(u1)) { + return -1; + } else if (_manager.isSystemDefaultNetwork(u2)) { + return 1; + } + return u1.getUuid().compareTo(u2.getUuid()); + } + }; + return comparator; + } + + public Comparator vncComparatorVirtualNetwork() { + Comparator comparator = new Comparator() { + public int compare(VirtualNetwork u1, VirtualNetwork u2) { + if (_manager.isSystemDefaultNetwork(u1) && _manager.isSystemDefaultNetwork(u2)) { + return u1.getName().compareTo(u2.getName()); + } else if (_manager.isSystemDefaultNetwork(u1)) { + return -1; + } else if (_manager.isSystemDefaultNetwork(u2)) { + return 1; + } + return u1.getUuid().compareTo(u2.getUuid()); + } + }; + return comparator; + } + + public void createVirtualNetwork(NetworkVO dbNet, StringBuffer syncLogMesg) throws IOException { + syncLogMesg.append("VN# DB: " + _manager.getCanonicalName(dbNet) + + "(" + dbNet.getUuid() + "); VNC: none; action: create\n"); + + if (_manager.getDatabase().lookupVirtualNetwork(dbNet.getUuid(), + _manager.getCanonicalName(dbNet), dbNet.getTrafficType()) != null) { + s_logger.warn("VN model object is already present in DB: " + + dbNet.getUuid() + ", name: " + dbNet.getName()); + } + + VirtualNetworkModel vnModel = new VirtualNetworkModel(dbNet, + dbNet.getUuid(), _manager.getCanonicalName(dbNet), dbNet.getTrafficType()); + vnModel.build(_manager.getModelController(), dbNet); + + if (_rw_mode) { + try { + if (!vnModel.verify(_manager.getModelController())) { + vnModel.update(_manager.getModelController()); + } + } catch (InternalErrorException ex) { + s_logger.warn("create virtual-network", ex); + syncLogMesg.append("Error: VN# VNC : Unable to create network " + + dbNet.getName() + "\n"); + return; + } + s_logger.debug("add model " + vnModel.getName()); + _manager.getDatabase().getVirtualNetworks().add(vnModel); + syncLogMesg.append("VN# VNC: " + dbNet.getUuid() + ", " + vnModel.getName() + " created\n"); + } else { + syncLogMesg.append("VN# VNC: " + vnModel.getName() + " created \n"); + } + } + + + public void deleteVirtualNetwork(VirtualNetwork vnet, StringBuffer syncLogMesg) throws IOException { + final ApiConnector api = _manager.getApiConnector(); + if (_manager.isSystemDefaultNetwork(vnet)) { + syncLogMesg.append("VN# System default virtual Network# VNC: " + vnet.getName() + " can not be deleted\n"); + return; + } + api.read(vnet); + + deleteInstanceIps(vnet.getInstanceIpBackRefs(), syncLogMesg); + + List> fipPools = vnet.getFloatingIpPools(); + if (fipPools != null && !fipPools.isEmpty()) { + FloatingIpPool floatingIpPool = (FloatingIpPool) api.findById(FloatingIpPool.class, fipPools.get(0).getUuid()); + if (floatingIpPool != null ) { + deleteFloatingIps(floatingIpPool.getFloatingIps(), syncLogMesg); + } + } + + deleteVirtualMachineInterfaces(vnet.getVirtualMachineInterfaceBackRefs(), syncLogMesg); + + syncLogMesg.append("VN# DB: none; VNC: " + vnet.getName() + "(" + vnet.getUuid() + "); action: delete\n"); + api.delete(vnet); + syncLogMesg.append("VN# VNC: " + vnet.getName() + " deleted\n"); + } + + public Integer compareVirtualNetwork(NetworkVO dbn, VirtualNetwork vnet, StringBuffer syncLogMesg) { + if (_manager.isSystemDefaultNetwork(dbn) && _manager.isSystemDefaultNetwork(vnet)) { + return _manager.getCanonicalName(dbn).compareTo(vnet.getName()); + } else if (_manager.isSystemDefaultNetwork(dbn)) { + return -1; + } else if (_manager.isSystemDefaultNetwork(vnet)) { + return 1; + } + return dbn.getUuid().compareTo(vnet.getUuid()); + } + + public Boolean filterVirtualNetwork(VirtualNetwork vnet, StringBuffer syncLogMesg) { + if (_manager.isSystemDefaultNetwork(vnet)) { + syncLogMesg.append("VN# VNC: " + vnet.getName() + " filtered; action: don't delete\n"); + return true; + } + return false; + } + + public Boolean equalVirtualNetwork(NetworkVO dbn, VirtualNetwork vnet, StringBuffer syncLogMesg) { + syncLogMesg.append("VN# DB: " + _manager.getCanonicalName(dbn) + + "; VNC: " + vnet.getName() + "; action: equal\n"); + + VirtualNetworkModel current = _manager.getDatabase().lookupVirtualNetwork(vnet.getUuid(), + _manager.getCanonicalName(dbn), dbn.getTrafficType()); + + VirtualNetworkModel vnModel = new VirtualNetworkModel(dbn, vnet.getUuid(), + _manager.getCanonicalName(dbn), dbn.getTrafficType()); + vnModel.build(_manager.getModelController(), dbn); + + if (_rw_mode) { + if (current != null) { + FloatingIpPoolModel fipPoolModel = current.getFipPoolModel(); + if (fipPoolModel != null) { + vnModel.setFipPoolModel(fipPoolModel); + fipPoolModel.addToVirtualNetwork(vnModel); + } + _manager.getDatabase().getVirtualNetworks().remove(current); + } + s_logger.debug("add model " + vnModel.getName()); + _manager.getDatabase().getVirtualNetworks().add(vnModel); + try { + if (!vnModel.verify(_manager.getModelController())) { + vnModel.update(_manager.getModelController()); + } + } catch (Exception ex) { + s_logger.warn("update virtual-network", ex); + } + } else { + //compare + if (current != null && current.compare(_manager.getModelController(), vnModel) == false) { + syncLogMesg.append("VN# DB: " + _manager.getCanonicalName(dbn) + + "; VNC: " + vnet.getName() + "; attributes differ\n"); + return false; + } + } + return true; + } + + /* + * Virtual Machine Synchronization methods + */ + + public boolean syncVirtualMachine() { + final ApiConnector api = _manager.getApiConnector(); + try { + List vmDbList = _vmInstanceDao.listAll(); + @SuppressWarnings("unchecked") + List vncVmList = (List) api.list(VirtualMachine.class, null); + s_logger.debug("sync VM: CS size: " + vmDbList.size() + " VNC size: " + vncVmList.size()); + return _dbSync.syncGeneric(VirtualMachine.class, vmDbList, vncVmList); + } catch (Exception ex) { + s_logger.warn("sync virtual-machines", ex); + } + return false; + } + + public Comparator dbComparatorVirtualMachine() { + Comparator comparator = new Comparator() { + public int compare(VMInstanceVO u1, VMInstanceVO u2) { + return u1.getUuid().compareTo(u2.getUuid()); + } + }; + return comparator; + } + + public Comparator vncComparatorVirtualMachine() { + Comparator comparator = new Comparator () { + public int compare(VirtualMachine u1, VirtualMachine u2) { + return u1.getUuid().compareTo(u2.getUuid()); + } + }; + return comparator; + } + + public void createVirtualMachine(VMInstanceVO dbVm, StringBuffer syncLogMesg) throws IOException { + syncLogMesg.append("VM# DB: " + dbVm.getInstanceName() + "/" + dbVm.getUuid() + "; VNC: none; action: create\n"); + VirtualMachineModel vmModel = new VirtualMachineModel(dbVm, dbVm.getUuid()); + vmModel.build(_manager.getModelController(), dbVm); + buildNicResources(vmModel, dbVm, syncLogMesg); + + if (_rw_mode) { + try { + vmModel.update(_manager.getModelController()); + } catch (InternalErrorException ex) { + s_logger.warn("create virtual-machine", ex); + return; + } + _manager.getDatabase().getVirtualMachines().add(vmModel); + syncLogMesg.append("VM# VNC: " + dbVm.getUuid() + " created\n"); + } + } + + private void deleteVirtualMachineInterfaces(List> list, StringBuffer syncLogMesg) throws IOException { + if (list == null) { + return; + } + final ApiConnector api = _manager.getApiConnector(); + for (ObjectReference vmiRef: list) { + VirtualMachineInterface vmi = (VirtualMachineInterface) api.findById(VirtualMachineInterface.class, vmiRef.getUuid()); + deleteInstanceIps(vmi.getInstanceIpBackRefs(), syncLogMesg); + deleteFloatingIps(vmi.getFloatingIpBackRefs(), syncLogMesg); + api.delete(VirtualMachineInterface.class, vmiRef.getUuid()); + syncLogMesg.append("VNC vmi: " + vmi.getUuid() + " deleted\n"); + } + } + + private void deleteInstanceIps(List> list, StringBuffer syncLogMesg) throws IOException { + if (list == null) { + return; + } + final ApiConnector api = _manager.getApiConnector(); + for (ObjectReference instIp: list) { + api.delete(InstanceIp.class, instIp.getUuid()); + syncLogMesg.append("VNC instance ip: " + instIp.getUuid() + " deleted\n"); + } + + } + + private void deleteFloatingIps(List> list, StringBuffer syncLogMesg) throws IOException { + if (list == null) { + return; + } + final ApiConnector api = _manager.getApiConnector(); + for (ObjectReference floatingIp: list) { + api.delete(FloatingIp.class, floatingIp.getUuid()); + syncLogMesg.append("VNC instance ip: " + floatingIp.getUuid() + " deleted\n"); + } + } + + public void deleteVirtualMachine(VirtualMachine vncVm, StringBuffer syncLogMesg) { + final ApiConnector api = _manager.getApiConnector(); + syncLogMesg.append("VM# DB:none; VNC: " + vncVm.getName() + "/" + vncVm.getUuid() + "; action: delete\n"); + if (!_rw_mode) { + return; + } + try { + if (!api.read(vncVm)) { + return; + } + deleteVirtualMachineInterfaces(vncVm.getVirtualMachineInterfaces(), syncLogMesg); + api.delete(VirtualMachine.class, vncVm.getUuid()); + } catch (IOException ex) { + s_logger.warn("delete virtual-machine", ex); + return; + } + syncLogMesg.append("VM# VNC: " + vncVm.getName() + " deleted\n"); + } + + public Integer compareVirtualMachine(VMInstanceVO dbVm, VirtualMachine vncVm, StringBuffer syncLogMesg) { + String dbVmId = dbVm.getUuid(); + String vncVmId = vncVm.getUuid(); + return dbVmId.compareTo(vncVmId); + } + + public boolean filterVirtualMachine(VirtualMachine vncVm, StringBuffer syncLogMesg) { + return false; + } + + private void buildNicResources(VirtualMachineModel vmModel, VMInstanceVO dbVm, StringBuffer syncLogMsg) + throws IOException { + List nics = _nicDao.listByVmId(dbVm.getId()); + for (NicVO nic : nics) { + VMInterfaceModel vmiModel = vmModel.getVMInterface(nic.getUuid()); + if (vmiModel == null) { + vmiModel = new VMInterfaceModel(nic.getUuid()); + NetworkVO network = _networksDao.findById(nic.getNetworkId()); + VirtualNetworkModel vnModel = _manager.getDatabase().lookupVirtualNetwork( + network.getUuid(), _manager.getCanonicalName(network), network.getTrafficType()); + if (vnModel == null) { + s_logger.warn("Unable to locate virtual-network for network id " + network.getId()); + continue; + } + vmiModel.addToVirtualMachine(vmModel); + vmiModel.addToVirtualNetwork(vnModel); + } + vmiModel.build(_manager.getModelController(), dbVm, nic); + } + } + + public Boolean equalVirtualMachine(VMInstanceVO dbVm, VirtualMachine vncVm, StringBuffer syncLogMsg) { + + syncLogMsg.append("VM# DB: " + dbVm.getInstanceName() + "/" + dbVm.getUuid() + + "; VNC: " + vncVm.getUuid() + "; action: equal; DB VM State: " + dbVm.getState() + "\n"); + + VirtualMachineModel vmModel = new VirtualMachineModel(dbVm, dbVm.getUuid()); + vmModel.build(_manager.getModelController(), dbVm); + + if (vmModel.isActive()) { + try { + buildNicResources(vmModel, dbVm, syncLogMsg); + } catch (IOException ex) { + s_logger.warn("build nic information for " + dbVm.getInstanceName(), ex); + } + } + + VirtualMachineModel current = _manager.getDatabase().lookupVirtualMachine(vncVm.getUuid()); + if (_rw_mode) { + if (current != null) { + _manager.getDatabase().getVirtualMachines().remove(current); + } + _manager.getDatabase().getVirtualMachines().add(vmModel); + try { + vmModel.update(_manager.getModelController()); + } catch (Exception ex) { + s_logger.warn("update virtual-machine", ex); + } + } else { + //compare + if (current != null && current.compare(_manager.getModelController(), vmModel) == false) { + syncLogMsg.append("VM # DB: " + dbVm.getInstanceName() + + "; VNC: " + vncVm.getName() + "; attributes differ\n"); + return false; + } + } + return true; + } + + + public boolean syncFloatingIp() throws Exception { + + List ipList = _manager.findJuniperManagedPublicIps(); + List vncList = _manager.getFloatingIps(); + if (ipList == null) { + ipList = new ArrayList(); + } + if (vncList == null) { + vncList = new ArrayList(); + } + + boolean status = false; + try { + status = _dbSync.syncGeneric(FloatingIp.class, ipList, vncList); + } catch (Exception ex) { + s_logger.warn("sync floating-ips", ex); + throw ex; + } + return status; + } + + public Comparator dbComparatorFloatingIp() { + Comparator comparator = new Comparator() { + public int compare(IpAddress u1, IpAddress u2) { + return u1.getUuid().compareTo(u2.getUuid()); + } + }; + return comparator; + } + + public Comparator vncComparatorFloatingIp() { + Comparator comparator = new Comparator () { + public int compare(FloatingIp u1, FloatingIp u2) { + return u1.getUuid().compareTo(u2.getUuid()); + } + }; + return comparator; + } + + public Integer compareFloatingIp(IpAddress db, FloatingIp vnc, StringBuffer syncLogMesg) { + String dbId = db.getUuid(); + String vncId = vnc.getUuid(); + return dbId.compareTo(vncId); + } + + public void createFloatingIp(IPAddressVO dbIp, StringBuffer syncLogMesg) throws Exception { + + if (dbIp.getState() == IpAddress.State.Releasing) { + /* Don't need to push releasing ip */ + syncLogMesg.append("fip# DB: " + dbIp.getUuid() + ", state releasing, don't create in vnc\n"); + return; + } + syncLogMesg.append("fip# DB: " + dbIp.getAddress().addr() + "; VNC: none; action: create\n"); + if (!_manager.createFloatingIp(PublicIp.createFromAddrAndVlan(dbIp, _vlanDao.findById(dbIp.getVlanId())))) { + syncLogMesg.append("fip# VNC: " + dbIp.getAddress().addr() + " unable to create\n"); + return ; + } + syncLogMesg.append("fip# VNC: " + dbIp.getUuid() + " created\n"); + } + + public void deleteFloatingIp(FloatingIp vnc, StringBuffer syncLogMesg) throws IOException { + final ApiConnector api = _manager.getApiConnector(); + syncLogMesg.append("fip# DB: none; VNC: " + vnc.getAddress() + "(" + + vnc.getUuid() + "); action: delete\n"); + api.delete(vnc); + syncLogMesg.append("fip# VNC: " + vnc.getUuid() + " deleted\n"); + } + + public Boolean equalFloatingIp(IPAddressVO db, FloatingIp vnc, StringBuffer syncLogMsg) + throws IOException { + + syncLogMsg.append("fip# DB: " + db.getAddress().addr() + + "; VNC: " + vnc.getAddress() + "; action: equal" + "\n"); + + VirtualNetworkModel vnModel = _manager.lookupPublicNetworkModel(); + assert vnModel != null : "public network vn model is null"; + + FloatingIpPoolModel fipPoolModel = vnModel.getFipPoolModel(); + if (fipPoolModel == null) { + fipPoolModel = new FloatingIpPoolModel(); + fipPoolModel.addToVirtualNetwork(vnModel); + fipPoolModel.build(_manager.getModelController()); + try { + fipPoolModel.update(_manager.getModelController()); + vnModel.setFipPoolModel(fipPoolModel); + } catch (Exception ex) { + s_logger.warn("floating-ip-pool create: ", ex); + return false; + } + } + + FloatingIpModel current = fipPoolModel.getFloatingIpModel(db.getUuid()); + if (current == null) { + s_logger.debug("add model " + db.getAddress().addr()); + FloatingIpModel fipModel = new FloatingIpModel(db.getUuid()); + fipModel.addToFloatingIpPool(fipPoolModel); + fipModel.build(_manager.getModelController(), + PublicIp.createFromAddrAndVlan(db, _vlanDao.findById(db.getVlanId()))); + try { + fipModel.update(_manager.getModelController()); + } catch (Exception ex) { + s_logger.warn("floating-ip create: ", ex); + return false; + } + } + return true; + } + + public Integer compareServiceInstance(ServiceInstanceModel siModel, ServiceInstance siObj, StringBuffer logMsg) { + String fqn = StringUtils.join(siObj.getQualifiedName(), ':'); + return siModel.getQualifiedName().compareTo(fqn); + } + + /** + * createServiceInstance + * + * This method should never be invoked since the model objects have been installed already when sync is called. + * @param siModel + * @param logMsg + */ + public void createServiceInstance(ServiceInstanceModel siModel, StringBuffer logMsg) { + assert false; + } + + public void deleteServiceInstance(ServiceInstance siObj, StringBuffer logMsg) { + final ApiConnector api = _manager.getApiConnector(); + s_logger.debug("delete " + siObj.getQualifiedName()); + if (!_rw_mode) { + return; + } + try { + api.delete(siObj); + } catch (IOException ex) { + s_logger.warn("service-instance delete", ex); + } + } + + /** + * equalServiceInstance + * + * @param siModel + * @param siObj + * @param logMsg + */ + public void equalServiceInstance(ServiceInstanceModel siModel, ServiceInstance siObj, StringBuffer logMsg) { + s_logger.debug("equal " + siModel.getQualifiedName()); + } + + static class ServiceInstanceComparator implements Comparator { + @Override + public int compare(ServiceInstance obj1, ServiceInstance obj2) { + String name1 = StringUtils.join(obj1.getQualifiedName(), ':'); + String name2 = StringUtils.join(obj2.getQualifiedName(), ':'); + return name1.compareTo(name2); + } + + } + /** + * The service-instance model list is build as a result of synchronizing virtual-machines. + * @return + */ + public boolean syncServiceInstance() { + final ApiConnector api = _manager.getApiConnector(); + boolean inSync; + try { + @SuppressWarnings("unchecked") + List siList = (List) api.list(ServiceInstance.class, null); + java.util.Collections.sort(siList, new ServiceInstanceComparator()); + DBSyncGeneric.SyncStats stats = new DBSyncGeneric.SyncStats(); + _dbSync.syncCollections(ServiceInstance.class, _manager.getDatabase().getServiceInstances(), siList, + _rw_mode, stats); + inSync = stats.create == 0 && stats.delete == 0; + } catch (Exception ex) { + s_logger.warn("synchronize service-instances", ex); + return false; + } + return inSync; + } +} + diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerEventHandler.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerEventHandler.java new file mode 100644 index 00000000000..7fb94d81731 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerEventHandler.java @@ -0,0 +1,22 @@ +// 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.network.contrail.management; + +public interface ServerEventHandler { + public void subscribe(); +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerEventHandlerImpl.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerEventHandlerImpl.java new file mode 100644 index 00000000000..455e6012e43 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerEventHandlerImpl.java @@ -0,0 +1,251 @@ +// 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.network.contrail.management; + +import java.lang.reflect.Method; +import java.util.HashMap; + +import javax.inject.Inject; + +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; + +import com.cloud.domain.DomainVO; +import com.cloud.domain.dao.DomainDao; +import com.cloud.event.EventTypes; +import com.cloud.offerings.dao.NetworkOfferingDao; +import com.cloud.projects.ProjectVO; +import com.cloud.projects.dao.ProjectDao; + +import org.apache.cloudstack.framework.messagebus.MessageBus; +import org.apache.cloudstack.framework.messagebus.MessageDispatcher; +import org.apache.cloudstack.framework.messagebus.MessageHandler; + +/* + * When an Object is created/deleted in cloudstack DB, it has to be reflected in VNC. + * This class handles create, delete and update events of cloudstack db objects. + * + * - subscribe for interested events + * - create events will have db id of the object and hence db object and its parameters can be retrieved + * - delete events will have db id but the object no longer exists in db and hence complete class needs to be synchronized + * + */ +@Component +public class ServerEventHandlerImpl implements ServerEventHandler { + @Inject NetworkOfferingDao _networkOfferingDao; + @Inject DomainDao _domainDao; + @Inject ProjectDao _projectDao; + @Inject private MessageBus _messageBus; + @Inject ServerDBSync _dbSync; + @Inject ContrailManager _manager; + private HashMap _methodMap; + private HashMap> _classMap; + + private static final Logger s_logger = Logger.getLogger(MessageHandler.class); + + ServerEventHandlerImpl() { + setMethodMap(); + setClassMap(); + } + + protected void finalize () { + + } + + private void setMethodMap() { + _methodMap = new HashMap(); + Method methods[] = this.getClass().getMethods(); + for (int i = 0; i < methods.length; i++) { + _methodMap.put(methods[i].getName(), methods[i]); + } + } + + private void setClassMap() { + _classMap = new HashMap>(); + _classMap.put("Domain", net.juniper.contrail.api.types.Domain.class); + _classMap.put("Project", net.juniper.contrail.api.types.Project.class); + } + + @MessageHandler(topic=".*") + public void defaultMessageHandler(String subject, String topic, Object args) { + s_logger.info("DB Event Received - topic: " + topic + "; subject: " + subject); + + if (subject.equals("VLAN.IP.RANGE.CREATE")) { + _manager.createPublicNetworks(); + return; + } else if (subject.equals("VLAN.IP.RANGE.DELETE")) { + // TODO + return; + } + + org.apache.cloudstack.framework.events.Event event = (org.apache.cloudstack.framework.events.Event)args; + + /* Method name should be on for example: onDomainCreate */ + Method method = null; + + try { + /* Only create event needs special implementation */ + if (event.getEventType().contains("CREATE")) { + String methodName = "on" + event.getResourceType() + "Create"; + method = _methodMap.get(methodName); + if (method == null) { + defaultCreateHandler(subject, topic, event); + } else { + method.invoke(this, subject, topic, event); + } + } else if (event.getEventType().contains("DELETE")) { + defaultDeleteHandler(subject, topic, event); + } else { + defaultHandler(subject, topic, event); + } + } catch (Exception e) { + s_logger.debug(e); + } + } + + /* Default create handler */ + void defaultCreateHandler(String subject, String topic, org.apache.cloudstack.framework.events.Event event ) { + + s_logger.debug("Default handler is invoked for subject: " + subject + "; topic: " + topic); + s_logger.debug("description: " + event.getDescription()); + s_logger.debug("category: " + event.getEventCategory()); + s_logger.debug("type: " + event.getResourceType()); + s_logger.debug("event-type: " + event.getEventType()); + + Class cls = _classMap.get(event.getResourceType()); + + if ( cls != null ) { + _dbSync.syncClass(cls); + } + + return; + } + + /* Default handler */ + void defaultDeleteHandler(String subject, String topic, org.apache.cloudstack.framework.events.Event event ) { + + s_logger.debug("Default handler is invoked for subject: " + subject + "; topic: " + topic); + + s_logger.debug("description: " + event.getDescription()); + s_logger.debug("category: " + event.getEventCategory()); + s_logger.debug("type: " + event.getResourceType()); + s_logger.debug("event-type: " + event.getEventType()); + Class cls = _classMap.get(event.getResourceType()); + if ( cls != null ) { + _dbSync.syncClass(cls); + } + return; + } + + /* Default handler */ + void defaultHandler(String subject, String topic, org.apache.cloudstack.framework.events.Event event ) { + + s_logger.debug("Default handler is invoked for subject: " + subject + "; topic: " + topic); + + s_logger.debug("description: " + event.getDescription()); + s_logger.debug("category: " + event.getEventCategory()); + s_logger.debug("type: " + event.getResourceType()); + s_logger.debug("event-type: " + event.getEventType()); + Class cls = _classMap.get(event.getResourceType()); + if ( cls != null ) { + _dbSync.syncClass(cls); + } + return; + } + + /* Description string contains substring of format "resourceType Id: " for example: "Project id: 35" + * + * example: + * description: {"details":"Successfully completed deleting project. Project Id: 39","status":"Completed","event":"PROJECT.DELETE","account":"3afca502-d83c-11e2-b748-52540076b7ca","user":"3b111406-d83c-11e2-b748-52540076b7ca"} + * + * If the description string format is changed, this code has to be modified + */ + private long parseForId(String resourceType, String description) { + String typeStr = resourceType + " Id:"; + int idIdx = description.indexOf(typeStr) + typeStr.length(); + String idStr = description.substring(idIdx, description.indexOf('"', idIdx)); + long id = 0; + try { + id = Long.parseLong(idStr.trim()); + } catch (Exception e) { + s_logger.debug("Unable to parse id string<" + idStr.trim() + "> for long value, ignored"); + } + return id; + } + + + public void onDomainCreate(String subject, String topic, org.apache.cloudstack.framework.events.Event event) { + s_logger.info("onDomainCreate; topic: " + topic + "; subject: " + subject); + try { + long id = parseForId(event.getResourceType(), event.getDescription()); + if (id != 0) { + DomainVO domain = _domainDao.findById(id); + if (domain != null) { + s_logger.info("createDomain for name: " + domain.getName() + "; uuid: " + domain.getUuid()); + StringBuffer logMesg = new StringBuffer(); + _dbSync.createDomain(domain, logMesg); + } else { + /* could not find db record, resync complete class */ + _dbSync.syncClass(net.juniper.contrail.api.types.Domain.class); + } + } else { + /* Unknown id, resync complete class */ + _dbSync.syncClass(net.juniper.contrail.api.types.Domain.class); + } + } catch (Exception e) { + s_logger.debug(e); + } + } + + public void onProjectCreate(String subject, String topic, org.apache.cloudstack.framework.events.Event event) { + s_logger.info("onProjectCreate; topic: " + topic + "; subject: " + subject); + try { + long id = parseForId(event.getResourceType(), event.getDescription()); + if (id != 0) { + ProjectVO project = _projectDao.findById(id); + if (project != null) { + s_logger.info("createProject for name: " + project.getName() + "; uuid: " + project.getUuid()); + StringBuffer logMesg = new StringBuffer(); + _dbSync.createProject(project, logMesg); + } else { + /* could not find db record, resync complete class */ + _dbSync.syncClass(net.juniper.contrail.api.types.Project.class); + } + } else { + /* Unknown id, resync complete class */ + _dbSync.syncClass(net.juniper.contrail.api.types.Project.class); + } + } catch (Exception e) { + s_logger.info(e); + } + + } + + + @Override + public void subscribe() { + /* subscribe to DB events */ + _messageBus.subscribe(EventTypes.EVENT_PROJECT_CREATE, MessageDispatcher.getDispatcher(this)); + _messageBus.subscribe(EventTypes.EVENT_PROJECT_DELETE, MessageDispatcher.getDispatcher(this)); + _messageBus.subscribe(EventTypes.EVENT_DOMAIN_CREATE, MessageDispatcher.getDispatcher(this)); + _messageBus.subscribe(EventTypes.EVENT_DOMAIN_DELETE, MessageDispatcher.getDispatcher(this)); + _messageBus.subscribe(EventTypes.EVENT_VLAN_IP_RANGE_CREATE, MessageDispatcher.getDispatcher(this)); + _messageBus.subscribe(EventTypes.EVENT_VLAN_IP_RANGE_DELETE, MessageDispatcher.getDispatcher(this)); + } +} + diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManager.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManager.java new file mode 100644 index 00000000000..dcc643cd7a7 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManager.java @@ -0,0 +1,40 @@ +// 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.network.contrail.management; + +import org.apache.cloudstack.network.contrail.api.response.ServiceInstanceResponse; + +import com.cloud.dc.DataCenter; +import com.cloud.network.Network; +import com.cloud.offering.ServiceOffering; +import com.cloud.template.VirtualMachineTemplate; +import com.cloud.user.Account; + +public interface ServiceManager { + /** + * Create a virtual machine that executes a network service appliance (e.g. vSRX) + * @param left Left or inside network (e.g. project network). + * @param right Right or outside network (e.g. public network). + * @return + */ + public ServiceVirtualMachine createServiceInstance(DataCenter zone, Account owner, VirtualMachineTemplate template, + ServiceOffering serviceOffering, String name, Network left, Network right); + + public void startServiceInstance(long instanceId); + public ServiceInstanceResponse createServiceInstanceResponse(long instanceId); +} 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 new file mode 100644 index 00000000000..47fc99e371a --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java @@ -0,0 +1,249 @@ +// 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.network.contrail.management; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; +import javax.inject.Inject; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.dc.DataCenter; +import com.cloud.deploy.DataCenterDeployment; +import com.cloud.event.ActionEvent; +import com.cloud.event.EventTypes; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.Network; +import com.cloud.network.NetworkModel; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.dao.NetworkVO; +import com.cloud.offering.ServiceOffering; +import com.cloud.projects.Project; +import com.cloud.service.ServiceOfferingVO; +import com.cloud.storage.VMTemplateVO; +import com.cloud.template.VirtualMachineTemplate; +import com.cloud.user.Account; +import com.cloud.user.AccountService; +import com.cloud.user.User; +import com.cloud.user.UserVO; +import com.cloud.user.dao.UserDao; +import com.cloud.utils.Pair; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.vm.NicProfile; +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; + +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 net.juniper.contrail.api.ApiConnector; +import net.juniper.contrail.api.types.ServiceInstance; +import net.juniper.contrail.api.types.VirtualNetwork; + +@Local(value = {ServiceManager.class}) +public class ServiceManagerImpl implements ServiceManager { + private static final Logger s_logger = Logger.getLogger(ServiceManager.class); + + @Inject UserDao _userDao; + @Inject UserVmDao _vmDao; + @Inject VirtualMachineManager _vmManager; + @Inject NetworkModel _networkModel; + @Inject AccountService _accountService; + @Inject ContrailManager _manager; + + /** + * In the case of service instance the master object is in the contrail API server. This object stores the + * service instance parameters in the database. + * + * @param owner Used to determine the project. + * @param name Service instance name (user specified). + * @param template Image to execute. + * @param serviceOffering + * @param left Inside network. + * @param right Outside network. + * @return + */ + + + /** + * create a new ServiceVM object. + * @return + */ + @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) { + long id = _vmDao.getNextInSequence(Long.class, "id"); + + DataCenterDeployment plan = new DataCenterDeployment(zone.getId()); + + LinkedHashMap networks = new LinkedHashMap(); + NetworkVO linklocal = (NetworkVO) _networkModel.getSystemNetworkByZoneAndTrafficType(zone.getId(), + TrafficType.Management); + networks.put(linklocal, null); + networks.put((NetworkVO) left, null); + networks.put((NetworkVO) right, null); + + 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); + + // database synchronization code must be able to distinguish service instance VMs. + Map kvmap = new HashMap(); + kvmap.put("service-instance", siObj.getUuid()); + Gson json = new Gson(); + String userData = json.toJson(kvmap); + svm.setUserData(userData); + + try { + _vmManager.allocate(instanceName, template, serviceOffering, networks, + plan, template.getHypervisorType()); + } catch (InsufficientCapacityException ex) { + throw new CloudRuntimeException("Insufficient capacity", ex); + } + CallContext.current().setEventDetails("Vm Id: " + svm.getId()); + return svm; + } + + @Override + public ServiceVirtualMachine createServiceInstance(DataCenter zone, Account owner, VirtualMachineTemplate template, + ServiceOffering serviceOffering, String name, 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. + if (left.getTrafficType() == TrafficType.Guest) { + _networkModel.checkNetworkPermissions(owner, left); + } + if (right.getTrafficType() == TrafficType.Guest) { + _networkModel.checkNetworkPermissions(owner, right); + } + + final ApiConnector api = _manager.getApiConnector(); + final VirtualNetwork netLeft; + try { + netLeft = (VirtualNetwork) api.findById(VirtualNetwork.class, left.getUuid()); + } catch (IOException ex) { + throw new CloudRuntimeException("Unable to read virtual-network object", ex); + } + final VirtualNetwork netRight; + try { + netRight = (VirtualNetwork) api.findById(VirtualNetwork.class, right.getUuid()); + } catch (IOException ex) { + throw new CloudRuntimeException("Unable to read virtual-network object", ex); + } + + net.juniper.contrail.api.types.Project project; + try { + project = _manager.getVncProject(owner.getDomainId(), owner.getAccountId()); + } catch (IOException ex) { + s_logger.warn("read project", ex); + throw new CloudRuntimeException(ex); + } + + try { + final String srvid = api.findByName(ServiceInstance.class, project, name); + if (srvid != null) { + throw new InvalidParameterValueException("service-instance " + name + " already exists uuid=" + srvid); + } + } catch (IOException ex) { + s_logger.warn("service-instance lookup", ex); + throw new CloudRuntimeException(ex); + } + + // 1. Create service-instance. + ServiceInstanceModel serviceModel = new ServiceInstanceModel(project, name, template, serviceOffering, + netLeft, netRight); + + try { + serviceModel.update(_manager.getModelController()); + } catch (Exception ex) { + s_logger.warn("service-instance update", ex); + throw new CloudRuntimeException(ex); + } + + s_logger.debug("service-instance object created"); + + ServiceInstance siObj; + try { + _manager.getDatabase().getServiceInstances().add(serviceModel); + siObj = serviceModel.getServiceInstance(); + } catch (Exception ex){ + s_logger.warn("DB add", ex); + throw new CloudRuntimeException(ex); + } + + // 2. Create one virtual-machine. + String svmName = name.replace(" ", "_") + "-1"; + ServiceVirtualMachine svm = createServiceVM(zone, owner, template, serviceOffering, svmName, siObj, left, right); + + s_logger.debug("created VMInstance " + svm.getUuid()); + + // 3. Create the virtual-machine model and push the update. + VirtualMachineModel instanceModel = new VirtualMachineModel(svm, svm.getUuid()); + _manager.getDatabase().getVirtualMachines().add(instanceModel); + try { + instanceModel.setServiceInstance(_manager.getModelController(), svm, serviceModel); + instanceModel.update(_manager.getModelController()); + } catch (Exception ex) { + s_logger.warn("service virtual-machine update", ex); + throw new CloudRuntimeException(ex); + } + + return svm; + } + + @Override + public void startServiceInstance(long instanceId) { + s_logger.debug("start service instance " + instanceId); + + UserVmVO vm = _vmDao.findById(instanceId); + _vmManager.start(vm.getUuid(), null); + } + + @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()); + response.setProjectName(project.getName()); + } else { + response.setAccountName(owner.getAccountName()); + } + return response; + } + +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceVirtualMachine.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceVirtualMachine.java new file mode 100644 index 00000000000..741879241a3 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceVirtualMachine.java @@ -0,0 +1,30 @@ +// 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.network.contrail.management; + +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.vm.UserVmVO; + +public class ServiceVirtualMachine extends UserVmVO { + public ServiceVirtualMachine(long id, String instanceName, String name, long templateId, long serviceOfferingId, + HypervisorType hypervisorType, long guestOSId, long dataCenterId, long domainId, long accountId, + boolean haEnabled) { + super(id, instanceName, name, templateId, hypervisorType, guestOSId, false, false, domainId, accountId, + serviceOfferingId, null, name, null); + } +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/FloatingIpModel.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/FloatingIpModel.java new file mode 100644 index 00000000000..a640b1ed7bd --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/FloatingIpModel.java @@ -0,0 +1,213 @@ +// 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.network.contrail.model; + +import java.io.IOException; + +import org.apache.cloudstack.network.contrail.management.ContrailManager; +import org.apache.log4j.Logger; + +import com.cloud.exception.InternalErrorException; +import com.cloud.network.PublicIpAddress; +import com.cloud.network.dao.IPAddressVO; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.vm.NicVO; +import com.cloud.vm.VMInstanceVO; + +import net.juniper.contrail.api.types.FloatingIp; +import net.juniper.contrail.api.ApiConnector; + +public class FloatingIpModel extends ModelObjectBase { + private static final Logger s_logger = Logger.getLogger(FloatingIpModel.class); + + private String _uuid; + private long _id; + private String _name; + private String _addr; + private boolean _initialized; + + /* + * cached API server objects + */ + private FloatingIp _fip; + private FloatingIpPoolModel _fipPoolModel; + + public FloatingIpModel(String uuid) { + _uuid = uuid; + } + + public void addToFloatingIpPool(FloatingIpPoolModel fipPoolModel) { + _fipPoolModel = fipPoolModel; + if (fipPoolModel != null) { + fipPoolModel.addSuccessor(this); + } + } + + public void addToVMInterface(VMInterfaceModel vmiModel) { + if (vmiModel != null) { + vmiModel.addSuccessor(this); + } + } + + /* + * Resynchronize internal state from the cloudstack DB object. + */ + public void build(ModelController controller, PublicIpAddress ip) { + setProperties(controller, ip); + } + + @Override + public int compareTo(ModelObject o) { + FloatingIpModel other; + try { + other = (FloatingIpModel) o; + } catch (ClassCastException ex) { + String clsname = o.getClass().getName(); + return FloatingIpModel.class.getName().compareTo(clsname); + } + + return _uuid.compareTo(other._uuid); + } + + @Override + public void delete(ModelController controller) throws IOException { + ApiConnector api = controller.getApiAccessor(); + for (ModelObject successor: successors()) { + successor.delete(controller); + } + + try { + api.delete(FloatingIp.class, _uuid); + } catch (IOException ex) { + s_logger.warn("floating ip delete", ex); + } + } + + @Override + public void destroy(ModelController controller) throws IOException { + delete(controller); + + for (ModelObject successor: successors()) { + successor.destroy(controller); + } + clearSuccessors(); + } + + public String getName() { + return _name; + } + + public String getUuid() { + return _uuid; + } + + + public FloatingIp getFloatingIp() { + return _fip; + } + + /** + * Initialize the object properties based on the DB object. + * Common code between plugin calls and DBSync. + */ + public void setProperties(ModelController controller, PublicIpAddress ip) { + _uuid = ip.getUuid(); + _name = Long.toString(ip.getId()); + _addr = ip.getAddress().addr(); + _id = ip.getId(); + assert _fipPoolModel != null : "floating ip uuid is not set"; + _initialized = true; + } + + @Override + public void update(ModelController controller) throws InternalErrorException, IOException { + + assert _initialized; + + ApiConnector api = controller.getApiAccessor(); + ContrailManager manager = controller.getManager(); + FloatingIp fip = _fip; + + if (_fip == null) { + _fip = fip = (FloatingIp) controller.getApiAccessor().findById(FloatingIp.class, _uuid); + if (fip == null) { + fip = new FloatingIp(); + fip.setUuid(_uuid); + fip.setAddress(_addr); + fip.setName(_name); + fip.setParent(_fipPoolModel.getFloatingIpPool()); + } + } + + IPAddressVO ipAddrVO = controller.getIPAddressDao().findById(_id); + assert ipAddrVO != null : "can not find address object in db"; + Long vmId = ipAddrVO.getAssociatedWithVmId(); + Long networkId = ipAddrVO.getAssociatedWithNetworkId(); + if (vmId == null || networkId == null) { + s_logger.debug("Floating ip is not yet associated to either vm or network"); + return; + } + NicVO nic = controller.getNicDao().findByNtwkIdAndInstanceId(networkId, vmId); + assert nic != null : "can not find nic for the given network and vm in db"; + + VMInstanceVO vm = controller.getVmDao().findById(vmId); + assert vm != null : "can not find vm in db"; + + VirtualMachineModel vmModel = manager.getDatabase().lookupVirtualMachine(vm.getUuid()); + assert vmModel != null : "can not find vm model"; + + VMInterfaceModel vmiModel = vmModel.getVMInterface(nic.getUuid()); + assert vmiModel != null && vmiModel.getVMInterface() != null : "can not find virtual machine interface"; + + fip.setVirtualMachineInterface(vmiModel.getVMInterface()); + + if (_fip == null) { + try { + api.create(fip); + } catch (Exception ex) { + s_logger.debug("floating ip create", ex); + throw new CloudRuntimeException("Failed to create floating ip", ex); + } + _fip = fip; + } else { + try { + api.update(fip); + } catch (IOException ex) { + s_logger.warn("floating ip update", ex); + throw new CloudRuntimeException("Unable to update floating ip object", ex); + } + } + + addToVMInterface(vmiModel); + + for (ModelObject successor: successors()) { + successor.update(controller); + } + } + + @Override + public boolean verify(ModelController controller) { + assert _initialized : "initialized is false"; + return false; + } + + @Override + public boolean compare(ModelController controller, ModelObject o) { + return true; + } +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/FloatingIpPoolModel.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/FloatingIpPoolModel.java new file mode 100644 index 00000000000..1205c8753f3 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/FloatingIpPoolModel.java @@ -0,0 +1,170 @@ +// 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.network.contrail.model; + +import java.io.IOException; +import java.util.TreeSet; + +import org.apache.cloudstack.network.contrail.management.ContrailManager; +import org.apache.log4j.Logger; + +import com.cloud.exception.InternalErrorException; +import com.cloud.utils.exception.CloudRuntimeException; + +import net.juniper.contrail.api.types.FloatingIpPool; +import net.juniper.contrail.api.ApiConnector; + +public class FloatingIpPoolModel extends ModelObjectBase { + private static final Logger s_logger = Logger.getLogger(FloatingIpPoolModel.class); + + private String _name; + + /* + * cached API server objects + */ + private FloatingIpPool _fipPool; + private VirtualNetworkModel _vnModel; + + public FloatingIpPoolModel() { + + } + + public void addToVirtualNetwork(VirtualNetworkModel vnModel) { + _vnModel = vnModel; + if (vnModel != null) { + vnModel.addSuccessor(this); + } + } + + public FloatingIpModel getFloatingIpModel(String uuid) { + TreeSet tree = successors(); + FloatingIpModel fipKey = new FloatingIpModel(uuid); + FloatingIpModel current = (FloatingIpModel) tree.ceiling(fipKey); + if (current != null && current.getUuid().equals(uuid)) { + return current; + } + return null; + } + + /* + * Resynchronize internal state from the cloudstack DB object. + */ + public void build(ModelController controller) { + setProperties(controller); + } + + @Override + public int compareTo(ModelObject o) { + /* there can be only one instance */ + return 0; + } + + @Override + public void delete(ModelController controller) throws IOException { + ApiConnector api = controller.getApiAccessor(); + for (ModelObject successor: successors()) { + successor.delete(controller); + } + try { + if (_fipPool != null) { + api.delete(_fipPool); + } + _fipPool = null; + } catch (IOException ex) { + s_logger.warn("floating ip pool delete", ex); + } + } + + @Override + public void destroy(ModelController controller) throws IOException { + delete(controller); + for (ModelObject successor: successors()) { + successor.destroy(controller); + } + clearSuccessors(); + } + + public String getName() { + return _name; + } + + public FloatingIpPool getFloatingIpPool() { + return _fipPool; + } + + /** + * Initialize the object properties based on the DB object. + * Common code between plugin calls and DBSync. + */ + public void setProperties(ModelController controller) { + _name = "PublicIpPool"; + assert _vnModel != null : "vn nodel is not initialized"; + } + + @Override + public void update(ModelController controller) throws InternalErrorException, IOException { + + assert _vnModel != null : "vn model is not set"; + + ApiConnector api = controller.getApiAccessor(); + ContrailManager manager = controller.getManager(); + FloatingIpPool fipPool = _fipPool; + + if (fipPool == null) { + String fipPoolName = manager.getDefaultPublicNetworkFQN() + ":PublicIpPool"; + _fipPool = fipPool = (FloatingIpPool) controller.getApiAccessor().findByFQN(FloatingIpPool.class, fipPoolName); + if (fipPool == null) { + fipPool = new FloatingIpPool(); + fipPool.setName(_name); + fipPool.setParent(_vnModel.getVirtualNetwork()); + } + } + + if (_fipPool == null) { + try { + api.create(fipPool); + } catch (Exception ex) { + s_logger.debug("floating ip pool create", ex); + throw new CloudRuntimeException("Failed to create floating ip pool", ex); + } + _fipPool = fipPool; + } else { + try { + api.update(fipPool); + } catch (IOException ex) { + s_logger.warn("floating ip pool update", ex); + throw new CloudRuntimeException("Unable to update floating ip ppol object", ex); + } + } + + for (ModelObject successor: successors()) { + successor.update(controller); + } + } + + @Override + public boolean verify(ModelController controller) { + assert _vnModel != null : "vn model is not set"; + return false; + } + + @Override + public boolean compare(ModelController controller, ModelObject o) { + return true; + } +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/InstanceIpModel.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/InstanceIpModel.java new file mode 100644 index 00000000000..7588ba74fcd --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/InstanceIpModel.java @@ -0,0 +1,174 @@ +// 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.network.contrail.model; + +import java.io.IOException; + +import org.apache.log4j.Logger; + +import net.juniper.contrail.api.ObjectReference; +import net.juniper.contrail.api.types.InstanceIp; +import net.juniper.contrail.api.types.VirtualMachineInterface; +import net.juniper.contrail.api.types.VirtualNetwork; +import net.juniper.contrail.api.ApiConnector; + +import com.cloud.exception.InternalErrorException; + +public class InstanceIpModel extends ModelObjectBase { + private static final Logger s_logger = Logger.getLogger(InstanceIpModel.class); + + private String _name; + private String _uuid; + + private String _ipAddress; + + private VMInterfaceModel _vmiModel; + + public InstanceIpModel(String vmName, int deviceId) { + _name = vmName + '-' + deviceId; + } + + public void addToVMInterface(VMInterfaceModel vmiModel) { + _vmiModel = vmiModel; + if (vmiModel != null) { + vmiModel.addSuccessor(this); + s_logger.debug("vmiModel has " + vmiModel.successors().size() + " IP addresses"); + } + } + + @Override + public int compareTo(ModelObject o) { + InstanceIpModel other; + try { + other = (InstanceIpModel) o; + } catch (ClassCastException ex) { + String clsname = o.getClass().getName(); + return InstanceIpModel.class.getName().compareTo(clsname); + } + return _name.compareTo(other._name); + } + + @Override + public void delete(ModelController controller) throws IOException { + ApiConnector api = controller.getApiAccessor(); + if (_uuid != null) { + api.delete(InstanceIp.class, _uuid); + } + _uuid = null; + } + + @Override + public void destroy(ModelController controller) throws IOException { + } + + public String getAddress() { + return _ipAddress; + } + + public String getName() { + return _name; + } + + public void setAddress(String ipaddress) { + _ipAddress = ipaddress; + } + + @Override + public void update(ModelController controller) + throws InternalErrorException, IOException { + assert _vmiModel != null; + + ApiConnector api = controller.getApiAccessor(); + VirtualNetworkModel vnModel = _vmiModel.getVirtualNetworkModel(); + assert vnModel != null; + + VirtualMachineInterface vmi = _vmiModel.getVMInterface(); + VirtualNetwork vnet = vnModel.getVirtualNetwork(); + if (vnet == null) { + vnet = (VirtualNetwork) api.findById(VirtualNetwork.class, _vmiModel.getNetworkUuid()); + } + + String ipid = api.findByName(InstanceIp.class, null, _name); + if (ipid == null) { + InstanceIp ip_obj = new InstanceIp(); + ip_obj.setName(_name); + ip_obj.setVirtualNetwork(vnet); + if (_ipAddress != null) { + ip_obj.setAddress(_ipAddress); + } + ip_obj.setVirtualMachineInterface(vmi); + if (!api.create(ip_obj)) { + throw new InternalErrorException("Unable to create instance-ip " + _name); + } + api.read(ip_obj); + _uuid = ip_obj.getUuid(); + if (_ipAddress == null) { + if (!api.read(ip_obj)) { + throw new InternalErrorException("Unable to read instance-ip " + _name); + } + } + _ipAddress = ip_obj.getAddress(); + } else { + // Ensure that the instance-ip has the correct value and is pointing at the VMI. + InstanceIp ip_obj = (InstanceIp) api.findById(InstanceIp.class, ipid); + if (ip_obj == null) { + throw new InternalErrorException("Unable to read instance-ip " + _name); + } + boolean update = false; + String ipnet_id = ObjectReference.getReferenceListUuid(ip_obj.getVirtualNetwork()); + if (ipnet_id == null || !ipnet_id.equals(_vmiModel.getNetworkUuid())) { + ip_obj.setVirtualNetwork(vnet); + update = true; + } + + if (_ipAddress != null && !ip_obj.getAddress().equals(_ipAddress)) { + ip_obj.setAddress(_ipAddress); + update = true; + } + + String vmi_id = ObjectReference.getReferenceListUuid(ip_obj.getVirtualMachineInterface()); + if (vmi_id == null || !vmi_id.equals(_vmiModel.getUuid())) { + if (vmi != null) { + ip_obj.setVirtualMachineInterface(vmi); + update = true; + } + } + + if (update && !api.update(ip_obj)) { + throw new InternalErrorException("Unable to update instance-ip: " + ip_obj.getName()); + } + api.read(ip_obj); + _uuid = ip_obj.getUuid(); + _ipAddress = ip_obj.getAddress(); + } + } + + @Override + public boolean verify(ModelController controller) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean compare(ModelController controller, ModelObject current) { + // TODO Auto-generated method stub + return false; + } + + +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ModelController.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ModelController.java new file mode 100644 index 00000000000..8d57879a399 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ModelController.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 org.apache.cloudstack.network.contrail.model; + +import org.apache.cloudstack.network.contrail.management.ContrailManager; + +import com.cloud.dc.dao.VlanDao; +import com.cloud.network.dao.IPAddressDao; +import com.cloud.network.dao.NetworkDao; +import com.cloud.vm.dao.NicDao; +import com.cloud.vm.dao.UserVmDao; + +import net.juniper.contrail.api.ApiConnector; + +/** + * Collection of state necessary for model object to update the Contrail API server. + * + */ +public class ModelController { + ApiConnector _api; + ContrailManager _manager; + UserVmDao _vmDao; + NetworkDao _networkDao; + NicDao _nicDao; + VlanDao _vlanDao; + IPAddressDao _ipAddressDao; + + public ModelController(ContrailManager manager, ApiConnector api, UserVmDao vmDao, NetworkDao networkDao, + NicDao nicDao, VlanDao vlanDao, IPAddressDao ipAddressDao) { + _manager = manager; + assert api != null; + _api = api; + assert vmDao != null; + _vmDao = vmDao; + assert networkDao != null; + _networkDao = networkDao; + assert nicDao != null; + _nicDao = nicDao; + assert vlanDao != null; + _vlanDao = vlanDao; + assert ipAddressDao != null; + _ipAddressDao = ipAddressDao; + } + ApiConnector getApiAccessor() { + return _api; + } + ContrailManager getManager() { + return _manager; + } + + UserVmDao getVmDao() { + return _vmDao; + } + + NetworkDao getNetworkDao() { + return _networkDao; + } + + NicDao getNicDao() { + return _nicDao; + } + + VlanDao getVlanDao() { + return _vlanDao; + } + + IPAddressDao getIPAddressDao() { + return _ipAddressDao; + } +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ModelObject.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ModelObject.java new file mode 100644 index 00000000000..71d28ac5867 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ModelObject.java @@ -0,0 +1,118 @@ +// 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.network.contrail.model; + +import java.io.IOException; +import java.lang.ref.WeakReference; +import java.util.TreeSet; + +import com.cloud.exception.InternalErrorException; + +/** + * ModelObject + * + * A model object represents the desired state of the system. + * + * The object constructor should set the uuid and the internal id of the cloudstack objects. + * + * The build method reads the master database (typically cloudstack mysql) and derives the state that + * we wish to reflect in the contrail API. This method should not modify the Contrail API state. + * + * The verify method reads the API server state and compares with cached properties. + * + * The update method pushes updates to the contrail API server. + */ +public interface ModelObject { + public static class ModelReference implements Comparable { + WeakReference reference; + ModelReference(ModelObject obj) { + reference = new WeakReference(obj); + } + + @Override + public int compareTo(ModelReference other) { + ModelObject lhs = reference.get(); + ModelObject rhs = other.reference.get(); + if (lhs == null) { + if (rhs == null) { + return 0; + } + return -1; + } + + return lhs.compareTo(rhs); + } + @Override + public boolean equals(Object other) { + try { + ModelReference rhs = (ModelReference) other; + return compareTo(rhs) == 0; + } catch (ClassCastException ex) { + } + return false; + } + public ModelObject get() { + return reference.get(); + } + }; + + public void addSuccessor(ModelObject child); + + public TreeSet ancestors(); + public void clearSuccessors(); + public int compareTo(ModelObject o); + + /** + * Delete the object from the API server. + * @param controller + * @throws IOException + */ + public void delete(ModelController controller) throws IOException; + + /** + * Deletes the object from the data model graph. + * + * @param controller + * @throws IOException + */ + public void destroy(ModelController controller) throws IOException; + + public void removeSuccessor(ModelObject child); + + public TreeSet successors(); + + /** + * Push updates to Contrail API server. This API is only valid for objects in the database. + * @param controller + * @throws IOException + * @throws InternalErrorException + */ + public void update(ModelController controller) throws InternalErrorException, IOException; + + /** + * Check that the state of the current object matches the state of the API server. + * @param controller + * @return + */ + public boolean verify(ModelController controller); + + /* + * Compare the state of existing model object with latest model object + */ + public boolean compare(ModelController controller, ModelObject current); +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ModelObjectBase.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ModelObjectBase.java new file mode 100644 index 00000000000..f22c7c546a3 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ModelObjectBase.java @@ -0,0 +1,111 @@ +// 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.network.contrail.model; + +import java.util.Comparator; +import java.util.TreeSet; + +public abstract class ModelObjectBase implements ModelObject { + public static class UuidComparator implements Comparator { + @Override + public int compare(ModelObject lhs, ModelObject rhs) { + if (lhs == null) { + if (rhs == null) { + return 0; + } + return -1; + } + if (rhs == null) { + return 1; + } + return lhs.compareTo(rhs); + } + } + private TreeSet _ancestors; + + private TreeSet _successors; + + ModelObjectBase() { + _ancestors = new TreeSet(); + _successors = new TreeSet(new UuidComparator()); + } + + @Override + public void addSuccessor(ModelObject child) { + _successors.add(child); + ModelObjectBase base = (ModelObjectBase) child; + base._ancestors.add(new ModelReference(this)); + } + + @Override + public TreeSet ancestors() { + return _ancestors; + } + + private void clearAncestorReference(ModelObjectBase child) { + ModelReference ref = null; + for (ModelReference objref : child._ancestors) { + if (objref.get() == this) { + ref = objref; + break; + } + } + if (ref != null) { + child._ancestors.remove(ref); + } + } + + @Override + public void clearSuccessors() { + for (ModelObject successor : _successors) { + clearAncestorReference((ModelObjectBase) successor); + } + _successors.clear(); + } + + @Override + public boolean equals(Object rhs) { + ModelObject other; + try { + other = (ModelObject) rhs; + } catch (ClassCastException ex) { + return false; + } + return compareTo(other) == 0; + } + + @Override + protected void finalize() { + clearSuccessors(); + } + + public boolean hasDescendents() { + return !successors().isEmpty(); + } + + @Override + public void removeSuccessor(ModelObject child) { + clearAncestorReference((ModelObjectBase) child); + _successors.remove(child); + } + + @Override + public TreeSet successors() { + return _successors; + } +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ServiceInstanceModel.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ServiceInstanceModel.java new file mode 100644 index 00000000000..20b80bead4c --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ServiceInstanceModel.java @@ -0,0 +1,320 @@ +// 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.network.contrail.model; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import javax.inject.Inject; + +import org.apache.cloudstack.network.contrail.management.ContrailManager; +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; + +import net.juniper.contrail.api.ObjectReference; +import net.juniper.contrail.api.types.NetworkPolicy; +import net.juniper.contrail.api.types.PolicyEntriesType; +import net.juniper.contrail.api.types.PolicyEntriesType.PolicyRuleType; +import net.juniper.contrail.api.types.Project; +import net.juniper.contrail.api.types.ServiceInstance; +import net.juniper.contrail.api.types.ServiceInstanceType; +import net.juniper.contrail.api.types.ServiceTemplate; +import net.juniper.contrail.api.types.ServiceTemplateType; +import net.juniper.contrail.api.types.VirtualNetwork; +import net.juniper.contrail.api.types.VirtualNetworkPolicyType; +import net.juniper.contrail.api.ApiConnector; + +import com.cloud.offering.ServiceOffering; +import com.cloud.template.VirtualMachineTemplate; +import com.cloud.utils.exception.CloudRuntimeException; + +public class ServiceInstanceModel extends ModelObjectBase { + private static final Logger s_logger = Logger.getLogger(ServiceInstanceModel.class); + + private String _uuid; + private String _fq_name; + private String _projectId; + private String _mgmtName; + private String _leftName; + private String _rightName; + + private String _templateName; + private String _templateId; + private String _templateUrl; + private VirtualNetwork _left; + private VirtualNetwork _right; + private ServiceTemplate _tmpl; + private ServiceInstance _serviceInstance; + private NetworkPolicy _policy; + + /** + * Create a ServiceInstance as result of an API call. + * + * @param owner + * @param name + * @param template + * @param serviceOffering + * @param left + * @param right + */ + public ServiceInstanceModel(Project project, String name, VirtualMachineTemplate template, + ServiceOffering serviceOffering, VirtualNetwork left, VirtualNetwork right) { + String parent_name; + if (project != null) { + parent_name = StringUtils.join(project.getQualifiedName(), ':'); + } else { + parent_name = ContrailManager.VNC_ROOT_DOMAIN + ":" + ContrailManager.VNC_DEFAULT_PROJECT; + } + _fq_name = parent_name + ":" + name; + + _mgmtName = ContrailManager.VNC_ROOT_DOMAIN + ":" + ContrailManager.VNC_DEFAULT_PROJECT + ":" + + ContrailManager.managementNetworkName; + _left = left; + _right = right; + _leftName = StringUtils.join(left.getQualifiedName(), ":"); + _rightName = StringUtils.join(right.getQualifiedName(), ":"); + + _templateName = template.getName(); + _templateId = template.getUuid(); + _templateUrl = template.getUrl(); + + _projectId = project.getUuid(); + } + + /** + * Create an empty ServiceInstance. + * @param uuid + */ + public ServiceInstanceModel(String uuid) { + _uuid = uuid; + } + + public String getQualifiedName() { + return _fq_name; + } + + public String getName() { + return _fq_name.substring(_fq_name.lastIndexOf(':') + 1); + } + + private void applyNetworkPolicy(ModelController controller, NetworkPolicy policy, + VirtualNetwork left, VirtualNetwork right) { + left.setNetworkPolicy(policy, new VirtualNetworkPolicyType( + new VirtualNetworkPolicyType.SequenceType(1, 0), null)); + // TODO: network_ipam_refs attr is missing + left.clearNetworkIpam(); + try { + ApiConnector api = controller.getApiAccessor(); + api.update(left); + } catch (IOException ex) { + throw new CloudRuntimeException("Unable to update virtual-network", ex); + } + + right.setNetworkPolicy(policy, new VirtualNetworkPolicyType( + new VirtualNetworkPolicyType.SequenceType(1, 0), null)); + // TODO: network_ipam_refs attr is missing + right.clearNetworkIpam(); + try { + ApiConnector api = controller.getApiAccessor(); + api.update(right); + } catch (IOException ex) { + throw new CloudRuntimeException("Unable to update virtual-network", ex); + } + } + + /** + * Recreate the model object from the Contrail API which is the master for this type of object. + * @param siObj + */ + public void build(ModelController controller, ServiceInstance siObj) { + ApiConnector api = controller.getApiAccessor(); + _serviceInstance = siObj; + _fq_name = StringUtils.join(siObj.getQualifiedName(), ':'); + ServiceInstanceType props = siObj.getProperties(); + // TODO: read management network names and cache network objects. + ObjectReference ref = siObj.getServiceTemplate().get(0); + if (ref != null) { + try { + ServiceTemplate tmpl = (ServiceTemplate) api.findById(ServiceTemplate.class, ref.getUuid()); + _templateId = tmpl.getUuid(); + } catch (IOException ex) { + s_logger.warn("service-template read", ex); + } + } + try { + Project project = (Project) api.findById(Project.class, siObj.getParentUuid()); + if (project != null) { + _projectId = project.getUuid(); + } + String policyId = api.findByName(NetworkPolicy.class, project, siObj.getName()); + if (policyId != null) { + _policy = (NetworkPolicy) api.findById(NetworkPolicy.class, policyId); + } + } catch (IOException ex) { + s_logger.warn("network-policy read", ex); + } + } + + @Override + public int compareTo(ModelObject o) { + ServiceInstanceModel other; + try { + other = (ServiceInstanceModel) o; + } catch (ClassCastException ex) { + String clsname = o.getClass().getName(); + return ServiceInstanceModel.class.getName().compareTo(clsname); + } + return _fq_name.compareTo(other._fq_name); + } + + private ServiceInstance createServiceInstance(ModelController controller) { + Project project = null; + if (_projectId != null) { + try { + ApiConnector api = controller.getApiAccessor(); + project = (Project) api.findById(Project.class, _projectId); + } catch (IOException ex) { + s_logger.warn("project read", ex); + throw new CloudRuntimeException("Unable to create service-instance object", ex); + } + } + + ServiceInstance si_obj = new ServiceInstance(); + if (project != null) { + si_obj.setParent(project); + } + si_obj.setName(getName()); + si_obj.setServiceTemplate(_tmpl); + si_obj.setProperties(new ServiceInstanceType(false, _mgmtName, _leftName, null, _rightName, null, + new ServiceInstanceType.ServiceScaleOutType(1, false))); + try { + ApiConnector api = controller.getApiAccessor(); + api.create(si_obj); + } catch (IOException ex) { + s_logger.warn("service-instance create", ex); + throw new CloudRuntimeException("Unable to create service-instance object", ex); + } + + return si_obj; + } + + private NetworkPolicy createServicePolicy(ModelController controller) { + NetworkPolicy policy = new NetworkPolicy(); + policy.setParent(_serviceInstance.getParent()); + policy.setName(_serviceInstance.getName()); + PolicyEntriesType policy_map = new PolicyEntriesType(); + List srcList = new ArrayList(); + srcList.add(new PolicyRuleType.AddressType(null, _leftName, null)); + List dstList = new ArrayList(); + dstList.add(new PolicyRuleType.AddressType(null, _rightName, null)); + List siList = new ArrayList(); + siList.add(StringUtils.join(_serviceInstance.getQualifiedName(), ':')); + List portAny = new ArrayList(); + portAny.add(new PolicyRuleType.PortType(0, 65535)); + + PolicyRuleType rule = new PolicyRuleType( + new PolicyRuleType.SequenceType(1, 0), /* uuid */ null, "<>", "any", + srcList, portAny, /* application */ null, dstList, portAny, + new PolicyRuleType.ActionListType("pass", "in-network", siList, null)); + policy_map.addPolicyRule(rule); + policy.setEntries(policy_map); + + try { + ApiConnector api = controller.getApiAccessor(); + if (!api.create(policy)) { + throw new CloudRuntimeException("Unable to create network-policy"); + } + } catch (IOException ex) { + throw new CloudRuntimeException("Unable to create network-policy", ex); + } + return policy; + } + + @Override + public void delete(ModelController controller) throws IOException { + ApiConnector api = controller.getApiAccessor(); + if (_serviceInstance != null) { + api.delete(_serviceInstance); + } + } + + @Override + public void destroy(ModelController controller) throws IOException { + } + + public ServiceInstance getServiceInstance() { + return _serviceInstance; + } + + public String getUuid() { + return _uuid; + } + + private ServiceTemplate locateServiceTemplate(ModelController controller) { + ServiceTemplate tmpl; + try { + ApiConnector api = controller.getApiAccessor(); + tmpl = (ServiceTemplate) api.findById(ServiceTemplate.class, _templateId); + } catch (IOException ex) { + s_logger.warn("service-template read", ex); + throw new CloudRuntimeException("Unable to create service-template object", ex); + } + if (tmpl == null) { + tmpl = new ServiceTemplate(); + tmpl.setName(_templateName); + tmpl.setUuid(_templateId); + ServiceTemplateType props = new ServiceTemplateType("in-network", null, _templateUrl, false, null); + tmpl.setProperties(props); + try { + ApiConnector api = controller.getApiAccessor(); + api.create(tmpl); + } catch (IOException ex) { + throw new CloudRuntimeException("Unable to create service-template object", ex); + } + } + return tmpl; + } + + @Override + public void update(ModelController controller) { + _tmpl = locateServiceTemplate(controller); + if (_serviceInstance == null) { + _serviceInstance = createServiceInstance(controller); + } + _uuid = _serviceInstance.getUuid(); + if (_policy == null) { + _policy = createServicePolicy(controller); + // TODO: update the network model objects and call update + applyNetworkPolicy(controller, _policy, _left, _right); + } + } + + @Override + public boolean verify(ModelController controller) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean compare(ModelController controller, ModelObject current) { + // TODO Auto-generated method stub + return true; + } + +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VMInterfaceModel.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VMInterfaceModel.java new file mode 100644 index 00000000000..347656968e4 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VMInterfaceModel.java @@ -0,0 +1,265 @@ +// 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.network.contrail.model; + +import java.io.IOException; + +import org.apache.cloudstack.network.contrail.management.ContrailManager; +import org.apache.log4j.Logger; + +import net.juniper.contrail.api.types.MacAddressesType; +import net.juniper.contrail.api.types.VirtualMachineInterface; +import net.juniper.contrail.api.types.VirtualMachineInterfacePropertiesType; +import net.juniper.contrail.api.ApiConnector; + +import com.cloud.exception.InternalErrorException; +import com.cloud.network.Network; +import com.cloud.vm.NicVO; +import com.cloud.vm.VMInstanceVO; + +public class VMInterfaceModel extends ModelObjectBase { + private static final Logger s_logger = Logger.getLogger(VMInterfaceModel.class); + + private String _uuid; + + /** + * properties + */ + private String _vmName; + private int _deviceId; + private boolean _netActive; + private boolean _nicActive; + private String _serviceTag; + private String _networkId; + private String _macAddress; + + /** + * cached objects + */ + private VirtualMachineModel _vmModel; + private VirtualNetworkModel _vnModel; + private VirtualMachineInterface _vmi; + + public VMInterfaceModel(String uuid) { + _uuid = uuid; + } + + public void addToVirtualMachine(VirtualMachineModel vmModel) { + _vmModel = vmModel; + if (vmModel != null) { + vmModel.addSuccessor(this); + } + } + + public void addToVirtualNetwork(VirtualNetworkModel vnModel) { + _vnModel = vnModel; + if (vnModel != null) { + vnModel.addSuccessor(this); + } + } + + public void build(ModelController controller, VMInstanceVO instance, NicVO nic) throws IOException { + setProperties(controller, instance, nic); + + InstanceIpModel ipModel = getInstanceIp(); + String ipAddress = nic.getIp4Address(); + if (ipAddress != null) { + if (ipModel == null) { + ipModel = new InstanceIpModel(_vmName, _deviceId); + ipModel.addToVMInterface(this); + } + ipModel.setAddress(ipAddress); + } else if (ipModel != null) { + removeSuccessor(ipModel); + } + + _macAddress = nic.getMacAddress(); + } + + @Override + public int compareTo(ModelObject o) { + VMInterfaceModel other; + try { + other = (VMInterfaceModel) o; + } catch (ClassCastException ex) { + String clsname = o.getClass().getName(); + return VMInterfaceModel.class.getName().compareTo(clsname); + } + return _uuid.compareTo(other._uuid); + } + + @Override + public void delete(ModelController controller) throws IOException { + for (ModelObject successor: successors()) { + successor.delete(controller); + } + + ApiConnector api = controller.getApiAccessor(); + api.delete(VirtualMachineInterface.class, _uuid); + } + + @Override + public void destroy(ModelController controller) throws IOException { + delete(controller); + + for (ModelObject successor: successors()) { + successor.destroy(controller); + } + clearSuccessors(); + } + + public InstanceIpModel getInstanceIp() { + for (ModelObject successor : successors()) { + if (successor.getClass() == InstanceIpModel.class) { + return (InstanceIpModel) successor; + } + } + return null; + } + + public String getNetworkUuid() { + return _networkId; + } + + public VirtualNetworkModel getVirtualNetworkModel() { + return _vnModel; + } + + public String getUuid() { + return _uuid; + } + + public VirtualMachineInterface getVMInterface() { + return _vmi; + } + + public void setProperties(ModelController controller, VMInstanceVO instance, NicVO nic) throws IOException { + _vmName = instance.getInstanceName(); + _deviceId = nic.getDeviceId(); + Network network = controller.getNetworkDao().findById(nic.getNetworkId()); + + switch (nic.getState()) { + case Allocated: + case Reserved: + _nicActive = true; + break; + default: + _nicActive = false; + break; + } + + switch (network.getState()) { + case Implemented: + case Setup: + _netActive = true; + break; + default: + _netActive = false; + break; + } + assert _vnModel != null; + _networkId = _vnModel.getUuid(); + } + + public void setActive() { + _nicActive = true; + } + + void setServiceTag(String tag) { + _serviceTag = tag; + } + + @Override + public void update(ModelController controller) throws InternalErrorException, IOException { + if (!_netActive || !_nicActive) { + s_logger.debug("vm interface update, _netActive: " + _netActive + ", _nicActive: " + _nicActive); + delete(controller); + return; + } + if (_vmModel == null) { + throw new InternalErrorException("virtual-machine not set on VMI: " + _uuid); + } + if (_vnModel == null) { + throw new InternalErrorException("virtual-network not set on VMI: " + _uuid); + } + ContrailManager manager = controller.getManager(); + ApiConnector api = controller.getApiAccessor(); + + VirtualMachineInterface vmi = (VirtualMachineInterface) api.findById(VirtualMachineInterface.class, _uuid); + boolean create = false; + if (vmi == null) { + create = true; + vmi = new VirtualMachineInterface(); + vmi.setParent(_vmModel.getVirtualMachine()); + vmi.setName(manager.getVifNameByVmName(_vmModel.getInstanceName(), _deviceId)); + vmi.setUuid(_uuid); + vmi.setVirtualNetwork(_vnModel.getVirtualNetwork()); + } else { + // Do not try to update VMI to routing-instance references. These are managed by schema-transformer. + vmi.clearRoutingInstance(); + } + _vmi = vmi; + if (_macAddress != null) { + MacAddressesType mac = new MacAddressesType(); + mac.addMacAddress(_macAddress); + vmi.setMacAddresses(mac); + } + + if (_serviceTag != null) { + vmi.setProperties(new VirtualMachineInterfacePropertiesType(_serviceTag, null)); + } + + if (create) { + if (!api.create(vmi)) { + throw new InternalErrorException("Unable to create virtual-machine-interface " + _uuid); + } + } else { + if (!api.update(vmi)) { + throw new InternalErrorException("Unable to update virtual-machine-interface " + _uuid); + } + } + + api.read(vmi); + + int ipCount = 0; + for (ModelObject successor: successors()) { + if (successor.getClass() == InstanceIpModel.class) { + ipCount++; + } + successor.update(controller); + } + // TODO: if there are no instance-ip successors present and we have an instance-ip object reference + // delete the object. + if (ipCount == 0) { + s_logger.warn("virtual-machine-interface " + _uuid + " has no instance-ip"); + } + } + + @Override + public boolean verify(ModelController controller) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean compare(ModelController controller, ModelObject current) { + // TODO Auto-generated method stub + return true; + } + +} 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 new file mode 100644 index 00000000000..ec20a9417ec --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VirtualMachineModel.java @@ -0,0 +1,349 @@ +// 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.network.contrail.model; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.TreeSet; + +import org.apache.cloudstack.network.contrail.management.ContrailManager; +import org.apache.log4j.Logger; + +import com.cloud.exception.InternalErrorException; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.uservm.UserVm; +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; + +import net.juniper.contrail.api.types.Project; +import net.juniper.contrail.api.types.ServiceInstance; +import net.juniper.contrail.api.types.VirtualMachine; +import net.juniper.contrail.api.ApiConnector; + +public class VirtualMachineModel extends ModelObjectBase { + private static final Logger s_logger = Logger.getLogger(VirtualMachineModel.class); + + private String _uuid; + private long _instanceId; + + /* + * current state for object properties + */ + private boolean _initialized; + private boolean _active; + private String _serviceUuid; + private String _instanceName; + private String _projectId; + + /* + * cached API server objects + */ + private VirtualMachine _vm; + private ServiceInstanceModel _serviceModel; + + public VirtualMachineModel(VMInstanceVO vm, String uuid) { + _uuid = uuid; + if (vm != null) { + _instanceId = vm.getId(); + _instanceName = vm.getInstanceName(); + } + } + + /** + * Resynchronize internal state from the cloudstack DB object. + * @param instance + */ + public void build(ModelController controller, VMInstanceVO instance) { + setProperties(controller, instance); + UserVm userVm = controller.getVmDao().findById(instance.getId()); + if (userVm != null && userVm.getUserData() != null) { + s_logger.debug("vm " + instance.getInstanceName() + " user data: " + userVm.getUserData()); + final Gson json = new Gson(); + Map kvmap = json.fromJson(userVm.getUserData(), + new TypeToken>(){}.getType()); + String data = kvmap.get("service-instance"); + if (data != null) { + /* link the object with the service instance */ + buildServiceInstance(controller, data); + } + } + } + + /** + * Link the virtual machine with the service instance when recovering state from database. + * + * @param controller + * @param serviceUuid + */ + private void buildServiceInstance(ModelController controller, String serviceUuid) { + ContrailManager manager = controller.getManager(); + ApiConnector api = controller.getApiAccessor(); + _serviceUuid = serviceUuid; + + ServiceInstanceModel siModel = manager.getDatabase().lookupServiceInstance(serviceUuid); + if (siModel == null) { + ServiceInstance siObj; + try { + siObj = (ServiceInstance) api.findById(ServiceInstance.class, serviceUuid); + } catch (IOException ex) { + s_logger.warn("service-instance read", ex); + throw new CloudRuntimeException("Unable to read service-instance object", ex); + } + if (siObj == null) { + siModel = new ServiceInstanceModel(serviceUuid); + siModel.build(controller, siObj); + } + } + _serviceModel = siModel; + } + + @Override + public int compareTo(ModelObject o) { + VirtualMachineModel other; + try { + other = (VirtualMachineModel) o; + } catch (ClassCastException ex) { + String clsname = o.getClass().getName(); + return VirtualMachineModel.class.getName().compareTo(clsname); + } + return _uuid.compareTo(other._uuid); + } + + @Override + public void delete(ModelController controller) throws IOException { + ApiConnector api = controller.getApiAccessor(); + for (ModelObject successor: successors()) { + successor.delete(controller); + } + + try { + api.delete(VirtualMachine.class, _uuid); + } catch (IOException ex) { + s_logger.warn("virtual-machine delete", ex); + } + + + if (_serviceModel != null) { + _serviceModel.delete(controller); + } + } + + @Override + public void destroy(ModelController controller) throws IOException { + delete(controller); + + for (ModelObject successor: successors()) { + successor.destroy(controller); + } + + clearSuccessors(); + + if (_serviceModel != null) { + _serviceModel.removeSuccessor(this); + _serviceModel.destroy(controller); + ContrailManager manager = controller.getManager(); + manager.getDatabase().getServiceInstances().remove(_serviceModel); + _serviceModel = null; + } + } + + public String getInstanceName() { + return _instanceName; + } + + public String getUuid() { + return _uuid; + } + + + public VirtualMachine getVirtualMachine() { + return _vm; + } + + public VMInterfaceModel getVMInterface(String uuid) { + TreeSet tree = successors(); + VMInterfaceModel vmiKey = new VMInterfaceModel(uuid); + VMInterfaceModel current = (VMInterfaceModel) tree.ceiling(vmiKey); + if (current != null && current.getUuid().equals(uuid)) { + return current; + } + return null; + } + + public boolean isActive() { + return _active; + } + + boolean isActiveInstance(VMInstanceVO instance) { + switch (instance.getState()) { + case Migrating: + case Starting: + case Running: + case Shutdowned: + case Stopped: + case Stopping: + return true; + + case Destroyed: + case Error: + case Expunging: + return false; + + default: + s_logger.warn("Unknown VMInstance state " + instance.getState().getDescription()); + } + return true; + } + + /** + * Initialize the object properties based on the DB object. + * Common code between plugin calls and DBSync. + */ + public void setProperties(ModelController controller, VMInstanceVO instance) { + ContrailManager manager = controller.getManager(); + _instanceName = instance.getInstanceName(); + _active = isActiveInstance(instance); + + try { + _projectId = manager.getProjectId(instance.getDomainId(), instance.getAccountId()); + } catch (IOException ex) { + s_logger.warn("project read", ex); + throw new CloudRuntimeException(ex); + } + _initialized = true; + } + + /** + * Link the virtual machine with a service instance via programmatic API call. + * @throws IOException + */ + public void setServiceInstance(ModelController controller, VMInstanceVO instance, + ServiceInstanceModel serviceModel) throws IOException { + _serviceUuid = serviceModel.getUuid(); + _serviceModel = serviceModel; + serviceModel.addSuccessor(this); + setServiceInstanceNics(controller, instance); + } + + private void setServiceInstanceNics(ModelController controller, VMInstanceVO instance) throws IOException { + NicDao nicDao = controller.getNicDao(); + ContrailManager manager = controller.getManager(); + NetworkDao networkDao = controller.getNetworkDao(); + + List nics = nicDao.listByVmId(_instanceId); + for (NicVO nic : nics) { + String tag; + + switch (nic.getDeviceId()) { + case 0: + tag = "management"; + break; + case 1: + tag = "left"; + break; + case 2: + tag = "right"; + break; + default: + tag = null; + } + + VMInterfaceModel vmiModel = getVMInterface(nic.getUuid()); + if (vmiModel == null) { + vmiModel = new VMInterfaceModel(nic.getUuid()); + vmiModel.addToVirtualMachine(this); + NetworkVO network = networkDao.findById(nic.getNetworkId()); + VirtualNetworkModel vnModel = manager.getDatabase().lookupVirtualNetwork( + network.getUuid(), manager.getCanonicalName(network), network.getTrafficType()); + assert vnModel != null; + vmiModel.addToVirtualNetwork(vnModel); + } + vmiModel.setProperties(controller, instance, nic); + vmiModel.setServiceTag(tag); + } + } + + @Override + public void update(ModelController controller) throws InternalErrorException, IOException { + assert _initialized; + ApiConnector api = controller.getApiAccessor(); + + VirtualMachine vm = _vm; + if (vm == null) { + _vm = vm = (VirtualMachine) api.findById(VirtualMachine.class, _uuid); + if (vm == null) { + vm = new VirtualMachine(); + if (_projectId != null) { + Project project; + try { + project = (Project) api.findById(Project.class, _projectId); + } catch (IOException ex) { + s_logger.debug("project read", ex); + throw new CloudRuntimeException("Failed to read project", ex); + } + vm.setParent(project); + } + vm.setName(_instanceName); + vm.setUuid(_uuid); + } + } + + if (_serviceModel != null) { + vm.setServiceInstance(_serviceModel.getServiceInstance()); + } + + if (_vm == null) { + try { + api.create(vm); + } catch (Exception ex) { + s_logger.debug("virtual-machine create", ex); + throw new CloudRuntimeException("Failed to create virtual-machine", ex); + } + _vm = vm; + } else { + try { + api.update(vm); + } catch (IOException ex) { + s_logger.warn("virtual-machine update", ex); + throw new CloudRuntimeException("Unable to update virtual-machine object", ex); + } + } + + for (ModelObject successor: successors()) { + successor.update(controller); + } + } + + @Override + public boolean verify(ModelController controller) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean compare(ModelController controller, ModelObject current) { + // TODO Auto-generated method stub + return true; + } +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VirtualNetworkModel.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VirtualNetworkModel.java new file mode 100644 index 00000000000..b4968ac7805 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VirtualNetworkModel.java @@ -0,0 +1,494 @@ +// 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.network.contrail.model; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.apache.cloudstack.network.contrail.management.ContrailManager; +import org.apache.log4j.Logger; + +import com.cloud.dc.VlanVO; +import com.cloud.dc.dao.VlanDao; +import com.cloud.exception.InternalErrorException; +import com.cloud.network.Network; +import com.cloud.network.Networks.TrafficType; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.net.NetUtils; + +import net.juniper.contrail.api.ObjectReference; +import net.juniper.contrail.api.types.NetworkIpam; +import net.juniper.contrail.api.types.Project; +import net.juniper.contrail.api.types.SubnetType; +import net.juniper.contrail.api.types.VirtualNetwork; +import net.juniper.contrail.api.types.VnSubnetsType; +import net.juniper.contrail.api.ApiConnector; + +public class VirtualNetworkModel extends ModelObjectBase { + private static final Logger s_logger = Logger.getLogger(VirtualNetworkModel.class); + + private String _uuid; + private long _id; + private TrafficType _trafficType; + + /* + * current state for object properties + */ + private boolean _initialized; + private String _name; + private String _prefix; + private String _gateway; + private String _projectId; + + /* + * cached API server objects + */ + private VirtualNetwork _vn; + private NetworkIpam _ipam; + + private FloatingIpPoolModel _fipPoolModel; + + public VirtualNetworkModel(Network network, String uuid, String name, TrafficType trafficType) { + _uuid = uuid; + _name = name; + _trafficType = trafficType; + if (network != null) { + _id = network.getId(); + } + + if (isDynamicNetwork()) { + assert _uuid != null : "uuid is must for dynamic networks"; + } else { + assert _name != null : "name is must for static networks"; + } + } + + /* + * Resynchronize internal state from the cloudstack DB object. + */ + public void build(ModelController controller, Network network) { + setProperties(controller, network); + } + + /** + * Determine whether this network is dynamically created by cloudstack or is created by default by the contrail + * API server. + * + * @return + */ + boolean isDynamicNetwork() { + return (_trafficType == TrafficType.Guest) || (_trafficType == TrafficType.Public); + } + + @Override + public int compareTo(ModelObject o) { + VirtualNetworkModel other; + try { + other = (VirtualNetworkModel) o; + } catch (ClassCastException ex) { + String clsname = o.getClass().getName(); + return VirtualNetworkModel.class.getName().compareTo(clsname); + } + + if (!isDynamicNetwork()) { + if (!other.isDynamicNetwork()) { + // name is not unique since both management and storage networks may map to ip-fabric + int cmp = _name.compareTo(other.getName()); + if (cmp != 0) { + return cmp; + } + return _trafficType.compareTo(other._trafficType); + } + return -1; + } else if (!other.isDynamicNetwork()) { + return 1; + } + + return _uuid.compareTo(other._uuid); + } + + @Override + public void delete(ModelController controller) throws IOException { + ApiConnector api = controller.getApiAccessor(); + for (ModelObject successor: successors()) { + successor.delete(controller); + } + + try { + api.delete(VirtualNetwork.class, _uuid); + } catch (IOException ex) { + s_logger.warn("virtual-network delete", ex); + } + } + + @Override + public void destroy(ModelController controller) throws IOException { + delete(controller); + + for (ModelObject successor: successors()) { + successor.destroy(controller); + } + clearSuccessors(); + } + + public String getName() { + return _name; + } + + public String getUuid() { + return _uuid; + } + + + public VirtualNetwork getVirtualNetwork() { + return _vn; + } + + /** + * Initialize the object properties based on the DB object. + * Common code between plugin calls and DBSync. + */ + public void setProperties(ModelController controller, Network network) { + ContrailManager manager = controller.getManager(); + _name = manager.getCanonicalName(network); + _prefix = network.getCidr(); + _gateway = network.getGateway(); + + // For non-cloudstack managed network, find the uuid at this stage. + if (!isDynamicNetwork()) { + try { + _uuid = manager.findVirtualNetworkId(network); + } catch (IOException ex) { + s_logger.warn("Unable to read virtual-network", ex); + } + } + + try { + _projectId = manager.getProjectId(network.getDomainId(), network.getAccountId()); + } catch (IOException ex) { + s_logger.warn("project read", ex); + throw new CloudRuntimeException(ex); + } + + _initialized = true; + } + + @Override + public void update(ModelController controller) throws InternalErrorException, IOException { + + assert _initialized; + + ApiConnector api = controller.getApiAccessor(); + VlanDao vlanDao = controller.getVlanDao(); + VirtualNetwork vn = _vn; + + if (!isDynamicNetwork()) { + _vn = (VirtualNetwork) controller.getApiAccessor().findById(VirtualNetwork.class, _uuid); + return; + } + + assert _uuid != null : "uuid is not set"; + + if (_vn == null) { + vn = _vn = (VirtualNetwork) controller.getApiAccessor().findById(VirtualNetwork.class, _uuid); + if (vn == null) { + vn = new VirtualNetwork(); + if (_projectId != null) { + Project project; + try { + project = (Project) api.findById(Project.class, _projectId); + } catch (IOException ex) { + s_logger.debug("project read", ex); + throw new CloudRuntimeException("Failed to read project", ex); + } + vn.setParent(project); + } + vn.setName(_name); + vn.setUuid(_uuid); + } + } + + if (_ipam == null) { + NetworkIpam ipam = null; + try { + String ipam_id = api.findByName(NetworkIpam.class, null, "default-network-ipam"); + if (ipam_id == null) { + s_logger.debug("could not find default-network-ipam"); + return; + } + ipam = (NetworkIpam) api.findById(NetworkIpam.class, ipam_id); + if (ipam == null) { + s_logger.debug("could not find NetworkIpam with ipam_id: " + ipam_id); + return; + } + } catch (IOException ex) { + s_logger.error(ex); + return; + } + _ipam = ipam; + } + + if (_prefix != null) { + VnSubnetsType subnet = new VnSubnetsType(); + String[] addr_pair = _prefix.split("\\/"); + subnet.addIpamSubnets(new SubnetType(addr_pair[0], Integer.parseInt(addr_pair[1])), _gateway); + vn.setNetworkIpam(_ipam, subnet); + } else if (_trafficType == TrafficType.Public) { + vn.clearNetworkIpam(); + /* Subnet information for Public is stored in the vlan table */ + List vlan_list = vlanDao.listVlansByNetworkId(_id); + for (VlanVO vlan : vlan_list) { + String cidr = NetUtils.ipAndNetMaskToCidr(vlan.getVlanGateway(), vlan.getVlanNetmask()); + int slash = cidr.indexOf('/'); + String ip_addr = cidr.substring(0, slash); + int plen = Integer.parseInt(cidr.substring(slash + 1)); + VnSubnetsType subnet = new VnSubnetsType(); + subnet.addIpamSubnets(new SubnetType(ip_addr, plen), vlan.getVlanGateway()); + vn.addNetworkIpam(_ipam, subnet); + } + } + + if (_vn == null) { + try { + api.create(vn); + } catch (Exception ex) { + s_logger.debug("virtual-network create", ex); + throw new CloudRuntimeException("Failed to create virtual-network", ex); + } + _vn = vn; + } else { + try { + api.update(vn); + } catch (IOException ex) { + s_logger.warn("virtual-network update", ex); + throw new CloudRuntimeException("Unable to update virtual-network object", ex); + } + } + + for (ModelObject successor: successors()) { + successor.update(controller); + } + } + + public void read(ModelController controller) { + ApiConnector api = controller.getApiAccessor(); + VlanDao vlanDao = controller.getVlanDao(); + try { + _vn = (VirtualNetwork) api.findById(VirtualNetwork.class, _uuid); + } catch (IOException e) { + e.printStackTrace(); + } + if (_vn == null) { + return; + } + if (_ipam == null) { + NetworkIpam ipam = null; + try { + String ipam_id = api.findByName(NetworkIpam.class, null, "default-network-ipam"); + if (ipam_id == null) { + s_logger.debug("could not find default-network-ipam"); + return; + } + ipam = (NetworkIpam) api.findById(NetworkIpam.class, ipam_id); + if (ipam == null) { + s_logger.debug("could not find NetworkIpam with ipam_id: " + ipam_id); + return; + } + } catch (IOException ex) { + s_logger.error(ex); + return; + } + _ipam = ipam; + } + + if (_prefix != null) { + VnSubnetsType subnet = new VnSubnetsType(); + String[] addr_pair = _prefix.split("\\/"); + subnet.addIpamSubnets(new SubnetType(addr_pair[0], Integer.parseInt(addr_pair[1])), _gateway); + _vn.setNetworkIpam(_ipam, subnet); + } else if (_trafficType == TrafficType.Public) { + _vn.clearNetworkIpam(); + /* Subnet information for Public is stored in the vlan table */ + List vlan_list = vlanDao.listVlansByNetworkId(_id); + for (VlanVO vlan : vlan_list) { + String cidr = NetUtils.ipAndNetMaskToCidr(vlan.getVlanGateway(), vlan.getVlanNetmask()); + int slash = cidr.indexOf('/'); + String ip_addr = cidr.substring(0, slash); + int plen = Integer.parseInt(cidr.substring(slash + 1)); + VnSubnetsType subnet = new VnSubnetsType(); + subnet.addIpamSubnets(new SubnetType(ip_addr, plen), vlan.getVlanGateway()); + _vn.addNetworkIpam(_ipam, subnet); + } + } + return; + } + + @Override + public boolean verify(ModelController controller) { + assert _initialized : "initialized is false"; + assert _uuid != null : "uuid is not set"; + + ApiConnector api = controller.getApiAccessor(); + VlanDao vlanDao = controller.getVlanDao(); + + try { + _vn = (VirtualNetwork) api.findById(VirtualNetwork.class, _uuid); + } catch (IOException e) { + e.printStackTrace(); + } + + if (_vn == null) { + return false; + } + + if (!isDynamicNetwork()) { + return true; + } + + List dbSubnets = new ArrayList(); + if (_trafficType == TrafficType.Public) { + List vlan_list = vlanDao.listVlansByNetworkId(_id); + for (VlanVO vlan:vlan_list) { + String cidr = NetUtils.ipAndNetMaskToCidr(vlan.getVlanGateway(), vlan.getVlanNetmask()); + dbSubnets.add(vlan.getVlanGateway() + cidr); + } + } else { + dbSubnets.add(this._gateway + this._prefix); + } + + List> ipamRefs = _vn.getNetworkIpam(); + List vncSubnets = new ArrayList(); + + if (ipamRefs == null && !dbSubnets.isEmpty()) { + return false; + } + + if (ipamRefs != null) { + for (ObjectReference ref: ipamRefs) { + VnSubnetsType vnSubnetType = ref.getAttr(); + if (vnSubnetType != null) { + List subnets = vnSubnetType.getIpamSubnets(); + if (subnets != null && !subnets.isEmpty()) { + VnSubnetsType.IpamSubnetType ipamSubnet = subnets.get(0); + vncSubnets.add(ipamSubnet.getDefaultGateway() + + ipamSubnet.getSubnet().getIpPrefix() +"/" + ipamSubnet.getSubnet().getIpPrefixLen()); + } + } + } + } + // unordered, no duplicates hence perform negation operation as set + Set diff = new HashSet(dbSubnets); + diff.removeAll(vncSubnets); + + if (!diff.isEmpty()) { + s_logger.debug("Subnets changed, network: " + this._name + + "; db: " + dbSubnets + ", vnc: " + vncSubnets + ", diff: " + diff); + return false; + } + + for (ModelObject successor: successors()) { + if (!successor.verify(controller)) { + return false; + } + } + return true; + } + + @Override + public boolean compare(ModelController controller, ModelObject o) { + VirtualNetworkModel latest; + ApiConnector api = controller.getApiAccessor(); + + assert this._vn != null : "vnc virtual network current is not initialized"; + + try { + latest = (VirtualNetworkModel) o; + } catch (ClassCastException ex) { + s_logger.warn("Invalid model object is passed to cast to VirtualNetworkModel"); + return false; + } + + try { + latest.read(controller); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + assert latest._vn != null : "vnc virtual network new is not initialized"; + + List> currentIpamRefs = this._vn.getNetworkIpam(); + List> newIpamRefs = latest._vn.getNetworkIpam(); + List currentSubnets = new ArrayList(); + List newSubnets = new ArrayList(); + + + if ((currentIpamRefs == null && newIpamRefs != null) || + (currentIpamRefs != null && newIpamRefs == null)) { //Check for existence only + s_logger.debug("ipams differ: current=" + currentIpamRefs + ", new=" + newIpamRefs); + return false; + } + if (currentIpamRefs == null) { + return true; + } + + for (ObjectReference ref: currentIpamRefs) { + VnSubnetsType vnSubnetType = ref.getAttr(); + if (vnSubnetType != null) { + List subnets = vnSubnetType.getIpamSubnets(); + if (subnets != null && !subnets.isEmpty()) { + VnSubnetsType.IpamSubnetType ipamSubnet = subnets.get(0); + currentSubnets.add(ipamSubnet.getDefaultGateway() + ipamSubnet.getSubnet().getIpPrefix() + + "/" + ipamSubnet.getSubnet().getIpPrefixLen()); + } + } + } + + for (ObjectReference ref: newIpamRefs) { + VnSubnetsType vnSubnetType = ref.getAttr(); + if (vnSubnetType != null) { + List subnets = vnSubnetType.getIpamSubnets(); + if (subnets != null && !subnets.isEmpty()) { + VnSubnetsType.IpamSubnetType ipamSubnet = subnets.get(0); + newSubnets.add(ipamSubnet.getDefaultGateway() + ipamSubnet.getSubnet().getIpPrefix() + + "/" + ipamSubnet.getSubnet().getIpPrefixLen()); + } + } + } + + Set diff = new HashSet(currentSubnets); + diff.removeAll(newSubnets); + + if (!diff.isEmpty()) { + s_logger.debug("Subnets differ, network: " + this._name + + "; db: " + currentSubnets + ", vnc: " + newSubnets + ", diff: " + diff); + return false; + } + + return true; + } + + public FloatingIpPoolModel getFipPoolModel() { + return _fipPoolModel; + } + public void setFipPoolModel(FloatingIpPoolModel fipPoolModel) { + _fipPoolModel = fipPoolModel; + } +} diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/ApiConnectorMockito.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/ApiConnectorMockito.java new file mode 100644 index 00000000000..e70ac5eeca0 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/ApiConnectorMockito.java @@ -0,0 +1,149 @@ +// 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.network.contrail.management; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import net.juniper.contrail.api.ApiConnector; +import net.juniper.contrail.api.ApiConnectorMock; +import net.juniper.contrail.api.ApiObjectBase; +import net.juniper.contrail.api.ApiPropertyBase; +import net.juniper.contrail.api.ObjectReference; +import net.juniper.contrail.api.types.NetworkIpam; + +import org.apache.log4j.Logger; +import static org.mockito.Mockito.*; + +import com.google.common.collect.ImmutableMap; + +public class ApiConnectorMockito implements ApiConnector { + private static final Logger s_logger = + Logger.getLogger(ApiConnectorMockito.class); + + static final Map object_map = new ImmutableMap.Builder(). + put("network-ipam:default-network-ipam", new NetworkIpam()). + build(); + private ApiConnectorMock _mock; + private ApiConnector _spy; + + public ApiConnectorMockito(String hostname, int port) { + _mock = new ApiConnectorMock(hostname, port); + _spy = spy(_mock); + } + + public ApiConnector getSpy() { + return _spy; + } + + @Override + public boolean create(ApiObjectBase arg0) throws IOException { + s_logger.debug("create " + arg0.getClass().getName() + " id: " + arg0.getUuid()); + return _spy.create(arg0); + } + + @Override + public void delete(ApiObjectBase arg0) throws IOException { + s_logger.debug("delete " + arg0.getClass().getName() + " id: " + arg0.getUuid()); + _spy.delete(arg0); + } + + @Override + public void delete(Class arg0, String arg1) + throws IOException { + s_logger.debug("create " + arg0.getName() + " id: " + arg1); + _spy.delete(arg0, arg1); + } + + @Override + public ApiObjectBase find(Class arg0, + ApiObjectBase arg1, String arg2) throws IOException { + StringBuilder msg = new StringBuilder(); + msg.append("find " + arg0.getName()); + if (arg1 != null) { + msg.append(" parent: " + arg1.getName()); + } + msg.append(" name: " + arg2); + + return _mock.find(arg0, arg1, arg2); + } + + @Override + public ApiObjectBase findByFQN(Class arg0, + String arg1) throws IOException { + s_logger.debug("find " + arg0.getName() + " name: " + arg1); + return _mock.findByFQN(arg0, arg1); + } + + @Override + public ApiObjectBase findById(Class arg0, + String arg1) throws IOException { + s_logger.debug("find " + arg0.getName() + " id: " + arg1); + return _mock.findById(arg0, arg1); + } + + @Override + public String findByName(Class arg0, + List arg1) throws IOException { + s_logger.debug("find " + arg0.getName() + " name: " + arg1); + return _mock.findByName(arg0, arg1); + } + + @Override + public String findByName(Class arg0, + ApiObjectBase arg1, String arg2) throws IOException { + StringBuilder msg = new StringBuilder(); + msg.append("findByName " + arg0.getName()); + if (arg1 != null) { + msg.append(" parent: " + arg1.getName()); + } + msg.append(" name: " + arg2); + s_logger.debug(msg.toString()); + return _mock.findByName(arg0, arg1, arg2); + } + + @Override + public List getObjects( + Class arg0, List> arg1) + throws IOException { + s_logger.debug("getObjects" + arg0.getName()); + return _mock.getObjects(arg0, arg1); + } + + @Override + public List list( + Class arg0, List arg1) + throws IOException { + s_logger.debug("list" + arg0.getName()); + return _mock.list(arg0, arg1); + } + + @Override + public boolean read(ApiObjectBase arg0) throws IOException { + s_logger.debug("read " + arg0.getClass().getName() + " id: " + arg0.getUuid()); + return _mock.read(arg0); + } + + @Override + public boolean update(ApiObjectBase arg0) throws IOException { + s_logger.debug("update " + arg0.getClass().getName() + " id: " + arg0.getUuid()); + return _spy.update(arg0); + } + +} diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/IntegrationTestConfiguration.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/IntegrationTestConfiguration.java new file mode 100644 index 00000000000..dec4a9e4953 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/IntegrationTestConfiguration.java @@ -0,0 +1,835 @@ +// 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.network.contrail.management; + +import java.io.IOException; + +import javax.inject.Inject; + +import com.cloud.network.dao.IPAddressDao; +import com.cloud.network.IpAddress; + +import org.apache.cloudstack.acl.APIChecker; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.affinity.AffinityGroupService; +import org.apache.cloudstack.affinity.AffinityGroupVO; +import org.apache.cloudstack.affinity.dao.AffinityGroupDao; +import org.apache.cloudstack.affinity.dao.AffinityGroupDaoImpl; +import org.apache.cloudstack.affinity.dao.AffinityGroupDomainMapDaoImpl; +import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDaoImpl; +import org.apache.cloudstack.api.IdentityService; +import org.apache.cloudstack.engine.service.api.OrchestrationService; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; +import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; +import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator; +import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; +import org.apache.cloudstack.lb.dao.ApplicationLoadBalancerRuleDaoImpl; +import org.apache.cloudstack.query.QueryService; +import org.apache.cloudstack.region.PortableIpDaoImpl; +import org.apache.cloudstack.region.PortableIpRangeDaoImpl; +import org.apache.cloudstack.region.RegionManager; +import org.apache.cloudstack.region.dao.RegionDaoImpl; +import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDaoImpl; +import org.apache.cloudstack.storage.image.db.ImageStoreDaoImpl; +import org.apache.cloudstack.storage.image.db.TemplateDataStoreDaoImpl; +import org.apache.cloudstack.usage.UsageService; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.ComponentScan.Filter; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.FilterType; +import org.springframework.core.type.classreading.MetadataReader; +import org.springframework.core.type.classreading.MetadataReaderFactory; +import org.springframework.core.type.filter.TypeFilter; + +import com.cloud.acl.DomainChecker; +import com.cloud.agent.AgentManager; +import com.cloud.agent.manager.allocator.HostAllocator; +import com.cloud.agent.manager.allocator.PodAllocator; +import com.cloud.alert.AlertManager; +import com.cloud.api.ApiDBUtils; +import com.cloud.api.query.dao.AccountJoinDaoImpl; +import com.cloud.api.query.dao.AffinityGroupJoinDaoImpl; +import com.cloud.api.query.dao.AsyncJobJoinDaoImpl; +import com.cloud.api.query.dao.DataCenterJoinDaoImpl; +import com.cloud.api.query.dao.DiskOfferingJoinDaoImpl; +import com.cloud.api.query.dao.DomainRouterJoinDaoImpl; +import com.cloud.api.query.dao.HostJoinDaoImpl; +import com.cloud.api.query.dao.ImageStoreJoinDaoImpl; +import com.cloud.api.query.dao.InstanceGroupJoinDaoImpl; +import com.cloud.api.query.dao.ProjectAccountJoinDaoImpl; +import com.cloud.api.query.dao.ProjectInvitationJoinDaoImpl; +import com.cloud.api.query.dao.ProjectJoinDaoImpl; +import com.cloud.api.query.dao.ResourceTagJoinDaoImpl; +import com.cloud.api.query.dao.SecurityGroupJoinDaoImpl; +import com.cloud.api.query.dao.ServiceOfferingJoinDaoImpl; +import com.cloud.api.query.dao.StoragePoolJoinDaoImpl; +import com.cloud.api.query.dao.TemplateJoinDaoImpl; +import com.cloud.api.query.dao.UserAccountJoinDaoImpl; +import com.cloud.api.query.dao.UserVmJoinDaoImpl; +import com.cloud.api.query.dao.VolumeJoinDaoImpl; +import com.cloud.capacity.CapacityManager; +import com.cloud.capacity.dao.CapacityDaoImpl; +import com.cloud.cluster.ClusterManager; +import com.cloud.cluster.agentlb.dao.HostTransferMapDaoImpl; +import com.cloud.cluster.dao.ManagementServerHostDaoImpl; +import com.cloud.configuration.ConfigurationManagerImpl; + +import org.apache.cloudstack.framework.config.dao.ConfigurationDaoImpl; + +import com.cloud.configuration.dao.ResourceCountDaoImpl; +import com.cloud.configuration.dao.ResourceLimitDaoImpl; +import com.cloud.consoleproxy.ConsoleProxyManager; +import com.cloud.consoleproxy.ConsoleProxyService; +import com.cloud.dc.ClusterDetailsDaoImpl; +import com.cloud.dc.DataCenter; +import com.cloud.dc.dao.AccountVlanMapDaoImpl; +import com.cloud.dc.dao.ClusterDaoImpl; +import com.cloud.dc.dao.DataCenterDaoImpl; +import com.cloud.dc.dao.DataCenterIpAddressDaoImpl; +import com.cloud.dc.dao.DataCenterLinkLocalIpAddressDaoImpl; +import com.cloud.dc.dao.DataCenterVnetDaoImpl; +import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.DcDetailsDaoImpl; +import com.cloud.dc.dao.DedicatedResourceDaoImpl; +import com.cloud.dc.dao.HostPodDaoImpl; +import com.cloud.dc.dao.PodVlanDaoImpl; +import com.cloud.dc.dao.PodVlanMapDaoImpl; +import com.cloud.dc.dao.VlanDaoImpl; +import com.cloud.deploy.DeploymentPlanner; +import com.cloud.deploy.DeploymentPlanningManager; +import com.cloud.deploy.dao.PlannerHostReservationDaoImpl; +import com.cloud.domain.dao.DomainDaoImpl; +import com.cloud.event.dao.EventDaoImpl; +import com.cloud.event.dao.EventJoinDaoImpl; +import com.cloud.event.dao.UsageEventDaoImpl; +import com.cloud.ha.HighAvailabilityManager; +import com.cloud.host.dao.HostDaoImpl; +import com.cloud.host.dao.HostDetailsDaoImpl; +import com.cloud.host.dao.HostTagsDaoImpl; +import com.cloud.hypervisor.HypervisorGuruManagerImpl; +import com.cloud.hypervisor.dao.HypervisorCapabilitiesDaoImpl; +import com.cloud.network.ExternalDeviceUsageManager; +import com.cloud.network.Ipv6AddressManagerImpl; +import com.cloud.network.NetworkModelImpl; +import com.cloud.network.NetworkServiceImpl; +import com.cloud.network.NetworkUsageService; +import com.cloud.network.StorageNetworkManager; +import com.cloud.network.StorageNetworkService; +import com.cloud.network.as.AutoScaleService; +import com.cloud.network.as.dao.AutoScalePolicyConditionMapDaoImpl; +import com.cloud.network.as.dao.AutoScalePolicyDaoImpl; +import com.cloud.network.as.dao.AutoScaleVmGroupDaoImpl; +import com.cloud.network.as.dao.AutoScaleVmGroupPolicyMapDaoImpl; +import com.cloud.network.as.dao.AutoScaleVmProfileDaoImpl; +import com.cloud.network.as.dao.ConditionDaoImpl; +import com.cloud.network.as.dao.CounterDaoImpl; +import com.cloud.network.dao.AccountGuestVlanMapDaoImpl; +import com.cloud.network.dao.FirewallRulesCidrsDaoImpl; +import com.cloud.network.dao.FirewallRulesDaoImpl; +import com.cloud.network.dao.LBHealthCheckPolicyDaoImpl; +import com.cloud.network.dao.LBStickinessPolicyDaoImpl; +import com.cloud.network.dao.LoadBalancerDaoImpl; +import com.cloud.network.dao.LoadBalancerVMMapDaoImpl; +import com.cloud.network.dao.NetworkAccountDaoImpl; +import com.cloud.network.dao.NetworkDaoImpl; +import com.cloud.network.dao.NetworkDomainDaoImpl; +import com.cloud.network.dao.NetworkOpDaoImpl; +import com.cloud.network.dao.NetworkRuleConfigDaoImpl; +import com.cloud.network.dao.NetworkServiceMapDaoImpl; +import com.cloud.network.dao.PhysicalNetworkDaoImpl; +import com.cloud.network.dao.PhysicalNetworkServiceProviderDaoImpl; +import com.cloud.network.dao.PhysicalNetworkTrafficTypeDaoImpl; +import com.cloud.network.dao.RemoteAccessVpnDaoImpl; +import com.cloud.network.dao.RouterNetworkDaoImpl; +import com.cloud.network.dao.Site2SiteCustomerGatewayDaoImpl; +import com.cloud.network.dao.Site2SiteVpnConnectionDaoImpl; +import com.cloud.network.dao.Site2SiteVpnGatewayDaoImpl; +import com.cloud.network.dao.UserIpv6AddressDaoImpl; +import com.cloud.network.dao.VirtualRouterProviderDaoImpl; +import com.cloud.network.dao.VpnUserDaoImpl; +import com.cloud.network.element.Site2SiteVpnServiceProvider; +import com.cloud.network.firewall.FirewallManagerImpl; +import com.cloud.network.lb.LoadBalancingRulesManagerImpl; +import com.cloud.network.router.VpcVirtualNetworkApplianceManagerImpl; +import com.cloud.network.rules.RulesManagerImpl; +import com.cloud.network.rules.dao.PortForwardingRulesDaoImpl; +import com.cloud.network.security.dao.SecurityGroupDaoImpl; +import com.cloud.network.security.dao.SecurityGroupRuleDaoImpl; +import com.cloud.network.security.dao.SecurityGroupRulesDaoImpl; +import com.cloud.network.security.dao.SecurityGroupVMMapDaoImpl; +import com.cloud.network.security.dao.SecurityGroupWorkDaoImpl; +import com.cloud.network.security.dao.VmRulesetLogDaoImpl; +import com.cloud.network.vpc.NetworkACLManagerImpl; +import com.cloud.network.vpc.NetworkACLService; +import com.cloud.network.vpc.VpcManagerImpl; +import com.cloud.network.vpc.dao.NetworkACLDaoImpl; +import com.cloud.network.vpc.dao.NetworkACLItemDaoImpl; +import com.cloud.network.vpc.dao.PrivateIpDaoImpl; +import com.cloud.network.vpc.dao.StaticRouteDaoImpl; +import com.cloud.network.vpc.dao.VpcDaoImpl; +import com.cloud.network.vpc.dao.VpcGatewayDaoImpl; +import com.cloud.network.vpc.dao.VpcOfferingDaoImpl; +import com.cloud.network.vpc.dao.VpcOfferingServiceMapDaoImpl; +import com.cloud.network.vpc.dao.VpcServiceMapDaoImpl; +import com.cloud.network.vpn.RemoteAccessVpnService; +import com.cloud.network.vpn.Site2SiteVpnManager; +import com.cloud.projects.dao.ProjectInvitationDaoImpl; +import com.cloud.dc.DataCenter; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.offerings.dao.NetworkOfferingDaoImpl; +import com.cloud.offerings.dao.NetworkOfferingDao; +import com.cloud.offering.NetworkOffering; +import com.cloud.offerings.dao.NetworkOfferingDetailsDaoImpl; +import com.cloud.offerings.dao.NetworkOfferingServiceMapDaoImpl; +import com.cloud.projects.ProjectManager; +import com.cloud.projects.dao.ProjectAccountDaoImpl; +import com.cloud.projects.ProjectManagerImpl; +import com.cloud.projects.dao.ProjectDaoImpl; +import com.cloud.region.ha.GlobalLoadBalancingRulesService; +import com.cloud.resource.ResourceManager; +import com.cloud.server.ConfigurationServerImpl; +import com.cloud.server.ManagementServer; +import com.cloud.server.ResourceMetaDataService; +import com.cloud.server.StatsCollector; +import com.cloud.server.TaggedResourceService; +import com.cloud.server.auth.UserAuthenticator; +import com.cloud.service.dao.ServiceOfferingDaoImpl; +import com.cloud.service.dao.ServiceOfferingDetailsDaoImpl; +import com.cloud.storage.DataStoreProviderApiService; +import com.cloud.storage.StorageManager; +import com.cloud.storage.dao.DiskOfferingDaoImpl; +import com.cloud.storage.dao.GuestOSCategoryDaoImpl; +import com.cloud.storage.dao.GuestOSDaoImpl; +import com.cloud.storage.dao.LaunchPermissionDao; +import com.cloud.storage.dao.SnapshotDaoImpl; +import com.cloud.storage.dao.SnapshotPolicyDaoImpl; +import com.cloud.storage.dao.StoragePoolDetailsDaoImpl; +import com.cloud.storage.dao.StoragePoolHostDaoImpl; +import com.cloud.storage.dao.UploadDaoImpl; +import com.cloud.storage.dao.VMTemplateDaoImpl; +import com.cloud.storage.dao.VMTemplateDetailsDaoImpl; +import com.cloud.storage.dao.VMTemplateHostDaoImpl; +import com.cloud.storage.dao.VMTemplateZoneDaoImpl; +import com.cloud.storage.dao.VolumeDaoImpl; +import com.cloud.storage.dao.VolumeHostDaoImpl; +import com.cloud.storage.secondary.SecondaryStorageVmManager; +import com.cloud.storage.snapshot.SnapshotApiService; +import com.cloud.storage.snapshot.SnapshotManager; +import com.cloud.storage.VolumeApiService; +import com.cloud.tags.dao.ResourceTagDao; +import com.cloud.tags.dao.ResourceTagsDaoImpl; +import com.cloud.template.TemplateApiService; +import com.cloud.template.TemplateManager; +import com.cloud.user.Account; +import com.cloud.user.dao.AccountDao; +import com.cloud.user.AccountManager; +import com.cloud.user.User; +import com.cloud.user.UserVO; +import com.cloud.user.dao.UserDao; +import com.cloud.user.AccountDetailsDaoImpl; +import com.cloud.user.AccountVO; +import com.cloud.user.DomainManagerImpl; +import com.cloud.user.ResourceLimitService; +import com.cloud.user.dao.AccountDaoImpl; +import com.cloud.user.dao.SSHKeyPairDaoImpl; +import com.cloud.user.dao.UserDaoImpl; +import com.cloud.user.dao.UserStatisticsDaoImpl; +import com.cloud.user.dao.UserStatsLogDaoImpl; +import com.cloud.user.dao.VmDiskStatisticsDaoImpl; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.TransactionCallbackNoReturn; +import com.cloud.utils.db.TransactionStatus; +import com.cloud.uuididentity.dao.IdentityDaoImpl; +import com.cloud.vm.ItWorkDaoImpl; +import com.cloud.vm.dao.ConsoleProxyDaoImpl; +import com.cloud.vm.dao.DomainRouterDaoImpl; +import com.cloud.vm.dao.InstanceGroupDaoImpl; +import com.cloud.vm.dao.InstanceGroupVMMapDaoImpl; +import com.cloud.vm.dao.NicIpAliasDaoImpl; +import com.cloud.vm.dao.NicSecondaryIpDaoImpl; +import com.cloud.vm.dao.SecondaryStorageVmDaoImpl; +import com.cloud.vm.dao.UserVmCloneSettingDaoImpl; +import com.cloud.vm.dao.UserVmDaoImpl; +import com.cloud.vm.dao.UserVmDetailsDaoImpl; +import com.cloud.vm.dao.VMInstanceDaoImpl; +import com.cloud.vm.snapshot.VMSnapshotManager; +import com.cloud.vm.snapshot.dao.VMSnapshotDaoImpl; + +import org.apache.cloudstack.framework.jobs.impl.AsyncJobManagerImpl; +import org.apache.cloudstack.framework.jobs.dao.AsyncJobDaoImpl; +import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService; + +import com.cloud.network.IpAddressManagerImpl; + +import org.apache.cloudstack.framework.config.ConfigDepot; +import org.apache.cloudstack.framework.jobs.dao.SyncQueueItemDaoImpl; +import org.apache.cloudstack.framework.jobs.impl.SyncQueueManager; +import org.apache.cloudstack.framework.jobs.dao.AsyncJobJournalDaoImpl; +import org.apache.cloudstack.framework.jobs.dao.AsyncJobJoinMapDaoImpl; +import org.apache.cloudstack.framework.jobs.AsyncJobDispatcher; +import org.apache.cloudstack.framework.jobs.impl.AsyncJobMonitor; +import org.apache.cloudstack.framework.config.ConfigDepotAdmin; +import org.apache.cloudstack.network.lb.InternalLoadBalancerVMManager; +import org.apache.cloudstack.network.lb.InternalLoadBalancerVMService; +import org.apache.cloudstack.network.lb.ApplicationLoadBalancerService; + +import com.cloud.utils.db.EntityManager; + +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.network.contrail.management.ContrailElementImpl; +import org.apache.cloudstack.network.contrail.management.ContrailGuru; +import org.apache.cloudstack.network.contrail.management.ContrailManagerImpl; +import org.apache.cloudstack.network.contrail.management.EventUtils; +import org.apache.cloudstack.network.contrail.management.ServerEventHandlerImpl; + + +@ComponentScan(basePackageClasses={ + AccountDaoImpl.class, + AccountDetailsDaoImpl.class, + AccountGuestVlanMapDaoImpl.class, + AccountJoinDaoImpl.class, + AccountVlanMapDaoImpl.class, + AffinityGroupDaoImpl.class, + AffinityGroupDomainMapDaoImpl.class, + AffinityGroupJoinDaoImpl.class, + AffinityGroupVMMapDaoImpl.class, + ApiDBUtils.class, + ApplicationLoadBalancerRuleDaoImpl.class, + AsyncJobDaoImpl.class, + AsyncJobJoinDaoImpl.class, + AsyncJobJoinMapDaoImpl.class, + AsyncJobJournalDaoImpl.class, + AsyncJobManagerImpl.class, + AutoScalePolicyConditionMapDaoImpl.class, + AutoScalePolicyDaoImpl.class, + AutoScaleVmGroupDaoImpl.class, + AutoScaleVmGroupPolicyMapDaoImpl.class, + AutoScaleVmProfileDaoImpl.class, + CapacityDaoImpl.class, + ClusterDaoImpl.class, + ClusterDetailsDaoImpl.class, + ConditionDaoImpl.class, + ConfigurationDaoImpl.class, + ConfigurationManagerImpl.class, + ConfigurationServerImpl.class, + ConsoleProxyDaoImpl.class, + ContrailElementImpl.class, + ContrailGuru.class, + ContrailManagerImpl.class, + CounterDaoImpl.class, + DataCenterDaoImpl.class, + DataCenterIpAddressDaoImpl.class, + DataCenterJoinDaoImpl.class, + DataCenterLinkLocalIpAddressDaoImpl.class, + DataCenterVnetDaoImpl.class, + DcDetailsDaoImpl.class, + DedicatedResourceDaoImpl.class, + DiskOfferingDaoImpl.class, + DiskOfferingJoinDaoImpl.class, + DomainDaoImpl.class, + DomainManagerImpl.class, + DomainRouterDaoImpl.class, + DomainRouterJoinDaoImpl.class, + EventDaoImpl.class, + EventJoinDaoImpl.class, + EventUtils.class, + EventUtils.class, + FirewallManagerImpl.class, + FirewallRulesCidrsDaoImpl.class, + FirewallRulesDaoImpl.class, + GuestOSCategoryDaoImpl.class, + GuestOSDaoImpl.class, + HostDaoImpl.class, + HostDetailsDaoImpl.class, + HostJoinDaoImpl.class, + HostPodDaoImpl.class, + HostTagsDaoImpl.class, + HostTransferMapDaoImpl.class, + HypervisorCapabilitiesDaoImpl.class, + HypervisorGuruManagerImpl.class, + IdentityDaoImpl.class, + ImageStoreDaoImpl.class, + ImageStoreJoinDaoImpl.class, + InstanceGroupDaoImpl.class, + InstanceGroupJoinDaoImpl.class, + InstanceGroupVMMapDaoImpl.class, + IpAddressManagerImpl.class, + Ipv6AddressManagerImpl.class, + ItWorkDaoImpl.class, + LBHealthCheckPolicyDaoImpl.class, + LBStickinessPolicyDaoImpl.class, + LaunchPermissionDao.class, + LoadBalancerDaoImpl.class, + LoadBalancerVMMapDaoImpl.class, + LoadBalancingRulesManagerImpl.class, + ManagementServerHostDaoImpl.class, + MockAccountManager.class, + NetworkACLDaoImpl.class, + NetworkACLItemDaoImpl.class, + NetworkACLManagerImpl.class, + NetworkAccountDaoImpl.class, + NetworkDaoImpl.class, + NetworkDomainDaoImpl.class, + NetworkModelImpl.class, + NetworkOfferingDaoImpl.class, + NetworkOfferingDetailsDaoImpl.class, + NetworkOfferingServiceMapDaoImpl.class, + NetworkOpDaoImpl.class, + NetworkRuleConfigDaoImpl.class, + NetworkServiceImpl.class, + NetworkServiceMapDaoImpl.class, + NicIpAliasDaoImpl.class, + NicSecondaryIpDaoImpl.class, + PhysicalNetworkDaoImpl.class, + PhysicalNetworkServiceProviderDaoImpl.class, + PhysicalNetworkTrafficTypeDaoImpl.class, + PlannerHostReservationDaoImpl.class, + PodVlanDaoImpl.class, + PodVlanMapDaoImpl.class, + PortForwardingRulesDaoImpl.class, + PortableIpDaoImpl.class, + PortableIpRangeDaoImpl.class, + PrimaryDataStoreDaoImpl.class, + PrivateIpDaoImpl.class, + ProjectAccountDaoImpl.class, + ProjectAccountJoinDaoImpl.class, + ProjectInvitationDaoImpl.class, + ProjectDaoImpl.class, + ProjectInvitationJoinDaoImpl.class, + ProjectJoinDaoImpl.class, + ProjectManagerImpl.class, + RegionDaoImpl.class, + RemoteAccessVpnDaoImpl.class, + ResourceCountDaoImpl.class, + ResourceLimitDaoImpl.class, + ResourceTagDao.class, + ResourceTagJoinDaoImpl.class, + ResourceTagsDaoImpl.class, + RouterNetworkDaoImpl.class, + RulesManagerImpl.class, + SSHKeyPairDaoImpl.class, + SecondaryStorageVmDaoImpl.class, + SecurityGroupDaoImpl.class, + SecurityGroupJoinDaoImpl.class, + SecurityGroupRuleDaoImpl.class, + SecurityGroupRulesDaoImpl.class, + SecurityGroupVMMapDaoImpl.class, + SecurityGroupWorkDaoImpl.class, + ServerEventHandlerImpl.class, + ServiceOfferingDaoImpl.class, + ServiceOfferingDetailsDaoImpl.class, + ServiceOfferingJoinDaoImpl.class, + Site2SiteCustomerGatewayDaoImpl.class, + Site2SiteVpnConnectionDaoImpl.class, + Site2SiteVpnGatewayDaoImpl.class, + SnapshotDaoImpl.class, + SnapshotPolicyDaoImpl.class, + StaticRouteDaoImpl.class, + StatsCollector.class, + StoragePoolDetailsDaoImpl.class, + StoragePoolHostDaoImpl.class, + StoragePoolJoinDaoImpl.class, + SyncQueueItemDaoImpl.class, + TemplateDataStoreDaoImpl.class, + TemplateJoinDaoImpl.class, + UploadDaoImpl.class, + UsageEventDaoImpl.class, + UserAccountJoinDaoImpl.class, + UserDaoImpl.class, + UserIpv6AddressDaoImpl.class, + UserStatisticsDaoImpl.class, + UserStatsLogDaoImpl.class, + UserVmCloneSettingDaoImpl.class, + UserVmDaoImpl.class, + UserVmDetailsDaoImpl.class, + UserVmJoinDaoImpl.class, + VMInstanceDaoImpl.class, + VMSnapshotDaoImpl.class, + VMTemplateDaoImpl.class, + VMTemplateDetailsDaoImpl.class, + VMTemplateHostDaoImpl.class, + VMTemplateZoneDaoImpl.class, + VirtualRouterProviderDaoImpl.class, + VlanDaoImpl.class, + VmDiskStatisticsDaoImpl.class, + VmRulesetLogDaoImpl.class, + VolumeDaoImpl.class, + VolumeHostDaoImpl.class, + VolumeJoinDaoImpl.class, + VpcDaoImpl.class, + VpcGatewayDaoImpl.class, + VpcManagerImpl.class, + VpcOfferingDaoImpl.class, + VpcOfferingServiceMapDaoImpl.class, + VpcServiceMapDaoImpl.class, + VpcVirtualNetworkApplianceManagerImpl.class, + VpnUserDaoImpl.class +}, +includeFilters={@Filter(value=IntegrationTestConfiguration.ComponentFilter.class, type=FilterType.CUSTOM)}, +useDefaultFilters=false) + +@Configuration +public class IntegrationTestConfiguration { + public static class ComponentFilter implements TypeFilter { + @Override + public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException { + String clsname = mdr.getClassMetadata().getClassName(); + ComponentScan cs = IntegrationTestConfiguration.class.getAnnotation(ComponentScan.class); + return includedInBasePackageClasses(clsname, cs); + } + } + + public static boolean includedInBasePackageClasses(String clazzName, ComponentScan cs) { + Class clazzToCheck; + try { + clazzToCheck = Class.forName(clazzName); + } catch (ClassNotFoundException e) { + System.out.println("Unable to find " + clazzName); + return false; + } + Class[] clazzes = cs.basePackageClasses(); + for (Class clazz : clazzes) { + if (clazzToCheck.isAssignableFrom(clazz)) { + return true; + } + } + return false; + } + + @Inject + AffinityGroupDao _affinityGroupDao; + @Inject AccountDao _accountDao; + @Inject UserDao _userDao; + @Inject NetworkOfferingDao _networkOfferingDao; + @Inject DataCenterDao _zoneDao; + @Inject IPAddressDao _ipAddressDao; + + + @Bean + public AffinityGroupService affinityGroupService() { + AffinityGroupService mock = Mockito.mock(AffinityGroupService.class); + try { + final AffinityGroupVO gmock = new AffinityGroupVO("grp1", "grp-type", "affinity group", 1, AccountVO.ACCOUNT_ID_SYSTEM, ControlledEntity.ACLType.Account); + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + _affinityGroupDao.persist(gmock); + } + }); + Mockito.when(mock.createAffinityGroupInternal(Mockito.any(String.class), Mockito.any(Long.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))).thenReturn(gmock); + } catch (Exception e) { + e.printStackTrace(); + } + return mock; + } + + @Bean + public AgentManager agentManager() { + return Mockito.mock(AgentManager.class); + } + + @Bean + public AlertManager alertManager() { + return Mockito.mock(AlertManager.class); + } + + @Bean + public APIChecker apiChecker() { + return Mockito.mock(APIChecker.class); + } + + @Bean + public AsyncJobDispatcher asyncJobDispatcher() { + return Mockito.mock(AsyncJobDispatcher.class); + } + @Bean + public AsyncJobMonitor asyncJobMonitor() { + return Mockito.mock(AsyncJobMonitor.class); + } + + @Bean + public AutoScaleService autoScaleService() { + return Mockito.mock(AutoScaleService.class); + } + @Bean + public CapacityManager capacityManager() { + return Mockito.mock(CapacityManager.class); + } + @Bean + public ClusterManager clusterManager() { + return Mockito.mock(ClusterManager.class); + } + @Bean + public ConfigDepot configDepot() { + return Mockito.mock(ConfigDepot.class); + } + @Bean + public ConfigDepotAdmin configDepotAdmin() { + return Mockito.mock(ConfigDepotAdmin.class); + } + @Bean + public ConsoleProxyManager consoleProxyManager() { + return Mockito.mock(ConsoleProxyManager.class); + } + @Bean + public ConsoleProxyService consoleProxyService() { + return Mockito.mock(ConsoleProxyService.class); + } + @Bean + public DataStoreManager dataStoreManager() { + return Mockito.mock(DataStoreManager.class); + } + @Bean + public DataStoreProviderApiService dataStoreProviderApiService() { + return Mockito.mock(DataStoreProviderApiService.class); + } + @Bean + public DeploymentPlanner deploymentPlanner() { + return Mockito.mock(DeploymentPlanner.class); + } + @Bean + public DeploymentPlanningManager deploymentPlanningManager() { + return Mockito.mock(DeploymentPlanningManager.class); + } + @Bean + public DomainChecker domainChecker() { + DomainChecker mock = Mockito.mock(DomainChecker.class); + try { + Mockito.when(mock.checkAccess(Mockito.any(Account.class), Mockito.any(DataCenter.class))).thenReturn(true); + } catch (Exception e) { + e.printStackTrace(); + } + return mock; + } + @Bean + public EndPointSelector endPointSelector() { + return Mockito.mock(EndPointSelector.class); + } + @Bean + public EntityManager entityManager() { + EntityManager mock = Mockito.mock(EntityManager.class); + try { + Mockito.when(mock.findById(Mockito.same(Account.class), Mockito.anyLong())).thenReturn(_accountDao.findById(AccountVO.ACCOUNT_ID_SYSTEM)); + Mockito.when(mock.findById(Mockito.same(User.class), Mockito.anyLong())).thenReturn(_userDao.findById(UserVO.UID_SYSTEM)); + Mockito.when(mock.findById(Mockito.same(NetworkOffering.class), Mockito.any(Long.class))).thenAnswer( + new Answer() + { + @Override + public NetworkOffering answer(final InvocationOnMock invocation) throws Throwable + { + Long id = (Long) invocation.getArguments()[1]; + return _networkOfferingDao.findById(id); + } + } + ); + Mockito.when(mock.findById(Mockito.same(IpAddress.class), Mockito.any(Long.class))).thenAnswer( + new Answer() + { + @Override + public IpAddress answer(final InvocationOnMock invocation) throws Throwable + { + Long id = (Long) invocation.getArguments()[1]; + return _ipAddressDao.findById(id); + } + } + ); + Mockito.when(mock.findById(Mockito.same(DataCenter.class), Mockito.any(Long.class))).thenAnswer( + new Answer() + { + @Override + public DataCenter answer(final InvocationOnMock invocation) throws Throwable + { + Long id = (Long) invocation.getArguments()[1]; + return _zoneDao.findById(id); + } + } + ); + } catch (Exception e) { + e.printStackTrace(); + } + CallContext.init(mock); + return mock; + } + @Bean + public ExternalDeviceUsageManager externalDeviceUsageManager() { + return Mockito.mock(ExternalDeviceUsageManager.class); + } + @Bean + public GlobalLoadBalancingRulesService globalLoadBalancingRulesService() { + return Mockito.mock(GlobalLoadBalancingRulesService.class); + } + @Bean + public HighAvailabilityManager highAvailabilityManager() { + return Mockito.mock(HighAvailabilityManager.class); + } + @Bean + public HostAllocator hostAllocator() { + return Mockito.mock(HostAllocator.class); + } + @Bean + public IdentityService identityService() { + return Mockito.mock(IdentityService.class); + } + @Bean + public InternalLoadBalancerVMManager internalLoadBalancerVMManager() { + return Mockito.mock(InternalLoadBalancerVMManager.class); + } + @Bean + public InternalLoadBalancerVMService internalLoadBalancerVMService() { + return Mockito.mock(InternalLoadBalancerVMService.class); + } + @Bean + public ApplicationLoadBalancerService applicationLoadBalancerService() { + return Mockito.mock(ApplicationLoadBalancerService.class); + } + @Bean + public ManagementServer managementServer() { + return Mockito.mock(ManagementServer.class); + } + @Bean + public NetworkACLService networkACLService() { + return Mockito.mock(NetworkACLService.class); + } + @Bean + public NetworkUsageService networkUsageService() { + return Mockito.mock(NetworkUsageService.class); + } + @Bean + public OrchestrationService orchSrvc() { + return Mockito.mock(OrchestrationService.class); + } + @Bean + public PodAllocator podAllocator() { + return Mockito.mock(PodAllocator.class); + } + @Bean + public QueryService queryService() { + return Mockito.mock(QueryService.class); + } + @Bean + public RegionManager regionManager() { + return Mockito.mock(RegionManager.class); + } + @Bean + public RemoteAccessVpnService remoteAccessVpnService() { + return Mockito.mock(RemoteAccessVpnService.class); + } + @Bean + public ResourceLimitService resourceLimitService() { + return Mockito.mock(ResourceLimitService.class); + } + @Bean + public ResourceManager resourceManager() { + return Mockito.mock(ResourceManager.class); + } + @Bean + public ResourceMetaDataService resourceMetaDataService() { + return Mockito.mock(ResourceMetaDataService.class); + } + @Bean + public SecondaryStorageVmManager secondaryStorageVmManager() { + return Mockito.mock(SecondaryStorageVmManager.class); + } + @Bean + public Site2SiteVpnManager site2SiteVpnManager() { + return Mockito.mock(Site2SiteVpnManager.class); + } + @Bean + public Site2SiteVpnServiceProvider site2SiteVpnServiceProvider() { + return Mockito.mock(Site2SiteVpnServiceProvider.class); + } + @Bean + public SnapshotApiService snapshotApiService() { + return Mockito.mock(SnapshotApiService.class); + } + @Bean + public SnapshotManager snapshotManager() { + return Mockito.mock(SnapshotManager.class); + } + @Bean + public StorageManager storageManager() { + return Mockito.mock(StorageManager.class); + } + @Bean + public StorageNetworkManager storageNetworkManager() { + return Mockito.mock(StorageNetworkManager.class); + } + @Bean + public StorageNetworkService storageNetworkService() { + return Mockito.mock(StorageNetworkService.class); + } + @Bean + public StoragePoolAllocator storagePoolAllocator() { + return Mockito.mock(StoragePoolAllocator.class); + } + @Bean + public SyncQueueManager syncQueueManager() { + return Mockito.mock(SyncQueueManager.class); + } + @Bean + public TaggedResourceService taggedResourceService() { + return Mockito.mock(TaggedResourceService.class); + } + @Bean + public TemplateDataFactory templateDataFactory() { + return Mockito.mock(TemplateDataFactory.class); + } + @Bean + public TemplateApiService templateApiService() { + return Mockito.mock(TemplateApiService.class); + } + @Bean + public TemplateManager templateManager() { + return Mockito.mock(TemplateManager.class); + } + @Bean + public TemplateService templateService() { + return Mockito.mock(TemplateService.class); + } + @Bean + public UsageService usageService() { + return Mockito.mock(UsageService.class); + } + @Bean + public UserAuthenticator userAuthenticator() { + return Mockito.mock(UserAuthenticator.class); + } + @Bean + public VMSnapshotManager vMSnapshotManager() { + return Mockito.mock(VMSnapshotManager.class); + } + @Bean + public VolumeApiService volumeApiService() { + return Mockito.mock(VolumeApiService.class); + } + @Bean + public VolumeDataFactory volumeDataFactory() { + return Mockito.mock(VolumeDataFactory.class); + } + @Bean + public VolumeOrchestrationService volumeOrchestrationService() { + return Mockito.mock(VolumeOrchestrationService.class); + } + +} diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/ManagementServerMock.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/ManagementServerMock.java new file mode 100644 index 00000000000..82893f1ed90 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/ManagementServerMock.java @@ -0,0 +1,393 @@ +// 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.network.contrail.management; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import javax.inject.Inject; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.command.admin.vlan.CreateVlanIpRangeCmd; +import org.apache.log4j.Logger; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import static org.junit.Assert.*; + +import com.cloud.agent.AgentManager; +import com.cloud.agent.api.PlugNicAnswer; +import com.cloud.agent.api.UnPlugNicAnswer; +import com.cloud.agent.manager.Commands; +import com.cloud.configuration.ConfigurationManager; +import com.cloud.configuration.ConfigurationService; +import com.cloud.dc.DataCenter; +import com.cloud.dc.DataCenter.NetworkType; +import com.cloud.dc.DataCenterVO; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.domain.Domain; +import com.cloud.exception.AgentUnavailableException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.OperationTimedoutException; +import com.cloud.host.Host.Type; +import com.cloud.host.HostVO; +import com.cloud.host.Status; +import com.cloud.host.dao.HostDao; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.network.Network; +import com.cloud.network.Network.Provider; +import com.cloud.network.NetworkService; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.PhysicalNetwork; +import com.cloud.network.PhysicalNetwork.BroadcastDomainRange; +import com.cloud.network.PhysicalNetworkServiceProvider; +import com.cloud.network.PhysicalNetworkTrafficType; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.network.dao.PhysicalNetworkDao; +import com.cloud.network.dao.PhysicalNetworkVO; +import com.cloud.offering.ServiceOffering; +import com.cloud.resource.ResourceState; +import com.cloud.service.ServiceOfferingVO; +import com.cloud.service.dao.ServiceOfferingDao; +import com.cloud.storage.Storage.StoragePoolType; +import com.cloud.storage.VMTemplateVO; +import com.cloud.storage.dao.VMTemplateDao; +import com.cloud.user.Account; +import com.cloud.user.AccountManager; +import com.cloud.user.User; +import com.cloud.uservm.UserVm; +import com.cloud.utils.Pair; +import com.cloud.utils.component.ComponentContext; +import com.cloud.vm.NicProfile; +import com.cloud.vm.UserVmVO; +import com.cloud.vm.VirtualMachineManager; +import com.cloud.vm.dao.UserVmDao; + +public class ManagementServerMock { + private static final Logger s_logger = + Logger.getLogger(ManagementServerMock.class); + + @Inject private AccountManager _accountMgr; + @Inject private ConfigurationService _configService; + @Inject private DataCenterDao _zoneDao; + @Inject private NetworkService _networkService; + @Inject private NetworkDao _networksDao; + @Inject private PhysicalNetworkDao _physicalNetworkDao; + @Inject private UserVmDao _userVmDao; + @Inject private ServiceOfferingDao _serviceOfferingDao; + @Inject private VMTemplateDao _vmTemplateDao; + @Inject private HostDao _hostDao; + @Inject public AgentManager _agentMgr; + @Inject public VirtualMachineManager _vmMgr; + + private DataCenterVO _zone; + private PhysicalNetwork _znet; + + private long _host_id = -1L; + + // TODO: Use the name parameter to retrieve the @Parameter annotation. + static void setParameter(BaseCmd cmd, String name, BaseCmd.CommandType field_type, Object value) { + Class cls = cmd.getClass(); + Field field; + try { + field = cls.getDeclaredField(name); + } catch (Exception ex) { + s_logger.warn("class: " + cls.getName() + "\t" + ex); + return; + } + field.setAccessible(true); + switch (field_type) { + case STRING: + try { + field.set(cmd, value); + } catch (Exception ex) { + s_logger.warn(ex); + return; + } + break; + case UUID: + if (value.equals("-1")) { + try { + field.setLong(cmd, -1L); + } catch (Exception ex) { + s_logger.warn(ex); + return; + } + } + break; + case LONG: + try { + field.set(cmd, value); + } catch (Exception ex) { + s_logger.warn(ex); + return; + } + break; + default: + try { + field.set(cmd, value); + } catch (Exception ex) { + s_logger.warn(ex); + return; + } + break; + } + } + + private void createHost() { + HostVO host = new HostVO(_host_id, "aa01", Type.BaremetalDhcp, + "192.168.1.1", "255.255.255.0", null, + null, null, null, + null, null, null, + null, null, null, + UUID.randomUUID().toString(), Status.Up, "1.0", null, + null, _zone.getId(), null, 0, 0, "aa", 0, StoragePoolType.NetworkFilesystem); + host.setResourceState(ResourceState.Enabled); + _hostDao.persist(host); + _host_id = host.getId(); + } + private void createPublicVlanIpRange() { + CreateVlanIpRangeCmd cmd = new CreateVlanIpRangeCmd(); + BaseCmd proxy = ComponentContext.inject(cmd); + Long public_net_id = null; + + List nets = _networksDao.listByZoneAndTrafficType(_zone.getId(), TrafficType.Public); + if (nets != null && !nets.isEmpty()) { + NetworkVO public_net = nets.get(0); + public_net_id = public_net.getId(); + } else { + s_logger.debug("no public network found in the zone: " + _zone.getId()); + } + Account system = _accountMgr.getSystemAccount(); + + setParameter(cmd, "accountName", BaseCmd.CommandType.STRING, system.getAccountName()); + setParameter(cmd, "domainId", BaseCmd.CommandType.LONG, Domain.ROOT_DOMAIN); + setParameter(cmd, "startIp", BaseCmd.CommandType.STRING, "10.84.60.200"); + setParameter(cmd, "endIp", BaseCmd.CommandType.STRING, "10.84.60.250"); + setParameter(cmd, ApiConstants.GATEWAY, BaseCmd.CommandType.STRING, "10.84.60.254"); + setParameter(cmd, ApiConstants.NETMASK, BaseCmd.CommandType.STRING, "255.255.255.0"); + setParameter(cmd, "networkID", BaseCmd.CommandType.LONG, public_net_id); + setParameter(cmd, "zoneId", BaseCmd.CommandType.LONG, _zone.getId()); + setParameter(cmd, "vlan", BaseCmd.CommandType.STRING, "untagged"); + s_logger.debug("createPublicVlanIpRange execute : zone id: " + _zone.getId() + ", public net id: " + public_net_id); + try { + _configService.createVlanAndPublicIpRange(cmd); + } catch (Exception e) { + s_logger.debug("createPublicVlanIpRange: " + e); + } + } + + + public UserVm createVM(String name, Network network) { + VMTemplateVO tmpl = getVMTemplate(); + assertNotNull(tmpl); + ServiceOffering small = getServiceByName("Small Instance"); + assertNotNull(small); + + Answer callback = new Answer() { + public Object answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Commands cmds = (Commands) args[1]; + if (cmds == null) { + return null; + } + PlugNicAnswer reply = new PlugNicAnswer(null, true, "PlugNic"); + com.cloud.agent.api.Answer[] answers = { reply }; + cmds.setAnswers(answers); + return null; + } + }; + try { + Mockito.when(_agentMgr.send(Mockito.anyLong(), Mockito.any(Commands.class))).thenAnswer(callback); + } catch (AgentUnavailableException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (OperationTimedoutException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + long id = _userVmDao.getNextInSequence(Long.class, "id"); + UserVmVO vm = new UserVmVO(id, name, name, tmpl.getId(), HypervisorType.XenServer, tmpl.getGuestOSId(), + false, false, _zone.getDomainId(), Account.ACCOUNT_ID_SYSTEM, small.getId(), null, name, null); + vm.setState(com.cloud.vm.VirtualMachine.State.Running); + vm.setHostId(_host_id); + vm.setDataCenterId(network.getDataCenterId()); + _userVmDao.persist(vm); + + NicProfile profile = new NicProfile(); + try { + _vmMgr.addVmToNetwork(vm, network, profile); + } catch (Exception ex) { + // TODO Auto-generated catch block + //ex.printStackTrace(); + } + return vm; + } + + private void deleteHost() { + _hostDao.remove(_host_id); + + } + + public void deleteVM(UserVm vm, Network network) { + Answer callback = new Answer() { + public Object answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Commands cmds = (Commands) args[1]; + if (cmds == null) { + return null; + } + UnPlugNicAnswer reply = new UnPlugNicAnswer(null, true, "PlugNic"); + com.cloud.agent.api.Answer[] answers = { reply }; + cmds.setAnswers(answers); + return null; + } + }; + + try { + Mockito.when(_agentMgr.send(Mockito.anyLong(), Mockito.any(Commands.class))).thenAnswer(callback); + } catch (AgentUnavailableException e) { + e.printStackTrace(); + } catch (OperationTimedoutException e) { + e.printStackTrace(); + } + + _userVmDao.remove(vm.getId()); + } + + public void initialize(boolean oneShot) { + locateZone(); + locatePhysicalNetwork(); + createHost(); + if (oneShot) { + createPublicVlanIpRange(); + } + } + + private VMTemplateVO getVMTemplate() { + List tmpl_list = _vmTemplateDao.listDefaultBuiltinTemplates(); + for (VMTemplateVO tmpl: tmpl_list) { + if (tmpl.getHypervisorType() == HypervisorType.XenServer) { + return tmpl; + } + } + return null; + } + + private ServiceOffering getServiceByName(String name) { + List service_list = _serviceOfferingDao.findPublicServiceOfferings(); + for (ServiceOfferingVO service: service_list) { + if (service.getName().equals(name)) { + return service; + } + } + return null; + } + + public DataCenter getZone() { + return _zone; + } + + private void locatePhysicalNetwork() { + // mandatory: name, zone-id + try { + long id = _networkService.findPhysicalNetworkId(_zone.getId(), "znet", TrafficType.Guest); + _znet = _networkService.getPhysicalNetwork(id); + List nets = _physicalNetworkDao.listByZoneAndTrafficType(_zone.getId(), TrafficType.Public); + if (nets == null || nets.isEmpty()) { + _networkService.addTrafficTypeToPhysicalNetwork(_znet.getId(), TrafficType.Public.toString(), null, null, null, null, null); + } + } catch (InvalidParameterValueException e) { + List isolationMethods = new ArrayList(); + isolationMethods.add("GRE"); + _znet = _networkService.createPhysicalNetwork(_zone.getId(), null, null, isolationMethods, + BroadcastDomainRange.ZONE.toString(), _zone.getDomainId(), + null, "znet"); + List nets = _physicalNetworkDao.listByZoneAndTrafficType(_zone.getId(), TrafficType.Public); + if (nets == null || nets.isEmpty()) { + _networkService.addTrafficTypeToPhysicalNetwork(_znet.getId(), TrafficType.Public.toString(), null, null, null, null, null); + } + } + if (_znet.getState() != PhysicalNetwork.State.Enabled) { + _znet = _networkService.updatePhysicalNetwork(_znet.getId(), null, null, null, + PhysicalNetwork.State.Enabled.toString()); + } + + // Ensure that the physical network supports Guest traffic. + Pair, Integer> trafficTypes = + _networkService.listTrafficTypes(_znet.getId()); + boolean found = false; + for (PhysicalNetworkTrafficType ttype: trafficTypes.first()) { + if (ttype.getTrafficType() == TrafficType.Guest) { + found = true; + } + } + if (!found) { + _networkService.addTrafficTypeToPhysicalNetwork(_znet.getId(), TrafficType.Guest.toString(), + null, null, null, null, null); + } + + Pair, Integer> providers = + _networkService.listNetworkServiceProviders(_znet.getId(), Provider.JuniperContrail.getName(), + null, null, null); + if (providers.second() == 0) { + s_logger.debug("Add " + Provider.JuniperContrail.getName() + " to network " + _znet.getName()); + PhysicalNetworkServiceProvider provider = + _networkService.addProviderToPhysicalNetwork(_znet.getId(), Provider.JuniperContrail.getName(), + null, null); + _networkService.updateNetworkServiceProvider(provider.getId(), + PhysicalNetworkServiceProvider.State.Enabled.toString(), null); + } else { + PhysicalNetworkServiceProvider provider = providers.first().get(0); + if (provider.getState() != PhysicalNetworkServiceProvider.State.Enabled) { + _networkService.updateNetworkServiceProvider(provider.getId(), + PhysicalNetworkServiceProvider.State.Enabled.toString(), null); + } + } + + providers = _networkService.listNetworkServiceProviders(_znet.getId(), null, + PhysicalNetworkServiceProvider.State.Enabled.toString(), null, null); + s_logger.debug(_znet.getName() + " has " + providers.second().toString() + " Enabled providers"); + for (PhysicalNetworkServiceProvider provider: providers.first()) { + if (provider.getProviderName().equals(Provider.JuniperContrail.getName())) { + continue; + } + s_logger.debug("Disabling " + provider.getProviderName()); + _networkService.updateNetworkServiceProvider(provider.getId(), + PhysicalNetworkServiceProvider.State.Disabled.toString(), null); + } + } + + private void locateZone() { + _zone = _zoneDao.findByName("default"); + if (_zone == null) { + ConfigurationManager mgr = (ConfigurationManager) _configService; + _zone = mgr.createZone(User.UID_SYSTEM, "default", "8.8.8.8", null, "8.8.4.4", null, + null /* cidr */, "ROOT", Domain.ROOT_DOMAIN, + NetworkType.Advanced, null, null /* networkDomain */, false, false, null, null); + } + } + public void shutdown() { + deleteHost(); + } +} diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/MockAccountManager.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/MockAccountManager.java new file mode 100644 index 00000000000..29dc50acd14 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/MockAccountManager.java @@ -0,0 +1,383 @@ +// 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.network.contrail.management; + +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; +import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; +import org.apache.cloudstack.api.command.admin.user.RegisterCmd; +import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; +import org.apache.cloudstack.context.CallContext; + +import com.cloud.api.query.dao.AccountJoinDao; +import com.cloud.api.query.vo.ControlledViewEntity; +import com.cloud.configuration.ResourceLimit; +import com.cloud.configuration.dao.ResourceCountDao; +import com.cloud.domain.Domain; +import com.cloud.domain.PartOf; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.PermissionDeniedException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.projects.Project.ListProjectResourcesCriteria; +import com.cloud.user.Account; +import com.cloud.user.AccountManager; +import com.cloud.user.AccountVO; +import com.cloud.user.User; +import com.cloud.user.UserAccount; +import com.cloud.user.UserVO; +import com.cloud.user.dao.AccountDao; +import com.cloud.user.dao.UserDao; +import com.cloud.utils.Pair; +import com.cloud.utils.Ternary; +import com.cloud.utils.component.ManagerBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.TransactionCallbackNoReturn; +import com.cloud.utils.db.TransactionStatus; + +public class MockAccountManager extends ManagerBase implements AccountManager { + private static final Logger s_logger = + Logger.getLogger(MockAccountManager.class); + + @Inject AccountDao _accountDao; + @Inject ResourceCountDao _resourceCountDao; + + @Inject AccountJoinDao _accountJoinDao; + @Inject UserDao _userDao; + + UserVO _systemUser; + AccountVO _systemAccount; + + @Override + public boolean configure(final String name, final Map params) throws ConfigurationException { + _systemAccount = _accountDao.findById(AccountVO.ACCOUNT_ID_SYSTEM); + if (_systemAccount == null) { + throw new ConfigurationException("Unable to find the system account using " + Account.ACCOUNT_ID_SYSTEM); + } + + _systemUser = _userDao.findById(UserVO.UID_SYSTEM); + if (_systemUser == null) { + throw new ConfigurationException("Unable to find the system user using " + User.UID_SYSTEM); + } + CallContext.register(_systemUser, _systemAccount); + s_logger.info("MockAccountManager initialization successful"); + return true; + } + + @Override + public void checkAccess(Account arg0, Domain arg1) + throws PermissionDeniedException { + // TODO Auto-generated method stub + + } + + @Override + public void checkAccess(Account arg0, AccessType arg1, boolean arg2, + ControlledEntity... arg3) throws PermissionDeniedException { + // TODO Auto-generated method stub + + } + + @Override + public String[] createApiKeyAndSecretKey(RegisterCmd arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public User createUser(String arg0, String arg1, String arg2, String arg3, + String arg4, String arg5, String arg6, Long arg7, String arg8) { + // TODO Auto-generated method stub + return null; + } + + @Override + public UserAccount createUserAccount(String arg0, String arg1, String arg2, + String arg3, String arg4, String arg5, String arg6, short arg7, + Long arg8, String arg9, Map arg10, String arg11, + String arg12) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Account finalizeOwner(Account arg0, String arg1, Long arg2, Long arg3) { + return _systemAccount; + } + + @Override + public Account getActiveAccountByName(String arg0, Long arg1) { + // TODO Auto-generated method stub + return null; + } + + @Override + public User getActiveUser(long arg0) { + return _systemUser; + } + + @Override + public User getActiveUserByRegistrationToken(String arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public RoleType getRoleType(Account arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Account getSystemAccount() { + return _systemAccount; + } + + @Override + public User getSystemUser() { + return _systemUser; + } + + @Override + public UserAccount getUserByApiKey(String arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public User getUserIncludingRemoved(long arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isAdmin(short arg0) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isRootAdmin(long arg0) { + // TODO Auto-generated method stub + return true; + } + + @Override + public UserAccount lockUser(long arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void markUserRegistered(long arg0) { + // TODO Auto-generated method stub + + } + + @Override + public UserAccount authenticateUser(String arg0, String arg1, Long arg2, + String arg3, Map arg4) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void buildACLSearchBuilder( + SearchBuilder arg0, Long arg1, + boolean arg2, List arg3, ListProjectResourcesCriteria arg4) { + // TODO Auto-generated method stub + + } + + @Override + public void buildACLSearchCriteria( + SearchCriteria arg0, Long arg1, + boolean arg2, List arg3, ListProjectResourcesCriteria arg4) { + // TODO Auto-generated method stub + + } + + @Override + public void buildACLSearchParameters(Account arg0, Long arg1, String arg2, + Long arg3, List arg4, + Ternary arg5, + boolean arg6, boolean arg7) { + // TODO Auto-generated method stub + + } + + @Override + public void buildACLViewSearchBuilder( + SearchBuilder arg0, Long arg1, + boolean arg2, List arg3, ListProjectResourcesCriteria arg4) { + // TODO Auto-generated method stub + + } + + @Override + public void buildACLViewSearchCriteria( + SearchCriteria arg0, Long arg1, + boolean arg2, List arg3, ListProjectResourcesCriteria arg4) { + // TODO Auto-generated method stub + + } + + @Override + public Long checkAccessAndSpecifyAuthority(Account arg0, Long arg1) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean deleteAccount(AccountVO arg0, long arg1, Account arg2) { + return true; + } + + @Override + public boolean deleteUser(DeleteUserCmd arg0) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean deleteUserAccount(long arg0) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean disableAccount(long arg0) + throws ConcurrentOperationException, ResourceUnavailableException { + // TODO Auto-generated method stub + return false; + } + + @Override + public Account disableAccount(String arg0, Long arg1, Long arg2) + throws ConcurrentOperationException, ResourceUnavailableException { + // TODO Auto-generated method stub + return null; + } + + @Override + public UserAccount disableUser(long arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean enableAccount(long arg0) { + // TODO Auto-generated method stub + return false; + } + + @Override + public Account enableAccount(String arg0, Long arg1, Long arg2) { + // TODO Auto-generated method stub + return null; + } + + @Override + public UserAccount enableUser(long arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Pair findUserByApiKey(String arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Account lockAccount(String arg0, Long arg1, Long arg2) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Account updateAccount(UpdateAccountCmd arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public UserAccount updateUser(UpdateUserCmd arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Account getActiveAccountById(long accountId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Account getAccount(long accountId) { + return _systemAccount; + } + + @Override + public Account createAccount(String accountName, short accountType, + Long domainId, String networkDomain, Map details, + String uuid) { + final AccountVO account = new AccountVO(accountName, domainId, networkDomain, accountType, uuid); + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + + _accountDao.persist(account); + _resourceCountDao.createResourceCounts(account.getId(), ResourceLimit.ResourceOwnerType.Account); + } + }); + return account; + } + + @Override + public void logoutUser(long userId) { + // TODO Auto-generated method stub + + } + + @Override + public void checkAccess(Account account, AccessType accessType, boolean sameOwner, PartOf... entities) throws PermissionDeniedException { + // TODO Auto-generated method stub + + } + + @Override + public void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, boolean isRecursive, List permittedAccounts, + ListProjectResourcesCriteria listProjectResourcesCriteria, List grantedIds, List revokedIds) { + // TODO Auto-generated method stub + + } + + +} diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/NetworkProviderTest.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/NetworkProviderTest.java new file mode 100644 index 00000000000..40cd1ea30a8 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/NetworkProviderTest.java @@ -0,0 +1,477 @@ +// 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.network.contrail.management; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.inject.Inject; + +import junit.framework.TestCase; + +import org.apache.cloudstack.network.contrail.management.ContrailManager; +import org.apache.cloudstack.network.contrail.management.ServerDBSync; + +import net.juniper.contrail.api.ApiConnector; +import net.juniper.contrail.api.ApiConnectorFactory; +import net.juniper.contrail.api.ApiConnectorMock; +import net.juniper.contrail.api.types.InstanceIp; +import net.juniper.contrail.api.types.NetworkIpam; +import net.juniper.contrail.api.types.SubnetType; +import net.juniper.contrail.api.types.VirtualMachine; +import net.juniper.contrail.api.types.VirtualMachineInterface; +import net.juniper.contrail.api.types.VirtualNetwork; +import net.juniper.contrail.api.types.VnSubnetsType; +import net.juniper.contrail.api.types.Project; + +import org.apache.log4j.Logger; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.command.user.project.CreateProjectCmd; +import org.apache.cloudstack.api.command.user.project.DeleteProjectCmd; +import org.apache.cloudstack.api.command.user.address.AssociateIPAddrCmd; +import org.apache.cloudstack.api.command.user.nat.EnableStaticNatCmd; +import org.apache.cloudstack.api.command.user.nat.DisableStaticNatCmd; +import org.apache.cloudstack.api.command.user.network.CreateNetworkCmd; +import org.junit.runner.RunWith; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.cloud.utils.db.Merovingian2; +import com.cloud.utils.mgmt.JmxUtil; + +import org.apache.cloudstack.utils.identity.ManagementServerNode; + +import com.cloud.agent.AgentManager; +import com.cloud.dc.DataCenter; +import com.cloud.domain.Domain; +import com.cloud.exception.CloudException; +import com.cloud.network.Network; +import com.cloud.network.NetworkService; +import com.cloud.domain.DomainVO; +import com.cloud.domain.dao.DomainDao; +import com.cloud.projects.ProjectVO; +import com.cloud.projects.dao.ProjectDao; +import com.cloud.user.Account; +import com.cloud.user.AccountManager; +import com.cloud.user.User; +import com.cloud.uservm.UserVm; +import com.cloud.utils.component.ComponentContext; +import com.cloud.utils.component.ComponentLifecycle; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.vm.VirtualMachineManager; +import com.cloud.network.dao.IPAddressDao; +import com.cloud.network.dao.IPAddressVO; + +import org.apache.cloudstack.context.CallContext; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations="classpath:/providerContext.xml") +/** + * Exercise the public API. + */ +public class NetworkProviderTest extends TestCase { + private static final Logger s_logger = + Logger.getLogger(NetworkProviderTest.class); + + @Inject public ContrailManager _contrailMgr; + @Inject public ServerDBSync _dbSync; + @Inject public AccountManager _accountMgr; + @Inject IPAddressDao _ipAddressDao; + @Inject private NetworkService _networkService; + + @Inject public VirtualMachineManager _vmMgr; + + @Inject public DomainDao _domainDao; + @Inject public ProjectDao _projectDao; + @Inject public AgentManager _agentMgr; + + private ManagementServerMock _server; + private ApiConnector _api; + private static int _mysql_server_port; + private static long _msId; + private static Merovingian2 _lockMaster; + public static boolean _initDone = false; + + @BeforeClass + public static void globalSetUp() throws Exception { + ApiConnectorFactory.setImplementation(ApiConnectorMock.class); + s_logger.info("mysql server is getting launched "); + _mysql_server_port = TestDbSetup.init(null); + s_logger.info("mysql server launched on port " + _mysql_server_port); + + _msId = ManagementServerNode.getManagementServerId(); + _lockMaster = Merovingian2.createLockMaster(_msId); + } + + @AfterClass + public static void globalTearDown() throws Exception { + _lockMaster.cleanupForServer(_msId); + JmxUtil.unregisterMBean("Locks", "Locks"); + _lockMaster = null; + + AbstractApplicationContext ctx = (AbstractApplicationContext) ComponentContext.getApplicationContext(); + Map lifecycleComponents = ctx.getBeansOfType(ComponentLifecycle.class); + for (ComponentLifecycle bean: lifecycleComponents.values()) { + bean.stop(); + } + ctx.close(); + + s_logger.info("destroying mysql server instance running at port <" + _mysql_server_port + ">"); + TestDbSetup.destroy(_mysql_server_port, null); + } + + @Before + public void setUp() throws Exception { + try { + ComponentContext.initComponentsLifeCycle(); + } catch (Exception ex) { + ex.printStackTrace(); + s_logger.error(ex.getMessage()); + } + Account system = _accountMgr.getSystemAccount(); + User user = _accountMgr.getSystemUser(); + CallContext.register(user, system); + _server = ComponentContext.inject(new ManagementServerMock()); + + _server.initialize(!_initDone); + _initDone = false; + _api = _contrailMgr.getApiConnector(); + } + + @After + public void tearDown() throws Exception { + _server.shutdown(); + } + + private void purgeTestNetwork() { + Account system = _accountMgr.getSystemAccount(); + DataCenter zone = _server.getZone(); + List list = + _networkService.getIsolatedNetworksOwnedByAccountInZone(zone.getId(), system); + for (Network net : list) { + s_logger.debug("Delete network " + net.getName()); + _networkService.deleteNetwork(net.getId()); + } + } + + private Network lookupTestNetwork(String name) { + Account system = _accountMgr.getSystemAccount(); + DataCenter zone = _server.getZone(); + List list = + _networkService.getIsolatedNetworksOwnedByAccountInZone(zone.getId(), system); + for (Network net : list) { + if (net.getName().equals(name)) { + return net; + } + } + return null; + } + + private Network createTestNetwork(String name) { + CreateNetworkCmd cmd = new CreateNetworkCmd(); + ComponentContext.inject(cmd); + Account system = _accountMgr.getSystemAccount(); + DataCenter zone = _server.getZone(); + + ManagementServerMock.setParameter(cmd, "accountName", BaseCmd.CommandType.STRING, system.getAccountName()); + ManagementServerMock.setParameter(cmd, ApiConstants.NAME, BaseCmd.CommandType.STRING, name); + ManagementServerMock.setParameter(cmd, "displayText", BaseCmd.CommandType.STRING, "test network"); + ManagementServerMock.setParameter(cmd, "networkOfferingId", BaseCmd.CommandType.LONG, _contrailMgr.getOffering().getId()); + ManagementServerMock.setParameter(cmd, "zoneId", BaseCmd.CommandType.LONG, zone.getId()); + ManagementServerMock.setParameter(cmd, ApiConstants.GATEWAY, BaseCmd.CommandType.STRING, "10.0.1.254"); + ManagementServerMock.setParameter(cmd, ApiConstants.NETMASK, BaseCmd.CommandType.STRING, "255.255.255.0"); + // Physical network id can't be specified for Guest traffic type. + // SetParameter(cmd, "physicalNetworkId", BaseCmd.CommandType.LONG, _znet.getId()); + + Network result = null; + try { + result = _networkService.createGuestNetwork(cmd); + } catch (CloudException e) { + e.printStackTrace(); + return null; + } + return result; + } + + + @Test + //@Ignore + public void testCreateNetwork() { + purgeTestNetwork(); + createTestNetwork("test"); + } + + @Test + public void testConnectivity() { + Network network = lookupTestNetwork("test"); + if (network == null) { + network = createTestNetwork("test"); + } + UserVm vm1 = _server.createVM("x01", network); + UserVm vm2 = _server.createVM("x02", network); + + _server.deleteVM(vm1, network); + _server.deleteVM(vm2, network); + } + + @Test + public void floatingIpTest() { + Network network = lookupTestNetwork("test-fip-net"); + if (network == null) { + network = createTestNetwork("test-fip-net"); + } + UserVm vm = _server.createVM("test-fip-vm", network); + try { + IPAddressVO ip = createFloatingIp(network, vm); + deleteFloatingIp(ip); + } catch (Exception e) { + fail("unable to create/delete floating ip"); + } + _server.deleteVM(vm, network); + } + + public void deleteFloatingIp(IPAddressVO ip) throws Exception{ + BaseCmd cmd = new DisableStaticNatCmd(); + BaseCmd proxy = ComponentContext.inject(cmd); + ManagementServerMock.setParameter(proxy, "ipAddressId", BaseCmd.CommandType.LONG, ip.getId()); + try { + proxy.execute(); + } catch (Exception e) { + s_logger.debug("DisableStaticNatCmd exception: " + e); + e.printStackTrace(); + throw e; + } + } + + public IPAddressVO createFloatingIp(Network network, UserVm vm) throws Exception { + BaseCmd cmd = new AssociateIPAddrCmd(); + BaseCmd proxy = ComponentContext.inject(cmd); + Account system = _accountMgr.getSystemAccount(); + DataCenter zone = _server.getZone(); + + ManagementServerMock.setParameter(proxy, "accountName", BaseCmd.CommandType.STRING, system.getAccountName()); + ManagementServerMock.setParameter(proxy, "domainId", BaseCmd.CommandType.LONG, Domain.ROOT_DOMAIN); + ManagementServerMock.setParameter(proxy, "zoneId", BaseCmd.CommandType.LONG, zone.getId()); + ManagementServerMock.setParameter(proxy, "networkId", BaseCmd.CommandType.LONG, network.getId()); + try { + ((AssociateIPAddrCmd)cmd).create(); + ((AssociateIPAddrCmd)cmd).execute(); + } catch (Exception e) { + s_logger.debug("AssociateIPAddrCmd exception: " + e); + e.printStackTrace(); + throw e; + } + + SearchBuilder searchBuilder = _ipAddressDao.createSearchBuilder(); + searchBuilder.and("sourceNat", searchBuilder.entity().isSourceNat(), Op.EQ); + searchBuilder.and("network", searchBuilder.entity().getAssociatedWithNetworkId(), Op.EQ); + searchBuilder.and("dataCenterId", searchBuilder.entity().getDataCenterId(), Op.EQ); + searchBuilder.and("associatedWithVmId", searchBuilder.entity().getAssociatedWithVmId(), Op.NULL); + SearchCriteria sc = searchBuilder.create(); + sc.setParameters("sourceNat", false); + sc.setParameters("network", network.getId()); + + List publicIps = _ipAddressDao.search(sc, null); + assertNotNull(publicIps); + + cmd = new EnableStaticNatCmd(); + proxy = ComponentContext.inject(cmd); + ManagementServerMock.setParameter(proxy, "ipAddressId", BaseCmd.CommandType.LONG, publicIps.get(0).getId()); + ManagementServerMock.setParameter(proxy, "networkId", BaseCmd.CommandType.LONG, network.getId()); + ManagementServerMock.setParameter(proxy, "virtualMachineId", BaseCmd.CommandType.LONG, vm.getId()); + + try { + proxy.execute(); + } catch (Exception e) { + s_logger.debug("EnableStaticNatCmd exception: " + e); + e.printStackTrace(); + throw e; + } + return publicIps.get(0); + } + + public void createProject(String name) { + BaseCmd cmd = new CreateProjectCmd(); + BaseCmd proxy = ComponentContext.inject(cmd); + Account system = _accountMgr.getSystemAccount(); + + ManagementServerMock.setParameter(proxy, "accountName", BaseCmd.CommandType.STRING, system.getAccountName()); + ManagementServerMock.setParameter(proxy, "domainId", BaseCmd.CommandType.LONG, Domain.ROOT_DOMAIN); + ManagementServerMock.setParameter(proxy, "name", BaseCmd.CommandType.STRING, name); + ManagementServerMock.setParameter(proxy, "displayText", BaseCmd.CommandType.STRING, name); + try { + ((CreateProjectCmd)proxy).create(); + ((CreateProjectCmd)proxy).execute(); + } catch (Exception e) { + s_logger.debug("CreateProjectCmd exception: " + e); + e.printStackTrace(); + fail("create project cmd failed"); + } + DomainVO domain = _domainDao.findById(Domain.ROOT_DOMAIN); + try { + net.juniper.contrail.api.types.Domain vncDomain = (net.juniper.contrail.api.types.Domain) + _api.findById(net.juniper.contrail.api.types.Domain.class, domain.getUuid()); + if (_api.findByName(net.juniper.contrail.api.types.Project.class, vncDomain, name) == null) { + fail("create project failed in vnc"); + } + } catch (Exception e) { + e.printStackTrace(); + fail("Exception while creating a project in vnc"); + } + } + + public void deleteProject(String name) { + BaseCmd cmd = new DeleteProjectCmd(); + BaseCmd proxy = ComponentContext.inject(cmd); + + ProjectVO project = _projectDao.findByNameAndDomain(name, Domain.ROOT_DOMAIN); + try { + ManagementServerMock.setParameter(proxy, "id", BaseCmd.CommandType.LONG, project.getId()); + ((DeleteProjectCmd)proxy).execute(); + if (_api.findById(net.juniper.contrail.api.types.Project.class, project.getUuid()) != null) { + fail("unable to delete project in vnc"); + } + } catch (Exception e) { + e.printStackTrace(); + fail("Exception while deleting project"); + } + } + + @Test + public void testProject() { + createProject("test-project"); + deleteProject("test-project"); + } + + @Test + public void dbSyncTest() { + Network network = lookupTestNetwork("test-db-only-net"); + if (network == null) { + network = createTestNetwork("test-db-only-net"); + } + UserVm vm = _server.createVM("test-db-only-vm", network); + try { + createFloatingIp(network, vm); + } catch (Exception e) { + fail("unable to create floating ip"); + } + + /* reset ApiServer objects to default config only, so above created objects + * exists only in cludstack db but not in api server + */ + ((ApiConnectorMock)_api).initConfig(); + /* reset model cached objects */ + _contrailMgr.getDatabase().initDb(); + + /* Create one object of each type directly in api-server - these objects does not exist in cloudstack */ + net.juniper.contrail.api.types.Domain domain = new net.juniper.contrail.api.types.Domain(); + domain.setName("test-vnc-only-domain--1"); + domain.setUuid(UUID.randomUUID().toString()); + try { + assertTrue(_api.create(domain)); + } catch (IOException ex) { + fail(ex.getMessage()); + } + + Project project = new Project(); + project.setName("test-vnc-only-project-1"); + project.setUuid(UUID.randomUUID().toString()); + project.setParent(domain); + try { + assertTrue(_api.create(project)); + } catch (IOException ex) { + fail(ex.getMessage()); + } + + VirtualNetwork net = new VirtualNetwork(); + net.setName("test-vnc-only-net-1"); + net.setUuid(UUID.randomUUID().toString()); + net.setParent(project); + + NetworkIpam ipam = null; + try { + // Find default-network-ipam + String ipam_id = _api.findByName(NetworkIpam.class, null, "default-network-ipam"); + assertNotNull(ipam_id); + ipam = (NetworkIpam) _api.findById(NetworkIpam.class, ipam_id); + assertNotNull(ipam); + } catch (IOException ex) { + fail(ex.getMessage()); + } + + VnSubnetsType subnet = new VnSubnetsType(); + subnet.addIpamSubnets(new SubnetType("10.0.2.0", 24), "10.0.2.254"); + + net.addNetworkIpam(ipam, subnet); + + VirtualMachine vncVm = new VirtualMachine(); + vncVm.setName("test-vnc-only-vm-1"); + try { + assertTrue(_api.create(vncVm)); + } catch (IOException ex) { + fail(ex.getMessage()); + } + + VirtualMachineInterface vmi = new VirtualMachineInterface(); + vmi.setParent(vncVm); + vmi.setName("test-vnc-only-vmi-1"); + + try { + assertTrue(_api.create(vmi)); + assertTrue(_api.create(net)); + } catch (IOException ex) { + fail(ex.getMessage()); + } + InstanceIp ip_obj = new InstanceIp(); + ip_obj.setName(net.getName() + ":0"); + ip_obj.setVirtualNetwork(net); + ip_obj.setVirtualMachineInterface(vmi); + try { + assertTrue(_api.create(ip_obj)); + // Must perform a GET in order to update the object contents. + assertTrue(_api.read(ip_obj)); + assertNotNull(ip_obj.getAddress()); + + } catch (IOException ex) { + fail(ex.getMessage()); + } + + //now db sync + if (_dbSync.syncAll(DBSyncGeneric.SYNC_MODE_UPDATE) == ServerDBSync.SYNC_STATE_OUT_OF_SYNC) { + s_logger.info("# Cloudstack DB & VNC are out of sync - resync done"); + } + + if (_dbSync.syncAll(DBSyncGeneric.SYNC_MODE_CHECK) == ServerDBSync.SYNC_STATE_OUT_OF_SYNC) { + s_logger.info("# Cloudstack DB & VNC are still out of sync"); + fail("DB Sync failed"); + } + } + +} diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/ProviderTestConfiguration.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/ProviderTestConfiguration.java new file mode 100644 index 00000000000..3c215901533 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/ProviderTestConfiguration.java @@ -0,0 +1,30 @@ +/* + * 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.network.contrail.management; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ProviderTestConfiguration { + @Bean + ServerDBSync getServerDBSync() { + return new ServerDBSyncImpl(); + } +} diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/PublicNetworkTest.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/PublicNetworkTest.java new file mode 100644 index 00000000000..e214eb0bd30 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/PublicNetworkTest.java @@ -0,0 +1,147 @@ +// 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.network.contrail.management; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; + +import net.juniper.contrail.api.ApiConnector; +import net.juniper.contrail.api.ApiConnectorFactory; +import net.juniper.contrail.api.ApiObjectBase; +import net.juniper.contrail.api.types.VirtualMachineInterface; +import net.juniper.contrail.api.types.VirtualNetwork; + +import org.apache.cloudstack.utils.identity.ManagementServerNode; +import org.apache.log4j.Logger; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.cloud.dc.DataCenter; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.uservm.UserVm; +import com.cloud.utils.component.ComponentContext; +import com.cloud.utils.component.ComponentLifecycle; +import com.cloud.utils.db.Merovingian2; +import com.cloud.utils.mgmt.JmxUtil; + +import junit.framework.TestCase; +import static org.mockito.Mockito.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations="classpath:/publicNetworkContext.xml") + +public class PublicNetworkTest extends TestCase { + private static final Logger s_logger = + Logger.getLogger(PublicNetworkTest.class); + + @Inject public ContrailManager _contrailMgr; + @Inject public NetworkDao _networksDao; + + private static boolean _initDone = false; + private static int _mysql_server_port; + private static long _msId; + private static Merovingian2 _lockMaster; + private ManagementServerMock _server; + private ApiConnector _spy; + + + @BeforeClass + public static void globalSetUp() throws Exception { + ApiConnectorFactory.setImplementation(ApiConnectorMockito.class); + s_logger.info("mysql server is getting launched "); + _mysql_server_port = TestDbSetup.init(null); + s_logger.info("mysql server launched on port " + _mysql_server_port); + _msId = ManagementServerNode.getManagementServerId(); + _lockMaster = Merovingian2.createLockMaster(_msId); + } + + @AfterClass + public static void globalTearDown() throws Exception { + _lockMaster.cleanupForServer(_msId); + JmxUtil.unregisterMBean("Locks", "Locks"); + _lockMaster = null; + + AbstractApplicationContext ctx = (AbstractApplicationContext) ComponentContext.getApplicationContext(); + Map lifecycleComponents = ctx.getBeansOfType(ComponentLifecycle.class); + for (ComponentLifecycle bean: lifecycleComponents.values()) { + bean.stop(); + } + ctx.close(); + + s_logger.info("destroying mysql server instance running at port <" + _mysql_server_port + ">"); + TestDbSetup.destroy(_mysql_server_port, null); + } + + @Before + public void setUp() throws Exception { + try { + ComponentContext.initComponentsLifeCycle(); + } catch (Exception ex) { + ex.printStackTrace(); + s_logger.error(ex.getMessage()); + } + _server = ComponentContext.inject(new ManagementServerMock()); + + _server.initialize(!_initDone); + _initDone = false; + _spy = ((ApiConnectorMockito)_contrailMgr.getApiConnector()).getSpy(); + } + + @After + public void tearDown() throws Exception { + _server.shutdown(); + } + + @Test + public void testPublicNetwork() throws IOException { + DataCenter zone = _server.getZone(); + List networks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Public); + assertNotNull(networks); + assertFalse(networks.isEmpty()); + UserVm vm1 = _server.createVM("test", networks.get(0)); + + ArgumentCaptor createArg = ArgumentCaptor.forClass(ApiObjectBase.class); + verify(_spy, times(4)).create(createArg.capture()); + + List argumentList = createArg.getAllValues(); + ApiObjectBase vmObj = argumentList.get(0); + assertEquals(VirtualNetwork.class, vmObj.getClass()); + assertEquals("__default_Public__", vmObj.getName()); + + String vmiName = null; + for (ApiObjectBase obj: argumentList) { + if (obj.getClass() == VirtualMachineInterface.class) { + vmiName = obj.getName(); + } + } + assertEquals("test-0", vmiName); + } +} diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/PublicNetworkTestConfiguration.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/PublicNetworkTestConfiguration.java new file mode 100644 index 00000000000..b41e282d934 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/PublicNetworkTestConfiguration.java @@ -0,0 +1,31 @@ +/* + * 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.network.contrail.management; + +import org.mockito.Mockito; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class PublicNetworkTestConfiguration { + @Bean + ServerDBSync getServerDBSync() { + return Mockito.mock(ServerDBSync.class); + } +} diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/TestDbSetup.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/TestDbSetup.java new file mode 100644 index 00000000000..460f7804186 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/TestDbSetup.java @@ -0,0 +1,151 @@ +// 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.network.contrail.management; + +import java.net.ServerSocket; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.File; +import java.util.Properties; +import org.apache.commons.configuration.PropertiesConfiguration; + +import org.apache.log4j.Logger; + +public class TestDbSetup { + + public static int findFreePort() throws Exception { + + int port; + ServerSocket socket= new ServerSocket(0); + port = socket.getLocalPort(); + socket.close(); + + return port; + } + + public static void startMysqlServer(int port, String startMysqlScript) throws Exception { + + try { + String cwd = new java.io.File(".").getCanonicalPath(); + Runtime r = Runtime.getRuntime(); + String script = startMysqlScript; + if (script == null) { + script = "test/resources/mysql_db_start.sh " + port; + } + Process process = r.exec("sh " + cwd + "/" + script); + process.waitFor(); + System.out.println("new sql server instance launched on port: " + port); + } catch (Exception e) { + + String cause = e.getMessage(); + if (cause.equals("sh: not found")) + System.out.println("No sh interpreter found."); + throw e; + } + } + + public static void stopMysqlServer(int port, String stopMysqlScript) throws Exception { + + try { + Runtime r = Runtime.getRuntime(); + String script = stopMysqlScript; + if (script == null) { + script = "test/resources/mysql_db_stop.sh " + port; + } + Process process = r.exec("sh " + script); + process.waitFor(); + System.out.println("sql server instance running at port " + port + " stopped"); + } catch (Exception e) { + + String cause = e.getMessage(); + if (cause.equals("sh: not found")) + System.out.println("No sh interpreter found."); + throw e; + } + } + + /* this is required for deploying db with new set of sql server parameters */ + public static void copyDbPropertiesFile() throws Exception { + Runtime.getRuntime().exec("cp ../../../utils/conf/db.properties ../../../utils/conf/db.properties.override"); + } + + public static void updateSqlPort(int port, String propertyFileOverride) throws Exception { + + PropertiesConfiguration config = new PropertiesConfiguration(propertyFileOverride); + System.out.println("File: " + propertyFileOverride + "; old: db.properties port: " + + config.getProperty("db.cloud.port") + ", new port: " + port); + config.setProperty("db.cloud.port", "" + port); + config.setProperty("db.cloud.username", System.getProperty("user.name")); + config.setProperty("db.cloud.password", ""); + + config.setProperty("db.usage.port", "" + port); + config.setProperty("db.usage.username", System.getProperty("user.name")); + config.setProperty("db.usage.password", ""); + + config.setProperty("db.awsapi.port", "" + port); + config.setProperty("db.awsapi.username", System.getProperty("user.name")); + config.setProperty("db.awsapi.password", ""); + + config.setProperty("db.simulator.port", "" + port); + config.setProperty("db.simulator.username", System.getProperty("user.name")); + config.setProperty("db.simulator.password", ""); + + config.save(); + } + + public static void initCloudstackDb() throws Exception { + try { + File dir = new File("../../../"); + Runtime r = Runtime.getRuntime(); + Process process = r.exec("mvn -P developer -pl developer -Ddeploydb ", null, dir); + dumpProcessOutput(process); + process.waitFor(); + } catch (Exception e) { + String cause = e.getMessage(); + System.out.println("e: " + cause); + throw e; + } + } + + + public static void dumpProcessOutput(Process p) throws Exception { + + BufferedReader istream = null; + istream = new BufferedReader(new InputStreamReader(p.getInputStream())); + String line = null; + while ((line = istream.readLine()) != null) { + System.out.println(line); + } + } + + public static int init(String startScript) throws Exception { + int port = TestDbSetup.findFreePort(); + TestDbSetup.startMysqlServer(port, startScript); + copyDbPropertiesFile(); + /* both of these files needs to have mysql port, username password details */ + TestDbSetup.updateSqlPort(port, "db.properties"); /* for cloudstack runtime */ + TestDbSetup.updateSqlPort(port, "../../../utils/conf/db.properties.override"); /* for deploying db */ + TestDbSetup.initCloudstackDb(); + return port; + } + + public static void destroy(int port, String stopScript) throws Exception { + TestDbSetup.stopMysqlServer(port, stopScript); + } +} + diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/VirtualNetworkModelTest.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/VirtualNetworkModelTest.java new file mode 100644 index 00000000000..02835e57a45 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/VirtualNetworkModelTest.java @@ -0,0 +1,62 @@ +// 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.network.contrail.management; + +import java.util.UUID; + +import org.apache.cloudstack.network.contrail.management.ContrailManager; +import org.apache.cloudstack.network.contrail.management.ModelDatabase; +import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; +import org.apache.log4j.Logger; +import org.junit.Test; +import org.mockito.Mockito; + +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.dao.NetworkVO; + +import junit.framework.TestCase; + +public class VirtualNetworkModelTest extends TestCase { + private static final Logger s_logger = + Logger.getLogger(VirtualNetworkModelTest.class); + + @Test + public void testDBLookup() { + ModelDatabase db = new ModelDatabase(); + NetworkVO network = Mockito.mock(NetworkVO.class); + VirtualNetworkModel storageModel = new VirtualNetworkModel(network, null, ContrailManager.managementNetworkName, + TrafficType.Storage); + db.getVirtualNetworks().add(storageModel); + VirtualNetworkModel mgmtModel = new VirtualNetworkModel(network, null, ContrailManager.managementNetworkName, + TrafficType.Management); + db.getVirtualNetworks().add(mgmtModel); + VirtualNetworkModel guestModel1 = new VirtualNetworkModel(network, UUID.randomUUID().toString(), "test", + TrafficType.Guest); + db.getVirtualNetworks().add(guestModel1); + VirtualNetworkModel guestModel2 = new VirtualNetworkModel(network, UUID.randomUUID().toString(), "test", + TrafficType.Guest); + db.getVirtualNetworks().add(guestModel2); + s_logger.debug("networks: " + db.getVirtualNetworks().size()); + assertEquals(4, db.getVirtualNetworks().size()); + assertSame(storageModel, db.lookupVirtualNetwork(null, storageModel.getName(), TrafficType.Storage)); + assertSame(mgmtModel, db.lookupVirtualNetwork(null, mgmtModel.getName(), TrafficType.Management)); + assertSame(guestModel1, db.lookupVirtualNetwork(guestModel1.getUuid(), null, TrafficType.Guest)); + assertSame(guestModel2, db.lookupVirtualNetwork(guestModel2.getUuid(), null, TrafficType.Guest)); + } + +} diff --git a/plugins/network-elements/juniper-contrail/test/resources/commonContext.xml b/plugins/network-elements/juniper-contrail/test/resources/commonContext.xml new file mode 100644 index 00000000000..c57751328f9 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/resources/commonContext.xml @@ -0,0 +1,172 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/network-elements/juniper-contrail/test/resources/contrail.properties b/plugins/network-elements/juniper-contrail/test/resources/contrail.properties new file mode 100644 index 00000000000..0c5207e3eab --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/resources/contrail.properties @@ -0,0 +1,19 @@ +# 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. + +api.hostname = +api.port = diff --git a/plugins/network-elements/juniper-contrail/test/resources/db.properties b/plugins/network-elements/juniper-contrail/test/resources/db.properties new file mode 100644 index 00000000000..e07d80c112d --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/resources/db.properties @@ -0,0 +1,66 @@ +# 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. + +cluster.servlet.port=9090 + +# CloudStack database settings +db.cloud.username=cloud +db.cloud.password=cloud +db.root.password= +db.cloud.host=localhost +db.cloud.port=3306 +db.cloud.name=cloud + +# CloudStack database tuning parameters +db.cloud.maxActive=250 +db.cloud.maxIdle=30 +db.cloud.maxWait=10000 +db.cloud.autoReconnect=true +db.cloud.validationQuery=SELECT 1 +db.cloud.testOnBorrow=true +db.cloud.testWhileIdle=true +db.cloud.timeBetweenEvictionRunsMillis=40000 +db.cloud.minEvictableIdleTimeMillis=240000 +db.cloud.poolPreparedStatements=false +db.cloud.url.params=prepStmtCacheSize=517&cachePrepStmts=true&prepStmtCacheSqlLimit=4096 + +# usage database settings +db.usage.username=cloud +db.usage.password=cloud +db.usage.host=localhost +db.usage.port=3306 +db.usage.name=cloud_usage + +# usage database tuning parameters +db.usage.maxActive=100 +db.usage.maxIdle=30 +db.usage.maxWait=10000 +db.usage.autoReconnect=true + +# awsapi database settings +db.awsapi.name=cloudbridge + +# Simulator database settings +db.simulator.username=cloud +db.simulator.password=cloud +db.simulator.host=localhost +db.simulator.port=3306 +db.simulator.name=simulator +db.simulator.maxActive=250 +db.simulator.maxIdle=30 +db.simulator.maxWait=10000 +db.simulator.autoReconnect=true diff --git a/plugins/network-elements/juniper-contrail/test/resources/log4j.properties b/plugins/network-elements/juniper-contrail/test/resources/log4j.properties new file mode 100644 index 00000000000..138a9610873 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/resources/log4j.properties @@ -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. + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n +log4j.appender.stdout.threshold=INFO +log4j.rootLogger=INFO, stdout, rolling +log4j.appender.rolling=org.apache.log4j.DailyRollingFileAppender +log4j.appender.rolling.layout=org.apache.log4j.PatternLayout +log4j.appender.rolling.layout.ConversionPattern=%d %-5p [%c{3}] (%t:%x) %m%n +log4j.appender.rolling.file.threshold=DEBUG +log4j.appender.rolling.File=./logs/testclient.log +log4j.appender.rolling.DatePattern='.'yyy-MM-dd +log4j.appender.rolling.file.append=false +log4j.category.org.apache=INFO, rolling, stdout +#log4j.category.com.cloud.utils.db.Transaction=ALL +log4j.category.org.apache.cloudstack.network.contrail=ALL +log4j.category.com.cloud.network=ALL + diff --git a/plugins/network-elements/juniper-contrail/test/resources/mysql_db_start.sh b/plugins/network-elements/juniper-contrail/test/resources/mysql_db_start.sh new file mode 100644 index 00000000000..265cdea40be --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/resources/mysql_db_start.sh @@ -0,0 +1,51 @@ +# 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. + +if [ "$#" -ne 1 ] ; then + echo "Usage: $0 " >&2 + exit 1 +fi + +PORT=$1 +echo "starting mysql on port: "$PORT + +echo "creating temporary mysql db directories /tmp/mysql"$PORT +mkdir /tmp/mysql$PORT +mkdir /tmp/mysql$PORT/data + +echo "install db"; + +mysql_install_db --user=$USER --datadir=/tmp/mysql$PORT/data +mysqld_safe --datadir=/tmp/mysql$PORT/data --socket=/tmp/mysql$PORT/mysqld.sock --port=$PORT --log-error=/tmp/mysql$PORT/mysql.log --pid-file=/tmp/mysql$PORT/mysql.pid --user=$USER & + +attempts=0 +while [ $attempts -lt 30 ]; do + db=$(mysql -h 127.0.0.1 -P $PORT --user=$USER -e "show databases;") + status=$? + if [ $status == 0 ]; then + break + fi + attempts=`expr $attempts + 1` + sleep 1 +done + +echo "new mysql server is started on port "$PORT +echo $db + +echo "commands ...." +echo "to connect(from local host): mysql -h 127.0.0.1 -P "$PORT +echo "to stop: mysqladmin -S /tmp/mysql"$PORT"/mysqld.sock shutdown -u root" diff --git a/plugins/network-elements/juniper-contrail/test/resources/mysql_db_stop.sh b/plugins/network-elements/juniper-contrail/test/resources/mysql_db_stop.sh new file mode 100644 index 00000000000..62d70d3956e --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/resources/mysql_db_stop.sh @@ -0,0 +1,31 @@ +# 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. + +if [ "$#" -ne 1 ] ; then + echo "Usage: $0 " >&2 + exit 1 +fi + +echo "Stopping mysql server on port "$1 + +mysqladmin -S /tmp/mysql$1/mysqld.sock shutdown -u root + +rm -rf /tmp/mysql$1 + +echo "Deleting db directories" + + diff --git a/plugins/network-elements/juniper-contrail/test/resources/providerContext.xml b/plugins/network-elements/juniper-contrail/test/resources/providerContext.xml new file mode 100644 index 00000000000..62a9f6286f0 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/resources/providerContext.xml @@ -0,0 +1,34 @@ + + + + + + \ No newline at end of file diff --git a/plugins/network-elements/juniper-contrail/test/resources/publicNetworkContext.xml b/plugins/network-elements/juniper-contrail/test/resources/publicNetworkContext.xml new file mode 100644 index 00000000000..db978e7268c --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/resources/publicNetworkContext.xml @@ -0,0 +1,26 @@ + + + + + + \ No newline at end of file diff --git a/plugins/network-elements/nicira-nvp/pom.xml b/plugins/network-elements/nicira-nvp/pom.xml index 5030ddf02c5..9341c93c381 100644 --- a/plugins/network-elements/nicira-nvp/pom.xml +++ b/plugins/network-elements/nicira-nvp/pom.xml @@ -26,4 +26,39 @@ 4.3.0-SNAPSHOT ../../pom.xml + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${cs.checkstyle.version} + + + org.apache.cloudstack + checkstyle + ${project.version} + + + + + process-sources + + check + + + + + true + tooling/checkstyle.xml + true + true + ${project.basedir} + **\/*.java,**\/*.xml,**\/*.ini,**\/*.sh,**\/*.bat + **\/target\/,**\/bin\/ + + + + + diff --git a/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml b/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml index 302b072c8d0..8d9813a020e 100644 --- a/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml +++ b/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml @@ -36,5 +36,5 @@ - + diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java index 40bde6c6e74..94931a098af 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java @@ -5,7 +5,7 @@ // 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, @@ -17,18 +17,16 @@ package com.cloud.agent.api; /** - * + * */ public class ConfigurePortForwardingRulesOnLogicalRouterAnswer extends Answer { - public ConfigurePortForwardingRulesOnLogicalRouterAnswer(Command command, - boolean success, String details) { - super(command, success, details); - } + public ConfigurePortForwardingRulesOnLogicalRouterAnswer(Command command, boolean success, String details) { + super(command, success, details); + } - public ConfigurePortForwardingRulesOnLogicalRouterAnswer(Command command, - Exception e) { - super(command, e); - } + public ConfigurePortForwardingRulesOnLogicalRouterAnswer(Command command, Exception e) { + super(command, e); + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java index 5f0ea384af3..16ef2c41eac 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java @@ -5,7 +5,7 @@ // 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, @@ -21,40 +21,41 @@ import java.util.List; import com.cloud.agent.api.to.PortForwardingRuleTO; /** - * + * */ public class ConfigurePortForwardingRulesOnLogicalRouterCommand extends Command { - - private String logicalRouterUuid; - private List rules; - public ConfigurePortForwardingRulesOnLogicalRouterCommand(String logicalRouterUuid, List rules) { - this.logicalRouterUuid = logicalRouterUuid; - this.rules = rules; - } - - public String getLogicalRouterUuid() { - return logicalRouterUuid; - } + private String logicalRouterUuid; + private List rules; - public void setLogicalRouterUuid(String logicalRouterUuid) { - this.logicalRouterUuid = logicalRouterUuid; - } + public ConfigurePortForwardingRulesOnLogicalRouterCommand(String logicalRouterUuid, List rules) { + this.logicalRouterUuid = logicalRouterUuid; + this.rules = rules; + } - public List getRules() { - return rules; - } + public String getLogicalRouterUuid() { + return logicalRouterUuid; + } - public void setRules(List rules) { - this.rules = rules; - } + public void setLogicalRouterUuid(String logicalRouterUuid) { + this.logicalRouterUuid = logicalRouterUuid; + } - /* (non-Javadoc) - * @see com.cloud.agent.api.Command#executeInSequence() - */ - @Override - public boolean executeInSequence() { - return false; - } + public List getRules() { + return rules; + } + + public void setRules(List rules) { + this.rules = rules; + } + + /* + * (non-Javadoc) + * @see com.cloud.agent.api.Command#executeInSequence() + */ + @Override + public boolean executeInSequence() { + return false; + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java index 12b1a1ffb3f..09a3e7e2af5 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java @@ -18,13 +18,12 @@ package com.cloud.agent.api; public class ConfigurePublicIpsOnLogicalRouterAnswer extends Answer { - public ConfigurePublicIpsOnLogicalRouterAnswer(Command command, - boolean success, String details) { - super(command, success, details); - } + public ConfigurePublicIpsOnLogicalRouterAnswer(Command command, boolean success, String details) { + super(command, success, details); + } - public ConfigurePublicIpsOnLogicalRouterAnswer(Command command, Exception e) { - super(command, e); - } + public ConfigurePublicIpsOnLogicalRouterAnswer(Command command, Exception e) { + super(command, e); + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java index 8ee3793ed89..c08f540e698 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java @@ -19,47 +19,45 @@ package com.cloud.agent.api; import java.util.List; public class ConfigurePublicIpsOnLogicalRouterCommand extends Command { - - private String logicalRouterUuid; - private String l3GatewayServiceUuid; - private List publicCidrs; - - public ConfigurePublicIpsOnLogicalRouterCommand(String logicalRouterUuid, - String l3GatewayServiceUuid, - List publicCidrs) { - super(); - this.logicalRouterUuid = logicalRouterUuid; - this.publicCidrs = publicCidrs; - this.l3GatewayServiceUuid = l3GatewayServiceUuid; - } - public String getLogicalRouterUuid() { - return logicalRouterUuid; - } + private String logicalRouterUuid; + private String l3GatewayServiceUuid; + private List publicCidrs; - public void setLogicalRouterUuid(String logicalRouterUuid) { - this.logicalRouterUuid = logicalRouterUuid; - } - - public String getL3GatewayServiceUuid() { - return l3GatewayServiceUuid; - } + public ConfigurePublicIpsOnLogicalRouterCommand(String logicalRouterUuid, String l3GatewayServiceUuid, List publicCidrs) { + super(); + this.logicalRouterUuid = logicalRouterUuid; + this.publicCidrs = publicCidrs; + this.l3GatewayServiceUuid = l3GatewayServiceUuid; + } - public void setL3GatewayServiceUuid(String l3GatewayServiceUuid) { - this.l3GatewayServiceUuid = l3GatewayServiceUuid; - } + public String getLogicalRouterUuid() { + return logicalRouterUuid; + } - public List getPublicCidrs() { - return publicCidrs; - } + public void setLogicalRouterUuid(String logicalRouterUuid) { + this.logicalRouterUuid = logicalRouterUuid; + } - public void setPublicCidrs(List publicCidrs) { - this.publicCidrs = publicCidrs; - } + public String getL3GatewayServiceUuid() { + return l3GatewayServiceUuid; + } - @Override - public boolean executeInSequence() { - return false; - } + public void setL3GatewayServiceUuid(String l3GatewayServiceUuid) { + this.l3GatewayServiceUuid = l3GatewayServiceUuid; + } + + public List getPublicCidrs() { + return publicCidrs; + } + + public void setPublicCidrs(List publicCidrs) { + this.publicCidrs = publicCidrs; + } + + @Override + public boolean executeInSequence() { + return false; + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java index 463dd4628cf..caab316a783 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java @@ -5,7 +5,7 @@ // 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, @@ -17,27 +17,25 @@ package com.cloud.agent.api; /** - * + * */ public class ConfigureStaticNatRulesOnLogicalRouterAnswer extends Answer { - /** - * @param command - * @param success - * @param details - */ - public ConfigureStaticNatRulesOnLogicalRouterAnswer(Command command, - boolean success, String details) { - super(command, success, details); - } + /** + * @param command + * @param success + * @param details + */ + public ConfigureStaticNatRulesOnLogicalRouterAnswer(Command command, boolean success, String details) { + super(command, success, details); + } - /** - * @param command - * @param e - */ - public ConfigureStaticNatRulesOnLogicalRouterAnswer(Command command, - Exception e) { - super(command, e); - } + /** + * @param command + * @param e + */ + public ConfigureStaticNatRulesOnLogicalRouterAnswer(Command command, Exception e) { + super(command, e); + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java index 960f609cb54..5f79ffc8b85 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java @@ -5,7 +5,7 @@ // 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, @@ -21,43 +21,43 @@ import java.util.List; import com.cloud.agent.api.to.StaticNatRuleTO; /** - * + * */ public class ConfigureStaticNatRulesOnLogicalRouterCommand extends Command { - - private String logicalRouterUuid; - private List rules; - public ConfigureStaticNatRulesOnLogicalRouterCommand( - String logicalRouterUuid, List rules) { - super(); - this.logicalRouterUuid = logicalRouterUuid; - this.rules = rules; + private String logicalRouterUuid; + private List rules; - } + public ConfigureStaticNatRulesOnLogicalRouterCommand(String logicalRouterUuid, List rules) { + super(); + this.logicalRouterUuid = logicalRouterUuid; + this.rules = rules; - public String getLogicalRouterUuid() { - return logicalRouterUuid; - } + } - public void setLogicalRouterUuid(String logicalRouterUuid) { - this.logicalRouterUuid = logicalRouterUuid; - } + public String getLogicalRouterUuid() { + return logicalRouterUuid; + } - public List getRules() { - return rules; - } + public void setLogicalRouterUuid(String logicalRouterUuid) { + this.logicalRouterUuid = logicalRouterUuid; + } - public void setRules(List rules) { - this.rules = rules; - } + public List getRules() { + return rules; + } - /* (non-Javadoc) - * @see com.cloud.agent.api.Command#executeInSequence() - */ - @Override - public boolean executeInSequence() { - return false; - } + public void setRules(List rules) { + this.rules = rules; + } + + /* + * (non-Javadoc) + * @see com.cloud.agent.api.Command#executeInSequence() + */ + @Override + public boolean executeInSequence() { + return false; + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterAnswer.java index 4a09e449af8..72a275baa75 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterAnswer.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterAnswer.java @@ -5,7 +5,7 @@ // 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, @@ -17,7 +17,7 @@ package com.cloud.agent.api; /** - * + * */ public class CreateLogicalRouterAnswer extends Answer { @@ -26,9 +26,9 @@ public class CreateLogicalRouterAnswer extends Answer { public CreateLogicalRouterAnswer(Command command, boolean success, String details, String logicalRouterUuid) { super(command, success, details); - this._logicalRouterUuid = logicalRouterUuid; + _logicalRouterUuid = logicalRouterUuid; } - + public CreateLogicalRouterAnswer(Command command, Exception e) { super(command, e); } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterCommand.java index 57440dfc4b0..1f3f24e2152 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterCommand.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterCommand.java @@ -5,7 +5,7 @@ // 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, @@ -17,99 +17,99 @@ package com.cloud.agent.api; /** - * + * */ public class CreateLogicalRouterCommand extends Command { - private String _gatewayServiceUuid; - private String _logicalSwitchUuid; - private long _vlanId; - private String _name; - private String _ownerName; - private String _publicIpCidr; - private String _publicNextHop; - private String _internalIpCidr; - - public CreateLogicalRouterCommand(String gatewayServiceUuid, long vlanId, - String logicalSwitchUuid, String name, - String publicIpCidr, String publicNextHop, - String internalIpCidr, String ownerName) { - super(); - this._gatewayServiceUuid = gatewayServiceUuid; - this._logicalSwitchUuid = logicalSwitchUuid; - this._vlanId = vlanId; - this._name = name; - this._ownerName = ownerName; - this._publicIpCidr = publicIpCidr; - this._publicNextHop = publicNextHop; - this._internalIpCidr = internalIpCidr; - } - + private String _gatewayServiceUuid; + private String _logicalSwitchUuid; + private long _vlanId; + private String _name; + private String _ownerName; + private String _publicIpCidr; + private String _publicNextHop; + private String _internalIpCidr; + + public CreateLogicalRouterCommand(String gatewayServiceUuid, long vlanId, + String logicalSwitchUuid, String name, + String publicIpCidr, String publicNextHop, + String internalIpCidr, String ownerName) { + super(); + _gatewayServiceUuid = gatewayServiceUuid; + _logicalSwitchUuid = logicalSwitchUuid; + _vlanId = vlanId; + _name = name; + _ownerName = ownerName; + _publicIpCidr = publicIpCidr; + _publicNextHop = publicNextHop; + _internalIpCidr = internalIpCidr; + } + @Override public boolean executeInSequence() { return false; } - public String getGatewayServiceUuid() { - return _gatewayServiceUuid; - } + public String getGatewayServiceUuid() { + return _gatewayServiceUuid; + } - public void setGatewayServiceUuid(String gatewayServiceUuid) { - this._gatewayServiceUuid = gatewayServiceUuid; - } - - public String getLogicalSwitchUuid() { - return _logicalSwitchUuid; - } - - public void setLogicalSwitchUuid(String logicalSwitchUuid) { - _logicalSwitchUuid = logicalSwitchUuid; - } + public void setGatewayServiceUuid(String gatewayServiceUuid) { + _gatewayServiceUuid = gatewayServiceUuid; + } - public long getVlanId() { - return _vlanId; - } + public String getLogicalSwitchUuid() { + return _logicalSwitchUuid; + } - public void setVlanId(long vlanId) { - this._vlanId = vlanId; - } + public void setLogicalSwitchUuid(String logicalSwitchUuid) { + _logicalSwitchUuid = logicalSwitchUuid; + } - public String getName() { - return _name; - } + public long getVlanId() { + return _vlanId; + } - public void setName(String name) { - this._name = name; - } + public void setVlanId(long vlanId) { + _vlanId = vlanId; + } - public String getOwnerName() { - return _ownerName; - } + public String getName() { + return _name; + } - public void setOwnerName(String ownerName) { - this._ownerName = ownerName; - } + public void setName(String name) { + _name = name; + } - public String getPublicIpCidr() { - return _publicIpCidr; - } + public String getOwnerName() { + return _ownerName; + } - public void setPublicIpCidr(String publicIpCidr) { - this._publicIpCidr = publicIpCidr; - } + public void setOwnerName(String ownerName) { + _ownerName = ownerName; + } - public String getInternalIpCidr() { - return _internalIpCidr; - } + public String getPublicIpCidr() { + return _publicIpCidr; + } - public void setInternalIpCidr(String internalIpCidr) { - this._internalIpCidr = internalIpCidr; - } - - public String getPublicNextHop() { - return _publicNextHop; - } - - public void setPublicNextHop(String publicNextHop) { - this._publicNextHop = publicNextHop; - } + public void setPublicIpCidr(String publicIpCidr) { + _publicIpCidr = publicIpCidr; + } + + public String getInternalIpCidr() { + return _internalIpCidr; + } + + public void setInternalIpCidr(String internalIpCidr) { + _internalIpCidr = internalIpCidr; + } + + public String getPublicNextHop() { + return _publicNextHop; + } + + public void setPublicNextHop(String publicNextHop) { + _publicNextHop = publicNextHop; + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchAnswer.java index d8c864de99b..753edecba61 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchAnswer.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchAnswer.java @@ -22,9 +22,9 @@ public class CreateLogicalSwitchAnswer extends Answer { public CreateLogicalSwitchAnswer(Command command, boolean success, String details, String logicalSwitchUuid) { super(command, success, details); - this._logicalSwitchUuid = logicalSwitchUuid; + _logicalSwitchUuid = logicalSwitchUuid; } - + public CreateLogicalSwitchAnswer(Command command, Exception e) { super(command, e); } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchCommand.java index 83b03bcade2..b2a5aaf1f6a 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchCommand.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchCommand.java @@ -17,17 +17,17 @@ package com.cloud.agent.api; public class CreateLogicalSwitchCommand extends Command { - + private String _transportUuid; private String _transportType; private String _name; private String _ownerName; public CreateLogicalSwitchCommand(String transportUuid, String transportType, String name, String ownerName) { - this._transportUuid = transportUuid; - this._transportType = transportType; - this._name = name; - this._ownerName = ownerName; + _transportUuid = transportUuid; + _transportType = transportType; + _name = name; + _ownerName = ownerName; } @Override diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java index 6c6ce770181..8fa7927d734 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java @@ -22,9 +22,9 @@ public class CreateLogicalSwitchPortAnswer extends Answer { public CreateLogicalSwitchPortAnswer(Command command, boolean success, String details, String localSwitchPortUuid) { super(command, success, details); - this._logicalSwitchPortUuid = localSwitchPortUuid; + _logicalSwitchPortUuid = localSwitchPortUuid; } - + public String getLogicalSwitchPortUuid() { return _logicalSwitchPortUuid; } @@ -32,5 +32,5 @@ public class CreateLogicalSwitchPortAnswer extends Answer { public CreateLogicalSwitchPortAnswer(Command command, Exception e) { super(command, e); } - + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java index 5a28432bac1..fe3f6835499 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java @@ -21,15 +21,15 @@ public class CreateLogicalSwitchPortCommand extends Command { private String _attachmentUuid; private String _ownerName; private String _nicName; - + public CreateLogicalSwitchPortCommand(String logicalSwitchUuid, String attachmentUuid, String ownerName, String nicName) { - this._logicalSwitchUuid = logicalSwitchUuid; - this._attachmentUuid = attachmentUuid; - this._ownerName = ownerName; - this._nicName = nicName; + _logicalSwitchUuid = logicalSwitchUuid; + _attachmentUuid = attachmentUuid; + _ownerName = ownerName; + _nicName = nicName; } - - + + public String getLogicalSwitchUuid() { return _logicalSwitchUuid; } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterAnswer.java index 8a6bb9f193a..db0754744c8 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterAnswer.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterAnswer.java @@ -5,7 +5,7 @@ // 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, @@ -17,10 +17,10 @@ package com.cloud.agent.api; /** - * + * */ public class DeleteLogicalRouterAnswer extends Answer { - + public DeleteLogicalRouterAnswer(Command command, boolean success, String details) { super(command, success, details); diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterCommand.java index 4799f9e58fe..96e2cb9d8f8 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterCommand.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterCommand.java @@ -5,7 +5,7 @@ // 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, @@ -17,25 +17,26 @@ package com.cloud.agent.api; /** - * + * */ public class DeleteLogicalRouterCommand extends Command { - - private String _logicalRouterUuid; - - public DeleteLogicalRouterCommand(String logicalRouterUuid) { - this._logicalRouterUuid = logicalRouterUuid; - } - /* (non-Javadoc) - * @see com.cloud.agent.api.Command#executeInSequence() - */ - @Override - public boolean executeInSequence() { - return false; - } + private String _logicalRouterUuid; - public String getLogicalRouterUuid() { - return _logicalRouterUuid; - } + public DeleteLogicalRouterCommand(String logicalRouterUuid) { + _logicalRouterUuid = logicalRouterUuid; + } + + /* + * (non-Javadoc) + * @see com.cloud.agent.api.Command#executeInSequence() + */ + @Override + public boolean executeInSequence() { + return false; + } + + public String getLogicalRouterUuid() { + return _logicalRouterUuid; + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchCommand.java index ce6b82bce03..25aa3393b91 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchCommand.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchCommand.java @@ -17,11 +17,11 @@ package com.cloud.agent.api; public class DeleteLogicalSwitchCommand extends Command { - + private String _logicalSwitchUuid; - + public DeleteLogicalSwitchCommand(String logicalSwitchUuid) { - this._logicalSwitchUuid = logicalSwitchUuid; + _logicalSwitchUuid = logicalSwitchUuid; } @Override diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java index aad6eeacd6f..e91a03208af 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java @@ -19,16 +19,16 @@ package com.cloud.agent.api; public class DeleteLogicalSwitchPortCommand extends Command { private String _logicalSwitchUuid; private String _logicalSwithPortUuid; - + public DeleteLogicalSwitchPortCommand(String logicalSwitchUuid, String logicalSwitchPortUuid) { - this._logicalSwitchUuid = logicalSwitchUuid; - this._logicalSwithPortUuid = logicalSwitchPortUuid; + _logicalSwitchUuid = logicalSwitchUuid; + _logicalSwithPortUuid = logicalSwitchPortUuid; } - + public String getLogicalSwitchUuid() { return _logicalSwitchUuid; } - + public String getLogicalSwitchPortUuid() { return _logicalSwithPortUuid; } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java index f54bd85882d..edc0c5f8119 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java @@ -22,9 +22,9 @@ public class FindLogicalSwitchPortAnswer extends Answer { public FindLogicalSwitchPortAnswer(Command command, boolean success, String details, String localSwitchPortUuid) { super(command, success, details); - this._logicalSwitchPortUuid = localSwitchPortUuid; + _logicalSwitchPortUuid = localSwitchPortUuid; } - + public String getLogicalSwitchPortUuid() { return _logicalSwitchPortUuid; } @@ -32,5 +32,5 @@ public class FindLogicalSwitchPortAnswer extends Answer { public FindLogicalSwitchPortAnswer(Command command, Exception e) { super(command, e); } - + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortCommand.java index cccce67182b..b737c50a3e4 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortCommand.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortCommand.java @@ -17,25 +17,25 @@ package com.cloud.agent.api; public class FindLogicalSwitchPortCommand extends Command { - private String _logicalSwitchUuid; + private String _logicalSwitchUuid; private String _logicalSwitchPortUuid; - + public FindLogicalSwitchPortCommand(String logicalSwitchUuid, String logicalSwitchPortUuid) { - this._logicalSwitchUuid = logicalSwitchUuid; - this._logicalSwitchPortUuid = logicalSwitchPortUuid; + _logicalSwitchUuid = logicalSwitchUuid; + _logicalSwitchPortUuid = logicalSwitchPortUuid; } - - + + public String getLogicalSwitchUuid() { return _logicalSwitchUuid; } - + public String getLogicalSwitchPortUuid() { return _logicalSwitchPortUuid; } - + @Override public boolean executeInSequence() { return false; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java index 3b7fbf7f2ae..f4c4130d153 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java @@ -22,9 +22,9 @@ public class UpdateLogicalSwitchPortAnswer extends Answer { public UpdateLogicalSwitchPortAnswer(Command command, boolean success, String details, String localSwitchPortUuid) { super(command, success, details); - this._logicalSwitchPortUuid = localSwitchPortUuid; + _logicalSwitchPortUuid = localSwitchPortUuid; } - + public String getLogicalSwitchPortUuid() { return _logicalSwitchPortUuid; } @@ -32,5 +32,5 @@ public class UpdateLogicalSwitchPortAnswer extends Answer { public UpdateLogicalSwitchPortAnswer(Command command, Exception e) { super(command, e); } - + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java index 83ae23146b5..1b8b5907f94 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java @@ -22,16 +22,16 @@ public class UpdateLogicalSwitchPortCommand extends Command { private String _attachmentUuid; private String _ownerName; private String _nicName; - + public UpdateLogicalSwitchPortCommand(String logicalSwitchPortUuid, String logicalSwitchUuid, String attachmentUuid, String ownerName, String nicName) { - this._logicalSwitchUuid = logicalSwitchUuid; - this._logicalSwitchPortUuid = logicalSwitchPortUuid; - this._attachmentUuid = attachmentUuid; - this._ownerName = ownerName; - this._nicName = nicName; + _logicalSwitchUuid = logicalSwitchUuid; + _logicalSwitchPortUuid = logicalSwitchPortUuid; + _attachmentUuid = attachmentUuid; + _ownerName = ownerName; + _nicName = nicName; } - - + + public String getLogicalSwitchUuid() { return _logicalSwitchUuid; } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java index 7f0d87c1564..937b665200e 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java @@ -18,12 +18,15 @@ package com.cloud.api.commands; import javax.inject.Inject; -import org.apache.cloudstack.api.*; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; - import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.cloudstack.context.CallContext; import com.cloud.api.response.NiciraNvpDeviceResponse; @@ -42,7 +45,7 @@ public class AddNiciraNvpDeviceCmd extends BaseAsyncCmd { private static final Logger s_logger = Logger.getLogger(AddNiciraNvpDeviceCmd.class.getName()); private static final String s_name = "addniciranvpdeviceresponse"; @Inject NiciraNvpElementService _niciraNvpElementService; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -56,16 +59,16 @@ public class AddNiciraNvpDeviceCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required = true, description="Credentials to access the Nicira Controller API") private String username; - + @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required = true, description="Credentials to access the Nicira Controller API") private String password; - + @Parameter(name=ApiConstants.NICIRA_NVP_TRANSPORT_ZONE_UUID, type=CommandType.STRING, required = true, description="The Transportzone UUID configured on the Nicira Controller") private String transportzoneuuid; - + @Parameter(name=ApiConstants.NICIRA_NVP_GATEWAYSERVICE_UUID, type=CommandType.STRING, required = false, description="The L3 Gateway Service UUID configured on the Nicira Controller") private String l3gatewayserviceuuid; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -85,13 +88,13 @@ public class AddNiciraNvpDeviceCmd extends BaseAsyncCmd { public String getPassword() { return password; } - + public String getTransportzoneUuid() { return transportzoneuuid; } - + public String getL3GatewayServiceUuid() { - return l3gatewayserviceuuid; + return l3gatewayserviceuuid; } ///////////////////////////////////////////////////// @@ -106,7 +109,7 @@ public class AddNiciraNvpDeviceCmd extends BaseAsyncCmd { NiciraNvpDeviceResponse response = _niciraNvpElementService.createNiciraNvpDeviceResponse(niciraNvpDeviceVO); response.setObjectName("niciranvpdevice"); response.setResponseName(getCommandName()); - this.setResponseObject(response); + setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Nicira NVP device due to internal error."); } @@ -116,7 +119,7 @@ public class AddNiciraNvpDeviceCmd extends BaseAsyncCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } - + @Override public String getCommandName() { return s_name; @@ -127,13 +130,13 @@ public class AddNiciraNvpDeviceCmd extends BaseAsyncCmd { return CallContext.current().getCallingAccount().getId(); } - @Override - public String getEventType() { - return EventTypes.EVENT_EXTERNAL_NVP_CONTROLLER_ADD; - } + @Override + public String getEventType() { + return EventTypes.EVENT_EXTERNAL_NVP_CONTROLLER_ADD; + } - @Override - public String getEventDescription() { - return "Adding a Nicira Nvp Controller"; - } + @Override + public String getEventDescription() { + return "Adding a Nicira Nvp Controller"; + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java index 948f1bf1c6a..6eb67644a40 100755 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java @@ -18,20 +18,18 @@ package com.cloud.api.commands; import javax.inject.Inject; -import com.cloud.api.response.NiciraNvpDeviceResponse; - import org.apache.log4j.Logger; +import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.context.CallContext; +import com.cloud.api.response.NiciraNvpDeviceResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -74,7 +72,7 @@ public class DeleteNiciraNvpDeviceCmd extends BaseAsyncCmd { if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); response.setResponseName(getCommandName()); - this.setResponseObject(response); + setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete Nicira device."); } @@ -95,14 +93,14 @@ public class DeleteNiciraNvpDeviceCmd extends BaseAsyncCmd { return CallContext.current().getCallingAccount().getId(); } - @Override - public String getEventType() { - return EventTypes.EVENT_EXTERNAL_NVP_CONTROLLER_DELETE; - } + @Override + public String getEventType() { + return EventTypes.EVENT_EXTERNAL_NVP_CONTROLLER_DELETE; + } - @Override - public String getEventDescription() { - return "Deleting Nicira Nvp Controller"; - } + @Override + public String getEventDescription() { + return "Deleting Nicira Nvp Controller"; + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java index e224cea7598..53203a7cfdf 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java @@ -21,18 +21,18 @@ import java.util.List; import javax.inject.Inject; -import com.cloud.api.response.NiciraNvpDeviceResponse; import org.apache.log4j.Logger; +import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.BaseListCmd; -import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.NetworkResponse; + +import com.cloud.api.response.NiciraNvpDeviceResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -85,7 +85,7 @@ public class ListNiciraNvpDeviceNetworksCmd extends BaseListCmd { response.setResponses(networkResponses); response.setResponseName(getCommandName()); - this.setResponseObject(response); + setResponseObject(response); } catch (InvalidParameterValueException invalidParamExcp) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java index 81cbb23ff54..3e02e192e42 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java @@ -21,17 +21,17 @@ import java.util.List; import javax.inject.Inject; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.BaseListCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; + import com.cloud.api.response.NiciraNvpDeviceResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -48,7 +48,7 @@ public class ListNiciraNvpDevicesCmd extends BaseListCmd { private static final String s_name = "listniciranvpdeviceresponse"; @Inject NiciraNvpElementService _niciraNvpElementService; - ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -92,7 +92,7 @@ public class ListNiciraNvpDevicesCmd extends BaseListCmd { response.setResponses(niciraDevicesResponse); response.setResponseName(getCommandName()); - this.setResponseObject(response); + setResponseObject(response); } catch (InvalidParameterValueException invalidParamExcp) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { @@ -104,5 +104,5 @@ public class ListNiciraNvpDevicesCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java index 097ecd975b2..d6085e211a6 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java @@ -16,13 +16,15 @@ // under the License. package com.cloud.api.response; -import com.cloud.network.NiciraNvpDeviceVO; -import org.apache.cloudstack.api.ApiConstants; -import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; + +import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; import org.apache.cloudstack.api.EntityReference; +import com.cloud.network.NiciraNvpDeviceVO; +import com.cloud.serializer.Param; + @EntityReference(value=NiciraNvpDeviceVO.class) public class NiciraNvpDeviceResponse extends BaseResponse { @SerializedName(ApiConstants.NICIRA_NVP_DEVICE_ID) @Param(description="device id of the Nicire Nvp") @@ -47,7 +49,7 @@ public class NiciraNvpDeviceResponse extends BaseResponse { private String l3GatewayServiceUuid; public void setId(String nvpDeviceId) { - this.id = nvpDeviceId; + id = nvpDeviceId; } public void setPhysicalNetworkId(String physicalNetworkId) { @@ -62,18 +64,16 @@ public class NiciraNvpDeviceResponse extends BaseResponse { this.deviceName = deviceName; } + public void setHostName(String hostName) { + this.hostName = hostName; + } + public void setTransportZoneUuid(String transportZoneUuid) { + this.transportZoneUuid = transportZoneUuid; + } - public void setHostName(String hostName) { - this.hostName = hostName; - } - - public void setTransportZoneUuid(String transportZoneUuid) { - this.transportZoneUuid = transportZoneUuid; - } - - public void setL3GatewayServiceUuid(String l3GatewayServiceUuid) { - this.l3GatewayServiceUuid = l3GatewayServiceUuid; - } + public void setL3GatewayServiceUuid(String l3GatewayServiceUuid) { + this.l3GatewayServiceUuid = l3GatewayServiceUuid; + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java index a1097b9ef1f..3832123015c 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java @@ -16,8 +16,6 @@ // under the License. package com.cloud.network; -import org.apache.cloudstack.api.InternalIdentity; - import java.util.UUID; import javax.persistence.Column; @@ -27,6 +25,8 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; +import org.apache.cloudstack.api.InternalIdentity; + @Entity @Table(name="external_nicira_nvp_devices") public class NiciraNvpDeviceVO implements InternalIdentity { @@ -35,25 +35,25 @@ public class NiciraNvpDeviceVO implements InternalIdentity { @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id") private long id; - + @Column(name="uuid") private String uuid; - + @Column(name="host_id") private long hostId; - + @Column(name="physical_network_id") private long physicalNetworkId; - + @Column(name="provider_name") private String providerName; - + @Column(name="device_name") private String deviceName; - + public NiciraNvpDeviceVO() { - this.uuid = UUID.randomUUID().toString(); + uuid = UUID.randomUUID().toString(); } public NiciraNvpDeviceVO(long hostId, long physicalNetworkId, @@ -63,13 +63,14 @@ public class NiciraNvpDeviceVO implements InternalIdentity { this.physicalNetworkId = physicalNetworkId; this.providerName = providerName; this.deviceName = deviceName; - this.uuid = UUID.randomUUID().toString(); + uuid = UUID.randomUUID().toString(); } + @Override public long getId() { return id; } - + public String getUuid() { return uuid; } @@ -93,5 +94,5 @@ public class NiciraNvpDeviceVO implements InternalIdentity { public String getDeviceName() { return deviceName; } - + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java index 4c948cc965b..d9dbb024653 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java @@ -16,8 +16,6 @@ // under the License. package com.cloud.network; -import org.apache.cloudstack.api.InternalIdentity; - import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,6 +23,8 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; +import org.apache.cloudstack.api.InternalIdentity; + @Entity @Table(name="nicira_nvp_nic_map") public class NiciraNvpNicMappingVO implements InternalIdentity { @@ -36,16 +36,16 @@ public class NiciraNvpNicMappingVO implements InternalIdentity { @Column(name="logicalswitch") private String logicalSwitchUuid; - + @Column(name="logicalswitchport") private String logicalSwitchPortUuid; - + @Column(name="nic") private String nicUuid; - - public NiciraNvpNicMappingVO () { + + public NiciraNvpNicMappingVO () { } - + public NiciraNvpNicMappingVO (String logicalSwitchUuid, String logicalSwitchPortUuid, String nicUuid) { this.logicalSwitchUuid = logicalSwitchUuid; this.logicalSwitchPortUuid = logicalSwitchPortUuid; @@ -76,8 +76,9 @@ public class NiciraNvpNicMappingVO implements InternalIdentity { this.nicUuid = nicUuid; } + @Override public long getId() { return id; } - + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java index ced880fe619..1e2a8311160 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java @@ -5,7 +5,7 @@ // 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, @@ -16,8 +16,6 @@ // under the License. package com.cloud.network; -import org.apache.cloudstack.api.InternalIdentity; - import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,57 +23,59 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; +import org.apache.cloudstack.api.InternalIdentity; + @Entity @Table(name="nicira_nvp_router_map") public class NiciraNvpRouterMappingVO implements InternalIdentity { - //FIXME the ddl for this table should be in one of the upgrade scripts - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="logicalrouter_uuid") - private String logicalRouterUuid; - - @Column(name="network_id") - private long networkId; - - public NiciraNvpRouterMappingVO() { - } + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name="id") + private long id; - public NiciraNvpRouterMappingVO(String logicalRouterUuid, long networkId) { - this.logicalRouterUuid = logicalRouterUuid; - this.networkId = networkId; - } - - public NiciraNvpRouterMappingVO(long id, String logicalRouterUuid, long networkId) { - this.id = id; - this.logicalRouterUuid = logicalRouterUuid; - this.networkId = networkId; - } + @Column(name="logicalrouter_uuid") + private String logicalRouterUuid; - public long getId() { - return id; - } + @Column(name="network_id") + private long networkId; - public void setId(long id) { - this.id = id; - } + public NiciraNvpRouterMappingVO() { + } - public String getLogicalRouterUuid() { - return logicalRouterUuid; - } + public NiciraNvpRouterMappingVO(String logicalRouterUuid, long networkId) { + this.logicalRouterUuid = logicalRouterUuid; + this.networkId = networkId; + } - public void setLogicalRouterUuid(String logicalRouterUuid) { - this.logicalRouterUuid = logicalRouterUuid; - } + public NiciraNvpRouterMappingVO(long id, String logicalRouterUuid, long networkId) { + this.id = id; + this.logicalRouterUuid = logicalRouterUuid; + this.networkId = networkId; + } - public long getNetworkId() { - return networkId; - } + @Override + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getLogicalRouterUuid() { + return logicalRouterUuid; + } + + public void setLogicalRouterUuid(String logicalRouterUuid) { + this.logicalRouterUuid = logicalRouterUuid; + } + + public long getNetworkId() { + return networkId; + } + + public void setNetworkId(long networkId) { + this.networkId = networkId; + } - public void setNetworkId(long networkId) { - this.networkId = networkId; - } - } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpDaoImpl.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpDaoImpl.java index 62662c54036..5e07246f65e 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpDaoImpl.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpDaoImpl.java @@ -31,10 +31,10 @@ import com.cloud.utils.db.SearchCriteria.Op; @Component @Local(value=NiciraNvpDao.class) public class NiciraNvpDaoImpl extends GenericDaoBase - implements NiciraNvpDao { - +implements NiciraNvpDao { + protected final SearchBuilder physicalNetworkIdSearch; - + public NiciraNvpDaoImpl() { physicalNetworkIdSearch = createSearchBuilder(); physicalNetworkIdSearch.and("physicalNetworkId", physicalNetworkIdSearch.entity().getPhysicalNetworkId(), Op.EQ); diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDao.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDao.java index b463fe8a85c..f693dcb7d9c 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDao.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDao.java @@ -21,9 +21,12 @@ import com.cloud.utils.db.GenericDao; public interface NiciraNvpNicMappingDao extends GenericDao { - /** find the mapping for a nic - * @param nicUuid the Uuid of a nic attached to a logical switch port - * @return NiciraNvpNicMapping for this nic uuid or null if it does not exist + /** + * find the mapping for a nic + * @param nicUuid + * the Uuid of a nic attached to a logical switch port + * @return NiciraNvpNicMapping for this nic uuid or null if it does not + * exist */ public NiciraNvpNicMappingVO findByNicUuid(String nicUuid); } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java index b40aad48d36..1a0fcd1ebc1 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java @@ -29,16 +29,16 @@ import com.cloud.utils.db.SearchCriteria.Op; @Component @Local(value=NiciraNvpNicMappingDao.class) public class NiciraNvpNicMappingDaoImpl extends - GenericDaoBase implements NiciraNvpNicMappingDao { +GenericDaoBase implements NiciraNvpNicMappingDao { protected final SearchBuilder nicSearch; - + public NiciraNvpNicMappingDaoImpl() { nicSearch = createSearchBuilder(); nicSearch.and("nicUuid", nicSearch.entity().getNicUuid(), Op.EQ); nicSearch.done(); } - + @Override public NiciraNvpNicMappingVO findByNicUuid(String nicUuid) { SearchCriteria sc = nicSearch.create(); diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDao.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDao.java index c6c58c8846f..e822ebdb1df 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDao.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDao.java @@ -21,5 +21,5 @@ import com.cloud.utils.db.GenericDao; public interface NiciraNvpRouterMappingDao extends GenericDao { - public NiciraNvpRouterMappingVO findByNetworkId(long id); + public NiciraNvpRouterMappingVO findByNetworkId(long id); } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java index d3192ec723f..dc41f570559 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java @@ -30,20 +30,19 @@ import com.cloud.utils.db.SearchCriteria.Op; @Local(value=NiciraNvpRouterMappingDao.class) public class NiciraNvpRouterMappingDaoImpl extends GenericDaoBase implements NiciraNvpRouterMappingDao { - protected final SearchBuilder networkSearch; - - public NiciraNvpRouterMappingDaoImpl() { - networkSearch = createSearchBuilder(); - networkSearch.and("network_id", networkSearch.entity().getNetworkId(), Op.EQ); - networkSearch.done(); - } - - @Override - public NiciraNvpRouterMappingVO findByNetworkId(long id) { - SearchCriteria sc = networkSearch.create(); - sc.setParameters("network_id", id); - return findOneBy(sc); - } - + protected final SearchBuilder networkSearch; + + public NiciraNvpRouterMappingDaoImpl() { + networkSearch = createSearchBuilder(); + networkSearch.and("network_id", networkSearch.entity().getNetworkId(), Op.EQ); + networkSearch.done(); + } + + @Override + public NiciraNvpRouterMappingVO findByNetworkId(long id) { + SearchCriteria sc = networkSearch.create(); + sc.setParameters("network_id", id); + return findOneBy(sc); + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java index ef8ec863c9a..3e9e16a8a6f 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java @@ -30,6 +30,7 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; + import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; @@ -128,9 +129,9 @@ import com.cloud.vm.dao.NicDao; SourceNatServiceProvider.class, StaticNatServiceProvider.class, PortForwardingServiceProvider.class, IpDeployer.class} ) public class NiciraNvpElement extends AdapterBase implements - ConnectivityProvider, SourceNatServiceProvider, - PortForwardingServiceProvider, StaticNatServiceProvider, - NiciraNvpElementService, ResourceStateAdapter, IpDeployer { +ConnectivityProvider, SourceNatServiceProvider, +PortForwardingServiceProvider, StaticNatServiceProvider, +NiciraNvpElementService, ResourceStateAdapter, IpDeployer { private static final Logger s_logger = Logger .getLogger(NiciraNvpElement.class); @@ -217,8 +218,8 @@ public class NiciraNvpElement extends AdapterBase implements @Override public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { + throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { s_logger.debug("entering NiciraNvpElement implement function for network " + network.getDisplayText() + " (state " @@ -247,17 +248,6 @@ public class NiciraNvpElement extends AdapterBase implements Account owner = context.getAccount(); - /** - * Lock the network as we might need to do multiple operations that - * should be done only once. - */ -// Network lock = _networkDao.acquireInLockTable(network.getId(), -// _networkModel.getNetworkLockTimeout()); -// if (lock == null) { -// throw new ConcurrentOperationException("Unable to lock network " -// + network.getId()); -// } - // Implement SourceNat immediately as we have al the info already if (_networkModel.isProviderSupportServiceInNetwork( network.getId(), Service.SourceNat, Provider.NiciraNvp)) { @@ -277,9 +267,9 @@ public class NiciraNvpElement extends AdapterBase implements BroadcastDomainType.getValue(network.getBroadcastUri()), "router-" + network.getDisplayText(), publicCidr, sourceNatIp.getGateway(), internalCidr, context - .getDomain().getName() - + "-" - + context.getAccount().getAccountName()); + .getDomain().getName() + + "-" + + context.getAccount().getAccountName()); CreateLogicalRouterAnswer answer = (CreateLogicalRouterAnswer)_agentMgr .easySend(niciraNvpHost.getId(), cmd); if (answer.getResult() == false) { @@ -343,7 +333,7 @@ public class NiciraNvpElement extends AdapterBase implements BroadcastDomainType.getValue(network.getBroadcastUri()), nicVO.getUuid(), context.getDomain().getName() + "-" + context.getAccount().getAccountName(), - nic.getName()); + nic.getName()); _agentMgr.easySend(niciraNvpHost.getId(), cmd); return true; } else { @@ -489,7 +479,7 @@ public class NiciraNvpElement extends AdapterBase implements @Override public boolean shutdownProviderInstances( PhysicalNetworkServiceProvider provider, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException { + throws ConcurrentOperationException, ResourceUnavailableException { // Nothing to do here. return true; } @@ -618,7 +608,7 @@ public class NiciraNvpElement extends AdapterBase implements physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName); _niciraNvpDao.persist(niciraNvpDevice); - + DetailVO detail = new DetailVO(host.getId(), "niciranvpdeviceid", String.valueOf(niciraNvpDevice .getId())); @@ -818,7 +808,7 @@ public class NiciraNvpElement extends AdapterBase implements @Override public boolean applyIps(Network network, List ipAddress, Set services) - throws ResourceUnavailableException { + throws ResourceUnavailableException { if (services.contains(Service.SourceNat)) { // Only if we need to provide SourceNat we need to configure the logical router // SourceNat is required for StaticNat and PortForwarding @@ -869,7 +859,7 @@ public class NiciraNvpElement extends AdapterBase implements @Override public boolean applyStaticNats(Network network, List rules) - throws ResourceUnavailableException { + throws ResourceUnavailableException { if (!canHandle(network, Service.StaticNat)) { return false; } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java index 51c59bf5c7f..70579153836 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java @@ -62,7 +62,6 @@ import com.cloud.user.Account; import com.cloud.user.dao.AccountDao; import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; @Local(value = NetworkGuru.class) diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/ControlClusterStatus.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/ControlClusterStatus.java index 10890d52e66..2914d35f208 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/ControlClusterStatus.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/ControlClusterStatus.java @@ -17,66 +17,68 @@ package com.cloud.network.nicira; public class ControlClusterStatus { - private String cluster_status; - private Stats node_stats; - private Stats lqueue_stats; - private Stats lport_stats; - private Stats lrouterport_stats; - private Stats lswitch_stats; - private Stats zone_stats; - private Stats lrouter_stats; - private Stats security_profile_stats; - - public String getClusterStatus() { - return cluster_status; - } + private String cluster_status; + private Stats node_stats; + private Stats lqueue_stats; + private Stats lport_stats; + private Stats lrouterport_stats; + private Stats lswitch_stats; + private Stats zone_stats; + private Stats lrouter_stats; + private Stats security_profile_stats; - public Stats getNodeStats() { - return node_stats; - } + public String getClusterStatus() { + return cluster_status; + } - public Stats getLqueueStats() { - return lqueue_stats; - } + public Stats getNodeStats() { + return node_stats; + } - public Stats getLportStats() { - return lport_stats; - } + public Stats getLqueueStats() { + return lqueue_stats; + } - public Stats getLrouterportStats() { - return lrouterport_stats; - } + public Stats getLportStats() { + return lport_stats; + } - public Stats getLswitchStats() { - return lswitch_stats; - } + public Stats getLrouterportStats() { + return lrouterport_stats; + } - public Stats getZoneStats() { - return zone_stats; - } + public Stats getLswitchStats() { + return lswitch_stats; + } - public Stats getLrouterStats() { - return lrouter_stats; - } + public Stats getZoneStats() { + return zone_stats; + } - public Stats getSecurityProfileStats() { - return security_profile_stats; - } + public Stats getLrouterStats() { + return lrouter_stats; + } - public class Stats { - private int error_state_count; - private int registered_count; - private int active_count; - - public int getErrorStateCount() { - return error_state_count; - } - public int getRegisteredCount() { - return registered_count; - } - public int getActiveCount() { - return active_count; - } - - } + public Stats getSecurityProfileStats() { + return security_profile_stats; + } + + public class Stats { + private int error_state_count; + private int registered_count; + private int active_count; + + public int getErrorStateCount() { + return error_state_count; + } + + public int getRegisteredCount() { + return registered_count; + } + + public int getActiveCount() { + return active_count; + } + + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java index 20afea9710b..d149c4b087e 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java @@ -19,7 +19,7 @@ package com.cloud.network.nicira; public class DestinationNatRule extends NatRule { private String toDestinationIpAddress; private Integer toDestinationPort; - + public DestinationNatRule() { setType("DestinationNatRule"); } @@ -28,17 +28,14 @@ public class DestinationNatRule extends NatRule { return toDestinationIpAddress; } - public void setToDestinationIpAddress(String toDestinationIpAddress) { this.toDestinationIpAddress = toDestinationIpAddress; } - public Integer getToDestinationPort() { return toDestinationPort; } - public void setToDestinationPort(Integer toDestinationPort) { this.toDestinationPort = toDestinationPort; } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java index 8b807fd9e72..96d199132e1 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java @@ -5,7 +5,7 @@ // 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, @@ -17,36 +17,36 @@ package com.cloud.network.nicira; /** - * + * */ public class L3GatewayAttachment extends Attachment { - private String l3_gateway_service_uuid; - private String type = "L3GatewayAttachment"; - private Long vlan_id; - - public L3GatewayAttachment(String l3_gateway_service_uuid) { - this.l3_gateway_service_uuid = l3_gateway_service_uuid; - } - - public L3GatewayAttachment(String l3_gateway_service_uuid, long vlan_id) { - this.l3_gateway_service_uuid = l3_gateway_service_uuid; - this.vlan_id = vlan_id; - } - - public String getL3GatewayServiceUuid() { - return l3_gateway_service_uuid; - } - - public void setL3GatewayServiceUuid(String l3_gateway_service_uuid) { - this.l3_gateway_service_uuid = l3_gateway_service_uuid; - } - - public long getVlanId() { - return vlan_id; - } - - public void setVlanId(long vlan_id) { - this.vlan_id = vlan_id; - } + private String l3_gateway_service_uuid; + private String type = "L3GatewayAttachment"; + private Long vlan_id; + + public L3GatewayAttachment(String l3_gateway_service_uuid) { + this.l3_gateway_service_uuid = l3_gateway_service_uuid; + } + + public L3GatewayAttachment(String l3_gateway_service_uuid, long vlan_id) { + this.l3_gateway_service_uuid = l3_gateway_service_uuid; + this.vlan_id = vlan_id; + } + + public String getL3GatewayServiceUuid() { + return l3_gateway_service_uuid; + } + + public void setL3GatewayServiceUuid(String l3_gateway_service_uuid) { + this.l3_gateway_service_uuid = l3_gateway_service_uuid; + } + + public long getVlanId() { + return vlan_id; + } + + public void setVlanId(long vlan_id) { + this.vlan_id = vlan_id; + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterConfig.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterConfig.java index 897ee06b844..088cefc79c2 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterConfig.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterConfig.java @@ -5,7 +5,7 @@ // 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, @@ -19,39 +19,39 @@ package com.cloud.network.nicira; import java.util.List; /** - * + * */ public class LogicalRouterConfig { - private String display_name; - private RoutingConfig routing_config; - private String type = "LogicalRouterConfig"; - private String uuid; + private String display_name; + private RoutingConfig routing_config; + private String type = "LogicalRouterConfig"; + private String uuid; private List tags; - - public RoutingConfig getRoutingConfig() { - return routing_config; - } - - public void setRoutingConfig(RoutingConfig routing_config) { - this.routing_config = routing_config; - } - - public String getDisplayName() { - return display_name; - } - - public void setDisplayName(String display_name) { - this.display_name = display_name; - } - + + public RoutingConfig getRoutingConfig() { + return routing_config; + } + + public void setRoutingConfig(RoutingConfig routing_config) { + this.routing_config = routing_config; + } + + public String getDisplayName() { + return display_name; + } + + public void setDisplayName(String display_name) { + this.display_name = display_name; + } + public String getUuid() { return uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } - + public List getTags() { return tags; } @@ -59,6 +59,5 @@ public class LogicalRouterConfig { public void setTags(List tags) { this.tags = tags; } - - + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java index 196106dbe40..112825d60a4 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java @@ -5,7 +5,7 @@ // 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, @@ -19,72 +19,72 @@ package com.cloud.network.nicira; import java.util.List; /** - * + * */ public class LogicalRouterPort { - private String display_name; - private List tags; - private Integer portno; - private boolean admin_status_enabled; - private List ip_addresses; - private String mac_address; - private String type = "LogicalRouterPortConfig"; - private String uuid; - - public int getPortno() { - return portno; - } - - public void setPortno(int portno) { - this.portno = portno; - } - - public boolean isAdminStatusEnabled() { - return admin_status_enabled; - } - - public void setAdminStatusEnabled(boolean admin_status_enabled) { - this.admin_status_enabled = admin_status_enabled; - } - - public List getIpAddresses() { - return ip_addresses; - } - - public void setIpAddresses(List ip_addresses) { - this.ip_addresses = ip_addresses; - } - - public String getMacAddress() { - return mac_address; - } - - public void setMacAddress(String mac_address) { - this.mac_address = mac_address; - } - - public String getDisplayName() { - return display_name; - } + private String display_name; + private List tags; + private Integer portno; + private boolean admin_status_enabled; + private List ip_addresses; + private String mac_address; + private String type = "LogicalRouterPortConfig"; + private String uuid; - public void setDisplayName(String display_name) { - this.display_name = display_name; - } + public int getPortno() { + return portno; + } - public List getTags() { - return tags; - } + public void setPortno(int portno) { + this.portno = portno; + } - public void setTags(List tags) { - this.tags = tags; - } + public boolean isAdminStatusEnabled() { + return admin_status_enabled; + } - public String getUuid() { - return uuid; - } + public void setAdminStatusEnabled(boolean admin_status_enabled) { + this.admin_status_enabled = admin_status_enabled; + } - public void setUuid(String uuid) { - this.uuid = uuid; - } + public List getIpAddresses() { + return ip_addresses; + } + + public void setIpAddresses(List ip_addresses) { + this.ip_addresses = ip_addresses; + } + + public String getMacAddress() { + return mac_address; + } + + public void setMacAddress(String mac_address) { + this.mac_address = mac_address; + } + + public String getDisplayName() { + return display_name; + } + + public void setDisplayName(String display_name) { + this.display_name = display_name; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } } \ No newline at end of file diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java index f56518924b8..f022ff754c0 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java @@ -29,51 +29,51 @@ public class LogicalSwitch { //private RequestQueryParameters _query; //private LogicalSwitchRelations _relations; private String _schema; - + public String getDisplay_name() { return display_name; } - + public void setDisplay_name(String display_name) { this.display_name = display_name; } - + public boolean isPort_isolation_enabled() { return port_isolation_enabled; } - + public void setPort_isolation_enabled(boolean port_isolation_enabled) { this.port_isolation_enabled = port_isolation_enabled; } - + public String getType() { return type; } - + public void setType(String type) { this.type = type; } - + public String getUuid() { return uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } - + public String get_href() { return _href; } - + public void set_href(String _href) { this._href = _href; } - + public String get_schema() { return _schema; } - + public void set_schema(String _schema) { this._schema = _schema; } @@ -93,6 +93,6 @@ public class LogicalSwitch { public void setTransport_zones(List transport_zones) { this.transport_zones = transport_zones; } - - + + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java index c5714585c99..aaf549493b3 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java @@ -29,7 +29,7 @@ public class LogicalSwitchPort { private List mirror_targets; private String type; private String uuid; - + public LogicalSwitchPort() { super(); } @@ -113,5 +113,5 @@ public class LogicalSwitchPort { public void setUuid(String uuid) { this.uuid = uuid; } - + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java index f7777822a06..e437344cc39 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java @@ -5,7 +5,7 @@ // 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, @@ -17,131 +17,117 @@ package com.cloud.network.nicira; /** - * + * */ public class Match { - private Integer protocol; - private String source_ip_addresses; - private String destination_ip_addresses; - private Integer source_port; - private Integer destination_port; - private String ethertype = "IPv4"; - - public Integer getProtocol() { - return protocol; - } - - public void setProtocol(Integer protocol) { - this.protocol = protocol; - } - - public Integer getSourcePort() { - return source_port; - } - - public void setSourcePort(Integer source_port) { - this.source_port = source_port; - } - - public Integer getDestinationPort() { - return destination_port; - } - - public void setDestinationPort(Integer destination_port) { - this.destination_port = destination_port; - } - - public String getEthertype() { - return ethertype; - } - - public void setEthertype(String ethertype) { - this.ethertype = ethertype; - } + private Integer protocol; + private String source_ip_addresses; + private String destination_ip_addresses; + private Integer source_port; + private Integer destination_port; + private String ethertype = "IPv4"; - public String getSourceIpAddresses() { - return source_ip_addresses; - } + public Integer getProtocol() { + return protocol; + } - public void setSourceIpAddresses(String source_ip_addresses) { - this.source_ip_addresses = source_ip_addresses; - } + public void setProtocol(Integer protocol) { + this.protocol = protocol; + } - public String getDestinationIpAddresses() { - return destination_ip_addresses; - } + public Integer getSourcePort() { + return source_port; + } - public void setDestinationIpAddresses(String destination_ip_addresses) { - this.destination_ip_addresses = destination_ip_addresses; - } + public void setSourcePort(Integer source_port) { + this.source_port = source_port; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime - * result - + ((destination_ip_addresses == null) ? 0 - : destination_ip_addresses.hashCode()); - result = prime - * result - + ((destination_port == null) ? 0 : destination_port - .hashCode()); - result = prime * result - + ((ethertype == null) ? 0 : ethertype.hashCode()); - result = prime * result - + ((protocol == null) ? 0 : protocol.hashCode()); - result = prime - * result - + ((source_ip_addresses == null) ? 0 : source_ip_addresses - .hashCode()); - result = prime * result - + ((source_port == null) ? 0 : source_port.hashCode()); - return result; - } + public Integer getDestinationPort() { + return destination_port; + } + + public void setDestinationPort(Integer destination_port) { + this.destination_port = destination_port; + } + + public String getEthertype() { + return ethertype; + } + + public void setEthertype(String ethertype) { + this.ethertype = ethertype; + } + + public String getSourceIpAddresses() { + return source_ip_addresses; + } + + public void setSourceIpAddresses(String source_ip_addresses) { + this.source_ip_addresses = source_ip_addresses; + } + + public String getDestinationIpAddresses() { + return destination_ip_addresses; + } + + public void setDestinationIpAddresses(String destination_ip_addresses) { + this.destination_ip_addresses = destination_ip_addresses; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((destination_ip_addresses == null) ? 0 : destination_ip_addresses.hashCode()); + result = prime * result + ((destination_port == null) ? 0 : destination_port.hashCode()); + result = prime * result + ((ethertype == null) ? 0 : ethertype.hashCode()); + result = prime * result + ((protocol == null) ? 0 : protocol.hashCode()); + result = prime * result + ((source_ip_addresses == null) ? 0 : source_ip_addresses.hashCode()); + result = prime * result + ((source_port == null) ? 0 : source_port.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Match other = (Match) obj; + if (destination_ip_addresses == null) { + if (other.destination_ip_addresses != null) + return false; + } else if (!destination_ip_addresses.equals(other.destination_ip_addresses)) + return false; + if (destination_port == null) { + if (other.destination_port != null) + return false; + } else if (!destination_port.equals(other.destination_port)) + return false; + if (ethertype == null) { + if (other.ethertype != null) + return false; + } else if (!ethertype.equals(other.ethertype)) + return false; + if (protocol == null) { + if (other.protocol != null) + return false; + } else if (!protocol.equals(other.protocol)) + return false; + if (source_ip_addresses == null) { + if (other.source_ip_addresses != null) + return false; + } else if (!source_ip_addresses.equals(other.source_ip_addresses)) + return false; + if (source_port == null) { + if (other.source_port != null) + return false; + } else if (!source_port.equals(other.source_port)) + return false; + return true; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Match other = (Match) obj; - if (destination_ip_addresses == null) { - if (other.destination_ip_addresses != null) - return false; - } else if (!destination_ip_addresses - .equals(other.destination_ip_addresses)) - return false; - if (destination_port == null) { - if (other.destination_port != null) - return false; - } else if (!destination_port.equals(other.destination_port)) - return false; - if (ethertype == null) { - if (other.ethertype != null) - return false; - } else if (!ethertype.equals(other.ethertype)) - return false; - if (protocol == null) { - if (other.protocol != null) - return false; - } else if (!protocol.equals(other.protocol)) - return false; - if (source_ip_addresses == null) { - if (other.source_ip_addresses != null) - return false; - } else if (!source_ip_addresses.equals(other.source_ip_addresses)) - return false; - if (source_port == null) { - if (other.source_port != null) - return false; - } else if (!source_port.equals(other.source_port)) - return false; - return true; - } - - } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java index 93de51e45ac..f33f2492599 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java @@ -5,7 +5,7 @@ // 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, @@ -19,7 +19,7 @@ package com.cloud.network.nicira; import java.util.UUID; /** - * + * */ public abstract class NatRule { protected Match match; @@ -53,15 +53,15 @@ public abstract class NatRule { public void setType(String type) { this.type = type; } - + public int getOrder() { return order; } - + public void setOrder(int order) { this.order = order; } - + @Override public int hashCode() { final int prime = 31; @@ -101,7 +101,7 @@ public abstract class NatRule { return false; return true; } - + public boolean equalsIgnoreUuid(Object obj) { if (this == obj) return true; @@ -124,6 +124,6 @@ public abstract class NatRule { return false; return true; } - + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java index 12fa6c0b67c..ea69a095642 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java @@ -75,103 +75,103 @@ public class NiciraNvpApi { private static final Logger s_logger = Logger.getLogger(NiciraNvpApi.class); private final static String _protocol = "https"; private static final MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager(); - + private String _name; private String _host; private String _adminuser; private String _adminpass; - + private HttpClient _client; private String _nvpversion; - + private Gson _gson; - + /* This factory method is protected so we can extend this * in the unittests. */ protected HttpClient createHttpClient() { - return new HttpClient(s_httpClientManager); + return new HttpClient(s_httpClientManager); } - + protected HttpMethod createMethod(String type, String uri) throws NiciraNvpApiException { - String url; + String url; try { url = new URL(_protocol, _host, uri).toString(); } catch (MalformedURLException e) { s_logger.error("Unable to build Nicira API URL", e); throw new NiciraNvpApiException("Unable to build Nicira API URL", e); } - + if ("post".equalsIgnoreCase(type)) { - return new PostMethod(url); + return new PostMethod(url); } else if ("get".equalsIgnoreCase(type)) { - return new GetMethod(url); + return new GetMethod(url); } else if ("delete".equalsIgnoreCase(type)) { - return new DeleteMethod(url); + return new DeleteMethod(url); } else if ("put".equalsIgnoreCase(type)) { - return new PutMethod(url); + return new PutMethod(url); } else { - throw new NiciraNvpApiException("Requesting unknown method type"); + throw new NiciraNvpApiException("Requesting unknown method type"); } } public NiciraNvpApi() { _client = createHttpClient(); _client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); - - try { + + try { // Cast to ProtocolSocketFactory to avoid the deprecated constructor with the SecureProtocolSocketFactory parameter Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) new TrustingProtocolSocketFactory(), 443)); } catch (IOException e) { s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e); } - + _gson = new GsonBuilder() - .registerTypeAdapter(NatRule.class, new NatRuleAdapter()) - .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) - .create(); - + .registerTypeAdapter(NatRule.class, new NatRuleAdapter()) + .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) + .create(); + } - + public void setControllerAddress(String address) { - this._host = address; + _host = address; } - + public void setAdminCredentials(String username, String password) { - this._adminuser = username; - this._adminpass = password; + _adminuser = username; + _adminpass = password; } - + /** - * Logs into the Nicira API. The cookie is stored in the _authcookie variable. + * Logs into the Nicira API. The cookie is stored in the + * _authcookie variable. *

* The method returns false if the login failed or the connection could not be made. - * */ protected void login() throws NiciraNvpApiException { String url; - + if (_host == null || _host.isEmpty() || - _adminuser == null || _adminuser.isEmpty() || - _adminpass == null || _adminpass.isEmpty()) { - throw new NiciraNvpApiException("Hostname/credentials are null or empty"); + _adminuser == null || _adminuser.isEmpty() || + _adminpass == null || _adminpass.isEmpty()) { + throw new NiciraNvpApiException("Hostname/credentials are null or empty"); } - + try { url = new URL(_protocol, _host, "/ws.v1/login").toString(); } catch (MalformedURLException e) { s_logger.error("Unable to build Nicira API URL", e); throw new NiciraNvpApiException("Unable to build Nicira API URL", e); } - + PostMethod pm = new PostMethod(url); pm.addParameter("username", _adminuser); pm.addParameter("password", _adminpass); - + try { _client.executeMethod(pm); } catch (HttpException e) { @@ -181,25 +181,25 @@ public class NiciraNvpApi { } finally { pm.releaseConnection(); } - + if (pm.getStatusCode() != HttpStatus.SC_OK) { s_logger.error("Nicira NVP API login failed : " + pm.getStatusText()); throw new NiciraNvpApiException("Nicira NVP API login failed " + pm.getStatusText()); } - + // Extract the version for later use if (pm.getResponseHeader("Server") != null) { _nvpversion = pm.getResponseHeader("Server").getValue(); s_logger.debug("NVP Controller reports version " + _nvpversion); } - + // Success; the cookie required for login is kept in _client } - + public LogicalSwitch createLogicalSwitch(LogicalSwitch logicalSwitch) throws NiciraNvpApiException { String uri = "/ws.v1/lswitch"; LogicalSwitch createdLogicalSwitch = executeCreateObject(logicalSwitch, new TypeToken(){}.getType(), uri, Collections.emptyMap()); - + return createdLogicalSwitch; } @@ -207,11 +207,11 @@ public class NiciraNvpApi { String uri = "/ws.v1/lswitch/" + uuid; executeDeleteObject(uri); } - + public LogicalSwitchPort createLogicalSwitchPort(String logicalSwitchUuid, LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException { String uri = "/ws.v1/lswitch/" + logicalSwitchUuid + "/lport"; LogicalSwitchPort createdLogicalSwitchPort = executeCreateObject(logicalSwitchPort, new TypeToken(){}.getType(), uri, Collections.emptyMap());; - + return createdLogicalSwitchPort; } @@ -219,28 +219,28 @@ public class NiciraNvpApi { String uri = "/ws.v1/lswitch/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid + "/attachment"; executeUpdateObject(attachment, uri, Collections.emptyMap()); } - + public void deleteLogicalSwitchPort(String logicalSwitchUuid, String logicalSwitchPortUuid) throws NiciraNvpApiException { String uri = "/ws.v1/lswitch/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid; executeDeleteObject(uri); } - + public String findLogicalSwitchPortUuidByVifAttachmentUuid(String logicalSwitchUuid, String vifAttachmentUuid) throws NiciraNvpApiException { String uri = "/ws.v1/lswitch/" + logicalSwitchUuid + "/lport"; Map params = new HashMap(); params.put("attachment_vif_uuid", vifAttachmentUuid); params.put("fields", "uuid"); - + NiciraNvpList lspl = executeRetrieveObject(new TypeToken>(){}.getType(), uri, params); - + if (lspl == null || lspl.getResultCount() != 1) { throw new NiciraNvpApiException("Unexpected response from API"); } - + LogicalSwitchPort lsp = lspl.getResults().get(0); return lsp.getUuid(); } - + public ControlClusterStatus getControlClusterStatus() throws NiciraNvpApiException { String uri = "/ws.v1/control-cluster/status"; ControlClusterStatus ccs = executeRetrieveObject(new TypeToken(){}.getType(), uri, null); @@ -253,118 +253,118 @@ public class NiciraNvpApi { Map params = new HashMap(); params.put("uuid", logicalSwitchPortUuid); params.put("fields", "uuid"); - + NiciraNvpList lspl = executeRetrieveObject(new TypeToken>(){}.getType(), uri, params); - + if (lspl == null ) { throw new NiciraNvpApiException("Unexpected response from API"); } - + return lspl; } - + public LogicalRouterConfig createLogicalRouter(LogicalRouterConfig logicalRouterConfig) throws NiciraNvpApiException { - String uri = "/ws.v1/lrouter"; - - LogicalRouterConfig lrc = executeCreateObject(logicalRouterConfig, new TypeToken(){}.getType(), uri, Collections.emptyMap()); - - return lrc; + String uri = "/ws.v1/lrouter"; + + LogicalRouterConfig lrc = executeCreateObject(logicalRouterConfig, new TypeToken(){}.getType(), uri, Collections.emptyMap()); + + return lrc; } public void deleteLogicalRouter(String logicalRouterUuid) throws NiciraNvpApiException { - String uri = "/ws.v1/lrouter/" + logicalRouterUuid; - - executeDeleteObject(uri); + String uri = "/ws.v1/lrouter/" + logicalRouterUuid; + + executeDeleteObject(uri); } - + public LogicalRouterPort createLogicalRouterPort(String logicalRouterUuid, LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { - String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport"; - - LogicalRouterPort lrp = executeCreateObject(logicalRouterPort, new TypeToken(){}.getType(), uri, Collections.emptyMap()); - return lrp; + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport"; + + LogicalRouterPort lrp = executeCreateObject(logicalRouterPort, new TypeToken(){}.getType(), uri, Collections.emptyMap()); + return lrp; } - + public void deleteLogicalRouterPort(String logicalRouterUuid, String logicalRouterPortUuid) throws NiciraNvpApiException { - String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid; - - executeDeleteObject(uri); + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid; + + executeDeleteObject(uri); } public void modifyLogicalRouterPort(String logicalRouterUuid, LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { - String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport/" + logicalRouterPort.getUuid(); - - executeUpdateObject(logicalRouterPort, uri, Collections.emptyMap()); + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport/" + logicalRouterPort.getUuid(); + + executeUpdateObject(logicalRouterPort, uri, Collections.emptyMap()); } - + public void modifyLogicalRouterPortAttachment(String logicalRouterUuid, String logicalRouterPortUuid, Attachment attachment) throws NiciraNvpApiException { String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid + "/attachment"; executeUpdateObject(attachment, uri, Collections.emptyMap()); } - + public NatRule createLogicalRouterNatRule(String logicalRouterUuid, NatRule natRule) throws NiciraNvpApiException { - String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/nat"; - - return executeCreateObject(natRule, new TypeToken(){}.getType(), uri, Collections.emptyMap()); + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/nat"; + + return executeCreateObject(natRule, new TypeToken(){}.getType(), uri, Collections.emptyMap()); } - + public void modifyLogicalRouterNatRule(String logicalRouterUuid, NatRule natRule) throws NiciraNvpApiException { - String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/nat/" + natRule.getUuid(); - - executeUpdateObject(natRule, uri, Collections.emptyMap()); + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/nat/" + natRule.getUuid(); + + executeUpdateObject(natRule, uri, Collections.emptyMap()); } - + public void deleteLogicalRouterNatRule(String logicalRouterUuid, UUID natRuleUuid) throws NiciraNvpApiException { - String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/nat/" + natRuleUuid.toString(); - - executeDeleteObject(uri); + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/nat/" + natRuleUuid.toString(); + + executeDeleteObject(uri); } - + public NiciraNvpList findLogicalRouterPortByGatewayServiceAndVlanId(String logicalRouterUuid, String gatewayServiceUuid, long vlanId) throws NiciraNvpApiException { - String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport"; + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport"; Map params = new HashMap(); params.put("attachment_gwsvc_uuid", gatewayServiceUuid); params.put("attachment_vlan", "0"); params.put("fields","*"); - + return executeRetrieveObject(new TypeToken>(){}.getType(), uri, params); } - + public LogicalRouterConfig findOneLogicalRouterByUuid(String logicalRouterUuid) throws NiciraNvpApiException { - String uri = "/ws.v1/lrouter/" + logicalRouterUuid; - - return executeRetrieveObject(new TypeToken(){}.getType(), uri, Collections.emptyMap()); + String uri = "/ws.v1/lrouter/" + logicalRouterUuid; + + return executeRetrieveObject(new TypeToken(){}.getType(), uri, Collections.emptyMap()); } - + public void updateLogicalRouterPortConfig(String logicalRouterUuid, LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { - String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport" + logicalRouterPort.getUuid(); - - executeUpdateObject(logicalRouterPort, uri, Collections.emptyMap()); + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport" + logicalRouterPort.getUuid(); + + executeUpdateObject(logicalRouterPort, uri, Collections.emptyMap()); } - + public NiciraNvpList findNatRulesByLogicalRouterUuid(String logicalRouterUuid) throws NiciraNvpApiException { - String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/nat"; + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/nat"; Map params = new HashMap(); params.put("fields","*"); - - return executeRetrieveObject(new TypeToken>(){}.getType(), uri, params); + + return executeRetrieveObject(new TypeToken>(){}.getType(), uri, params); } - + public NiciraNvpList findLogicalRouterPortByGatewayServiceUuid(String logicalRouterUuid, String l3GatewayServiceUuid) throws NiciraNvpApiException { - String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport"; - Map params = new HashMap(); - params.put("fields", "*"); - params.put("attachment_gwsvc_uuid", l3GatewayServiceUuid); - - return executeRetrieveObject(new TypeToken>(){}.getType(), uri, params); + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport"; + Map params = new HashMap(); + params.put("fields", "*"); + params.put("attachment_gwsvc_uuid", l3GatewayServiceUuid); + + return executeRetrieveObject(new TypeToken>(){}.getType(), uri, params); } - + protected void executeUpdateObject(T newObject, String uri, Map parameters) throws NiciraNvpApiException { if (_host == null || _host.isEmpty() || - _adminuser == null || _adminuser.isEmpty() || - _adminpass == null || _adminpass.isEmpty()) { - throw new NiciraNvpApiException("Hostname/credentials are null or empty"); + _adminuser == null || _adminuser.isEmpty() || + _adminpass == null || _adminpass.isEmpty()) { + throw new NiciraNvpApiException("Hostname/credentials are null or empty"); } - + PutMethod pm = (PutMethod) createMethod("put", uri); pm.setRequestHeader("Content-Type", "application/json"); try { @@ -373,9 +373,9 @@ public class NiciraNvpApi { } catch (UnsupportedEncodingException e) { throw new NiciraNvpApiException("Failed to encode json request body", e); } - + executeMethod(pm); - + if (pm.getStatusCode() != HttpStatus.SC_OK) { String errorMessage = responseToErrorMessage(pm); pm.releaseConnection(); @@ -384,14 +384,14 @@ public class NiciraNvpApi { } pm.releaseConnection(); } - + protected T executeCreateObject(T newObject, Type returnObjectType, String uri, Map parameters) throws NiciraNvpApiException { if (_host == null || _host.isEmpty() || - _adminuser == null || _adminuser.isEmpty() || - _adminpass == null || _adminpass.isEmpty()) { - throw new NiciraNvpApiException("Hostname/credentials are null or empty"); + _adminuser == null || _adminuser.isEmpty() || + _adminpass == null || _adminpass.isEmpty()) { + throw new NiciraNvpApiException("Hostname/credentials are null or empty"); } - + PostMethod pm = (PostMethod) createMethod("post", uri); pm.setRequestHeader("Content-Type", "application/json"); try { @@ -400,16 +400,16 @@ public class NiciraNvpApi { } catch (UnsupportedEncodingException e) { throw new NiciraNvpApiException("Failed to encode json request body", e); } - + executeMethod(pm); - + if (pm.getStatusCode() != HttpStatus.SC_CREATED) { String errorMessage = responseToErrorMessage(pm); pm.releaseConnection(); s_logger.error("Failed to create object : " + errorMessage); throw new NiciraNvpApiException("Failed to create object : " + errorMessage); } - + T result; try { result = (T)_gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType()); @@ -418,22 +418,22 @@ public class NiciraNvpApi { } finally { pm.releaseConnection(); } - - return result; + + return result; } - + protected void executeDeleteObject(String uri) throws NiciraNvpApiException { if (_host == null || _host.isEmpty() || - _adminuser == null || _adminuser.isEmpty() || - _adminpass == null || _adminpass.isEmpty()) { - throw new NiciraNvpApiException("Hostname/credentials are null or empty"); + _adminuser == null || _adminuser.isEmpty() || + _adminpass == null || _adminpass.isEmpty()) { + throw new NiciraNvpApiException("Hostname/credentials are null or empty"); } - + DeleteMethod dm = (DeleteMethod) createMethod("delete", uri); dm.setRequestHeader("Content-Type", "application/json"); - + executeMethod(dm); - + if (dm.getStatusCode() != HttpStatus.SC_NO_CONTENT) { String errorMessage = responseToErrorMessage(dm); dm.releaseConnection(); @@ -442,33 +442,33 @@ public class NiciraNvpApi { } dm.releaseConnection(); } - + protected T executeRetrieveObject(Type returnObjectType, String uri, Map parameters) throws NiciraNvpApiException { if (_host == null || _host.isEmpty() || - _adminuser == null || _adminuser.isEmpty() || - _adminpass == null || _adminpass.isEmpty()) { - throw new NiciraNvpApiException("Hostname/credentials are null or empty"); + _adminuser == null || _adminuser.isEmpty() || + _adminpass == null || _adminpass.isEmpty()) { + throw new NiciraNvpApiException("Hostname/credentials are null or empty"); } - + GetMethod gm = (GetMethod) createMethod("get", uri); gm.setRequestHeader("Content-Type", "application/json"); if (parameters != null && !parameters.isEmpty()) { - List nameValuePairs = new ArrayList(parameters.size()); - for (Entry e : parameters.entrySet()) { - nameValuePairs.add(new NameValuePair(e.getKey(), e.getValue())); - } - gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0])); + List nameValuePairs = new ArrayList(parameters.size()); + for (Entry e : parameters.entrySet()) { + nameValuePairs.add(new NameValuePair(e.getKey(), e.getValue())); + } + gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0])); } - + executeMethod(gm); - + if (gm.getStatusCode() != HttpStatus.SC_OK) { String errorMessage = responseToErrorMessage(gm); gm.releaseConnection(); s_logger.error("Failed to retrieve object : " + errorMessage); throw new NiciraNvpApiException("Failed to retrieve object : " + errorMessage); } - + T returnValue; try { returnValue = (T)_gson.fromJson(gm.getResponseBodyAsString(), returnObjectType); @@ -480,7 +480,7 @@ public class NiciraNvpApi { } return returnValue; } - + protected void executeMethod(HttpMethodBase method) throws NiciraNvpApiException { try { _client.executeMethod(method); @@ -497,13 +497,13 @@ public class NiciraNvpApi { } catch (IOException e) { s_logger.error("IOException caught while trying to connect to the Nicira NVP Controller", e); method.releaseConnection(); - throw new NiciraNvpApiException("API call to Nicira NVP Controller Failed", e); + throw new NiciraNvpApiException("API call to Nicira NVP Controller Failed", e); } } - + private String responseToErrorMessage(HttpMethodBase method) { assert method.isRequestSent() : "no use getting an error message unless the request is sent"; - + if ("text/html".equals(method.getResponseHeader("Content-Type").getValue())) { // The error message is the response content // Safety margin of 1024 characters, anything longer is probably useless @@ -514,38 +514,41 @@ public class NiciraNvpApi { s_logger.debug("Error while loading response body", e); } } - + // The default return method.getStatusText(); } - - /* The Nicira controller uses a self-signed certificate. The + + /* The Nicira controller uses a self-signed certificate. The * TrustingProtocolSocketFactory will accept any provided - * certificate when making an SSL connection to the SDN + * certificate when making an SSL connection to the SDN * Manager */ private class TrustingProtocolSocketFactory implements SecureProtocolSocketFactory { private SSLSocketFactory ssf; - + public TrustingProtocolSocketFactory() throws IOException { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { - new X509TrustManager() { - public X509Certificate[] getAcceptedIssuers() { - return null; + new X509TrustManager() { + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + @Override + public void checkClientTrusted(X509Certificate[] certs, String authType) { + // Trust always + } + + @Override + public void checkServerTrusted(X509Certificate[] certs, String authType) { + // Trust always + } } - - public void checkClientTrusted(X509Certificate[] certs, String authType) { - // Trust always - } - - public void checkServerTrusted(X509Certificate[] certs, String authType) { - // Trust always - } - } }; - + try { // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); @@ -557,10 +560,10 @@ public class NiciraNvpApi { throw new IOException(e); } } - + @Override public Socket createSocket(String host, int port) throws IOException, - UnknownHostException { + UnknownHostException { return ssf.createSocket(host, port); } @@ -592,21 +595,19 @@ public class NiciraNvpApi { } } - + } - + public static class NatRuleAdapter implements JsonDeserializer { @Override public NatRule deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); - NatRule natRule = null; - if (!jsonObject.has("type")) { throw new JsonParseException("Deserializing as a NatRule, but no type present in the json object"); } - + String natRuleType = jsonObject.get("type").getAsString(); if ("SourceNatRule".equals(natRuleType)) { return context.deserialize(jsonElement, SourceNatRule.class); @@ -614,7 +615,7 @@ public class NiciraNvpApi { else if ("DestinationNatRule".equals(natRuleType)) { return context.deserialize(jsonElement, DestinationNatRule.class); } - + throw new JsonParseException("Failed to deserialize type \"" + natRuleType + "\""); } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java index c97e40ecd81..9d78e84e0eb 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java @@ -37,9 +37,9 @@ public class NiciraNvpList { public void setResultCount(int result_count) { this.result_count = result_count; } - + public boolean isEmpty() { - return result_count == 0; + return result_count == 0; } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java index 157c3b522c7..a5dd3bd1206 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java @@ -22,9 +22,9 @@ public class NiciraNvpTag { private static final Logger s_logger = Logger.getLogger(NiciraNvpTag.class); private String scope; private String tag; - + public NiciraNvpTag() {} - + public NiciraNvpTag(String scope, String tag) { this.scope = scope; if (tag.length() > 40) { @@ -34,19 +34,19 @@ public class NiciraNvpTag { this.tag = tag; } } - + public String getScope() { return scope; } - + public void setScope(String scope) { this.scope = scope; } - + public String getTag() { return tag; } - + public void setTag(String tag) { if (tag.length() > 40) { s_logger.warn("tag \"" + tag + "\" too long, truncating to 40 characters"); @@ -55,5 +55,5 @@ public class NiciraNvpTag { this.tag = tag; } } - + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java index e57c2493f1c..137f0710f18 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java @@ -5,7 +5,7 @@ // 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, @@ -17,23 +17,22 @@ package com.cloud.network.nicira; /** - * + * */ public class PatchAttachment extends Attachment { - private final String type = "PatchAttachment"; - private String peer_port_uuid; - - public PatchAttachment(String peerPortUuid) { - this.peer_port_uuid = peerPortUuid; - } + private final String type = "PatchAttachment"; + private String peer_port_uuid; - public String getPeerPortUuid() { - return peer_port_uuid; - } + public PatchAttachment(String peerPortUuid) { + peer_port_uuid = peerPortUuid; + } + + public String getPeerPortUuid() { + return peer_port_uuid; + } + + public void setPeerPortUuid(String peerPortUuid) { + peer_port_uuid = peerPortUuid; + } - public void setPeerPortUuid(String peerPortUuid) { - this.peer_port_uuid = peerPortUuid; - } - - } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java index c018af37467..a204e557adb 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java @@ -5,7 +5,7 @@ // 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, @@ -17,22 +17,22 @@ package com.cloud.network.nicira; /** - * + * */ public class RouterNextHop { - private String gateway_ip_address; - private String type = "RouterNextHop"; - - public RouterNextHop(String gatewayIpAddress) { - this.gateway_ip_address = gatewayIpAddress; - } - - public String getGatewayIpAddress() { - return gateway_ip_address; - } - - public void setGatewayIpAddress(String gateway_ip_address) { - this.gateway_ip_address = gateway_ip_address; - } - + private String gateway_ip_address; + private String type = "RouterNextHop"; + + public RouterNextHop(String gatewayIpAddress) { + gateway_ip_address = gatewayIpAddress; + } + + public String getGatewayIpAddress() { + return gateway_ip_address; + } + + public void setGatewayIpAddress(String gateway_ip_address) { + this.gateway_ip_address = gateway_ip_address; + } + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplictRoutingConfig.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplictRoutingConfig.java index b4eda447b13..1228deb3f5d 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplictRoutingConfig.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplictRoutingConfig.java @@ -5,7 +5,7 @@ // 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, @@ -17,22 +17,22 @@ package com.cloud.network.nicira; /** - * + * */ public class SingleDefaultRouteImplictRoutingConfig extends RoutingConfig { - public RouterNextHop default_route_next_hop; - public String type = "SingleDefaultRouteImplicitRoutingConfig"; - - public SingleDefaultRouteImplictRoutingConfig(RouterNextHop routerNextHop) { - default_route_next_hop = routerNextHop; - } - - public RouterNextHop getDefaultRouteNextHop() { - return default_route_next_hop; - } - - public void setDefaultRouteNextHop(RouterNextHop default_route_next_hop) { - this.default_route_next_hop = default_route_next_hop; - } - + public RouterNextHop default_route_next_hop; + public String type = "SingleDefaultRouteImplicitRoutingConfig"; + + public SingleDefaultRouteImplictRoutingConfig(RouterNextHop routerNextHop) { + default_route_next_hop = routerNextHop; + } + + public RouterNextHop getDefaultRouteNextHop() { + return default_route_next_hop; + } + + public void setDefaultRouteNextHop(RouterNextHop default_route_next_hop) { + this.default_route_next_hop = default_route_next_hop; + } + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java index 4132da48094..910f83028f5 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java @@ -20,7 +20,7 @@ public class SourceNatRule extends NatRule { private String toSourceIpAddressMax; private String toSourceIpAddressMin; private Integer toSourcePort; - + public SourceNatRule() { setType("SourceNatRule"); } @@ -119,5 +119,5 @@ public class SourceNatRule extends NatRule { return false; return true; } - + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java index e55d759bdad..9c5f44d642b 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java @@ -19,9 +19,9 @@ package com.cloud.network.nicira; public class TransportZoneBinding { private String zone_uuid; private String transport_type; - + public TransportZoneBinding() {} - + public TransportZoneBinding(String zone_uuid, String transport_type) { this.zone_uuid = zone_uuid; this.transport_type = transport_type; @@ -42,5 +42,5 @@ public class TransportZoneBinding { public void setTransport_type(String transport_type) { this.transport_type = transport_type; } - + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java index dc87a5a58ea..3a0b5f31905 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java @@ -19,12 +19,12 @@ package com.cloud.network.nicira; public class VifAttachment extends Attachment { private final String type = "VifAttachment"; private String vif_uuid; - + public VifAttachment() { } - + public VifAttachment(String vifUuid) { - this.vif_uuid = vifUuid; + vif_uuid = vifUuid; } public String getVif_uuid() { @@ -38,5 +38,5 @@ public class VifAttachment extends Attachment { public String getType() { return type; } - + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java index 114c9395d15..3ab5f2bc49c 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java @@ -83,54 +83,54 @@ import com.cloud.resource.ServerResource; public class NiciraNvpResource implements ServerResource { private static final Logger s_logger = Logger.getLogger(NiciraNvpResource.class); - + private String _name; private String _guid; private String _zoneId; private int _numRetries; - + private NiciraNvpApi _niciraNvpApi; - + protected NiciraNvpApi createNiciraNvpApi() { - return new NiciraNvpApi(); + return new NiciraNvpApi(); } - + @Override public boolean configure(String name, Map params) throws ConfigurationException { - + _name = (String) params.get("name"); if (_name == null) { throw new ConfigurationException("Unable to find name"); } - + _guid = (String)params.get("guid"); if (_guid == null) { throw new ConfigurationException("Unable to find the guid"); } - + _zoneId = (String) params.get("zoneId"); if (_zoneId == null) { throw new ConfigurationException("Unable to find zone"); } - + _numRetries = 2; String ip = (String) params.get("ip"); if (ip == null) { throw new ConfigurationException("Unable to find IP"); } - + String adminuser = (String) params.get("adminuser"); if (adminuser == null) { throw new ConfigurationException("Unable to find admin username"); } - + String adminpass = (String) params.get("adminpass"); if (adminpass == null) { throw new ConfigurationException("Unable to find admin password"); - } - + } + _niciraNvpApi = createNiciraNvpApi(); _niciraNvpApi.setControllerAddress(ip); _niciraNvpApi.setAdminCredentials(adminuser,adminpass); @@ -172,21 +172,21 @@ public class NiciraNvpResource implements ServerResource { return new StartupCommand[] { sc }; } - @Override - public PingCommand getCurrentStatus(long id) { + @Override + public PingCommand getCurrentStatus(long id) { try { ControlClusterStatus ccs = _niciraNvpApi.getControlClusterStatus(); if (!"stable".equals(ccs.getClusterStatus())) { - s_logger.error("ControlCluster state is not stable: " - + ccs.getClusterStatus()); - return null; + s_logger.error("ControlCluster state is not stable: " + + ccs.getClusterStatus()); + return null; } } catch (NiciraNvpApiException e) { - s_logger.error("getControlClusterStatus failed", e); - return null; + s_logger.error("getControlClusterStatus failed", e); + return null; } return new PingCommand(Host.Type.L2Networking, id); - } + } @Override public Answer executeRequest(Command cmd) { @@ -213,25 +213,25 @@ public class NiciraNvpResource implements ServerResource { return executeRequest((DeleteLogicalSwitchPortCommand) cmd, numRetries); } else if (cmd instanceof UpdateLogicalSwitchPortCommand) { - return executeRequest((UpdateLogicalSwitchPortCommand) cmd, numRetries); + return executeRequest((UpdateLogicalSwitchPortCommand) cmd, numRetries); } else if (cmd instanceof FindLogicalSwitchPortCommand) { - return executeRequest((FindLogicalSwitchPortCommand) cmd, numRetries); + return executeRequest((FindLogicalSwitchPortCommand) cmd, numRetries); } else if (cmd instanceof CreateLogicalRouterCommand) { - return executeRequest((CreateLogicalRouterCommand) cmd, numRetries); + return executeRequest((CreateLogicalRouterCommand) cmd, numRetries); } else if (cmd instanceof DeleteLogicalRouterCommand) { - return executeRequest((DeleteLogicalRouterCommand) cmd, numRetries); + return executeRequest((DeleteLogicalRouterCommand) cmd, numRetries); } else if (cmd instanceof ConfigureStaticNatRulesOnLogicalRouterCommand) { - return executeRequest((ConfigureStaticNatRulesOnLogicalRouterCommand) cmd, numRetries); + return executeRequest((ConfigureStaticNatRulesOnLogicalRouterCommand) cmd, numRetries); } else if (cmd instanceof ConfigurePortForwardingRulesOnLogicalRouterCommand) { - return executeRequest((ConfigurePortForwardingRulesOnLogicalRouterCommand) cmd, numRetries); - } + return executeRequest((ConfigurePortForwardingRulesOnLogicalRouterCommand) cmd, numRetries); + } else if (cmd instanceof ConfigurePublicIpsOnLogicalRouterCommand) { - return executeRequest((ConfigurePublicIpsOnLogicalRouterCommand) cmd, numRetries); + return executeRequest((ConfigurePublicIpsOnLogicalRouterCommand) cmd, numRetries); } s_logger.debug("Received unsupported command " + cmd.toString()); return Answer.createUnsupportedCommandAnswer(cmd); @@ -249,7 +249,7 @@ public class NiciraNvpResource implements ServerResource { @Override public void setAgentControl(IAgentControl agentControl) { } - + private Answer executeRequest(CreateLogicalSwitchCommand cmd, int numRetries) { LogicalSwitch logicalSwitch = new LogicalSwitch(); logicalSwitch.setDisplay_name(truncate("lswitch-" + cmd.getName(), 40)); @@ -264,39 +264,39 @@ public class NiciraNvpResource implements ServerResource { List tags = new ArrayList(); tags.add(new NiciraNvpTag("cs_account",cmd.getOwnerName())); logicalSwitch.setTags(tags); - + try { logicalSwitch = _niciraNvpApi.createLogicalSwitch(logicalSwitch); return new CreateLogicalSwitchAnswer(cmd, true, "Logicalswitch " + logicalSwitch.getUuid() + " created", logicalSwitch.getUuid()); } catch (NiciraNvpApiException e) { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } - else { - return new CreateLogicalSwitchAnswer(cmd, e); - } + if (numRetries > 0) { + return retry(cmd, --numRetries); + } + else { + return new CreateLogicalSwitchAnswer(cmd, e); + } } - + } - + private Answer executeRequest(DeleteLogicalSwitchCommand cmd, int numRetries) { try { _niciraNvpApi.deleteLogicalSwitch(cmd.getLogicalSwitchUuid()); return new DeleteLogicalSwitchAnswer(cmd, true, "Logicalswitch " + cmd.getLogicalSwitchUuid() + " deleted"); } catch (NiciraNvpApiException e) { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } - else { - return new DeleteLogicalSwitchAnswer(cmd, e); - } + if (numRetries > 0) { + return retry(cmd, --numRetries); + } + else { + return new DeleteLogicalSwitchAnswer(cmd, e); + } } } - + private Answer executeRequest(CreateLogicalSwitchPortCommand cmd, int numRetries) { String logicalSwitchUuid = cmd.getLogicalSwitchUuid(); String attachmentUuid = cmd.getAttachmentUuid(); - + try { // Tags set to scope cs_account and account name List tags = new ArrayList(); @@ -305,35 +305,35 @@ public class NiciraNvpResource implements ServerResource { LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort(attachmentUuid, tags, true); LogicalSwitchPort newPort = _niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, logicalSwitchPort); try { - _niciraNvpApi.modifyLogicalSwitchPortAttachment(cmd.getLogicalSwitchUuid(), newPort.getUuid(), new VifAttachment(attachmentUuid)); + _niciraNvpApi.modifyLogicalSwitchPortAttachment(cmd.getLogicalSwitchUuid(), newPort.getUuid(), new VifAttachment(attachmentUuid)); } catch (NiciraNvpApiException ex) { - s_logger.warn("modifyLogicalSwitchPort failed after switchport was created, removing switchport"); - _niciraNvpApi.deleteLogicalSwitchPort(cmd.getLogicalSwitchUuid(), newPort.getUuid()); - throw (ex); // Rethrow the original exception + s_logger.warn("modifyLogicalSwitchPort failed after switchport was created, removing switchport"); + _niciraNvpApi.deleteLogicalSwitchPort(cmd.getLogicalSwitchUuid(), newPort.getUuid()); + throw (ex); // Rethrow the original exception } return new CreateLogicalSwitchPortAnswer(cmd, true, "Logical switch port " + newPort.getUuid() + " created", newPort.getUuid()); } catch (NiciraNvpApiException e) { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } - else { - return new CreateLogicalSwitchPortAnswer(cmd, e); - } + if (numRetries > 0) { + return retry(cmd, --numRetries); + } + else { + return new CreateLogicalSwitchPortAnswer(cmd, e); + } } - + } - + private Answer executeRequest(DeleteLogicalSwitchPortCommand cmd, int numRetries) { try { _niciraNvpApi.deleteLogicalSwitchPort(cmd.getLogicalSwitchUuid(), cmd.getLogicalSwitchPortUuid()); return new DeleteLogicalSwitchPortAnswer(cmd, true, "Logical switch port " + cmd.getLogicalSwitchPortUuid() + " deleted"); } catch (NiciraNvpApiException e) { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } - else { - return new DeleteLogicalSwitchPortAnswer(cmd, e); - } + if (numRetries > 0) { + return retry(cmd, --numRetries); + } + else { + return new DeleteLogicalSwitchPortAnswer(cmd, e); + } } } @@ -341,7 +341,7 @@ public class NiciraNvpResource implements ServerResource { String logicalSwitchUuid = cmd.getLogicalSwitchUuid(); String logicalSwitchPortUuid = cmd.getLogicalSwitchPortUuid(); String attachmentUuid = cmd.getAttachmentUuid(); - + try { // Tags set to scope cs_account and account name List tags = new ArrayList(); @@ -350,474 +350,474 @@ public class NiciraNvpResource implements ServerResource { _niciraNvpApi.modifyLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, new VifAttachment(attachmentUuid)); return new UpdateLogicalSwitchPortAnswer(cmd, true, "Attachment for " + logicalSwitchPortUuid + " updated", logicalSwitchPortUuid); } catch (NiciraNvpApiException e) { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } - else { - return new UpdateLogicalSwitchPortAnswer(cmd, e); - } + if (numRetries > 0) { + return retry(cmd, --numRetries); + } + else { + return new UpdateLogicalSwitchPortAnswer(cmd, e); + } } - + } - + private Answer executeRequest(FindLogicalSwitchPortCommand cmd, int numRetries) { - String logicalSwitchUuid = cmd.getLogicalSwitchUuid(); + String logicalSwitchUuid = cmd.getLogicalSwitchUuid(); String logicalSwitchPortUuid = cmd.getLogicalSwitchPortUuid(); - + try { - NiciraNvpList ports = _niciraNvpApi.findLogicalSwitchPortsByUuid(logicalSwitchUuid, logicalSwitchPortUuid); - if (ports.getResultCount() == 0) { - return new FindLogicalSwitchPortAnswer(cmd, false, "Logical switchport " + logicalSwitchPortUuid + " not found", null); - } - else { - return new FindLogicalSwitchPortAnswer(cmd, true, "Logical switchport " + logicalSwitchPortUuid + " found", logicalSwitchPortUuid); - } + NiciraNvpList ports = _niciraNvpApi.findLogicalSwitchPortsByUuid(logicalSwitchUuid, logicalSwitchPortUuid); + if (ports.getResultCount() == 0) { + return new FindLogicalSwitchPortAnswer(cmd, false, "Logical switchport " + logicalSwitchPortUuid + " not found", null); + } + else { + return new FindLogicalSwitchPortAnswer(cmd, true, "Logical switchport " + logicalSwitchPortUuid + " found", logicalSwitchPortUuid); + } } catch (NiciraNvpApiException e) { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } - else { - return new FindLogicalSwitchPortAnswer(cmd, e); - } - } + if (numRetries > 0) { + return retry(cmd, --numRetries); + } + else { + return new FindLogicalSwitchPortAnswer(cmd, e); + } + } } - + private Answer executeRequest(CreateLogicalRouterCommand cmd, int numRetries) { - String routerName = cmd.getName(); - String gatewayServiceUuid = cmd.getGatewayServiceUuid(); - String logicalSwitchUuid = cmd.getLogicalSwitchUuid(); - + String routerName = cmd.getName(); + String gatewayServiceUuid = cmd.getGatewayServiceUuid(); + String logicalSwitchUuid = cmd.getLogicalSwitchUuid(); + List tags = new ArrayList(); tags.add(new NiciraNvpTag("cs_account",cmd.getOwnerName())); - + String publicNetworkNextHopIp = cmd.getPublicNextHop(); String publicNetworkIpAddress = cmd.getPublicIpCidr(); String internalNetworkAddress = cmd.getInternalIpCidr(); - - s_logger.debug("Creating a logical router with external ip " - + publicNetworkIpAddress + " and internal ip " + internalNetworkAddress - + "on gateway service " + gatewayServiceUuid); - - try { - // Create the Router - LogicalRouterConfig lrc = new LogicalRouterConfig(); - lrc.setDisplayName(truncate(routerName, 40)); - lrc.setTags(tags); - lrc.setRoutingConfig(new SingleDefaultRouteImplictRoutingConfig( - new RouterNextHop(publicNetworkNextHopIp))); - lrc = _niciraNvpApi.createLogicalRouter(lrc); - - // store the switchport for rollback - LogicalSwitchPort lsp = null; - - try { - // Create the outside port for the router - LogicalRouterPort lrpo = new LogicalRouterPort(); - lrpo.setAdminStatusEnabled(true); - lrpo.setDisplayName(truncate(routerName + "-outside-port", 40)); - lrpo.setTags(tags); - List outsideIpAddresses = new ArrayList(); - outsideIpAddresses.add(publicNetworkIpAddress); - lrpo.setIpAddresses(outsideIpAddresses); - lrpo = _niciraNvpApi.createLogicalRouterPort(lrc.getUuid(),lrpo); - - // Attach the outside port to the gateway service on the correct VLAN - L3GatewayAttachment attachment = new L3GatewayAttachment(gatewayServiceUuid); - if (cmd.getVlanId() != 0) { - attachment.setVlanId(cmd.getVlanId()); - } - _niciraNvpApi.modifyLogicalRouterPortAttachment(lrc.getUuid(), lrpo.getUuid(), attachment); - - // Create the inside port for the router - LogicalRouterPort lrpi = new LogicalRouterPort(); - lrpi.setAdminStatusEnabled(true); - lrpi.setDisplayName(truncate(routerName + "-inside-port", 40)); - lrpi.setTags(tags); - List insideIpAddresses = new ArrayList(); - insideIpAddresses.add(internalNetworkAddress); - lrpi.setIpAddresses(insideIpAddresses); - lrpi = _niciraNvpApi.createLogicalRouterPort(lrc.getUuid(),lrpi); - - // Create the inside port on the lswitch - lsp = new LogicalSwitchPort(truncate(routerName + "-inside-port", 40), tags, true); - lsp = _niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, lsp); - - // Attach the inside router port to the lswitch port with a PatchAttachment - _niciraNvpApi.modifyLogicalRouterPortAttachment(lrc.getUuid(), lrpi.getUuid(), - new PatchAttachment(lsp.getUuid())); - - // Attach the inside lswitch port to the router with a PatchAttachment - _niciraNvpApi.modifyLogicalSwitchPortAttachment(logicalSwitchUuid, lsp.getUuid(), - new PatchAttachment(lrpi.getUuid())); - - // Setup the source nat rule - SourceNatRule snr = new SourceNatRule(); - snr.setToSourceIpAddressMin(publicNetworkIpAddress.split("/")[0]); - snr.setToSourceIpAddressMax(publicNetworkIpAddress.split("/")[0]); - Match match = new Match(); - match.setSourceIpAddresses(internalNetworkAddress); - snr.setMatch(match); - snr.setOrder(200); - _niciraNvpApi.createLogicalRouterNatRule(lrc.getUuid(), snr); - } catch (NiciraNvpApiException e) { - // We need to destroy the router if we already created it - // this will also take care of any router ports and rules - try { - _niciraNvpApi.deleteLogicalRouter(lrc.getUuid()); - if (lsp != null) { - _niciraNvpApi.deleteLogicalSwitchPort(logicalSwitchUuid, lsp.getUuid()); - } - } catch (NiciraNvpApiException ex) {} - - throw e; - } - - return new CreateLogicalRouterAnswer(cmd, true, "Logical Router created (uuid " + lrc.getUuid() + ")", lrc.getUuid()); - } catch (NiciraNvpApiException e) { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } - else { - return new CreateLogicalRouterAnswer(cmd, e); - } - } - } - - private Answer executeRequest(DeleteLogicalRouterCommand cmd, int numRetries) { - try { - _niciraNvpApi.deleteLogicalRouter(cmd.getLogicalRouterUuid()); - return new DeleteLogicalRouterAnswer(cmd, true, "Logical Router deleted (uuid " + cmd.getLogicalRouterUuid() + ")"); - } catch (NiciraNvpApiException e) { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } - else { - return new DeleteLogicalRouterAnswer(cmd, e); - } - } - } - - private Answer executeRequest(ConfigurePublicIpsOnLogicalRouterCommand cmd, int numRetries) { - try { - NiciraNvpList ports = _niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(cmd.getLogicalRouterUuid(), cmd.getL3GatewayServiceUuid()); - if (ports.getResultCount() != 1) { - return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, false, "No logical router ports found, unable to set ip addresses"); - } - LogicalRouterPort lrp = ports.getResults().get(0); - lrp.setIpAddresses(cmd.getPublicCidrs()); - _niciraNvpApi.modifyLogicalRouterPort(cmd.getLogicalRouterUuid(), lrp); - - return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, true, "Configured " + cmd.getPublicCidrs().size() + - " ip addresses on logical router uuid " + cmd.getLogicalRouterUuid()); - } catch (NiciraNvpApiException e) { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } - else { - return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, e); - } - } - - } - - private Answer executeRequest(ConfigureStaticNatRulesOnLogicalRouterCommand cmd, int numRetries) { - try { - NiciraNvpList existingRules = _niciraNvpApi.findNatRulesByLogicalRouterUuid(cmd.getLogicalRouterUuid()); - // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on) - // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule - // Any other SourceNat rule should have a corresponding DestinationNat rule - - for (StaticNatRuleTO rule : cmd.getRules()) { - - NatRule[] rulepair = generateStaticNatRulePair(rule.getDstIp(), rule.getSrcIp()); - - NatRule incoming = null; - NatRule outgoing = null; - for (NatRule storedRule : existingRules.getResults()) { - if (storedRule.equalsIgnoreUuid(rulepair[1])) { - // The outgoing rule exists - outgoing = storedRule; - s_logger.debug("Found matching outgoing rule " + outgoing.getUuid()); - if (incoming != null) { - break; - } - } - else if (storedRule.equalsIgnoreUuid(rulepair[0])) { - // The incoming rule exists - incoming = storedRule; - s_logger.debug("Found matching incoming rule " + incoming.getUuid()); - if (outgoing != null) { - break; - } - } - } - if (incoming != null && outgoing != null) { - if (rule.revoked()) { - s_logger.debug("Deleting incoming rule " + incoming.getUuid()); - _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), incoming.getUuid()); - - s_logger.debug("Deleting outgoing rule " + outgoing.getUuid()); - _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), outgoing.getUuid()); - } - } - else { - if (rule.revoked()) { - s_logger.warn("Tried deleting a rule that does not exist, " + - rule.getSrcIp() + " -> " + rule.getDstIp()); - break; - } - - rulepair[0] = _niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0]); - s_logger.debug("Created " + natRuleToString(rulepair[0])); - - try { - rulepair[1] = _niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[1]); - s_logger.debug("Created " + natRuleToString(rulepair[1])); - } catch (NiciraNvpApiException ex) { - s_logger.debug("Failed to create SourceNatRule, rolling back DestinationNatRule"); - _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0].getUuid()); - throw ex; // Rethrow original exception - } - - } - } - return new ConfigureStaticNatRulesOnLogicalRouterAnswer(cmd, true, cmd.getRules().size() +" StaticNat rules applied"); + s_logger.debug("Creating a logical router with external ip " + + publicNetworkIpAddress + " and internal ip " + internalNetworkAddress + + "on gateway service " + gatewayServiceUuid); + + try { + // Create the Router + LogicalRouterConfig lrc = new LogicalRouterConfig(); + lrc.setDisplayName(truncate(routerName, 40)); + lrc.setTags(tags); + lrc.setRoutingConfig(new SingleDefaultRouteImplictRoutingConfig( + new RouterNextHop(publicNetworkNextHopIp))); + lrc = _niciraNvpApi.createLogicalRouter(lrc); + + // store the switchport for rollback + LogicalSwitchPort lsp = null; + + try { + // Create the outside port for the router + LogicalRouterPort lrpo = new LogicalRouterPort(); + lrpo.setAdminStatusEnabled(true); + lrpo.setDisplayName(truncate(routerName + "-outside-port", 40)); + lrpo.setTags(tags); + List outsideIpAddresses = new ArrayList(); + outsideIpAddresses.add(publicNetworkIpAddress); + lrpo.setIpAddresses(outsideIpAddresses); + lrpo = _niciraNvpApi.createLogicalRouterPort(lrc.getUuid(),lrpo); + + // Attach the outside port to the gateway service on the correct VLAN + L3GatewayAttachment attachment = new L3GatewayAttachment(gatewayServiceUuid); + if (cmd.getVlanId() != 0) { + attachment.setVlanId(cmd.getVlanId()); + } + _niciraNvpApi.modifyLogicalRouterPortAttachment(lrc.getUuid(), lrpo.getUuid(), attachment); + + // Create the inside port for the router + LogicalRouterPort lrpi = new LogicalRouterPort(); + lrpi.setAdminStatusEnabled(true); + lrpi.setDisplayName(truncate(routerName + "-inside-port", 40)); + lrpi.setTags(tags); + List insideIpAddresses = new ArrayList(); + insideIpAddresses.add(internalNetworkAddress); + lrpi.setIpAddresses(insideIpAddresses); + lrpi = _niciraNvpApi.createLogicalRouterPort(lrc.getUuid(),lrpi); + + // Create the inside port on the lswitch + lsp = new LogicalSwitchPort(truncate(routerName + "-inside-port", 40), tags, true); + lsp = _niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, lsp); + + // Attach the inside router port to the lswitch port with a PatchAttachment + _niciraNvpApi.modifyLogicalRouterPortAttachment(lrc.getUuid(), lrpi.getUuid(), + new PatchAttachment(lsp.getUuid())); + + // Attach the inside lswitch port to the router with a PatchAttachment + _niciraNvpApi.modifyLogicalSwitchPortAttachment(logicalSwitchUuid, lsp.getUuid(), + new PatchAttachment(lrpi.getUuid())); + + // Setup the source nat rule + SourceNatRule snr = new SourceNatRule(); + snr.setToSourceIpAddressMin(publicNetworkIpAddress.split("/")[0]); + snr.setToSourceIpAddressMax(publicNetworkIpAddress.split("/")[0]); + Match match = new Match(); + match.setSourceIpAddresses(internalNetworkAddress); + snr.setMatch(match); + snr.setOrder(200); + _niciraNvpApi.createLogicalRouterNatRule(lrc.getUuid(), snr); + } catch (NiciraNvpApiException e) { + // We need to destroy the router if we already created it + // this will also take care of any router ports and rules + try { + _niciraNvpApi.deleteLogicalRouter(lrc.getUuid()); + if (lsp != null) { + _niciraNvpApi.deleteLogicalSwitchPort(logicalSwitchUuid, lsp.getUuid()); + } + } catch (NiciraNvpApiException ex) {} + + throw e; + } + + return new CreateLogicalRouterAnswer(cmd, true, "Logical Router created (uuid " + lrc.getUuid() + ")", lrc.getUuid()); } catch (NiciraNvpApiException e) { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } - else { - return new ConfigureStaticNatRulesOnLogicalRouterAnswer(cmd, e); - } + if (numRetries > 0) { + return retry(cmd, --numRetries); + } + else { + return new CreateLogicalRouterAnswer(cmd, e); + } + } + } + + private Answer executeRequest(DeleteLogicalRouterCommand cmd, int numRetries) { + try { + _niciraNvpApi.deleteLogicalRouter(cmd.getLogicalRouterUuid()); + return new DeleteLogicalRouterAnswer(cmd, true, "Logical Router deleted (uuid " + cmd.getLogicalRouterUuid() + ")"); + } catch (NiciraNvpApiException e) { + if (numRetries > 0) { + return retry(cmd, --numRetries); + } + else { + return new DeleteLogicalRouterAnswer(cmd, e); + } + } + } + + private Answer executeRequest(ConfigurePublicIpsOnLogicalRouterCommand cmd, int numRetries) { + try { + NiciraNvpList ports = _niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(cmd.getLogicalRouterUuid(), cmd.getL3GatewayServiceUuid()); + if (ports.getResultCount() != 1) { + return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, false, "No logical router ports found, unable to set ip addresses"); + } + LogicalRouterPort lrp = ports.getResults().get(0); + lrp.setIpAddresses(cmd.getPublicCidrs()); + _niciraNvpApi.modifyLogicalRouterPort(cmd.getLogicalRouterUuid(), lrp); + + return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, true, "Configured " + cmd.getPublicCidrs().size() + + " ip addresses on logical router uuid " + cmd.getLogicalRouterUuid()); + } catch (NiciraNvpApiException e) { + if (numRetries > 0) { + return retry(cmd, --numRetries); + } + else { + return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, e); + } + } + + } + + private Answer executeRequest(ConfigureStaticNatRulesOnLogicalRouterCommand cmd, int numRetries) { + try { + NiciraNvpList existingRules = _niciraNvpApi.findNatRulesByLogicalRouterUuid(cmd.getLogicalRouterUuid()); + // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on) + // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule + // Any other SourceNat rule should have a corresponding DestinationNat rule + + for (StaticNatRuleTO rule : cmd.getRules()) { + + NatRule[] rulepair = generateStaticNatRulePair(rule.getDstIp(), rule.getSrcIp()); + + NatRule incoming = null; + NatRule outgoing = null; + + for (NatRule storedRule : existingRules.getResults()) { + if (storedRule.equalsIgnoreUuid(rulepair[1])) { + // The outgoing rule exists + outgoing = storedRule; + s_logger.debug("Found matching outgoing rule " + outgoing.getUuid()); + if (incoming != null) { + break; + } + } + else if (storedRule.equalsIgnoreUuid(rulepair[0])) { + // The incoming rule exists + incoming = storedRule; + s_logger.debug("Found matching incoming rule " + incoming.getUuid()); + if (outgoing != null) { + break; + } + } + } + if (incoming != null && outgoing != null) { + if (rule.revoked()) { + s_logger.debug("Deleting incoming rule " + incoming.getUuid()); + _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), incoming.getUuid()); + + s_logger.debug("Deleting outgoing rule " + outgoing.getUuid()); + _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), outgoing.getUuid()); + } + } + else { + if (rule.revoked()) { + s_logger.warn("Tried deleting a rule that does not exist, " + + rule.getSrcIp() + " -> " + rule.getDstIp()); + break; + } + + rulepair[0] = _niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0]); + s_logger.debug("Created " + natRuleToString(rulepair[0])); + + try { + rulepair[1] = _niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[1]); + s_logger.debug("Created " + natRuleToString(rulepair[1])); + } catch (NiciraNvpApiException ex) { + s_logger.debug("Failed to create SourceNatRule, rolling back DestinationNatRule"); + _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0].getUuid()); + throw ex; // Rethrow original exception + } + + } + } + return new ConfigureStaticNatRulesOnLogicalRouterAnswer(cmd, true, cmd.getRules().size() +" StaticNat rules applied"); + } catch (NiciraNvpApiException e) { + if (numRetries > 0) { + return retry(cmd, --numRetries); + } + else { + return new ConfigureStaticNatRulesOnLogicalRouterAnswer(cmd, e); + } } } private Answer executeRequest(ConfigurePortForwardingRulesOnLogicalRouterCommand cmd, int numRetries) { - try { - NiciraNvpList existingRules = _niciraNvpApi.findNatRulesByLogicalRouterUuid(cmd.getLogicalRouterUuid()); - // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on) - // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule - // Any other SourceNat rule should have a corresponding DestinationNat rule - - for (PortForwardingRuleTO rule : cmd.getRules()) { - if (rule.isAlreadyAdded() && !rule.revoked()) { - // Don't need to do anything - continue; - } - - if (rule.getDstPortRange()[0] != rule.getDstPortRange()[1] || - rule.getSrcPortRange()[0] != rule.getSrcPortRange()[1] ) { - return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(cmd, false, "Nicira NVP doesn't support port ranges for port forwarding"); - } - - NatRule[] rulepair = generatePortForwardingRulePair(rule.getDstIp(), rule.getDstPortRange(), rule.getSrcIp(), rule.getSrcPortRange(), rule.getProtocol()); - - NatRule incoming = null; - NatRule outgoing = null; + try { + NiciraNvpList existingRules = _niciraNvpApi.findNatRulesByLogicalRouterUuid(cmd.getLogicalRouterUuid()); + // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on) + // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule + // Any other SourceNat rule should have a corresponding DestinationNat rule - for (NatRule storedRule : existingRules.getResults()) { - if (storedRule.equalsIgnoreUuid(rulepair[1])) { - // The outgoing rule exists - outgoing = storedRule; - s_logger.debug("Found matching outgoing rule " + outgoing.getUuid()); - if (incoming != null) { - break; - } - } - else if (storedRule.equalsIgnoreUuid(rulepair[0])) { - // The incoming rule exists - incoming = storedRule; - s_logger.debug("Found matching incoming rule " + incoming.getUuid()); - if (outgoing != null) { - break; - } - } - } - if (incoming != null && outgoing != null) { - if (rule.revoked()) { - s_logger.debug("Deleting incoming rule " + incoming.getUuid()); - _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), incoming.getUuid()); - - s_logger.debug("Deleting outgoing rule " + outgoing.getUuid()); - _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), outgoing.getUuid()); - } - } - else { - if (rule.revoked()) { - s_logger.warn("Tried deleting a rule that does not exist, " + - rule.getSrcIp() + " -> " + rule.getDstIp()); - break; - } - - rulepair[0] = _niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0]); - s_logger.debug("Created " + natRuleToString(rulepair[0])); - - try { - rulepair[1] = _niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[1]); - s_logger.debug("Created " + natRuleToString(rulepair[1])); - } catch (NiciraNvpApiException ex) { - s_logger.warn("NiciraNvpApiException during create call, rolling back previous create"); - _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0].getUuid()); - throw ex; // Rethrow the original exception - } - - } - } - return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(cmd, true, cmd.getRules().size() +" PortForwarding rules applied"); + for (PortForwardingRuleTO rule : cmd.getRules()) { + if (rule.isAlreadyAdded() && !rule.revoked()) { + // Don't need to do anything + continue; + } + + if (rule.getDstPortRange()[0] != rule.getDstPortRange()[1] || + rule.getSrcPortRange()[0] != rule.getSrcPortRange()[1] ) { + return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(cmd, false, "Nicira NVP doesn't support port ranges for port forwarding"); + } + + NatRule[] rulepair = generatePortForwardingRulePair(rule.getDstIp(), rule.getDstPortRange(), rule.getSrcIp(), rule.getSrcPortRange(), rule.getProtocol()); + + NatRule incoming = null; + NatRule outgoing = null; + + for (NatRule storedRule : existingRules.getResults()) { + if (storedRule.equalsIgnoreUuid(rulepair[1])) { + // The outgoing rule exists + outgoing = storedRule; + s_logger.debug("Found matching outgoing rule " + outgoing.getUuid()); + if (incoming != null) { + break; + } + } + else if (storedRule.equalsIgnoreUuid(rulepair[0])) { + // The incoming rule exists + incoming = storedRule; + s_logger.debug("Found matching incoming rule " + incoming.getUuid()); + if (outgoing != null) { + break; + } + } + } + if (incoming != null && outgoing != null) { + if (rule.revoked()) { + s_logger.debug("Deleting incoming rule " + incoming.getUuid()); + _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), incoming.getUuid()); + + s_logger.debug("Deleting outgoing rule " + outgoing.getUuid()); + _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), outgoing.getUuid()); + } + } + else { + if (rule.revoked()) { + s_logger.warn("Tried deleting a rule that does not exist, " + + rule.getSrcIp() + " -> " + rule.getDstIp()); + break; + } + + rulepair[0] = _niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0]); + s_logger.debug("Created " + natRuleToString(rulepair[0])); + + try { + rulepair[1] = _niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[1]); + s_logger.debug("Created " + natRuleToString(rulepair[1])); + } catch (NiciraNvpApiException ex) { + s_logger.warn("NiciraNvpApiException during create call, rolling back previous create"); + _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0].getUuid()); + throw ex; // Rethrow the original exception + } + + } + } + return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(cmd, true, cmd.getRules().size() +" PortForwarding rules applied"); } catch (NiciraNvpApiException e) { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } - else { - return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(cmd, e); - } + if (numRetries > 0) { + return retry(cmd, --numRetries); + } + else { + return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(cmd, e); + } } - + } - + private Answer executeRequest(ReadyCommand cmd) { return new ReadyAnswer(cmd); } - + private Answer executeRequest(MaintainCommand cmd) { return new MaintainAnswer(cmd); - } + } private Answer retry(Command cmd, int numRetries) { s_logger.warn("Retrying " + cmd.getClass().getSimpleName() + ". Number of retries remaining: " + numRetries); return executeRequest(cmd, numRetries); } - + private String natRuleToString(NatRule rule) { - - StringBuilder natRuleStr = new StringBuilder(); - natRuleStr.append("Rule "); - natRuleStr.append(rule.getUuid()); - natRuleStr.append(" ("); - natRuleStr.append(rule.getType()); - natRuleStr.append(") :"); - Match m = rule.getMatch(); - natRuleStr.append("match ("); - natRuleStr.append(m.getProtocol()); - natRuleStr.append(" "); - natRuleStr.append(m.getSourceIpAddresses()); - natRuleStr.append(" ["); - natRuleStr.append(m.getSourcePort()); - natRuleStr.append(" ] -> "); - natRuleStr.append(m.getDestinationIpAddresses()); - natRuleStr.append(" ["); - natRuleStr.append(m.getDestinationPort()); - natRuleStr.append(" ]) -->"); - if ("SourceNatRule".equals(rule.getType())) { - natRuleStr.append(((SourceNatRule)rule).getToSourceIpAddressMin()); - natRuleStr.append("-"); - natRuleStr.append(((SourceNatRule)rule).getToSourceIpAddressMax()); - natRuleStr.append(" ["); - natRuleStr.append(((SourceNatRule)rule).getToSourcePort()); - natRuleStr.append(" ])"); - } - else { - natRuleStr.append(((DestinationNatRule)rule).getToDestinationIpAddress()); - natRuleStr.append(" ["); - natRuleStr.append(((DestinationNatRule)rule).getToDestinationPort()); - natRuleStr.append(" ])"); - } - return natRuleStr.toString(); + + StringBuilder natRuleStr = new StringBuilder(); + natRuleStr.append("Rule "); + natRuleStr.append(rule.getUuid()); + natRuleStr.append(" ("); + natRuleStr.append(rule.getType()); + natRuleStr.append(") :"); + Match m = rule.getMatch(); + natRuleStr.append("match ("); + natRuleStr.append(m.getProtocol()); + natRuleStr.append(" "); + natRuleStr.append(m.getSourceIpAddresses()); + natRuleStr.append(" ["); + natRuleStr.append(m.getSourcePort()); + natRuleStr.append(" ] -> "); + natRuleStr.append(m.getDestinationIpAddresses()); + natRuleStr.append(" ["); + natRuleStr.append(m.getDestinationPort()); + natRuleStr.append(" ]) -->"); + if ("SourceNatRule".equals(rule.getType())) { + natRuleStr.append(((SourceNatRule)rule).getToSourceIpAddressMin()); + natRuleStr.append("-"); + natRuleStr.append(((SourceNatRule)rule).getToSourceIpAddressMax()); + natRuleStr.append(" ["); + natRuleStr.append(((SourceNatRule)rule).getToSourcePort()); + natRuleStr.append(" ])"); + } + else { + natRuleStr.append(((DestinationNatRule)rule).getToDestinationIpAddress()); + natRuleStr.append(" ["); + natRuleStr.append(((DestinationNatRule)rule).getToDestinationPort()); + natRuleStr.append(" ])"); + } + return natRuleStr.toString(); } - + private String truncate(String string, int length) { - if (string.length() <= length) { - return string; - } - else { - return string.substring(0, length); - } + if (string.length() <= length) { + return string; + } + else { + return string.substring(0, length); + } } - + protected NatRule[] generateStaticNatRulePair(String insideIp, String outsideIp) { - NatRule[] rulepair = new NatRule[2]; - rulepair[0] = new DestinationNatRule(); - rulepair[0].setType("DestinationNatRule"); - rulepair[0].setOrder(100); - rulepair[1] = new SourceNatRule(); - rulepair[1].setType("SourceNatRule"); - rulepair[1].setOrder(100); - - Match m = new Match(); - m.setDestinationIpAddresses(outsideIp); - rulepair[0].setMatch(m); - ((DestinationNatRule)rulepair[0]).setToDestinationIpAddress(insideIp); + NatRule[] rulepair = new NatRule[2]; + rulepair[0] = new DestinationNatRule(); + rulepair[0].setType("DestinationNatRule"); + rulepair[0].setOrder(100); + rulepair[1] = new SourceNatRule(); + rulepair[1].setType("SourceNatRule"); + rulepair[1].setOrder(100); + + Match m = new Match(); + m.setDestinationIpAddresses(outsideIp); + rulepair[0].setMatch(m); + ((DestinationNatRule)rulepair[0]).setToDestinationIpAddress(insideIp); + + // create matching snat rule + m = new Match(); + m.setSourceIpAddresses(insideIp); + rulepair[1].setMatch(m); + ((SourceNatRule)rulepair[1]).setToSourceIpAddressMin(outsideIp); + ((SourceNatRule)rulepair[1]).setToSourceIpAddressMax(outsideIp); + + return rulepair; - // create matching snat rule - m = new Match(); - m.setSourceIpAddresses(insideIp); - rulepair[1].setMatch(m); - ((SourceNatRule)rulepair[1]).setToSourceIpAddressMin(outsideIp); - ((SourceNatRule)rulepair[1]).setToSourceIpAddressMax(outsideIp); - - return rulepair; - } - + protected NatRule[] generatePortForwardingRulePair(String insideIp, int[] insidePorts, String outsideIp, int[] outsidePorts, String protocol) { - // Start with a basic static nat rule, then add port and protocol details - NatRule[] rulepair = generateStaticNatRulePair(insideIp, outsideIp); - - ((DestinationNatRule)rulepair[0]).setToDestinationPort(insidePorts[0]); - rulepair[0].getMatch().setDestinationPort(outsidePorts[0]); - rulepair[0].setOrder(50); - rulepair[0].getMatch().setEthertype("IPv4"); - if ("tcp".equals(protocol)) { - rulepair[0].getMatch().setProtocol(6); - } - else if ("udp".equals(protocol)) { - rulepair[0].getMatch().setProtocol(17); - } + // Start with a basic static nat rule, then add port and protocol details + NatRule[] rulepair = generateStaticNatRulePair(insideIp, outsideIp); - ((SourceNatRule)rulepair[1]).setToSourcePort(outsidePorts[0]); - rulepair[1].getMatch().setSourcePort(insidePorts[0]); - rulepair[1].setOrder(50); - rulepair[1].getMatch().setEthertype("IPv4"); - if ("tcp".equals(protocol)) { - rulepair[1].getMatch().setProtocol(6); - } - else if ("udp".equals(protocol)) { - rulepair[1].getMatch().setProtocol(17); - } + ((DestinationNatRule)rulepair[0]).setToDestinationPort(insidePorts[0]); + rulepair[0].getMatch().setDestinationPort(outsidePorts[0]); + rulepair[0].setOrder(50); + rulepair[0].getMatch().setEthertype("IPv4"); + if ("tcp".equals(protocol)) { + rulepair[0].getMatch().setProtocol(6); + } + else if ("udp".equals(protocol)) { + rulepair[0].getMatch().setProtocol(17); + } + + ((SourceNatRule)rulepair[1]).setToSourcePort(outsidePorts[0]); + rulepair[1].getMatch().setSourcePort(insidePorts[0]); + rulepair[1].setOrder(50); + rulepair[1].getMatch().setEthertype("IPv4"); + if ("tcp".equals(protocol)) { + rulepair[1].getMatch().setProtocol(6); + } + else if ("udp".equals(protocol)) { + rulepair[1].getMatch().setProtocol(17); + } + + return rulepair; - return rulepair; - } - @Override - public void setName(String name) { - // TODO Auto-generated method stub - - } + @Override + public void setName(String name) { + // TODO Auto-generated method stub - @Override - public void setConfigParams(Map params) { - // TODO Auto-generated method stub - - } + } - @Override - public Map getConfigParams() { - // TODO Auto-generated method stub - return null; - } + @Override + public void setConfigParams(Map params) { + // TODO Auto-generated method stub - @Override - public int getRunLevel() { - // TODO Auto-generated method stub - return 0; - } + } + + @Override + public Map getConfigParams() { + // TODO Auto-generated method stub + return null; + } + + @Override + public int getRunLevel() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public void setRunLevel(int level) { + // TODO Auto-generated method stub + + } - @Override - public void setRunLevel(int level) { - // TODO Auto-generated method stub - - } - } diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/element/NiciraNvpElementTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/element/NiciraNvpElementTest.java index 6b5c103065f..9202241e989 100644 --- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/element/NiciraNvpElementTest.java +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/element/NiciraNvpElementTest.java @@ -16,6 +16,16 @@ // under the License. package com.cloud.network.element; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.argThat; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; @@ -31,7 +41,6 @@ import org.mockito.ArgumentMatcher; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Command; import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer; import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand; import com.cloud.deploy.DeployDestination; @@ -41,11 +50,11 @@ import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; +import com.cloud.network.IpAddress; import com.cloud.network.Network; import com.cloud.network.Network.GuestType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; -import com.cloud.network.IpAddress; import com.cloud.network.NetworkModel; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.TrafficType; @@ -55,18 +64,12 @@ import com.cloud.network.PublicIpAddress; import com.cloud.network.dao.NetworkServiceMapDao; import com.cloud.network.dao.NiciraNvpDao; import com.cloud.network.dao.NiciraNvpRouterMappingDao; -import com.cloud.network.nicira.NatRule; import com.cloud.offering.NetworkOffering; import com.cloud.resource.ResourceManager; import com.cloud.user.Account; import com.cloud.utils.net.Ip; import com.cloud.vm.ReservationContext; -import static org.junit.Assert.*; -import static org.mockito.Matchers.argThat; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; - public class NiciraNvpElementTest { NiciraNvpElement _element = new NiciraNvpElement(); @@ -136,7 +139,7 @@ public class NiciraNvpElementTest { when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getGuestType()).thenReturn(GuestType.Isolated); - DeployDestination dest = mock(DeployDestination.class); + mock(DeployDestination.class); Domain dom = mock(Domain.class); when(dom.getName()).thenReturn("domain"); diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java index 58c0333c9e3..42e436f315d 100644 --- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java @@ -16,8 +16,19 @@ // under the License. package com.cloud.network.guru; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyLong; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import java.net.URI; import java.net.URISyntaxException; +import java.util.Arrays; import java.util.Collections; import org.junit.Before; @@ -25,16 +36,13 @@ import org.junit.Test; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - import com.cloud.agent.AgentManager; import com.cloud.agent.api.Command; import com.cloud.agent.api.CreateLogicalSwitchAnswer; import com.cloud.agent.api.DeleteLogicalSwitchAnswer; import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenterVO; import com.cloud.dc.DataCenter.NetworkType; +import com.cloud.dc.DataCenterVO; import com.cloud.dc.dao.DataCenterDao; import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeploymentPlan; @@ -61,404 +69,401 @@ import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; import com.cloud.user.Account; import com.cloud.vm.ReservationContext; -import java.util.Arrays; - public class NiciraNvpGuestNetworkGuruTest { - PhysicalNetworkDao physnetdao = mock (PhysicalNetworkDao.class); - NiciraNvpDao nvpdao = mock(NiciraNvpDao.class); - DataCenterDao dcdao = mock(DataCenterDao.class); - NetworkOfferingServiceMapDao nosd = mock(NetworkOfferingServiceMapDao.class); - AgentManager agentmgr = mock (AgentManager.class); - NetworkOrchestrationService netmgr = mock (NetworkOrchestrationService.class); - NetworkModel netmodel = mock (NetworkModel.class); + PhysicalNetworkDao physnetdao = mock(PhysicalNetworkDao.class); + NiciraNvpDao nvpdao = mock(NiciraNvpDao.class); + DataCenterDao dcdao = mock(DataCenterDao.class); + NetworkOfferingServiceMapDao nosd = mock(NetworkOfferingServiceMapDao.class); + AgentManager agentmgr = mock (AgentManager.class); + NetworkOrchestrationService netmgr = mock (NetworkOrchestrationService.class); + NetworkModel netmodel = mock (NetworkModel.class); - HostDao hostdao = mock (HostDao.class); - NetworkDao netdao = mock(NetworkDao.class); - NiciraNvpGuestNetworkGuru guru; - - - @Before - public void setUp() { - guru = new NiciraNvpGuestNetworkGuru(); - ((GuestNetworkGuru) guru)._physicalNetworkDao = physnetdao; - guru._physicalNetworkDao = physnetdao; - guru._niciraNvpDao = nvpdao; - guru._dcDao = dcdao; - guru._ntwkOfferingSrvcDao = nosd; - guru._networkModel = netmodel; - guru._hostDao = hostdao; - guru._agentMgr = agentmgr; - guru._networkDao = netdao; - - DataCenterVO dc = mock(DataCenterVO.class); - when(dc.getNetworkType()).thenReturn(NetworkType.Advanced); - when(dc.getGuestNetworkCidr()).thenReturn("10.1.1.1/24"); - - when(dcdao.findById((Long) any())).thenReturn((DataCenterVO) dc); - } - - @Test - public void testCanHandle() { - NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(42L); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); - when(physnet.getId()).thenReturn(42L); - - when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(true); - - assertTrue(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); - - // Not supported TrafficType != Guest - when(offering.getTrafficType()).thenReturn(TrafficType.Management); - assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); - - // Not supported: GuestType Shared - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Shared); - assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); - - // Not supported: Basic networking - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - assertFalse(guru.canHandle(offering, NetworkType.Basic, physnet) == true); - - // Not supported: IsolationMethod != STT - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "VLAN" })); - assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); - - } - - - @Test - public void testDesign() { - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long) any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); - when(physnet.getId()).thenReturn(42L); - - NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device })); - when(device.getId()).thenReturn(1L); - - NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(42L); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(true); - - DeploymentPlan plan = mock(DeploymentPlan.class); - Network network = mock(Network.class); - Account account = mock(Account.class); - - Network designednetwork = guru.design(offering, plan, network, account); - assertTrue(designednetwork != null); - assertTrue(designednetwork.getBroadcastDomainType() == BroadcastDomainType.Lswitch); - } - - @Test - public void testDesignNoElementOnPhysicalNetwork() { - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long) any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); - when(physnet.getId()).thenReturn(42L); - - NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Collections. emptyList()); - - NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(42L); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - DeploymentPlan plan = mock(DeploymentPlan.class); - Network network = mock(Network.class); - Account account = mock(Account.class); - - Network designednetwork = guru.design(offering, plan, network, account); - assertTrue(designednetwork == null); - } - - @Test - public void testDesignNoIsolationMethodSTT() { - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long) any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "VLAN" })); - when(physnet.getId()).thenReturn(42L); - - NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Collections. emptyList()); - - NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(42L); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - DeploymentPlan plan = mock(DeploymentPlan.class); - Network network = mock(Network.class); - Account account = mock(Account.class); - - Network designednetwork = guru.design(offering, plan, network, account); - assertTrue(designednetwork == null); - } - - @Test - public void testDesignNoConnectivityInOffering() { - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long) any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); - when(physnet.getId()).thenReturn(42L); - - NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device })); - when(device.getId()).thenReturn(1L); - - NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(42L); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(false); - - DeploymentPlan plan = mock(DeploymentPlan.class); - Network network = mock(Network.class); - Account account = mock(Account.class); - - Network designednetwork = guru.design(offering, plan, network, account); - assertTrue(designednetwork == null); - } - - @Test - public void testImplement() throws InsufficientVirtualNetworkCapcityException { - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long) any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); - when(physnet.getId()).thenReturn(42L); - - NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device })); - when(device.getId()).thenReturn(1L); - - NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(42L); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(false); - - DeploymentPlan plan = mock(DeploymentPlan.class); - - NetworkVO network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(State.Implementing); - when(network.getPhysicalNetworkId()).thenReturn(42L); - - DeployDestination dest = mock(DeployDestination.class); - - DataCenter dc = mock(DataCenter.class); - when(dest.getDataCenter()).thenReturn(dc); - - HostVO niciraHost = mock(HostVO.class); - when(hostdao.findById(anyLong())).thenReturn(niciraHost); - when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); - when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); - when(niciraHost.getId()).thenReturn(42L); - - when(netmodel.findPhysicalNetworkId(anyLong(), (String) any(), (TrafficType) any())).thenReturn(42L); - Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("domain"); - Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("accountname"); - ReservationContext res = mock(ReservationContext.class); - when(res.getDomain()).thenReturn(dom); - when(res.getAccount()).thenReturn(acc); - - CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); - when(answer.getResult()).thenReturn(true); - when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); - when(agentmgr.easySend(eq(42L), (Command)any())).thenReturn(answer); + HostDao hostdao = mock (HostDao.class); + NetworkDao netdao = mock(NetworkDao.class); + NiciraNvpGuestNetworkGuru guru; - Network implementednetwork = guru.implement(network, offering, dest, res); - assertTrue(implementednetwork != null); - verify(agentmgr, times(1)).easySend(eq(42L), (Command)any()); - } - @Test - public void testImplementWithCidr() throws InsufficientVirtualNetworkCapcityException { - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long) any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); - when(physnet.getId()).thenReturn(42L); - - NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device })); - when(device.getId()).thenReturn(1L); - - NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(42L); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(false); - - DeploymentPlan plan = mock(DeploymentPlan.class); - - NetworkVO network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(State.Implementing); - when(network.getGateway()).thenReturn("10.1.1.1"); - when(network.getCidr()).thenReturn("10.1.1.0/24"); - when(network.getPhysicalNetworkId()).thenReturn(42L); - - DeployDestination dest = mock(DeployDestination.class); - - DataCenter dc = mock(DataCenter.class); - when(dest.getDataCenter()).thenReturn(dc); - - HostVO niciraHost = mock(HostVO.class); - when(hostdao.findById(anyLong())).thenReturn(niciraHost); - when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); - when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); - when(niciraHost.getId()).thenReturn(42L); - - when(netmodel.findPhysicalNetworkId(anyLong(), (String) any(), (TrafficType) any())).thenReturn(42L); - Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("domain"); - Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("accountname"); - ReservationContext res = mock(ReservationContext.class); - when(res.getDomain()).thenReturn(dom); - when(res.getAccount()).thenReturn(acc); - - CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); - when(answer.getResult()).thenReturn(true); - when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); - when(agentmgr.easySend(eq(42L), (Command)any())).thenReturn(answer); + @Before + public void setUp() { + guru = new NiciraNvpGuestNetworkGuru(); + ((GuestNetworkGuru) guru)._physicalNetworkDao = physnetdao; + guru._physicalNetworkDao = physnetdao; + guru._niciraNvpDao = nvpdao; + guru._dcDao = dcdao; + guru._ntwkOfferingSrvcDao = nosd; + guru._networkModel = netmodel; + guru._hostDao = hostdao; + guru._agentMgr = agentmgr; + guru._networkDao = netdao; - Network implementednetwork = guru.implement(network, offering, dest, res); - assertTrue(implementednetwork != null); - assertTrue(implementednetwork.getCidr().equals("10.1.1.0/24")); - assertTrue(implementednetwork.getGateway().equals("10.1.1.1")); - verify(agentmgr, times(1)).easySend(eq(42L), (Command)any()); - } - - @Test - public void testImplementURIException() throws InsufficientVirtualNetworkCapcityException { - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long) any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); - when(physnet.getId()).thenReturn(42L); - - NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device })); - when(device.getId()).thenReturn(1L); - - NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(42L); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(false); - - DeploymentPlan plan = mock(DeploymentPlan.class); - - NetworkVO network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(State.Implementing); - when(network.getPhysicalNetworkId()).thenReturn(42L); - - DeployDestination dest = mock(DeployDestination.class); - - DataCenter dc = mock(DataCenter.class); - when(dest.getDataCenter()).thenReturn(dc); - - HostVO niciraHost = mock(HostVO.class); - when(hostdao.findById(anyLong())).thenReturn(niciraHost); - when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); - when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); - when(niciraHost.getId()).thenReturn(42L); - - when(netmodel.findPhysicalNetworkId(anyLong(), (String) any(), (TrafficType) any())).thenReturn(42L); - Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("domain"); - Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("accountname"); - ReservationContext res = mock(ReservationContext.class); - when(res.getDomain()).thenReturn(dom); - when(res.getAccount()).thenReturn(acc); - - CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); - when(answer.getResult()).thenReturn(true); - //when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); - when(agentmgr.easySend(eq(42L), (Command)any())).thenReturn(answer); + DataCenterVO dc = mock(DataCenterVO.class); + when(dc.getNetworkType()).thenReturn(NetworkType.Advanced); + when(dc.getGuestNetworkCidr()).thenReturn("10.1.1.1/24"); - Network implementednetwork = guru.implement(network, offering, dest, res); - assertTrue(implementednetwork == null); - verify(agentmgr, times(1)).easySend(eq(42L), (Command)any()); - } - - @Test - public void testShutdown() throws InsufficientVirtualNetworkCapcityException, URISyntaxException { - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long) any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); - when(physnet.getId()).thenReturn(42L); - - NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device })); - when(device.getId()).thenReturn(1L); - - NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(42L); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(false); - - DeploymentPlan plan = mock(DeploymentPlan.class); - - NetworkVO network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(State.Implementing); - when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); - when(network.getBroadcastUri()).thenReturn(new URI("lswitch:aaaaa")); - when(network.getPhysicalNetworkId()).thenReturn(42L); - when(netdao.findById(42L)).thenReturn(network); - - DeployDestination dest = mock(DeployDestination.class); - - DataCenter dc = mock(DataCenter.class); - when(dest.getDataCenter()).thenReturn(dc); - - HostVO niciraHost = mock(HostVO.class); - when(hostdao.findById(anyLong())).thenReturn(niciraHost); - when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); - when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); - when(niciraHost.getId()).thenReturn(42L); - - when(netmodel.findPhysicalNetworkId(anyLong(), (String) any(), (TrafficType) any())).thenReturn(42L); - Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("domain"); - Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("accountname"); - ReservationContext res = mock(ReservationContext.class); - when(res.getDomain()).thenReturn(dom); - when(res.getAccount()).thenReturn(acc); - - DeleteLogicalSwitchAnswer answer = mock(DeleteLogicalSwitchAnswer.class); - when(answer.getResult()).thenReturn(true); - when(agentmgr.easySend(eq(42L), (Command)any())).thenReturn(answer); + when(dcdao.findById((Long) any())).thenReturn(dc); + } - NetworkProfile implementednetwork = mock(NetworkProfile.class); - when(implementednetwork.getId()).thenReturn(42L); - when(implementednetwork.getBroadcastUri()).thenReturn(new URI("lswitch:aaaa")); - when(offering.getSpecifyVlan()).thenReturn(false); - - guru.shutdown(implementednetwork, offering); - verify(agentmgr, times(1)).easySend(eq(42L), (Command)any()); - verify(implementednetwork, times(1)).setBroadcastUri(null); - } + @Test + public void testCanHandle() { + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); + when(physnet.getId()).thenReturn(42L); + + when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(true); + + assertTrue(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); + + // Not supported TrafficType != Guest + when(offering.getTrafficType()).thenReturn(TrafficType.Management); + assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); + + // Not supported: GuestType Shared + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Shared); + assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); + + // Not supported: Basic networking + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + assertFalse(guru.canHandle(offering, NetworkType.Basic, physnet) == true); + + // Not supported: IsolationMethod != STT + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "VLAN" })); + assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); + + } + + @Test + public void testDesign() { + PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long) any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); + when(physnet.getId()).thenReturn(42L); + + NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device })); + when(device.getId()).thenReturn(1L); + + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(true); + + DeploymentPlan plan = mock(DeploymentPlan.class); + Network network = mock(Network.class); + Account account = mock(Account.class); + + Network designednetwork = guru.design(offering, plan, network, account); + assertTrue(designednetwork != null); + assertTrue(designednetwork.getBroadcastDomainType() == BroadcastDomainType.Lswitch); + } + + @Test + public void testDesignNoElementOnPhysicalNetwork() { + PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long) any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); + when(physnet.getId()).thenReturn(42L); + + mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Collections. emptyList()); + + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + DeploymentPlan plan = mock(DeploymentPlan.class); + Network network = mock(Network.class); + Account account = mock(Account.class); + + Network designednetwork = guru.design(offering, plan, network, account); + assertTrue(designednetwork == null); + } + + @Test + public void testDesignNoIsolationMethodSTT() { + PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long) any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "VLAN" })); + when(physnet.getId()).thenReturn(42L); + + mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Collections. emptyList()); + + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + DeploymentPlan plan = mock(DeploymentPlan.class); + Network network = mock(Network.class); + Account account = mock(Account.class); + + Network designednetwork = guru.design(offering, plan, network, account); + assertTrue(designednetwork == null); + } + + @Test + public void testDesignNoConnectivityInOffering() { + PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long) any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); + when(physnet.getId()).thenReturn(42L); + + NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device })); + when(device.getId()).thenReturn(1L); + + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(false); + + DeploymentPlan plan = mock(DeploymentPlan.class); + Network network = mock(Network.class); + Account account = mock(Account.class); + + Network designednetwork = guru.design(offering, plan, network, account); + assertTrue(designednetwork == null); + } + + @Test + public void testImplement() throws InsufficientVirtualNetworkCapcityException { + PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long) any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); + when(physnet.getId()).thenReturn(42L); + + NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device })); + when(device.getId()).thenReturn(1L); + + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(false); + + mock(DeploymentPlan.class); + + NetworkVO network = mock(NetworkVO.class); + when(network.getName()).thenReturn("testnetwork"); + when(network.getState()).thenReturn(State.Implementing); + when(network.getPhysicalNetworkId()).thenReturn(42L); + + DeployDestination dest = mock(DeployDestination.class); + + DataCenter dc = mock(DataCenter.class); + when(dest.getDataCenter()).thenReturn(dc); + + HostVO niciraHost = mock(HostVO.class); + when(hostdao.findById(anyLong())).thenReturn(niciraHost); + when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); + when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); + when(niciraHost.getId()).thenReturn(42L); + + when(netmodel.findPhysicalNetworkId(anyLong(), (String) any(), (TrafficType) any())).thenReturn(42L); + Domain dom = mock(Domain.class); + when(dom.getName()).thenReturn("domain"); + Account acc = mock(Account.class); + when(acc.getAccountName()).thenReturn("accountname"); + ReservationContext res = mock(ReservationContext.class); + when(res.getDomain()).thenReturn(dom); + when(res.getAccount()).thenReturn(acc); + + CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); + when(answer.getResult()).thenReturn(true); + when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); + when(agentmgr.easySend(eq(42L), (Command)any())).thenReturn(answer); + + Network implementednetwork = guru.implement(network, offering, dest, res); + assertTrue(implementednetwork != null); + verify(agentmgr, times(1)).easySend(eq(42L), (Command)any()); + } + + @Test + public void testImplementWithCidr() throws InsufficientVirtualNetworkCapcityException { + PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long) any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); + when(physnet.getId()).thenReturn(42L); + + NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device })); + when(device.getId()).thenReturn(1L); + + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(false); + + mock(DeploymentPlan.class); + + NetworkVO network = mock(NetworkVO.class); + when(network.getName()).thenReturn("testnetwork"); + when(network.getState()).thenReturn(State.Implementing); + when(network.getGateway()).thenReturn("10.1.1.1"); + when(network.getCidr()).thenReturn("10.1.1.0/24"); + when(network.getPhysicalNetworkId()).thenReturn(42L); + + DeployDestination dest = mock(DeployDestination.class); + + DataCenter dc = mock(DataCenter.class); + when(dest.getDataCenter()).thenReturn(dc); + + HostVO niciraHost = mock(HostVO.class); + when(hostdao.findById(anyLong())).thenReturn(niciraHost); + when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); + when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); + when(niciraHost.getId()).thenReturn(42L); + + when(netmodel.findPhysicalNetworkId(anyLong(), (String) any(), (TrafficType) any())).thenReturn(42L); + Domain dom = mock(Domain.class); + when(dom.getName()).thenReturn("domain"); + Account acc = mock(Account.class); + when(acc.getAccountName()).thenReturn("accountname"); + ReservationContext res = mock(ReservationContext.class); + when(res.getDomain()).thenReturn(dom); + when(res.getAccount()).thenReturn(acc); + + CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); + when(answer.getResult()).thenReturn(true); + when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); + when(agentmgr.easySend(eq(42L), (Command)any())).thenReturn(answer); + + Network implementednetwork = guru.implement(network, offering, dest, res); + assertTrue(implementednetwork != null); + assertTrue(implementednetwork.getCidr().equals("10.1.1.0/24")); + assertTrue(implementednetwork.getGateway().equals("10.1.1.1")); + verify(agentmgr, times(1)).easySend(eq(42L), (Command)any()); + } + + @Test + public void testImplementURIException() throws InsufficientVirtualNetworkCapcityException { + PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long) any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); + when(physnet.getId()).thenReturn(42L); + + NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device })); + when(device.getId()).thenReturn(1L); + + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(false); + + mock(DeploymentPlan.class); + + NetworkVO network = mock(NetworkVO.class); + when(network.getName()).thenReturn("testnetwork"); + when(network.getState()).thenReturn(State.Implementing); + when(network.getPhysicalNetworkId()).thenReturn(42L); + + DeployDestination dest = mock(DeployDestination.class); + + DataCenter dc = mock(DataCenter.class); + when(dest.getDataCenter()).thenReturn(dc); + + HostVO niciraHost = mock(HostVO.class); + when(hostdao.findById(anyLong())).thenReturn(niciraHost); + when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); + when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); + when(niciraHost.getId()).thenReturn(42L); + + when(netmodel.findPhysicalNetworkId(anyLong(), (String) any(), (TrafficType) any())).thenReturn(42L); + Domain dom = mock(Domain.class); + when(dom.getName()).thenReturn("domain"); + Account acc = mock(Account.class); + when(acc.getAccountName()).thenReturn("accountname"); + ReservationContext res = mock(ReservationContext.class); + when(res.getDomain()).thenReturn(dom); + when(res.getAccount()).thenReturn(acc); + + CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); + when(answer.getResult()).thenReturn(true); + //when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); + when(agentmgr.easySend(eq(42L), (Command)any())).thenReturn(answer); + + Network implementednetwork = guru.implement(network, offering, dest, res); + assertTrue(implementednetwork == null); + verify(agentmgr, times(1)).easySend(eq(42L), (Command)any()); + } + + @Test + public void testShutdown() throws InsufficientVirtualNetworkCapcityException, URISyntaxException { + PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long) any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); + when(physnet.getId()).thenReturn(42L); + + NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device })); + when(device.getId()).thenReturn(1L); + + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(false); + + mock(DeploymentPlan.class); + + NetworkVO network = mock(NetworkVO.class); + when(network.getName()).thenReturn("testnetwork"); + when(network.getState()).thenReturn(State.Implementing); + when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); + when(network.getBroadcastUri()).thenReturn(new URI("lswitch:aaaaa")); + when(network.getPhysicalNetworkId()).thenReturn(42L); + when(netdao.findById(42L)).thenReturn(network); + + DeployDestination dest = mock(DeployDestination.class); + + DataCenter dc = mock(DataCenter.class); + when(dest.getDataCenter()).thenReturn(dc); + + HostVO niciraHost = mock(HostVO.class); + when(hostdao.findById(anyLong())).thenReturn(niciraHost); + when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); + when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); + when(niciraHost.getId()).thenReturn(42L); + + when(netmodel.findPhysicalNetworkId(anyLong(), (String) any(), (TrafficType) any())).thenReturn(42L); + Domain dom = mock(Domain.class); + when(dom.getName()).thenReturn("domain"); + Account acc = mock(Account.class); + when(acc.getAccountName()).thenReturn("accountname"); + ReservationContext res = mock(ReservationContext.class); + when(res.getDomain()).thenReturn(dom); + when(res.getAccount()).thenReturn(acc); + + DeleteLogicalSwitchAnswer answer = mock(DeleteLogicalSwitchAnswer.class); + when(answer.getResult()).thenReturn(true); + when(agentmgr.easySend(eq(42L), (Command)any())).thenReturn(answer); + + NetworkProfile implementednetwork = mock(NetworkProfile.class); + when(implementednetwork.getId()).thenReturn(42L); + when(implementednetwork.getBroadcastUri()).thenReturn(new URI("lswitch:aaaa")); + when(offering.getSpecifyVlan()).thenReturn(false); + + guru.shutdown(implementednetwork, offering); + verify(agentmgr, times(1)).easySend(eq(42L), (Command)any()); + verify(implementednetwork, times(1)).setBroadcastUri(null); + } } diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java index 8e7245ebbdf..9c6f85e5983 100644 --- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java @@ -16,7 +16,7 @@ // under the License. package com.cloud.network.nicira; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; import org.junit.Test; @@ -25,14 +25,14 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class NatRuleTest { - + @Test public void testNatRuleEncoding() { Gson gson = new GsonBuilder() - .registerTypeAdapter(NatRule.class, new com.cloud.network.nicira.NiciraNvpApi.NatRuleAdapter()) - .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) - .create(); - + .registerTypeAdapter(NatRule.class, new com.cloud.network.nicira.NiciraNvpApi.NatRuleAdapter()) + .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) + .create(); + DestinationNatRule rn1 = new DestinationNatRule(); rn1.setToDestinationIpAddress("10.10.10.10"); rn1.setToDestinationPort(80); @@ -41,12 +41,12 @@ public class NatRuleTest { mr1.setEthertype("IPv4"); mr1.setProtocol(6); rn1.setMatch(mr1); - + String jsonString = gson.toJson(rn1); NatRule dnr = gson.fromJson(jsonString, NatRule.class); assertTrue(dnr instanceof DestinationNatRule); assertTrue(rn1.equals(dnr)); } - + } diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java index 42eb96e42d8..1467d4711dd 100644 --- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java @@ -16,8 +16,12 @@ // under the License. package com.cloud.network.nicira; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.io.IOException; import java.util.Collections; @@ -36,271 +40,271 @@ import org.junit.Before; import org.junit.Test; public class NiciraNvpApiTest { - NiciraNvpApi _api; - HttpClient _client = mock(HttpClient.class); - HttpMethod _method; - - @Before - public void setUp() { - HttpClientParams hmp = mock(HttpClientParams.class); - when (_client.getParams()).thenReturn(hmp); - _api = new NiciraNvpApi() { - @Override - protected HttpClient createHttpClient() { - return _client; - } - - @Override - protected HttpMethod createMethod(String type, String uri) { - return _method; - } - }; - _api.setAdminCredentials("admin", "adminpass"); - _api.setControllerAddress("localhost"); - } - - @Test (expected=NiciraNvpApiException.class) - public void testExecuteLoginWithoutHostname() throws NiciraNvpApiException { - _api.setControllerAddress(null); - _api.login(); - } + NiciraNvpApi _api; + HttpClient _client = mock(HttpClient.class); + HttpMethod _method; - @Test (expected=NiciraNvpApiException.class) - public void testExecuteLoginWithoutCredentials() throws NiciraNvpApiException { - _api.setAdminCredentials(null, null); - _api.login(); - } + @Before + public void setUp() { + HttpClientParams hmp = mock(HttpClientParams.class); + when (_client.getParams()).thenReturn(hmp); + _api = new NiciraNvpApi() { + @Override + protected HttpClient createHttpClient() { + return _client; + } - @Test (expected=NiciraNvpApiException.class) - public void testExecuteUpdateObjectWithoutHostname() throws NiciraNvpApiException { - _api.setControllerAddress(null); - _api.executeUpdateObject(new String(), "/", Collections. emptyMap()); - } + @Override + protected HttpMethod createMethod(String type, String uri) { + return _method; + } + }; + _api.setAdminCredentials("admin", "adminpass"); + _api.setControllerAddress("localhost"); + } - @Test (expected=NiciraNvpApiException.class) - public void testExecuteUpdateObjectWithoutCredentials() throws NiciraNvpApiException { - _api.setAdminCredentials(null, null); - _api.executeUpdateObject(new String(), "/", Collections. emptyMap()); - } + @Test (expected=NiciraNvpApiException.class) + public void testExecuteLoginWithoutHostname() throws NiciraNvpApiException { + _api.setControllerAddress(null); + _api.login(); + } - @Test (expected=NiciraNvpApiException.class) - public void testExecuteCreateObjectWithoutHostname() throws NiciraNvpApiException { - _api.setControllerAddress(null); - _api.executeCreateObject(new String(), String.class, "/", Collections. emptyMap()); - } + @Test (expected=NiciraNvpApiException.class) + public void testExecuteLoginWithoutCredentials() throws NiciraNvpApiException { + _api.setAdminCredentials(null, null); + _api.login(); + } - @Test (expected=NiciraNvpApiException.class) - public void testExecuteCreateObjectWithoutCredentials() throws NiciraNvpApiException { - _api.setAdminCredentials(null, null); - _api.executeCreateObject(new String(), String.class, "/", Collections. emptyMap()); - } + @Test (expected=NiciraNvpApiException.class) + public void testExecuteUpdateObjectWithoutHostname() throws NiciraNvpApiException { + _api.setControllerAddress(null); + _api.executeUpdateObject(new String(), "/", Collections. emptyMap()); + } - @Test (expected=NiciraNvpApiException.class) - public void testExecuteDeleteObjectWithoutHostname() throws NiciraNvpApiException { - _api.setControllerAddress(null); - _api.executeDeleteObject("/"); - } + @Test (expected=NiciraNvpApiException.class) + public void testExecuteUpdateObjectWithoutCredentials() throws NiciraNvpApiException { + _api.setAdminCredentials(null, null); + _api.executeUpdateObject(new String(), "/", Collections. emptyMap()); + } - @Test (expected=NiciraNvpApiException.class) - public void testExecuteDeleteObjectWithoutCredentials() throws NiciraNvpApiException { - _api.setAdminCredentials(null, null); - _api.executeDeleteObject("/"); - } + @Test (expected=NiciraNvpApiException.class) + public void testExecuteCreateObjectWithoutHostname() throws NiciraNvpApiException { + _api.setControllerAddress(null); + _api.executeCreateObject(new String(), String.class, "/", Collections. emptyMap()); + } - @Test (expected=NiciraNvpApiException.class) - public void testExecuteRetrieveObjectWithoutHostname() throws NiciraNvpApiException { - _api.setControllerAddress(null); - _api.executeRetrieveObject(String.class, "/", Collections. emptyMap()); - } + @Test (expected=NiciraNvpApiException.class) + public void testExecuteCreateObjectWithoutCredentials() throws NiciraNvpApiException { + _api.setAdminCredentials(null, null); + _api.executeCreateObject(new String(), String.class, "/", Collections. emptyMap()); + } - @Test (expected=NiciraNvpApiException.class) - public void testExecuteRetrieveObjectWithoutCredentials() throws NiciraNvpApiException { - _api.setAdminCredentials(null, null); - _api.executeDeleteObject("/"); - } + @Test (expected=NiciraNvpApiException.class) + public void testExecuteDeleteObjectWithoutHostname() throws NiciraNvpApiException { + _api.setControllerAddress(null); + _api.executeDeleteObject("/"); + } - @Test - public void executeMethodTest() throws NiciraNvpApiException { - GetMethod gm = mock(GetMethod.class); - - when(gm.getStatusCode()).thenReturn(HttpStatus.SC_OK); - _api.executeMethod(gm); - verify(gm, times(1)).getStatusCode(); - } + @Test (expected=NiciraNvpApiException.class) + public void testExecuteDeleteObjectWithoutCredentials() throws NiciraNvpApiException { + _api.setAdminCredentials(null, null); + _api.executeDeleteObject("/"); + } - /* Bit of a roundabout way to ensure that login is called after an un authorized result - * It not possible to properly mock login() - */ - @Test (expected=NiciraNvpApiException.class) - public void executeMethodTestWithLogin() throws NiciraNvpApiException, HttpException, IOException { - GetMethod gm = mock(GetMethod.class); - when(_client.executeMethod((HttpMethod)any())).thenThrow(new HttpException()); - when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED); - _api.executeMethod(gm); - verify(gm, times(1)).getStatusCode(); - } - - @Test - public void testExecuteCreateObject() throws NiciraNvpApiException, IOException { - LogicalSwitch ls = new LogicalSwitch(); - _method = mock(PostMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED); - when(_method.getResponseBodyAsString()).thenReturn("{ \"uuid\" : \"aaaa\" }"); - ls = _api.executeCreateObject(ls, LogicalSwitch.class, "/", Collections. emptyMap()); - assertTrue("aaaa".equals(ls.getUuid())); - verify(_method, times(1)).releaseConnection(); - - } + @Test (expected=NiciraNvpApiException.class) + public void testExecuteRetrieveObjectWithoutHostname() throws NiciraNvpApiException { + _api.setControllerAddress(null); + _api.executeRetrieveObject(String.class, "/", Collections. emptyMap()); + } - @Test (expected=NiciraNvpApiException.class) - public void testExecuteCreateObjectFailure() throws NiciraNvpApiException, IOException { - LogicalSwitch ls = new LogicalSwitch(); - _method = mock(PostMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); - Header header = mock(Header.class); - when(header.getValue()).thenReturn("text/html"); - when(_method.getResponseHeader("Content-Type")).thenReturn(header); - when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); - when(_method.isRequestSent()).thenReturn(true); - try { - ls = _api.executeCreateObject(ls, LogicalSwitch.class, "/", Collections. emptyMap()); - } finally { - verify(_method, times(1)).releaseConnection(); - } - } + @Test (expected=NiciraNvpApiException.class) + public void testExecuteRetrieveObjectWithoutCredentials() throws NiciraNvpApiException { + _api.setAdminCredentials(null, null); + _api.executeDeleteObject("/"); + } - @Test (expected=NiciraNvpApiException.class) - public void testExecuteCreateObjectException() throws NiciraNvpApiException, IOException { - LogicalSwitch ls = new LogicalSwitch(); - when(_client.executeMethod((HttpMethod) any())).thenThrow(new HttpException()); - _method = mock(PostMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); - Header header = mock(Header.class); - when(header.getValue()).thenReturn("text/html"); - when(_method.getResponseHeader("Content-Type")).thenReturn(header); - when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); - try { - ls = _api.executeCreateObject(ls, LogicalSwitch.class, "/", Collections. emptyMap()); - } finally { - verify(_method, times(1)).releaseConnection(); - } - } + @Test + public void executeMethodTest() throws NiciraNvpApiException { + GetMethod gm = mock(GetMethod.class); - @Test - public void testExecuteUpdateObject() throws NiciraNvpApiException, IOException { - LogicalSwitch ls = new LogicalSwitch(); - _method = mock(PutMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - _api.executeUpdateObject(ls, "/", Collections. emptyMap()); - verify(_method, times(1)).releaseConnection(); - verify(_client, times(1)).executeMethod(_method); - } + when(gm.getStatusCode()).thenReturn(HttpStatus.SC_OK); + _api.executeMethod(gm); + verify(gm, times(1)).getStatusCode(); + } - @Test (expected=NiciraNvpApiException.class) - public void testExecuteUpdateObjectFailure() throws NiciraNvpApiException, IOException { - LogicalSwitch ls = new LogicalSwitch(); - _method = mock(PutMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); - Header header = mock(Header.class); - when(header.getValue()).thenReturn("text/html"); - when(_method.getResponseHeader("Content-Type")).thenReturn(header); - when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); - when(_method.isRequestSent()).thenReturn(true); - try { - _api.executeUpdateObject(ls, "/", Collections. emptyMap()); - } finally { - verify(_method, times(1)).releaseConnection(); - } - } + /* Bit of a roundabout way to ensure that login is called after an un authorized result + * It not possible to properly mock login() + */ + @Test (expected=NiciraNvpApiException.class) + public void executeMethodTestWithLogin() throws NiciraNvpApiException, HttpException, IOException { + GetMethod gm = mock(GetMethod.class); + when(_client.executeMethod((HttpMethod)any())).thenThrow(new HttpException()); + when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED); + _api.executeMethod(gm); + verify(gm, times(1)).getStatusCode(); + } - @Test (expected=NiciraNvpApiException.class) - public void testExecuteUpdateObjectException() throws NiciraNvpApiException, IOException { - LogicalSwitch ls = new LogicalSwitch(); - _method = mock(PutMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - when(_client.executeMethod((HttpMethod) any())).thenThrow(new IOException()); - try { - _api.executeUpdateObject(ls, "/", Collections. emptyMap()); - } finally { - verify(_method, times(1)).releaseConnection(); - } - } + @Test + public void testExecuteCreateObject() throws NiciraNvpApiException, IOException { + LogicalSwitch ls = new LogicalSwitch(); + _method = mock(PostMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED); + when(_method.getResponseBodyAsString()).thenReturn("{ \"uuid\" : \"aaaa\" }"); + ls = _api.executeCreateObject(ls, LogicalSwitch.class, "/", Collections. emptyMap()); + assertTrue("aaaa".equals(ls.getUuid())); + verify(_method, times(1)).releaseConnection(); - @Test - public void testExecuteDeleteObject() throws NiciraNvpApiException, IOException { - _method = mock(DeleteMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); - _api.executeDeleteObject("/"); - verify(_method, times(1)).releaseConnection(); - verify(_client, times(1)).executeMethod(_method); - } + } - @Test (expected=NiciraNvpApiException.class) - public void testExecuteDeleteObjectFailure() throws NiciraNvpApiException, IOException { - _method = mock(DeleteMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); - Header header = mock(Header.class); - when(header.getValue()).thenReturn("text/html"); - when(_method.getResponseHeader("Content-Type")).thenReturn(header); - when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); - when(_method.isRequestSent()).thenReturn(true); - try { - _api.executeDeleteObject("/"); - } finally { - verify(_method, times(1)).releaseConnection(); - } - } + @Test (expected=NiciraNvpApiException.class) + public void testExecuteCreateObjectFailure() throws NiciraNvpApiException, IOException { + LogicalSwitch ls = new LogicalSwitch(); + _method = mock(PostMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); + Header header = mock(Header.class); + when(header.getValue()).thenReturn("text/html"); + when(_method.getResponseHeader("Content-Type")).thenReturn(header); + when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); + when(_method.isRequestSent()).thenReturn(true); + try { + ls = _api.executeCreateObject(ls, LogicalSwitch.class, "/", Collections. emptyMap()); + } finally { + verify(_method, times(1)).releaseConnection(); + } + } - @Test (expected=NiciraNvpApiException.class) - public void testExecuteDeleteObjectException() throws NiciraNvpApiException, IOException { - _method = mock(DeleteMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); - when(_client.executeMethod((HttpMethod) any())).thenThrow(new HttpException()); - try { - _api.executeDeleteObject("/"); - } finally { - verify(_method, times(1)).releaseConnection(); - } - } + @Test (expected=NiciraNvpApiException.class) + public void testExecuteCreateObjectException() throws NiciraNvpApiException, IOException { + LogicalSwitch ls = new LogicalSwitch(); + when(_client.executeMethod((HttpMethod) any())).thenThrow(new HttpException()); + _method = mock(PostMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); + Header header = mock(Header.class); + when(header.getValue()).thenReturn("text/html"); + when(_method.getResponseHeader("Content-Type")).thenReturn(header); + when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); + try { + ls = _api.executeCreateObject(ls, LogicalSwitch.class, "/", Collections. emptyMap()); + } finally { + verify(_method, times(1)).releaseConnection(); + } + } - @Test - public void testExecuteRetrieveObject() throws NiciraNvpApiException, IOException { - _method = mock(GetMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - when(_method.getResponseBodyAsString()).thenReturn("{ \"uuid\" : \"aaaa\" }"); - _api.executeRetrieveObject(LogicalSwitch.class, "/", Collections. emptyMap()); - verify(_method, times(1)).releaseConnection(); - verify(_client, times(1)).executeMethod(_method); - } + @Test + public void testExecuteUpdateObject() throws NiciraNvpApiException, IOException { + LogicalSwitch ls = new LogicalSwitch(); + _method = mock(PutMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + _api.executeUpdateObject(ls, "/", Collections. emptyMap()); + verify(_method, times(1)).releaseConnection(); + verify(_client, times(1)).executeMethod(_method); + } - @Test (expected=NiciraNvpApiException.class) - public void testExecuteRetrieveObjectFailure() throws NiciraNvpApiException, IOException { - _method = mock(GetMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); - when(_method.getResponseBodyAsString()).thenReturn("{ \"uuid\" : \"aaaa\" }"); - Header header = mock(Header.class); - when(header.getValue()).thenReturn("text/html"); - when(_method.getResponseHeader("Content-Type")).thenReturn(header); - when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); - when(_method.isRequestSent()).thenReturn(true); - try { - _api.executeRetrieveObject(LogicalSwitch.class, "/", Collections. emptyMap()); - } finally { - verify(_method, times(1)).releaseConnection(); - } - } + @Test (expected=NiciraNvpApiException.class) + public void testExecuteUpdateObjectFailure() throws NiciraNvpApiException, IOException { + LogicalSwitch ls = new LogicalSwitch(); + _method = mock(PutMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); + Header header = mock(Header.class); + when(header.getValue()).thenReturn("text/html"); + when(_method.getResponseHeader("Content-Type")).thenReturn(header); + when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); + when(_method.isRequestSent()).thenReturn(true); + try { + _api.executeUpdateObject(ls, "/", Collections. emptyMap()); + } finally { + verify(_method, times(1)).releaseConnection(); + } + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteUpdateObjectException() throws NiciraNvpApiException, IOException { + LogicalSwitch ls = new LogicalSwitch(); + _method = mock(PutMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + when(_client.executeMethod((HttpMethod) any())).thenThrow(new IOException()); + try { + _api.executeUpdateObject(ls, "/", Collections. emptyMap()); + } finally { + verify(_method, times(1)).releaseConnection(); + } + } + + @Test + public void testExecuteDeleteObject() throws NiciraNvpApiException, IOException { + _method = mock(DeleteMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); + _api.executeDeleteObject("/"); + verify(_method, times(1)).releaseConnection(); + verify(_client, times(1)).executeMethod(_method); + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteDeleteObjectFailure() throws NiciraNvpApiException, IOException { + _method = mock(DeleteMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); + Header header = mock(Header.class); + when(header.getValue()).thenReturn("text/html"); + when(_method.getResponseHeader("Content-Type")).thenReturn(header); + when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); + when(_method.isRequestSent()).thenReturn(true); + try { + _api.executeDeleteObject("/"); + } finally { + verify(_method, times(1)).releaseConnection(); + } + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteDeleteObjectException() throws NiciraNvpApiException, IOException { + _method = mock(DeleteMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); + when(_client.executeMethod((HttpMethod) any())).thenThrow(new HttpException()); + try { + _api.executeDeleteObject("/"); + } finally { + verify(_method, times(1)).releaseConnection(); + } + } + + @Test + public void testExecuteRetrieveObject() throws NiciraNvpApiException, IOException { + _method = mock(GetMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + when(_method.getResponseBodyAsString()).thenReturn("{ \"uuid\" : \"aaaa\" }"); + _api.executeRetrieveObject(LogicalSwitch.class, "/", Collections. emptyMap()); + verify(_method, times(1)).releaseConnection(); + verify(_client, times(1)).executeMethod(_method); + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteRetrieveObjectFailure() throws NiciraNvpApiException, IOException { + _method = mock(GetMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); + when(_method.getResponseBodyAsString()).thenReturn("{ \"uuid\" : \"aaaa\" }"); + Header header = mock(Header.class); + when(header.getValue()).thenReturn("text/html"); + when(_method.getResponseHeader("Content-Type")).thenReturn(header); + when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); + when(_method.isRequestSent()).thenReturn(true); + try { + _api.executeRetrieveObject(LogicalSwitch.class, "/", Collections. emptyMap()); + } finally { + verify(_method, times(1)).releaseConnection(); + } + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteRetrieveObjectException() throws NiciraNvpApiException, IOException { + _method = mock(GetMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + when(_method.getResponseBodyAsString()).thenReturn("{ \"uuid\" : \"aaaa\" }"); + when(_client.executeMethod((HttpMethod) any())).thenThrow(new HttpException()); + try { + _api.executeRetrieveObject(LogicalSwitch.class, "/", Collections. emptyMap()); + } finally { + verify(_method, times(1)).releaseConnection(); + } + } - @Test (expected=NiciraNvpApiException.class) - public void testExecuteRetrieveObjectException() throws NiciraNvpApiException, IOException { - _method = mock(GetMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - when(_method.getResponseBodyAsString()).thenReturn("{ \"uuid\" : \"aaaa\" }"); - when(_client.executeMethod((HttpMethod) any())).thenThrow(new HttpException()); - try { - _api.executeRetrieveObject(LogicalSwitch.class, "/", Collections. emptyMap()); - } finally { - verify(_method, times(1)).releaseConnection(); - } - } - } diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java index 8b5af3cc12d..78465e42041 100644 --- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java @@ -16,8 +16,18 @@ // under the License. package com.cloud.network.resource; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.argThat; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; @@ -74,768 +84,769 @@ import com.cloud.network.nicira.NiciraNvpList; import com.cloud.network.nicira.SourceNatRule; public class NiciraNvpResourceTest { - NiciraNvpApi _nvpApi = mock(NiciraNvpApi.class); - NiciraNvpResource _resource; - Map _parameters; - - @Before - public void setUp() throws ConfigurationException { - _resource = new NiciraNvpResource() { - protected NiciraNvpApi createNiciraNvpApi() { - return _nvpApi; - } - }; + NiciraNvpApi _nvpApi = mock(NiciraNvpApi.class); + NiciraNvpResource _resource; + Map _parameters; - _parameters = new HashMap(); - _parameters.put("name","nvptestdevice"); - _parameters.put("ip","127.0.0.1"); - _parameters.put("adminuser","adminuser"); - _parameters.put("guid", "aaaaa-bbbbb-ccccc"); - _parameters.put("zoneId", "blublub"); - _parameters.put("adminpass","adminpass"); - } - - @Test (expected=ConfigurationException.class) - public void resourceConfigureFailure() throws ConfigurationException { - _resource.configure("NiciraNvpResource", Collections.emptyMap()); - } - - @Test - public void resourceConfigure() throws ConfigurationException { - _resource.configure("NiciraNvpResource", _parameters); - - verify(_nvpApi).setAdminCredentials("adminuser", "adminpass"); - verify(_nvpApi).setControllerAddress("127.0.0.1"); - - assertTrue("nvptestdevice".equals(_resource.getName())); - - /* Pretty lame test, but here to assure this plugin fails - * if the type name ever changes from L2Networking - */ - assertTrue(_resource.getType() == Host.Type.L2Networking); - } - - @Test - public void testInitialization() throws ConfigurationException { - _resource.configure("NiciraNvpResource", _parameters); - - StartupCommand[] sc = _resource.initialize(); - assertTrue(sc.length ==1); - assertTrue("aaaaa-bbbbb-ccccc".equals(sc[0].getGuid())); - assertTrue("nvptestdevice".equals(sc[0].getName())); - assertTrue("blublub".equals(sc[0].getDataCenter())); - } - - @Test - public void testPingCommandStatusOk() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - ControlClusterStatus ccs = mock(ControlClusterStatus.class); - when(ccs.getClusterStatus()).thenReturn("stable"); - when(_nvpApi.getControlClusterStatus()).thenReturn(ccs); - - PingCommand ping = _resource.getCurrentStatus(42); - assertTrue(ping != null); - assertTrue(ping.getHostId() == 42); - assertTrue(ping.getHostType() == Host.Type.L2Networking); - } + @Before + public void setUp() throws ConfigurationException { + _resource = new NiciraNvpResource() { + @Override + protected NiciraNvpApi createNiciraNvpApi() { + return _nvpApi; + } + }; - @Test - public void testPingCommandStatusFail() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - ControlClusterStatus ccs = mock(ControlClusterStatus.class); - when(ccs.getClusterStatus()).thenReturn("unstable"); - when(_nvpApi.getControlClusterStatus()).thenReturn(ccs); - - PingCommand ping = _resource.getCurrentStatus(42); - assertTrue(ping == null); - } + _parameters = new HashMap(); + _parameters.put("name","nvptestdevice"); + _parameters.put("ip","127.0.0.1"); + _parameters.put("adminuser","adminuser"); + _parameters.put("guid", "aaaaa-bbbbb-ccccc"); + _parameters.put("zoneId", "blublub"); + _parameters.put("adminpass","adminpass"); + } - @Test - public void testPingCommandStatusApiException() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - ControlClusterStatus ccs = mock(ControlClusterStatus.class); - when(ccs.getClusterStatus()).thenReturn("unstable"); - when(_nvpApi.getControlClusterStatus()).thenThrow(new NiciraNvpApiException()); - - PingCommand ping = _resource.getCurrentStatus(42); - assertTrue(ping == null); - } - - @Test - public void testRetries() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - LogicalSwitch ls = mock(LogicalSwitch.class); - when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); - when(_nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenThrow(new NiciraNvpApiException()).thenThrow(new NiciraNvpApiException()).thenReturn(ls); - - CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)_parameters.get("guid"), "stt", "loigicalswitch","owner"); - CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) _resource.executeRequest(clsc); - assertTrue(clsa.getResult()); - } - - @Test - public void testCreateLogicalSwitch() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - LogicalSwitch ls = mock(LogicalSwitch.class); - when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); - when(_nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenReturn(ls); - - CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)_parameters.get("guid"), "stt", "loigicalswitch","owner"); - CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) _resource.executeRequest(clsc); - assertTrue(clsa.getResult()); - assertTrue("cccc".equals(clsa.getLogicalSwitchUuid())); - } + @Test (expected=ConfigurationException.class) + public void resourceConfigureFailure() throws ConfigurationException { + _resource.configure("NiciraNvpResource", Collections.emptyMap()); + } - @Test - public void testCreateLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - LogicalSwitch ls = mock(LogicalSwitch.class); - when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); - when(_nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenThrow(new NiciraNvpApiException()); - - CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)_parameters.get("guid"), "stt", "loigicalswitch","owner"); - CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) _resource.executeRequest(clsc); - assertFalse(clsa.getResult()); - } + @Test + public void resourceConfigure() throws ConfigurationException { + _resource.configure("NiciraNvpResource", _parameters); - @Test - public void testDeleteLogicalSwitch() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc"); - DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer) _resource.executeRequest(dlsc); - assertTrue(dlsa.getResult()); - } + verify(_nvpApi).setAdminCredentials("adminuser", "adminpass"); + verify(_nvpApi).setControllerAddress("127.0.0.1"); - @Test - public void testDeleteLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - doThrow(new NiciraNvpApiException()).when(_nvpApi).deleteLogicalSwitch((String)any()); - - DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc"); - DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer) _resource.executeRequest(dlsc); - assertFalse(dlsa.getResult()); - } + assertTrue("nvptestdevice".equals(_resource.getName())); - @Test - public void testCreateLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); - when(lsp.getUuid()).thenReturn("eeee"); - when(_nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenReturn(lsp); - - CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); - CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) _resource.executeRequest(clspc); - assertTrue(clspa.getResult()); - assertTrue("eeee".equals(clspa.getLogicalSwitchPortUuid())); - - } + /* Pretty lame test, but here to assure this plugin fails + * if the type name ever changes from L2Networking + */ + assertTrue(_resource.getType() == Host.Type.L2Networking); + } - @Test - public void testCreateLogicalSwitchPortApiExceptionInCreate() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); - when(lsp.getUuid()).thenReturn("eeee"); - when(_nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenThrow(new NiciraNvpApiException()); - - CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); - CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) _resource.executeRequest(clspc); - assertFalse(clspa.getResult()); - } + @Test + public void testInitialization() throws ConfigurationException { + _resource.configure("NiciraNvpResource", _parameters); - @Test - public void testCreateLogicalSwitchPortApiExceptionInModify() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); - when(lsp.getUuid()).thenReturn("eeee"); - when(_nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenReturn(lsp); - doThrow(new NiciraNvpApiException()).when(_nvpApi).modifyLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any()); - - - CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); - CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) _resource.executeRequest(clspc); - assertFalse(clspa.getResult()); - verify(_nvpApi, atLeastOnce()).deleteLogicalSwitchPort((String) any(), (String) any()); - } + StartupCommand[] sc = _resource.initialize(); + assertTrue(sc.length ==1); + assertTrue("aaaaa-bbbbb-ccccc".equals(sc[0].getGuid())); + assertTrue("nvptestdevice".equals(sc[0].getName())); + assertTrue("blublub".equals(sc[0].getDataCenter())); + } - @Test - public void testDeleteLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - doThrow(new NiciraNvpApiException()).when(_nvpApi).deleteLogicalSwitchPort((String) any(), (String) any()); - DeleteLogicalSwitchPortAnswer dlspa = (DeleteLogicalSwitchPortAnswer) _resource.executeRequest(new DeleteLogicalSwitchPortCommand("aaaa","bbbb")); - assertFalse(dlspa.getResult()); - } - - @Test - public void testUpdateLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - doThrow(new NiciraNvpApiException()).when(_nvpApi).modifyLogicalSwitchPortAttachment((String) any(), (String) any(), (Attachment) any()); - UpdateLogicalSwitchPortAnswer dlspa = (UpdateLogicalSwitchPortAnswer) _resource.executeRequest( - new UpdateLogicalSwitchPortCommand("aaaa","bbbb","cccc","owner","nicname")); - assertFalse(dlspa.getResult()); - } - - @Test - public void testFindLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - @SuppressWarnings("unchecked") - NiciraNvpList lspl = (NiciraNvpList)mock(NiciraNvpList.class); - when(lspl.getResultCount()).thenReturn(1); - when(_nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl); - - FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) _resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); - assertTrue(flspa.getResult()); - } + @Test + public void testPingCommandStatusOk() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); - @Test - public void testFindLogicalSwitchPortNotFound() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - @SuppressWarnings("unchecked") - NiciraNvpList lspl = (NiciraNvpList)mock(NiciraNvpList.class); - when(lspl.getResultCount()).thenReturn(0); - when(_nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl); - - FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) _resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); - assertFalse(flspa.getResult()); - } + ControlClusterStatus ccs = mock(ControlClusterStatus.class); + when(ccs.getClusterStatus()).thenReturn("stable"); + when(_nvpApi.getControlClusterStatus()).thenReturn(ccs); - @Test - public void testFindLogicalSwitchPortApiException() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - when(_nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenThrow(new NiciraNvpApiException()); - - FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) _resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); - assertFalse(flspa.getResult()); - } - - @Test - public void testCreateLogicalRouter() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - LogicalRouterConfig lrc = mock(LogicalRouterConfig.class); - LogicalRouterPort lrp = mock(LogicalRouterPort.class); - LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); - when(lrc.getUuid()).thenReturn("ccccc"); - when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee"); - when(lsp.getUuid()).thenReturn("fffff"); - when(_nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenReturn(lrc); - when(_nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp); - when(_nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp); - CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); - CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) _resource.executeRequest(clrc); - - assertTrue(clra.getResult()); - assertTrue("ccccc".equals(clra.getLogicalRouterUuid())); - verify(_nvpApi, atLeast(1)).createLogicalRouterNatRule((String) any(), (NatRule) any()); - } + PingCommand ping = _resource.getCurrentStatus(42); + assertTrue(ping != null); + assertTrue(ping.getHostId() == 42); + assertTrue(ping.getHostType() == Host.Type.L2Networking); + } - @Test - public void testCreateLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - when(_nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenThrow(new NiciraNvpApiException()); - CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); - CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) _resource.executeRequest(clrc); - - assertFalse(clra.getResult()); - } + @Test + public void testPingCommandStatusFail() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); - @Test - public void testCreateLogicalRouterApiExceptionRollbackRouter() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - LogicalRouterConfig lrc = mock(LogicalRouterConfig.class); - when(lrc.getUuid()).thenReturn("ccccc"); - when(_nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenReturn(lrc); - when(_nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenThrow(new NiciraNvpApiException()); - CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); - CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) _resource.executeRequest(clrc); - - assertFalse(clra.getResult()); - verify(_nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc")); - } + ControlClusterStatus ccs = mock(ControlClusterStatus.class); + when(ccs.getClusterStatus()).thenReturn("unstable"); + when(_nvpApi.getControlClusterStatus()).thenReturn(ccs); - @Test - public void testCreateLogicalRouterApiExceptionRollbackRouterAndSwitchPort() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - LogicalRouterConfig lrc = mock(LogicalRouterConfig.class); - LogicalRouterPort lrp = mock(LogicalRouterPort.class); - LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); - when(lrc.getUuid()).thenReturn("ccccc"); - when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee"); - when(lsp.getUuid()).thenReturn("fffff"); - when(_nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenReturn(lrc); - when(_nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp); - when(_nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp); - when(_nvpApi.createLogicalRouterNatRule((String) any(), (NatRule)any())).thenThrow(new NiciraNvpApiException()); - CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); - CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) _resource.executeRequest(clrc); - - assertFalse(clra.getResult()); - verify(_nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc")); - verify(_nvpApi, atLeast(1)).deleteLogicalSwitchPort(eq("bbbbb"), eq("fffff")); - } - - @Test - public void testDeleteLogicalRouterApiException() throws ConfigurationException,NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - doThrow(new NiciraNvpApiException()).when(_nvpApi).deleteLogicalRouter(eq("aaaaa")); - DeleteLogicalRouterAnswer dlspa = (DeleteLogicalRouterAnswer) _resource.executeRequest(new DeleteLogicalRouterCommand("aaaaa")); - assertFalse(dlspa.getResult()); - } - - @Test - public void testConfigurePublicIpsOnLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - - ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class); - @SuppressWarnings("unchecked") - NiciraNvpList list = mock(NiciraNvpList.class); - - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb"); - doThrow(new NiciraNvpApiException()).when(_nvpApi).modifyLogicalRouterPort((String) any(), (LogicalRouterPort) any()); - when(_nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa","bbbbb")).thenReturn(list); - - ConfigurePublicIpsOnLogicalRouterAnswer answer = - (ConfigurePublicIpsOnLogicalRouterAnswer) _resource.executeRequest(cmd); - assertFalse(answer.getResult()); - - } - - @Test - public void testConfigureStaticNatRulesOnLogicalRouter() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 - */ - - // Mock the command - ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); - StaticNatRuleTO rule = new StaticNatRuleTO(1,"11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); - List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api find call - @SuppressWarnings("unchecked") - NiciraNvpList storedRules = mock(NiciraNvpList.class); - when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - // Mock the api create calls - NatRule[] rulepair = _resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); - rulepair[0].setUuid(UUID.randomUUID()); - rulepair[1].setUuid(UUID.randomUUID()); - when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); - - ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); - - assertTrue(a.getResult()); - verify(_nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { - @Override - public boolean matches(Object argument) { - NatRule rule = (NatRule) argument; - if (rule.getType().equals("DestinationNatRule") && - ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) { - return true; - } - if (rule.getType().equals("SourceNatRule") && - ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) { - return true; - } - return false; - } })); - } + PingCommand ping = _resource.getCurrentStatus(42); + assertTrue(ping == null); + } - @Test - public void testConfigureStaticNatRulesOnLogicalRouterExistingRules() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 - */ - - // Mock the command - ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); - StaticNatRuleTO rule = new StaticNatRuleTO(1,"11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); - List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api create calls - NatRule[] rulepair = _resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); - rulepair[0].setUuid(UUID.randomUUID()); - rulepair[1].setUuid(UUID.randomUUID()); - when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + @Test + public void testPingCommandStatusApiException() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); - // Mock the api find call - @SuppressWarnings("unchecked") - NiciraNvpList storedRules = mock(NiciraNvpList.class); - when(storedRules.getResultCount()).thenReturn(2); - when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); - when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); - - assertTrue(a.getResult()); - verify(_nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { - @Override - public boolean matches(Object argument) { - NatRule rule = (NatRule) argument; - if (rule.getType().equals("DestinationNatRule") && - ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) { - return true; - } - if (rule.getType().equals("SourceNatRule") && - ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) { - return true; - } - return false; - } })); - } + ControlClusterStatus ccs = mock(ControlClusterStatus.class); + when(ccs.getClusterStatus()).thenReturn("unstable"); + when(_nvpApi.getControlClusterStatus()).thenThrow(new NiciraNvpApiException()); - @Test - public void testConfigureStaticNatRulesOnLogicalRouterRemoveRules() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 - */ - - // Mock the command - ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); - StaticNatRuleTO rule = new StaticNatRuleTO(1,"11.11.11.11", null, null, "10.10.10.10", null, null, null, true, false); - List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api create calls - NatRule[] rulepair = _resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); - final UUID rule0Uuid = UUID.randomUUID(); - final UUID rule1Uuid = UUID.randomUUID(); - rulepair[0].setUuid(rule0Uuid); - rulepair[1].setUuid(rule1Uuid); - when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + PingCommand ping = _resource.getCurrentStatus(42); + assertTrue(ping == null); + } - // Mock the api find call - @SuppressWarnings("unchecked") - NiciraNvpList storedRules = mock(NiciraNvpList.class); - when(storedRules.getResultCount()).thenReturn(2); - when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); - when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); - - assertTrue(a.getResult()); - verify(_nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { - @Override - public boolean matches(Object argument) { - UUID uuid = (UUID) argument; - if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) { - return true; - } - return false; - } })); - } + @Test + public void testRetries() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); - @Test - public void testConfigureStaticNatRulesOnLogicalRouterRollback() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 - */ - - // Mock the command - ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); - StaticNatRuleTO rule = new StaticNatRuleTO(1,"11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); - List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api create calls - NatRule[] rulepair = _resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); - rulepair[0].setUuid(UUID.randomUUID()); - rulepair[1].setUuid(UUID.randomUUID()); - when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException()); + LogicalSwitch ls = mock(LogicalSwitch.class); + when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); + when(_nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenThrow(new NiciraNvpApiException()).thenThrow(new NiciraNvpApiException()).thenReturn(ls); - // Mock the api find call - @SuppressWarnings("unchecked") - NiciraNvpList storedRules = mock(NiciraNvpList.class); - when(storedRules.getResultCount()).thenReturn(0); - when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); - - assertFalse(a.getResult()); - verify(_nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid())); - } + CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)_parameters.get("guid"), "stt", "loigicalswitch","owner"); + CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) _resource.executeRequest(clsc); + assertTrue(clsa.getResult()); + } - @Test - public void testConfigurePortForwardingRulesOnLogicalRouter() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 - */ - - // Mock the command - ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); - PortForwardingRuleTO rule = new PortForwardingRuleTO(1,"11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false); - List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api find call - @SuppressWarnings("unchecked") - NiciraNvpList storedRules = mock(NiciraNvpList.class); - when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - // Mock the api create calls - NatRule[] rulepair = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80}, "tcp"); - rulepair[0].setUuid(UUID.randomUUID()); - rulepair[1].setUuid(UUID.randomUUID()); - when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); - - ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); - - assertTrue(a.getResult()); - verify(_nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { - @Override - public boolean matches(Object argument) { - NatRule rule = (NatRule) argument; - if (rule.getType().equals("DestinationNatRule") && - ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) { - return true; - } - if (rule.getType().equals("SourceNatRule") && - ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) { - return true; - } - return false; - } })); - } + @Test + public void testCreateLogicalSwitch() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); - @Test - public void testConfigurePortForwardingRulesOnLogicalRouterExistingRules() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 - */ - - // Mock the command - ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); - PortForwardingRuleTO rule = new PortForwardingRuleTO(1,"11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, true); - List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api create calls - NatRule[] rulepair = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80}, "tcp"); - rulepair[0].setUuid(UUID.randomUUID()); - rulepair[1].setUuid(UUID.randomUUID()); - when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + LogicalSwitch ls = mock(LogicalSwitch.class); + when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); + when(_nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenReturn(ls); - // Mock the api find call - @SuppressWarnings("unchecked") - NiciraNvpList storedRules = mock(NiciraNvpList.class); - when(storedRules.getResultCount()).thenReturn(2); - when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); - when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); - - assertTrue(a.getResult()); - verify(_nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { - @Override - public boolean matches(Object argument) { - NatRule rule = (NatRule) argument; - if (rule.getType().equals("DestinationNatRule") && - ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) { - return true; - } - if (rule.getType().equals("SourceNatRule") && - ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) { - return true; - } - return false; - } })); - } + CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)_parameters.get("guid"), "stt", "loigicalswitch","owner"); + CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) _resource.executeRequest(clsc); + assertTrue(clsa.getResult()); + assertTrue("cccc".equals(clsa.getLogicalSwitchUuid())); + } - @Test - public void testConfigurePortForwardingRulesOnLogicalRouterRemoveRules() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 - */ - - // Mock the command - ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); - PortForwardingRuleTO rule = new PortForwardingRuleTO(1,"11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", true, true); - List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api create calls - NatRule[] rulepair = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80}, "tcp"); + @Test + public void testCreateLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + LogicalSwitch ls = mock(LogicalSwitch.class); + when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); + when(_nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenThrow(new NiciraNvpApiException()); + + CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)_parameters.get("guid"), "stt", "loigicalswitch","owner"); + CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) _resource.executeRequest(clsc); + assertFalse(clsa.getResult()); + } + + @Test + public void testDeleteLogicalSwitch() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc"); + DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer) _resource.executeRequest(dlsc); + assertTrue(dlsa.getResult()); + } + + @Test + public void testDeleteLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + doThrow(new NiciraNvpApiException()).when(_nvpApi).deleteLogicalSwitch((String)any()); + + DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc"); + DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer) _resource.executeRequest(dlsc); + assertFalse(dlsa.getResult()); + } + + @Test + public void testCreateLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); + when(lsp.getUuid()).thenReturn("eeee"); + when(_nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenReturn(lsp); + + CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); + CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) _resource.executeRequest(clspc); + assertTrue(clspa.getResult()); + assertTrue("eeee".equals(clspa.getLogicalSwitchPortUuid())); + + } + + @Test + public void testCreateLogicalSwitchPortApiExceptionInCreate() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); + when(lsp.getUuid()).thenReturn("eeee"); + when(_nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenThrow(new NiciraNvpApiException()); + + CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); + CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) _resource.executeRequest(clspc); + assertFalse(clspa.getResult()); + } + + @Test + public void testCreateLogicalSwitchPortApiExceptionInModify() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); + when(lsp.getUuid()).thenReturn("eeee"); + when(_nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenReturn(lsp); + doThrow(new NiciraNvpApiException()).when(_nvpApi).modifyLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any()); + + + CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); + CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) _resource.executeRequest(clspc); + assertFalse(clspa.getResult()); + verify(_nvpApi, atLeastOnce()).deleteLogicalSwitchPort((String) any(), (String) any()); + } + + @Test + public void testDeleteLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + doThrow(new NiciraNvpApiException()).when(_nvpApi).deleteLogicalSwitchPort((String) any(), (String) any()); + DeleteLogicalSwitchPortAnswer dlspa = (DeleteLogicalSwitchPortAnswer) _resource.executeRequest(new DeleteLogicalSwitchPortCommand("aaaa","bbbb")); + assertFalse(dlspa.getResult()); + } + + @Test + public void testUpdateLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + doThrow(new NiciraNvpApiException()).when(_nvpApi).modifyLogicalSwitchPortAttachment((String) any(), (String) any(), (Attachment) any()); + UpdateLogicalSwitchPortAnswer dlspa = (UpdateLogicalSwitchPortAnswer) _resource.executeRequest( + new UpdateLogicalSwitchPortCommand("aaaa","bbbb","cccc","owner","nicname")); + assertFalse(dlspa.getResult()); + } + + @Test + public void testFindLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + @SuppressWarnings("unchecked") + NiciraNvpList lspl = mock(NiciraNvpList.class); + when(lspl.getResultCount()).thenReturn(1); + when(_nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl); + + FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) _resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); + assertTrue(flspa.getResult()); + } + + @Test + public void testFindLogicalSwitchPortNotFound() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + @SuppressWarnings("unchecked") + NiciraNvpList lspl = mock(NiciraNvpList.class); + when(lspl.getResultCount()).thenReturn(0); + when(_nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl); + + FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) _resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); + assertFalse(flspa.getResult()); + } + + @Test + public void testFindLogicalSwitchPortApiException() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + when(_nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenThrow(new NiciraNvpApiException()); + + FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) _resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); + assertFalse(flspa.getResult()); + } + + @Test + public void testCreateLogicalRouter() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + LogicalRouterConfig lrc = mock(LogicalRouterConfig.class); + LogicalRouterPort lrp = mock(LogicalRouterPort.class); + LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); + when(lrc.getUuid()).thenReturn("ccccc"); + when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee"); + when(lsp.getUuid()).thenReturn("fffff"); + when(_nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenReturn(lrc); + when(_nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp); + when(_nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp); + CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); + CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) _resource.executeRequest(clrc); + + assertTrue(clra.getResult()); + assertTrue("ccccc".equals(clra.getLogicalRouterUuid())); + verify(_nvpApi, atLeast(1)).createLogicalRouterNatRule((String) any(), (NatRule) any()); + } + + @Test + public void testCreateLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + when(_nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenThrow(new NiciraNvpApiException()); + CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); + CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) _resource.executeRequest(clrc); + + assertFalse(clra.getResult()); + } + + @Test + public void testCreateLogicalRouterApiExceptionRollbackRouter() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + LogicalRouterConfig lrc = mock(LogicalRouterConfig.class); + when(lrc.getUuid()).thenReturn("ccccc"); + when(_nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenReturn(lrc); + when(_nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenThrow(new NiciraNvpApiException()); + CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); + CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) _resource.executeRequest(clrc); + + assertFalse(clra.getResult()); + verify(_nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc")); + } + + @Test + public void testCreateLogicalRouterApiExceptionRollbackRouterAndSwitchPort() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + LogicalRouterConfig lrc = mock(LogicalRouterConfig.class); + LogicalRouterPort lrp = mock(LogicalRouterPort.class); + LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); + when(lrc.getUuid()).thenReturn("ccccc"); + when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee"); + when(lsp.getUuid()).thenReturn("fffff"); + when(_nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenReturn(lrc); + when(_nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp); + when(_nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp); + when(_nvpApi.createLogicalRouterNatRule((String) any(), (NatRule)any())).thenThrow(new NiciraNvpApiException()); + CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); + CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) _resource.executeRequest(clrc); + + assertFalse(clra.getResult()); + verify(_nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc")); + verify(_nvpApi, atLeast(1)).deleteLogicalSwitchPort(eq("bbbbb"), eq("fffff")); + } + + @Test + public void testDeleteLogicalRouterApiException() throws ConfigurationException,NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + doThrow(new NiciraNvpApiException()).when(_nvpApi).deleteLogicalRouter(eq("aaaaa")); + DeleteLogicalRouterAnswer dlspa = (DeleteLogicalRouterAnswer) _resource.executeRequest(new DeleteLogicalRouterCommand("aaaaa")); + assertFalse(dlspa.getResult()); + } + + @Test + public void testConfigurePublicIpsOnLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class); + @SuppressWarnings("unchecked") + NiciraNvpList list = mock(NiciraNvpList.class); + + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb"); + doThrow(new NiciraNvpApiException()).when(_nvpApi).modifyLogicalRouterPort((String) any(), (LogicalRouterPort) any()); + when(_nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa","bbbbb")).thenReturn(list); + + ConfigurePublicIpsOnLogicalRouterAnswer answer = + (ConfigurePublicIpsOnLogicalRouterAnswer) _resource.executeRequest(cmd); + assertFalse(answer.getResult()); + + } + + @Test + public void testConfigureStaticNatRulesOnLogicalRouter() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); + StaticNatRuleTO rule = new StaticNatRuleTO(1,"11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + // Mock the api create calls + NatRule[] rulepair = _resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); + rulepair[0].setUuid(UUID.randomUUID()); + rulepair[1].setUuid(UUID.randomUUID()); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + + ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + assertTrue(a.getResult()); + verify(_nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + NatRule rule = (NatRule) argument; + if (rule.getType().equals("DestinationNatRule") && + ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) { + return true; + } + if (rule.getType().equals("SourceNatRule") && + ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) { + return true; + } + return false; + } })); + } + + @Test + public void testConfigureStaticNatRulesOnLogicalRouterExistingRules() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); + StaticNatRuleTO rule = new StaticNatRuleTO(1,"11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api create calls + NatRule[] rulepair = _resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); + rulepair[0].setUuid(UUID.randomUUID()); + rulepair[1].setUuid(UUID.randomUUID()); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(storedRules.getResultCount()).thenReturn(2); + when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + assertTrue(a.getResult()); + verify(_nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + NatRule rule = (NatRule) argument; + if (rule.getType().equals("DestinationNatRule") && + ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) { + return true; + } + if (rule.getType().equals("SourceNatRule") && + ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) { + return true; + } + return false; + } })); + } + + @Test + public void testConfigureStaticNatRulesOnLogicalRouterRemoveRules() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); + StaticNatRuleTO rule = new StaticNatRuleTO(1,"11.11.11.11", null, null, "10.10.10.10", null, null, null, true, false); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api create calls + NatRule[] rulepair = _resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); final UUID rule0Uuid = UUID.randomUUID(); final UUID rule1Uuid = UUID.randomUUID(); rulepair[0].setUuid(rule0Uuid); rulepair[1].setUuid(rule1Uuid); - when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); - // Mock the api find call - @SuppressWarnings("unchecked") - NiciraNvpList storedRules = mock(NiciraNvpList.class); - when(storedRules.getResultCount()).thenReturn(2); - when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); - when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); - - assertTrue(a.getResult()); - verify(_nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { - @Override - public boolean matches(Object argument) { - UUID uuid = (UUID) argument; - if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) { - return true; - } - return false; - } })); - } + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(storedRules.getResultCount()).thenReturn(2); + when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - @Test - public void testConfigurePortForwardingRulesOnLogicalRouterRollback() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 - */ - - // Mock the command - ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); - PortForwardingRuleTO rule = new PortForwardingRuleTO(1,"11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false); - List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api create calls - NatRule[] rulepair = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80}, "tcp"); - rulepair[0].setUuid(UUID.randomUUID()); - rulepair[1].setUuid(UUID.randomUUID()); - when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException()); + ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); - // Mock the api find call - @SuppressWarnings("unchecked") - NiciraNvpList storedRules = mock(NiciraNvpList.class); - when(storedRules.getResultCount()).thenReturn(0); - when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); - - assertFalse(a.getResult()); - verify(_nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid())); - } + assertTrue(a.getResult()); + verify(_nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + UUID uuid = (UUID) argument; + if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) { + return true; + } + return false; + } })); + } - @Test - public void testConfigurePortForwardingRulesOnLogicalRouterPortRange() throws ConfigurationException, NiciraNvpApiException { - _resource.configure("NiciraNvpResource", _parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 - */ - - // Mock the command - ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); - PortForwardingRuleTO rule = new PortForwardingRuleTO(1,"11.11.11.11", 80, 85, "10.10.10.10", 80, 85, "tcp", false, false); - List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api find call - @SuppressWarnings("unchecked") - NiciraNvpList storedRules = mock(NiciraNvpList.class); - when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - // Mock the api create calls - NatRule[] rulepair = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 80, 85 }, "11.11.11.11", new int[] { 80, 85}, "tcp"); - rulepair[0].setUuid(UUID.randomUUID()); - rulepair[1].setUuid(UUID.randomUUID()); - when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); - - ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); - - // The expected result is false, Nicira does not support port ranges in DNAT - assertFalse(a.getResult()); + @Test + public void testConfigureStaticNatRulesOnLogicalRouterRollback() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ - } + // Mock the command + ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); + StaticNatRuleTO rule = new StaticNatRuleTO(1,"11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - @Test - public void testGenerateStaticNatRulePair() { - NatRule[] rules = _resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); - assertTrue("DestinationNatRule".equals(rules[0].getType())); - assertTrue("SourceNatRule".equals(rules[1].getType())); - - DestinationNatRule dnr = (DestinationNatRule) rules[0]; - assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10")); - assertTrue(dnr.getToDestinationPort() == null); - assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11")); - - SourceNatRule snr = (SourceNatRule) rules[1]; - assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11")); - assertTrue(snr.getToSourcePort() == null); - assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10")); - } + // Mock the api create calls + NatRule[] rulepair = _resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); + rulepair[0].setUuid(UUID.randomUUID()); + rulepair[1].setUuid(UUID.randomUUID()); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException()); - @Test - public void testGeneratePortForwardingRulePair() { - NatRule[] rules = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp" ); - assertTrue("DestinationNatRule".equals(rules[0].getType())); - assertTrue("SourceNatRule".equals(rules[1].getType())); - - DestinationNatRule dnr = (DestinationNatRule) rules[0]; - assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10")); - assertTrue(dnr.getToDestinationPort() == 8080); - assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11")); - assertTrue(dnr.getMatch().getDestinationPort() == 80 ); - assertTrue(dnr.getMatch().getEthertype().equals("IPv4") && dnr.getMatch().getProtocol() == 6); - - SourceNatRule snr = (SourceNatRule) rules[1]; - assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11")); - assertTrue(snr.getToSourcePort() == 80); - assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10")); - assertTrue(snr.getMatch().getSourcePort() == 8080); - assertTrue(snr.getMatch().getEthertype().equals("IPv4") && rules[1].getMatch().getProtocol() == 6); - } + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(storedRules.getResultCount()).thenReturn(0); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + assertFalse(a.getResult()); + verify(_nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid())); + } + + @Test + public void testConfigurePortForwardingRulesOnLogicalRouter() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); + PortForwardingRuleTO rule = new PortForwardingRuleTO(1,"11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + // Mock the api create calls + NatRule[] rulepair = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80}, "tcp"); + rulepair[0].setUuid(UUID.randomUUID()); + rulepair[1].setUuid(UUID.randomUUID()); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + + ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + assertTrue(a.getResult()); + verify(_nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + NatRule rule = (NatRule) argument; + if (rule.getType().equals("DestinationNatRule") && + ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) { + return true; + } + if (rule.getType().equals("SourceNatRule") && + ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) { + return true; + } + return false; + } })); + } + + @Test + public void testConfigurePortForwardingRulesOnLogicalRouterExistingRules() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); + PortForwardingRuleTO rule = new PortForwardingRuleTO(1,"11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, true); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api create calls + NatRule[] rulepair = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80}, "tcp"); + rulepair[0].setUuid(UUID.randomUUID()); + rulepair[1].setUuid(UUID.randomUUID()); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(storedRules.getResultCount()).thenReturn(2); + when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + assertTrue(a.getResult()); + verify(_nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + NatRule rule = (NatRule) argument; + if (rule.getType().equals("DestinationNatRule") && + ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) { + return true; + } + if (rule.getType().equals("SourceNatRule") && + ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) { + return true; + } + return false; + } })); + } + + @Test + public void testConfigurePortForwardingRulesOnLogicalRouterRemoveRules() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); + PortForwardingRuleTO rule = new PortForwardingRuleTO(1,"11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", true, true); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api create calls + NatRule[] rulepair = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80}, "tcp"); + final UUID rule0Uuid = UUID.randomUUID(); + final UUID rule1Uuid = UUID.randomUUID(); + rulepair[0].setUuid(rule0Uuid); + rulepair[1].setUuid(rule1Uuid); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(storedRules.getResultCount()).thenReturn(2); + when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + assertTrue(a.getResult()); + verify(_nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + UUID uuid = (UUID) argument; + if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) { + return true; + } + return false; + } })); + } + + @Test + public void testConfigurePortForwardingRulesOnLogicalRouterRollback() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); + PortForwardingRuleTO rule = new PortForwardingRuleTO(1,"11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api create calls + NatRule[] rulepair = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80}, "tcp"); + rulepair[0].setUuid(UUID.randomUUID()); + rulepair[1].setUuid(UUID.randomUUID()); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException()); + + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(storedRules.getResultCount()).thenReturn(0); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + assertFalse(a.getResult()); + verify(_nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid())); + } + + @Test + public void testConfigurePortForwardingRulesOnLogicalRouterPortRange() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); + PortForwardingRuleTO rule = new PortForwardingRuleTO(1,"11.11.11.11", 80, 85, "10.10.10.10", 80, 85, "tcp", false, false); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + // Mock the api create calls + NatRule[] rulepair = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 80, 85 }, "11.11.11.11", new int[] { 80, 85}, "tcp"); + rulepair[0].setUuid(UUID.randomUUID()); + rulepair[1].setUuid(UUID.randomUUID()); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + + ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + // The expected result is false, Nicira does not support port ranges in DNAT + assertFalse(a.getResult()); + + } + + @Test + public void testGenerateStaticNatRulePair() { + NatRule[] rules = _resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); + assertTrue("DestinationNatRule".equals(rules[0].getType())); + assertTrue("SourceNatRule".equals(rules[1].getType())); + + DestinationNatRule dnr = (DestinationNatRule) rules[0]; + assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10")); + assertTrue(dnr.getToDestinationPort() == null); + assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11")); + + SourceNatRule snr = (SourceNatRule) rules[1]; + assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11")); + assertTrue(snr.getToSourcePort() == null); + assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10")); + } + + @Test + public void testGeneratePortForwardingRulePair() { + NatRule[] rules = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp" ); + assertTrue("DestinationNatRule".equals(rules[0].getType())); + assertTrue("SourceNatRule".equals(rules[1].getType())); + + DestinationNatRule dnr = (DestinationNatRule) rules[0]; + assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10")); + assertTrue(dnr.getToDestinationPort() == 8080); + assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11")); + assertTrue(dnr.getMatch().getDestinationPort() == 80 ); + assertTrue(dnr.getMatch().getEthertype().equals("IPv4") && dnr.getMatch().getProtocol() == 6); + + SourceNatRule snr = (SourceNatRule) rules[1]; + assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11")); + assertTrue(snr.getToSourcePort() == 80); + assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10")); + assertTrue(snr.getMatch().getSourcePort() == 8080); + assertTrue(snr.getMatch().getEthertype().equals("IPv4") && rules[1].getMatch().getProtocol() == 6); + } } diff --git a/plugins/pom.xml b/plugins/pom.xml index adc850b079f..9e87b12f9e4 100755 --- a/plugins/pom.xml +++ b/plugins/pom.xml @@ -41,8 +41,10 @@ event-bus/rabbitmq hypervisors/baremetal hypervisors/ucs + hypervisors/hyperv network-elements/elastic-loadbalancer network-elements/ovs + network-elements/juniper-contrail network-elements/nicira-nvp network-elements/bigswitch-vns network-elements/midonet 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 eefa3527119..be7c77db55a 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 @@ -22,18 +22,17 @@ import java.util.UUID; import javax.inject.Inject; +import org.apache.log4j.Logger; + import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.cloudstack.storage.image.BaseImageStoreDriverImpl; import org.apache.cloudstack.storage.image.datastore.ImageStoreEntity; import org.apache.cloudstack.storage.image.store.ImageStoreImpl; -import org.apache.log4j.Logger; - -import org.apache.cloudstack.storage.image.BaseImageStoreDriverImpl; - import com.cloud.agent.api.Answer; import com.cloud.agent.api.storage.CreateEntityDownloadURLCommand; import com.cloud.agent.api.to.DataStoreTO; @@ -68,7 +67,14 @@ public class CloudStackImageStoreDriverImpl extends BaseImageStoreDriverImpl { String path = installPath; String uuid = UUID.randomUUID().toString() + "." + format.getFileExtension(); CreateEntityDownloadURLCommand cmd = new CreateEntityDownloadURLCommand(((ImageStoreEntity) store).getMountPoint(), path, uuid, dataObject.getTO()); - Answer ans = ep.sendMessage(cmd); + Answer ans = null; + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + ans = new Answer(cmd, false, errMsg); + } else { + ans = ep.sendMessage(cmd); + } if (ans == null || !ans.getResult()) { String errorString = "Unable to create a link for entity at " + installPath + " on ssvm," + ans.getDetails(); s_logger.error(errorString); diff --git a/plugins/storage/image/swift/src/org/apache/cloudstack/storage/datastore/driver/SwiftImageStoreDriverImpl.java b/plugins/storage/image/swift/src/org/apache/cloudstack/storage/datastore/driver/SwiftImageStoreDriverImpl.java index 4a95844cdad..f8c0f059f96 100644 --- a/plugins/storage/image/swift/src/org/apache/cloudstack/storage/datastore/driver/SwiftImageStoreDriverImpl.java +++ b/plugins/storage/image/swift/src/org/apache/cloudstack/storage/datastore/driver/SwiftImageStoreDriverImpl.java @@ -19,32 +19,34 @@ package org.apache.cloudstack.storage.datastore.driver; import java.util.Map; -import java.util.Timer; + import javax.inject.Inject; -import com.cloud.agent.api.storage.DownloadAnswer; -import com.cloud.agent.api.to.DataObjectType; -import com.cloud.storage.download.DownloadListener; -import com.cloud.storage.template.TemplateConstants; -import com.cloud.storage.upload.UploadListener; -import com.cloud.template.VirtualMachineTemplate; -import com.cloud.utils.component.ComponentContext; +import org.apache.log4j.Logger; + import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.engine.subsystem.api.storage.*; +import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; +import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; +import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; +import org.apache.cloudstack.engine.subsystem.api.storage.StorageCacheManager; import org.apache.cloudstack.framework.async.AsyncCallbackDispatcher; import org.apache.cloudstack.framework.async.AsyncCompletionCallback; import org.apache.cloudstack.storage.command.DownloadCommand; -import org.apache.cloudstack.storage.command.DownloadProgressCommand; import org.apache.cloudstack.storage.datastore.db.ImageStoreDetailsDao; import org.apache.cloudstack.storage.image.BaseImageStoreDriverImpl; import org.apache.cloudstack.storage.image.store.ImageStoreImpl; import org.apache.cloudstack.storage.to.TemplateObjectTO; -import org.apache.log4j.Logger; +import com.cloud.agent.api.storage.DownloadAnswer; +import com.cloud.agent.api.to.DataObjectType; import com.cloud.agent.api.to.DataStoreTO; import com.cloud.agent.api.to.SwiftTO; import com.cloud.exception.UnsupportedServiceException; import com.cloud.storage.Storage.ImageFormat; +import com.cloud.template.VirtualMachineTemplate; +import com.cloud.utils.exception.CloudRuntimeException; public class SwiftImageStoreDriverImpl extends BaseImageStoreDriverImpl { private static final Logger s_logger = Logger.getLogger(SwiftImageStoreDriverImpl.class); @@ -80,8 +82,9 @@ public class SwiftImageStoreDriverImpl extends BaseImageStoreDriverImpl { EndPoint ep = _epSelector.select(data); if (ep == null) { - s_logger.warn("There is no secondary storage VM for downloading template to image store " + dataStore.getName()); - return; + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + throw new CloudRuntimeException(errMsg); } CreateContext context = new CreateContext(callback, data); @@ -96,7 +99,6 @@ public class SwiftImageStoreDriverImpl extends BaseImageStoreDriverImpl { } ep.sendMessageAsync(dcmd, caller); - } } diff --git a/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackPrimaryDataStoreDriverImpl.java b/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackPrimaryDataStoreDriverImpl.java index 82dc34769b8..2db0a0879f1 100644 --- a/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackPrimaryDataStoreDriverImpl.java +++ b/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackPrimaryDataStoreDriverImpl.java @@ -22,6 +22,8 @@ import java.util.UUID; import javax.inject.Inject; +import org.apache.log4j.Logger; + import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService; import org.apache.cloudstack.engine.subsystem.api.storage.ChapInfo; import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; @@ -45,7 +47,6 @@ import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.storage.to.TemplateObjectTO; import org.apache.cloudstack.storage.volume.VolumeObject; -import org.apache.log4j.Logger; import com.cloud.agent.api.Answer; import com.cloud.agent.api.storage.ResizeVolumeAnswer; @@ -214,7 +215,14 @@ public class CloudStackPrimaryDataStoreDriverImpl implements PrimaryDataStoreDri CopyCommand cmd = new CopyCommand(srcData.getTO(), destData.getTO(), _primaryStorageDownloadWait, true); EndPoint ep = epSelector.select(srcData, destData); - Answer answer = ep.sendMessage(cmd); + Answer answer = null; + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(cmd, false, errMsg); + } else { + answer = ep.sendMessage(cmd); + } CopyCommandResult result = new CopyCommandResult("", answer); callback.complete(result); } @@ -245,7 +253,7 @@ public class CloudStackPrimaryDataStoreDriverImpl implements PrimaryDataStoreDri CreateObjectCommand cmd = new CreateObjectCommand(snapshotTO); - EndPoint ep = this.epSelector.select(snapshot); + EndPoint ep = epSelector.select(snapshot); Answer answer = null; if ( ep == null ){ String errMsg = "No remote endpoint to send DeleteCommand, check if host or ssvm is down?"; @@ -284,7 +292,7 @@ public class CloudStackPrimaryDataStoreDriverImpl implements PrimaryDataStoreDri resizeParameter.newSize, resizeParameter.shrinkOk, resizeParameter.instanceName); CreateCmdResult result = new CreateCmdResult(null, null); try { - ResizeVolumeAnswer answer = (ResizeVolumeAnswer) this.storageMgr.sendToPool(pool, resizeParameter.hosts, + ResizeVolumeAnswer answer = (ResizeVolumeAnswer) storageMgr.sendToPool(pool, resizeParameter.hosts, resizeCmd); if (answer != null && answer.getResult()) { long finalSize = answer.getNewSize(); diff --git a/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java b/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java index d916d454422..b304a008a09 100644 --- a/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java +++ b/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java @@ -186,6 +186,7 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements PrimaryDataStore Object localStorage = dsInfos.get("localStorage"); if (localStorage != null) { hostPath = hostPath.replaceFirst("/", ""); + hostPath = hostPath.replace("+"," "); } String userInfo = uri.getUserInfo(); int port = uri.getPort(); diff --git a/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/driver/SamplePrimaryDataStoreDriverImpl.java b/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/driver/SamplePrimaryDataStoreDriverImpl.java index 75e8823a1b5..8f4c7bbf202 100644 --- a/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/driver/SamplePrimaryDataStoreDriverImpl.java +++ b/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/driver/SamplePrimaryDataStoreDriverImpl.java @@ -18,6 +18,8 @@ package org.apache.cloudstack.storage.datastore.driver; import javax.inject.Inject; +import org.apache.log4j.Logger; + import org.apache.cloudstack.engine.subsystem.api.storage.ChapInfo; import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; @@ -34,12 +36,12 @@ import org.apache.cloudstack.framework.async.AsyncRpcContext; import org.apache.cloudstack.storage.command.CommandResult; import org.apache.cloudstack.storage.command.CreateObjectCommand; import org.apache.cloudstack.storage.datastore.DataObjectManager; -import org.apache.log4j.Logger; import com.cloud.agent.api.Answer; import com.cloud.agent.api.to.DataStoreTO; import com.cloud.agent.api.to.DataTO; import com.cloud.storage.dao.StoragePoolHostDao; +import com.cloud.utils.exception.CloudRuntimeException; public class SamplePrimaryDataStoreDriverImpl implements PrimaryDataStoreDriver { private static final Logger s_logger = Logger.getLogger(SamplePrimaryDataStoreDriverImpl.class); @@ -163,6 +165,11 @@ public class SamplePrimaryDataStoreDriverImpl implements PrimaryDataStoreDriver @Override public void createAsync(DataStore dataStore, DataObject vol, AsyncCompletionCallback callback) { EndPoint ep = selector.select(vol); + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + throw new CloudRuntimeException(errMsg); + } CreateObjectCommand createCmd = new CreateObjectCommand(null); CreateVolumeContext context = new CreateVolumeContext(callback, vol); diff --git a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java index 120a357b270..be43e1c6af6 100644 --- a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java +++ b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java @@ -317,10 +317,12 @@ public class SolidFirePrimaryDataStoreLifeCycle implements PrimaryDataStoreLifeC dataStoreHelper.attachZone(dataStore); List xenServerHosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByHypervisor(HypervisorType.XenServer, scope.getScopeId()); + List vmWareServerHosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByHypervisor(HypervisorType.VMware, scope.getScopeId()); List kvmHosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByHypervisor(HypervisorType.KVM, scope.getScopeId()); List hosts = new ArrayList(); hosts.addAll(xenServerHosts); + hosts.addAll(vmWareServerHosts); hosts.addAll(kvmHosts); for (HostVO host : hosts) { diff --git a/plugins/user-authenticators/ldap/pom.xml b/plugins/user-authenticators/ldap/pom.xml index 1f9dea06631..34121e4db31 100644 --- a/plugins/user-authenticators/ldap/pom.xml +++ b/plugins/user-authenticators/ldap/pom.xml @@ -90,6 +90,40 @@ + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.codehaus.gmaven + + + gmaven-plugin + + [1.3,) + + compile + testCompile + + + + + + + + + + + + @@ -104,7 +138,6 @@ cglib cglib-nodep - 2.2 - + 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 f872247f07e..063db0e5ae1 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 @@ -26,6 +26,7 @@ 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; @@ -55,6 +56,15 @@ public class LdapImportUsersCmd extends BaseListCmd { @Parameter(name = ApiConstants.ACCOUNT_DETAILS, type = CommandType.MAP, description = "details for account used to store specific parameters") private Map details; + @Parameter(name = ApiConstants.DOMAIN, type = CommandType.STRING, + 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 String domainName; + + @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.") + private String groupName; + @Inject private LdapManager _ldapManager; @@ -75,14 +85,15 @@ public class LdapImportUsersCmd extends BaseListCmd { List ldapResponses = null; final ListResponse response = new ListResponse(); try { - final List users = _ldapManager.getUsers(); + List users; + if(StringUtils.isNotBlank(groupName)) { + users = _ldapManager.getUsersInGroup(groupName); + } else { + users = _ldapManager.getUsers(); + } for (LdapUser user : users) { - Domain domain = _domainService.getDomainByName(user.getDomain(), Domain.ROOT_DOMAIN); - - if (domain == null) { - domain = _domainService.createDomain(user.getDomain(), Domain.ROOT_DOMAIN, user.getDomain(), UUID.randomUUID().toString()); - } - _accountService.createUserAccount(user.getUsername(), generatePassword(), user.getFirstname(), user.getLastname(), user.getEmail(), timezone, user.getUsername(), + Domain domain = getDomain(user); + _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()); } ldapResponses = createLdapUserResponse(users); @@ -95,6 +106,33 @@ public class LdapImportUsersCmd extends BaseListCmd { } } + private Domain getDomain(LdapUser user) { + String csDomainName = null; + if (StringUtils.isNotBlank(domainName)) { + csDomainName = domainName; + } else { + if (StringUtils.isNotBlank(groupName)) { + csDomainName = groupName; + } else if (StringUtils.isNotBlank(user.getDomain())) { + csDomainName = user.getDomain(); + } + //removing all the special characters and trimming it length 190 to make the domain valid. + csDomainName = StringUtils.substring(csDomainName.replaceAll("\\W",""),0,190); + } + Domain domain; + if (StringUtils.isNotBlank(csDomainName)) { + domain = _domainService.getDomainByName(csDomainName, Domain.ROOT_DOMAIN); + + if (domain == null) { + domain = _domainService.createDomain(csDomainName, Domain.ROOT_DOMAIN, csDomainName, UUID.randomUUID().toString()); + } + } else { + domain = _domainService.getDomain(Domain.ROOT_DOMAIN); + } + + return domain; + } + private List createLdapUserResponse(List users) { final List ldapResponses = new ArrayList(); for (final LdapUser user : users) { diff --git a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapConfiguration.java b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapConfiguration.java index a08dccbd412..7db55f74a08 100644 --- a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapConfiguration.java +++ b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapConfiguration.java @@ -143,6 +143,16 @@ public class LdapConfiguration { return userObject == null ? "inetOrgPerson" : userObject; } + public String getGroupObject() { + final String groupObject = _configDao.getValue("ldap.group.object"); + return groupObject == null ? "groupOfUniqueNames" : groupObject; + } + + public String getGroupUniqueMemeberAttribute() { + final String uniqueMemberAttribute = _configDao.getValue("ldap.group.user.uniquemember"); + return uniqueMemberAttribute == null ? "uniquemember" : uniqueMemberAttribute; + } + public String getCommonNameAttribute() { return "cn"; } diff --git a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapManager.java b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapManager.java index 683822d31f4..2c99d080b9a 100644 --- a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapManager.java +++ b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapManager.java @@ -47,6 +47,8 @@ public interface LdapManager extends PluggableService { List getUsers() throws NoLdapUserMatchingQueryException; + List getUsersInGroup(String groupName) throws NoLdapUserMatchingQueryException; + boolean isLdapEnabled(); Pair, Integer> listConfigurations( diff --git a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapManagerImpl.java b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapManagerImpl.java index 90a79b3f96a..891d62538ab 100644 --- a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapManagerImpl.java +++ b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapManagerImpl.java @@ -194,7 +194,20 @@ public class LdapManagerImpl implements LdapManager, LdapValidator { } } - @Override + @Override + public List getUsersInGroup(String groupName) throws NoLdapUserMatchingQueryException { + DirContext context = null; + try { + context = _ldapContextFactory.createBindContext(); + return _ldapUserManager.getUsersInGroup(groupName, context); + } catch (final NamingException e) { + throw new NoLdapUserMatchingQueryException("groupName=" + groupName); + } finally { + closeContext(context); + } + } + + @Override public boolean isLdapEnabled() { return listConfigurations(new LdapListConfigurationCmd(this)).second() > 0; } diff --git a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapUserManager.java b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapUserManager.java index 47697c9127e..59a41dee75f 100644 --- a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapUserManager.java +++ b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapUserManager.java @@ -23,10 +23,7 @@ import java.util.List; import javax.inject.Inject; import javax.naming.NamingEnumeration; import javax.naming.NamingException; -import javax.naming.directory.Attributes; -import javax.naming.directory.DirContext; -import javax.naming.directory.SearchControls; -import javax.naming.directory.SearchResult; +import javax.naming.directory.*; public class LdapUserManager { @@ -86,6 +83,28 @@ public class LdapUserManager { return result.toString(); } + private String generateGroupSearchFilter(final String groupName) { + final StringBuilder groupObjectFilter = new StringBuilder(); + groupObjectFilter.append("(objectClass="); + groupObjectFilter.append(_ldapConfiguration.getGroupObject()); + groupObjectFilter.append(")"); + + final StringBuilder groupNameFilter = new StringBuilder(); + groupNameFilter.append("("); + groupNameFilter.append(_ldapConfiguration.getCommonNameAttribute()); + groupNameFilter.append("="); + groupNameFilter.append((groupName == null ? "*" : groupName)); + groupNameFilter.append(")"); + + final StringBuilder result = new StringBuilder(); + result.append("(&"); + result.append(groupObjectFilter); + result.append(groupNameFilter); + result.append(")"); + + return result.toString(); + } + public LdapUser getUser(final String username, final DirContext context) throws NamingException { final NamingEnumeration result = searchUsers(username, context); if (result.hasMoreElements()) { @@ -114,6 +133,44 @@ public class LdapUserManager { return users; } + public List getUsersInGroup(String groupName, DirContext context) throws NamingException { + String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute(); + final SearchControls controls = new SearchControls(); + controls.setSearchScope(_ldapConfiguration.getScope()); + controls.setReturningAttributes(new String[]{attributeName}); + + NamingEnumeration result = context.search(_ldapConfiguration.getBaseDn(), generateGroupSearchFilter(groupName), controls); + + final List users = new ArrayList(); + //Expecting only one result which has all the users + if (result.hasMoreElements()) { + Attribute attribute = result.nextElement().getAttributes().get(attributeName); + NamingEnumeration values = attribute.getAll(); + + while (values.hasMoreElements()) { + String userdn = String.valueOf(values.nextElement()); + users.add(getUserForDn(userdn,context)); + } + } + + Collections.sort(users); + + return users; + } + + private LdapUser getUserForDn(String userdn, DirContext context) throws NamingException { + final SearchControls controls = new SearchControls(); + controls.setSearchScope(_ldapConfiguration.getScope()); + controls.setReturningAttributes(_ldapConfiguration.getReturnAttributes()); + + NamingEnumeration result = context.search(userdn, "(objectClass="+_ldapConfiguration.getUserObject()+")", controls); + if (result.hasMoreElements()) { + return createUser(result.nextElement()); + } else { + throw new NamingException("No user found for dn " + userdn); + } + } + public NamingEnumeration searchUsers(final DirContext context) throws NamingException { return searchUsers(null, context); } diff --git a/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapConfigurationSpec.groovy b/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapConfigurationSpec.groovy index 66b4673b258..1017a0fa0f9 100644 --- a/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapConfigurationSpec.groovy +++ b/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapConfigurationSpec.groovy @@ -220,4 +220,37 @@ class LdapConfigurationSpec extends spock.lang.Specification { then: "The response should be true" result == true } + + def "Test getgroupobject"() { + given: "We have configdao for ldap group object" + def configDao = Mock(ConfigurationDao) + configDao.getValue("ldap.group.object") >> groupObject + + def ldapManger = Mock(LdapManager) + LdapConfiguration ldapConfiguration = new LdapConfiguration(configDao, ldapManger) + def expectedResult = groupObject == null ? "groupOfUniqueNames" : groupObject + + def result = ldapConfiguration.getGroupObject() + expect: + result == expectedResult + where: + groupObject << [null, "", "groupOfUniqueNames"] + } + + def "Test getGroupUniqueMemeberAttribute"() { + given: "We have configdao for ldap group object" + def configDao = Mock(ConfigurationDao) + configDao.getValue("ldap.group.user.uniquemember") >> groupObject + + def ldapManger = Mock(LdapManager) + LdapConfiguration ldapConfiguration = new LdapConfiguration(configDao, ldapManger) + def expectedResult = groupObject == null ? "uniquemember" : groupObject + + def result = ldapConfiguration.getGroupUniqueMemeberAttribute() + expect: + result == expectedResult + where: + groupObject << [null, "", "uniquemember"] + } + } diff --git a/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapCreateAccountCmdSpec.groovy b/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapCreateAccountCmdSpec.groovy index cc849defef5..b316a80a824 100644 --- a/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapCreateAccountCmdSpec.groovy +++ b/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapCreateAccountCmdSpec.groovy @@ -52,7 +52,7 @@ class LdapCreateAccountCmdSpec extends spock.lang.Specification { def "Test failed creation due to a null response from cloudstack account creater"() { given: "We have an LdapManager, AccountService and LdapCreateAccountCmd" LdapManager ldapManager = Mock(LdapManager) - ldapManager.getUser(_) >> new LdapUser("rmurphy", "rmurphy@cloudstack.org", "Ryan", "Murphy", "cn=rmurphy,dc=cloudstack,dc=org") + ldapManager.getUser(_) >> new LdapUser("rmurphy", "rmurphy@cloudstack.org", "Ryan", "Murphy", "cn=rmurphy,ou=engineering,dc=cloudstack,dc=org", "engineering") AccountService accountService = Mock(AccountService) def ldapCreateAccountCmd = Spy(LdapCreateAccountCmd, constructorArgs: [ldapManager, accountService]) ldapCreateAccountCmd.getCurrentContext() >> Mock(CallContext) @@ -104,7 +104,7 @@ class LdapCreateAccountCmdSpec extends spock.lang.Specification { AccountService accountService = Mock(AccountService) def ldapCreateAccountCmd = new LdapCreateAccountCmd(ldapManager, accountService); when: "a user with an username, email, firstname and lastname is validated" - def result = ldapCreateAccountCmd.validateUser(new LdapUser("username","email","firstname","lastname","principal")) + def result = ldapCreateAccountCmd.validateUser(new LdapUser("username","email","firstname","lastname","principal","domain")) then: "the result is true" result == true } @@ -115,7 +115,7 @@ class LdapCreateAccountCmdSpec extends spock.lang.Specification { AccountService accountService = Mock(AccountService) def ldapCreateAccountCmd = new LdapCreateAccountCmd(ldapManager, accountService) when: "A user with no email address attempts to validate" - ldapCreateAccountCmd.validateUser(new LdapUser("username",null,"firstname","lastname","principal")) + ldapCreateAccountCmd.validateUser(new LdapUser("username",null,"firstname","lastname","principal","domain")) then: "An exception is thrown" thrown Exception } @@ -137,7 +137,7 @@ class LdapCreateAccountCmdSpec extends spock.lang.Specification { AccountService accountService = Mock(AccountService) def ldapCreateAccountCmd = new LdapCreateAccountCmd(ldapManager, accountService) when: "A user with no lastname attempts to validate" - ldapCreateAccountCmd.validateUser(new LdapUser("username","email","firstname",null,"principal")) + ldapCreateAccountCmd.validateUser(new LdapUser("username","email","firstname",null,"principal","domain")) then: "An exception is thown" thrown Exception } diff --git a/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapImportUsersCmdSpec.groovy b/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapImportUsersCmdSpec.groovy index d04b0940c2b..04556401d71 100644 --- a/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapImportUsersCmdSpec.groovy +++ b/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapImportUsersCmdSpec.groovy @@ -34,7 +34,8 @@ class LdapImportUsersCmdSpec extends spock.lang.Specification { given: "We have an LdapManager, DomainService and a LdapImportUsersCmd" def ldapManager = Mock(LdapManager) def domainService = Mock(DomainService) - def ldapImportUsersCmd = new LdapImportUsersCmd(ldapManager, domainService) + def accountService = Mock(AccountService) + def ldapImportUsersCmd = new LdapImportUsersCmd(ldapManager, domainService, accountService) when: "Get command name is called" String commandName = ldapImportUsersCmd.getCommandName() then: "ldapuserresponse is returned" @@ -42,7 +43,7 @@ class LdapImportUsersCmdSpec extends spock.lang.Specification { } def "Test successful response from execute"() { - given: "We have an LdapManager, DomainService, one user and a LdapImportUsersCmd" + given: "We have an LdapManager, DomainService, two users and a LdapImportUsersCmd" def ldapManager = Mock(LdapManager) def domainService = Mock(DomainService) def accountService = Mock(AccountService) @@ -68,4 +69,123 @@ class LdapImportUsersCmdSpec extends spock.lang.Specification { then: "a list of size 2 is returned" ldapImportUsersCmd.responseObject.getResponses().size() == 2 } + + def "Test successful response from execute with group specified"() { + given: "We have an LdapManager, DomainService, two users and a LdapImportUsersCmd" + def ldapManager = Mock(LdapManager) + def domainService = Mock(DomainService) + def accountService = Mock(AccountService) + + List users = new ArrayList() + users.add(new LdapUser("rmurphy", "rmurphy@test.com", "Ryan", "Murphy", "cn=rmurphy,ou=engineering,dc=cloudstack,dc=org", "engineering")) + users.add(new LdapUser("bob", "bob@test.com", "Robert", "Young", "cn=bob,ou=engineering,dc=cloudstack,dc=org", "engineering")) + ldapManager.getUsersInGroup("TestGroup") >> users + LdapUserResponse response1 = new LdapUserResponse("rmurphy", "rmurphy@test.com", "Ryan", "Murphy", "cn=rmurphy,ou=engineering,dc=cloudstack,dc=org", "engineering") + LdapUserResponse response2 = new LdapUserResponse("bob", "bob@test.com", "Robert", "Young", "cn=bob,ou=engineering,dc=cloudstack,dc=org", "engineering") + ldapManager.createLdapUserResponse(_) >>>[response1, response2] + + + Domain domain = new DomainVO("TestGroup", 1L, 1L, "TestGroup", UUID.randomUUID().toString()) + domainService.getDomainByName("TestGroup", 1L) >>> [null, domain] + 1 * domainService.createDomain("TestGroup", 1L, "TestGroup", _) >> domain + + def ldapImportUsersCmd = new LdapImportUsersCmd(ldapManager, domainService, accountService) + ldapImportUsersCmd.accountType = 2; + ldapImportUsersCmd.groupName = "TestGroup"; + + when: "LdapListUsersCmd is executed" + ldapImportUsersCmd.execute() + then: "a list of size 2 is returned" + ldapImportUsersCmd.responseObject.getResponses().size() == 2 + } + + def "Test successful response from execute with group and domain specified"() { + given: "We have an LdapManager, DomainService, two users and a LdapImportUsersCmd" + def ldapManager = Mock(LdapManager) + def domainService = Mock(DomainService) + def accountService = Mock(AccountService) + + List users = new ArrayList() + users.add(new LdapUser("rmurphy", "rmurphy@test.com", "Ryan", "Murphy", "cn=rmurphy,ou=engineering,dc=cloudstack,dc=org", "engineering")) + users.add(new LdapUser("bob", "bob@test.com", "Robert", "Young", "cn=bob,ou=engineering,dc=cloudstack,dc=org", "engineering")) + ldapManager.getUsersInGroup("TestGroup") >> users + LdapUserResponse response1 = new LdapUserResponse("rmurphy", "rmurphy@test.com", "Ryan", "Murphy", "cn=rmurphy,ou=engineering,dc=cloudstack,dc=org", "engineering") + LdapUserResponse response2 = new LdapUserResponse("bob", "bob@test.com", "Robert", "Young", "cn=bob,ou=engineering,dc=cloudstack,dc=org", "engineering") + ldapManager.createLdapUserResponse(_) >>>[response1, response2] + + + Domain domain = new DomainVO("TestDomain", 1L, 1L, "TestDomain", UUID.randomUUID().toString()) + domainService.getDomainByName("TestDomain", 1L) >>> [null, domain] + 1 * domainService.createDomain("TestDomain", 1L, "TestDomain", _) >> domain + + def ldapImportUsersCmd = new LdapImportUsersCmd(ldapManager, domainService, accountService) + ldapImportUsersCmd.accountType = 2; + ldapImportUsersCmd.groupName = "TestGroup"; + ldapImportUsersCmd.domainName = "TestDomain"; + + when: "LdapListUsersCmd is executed" + ldapImportUsersCmd.execute() + then: "a list of size 2 is returned" + ldapImportUsersCmd.responseObject.getResponses().size() == 2 + } + + def "Test successful response from execute with domain specified"() { + given: "We have an LdapManager, DomainService, two users and a LdapImportUsersCmd" + def ldapManager = Mock(LdapManager) + def domainService = Mock(DomainService) + def accountService = Mock(AccountService) + + List users = new ArrayList() + users.add(new LdapUser("rmurphy", "rmurphy@test.com", "Ryan", "Murphy", "cn=rmurphy,ou=engineering,dc=cloudstack,dc=org", "engineering")) + users.add(new LdapUser("bob", "bob@test.com", "Robert", "Young", "cn=bob,ou=engineering,dc=cloudstack,dc=org", "engineering")) + ldapManager.getUsers() >> users + LdapUserResponse response1 = new LdapUserResponse("rmurphy", "rmurphy@test.com", "Ryan", "Murphy", "cn=rmurphy,ou=engineering,dc=cloudstack,dc=org", "engineering") + LdapUserResponse response2 = new LdapUserResponse("bob", "bob@test.com", "Robert", "Young", "cn=bob,ou=engineering,dc=cloudstack,dc=org", "engineering") + ldapManager.createLdapUserResponse(_) >>>[response1, response2] + + + Domain domain = new DomainVO("TestDomain", 1L, 1L, "TestDomain", UUID.randomUUID().toString()) + domainService.getDomainByName("TestDomain", 1L) >>> [null, domain] + 1 * domainService.createDomain("TestDomain", 1L, "TestDomain", _) >> domain + + def ldapImportUsersCmd = new LdapImportUsersCmd(ldapManager, domainService, accountService) + ldapImportUsersCmd.accountType = 2; + ldapImportUsersCmd.domainName = "TestDomain"; + + when: "LdapListUsersCmd is executed" + ldapImportUsersCmd.execute() + then: "a list of size 2 is returned" + ldapImportUsersCmd.responseObject.getResponses().size() == 2 + } + + def "Test getDomain with no domain or group name specified specified"() { + given: "We have an LdapManager, DomainService, two users and a LdapImportUsersCmd" + def ldapManager = Mock(LdapManager) + def domainService = Mock(DomainService) + def accountService = Mock(AccountService) + def ldapImportUsersCmd = new LdapImportUsersCmd(ldapManager, domainService, accountService) + ldapImportUsersCmd.domainName = varDomainName + ldapImportUsersCmd.groupName = varGroupName + + def ldapUser1 = new LdapUser("rmurphy", "rmurphy@test.com", "Ryan", "Murphy", "cn=rmurphy,ou=engineering,dc=cloudstack,dc=org", "engineering") + def ldapUser2 = new LdapUser("bob", "bob@test.com", "Robert", "Young", "cn=bob,ou=engineering,dc=cloudstack,dc=org", "engineering"); + + Domain domain = new DomainVO(expectedDomainName, 1L, 1L, expectedDomainName, UUID.randomUUID().toString()) + 2 * domainService.getDomainByName(expectedDomainName, 1L) >>> [null, domain] + 1 * domainService.createDomain(expectedDomainName, 1L, expectedDomainName, _) >> domain + + def result1 = ldapImportUsersCmd.getDomain(ldapUser1) + def result2 = ldapImportUsersCmd.getDomain(ldapUser2) + expect: "engineering domain is returned" + result1 == domain + result2 == domain + where: "The domain and group are set to the following values" + varDomainName | varGroupName | expectedDomainName + null | null | "engineering" + "TestDomain" | null | "TestDomain" + "TestDomain" | "TestGroup" | "TestDomain" + null | "TestGroup" | "TestGroup" + + } + } diff --git a/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapManagerImplSpec.groovy b/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapManagerImplSpec.groovy index 321e1af2ab4..42988e0caef 100644 --- a/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapManagerImplSpec.groovy +++ b/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapManagerImplSpec.groovy @@ -356,4 +356,20 @@ class LdapManagerImplSpec extends spock.lang.Specification { then: "true is returned because a configuration was found" result == true; } + + def "Test success getUsersInGroup"() { + given: "We have an LdapConfigurationDao, LdapContextFactory, LdapUserManager and LdapManager" + def ldapConfigurationDao = Mock(LdapConfigurationDaoImpl) + def ldapContextFactory = Mock(LdapContextFactory) + def ldapUserManager = Mock(LdapUserManager) + ldapContextFactory.createBindContext() >> null + List users = new ArrayList<>(); + users.add(new LdapUser("rmurphy", "rmurphy@test.com", "Ryan", "Murphy", "cn=rmurphy,dc=cloudstack,dc=org", "engineering")) + ldapUserManager.getUsersInGroup("engineering", _) >> users; + def ldapManager = new LdapManagerImpl(ldapConfigurationDao, ldapContextFactory, ldapUserManager) + when: "We search for a group of users" + def result = ldapManager.getUsersInGroup("engineering") + then: "A list greater of size one is returned" + result.size() == 1; + } } diff --git a/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapUserManagerSpec.groovy b/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapUserManagerSpec.groovy index 339923e57c0..fa735d3f67e 100644 --- a/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapUserManagerSpec.groovy +++ b/plugins/user-authenticators/ldap/test/groovy/org/apache/cloudstack/ldap/LdapUserManagerSpec.groovy @@ -21,8 +21,10 @@ import org.apache.cloudstack.ldap.LdapUserManager import spock.lang.Shared import javax.naming.NamingException +import javax.naming.NamingEnumeration import javax.naming.directory.Attribute import javax.naming.directory.Attributes +import javax.naming.directory.DirContext import javax.naming.directory.SearchControls import javax.naming.directory.SearchResult import javax.naming.ldap.LdapContext @@ -47,6 +49,38 @@ class LdapUserManagerSpec extends spock.lang.Specification { @Shared private def principal + private def createGroupSearchContext() { + + def umSearchResult = Mock(SearchResult) + umSearchResult.getName() >> principal; + umSearchResult.getAttributes() >> principal + + def uniqueMembers = new BasicNamingEnumerationImpl() + uniqueMembers.add(umSearchResult); + def attributes = Mock(Attributes) + def uniqueMemberAttribute = Mock(Attribute) + uniqueMemberAttribute.getId() >> "uniquemember" + uniqueMemberAttribute.getAll() >> uniqueMembers + attributes.get("uniquemember") >> uniqueMemberAttribute + + def groupSearchResult = Mock(SearchResult) + groupSearchResult.getName() >> principal; + groupSearchResult.getAttributes() >> attributes + + def searchGroupResults = new BasicNamingEnumerationImpl() + searchGroupResults.add(groupSearchResult); + + attributes = createUserAttributes(username, email, firstname, lastname) + SearchResult userSearchResult = createSearchResult(attributes) + def searchUsersResults = new BasicNamingEnumerationImpl() + searchUsersResults.add(userSearchResult); + + def context = Mock(LdapContext) + context.search(_, _, _) >>> [searchGroupResults, searchUsersResults]; + + return context + } + private def createContext() { Attributes attributes = createUserAttributes(username, email, firstname, lastname) SearchResult searchResults = createSearchResult(attributes) @@ -65,6 +99,7 @@ class LdapUserManagerSpec extends spock.lang.Specification { search.getName() >> "cn=" + attributes.getAt("uid").get(); search.getAttributes() >> attributes + search.getNameInNamespace() >> principal return search } @@ -105,6 +140,9 @@ class LdapUserManagerSpec extends spock.lang.Specification { ldapConfiguration.getFirstnameAttribute() >> "givenname" ldapConfiguration.getLastnameAttribute() >> "sn" ldapConfiguration.getBaseDn() >> "dc=cloudstack,dc=org" + ldapConfiguration.getCommonNameAttribute() >> "cn" + ldapConfiguration.getGroupObject() >> "groupOfUniqueNames" + ldapConfiguration.getGroupUniqueMemeberAttribute() >> "uniquemember" username = "rmurphy" email = "rmurphy@test.com" @@ -203,4 +241,43 @@ class LdapUserManagerSpec extends spock.lang.Specification { expect: "The result is not null" result != null } + + def "test successful generateGroupSearchFilter"() { + given: "ldap user manager and ldap config" + def ldapUserManager = new LdapUserManager(ldapConfiguration) + def groupName = varGroupName == null ? "*" : varGroupName + def expectedResult = "(&(objectClass=groupOfUniqueNames)(cn="+groupName+"))"; + + def result = ldapUserManager.generateGroupSearchFilter(varGroupName) + expect: + result == expectedResult + where: "The group name passed is set to " + varGroupName << ["", null, "Murphy"] + } + + def "test successful getUsersInGroup"(){ + given: "ldap user manager and ldap config" + def ldapUserManager = new LdapUserManager(ldapConfiguration) + + when: "A request for users is made" + def result = ldapUserManager.getUsersInGroup("engineering", createGroupSearchContext()) + then: "one user is returned" + result.size() == 1 + } + + def "test successful getUserForDn"(){ + given: "ldap user manager and ldap config" + def ldapUserManager = new LdapUserManager(ldapConfiguration) + + when: "A request for users is made" + def result = ldapUserManager.getUserForDn("cn=Ryan Murphy,ou=engineering,dc=cloudstack,dc=org",createContext()) + then: "A list of users is returned" + result != 1 + result.username == username + result.email == email + result.firstname == firstname + result.lastname == lastname + result.principal == principal + + } } diff --git a/pom.xml b/pom.xml index 679acedac80..6ea62c28e0f 100644 --- a/pom.xml +++ b/pom.xml @@ -86,6 +86,7 @@ target 1.0.10 4.0.0 + 2.10 @@ -174,6 +175,7 @@ services maven-standard quickcloud + parents/checkstyle @@ -566,6 +568,15 @@ deps/XenServerJava/BSD deps/XenServerJava/Makefile dist/console-proxy/js/jquery.js + plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.sln + plugins/hypervisors/hyperv/DotNet/ServerResource/packages/** + plugins/hypervisors/hyperv/DotNet/ServerResource/.nuget/** + plugins/hypervisors/hyperv/DotNet/ServerResource/**/obj/** + plugins/hypervisors/hyperv/DotNet/ServerResource/**/bin/** + plugins/hypervisors/hyperv/DotNet/ServerResource/**/packages.config + plugins/hypervisors/hyperv/DotNet/ServerResource/**/App.config + plugins/hypervisors/hyperv/DotNet/ServerResource/**/*.csproj + plugins/hypervisors/hyperv/conf/agent.properties scripts/vm/systemvm/id_rsa.cloud services/console-proxy/server/conf/agent.properties services/console-proxy/server/conf/environment.properties @@ -640,6 +651,7 @@ tools/marvin/marvin/sandbox/advanced/sandbox.cfg tools/ngui/static/bootstrap/* tools/ngui/static/js/lib/* + **/.checkstyle diff --git a/python/lib/cloudutils/serviceConfig.py b/python/lib/cloudutils/serviceConfig.py index 4ed9a57079c..d7c7e78c3ab 100755 --- a/python/lib/cloudutils/serviceConfig.py +++ b/python/lib/cloudutils/serviceConfig.py @@ -96,8 +96,9 @@ class networkConfigBase: return False if self.syscfg.env.bridgeType == "openvswitch" and not self.netcfg.isOvsBridge(br): raise CloudInternalException("%s is not an openvswitch bridge" % br) - if self.syscfg.env.bridgeType == "native" and not self.netcfg.isBridge(br): - raise CloudInternalException("%s is not a bridge" % br) + if self.syscfg.env.bridgeType == "native" and not self.netcfg.isBridge(br) and not self.netcfg.isNetworkDev(br): + # traffic label doesn't have to be a bridge, we'll create bridges on it + raise CloudInternalException("%s is not a bridge and not a net device" % br) preCfged = True return preCfged diff --git a/scripts/storage/secondary/createtmplt.sh b/scripts/storage/secondary/createtmplt.sh index 3fa43e33823..05874b4be09 100755 --- a/scripts/storage/secondary/createtmplt.sh +++ b/scripts/storage/secondary/createtmplt.sh @@ -169,6 +169,14 @@ do esac done +isCifs() { + #TO:DO incase of multiple zone where cifs and nfs exists, + #then check if the template file is from cifs using df -P filename + #Currently only cifs is supported in hyperv zone. + mount | grep "type cifs" > /dev/null + return $? +} + if [ "$tflag$nflag$fflag$sflag" != "1111" ] then usage @@ -196,12 +204,15 @@ rollback_if_needed $tmpltfs $? "tar archives not supported\n" if [ ${tmpltname%.vhd} != ${tmpltname} ] then - if which vhd-util &>/dev/null - then - vhd-util read -p -n ${tmpltimg2} > /dev/null - rollback_if_needed $tmpltfs $? "vhd check of $tmpltimg2 failed\n" - vhd-util set -n ${tmpltimg2} -f "hidden" -v "0" > /dev/null - rollback_if_needed $tmpltfs $? "vhd remove $tmpltimg2 hidden failed\n" + if [ isCifs -ne 0 ] ; + then + if which vhd-util &>/dev/null + then + vhd-util read -p -n ${tmpltimg2} > /dev/null + rollback_if_needed $tmpltfs $? "vhd check of $tmpltimg2 failed\n" + vhd-util set -n ${tmpltimg2} -f "hidden" -v "0" > /dev/null + rollback_if_needed $tmpltfs $? "vhd remove $tmpltimg2 hidden failed\n" + fi fi fi diff --git a/server/pom.xml b/server/pom.xml index c7978e2dd38..527bd97165c 100644 --- a/server/pom.xml +++ b/server/pom.xml @@ -228,5 +228,38 @@ + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-antrun-plugin + + [1.7,) + + run + + + + + + + + + + + + diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java index 013aa5789cd..c0cb10478f4 100755 --- a/server/src/com/cloud/api/ApiDBUtils.java +++ b/server/src/com/cloud/api/ApiDBUtils.java @@ -1485,7 +1485,15 @@ public class ApiDBUtils { } public static UserResponse newUserResponse(UserAccountJoinVO usr) { - return _userAccountJoinDao.newUserResponse(usr); + return newUserResponse(usr, null); + } + public static UserResponse newUserResponse(UserAccountJoinVO usr, Long domainId) { + UserResponse response = _userAccountJoinDao.newUserResponse(usr); + if (domainId != null && usr.getDomainId() != domainId) + response.setIsCallerChildDomain(true); + else + response.setIsCallerChildDomain(false); + return response; } public static UserAccountJoinVO newUserView(User usr){ diff --git a/server/src/com/cloud/api/ApiDispatcher.java b/server/src/com/cloud/api/ApiDispatcher.java index 610c1bbdb99..9672ef1e837 100755 --- a/server/src/com/cloud/api/ApiDispatcher.java +++ b/server/src/com/cloud/api/ApiDispatcher.java @@ -33,10 +33,9 @@ import java.util.regex.Matcher; import javax.annotation.PostConstruct; import javax.inject.Inject; -import org.apache.log4j.Logger; - import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; import org.apache.cloudstack.api.ApiConstants; @@ -59,6 +58,7 @@ import org.apache.cloudstack.api.command.user.event.ListEventsCmd; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.framework.jobs.AsyncJob; import org.apache.cloudstack.framework.jobs.AsyncJobManager; +import org.apache.log4j.Logger; import com.cloud.exception.InvalidParameterValueException; import com.cloud.user.Account; @@ -192,7 +192,22 @@ public class ApiDispatcher { } //TODO: Annotate @Validate on API Cmd classes, FIXME how to process Validate - Validate validateAnnotation = field.getAnnotation(Validate.class); + RoleType[] allowedRoles = parameterAnnotation.authorized(); + if (allowedRoles.length > 0) { + boolean permittedParameter = false; + Account caller = CallContext.current().getCallingAccount(); + for (RoleType allowedRole : allowedRoles) { + if (allowedRole.getValue() == caller.getType()) { + permittedParameter = true; + break; + } + } + if (!permittedParameter) { + s_logger.debug("Ignoring paremeter " + parameterAnnotation.name() + " as the caller is not authorized to pass it in"); + continue; + } + } + Object paramObj = unpackedParams.get(parameterAnnotation.name()); if (paramObj == null) { if (parameterAnnotation.required()) { diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index abb30152127..fd20f2b928d 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -3214,6 +3214,7 @@ public class ApiResponseHelper implements ResponseGenerator { public Site2SiteVpnConnectionResponse createSite2SiteVpnConnectionResponse(Site2SiteVpnConnection result) { Site2SiteVpnConnectionResponse response = new Site2SiteVpnConnectionResponse(); response.setId(result.getUuid()); + response.setPassive(result.isPassive()); Long vpnGatewayId = result.getVpnGatewayId(); if (vpnGatewayId != null) { diff --git a/server/src/com/cloud/api/query/QueryManagerImpl.java b/server/src/com/cloud/api/query/QueryManagerImpl.java index 7ab22984f8e..1bcf578b6b7 100644 --- a/server/src/com/cloud/api/query/QueryManagerImpl.java +++ b/server/src/com/cloud/api/query/QueryManagerImpl.java @@ -381,8 +381,8 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { public ListResponse searchForUsers(ListUsersCmd cmd) throws PermissionDeniedException { Pair, Integer> result = searchForUsersInternal(cmd); ListResponse response = new ListResponse(); - List userResponses = ViewResponseHelper.createUserResponse(result.first().toArray( - new UserAccountJoinVO[result.first().size()])); + List userResponses = ViewResponseHelper.createUserResponse(CallContext.current().getCallingAccount().getDomainId(), + result.first().toArray(new UserAccountJoinVO[result.first().size()])); response.setResponses(userResponses, result.second()); return response; } @@ -1641,6 +1641,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { String type = cmd.getType(); Map tags = cmd.getTags(); boolean isRootAdmin = _accountMgr.isRootAdmin(caller.getType()); + Long storageId = cmd.getStorageId(); Long zoneId = cmd.getZoneId(); Long podId = null; @@ -1676,6 +1677,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { sb.and("instanceId", sb.entity().getVmId(), SearchCriteria.Op.EQ); sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); + sb.and("storageId", sb.entity().getPoolId(), SearchCriteria.Op.EQ); // Only return volumes that are not destroyed sb.and("state", sb.entity().getState(), SearchCriteria.Op.NEQ); sb.and("systemUse", sb.entity().isSystemUse(), SearchCriteria.Op.NEQ); @@ -1735,6 +1737,10 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { sc.setParameters("podId", podId); } + if (storageId != null) { + sc.setParameters("storageId", storageId); + } + if(!isRootAdmin){ sc.setParameters("displayVolume", 1); } diff --git a/server/src/com/cloud/api/query/ViewResponseHelper.java b/server/src/com/cloud/api/query/ViewResponseHelper.java index f3bc796e481..0cf8e169c95 100644 --- a/server/src/com/cloud/api/query/ViewResponseHelper.java +++ b/server/src/com/cloud/api/query/ViewResponseHelper.java @@ -87,9 +87,13 @@ public class ViewResponseHelper { public static final Logger s_logger = Logger.getLogger(ViewResponseHelper.class); public static List createUserResponse(UserAccountJoinVO... users) { + return createUserResponse(null, users); + } + + public static List createUserResponse(Long domainId, UserAccountJoinVO... users) { List respList = new ArrayList(); for (UserAccountJoinVO vt : users){ - respList.add(ApiDBUtils.newUserResponse(vt)); + respList.add(ApiDBUtils.newUserResponse(vt, domainId)); } return respList; } diff --git a/server/src/com/cloud/configuration/Config.java b/server/src/com/cloud/configuration/Config.java index 3fdc3439092..e78757639ee 100755 --- a/server/src/com/cloud/configuration/Config.java +++ b/server/src/com/cloud/configuration/Config.java @@ -394,6 +394,9 @@ public enum Config { LdapSearchGroupPrinciple("Advanced", ManagementServer.class, String.class, "ldap.search.group.principle", null, "Sets the principle of the group that users must be a member of", null), LdapTrustStore("Advanced", ManagementServer.class, String.class, "ldap.truststore", null, "Sets the path to the truststore to use for SSL", null), LdapTrustStorePassword("Advanced", ManagementServer.class, String.class, "ldap.truststore.password", null, "Sets the password for the truststore", null), + LdapGroupObject("Advanced", ManagementServer.class, String.class, "ldap.group.object", "groupOfUniqueNames", "Sets the object type of groups within LDAP", null), + LdapGroupUniqueMemberAttribute("Advanced", ManagementServer.class, String.class, "ldap.group.user.uniquemember", "uniquemember", + "Sets the attribute for uniquemembers within a group", null), // VMSnapshots VMSnapshotMax("Advanced", VMSnapshotManager.class, Integer.class, "vmsnapshot.max", "10", "Maximum vm snapshots for a vm", null), diff --git a/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java b/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java index 59337c0326d..d6feaf3fd8a 100755 --- a/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java +++ b/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java @@ -206,8 +206,8 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai return; } - if(host.getHypervisorType() == HypervisorType.VMware) { - s_logger.info("Don't restart for VMs on host " + host.getId() + " as the host is VMware host"); + if(host.getHypervisorType() == HypervisorType.VMware || host.getHypervisorType() == HypervisorType.Hyperv) { + s_logger.info("Don't restart for VMs on host " + host.getId() + " as the host is VMware host or on Hyperv Host"); return; } @@ -302,6 +302,11 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai return; } + if(vm.getHypervisorType() == HypervisorType.VMware || vm.getHypervisorType() == HypervisorType.Hyperv) { + s_logger.info("Skip HA for VMware VM or Hyperv VM" + vm.getInstanceName()); + return; + } + if (!investigate) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM does not require investigation so I'm marking it as Stopped: " + vm.toString()); diff --git a/server/src/com/cloud/network/guru/ControlNetworkGuru.java b/server/src/com/cloud/network/guru/ControlNetworkGuru.java index 1943e16a4f3..a5b7c88d58f 100755 --- a/server/src/com/cloud/network/guru/ControlNetworkGuru.java +++ b/server/src/com/cloud/network/guru/ControlNetworkGuru.java @@ -133,7 +133,9 @@ public class ControlNetworkGuru extends PodBasedNetworkGuru implements NetworkGu InsufficientAddressCapacityException { assert nic.getTrafficType() == TrafficType.Control; - if (dest.getHost().getHypervisorType() == HypervisorType.VMware && isRouterVm(vm)) { + // we have to get management/private ip for the control nic for vmware/hyperv due ssh issues. + HypervisorType hType = dest.getHost().getHypervisorType(); + if ( ( (hType == HypervisorType.VMware) || (hType == HypervisorType.Hyperv) )&& isRouterVm(vm)) { if(dest.getDataCenter().getNetworkType() != NetworkType.Basic) { super.reserve(nic, config, vm, dest, context); diff --git a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java index 63eb75b672e..ecfce575fd0 100644 --- a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java @@ -1122,7 +1122,7 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian Boolean dpd = gw.getDpd(); Site2SiteVpnCfgCommand cmd = new Site2SiteVpnCfgCommand(isCreate, localPublicIp, localPublicGateway, localGuestCidr, - peerGatewayIp, peerGuestCidrList, ikePolicy, espPolicy, ipsecPsk, ikeLifetime, espLifetime, dpd); + peerGatewayIp, peerGuestCidrList, ikePolicy, espPolicy, ipsecPsk, ikeLifetime, espLifetime, dpd, conn.isPassive()); cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId())); cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId())); cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName()); diff --git a/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java b/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java index f29a8c87054..94d2dc3e223 100644 --- a/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java +++ b/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java @@ -290,7 +290,7 @@ public class Site2SiteVpnManagerImpl extends ManagerBase implements Site2SiteVpn } } - Site2SiteVpnConnectionVO conn = new Site2SiteVpnConnectionVO(owner.getAccountId(), owner.getDomainId(), vpnGatewayId, customerGatewayId); + Site2SiteVpnConnectionVO conn = new Site2SiteVpnConnectionVO(owner.getAccountId(), owner.getDomainId(), vpnGatewayId, customerGatewayId, cmd.isPassive()); conn.setState(State.Pending); _vpnConnectionDao.persist(conn); return conn; @@ -317,7 +317,11 @@ public class Site2SiteVpnManagerImpl extends ManagerBase implements Site2SiteVpn } if (result) { - conn.setState(State.Connected); + if (conn.isPassive()) { + conn.setState(State.Disconnected); + } else { + conn.setState(State.Connected); + } _vpnConnectionDao.persist(conn); return conn; } diff --git a/server/src/com/cloud/storage/VolumeApiServiceImpl.java b/server/src/com/cloud/storage/VolumeApiServiceImpl.java index 61422d13802..80d358f7751 100644 --- a/server/src/com/cloud/storage/VolumeApiServiceImpl.java +++ b/server/src/com/cloud/storage/VolumeApiServiceImpl.java @@ -1233,6 +1233,19 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic String errorMsg = "Failed to detach volume: " + volume.getName() + " from VM: " + vm.getHostName(); boolean sendCommand = (vm.getState() == State.Running); + + Long hostId = vm.getHostId(); + + if (hostId == null) { + hostId = vm.getLastHostId(); + + HostVO host = _hostDao.findById(hostId); + + if (host != null && host.getHypervisorType() == HypervisorType.VMware) { + sendCommand = true; + } + } + Answer answer = null; if (sendCommand) { @@ -1251,7 +1264,7 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic cmd.set_iScsiName(volume.get_iScsiName()); try { - answer = _agentMgr.send(vm.getHostId(), cmd); + answer = _agentMgr.send(hostId, cmd); } catch (Exception e) { throw new CloudRuntimeException(errorMsg + " due to: " + e.getMessage()); } diff --git a/server/src/com/cloud/storage/download/DownloadMonitorImpl.java b/server/src/com/cloud/storage/download/DownloadMonitorImpl.java index eb790a44f9c..89b3407b60f 100755 --- a/server/src/com/cloud/storage/download/DownloadMonitorImpl.java +++ b/server/src/com/cloud/storage/download/DownloadMonitorImpl.java @@ -22,11 +22,13 @@ import java.util.Date; import java.util.List; import java.util.Map; import java.util.Timer; -import java.util.concurrent.ConcurrentHashMap; import javax.ejb.Local; import javax.inject.Inject; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; + import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; @@ -48,16 +50,13 @@ import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO; import org.apache.cloudstack.storage.to.TemplateObjectTO; import org.apache.cloudstack.storage.to.VolumeObjectTO; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; - import com.cloud.agent.AgentManager; import com.cloud.agent.api.storage.DownloadAnswer; import com.cloud.agent.api.storage.Proxy; import com.cloud.configuration.Config; import com.cloud.storage.RegisterVolumePayload; -import com.cloud.storage.VMTemplateStorageResourceAssoc; import com.cloud.storage.Storage.ImageFormat; +import com.cloud.storage.VMTemplateStorageResourceAssoc; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.storage.Volume; import com.cloud.storage.dao.VMTemplateDao; @@ -68,6 +67,7 @@ import com.cloud.storage.upload.UploadListener; import com.cloud.template.VirtualMachineTemplate; import com.cloud.utils.component.ComponentContext; import com.cloud.utils.component.ManagerBase; +import com.cloud.utils.exception.CloudRuntimeException; @Component @Local(value = { DownloadMonitor.class }) @@ -159,7 +159,7 @@ public class DownloadMonitorImpl extends ManagerBase implements DownloadMonitor Long maxTemplateSizeInBytes = getMaxTemplateSizeInBytes(); if (vmTemplateStore != null) { start(); - VirtualMachineTemplate tmpl = this._templateDao.findById(template.getId()); + VirtualMachineTemplate tmpl = _templateDao.findById(template.getId()); DownloadCommand dcmd = new DownloadCommand((TemplateObjectTO)(template.getTO()), maxTemplateSizeInBytes); dcmd.setProxy(getHttpProxy()); if (downloadJobExists) { @@ -170,8 +170,9 @@ public class DownloadMonitorImpl extends ManagerBase implements DownloadMonitor } EndPoint ep = _epSelector.select(template); if (ep == null) { - s_logger.warn("There is no secondary storage VM for downloading template to image store " + store.getName()); - return; + String errMsg = "There is no secondary storage VM for downloading template to image store " + store.getName(); + s_logger.warn(errMsg); + throw new CloudRuntimeException(errMsg); } DownloadListener dl = new DownloadListener(ep, store, template, _timer, this, dcmd, callback); @@ -239,7 +240,7 @@ public class DownloadMonitorImpl extends ManagerBase implements DownloadMonitor Long maxVolumeSizeInBytes = getMaxVolumeSizeInBytes(); if (volumeHost != null) { start(); - Volume vol = this._volumeDao.findById(volume.getId()); + Volume vol = _volumeDao.findById(volume.getId()); DownloadCommand dcmd = new DownloadCommand((VolumeObjectTO)(volume.getTO()), maxVolumeSizeInBytes, checkSum, url, format); dcmd.setProxy(getHttpProxy()); if (downloadJobExists) { @@ -247,7 +248,7 @@ public class DownloadMonitorImpl extends ManagerBase implements DownloadMonitor dcmd.setResourceType(ResourceType.VOLUME); } - EndPoint ep = this._epSelector.select(volume); + EndPoint ep = _epSelector.select(volume); if (ep == null) { s_logger.warn("There is no secondary storage VM for image store " + store.getName()); return; diff --git a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java index 464f7f8b2f3..e11b959ef65 100755 --- a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java +++ b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java @@ -26,6 +26,9 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; + import org.apache.cloudstack.api.command.user.snapshot.CreateSnapshotPolicyCmd; import org.apache.cloudstack.api.command.user.snapshot.DeleteSnapshotPoliciesCmd; import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotPoliciesCmd; @@ -41,10 +44,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotService; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotStrategy; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotStrategy.SnapshotOperation; -import org.apache.cloudstack.engine.subsystem.api.storage.StrategyPriority; import org.apache.cloudstack.engine.subsystem.api.storage.StorageStrategyFactory; -import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotStrategy.SnapshotOperation; -import org.apache.cloudstack.engine.subsystem.api.storage.StrategyPriority; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; @@ -53,8 +53,6 @@ import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; @@ -593,7 +591,14 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager, String snapshotDir = TemplateConstants.DEFAULT_SNAPSHOT_ROOT_DIR + "/" + accountId + "/" + volumeId; DeleteSnapshotsDirCommand cmd = new DeleteSnapshotsDirCommand(ssHost.getTO(), snapshotDir); EndPoint ep = _epSelector.select(ssHost); - Answer answer = ep.sendMessage(cmd); + Answer answer = null; + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(cmd, false, errMsg); + } else { + answer = ep.sendMessage(cmd); + } if ((answer != null) && answer.getResult()) { s_logger.debug("Deleted all snapshots for volume: " + volumeId + " under account: " + accountId); } else { diff --git a/server/src/com/cloud/storage/upload/UploadListener.java b/server/src/com/cloud/storage/upload/UploadListener.java index add58774c28..f3b6806b691 100755 --- a/server/src/com/cloud/storage/upload/UploadListener.java +++ b/server/src/com/cloud/storage/upload/UploadListener.java @@ -21,12 +21,12 @@ import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Timer; -import java.util.TimerTask; import javax.inject.Inject; import org.apache.log4j.Level; import org.apache.log4j.Logger; + import org.apache.cloudstack.api.command.user.iso.ExtractIsoCmd; import org.apache.cloudstack.api.command.user.template.ExtractTemplateCmd; import org.apache.cloudstack.api.command.user.volume.ExtractVolumeCmd; @@ -437,6 +437,11 @@ public class UploadListener implements Listener { } try { EndPoint ep = _epSelector.select(sserver); + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + return; + } ep.sendMessageAsync(new UploadProgressCommand(getCommand(), getJobId(), reqType), new Callback(ep.getId(), this)); } catch (Exception e) { s_logger.debug("Send command failed", e); diff --git a/server/src/com/cloud/storage/upload/UploadMonitorImpl.java b/server/src/com/cloud/storage/upload/UploadMonitorImpl.java index 4eb4900e67d..4785e494c4b 100755 --- a/server/src/com/cloud/storage/upload/UploadMonitorImpl.java +++ b/server/src/com/cloud/storage/upload/UploadMonitorImpl.java @@ -34,6 +34,7 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; + import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; @@ -167,6 +168,11 @@ public class UploadMonitorImpl extends ManagerBase implements UploadMonitor { try { EndPoint ep = _epSelector.select(secStore); + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + return; + } ep.sendMessageAsync(ucmd, new UploadListener.Callback(ep.getId(), ul)); } catch (Exception e) { s_logger.warn("Unable to start upload of volume " + volume.getName() + " from " + secStore.getName() + " to " +url, e); @@ -194,6 +200,11 @@ public class UploadMonitorImpl extends ManagerBase implements UploadMonitor { _listenerMap.put(uploadTemplateObj, ul); try{ EndPoint ep = _epSelector.select(secStore); + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + return null; + } ep.sendMessageAsync(ucmd, new UploadListener.Callback(ep.getId(), ul)); } catch (Exception e) { s_logger.warn("Unable to start upload of " + template.getUniqueName() + " from " + secStore.getName() + " to " +url, e); @@ -205,61 +216,66 @@ public class UploadMonitorImpl extends ManagerBase implements UploadMonitor { return null; } - @Override - public UploadVO createEntityDownloadURL(VMTemplateVO template, TemplateDataStoreVO vmTemplateHost, Long dataCenterId, long eventId) { + @Override + public UploadVO createEntityDownloadURL(VMTemplateVO template, TemplateDataStoreVO vmTemplateHost, Long dataCenterId, long eventId) { - String errorString = ""; - boolean success = false; - Type type = (template.getFormat() == ImageFormat.ISO) ? Type.ISO : Type.TEMPLATE ; + String errorString = ""; + boolean success = false; + Type type = (template.getFormat() == ImageFormat.ISO) ? Type.ISO : Type.TEMPLATE; - // find an endpoint to send command - DataStore store = storeMgr.getDataStore(vmTemplateHost.getDataStoreId(), DataStoreRole.Image); - EndPoint ep = _epSelector.select(store); - - //Check if it already exists. - List extractURLList = _uploadDao.listByTypeUploadStatus(template.getId(), type, UploadVO.Status.DOWNLOAD_URL_CREATED); - if (extractURLList.size() > 0) { - // do some check here - UploadVO upload = extractURLList.get(0); - String uploadUrl = extractURLList.get(0).getUploadUrl(); - String[] token = uploadUrl.split("/"); - // example: uploadUrl = https://10-11-101-112.realhostip.com/userdata/2fdd9a70-9c4a-4a04-b1d5-1e41c221a1f9.iso - // then token[2] = 10-11-101-112.realhostip.com, token[4] = 2fdd9a70-9c4a-4a04-b1d5-1e41c221a1f9.iso - String hostname = ep.getPublicAddr().replace(".", "-") + "."; - if ((token != null) && (token.length == 5) && (token[2].equals(hostname + _ssvmUrlDomain))) // ssvm publicip and domain suffix not changed - return extractURLList.get(0); - else if ((token != null) && (token.length == 5) && (token[2].startsWith(hostname))) { // domain suffix changed - String uuid = token[4]; - uploadUrl = generateCopyUrl(ep.getPublicAddr(), uuid); - UploadVO vo = _uploadDao.createForUpdate(); - vo.setLastUpdated(new Date()); - vo.setUploadUrl(uploadUrl); - _uploadDao.update(upload.getId(), vo); - return _uploadDao.findById(upload.getId(), true); - } else { // ssvm publicip changed - return null; - } + // find an endpoint to send command + DataStore store = storeMgr.getDataStore(vmTemplateHost.getDataStoreId(), DataStoreRole.Image); + EndPoint ep = _epSelector.select(store); + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + return null; } - // It doesn't exist so create a DB entry. - UploadVO uploadTemplateObj = new UploadVO(vmTemplateHost.getDataStoreId(), template.getId(), new Date(), - Status.DOWNLOAD_URL_NOT_CREATED, 0, type, Mode.HTTP_DOWNLOAD); - uploadTemplateObj.setInstallPath(vmTemplateHost.getInstallPath()); - _uploadDao.persist(uploadTemplateObj); + //Check if it already exists. + List extractURLList = _uploadDao.listByTypeUploadStatus(template.getId(), type, UploadVO.Status.DOWNLOAD_URL_CREATED); + if (extractURLList.size() > 0) { + // do some check here + UploadVO upload = extractURLList.get(0); + String uploadUrl = extractURLList.get(0).getUploadUrl(); + String[] token = uploadUrl.split("/"); + // example: uploadUrl = https://10-11-101-112.realhostip.com/userdata/2fdd9a70-9c4a-4a04-b1d5-1e41c221a1f9.iso + // then token[2] = 10-11-101-112.realhostip.com, token[4] = 2fdd9a70-9c4a-4a04-b1d5-1e41c221a1f9.iso + String hostname = ep.getPublicAddr().replace(".", "-") + "."; + if ((token != null) && (token.length == 5) && (token[2].equals(hostname + _ssvmUrlDomain))) // ssvm publicip and domain suffix not changed + return extractURLList.get(0); + else if ((token != null) && (token.length == 5) && (token[2].startsWith(hostname))) { // domain suffix changed + String uuid = token[4]; + uploadUrl = generateCopyUrl(ep.getPublicAddr(), uuid); + UploadVO vo = _uploadDao.createForUpdate(); + vo.setLastUpdated(new Date()); + vo.setUploadUrl(uploadUrl); + _uploadDao.update(upload.getId(), vo); + return _uploadDao.findById(upload.getId(), true); + } else { // ssvm publicip changed + return null; + } + } - try{ - // Create Symlink at ssvm - String path = vmTemplateHost.getInstallPath(); - String uuid = UUID.randomUUID().toString() + "." + template.getFormat().getFileExtension(); // adding "." + vhd/ova... etc. - CreateEntityDownloadURLCommand cmd = new CreateEntityDownloadURLCommand(((ImageStoreEntity)store).getMountPoint(), path, uuid, null); - Answer ans = ep.sendMessage(cmd); - if (ans == null || !ans.getResult()) { - errorString = "Unable to create a link for " +type+ " id:"+template.getId() + "," + ans.getDetails(); + // It doesn't exist so create a DB entry. + UploadVO uploadTemplateObj = new UploadVO(vmTemplateHost.getDataStoreId(), template.getId(), new Date(), + Status.DOWNLOAD_URL_NOT_CREATED, 0, type, Mode.HTTP_DOWNLOAD); + uploadTemplateObj.setInstallPath(vmTemplateHost.getInstallPath()); + _uploadDao.persist(uploadTemplateObj); + + try { + // Create Symlink at ssvm + String path = vmTemplateHost.getInstallPath(); + String uuid = UUID.randomUUID().toString() + "." + template.getFormat().getFileExtension(); // adding "." + vhd/ova... etc. + CreateEntityDownloadURLCommand cmd = new CreateEntityDownloadURLCommand(((ImageStoreEntity)store).getMountPoint(), path, uuid, null); + Answer ans = ep.sendMessage(cmd); + if (ans == null || !ans.getResult()) { + errorString = "Unable to create a link for " + type + " id:" + template.getId() + "," + ans.getDetails(); s_logger.error(errorString); throw new CloudRuntimeException(errorString); } - //Construct actual URL locally now that the symlink exists at SSVM + //Construct actual URL locally now that the symlink exists at SSVM String extractURL = generateCopyUrl(ep.getPublicAddr(), uuid); UploadVO vo = _uploadDao.createForUpdate(); vo.setLastUpdated(new Date()); @@ -268,17 +284,17 @@ public class UploadMonitorImpl extends ManagerBase implements UploadMonitor { _uploadDao.update(uploadTemplateObj.getId(), vo); success = true; return _uploadDao.findById(uploadTemplateObj.getId(), true); - }finally{ - if(!success){ + } finally { + if (!success) { UploadVO uploadJob = _uploadDao.createForUpdate(uploadTemplateObj.getId()); uploadJob.setLastUpdated(new Date()); uploadJob.setErrorString(errorString); uploadJob.setUploadState(Status.ERROR); _uploadDao.update(uploadTemplateObj.getId(), uploadJob); } - } + } - } + } @Override public void createVolumeDownloadURL(Long entityId, String path, Type type, Long dataCenterId, Long uploadId, ImageFormat format) { diff --git a/server/src/com/cloud/template/TemplateManagerImpl.java b/server/src/com/cloud/template/TemplateManagerImpl.java index d40a01f3137..2fc0c66ed0d 100755 --- a/server/src/com/cloud/template/TemplateManagerImpl.java +++ b/server/src/com/cloud/template/TemplateManagerImpl.java @@ -583,7 +583,14 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager, public String getChecksum(DataStore store, String templatePath) { EndPoint ep = _epSelector.select(store); ComputeChecksumCommand cmd = new ComputeChecksumCommand(store.getTO(), templatePath); - Answer answer = ep.sendMessage(cmd); + Answer answer = null; + if (ep == null) { + String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; + s_logger.error(errMsg); + answer = new Answer(cmd, false, errMsg); + } else { + answer = ep.sendMessage(cmd); + } if (answer != null && answer.getResult()) { return answer.getDetails(); } diff --git a/server/src/com/cloud/usage/UsageServiceImpl.java b/server/src/com/cloud/usage/UsageServiceImpl.java index f7cfe313bb0..d22319b45ea 100755 --- a/server/src/com/cloud/usage/UsageServiceImpl.java +++ b/server/src/com/cloud/usage/UsageServiceImpl.java @@ -32,6 +32,7 @@ import org.apache.cloudstack.api.command.admin.usage.GetUsageRecordsCmd; import org.apache.cloudstack.api.response.UsageTypeResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.cloudstack.usage.Usage; import org.apache.cloudstack.usage.UsageService; import org.apache.cloudstack.usage.UsageTypes; import org.apache.log4j.Logger; @@ -50,11 +51,11 @@ import com.cloud.user.Account; import com.cloud.user.AccountService; import com.cloud.user.AccountVO; import com.cloud.user.dao.AccountDao; +import com.cloud.utils.Pair; import com.cloud.utils.component.Manager; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.db.Filter; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; import com.cloud.utils.db.TransactionLegacy; @Component @@ -115,7 +116,7 @@ public class UsageServiceImpl extends ManagerBase implements UsageService, Manag } @Override - public List getUsageRecords(GetUsageRecordsCmd cmd) { + public Pair, Integer> getUsageRecords(GetUsageRecordsCmd cmd) { Long accountId = cmd.getAccountId(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); @@ -212,13 +213,13 @@ public class UsageServiceImpl extends ManagerBase implements UsageService, Manag sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); } else { - return new ArrayList(); // return an empty list if we fail to validate the dates + return new Pair, Integer>(new ArrayList(), new Integer(0)); // return an empty list if we fail to validate the dates } - List usageRecords = null; + Pair, Integer> usageRecords = null; TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { - usageRecords = _usageDao.searchAllRecords(sc, usageFilter); + usageRecords = _usageDao.searchAndCountAllRecords(sc, usageFilter); } finally { txn.close(); @@ -227,7 +228,7 @@ public class UsageServiceImpl extends ManagerBase implements UsageService, Manag swap.close(); } - return usageRecords; + return new Pair, Integer>(usageRecords.first(), usageRecords.second()); } @Override diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 2f1c6c09d93..224c30e81ff 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -916,6 +916,10 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if(network == null) { throw new InvalidParameterValueException("unable to find a network with id " + networkId); } + if (!(network.getGuestType() == Network.GuestType.Shared && network.getAclType() == ACLType.Domain) + && !(network.getAclType() == ACLType.Account && network.getAccountId() == vmInstance.getAccountId())) { + throw new InvalidParameterValueException("only shared network or isolated network with the same account_id can be added to vmId: " + vmId); + } List allNics = _nicDao.listByVmId(vmInstance.getId()); for(NicVO nic : allNics){ if(nic.getNetworkId() == network.getId()) @@ -2652,7 +2656,10 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir + network.getId() + " doesn't belong to zone " + zone.getId()); } - + if (!(network.getGuestType() == Network.GuestType.Shared && network.getAclType() == ACLType.Domain) + && !(network.getAclType() == ACLType.Account && network.getAccountId() == accountId)) { + throw new InvalidParameterValueException("only shared network or isolated network with the same account_id can be added to vm"); + } IpAddresses requestedIpPair = null; if (requestedIps != null && !requestedIps.isEmpty()) { requestedIpPair = requestedIps.get(network.getId()); diff --git a/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java b/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java index ee81c82fe3f..3e6d7f96010 100644 --- a/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java +++ b/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java @@ -30,6 +30,7 @@ import javax.naming.ConfigurationException; import org.apache.cloudstack.api.command.user.vmsnapshot.ListVMSnapshotCmd; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.subsystem.api.storage.StorageStrategyFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.VMSnapshotOptions; import org.apache.cloudstack.engine.subsystem.api.storage.VMSnapshotStrategy; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.log4j.Logger; @@ -310,7 +311,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana @Override @ActionEvent(eventType = EventTypes.EVENT_VM_SNAPSHOT_CREATE, eventDescription = "creating VM snapshot", async = true) - public VMSnapshot creatVMSnapshot(Long vmId, Long vmSnapshotId) { + public VMSnapshot creatVMSnapshot(Long vmId, Long vmSnapshotId, Boolean quiescevm) { UserVmVO userVm = _userVMDao.findById(vmId); if (userVm == null) { throw new InvalidParameterValueException("Create vm to snapshot failed due to vm: " + vmId + " is not found"); @@ -319,6 +320,8 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana if(vmSnapshot == null){ throw new CloudRuntimeException("VM snapshot id: " + vmSnapshotId + " can not be found"); } + VMSnapshotOptions options = new VMSnapshotOptions(quiescevm); + vmSnapshot.setOptions(options); try { VMSnapshotStrategy strategy = findVMSnapshotStrategy(vmSnapshot); VMSnapshot snapshot = strategy.takeVMSnapshot(vmSnapshot); diff --git a/server/src/org/apache/cloudstack/region/RegionManagerImpl.java b/server/src/org/apache/cloudstack/region/RegionManagerImpl.java index 40ac46c176c..74fa8feb4ba 100755 --- a/server/src/org/apache/cloudstack/region/RegionManagerImpl.java +++ b/server/src/org/apache/cloudstack/region/RegionManagerImpl.java @@ -30,6 +30,8 @@ import com.cloud.utils.PropertiesUtil; import com.cloud.utils.component.Manager; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.crypt.EncryptionSecretKeyChecker; +import com.cloud.utils.db.DbProperties; + import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; @@ -43,6 +45,7 @@ import org.springframework.stereotype.Component; import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -71,23 +74,7 @@ public class RegionManagerImpl extends ManagerBase implements RegionManager, Man @Override public boolean configure(final String name, final Map params) throws ConfigurationException { _name = name; - File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); - final Properties dbProps; - if (EncryptionSecretKeyChecker.useEncryption()) { - StandardPBEStringEncryptor encryptor = EncryptionSecretKeyChecker.getEncryptor(); - dbProps = new EncryptableProperties(encryptor); - } else { - dbProps = new Properties(); - } - try { - PropertiesUtil.loadFromFile(dbProps, dbPropsFile); - } catch (IOException e) { - s_logger.fatal("Unable to load db properties file, pl. check the classpath and file path configuration", e); - return false; - } catch (NullPointerException e) { - s_logger.fatal("Unable to locate db properties file within classpath or absolute path: db.properties"); - return false; - } + final Properties dbProps = DbProperties.getDbProperties(); String regionId = dbProps.getProperty("region.id"); _id = 1; if(regionId != null){ diff --git a/setup/db/db/schema-420to421.sql b/setup/db/db/schema-420to421.sql index e72e1b219c6..d429b30c014 100644 --- a/setup/db/db/schema-420to421.sql +++ b/setup/db/db/schema-420to421.sql @@ -215,4 +215,9 @@ CREATE VIEW `cloud`.`user_vm_view` AS left join `cloud`.`affinity_group` ON affinity_group_vm_map.affinity_group_id = affinity_group.id left join - `cloud`.`user_vm_details` as all_details ON all_details.vm_id = vm_instance.id; \ No newline at end of file + `cloud`.`user_vm_details` as all_details ON all_details.vm_id = vm_instance.id; + +--Add the format for volumes table for uploaded volumes (CLOUDSTACK-5013) +update `cloud`.`volumes` v, `cloud`.`volume_host_ref` vhr set v.format=vhr.format where v.id=vhr.volume_id and v.format is null; + + diff --git a/setup/db/db/schema-421to430.sql b/setup/db/db/schema-421to430.sql index 5d7ba4cc047..9c66744949d 100644 --- a/setup/db/db/schema-421to430.sql +++ b/setup/db/db/schema-421to430.sql @@ -119,6 +119,8 @@ UPDATE `cloud`.`vm_template` SET `removed`=NULL; ALTER TABLE `cloud`.`remote_access_vpn` MODIFY COLUMN `network_id` bigint unsigned; ALTER TABLE `cloud`.`remote_access_vpn` ADD COLUMN `vpc_id` bigint unsigned default NULL; +ALTER TABLE `cloud`.`s2s_vpn_connection` ADD COLUMN `passive` int(1) unsigned NOT NULL DEFAULT 0; + DROP VIEW IF EXISTS `cloud`.`disk_offering_view`; CREATE VIEW `cloud`.`disk_offering_view` AS select @@ -641,9 +643,6 @@ CREATE VIEW `cloud`.`storage_pool_view` AS and async_job.instance_type = 'StoragePool' and async_job.job_status = 0; - - DROP TABLE IF EXISTS `cloud`.`vm_snapshot_details`; - CREATE TABLE `cloud`.`firewall_rule_details` ( `id` bigint unsigned NOT NULL auto_increment, `firewall_rule_id` bigint unsigned NOT NULL COMMENT 'Firewall rule id', @@ -664,3 +663,10 @@ ALTER TABLE `cloud`.`user_vm_details` CHANGE `display_detail` `display` tinyint( ALTER TABLE `cloud`.`service_offering_details` ADD COLUMN `display` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'True if the detail can be displayed to the end user'; ALTER TABLE `cloud`.`storage_pool_details` ADD COLUMN `display` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'True if the detail can be displayed to the end user'; + +INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 'ldap.group.object', 'groupOfUniqueNames', +'Sets the object type of groups within LDAP','groupOfUniqueNames',NULL,NULL,0); +INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 'ldap.group.user.uniquemember', 'uniquemember', +'Sets the attribute for uniquemembers within a group','uniquemember',NULL,NULL,0); + +UPDATE `cloud`.`volumes` SET display_volume=1 where id>0; diff --git a/systemvm/patches/debian/config/etc/init.d/cloud-early-config b/systemvm/patches/debian/config/etc/init.d/cloud-early-config index d44f94d7d17..d4bf0eb3d92 100755 --- a/systemvm/patches/debian/config/etc/init.d/cloud-early-config +++ b/systemvm/patches/debian/config/etc/init.d/cloud-early-config @@ -130,12 +130,11 @@ get_boot_params() { vmware) vmtoolsd --cmd 'machine.id.get' > /var/cache/cloud/cmdline ;; - virtualpc) - # Hyper-V is recognized as virtualpc hypervisor type. Boot args are passed in the NTFS data-disk - mkdir -p $EXTRA_MOUNT - mount -t ntfs /dev/sdb1 $EXTRA_MOUNT - cp -f $EXTRA_MOUNT/cmdline /var/cache/cloud/cmdline - umount $EXTRA_MOUNT + virtualpc|hyperv) + # Hyper-V is recognized as virtualpc hypervisor type. Boot args are passed using KVP Daemon + #waiting for the hv_kvp_daemon to start up + #sleep 30 need to fix the race condition of hv_kvp_daemon and cloud-early-config + cp -f /var/opt/hyperv/.kvp_pool_0 /var/cache/cloud/cmdline ;; esac @@ -157,6 +156,10 @@ patch() { cdrom_dev=/dev/cdrom elif [ -e /dev/cdrom1 ]; then cdrom_dev=/dev/cdrom1 + elif [ -e /dev/cdrom2 ]; then + cdrom_dev=/dev/cdrom2 + elif [ -e /dev/cdrom3 ]; then + cdrom_dev=/dev/cdrom3 fi [ -f /var/cache/cloud/authorized_keys ] && privkey=/var/cache/cloud/authorized_keys @@ -718,7 +721,7 @@ setup_dnsmasq() { [ $ETH0_IP ] && echo "dhcp-option=6,$NS" >> /etc/dnsmasq.conf [ $ETH0_IP6 ] && echo "dhcp-option=option6:dns-server,$NS6" >> /etc/dnsmasq.conf #adding the name data-server to the /etc/hosts for allowing the access to user-data service and ssh-key reset in every subnet. - //removing the existing entires to avoid duplicates on restarts. +#removing the existing entires to avoid duplicates on restarts. sed -i '/data-server/d' /etc/hosts if [ -n "$ETH0_IP" ] then diff --git a/systemvm/patches/debian/config/etc/logrotate.d/cloud b/systemvm/patches/debian/config/etc/logrotate.d/cloud new file mode 100644 index 00000000000..37440ace69f --- /dev/null +++ b/systemvm/patches/debian/config/etc/logrotate.d/cloud @@ -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. +/var/log/cloud.log { + rotate 4 + daily + missingok + notifempty + compress + delaycompress + postrotate + pkill socat > /dev/null + endscript +} diff --git a/systemvm/patches/debian/config/opt/cloud/bin/ipsectunnel.sh b/systemvm/patches/debian/config/opt/cloud/bin/ipsectunnel.sh index e511a3d966a..e20c10f9e6d 100755 --- a/systemvm/patches/debian/config/opt/cloud/bin/ipsectunnel.sh +++ b/systemvm/patches/debian/config/opt/cloud/bin/ipsectunnel.sh @@ -30,7 +30,7 @@ vpnoutmark="0x525" vpninmark="0x524" usage() { - printf "Usage: %s: (-A|-D) -l -n -g -r -N -e -i -t -T -s -d \n" $(basename $0) >&2 + printf "Usage: %s: (-A|-D) -l -n -g -r -N -e -i -t -T -s -d [ -p ]\n" $(basename $0) >&2 } #set -x @@ -173,29 +173,35 @@ ipsec_tunnel_add() { sudo ipsec auto --rereadall sudo ipsec auto --add vpn-$rightpeer - sudo ipsec auto --up vpn-$rightpeer logger -t cloud "$(basename $0): done ipsec tunnel entry for right peer=$rightpeer right networks=$rightnets" - #5 seconds for checking if it's ready - for i in {1..5} - do - logger -t cloud "$(basename $0): checking connection status..." - /opt/cloud/bin/checks2svpn.sh $rightpeer - result=$? + result=0 + + if [ $passive -eq 0 ] + then + sudo ipsec auto --up vpn-$rightpeer + + #5 seconds for checking if it's ready + for i in {1..5} + do + logger -t cloud "$(basename $0): checking connection status..." + /opt/cloud/bin/checks2svpn.sh $rightpeer + result=$? + if [ $result -eq 0 ] + then + break + fi + sleep 1 + done if [ $result -eq 0 ] then - break + logger -t cloud "$(basename $0): connect to remote successful" + else + logger -t cloud "$(basename $0): fail to connect to remote, status code: $result" + logger -t cloud "$(basename $0): would stop site-to-site VPN connection" + ipsec_tunnel_del fi - sleep 1 - done - if [ $result -eq 0 ] - then - logger -t cloud "$(basename $0): connect to remote successful" - else - logger -t cloud "$(basename $0): fail to connect to remote, status code: $result" - logger -t cloud "$(basename $0): would stop site-to-site VPN connection" - ipsec_tunnel_del fi return $result } @@ -208,9 +214,10 @@ lflag= iflag= Iflag= sflag= +passive=0 op="" -while getopts 'ADl:n:g:r:N:e:i:t:T:s:d:' OPTION +while getopts 'ADpl:n:g:r:N:e:i:t:T:s:d:' OPTION do case $OPTION in A) opflag=1 @@ -252,6 +259,8 @@ do d) dflag=1 dpd="$OPTARG" ;; + p) passive=1 + ;; ?) usage unlock_exit 2 $lock $locked ;; diff --git a/test/integration/component/test_base_image_updation.py b/test/integration/component/test_base_image_updation.py new file mode 100644 index 00000000000..8a993505559 --- /dev/null +++ b/test/integration/component/test_base_image_updation.py @@ -0,0 +1,648 @@ +# 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. + +""" Component tests for Base Image Updation functionality + + Feature Specifications: https://cwiki.apache.org/confluence/display/CLOUDSTACK/Base+Image+Update+facility + + Test Plan: https://cwiki.apache.org/confluence/display/CLOUDSTACK/Base+Image+Updation+facility+TestPlan + + Issue Link: https://issues.apache.org/jira/browse/CLOUDSTACK-2243 +""" + +#Import Local Modules +import marvin +from marvin.codes import (PASS, + RECURRING) +from nose.plugins.attrib import attr +from marvin.cloudstackTestCase import cloudstackTestCase, unittest + +from marvin.integration.lib.base import (ServiceOffering, + Account, + VirtualMachine, + Volume, + Host, + Snapshot, + SnapshotPolicy, + Template + ) + +from marvin.integration.lib.common import (get_domain, + get_zone, + get_template, + list_templates + ) + +from marvin.integration.lib.utils import (validateList, + cleanup_resources) + +import time +from datetime import datetime, timedelta + +class Services: + """Test Base Image Updation + """ + + def __init__(self): + self.services = { + "account": { + "email": "test@test.com", + "firstname": "Test", + "lastname": "User", + "username": "test", + # Random characters are appended for unique + # username + "password": "password", + }, + "service_offering_with_reset": { + "name": "Tiny Instance With Reset", + "displaytext": "Tiny Instance With Reset", + "cpunumber": 1, + "cpuspeed": 100, + "memory": 128, + "isvolatile": True, + }, + "service_offering_without_reset": { + "name": "Tiny Instance Without Reset", + "displaytext": "Tiny Instance Without Reset", + "cpunumber": 1, + "cpuspeed": 100, + "memory": 128, + "isvolatile": False, + }, + "recurring_snapshot": { + "intervaltype": 'HOURLY', + # Frequency of snapshots + "maxsnaps": 2, # Should be min 2 + "schedule": 1, + "timezone": 'America/New_York', + # Timezone Formats - http://cloudstack.apache.org/docs/en-US/Apache_CloudStack/4.0.0-incubating/html-single/API_Developers_Guide/#time-zones + }, + "templates": { + # Configs for different Template formats + # For Eg. raw image, zip etc + "XenServer": { + "displaytext": "Public Template - Xen", + "name": "Public template - Xen", + "ostype": "CentOS 5.3 (64-bit)", + "url": "http://download.cloud.com/releases/2.0.0/UbuntuServer-10-04-64bit.vhd.bz2", + "hypervisor": "XenServer", + "format": "VHD", + "isfeatured": True, + "ispublic": True, + "isextractable": True, + }, + "KVM": { + "displaytext": "Public Template - KVM", + "name": "Public template -KVM", + "ostype": "CentOS 5.3 (64-bit)", + "url": "http://download.cloud.com/releases/2.0.0/UbuntuServer-10-04-64bit.qcow2.bz2", + "hypervisor": "KVM", + "format": "qcow2", + "isfeatured": True, + "ispublic": True, + "isextractable": True, + + } + }, + "template": { + "displaytext": "Cent OS Template 2", + "name": "Cent OS Template 2", + "ostype": "CentOS 5.3 (64-bit)", + "templatefilter": "self", + }, + "virtual_machine": { + "displayname": "Test VM", + "username": "root", + "password": "password", + "ssh_port": 22, + "hypervisor": "XenServer", + # Hypervisor type should be same as + # hypervisor type of cluster + "privateport": 22, + "publicport": 22, + "protocol": "TCP", + "userdata": "This is sample data", + }, + "ostype": "CentOS 5.3 (64-bit)", + # Cent OS 5.3 (64 bit) + "sleep": 60, + "retriesCount": 10, + "mode": "advanced" + } + + +class TestBaseImageUpdate(cloudstackTestCase): + + @classmethod + def setUpClass(cls): + cls.api_client = super( + TestBaseImageUpdate, + cls + ).getClsTestClient().getApiClient() + cls.services = Services().services + # Get Zone, Domain and templates + cls.domain = get_domain(cls.api_client, cls.services) + cls.zone = get_zone(cls.api_client, cls.services) + cls.template = get_template( + cls.api_client, + cls.zone.id, + cls.services["ostype"] + ) + cls.services["virtual_machine"]["zoneid"] = cls.zone.id + cls.services["virtual_machine"]["template"] = cls.template.id + + cls.service_offering_with_reset = ServiceOffering.create( + cls.api_client, + cls.services["service_offering_with_reset"] + ) + + cls.service_offering_without_reset = ServiceOffering.create( + cls.api_client, + cls.services["service_offering_without_reset"] + ) + + cls.account = Account.create( + cls.api_client, + cls.services["account"], + admin=True, + domainid=cls.domain.id + ) + + cls.vm_with_reset = VirtualMachine.create( + cls.api_client, + cls.services["virtual_machine"], + accountid=cls.account.name, + domainid=cls.account.domainid, + serviceofferingid=cls.service_offering_with_reset.id, + ) + cls.vm_with_reset_root_disk_id = cls.get_root_device_uuid_for_vm(cls.vm_with_reset.id, + cls.vm_with_reset.rootdeviceid) + + + cls.vm_without_reset = VirtualMachine.create( + cls.api_client, + cls.services["virtual_machine"], + accountid=cls.account.name, + domainid=cls.account.domainid, + serviceofferingid=cls.service_offering_without_reset.id, + ) + cls.vm_without_reset_root_disk_id = cls.get_root_device_uuid_for_vm(cls.vm_without_reset.id, + cls.vm_without_reset.rootdeviceid) + + cls._cleanup = [ + cls.account, + cls.service_offering_with_reset, + cls.service_offering_without_reset, + ] + return + + @classmethod + def tearDownClass(cls): + try: + #Cleanup resources used + cleanup_resources(cls.api_client, cls._cleanup) + except Exception as e: + raise Exception("Warning: Exception during cleanup : %s" % e) + return + + @classmethod + def get_root_device_uuid_for_vm(cls, vm_id, root_device_id): + volumes = Volume.list(cls.api_client, virtualmachineid=vm_id, listall=True) + return volumes[root_device_id].id + + def setUp(self): + self.apiclient = self.testClient.getApiClient() + self.dbclient = self.testClient.getDbConnection() + self.cleanup = [] + + return + + def tearDown(self): + try: + #Clean up, terminate the created network offerings + cleanup_resources(self.apiclient, self.cleanup) + except Exception as e: + raise Exception("Warning: Exception during cleanup : %s" % e) + return + + def verify_template_listing(self, template): + + retriesCount = int(self.services["retriesCount"]) + + template_list_validation_result = None + + while True: + list_template_response = list_templates( + self.apiclient, + templatefilter=\ + self.services["template"]["templatefilter"], + id=template.id, + zoneid=self.zone.id, + account=self.account.name, + domainid=self.account.domainid + ) + + template_list_validation_result = validateList(list_template_response) + + if template_list_validation_result[0] == PASS: + break + + elif retriesCount == 0: + self.fail("Failed to get the template list") + + # Sleep for 5 seconds and again continue the loop if retriesCount has not reached zero + time.sleep(5) + + #Reduce the retriesCount until it becomes zero, when it reaches zero, exception is raised + retriesCount = retriesCount - 1 + + template_response = template_list_validation_result[1] + + self.assertEqual( + template_response.isready, + True, + "Check isready of newly created template Expected :True Got:%s" %template_response.isready + ) + + return + + def test_01_deploy_instance_with_is_volatile_offering(self): + """ Test deploy an instance with service offerings with IsVolatile set. + """ + + # Validate the following + # 1. Service offerings were created successfully + # 2. Vms were successfully deployed with the service offerings. + + self.debug("Checking if deployed VMs are in running state...") + vms = VirtualMachine.list( + self.apiclient, + account=self.account.name, + domainid=self.account.domainid, + listall=True + ) + vm_list_validation_result = validateList(vms) + + self.assertEqual(vm_list_validation_result[0], PASS, "VM list validation failed due to %s" % + vm_list_validation_result[2]) + + for vm in vms: + self.debug("VM name: %s, VM state: %s" % (vm.name, vm.state)) + self.debug("%s" %vm) + self.assertEqual( + vm.state, + "Running", + "Vm state should be running for each VM deployed" + ) + return + + def test_02_reboot_instance_with_is_volatile_offering(self): + """ Test rebooting instances created with isVolatile service offerings + """ + + # Validate the following + # 1. Reboot the virtual machines. + # 2. Validate the following + # a. VM with created with isVolatile=True should have new Root disk but same IP + # b. VM with created with isVolatile=False should have same Root disk and IP as before reboot + + self.debug("Rebooting the virtual machines in account: %s" % + self.account.name) + try: + self.vm_with_reset.reboot(self.apiclient) + self.vm_without_reset.reboot(self.apiclient) + except Exception as e: + self.fail("Failed to reboot the virtual machines, %s" % e) + + # Check if the the root disk was destroyed and recreated for isVolatile=True + self.debug("Checking root disk of VM with isVolatile=True") + vms = VirtualMachine.list( + self.apiclient, + id=self.vm_with_reset.id, + listall=True + ) + + vm_list_validation_result = validateList(vms) + + self.assertEqual(vm_list_validation_result[0], PASS, "VM list validation failed due to %s" % + vm_list_validation_result[2]) + + vm_with_reset = vm_list_validation_result[1] + vm_with_reset_root_disk_id = self.get_root_device_uuid_for_vm(vm_with_reset.id, vm_with_reset.rootdeviceid) + + self.assertNotEqual(self.vm_with_reset_root_disk_id, + vm_with_reset_root_disk_id, + "VM created with IsVolatile=True has same rootdeviceid : %s after reboot" %vm_with_reset_root_disk_id + ) + # Make sure it has the same IP after reboot + self.assertEqual(self.vm_with_reset.nic[0].ipaddress, + vm_with_reset.nic[0].ipaddress, + "VM created with IsVolatile=True doesn't have same ip after reboot. Got : %s Expected : %s" + %(vm_with_reset.nic[0].ipaddress, self.vm_with_reset.nic[0].ipaddress) + ) + + # Check if the the root disk was not destroyed for isVolatile=False + self.debug("Checking root disk of VM with isVolatile=False") + vms = VirtualMachine.list( + self.apiclient, + id=self.vm_without_reset.id, + listall=True + ) + vm_list_validation_result = validateList(vms) + + self.assertEqual(vm_list_validation_result[0], PASS, "list validation failed due to %s" % + vm_list_validation_result[2]) + + vm_without_reset = vm_list_validation_result[1] + + vm_without_reset_root_disk_id = self.get_root_device_uuid_for_vm(vm_without_reset.id, + vm_without_reset.rootdeviceid) + + self.assertEqual(self.vm_without_reset_root_disk_id, + vm_without_reset_root_disk_id, + "VM created with IsVolatile=False has different rootdeviceid after reboot Got: %s Expected : %s" + %(vm_without_reset_root_disk_id, self.vm_without_reset_root_disk_id) + ) + + # Make sure it has the same IP after reboot + self.assertEqual(self.vm_without_reset.nic[0].ipaddress, + vm_without_reset.nic[0].ipaddress, + "VM created with IsVolatile=True doesn't have same ip after reboot. Got : %s Expected : %s" + %(vm_without_reset.nic[0].ipaddress, self.vm_without_reset.nic[0].ipaddress) + ) + + return + + def test_03_restore_vm_with_new_template(self): + """ Test restoring a vm with different template than the one it was created with + """ + + hosts = Host.list( + self.apiclient, + type="Routing", + listall=True + ) + + host_list_validation_result = validateList(hosts) + + self.assertEqual(host_list_validation_result[0], PASS, "host list validation failed due to %s" % + host_list_validation_result[2]) + + hypervisor = host_list_validation_result[1].hypervisor + + for k, v in self.services["templates"].items(): + if k == hypervisor: + # Register new template + template = Template.register( + self.apiclient, + v, + zoneid=self.zone.id, + account=self.account.name, + domainid=self.account.domainid + ) + self.debug( + "Registered a template of format: %s with ID: %s" % ( + v["format"], + template.id + )) + self.debug( + "Downloading template with ID: %s" % ( + template.id + )) + template.download(self.apiclient) + self.cleanup.append(template) + + # Wait for template status to be changed across + time.sleep(self.services["sleep"]) + + self.verify_template_listing(template) + + # Restore a vm with the new template. + self.vm_with_reset.restore(self.apiclient, templateid=template.id) + self.vm_without_reset.restore(self.apiclient, templateid=template.id) + + # Make sure the VMs now have the new template ID + # Make sure the Ip address of the VMs haven't changed + self.debug("Checking template id of VM with isVolatile=True") + vms = VirtualMachine.list( + self.apiclient, + id=self.vm_with_reset.id, + listall=True + ) + + vm_list_validation_result = validateList(vms) + + self.assertEqual(vm_list_validation_result[0], PASS, "VM list validation failed due to %s" % + vm_list_validation_result[2]) + + vm_with_reset = vm_list_validation_result[1] + + self.assertNotEqual(self.vm_with_reset.templateid, + vm_with_reset.templateid, + "VM created with IsVolatile=True has same templateid : %s after restore" %vm_with_reset.templateid + ) + + self.assertNotEqual(self.vm_with_reset.templateid, + template.id, + "VM created with IsVolatile=True has wrong templateid after restore Got:%s Expected: %s" + %(self.vm_with_reset.templateid, template.id) + ) + # Make sure it has the same IP after reboot + self.assertEqual(self.vm_with_reset.nic[0].ipaddress, + vm_with_reset.nic[0].ipaddress, + "VM created with IsVolatile=True doesn't have same ip after restore. Got : %s Expected : %s" + %(vm_with_reset.nic[0].ipaddress, self.vm_with_reset.nic[0].ipaddress) + ) + + # Check if the the root disk was not destroyed for isVolatile=False + self.debug("Checking template id of VM with isVolatile=False") + vms = VirtualMachine.list( + self.apiclient, + id=self.vm_without_reset.id, + listall=True + ) + + vm_list_validation_result = validateList(vms) + + self.assertEqual(vm_list_validation_result[0], PASS, "VM list validation failed due to %s" % + vm_list_validation_result[2]) + + vm_without_reset = vm_list_validation_result[1] + + self.assertNotEqual(self.vm_without_reset.templateid, + vm_without_reset.templateid, + "VM created with IsVolatile=False has same templateid : %s after restore" %vm_with_reset.templateid + ) + + self.assertNotEqual(self.vm_without_reset.templateid, + template.id, + "VM created with IsVolatile=False has wrong templateid after restore Got:%s Expected: %s" + %(self.vm_without_reset.templateid, template.id) + ) + # Make sure it has the same IP after reboot + self.assertEqual(self.vm_without_reset.nic[0].ipaddress, + vm_without_reset.nic[0].ipaddress, + "VM created with IsVolatile=False doesn't have same ip after restore. Got : %s Expected : %s" + %(vm_without_reset.nic[0].ipaddress, self.vm_without_reset.nic[0].ipaddress) + ) + + return + + def test_04_reoccuring_snapshot_rules(self): + """ + 1) Create a VM using the Service offering IsVolatile enabled + 2) Apply a recurring snapshot rule on the Volume. + 3) After a couple of snapshots are taken reboot the VM. + + Verify the following conditions + 1) New root disk should be formed + 2) The recurring snapshot rule should be deleted + """ + vms = VirtualMachine.list( + self.apiclient, + id=self.vm_with_reset.id, + listall=True + ) + + vm_list_validation_result = validateList(vms) + + self.assertEqual(vm_list_validation_result[0], PASS, "vm list validation failed due to %s" % + vm_list_validation_result[2]) + + vm_with_reset = vm_list_validation_result[1] + vm_with_reset_root_disk_id = self.get_root_device_uuid_for_vm( + vm_with_reset.id, + vm_with_reset.rootdeviceid + ) + + now = datetime.now() + delta = timedelta(minutes=15) + scheduled_time = now + delta + + self.services["recurring_snapshot"]["schedule"] = scheduled_time.minute + + self.debug("Creating recurring snapshot policy for root disk on vm created with IsVolatile=True") + self.debug("Snapshot Policy - Type : %s Scheduled minute : %s" %( + self.services["recurring_snapshot"]["intervaltype"], + self.services["recurring_snapshot"]["schedule"])) + + recurring_snapshot = SnapshotPolicy.create( + self.apiclient, + vm_with_reset_root_disk_id, + self.services["recurring_snapshot"] + ) + + #ListSnapshotPolicy should return newly created policy + list_snapshots_policy = SnapshotPolicy.list( + self.apiclient, + id=recurring_snapshot.id, + volumeid=vm_with_reset_root_disk_id + ) + + snapshot_list_validation_result = validateList(list_snapshots_policy) + + self.assertEqual(snapshot_list_validation_result[0], PASS, "snapshot list validation failed due to %s" % + snapshot_list_validation_result[2]) + + snapshots_policy = snapshot_list_validation_result[1] + + self.assertEqual( + snapshots_policy.id, + recurring_snapshot.id, + "Check recurring snapshot id in list resources call" + ) + self.assertEqual( + snapshots_policy.maxsnaps, + self.services["recurring_snapshot"]["maxsnaps"], + "Check interval type in list resources call" + ) + sleep_seconds = delta.seconds + 600 + sleep_minutes = sleep_seconds/60 + self.debug("Sleeping for %s minutes till the volume is snapshoted" %sleep_minutes) + time.sleep(sleep_seconds) + + retriesCount = self.services["retriesCount"] + while True: + snapshots = Snapshot.list( + self.apiclient, + volumeid=vm_with_reset_root_disk_id, + intervaltype=\ + self.services["recurring_snapshot"]["intervaltype"], + snapshottype=RECURRING, + listall=True + ) + + snapshot_list_validation_result = validateList(snapshots) + + if snapshot_list_validation_result[0] == PASS: + break + + elif retriesCount == 0: + self.fail("Failed to get snapshots list") + + time.sleep(60) + retriesCount = retriesCount - 1 + + # rebooting the vm with isVolatile = True + try: + self.vm_with_reset.reboot(self.apiclient) + except Exception as e: + self.fail("Failed to reboot the virtual machine. Error: %s" % e) + + # Check if the the root disk was destroyed and recreated for isVolatile=True + self.debug("Checking whether root disk of VM with isVolatile=True was destroyed") + vms = VirtualMachine.list( + self.apiclient, + id=self.vm_with_reset.id, + listall=True + ) + + vm_list_validation_result = validateList(vms) + + self.assertEqual(vm_list_validation_result[0], PASS, "list validation failed due to %s" % + vm_list_validation_result[2]) + + vm_with_reset_after_reboot = vm_list_validation_result[1] + + vm_with_reset_root_disk_id_after_reboot = self.get_root_device_uuid_for_vm( + vm_with_reset_after_reboot.id, + vm_with_reset_after_reboot.rootdeviceid + ) + + self.assertNotEqual(vm_with_reset_root_disk_id, + vm_with_reset_root_disk_id_after_reboot, + "VM created with IsVolatile=True has same rootdeviceid : %s after reboot" %vm_with_reset_root_disk_id_after_reboot + ) + # Make sure it has the same IP after reboot + self.assertEqual(vm_with_reset.nic[0].ipaddress, + vm_with_reset_after_reboot.nic[0].ipaddress, + "VM created with IsVolatile=True doesn't have same ip after reboot. Got : %s Expected : %s" + %(vm_with_reset_after_reboot.nic[0].ipaddress, vm_with_reset.nic[0].ipaddress) + ) + + # Check whether the recurring policy has been deleted from the database + self.debug("Checking whether snapshot rule for VM with isVolatile=True was destroyed \ + Here we are passing root disk id of vm before reboot which does not exist hence\ + listing should fail") + + with self.assertRaises(Exception): + list_snapshots_policy = SnapshotPolicy.list( + self.apiclient, + volumeid=vm_with_reset_root_disk_id + ) + return diff --git a/test/integration/component/test_deploy_vm_userdata_reg.py b/test/integration/component/test_deploy_vm_userdata_reg.py new file mode 100755 index 00000000000..ca9179d77d2 --- /dev/null +++ b/test/integration/component/test_deploy_vm_userdata_reg.py @@ -0,0 +1,220 @@ +# 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. + + +# this script will cover VMdeployment with Userdata tests + +from marvin.cloudstackTestCase import cloudstackTestCase +from marvin.integration.lib.base import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.common import * +from nose.plugins.attrib import attr +from marvin import remoteSSHClient +import unittest +import random +import string + +_multiprocess_shared_ = True +import os + +class Services: + def __init__(self): + self.services = { + "account": { + "email": "test@test.com", + "firstname": "Test", + "lastname": "User", + "username": "test", + "password": "password", + }, + "virtual_machine": { + "displayname": "TesVM1", + "username": "root", + "password": "password", + "ssh_port": 22, + "hypervisor": 'XenServer', + "privateport": 22, + "publicport": 22, + "protocol": 'TCP', + }, + "ostype": 'CentOS 5.3 (64-bit)', + "service_offering": { + "name": "Tiny Instance", + "displaytext": "Tiny Instance", + "cpunumber": 1, + "cpuspeed": 100, + "memory": 256, + }, + } + + + + + +class TestDeployVmWithUserData(cloudstackTestCase): + """Tests for UserData + """ + + @classmethod + def setUpClass(cls): + cls.apiClient = super(TestDeployVmWithUserData, cls).getClsTestClient().getApiClient() + cls.services = Services().services + cls.zone = get_zone(cls.apiClient, cls.services) + if cls.zone.localstorageenabled: + #For devcloud since localstroage is enabled + cls.services["service_offering"]["storagetype"] = "local" + cls.service_offering = ServiceOffering.create( + cls.apiClient, + cls.services["service_offering"] + ) + cls.account = Account.create(cls.apiClient, services=cls.services["account"]) + cls.cleanup = [cls.account] + cls.template = get_template( + cls.apiClient, + cls.zone.id, + cls.services["ostype"] + ) + # Generate userdata of 2500 bytes. This is larger than the 2048 bytes limit. + # CS however allows for upto 4K bytes in the code. So this must succeed. + # Overall, the query length must not exceed 4K, for then the json decoder + # will fail this operation at the marvin client side itcls. + + + cls.userdata = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(2500)) + cls.user_data_2k= ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(2000)) + cls.user_data_2kl = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(1900)) + + + + @attr(tags=["simulator", "devcloud", "basic", "advanced"]) + def test_deployvm_userdata_post(self): + """Test userdata as POST, size > 2k + """ + + + self.userdata=base64.b64encode(self.userdata) + self.services["virtual_machine"]["userdata"] = self.userdata + + deployVmResponse = VirtualMachine.create( + self.apiClient, + services=self.services["virtual_machine"], + accountid=self.account.name, + domainid=self.account.domainid, + serviceofferingid=self.service_offering.id, + templateid=self.template.id, + zoneid=self.zone.id, + method="POST" + + ) + + vms = list_virtual_machines( + self.apiClient, + account=self.account.name, + domainid=self.account.domainid, + id=deployVmResponse.id + ) + self.assert_(len(vms) > 0, "There are no Vms deployed in the account %s" % self.account.name) + vm = vms[0] + self.assert_(vm.id == str(deployVmResponse.id), "Vm deployed is different from the test") + self.assert_(vm.state == "Running", "VM is not in Running state") + ip_addr=deployVmResponse.ipaddress + if self.zone.networktype == "Basic": + list_router_response = list_routers( + self.apiClient, + listall="true" + ) + else: + list_router_response = list_routers( + self.apiClient, + account=self.account.name, + domainid=self.account.domainid + ) + self.assertEqual( + isinstance(list_router_response, list), + True, + "Check list response returns a valid list" + ) + router = list_router_response[0] + + hosts = list_hosts( + self.apiClient, + zoneid=router.zoneid, + type='Routing', + state='Up', + id=router.hostid + ) + self.assertEqual( + isinstance(hosts, list), + True, + "Check list host returns a valid list" + ) + host = hosts[0] + self.debug("Router ID: %s, state: %s" % (router.id, router.state)) + + self.assertEqual( + router.state, + 'Running', + "Check list router response for router state" + ) + host.user="root" + host.passwd="password" + cmd="cat /var/www/html/userdata/"+deployVmResponse.ipaddress+"/user-data" + + if self.apiClient.hypervisor.lower() == 'vmware': + + try: + result = get_process_status( + self.apiClient.connection.mgtSvr, + 22, + self.apiClient.connection.user, + self.apiClient.connection.passwd, + router.linklocalip, + cmd, + hypervisor=self.apiClient.hypervisor + ) + res = str(result) + self.assertEqual(res.__contains__(self.userdata),True,"Userdata Not applied Check the failures") + + + except KeyError: + self.skipTest("Marvin configuration has no host credentials to check USERDATA") + + else: + try: + result = get_process_status( + host.ipaddress, + 22, + host.user, + host.passwd, + router.linklocalip, + cmd + ) + res = str(result) + self.assertEqual(res.__contains__(self.userdata),True,"Userdata Not applied Check the failures") + except KeyError: + self.skipTest("Marvin configuration has no host credentials to check router user data") + + + + @classmethod + def tearDownClass(cls): + try: + #Cleanup resources used + cleanup_resources(cls.apiClient, cls.cleanup) + + except Exception as e: + raise Exception("Warning: Exception during cleanup : %s" % e) diff --git a/test/integration/component/test_reset_ssh_keypair.py b/test/integration/component/test_reset_ssh_keypair.py index 4d0c45e9e17..7530335e4a9 100644 --- a/test/integration/component/test_reset_ssh_keypair.py +++ b/test/integration/component/test_reset_ssh_keypair.py @@ -19,13 +19,28 @@ """ #Import Local Modules -from marvin.cloudstackTestCase import * -from marvin.integration.lib.base import * -from marvin.integration.lib.common import * +from marvin.integration.lib.base import (VirtualMachine, + SSHKeyPair, + Account, + Template, + ServiceOffering, + EgressFireWallRule) +from marvin.integration.lib.common import (get_domain, + get_zone, + get_template, + list_virtual_machines, + list_volumes) +from marvin.integration.lib.utils import (cleanup_resources, + random_gen, + validateList) +from marvin.cloudstackTestCase import cloudstackTestCase, unittest +from marvin.codes import PASS, RUNNING + #Import System modules import tempfile import os from nose.plugins.attrib import attr +import time class Services: @@ -82,17 +97,12 @@ class Services: "mode": 'advanced', } -def wait_vm_start(apiclient, account, timeout, sleep): +def wait_vm_start(apiclient, vmid, timeout, sleep): while timeout: - vms = VirtualMachine.list( - apiclient, - account=account.name, - domainid=account.domainid, - listall=True - ) - if vms and vms[0].state == "Running": + vms = VirtualMachine.list(apiclient, id=vmid) + vm_list_validation_result = validateList(vms) + if vm_list_validation_result[0] == PASS and vm_list_validation_result[1].state == RUNNING: return timeout - time.sleep(sleep) timeout = timeout - 1 @@ -363,7 +373,7 @@ class TestResetSSHKeypair(cloudstackTestCase): self.fail("Failed to start virtual machine: %s, %s" % (virtual_machine.name, e)) - timeout = wait_vm_start(self.apiclient, self.account, self.services["timeout"], + timeout = wait_vm_start(self.apiclient, virtual_machine.id, self.services["timeout"], self.services["sleep"]) if timeout == 0: @@ -473,7 +483,7 @@ class TestResetSSHKeypair(cloudstackTestCase): self.fail("Failed to start virtual machine: %s, %s" % (virtual_machine.name, e)) - timeout = wait_vm_start(self.apiclient, self.account, self.services["timeout"], + timeout = wait_vm_start(self.apiclient, virtual_machine.id, self.services["timeout"], self.services["sleep"]) if timeout == 0: @@ -583,7 +593,7 @@ class TestResetSSHKeypair(cloudstackTestCase): self.fail("Failed to start virtual machine: %s, %s" % (virtual_machine.name, e)) - timeout = wait_vm_start(self.apiclient, self.account, self.services["timeout"], + timeout = wait_vm_start(self.apiclient, virtual_machine.id, self.services["timeout"], self.services["sleep"]) if timeout == 0: @@ -694,7 +704,7 @@ class TestResetSSHKeypair(cloudstackTestCase): self.fail("Failed to start virtual machine: %s, %s" % (virtual_machine.name, e)) - timeout = wait_vm_start(self.apiclient, self.account, self.services["timeout"], + timeout = wait_vm_start(self.apiclient, virtual_machine.id, self.services["timeout"], self.services["sleep"]) if timeout == 0: @@ -1207,7 +1217,7 @@ class TestResetSSHKeyUserRights(cloudstackTestCase): self.fail("Failed to start virtual machine: %s, %s" % (virtual_machine.name, e)) - timeout = wait_vm_start(self.apiclient, self.account, self.services["timeout"], + timeout = wait_vm_start(self.apiclient, virtual_machine.id, self.services["timeout"], self.services["sleep"]) if timeout == 0: @@ -1346,7 +1356,7 @@ class TestResetSSHKeyUserRights(cloudstackTestCase): self.fail("Failed to start virtual machine: %s, %s" % (virtual_machine.name, e)) - timeout = wait_vm_start(self.apiclient, self.account, self.services["timeout"], + timeout = wait_vm_start(self.apiclient, virtual_machine.id, self.services["timeout"], self.services["sleep"]) if timeout == 0: @@ -1486,7 +1496,7 @@ class TestResetSSHKeyUserRights(cloudstackTestCase): self.fail("Failed to start virtual machine: %s, %s" % (virtual_machine.name, e)) - timeout = wait_vm_start(self.apiclient, self.account, self.services["timeout"], + timeout = wait_vm_start(self.apiclient, virtual_machine.id, self.services["timeout"], self.services["sleep"]) if timeout == 0: diff --git a/test/integration/component/test_shared_network_offering.py b/test/integration/component/test_shared_network_offering.py deleted file mode 100644 index 85f08922069..00000000000 --- a/test/integration/component/test_shared_network_offering.py +++ /dev/null @@ -1,213 +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. - -import marvin -from nose.plugins.attrib import attr -from marvin.cloudstackTestCase import * -from marvin.cloudstackAPI import * -from marvin.integration.lib.utils import * -from marvin.integration.lib.base import * -from marvin.integration.lib.common import * - - -class Services: - """Test network offering Services - """ - - def __init__(self): - self.services = { - "account": { - "email": "test@test.com", - "firstname": "Test", - "lastname": "User", - "username": "test", - # Random characters are appended for unique - # username - "password": "password", - }, - "service_offering": { - "name": "Tiny Instance", - "displaytext": "Tiny Instance", - "cpunumber": 1, - "cpuspeed": 100, # in MHz - "memory": 128, # In MBs - }, - "network_offering": { - "name": 'Network offering-VR services', - "displaytext": 'Network offering-VR services', - "guestiptype": 'Isolated', - "supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,Vpn,Firewall,Lb,UserData,StaticNat', - "traffictype": 'GUEST', - "availability": 'Optional', - "serviceProviderList": { - "Dhcp": 'VirtualRouter', - "Dns": 'VirtualRouter', - "SourceNat": 'VirtualRouter', - "PortForwarding": 'VirtualRouter', - "Vpn": 'VirtualRouter', - "Firewall": 'VirtualRouter', - "Lb": 'VirtualRouter', - "UserData": 'VirtualRouter', - "StaticNat": 'VirtualRouter', - }, - }, - "network": { - "name": "Test Network", - "displaytext": "Test Network", - "vlan" : 3111, - "startip": "172.16.15.2", - "endip" : "172.16.15.10", - "gateway" : "172.16.15.1", - "netmask" : "255.255.255.0", - }, - "virtual_machine": { - "displayname": "Test VM", - "username": "root", - "password": "password", - "ssh_port": 22, - "hypervisor": 'XenServer', - # Hypervisor type should be same as - # hypervisor type of cluster - "privateport": 22, - "publicport": 22, - "protocol": 'TCP', - }, - "ostype": 'CentOS 5.3 (64-bit)', - # Cent OS 5.3 (64 bit) - "sleep": 60, - "timeout": 10, - } - -class TestSharedNetworkWithoutIp(cloudstackTestCase): - - @classmethod - def setUpClass(cls): - cls.api_client = super( - TestSharedNetworkWithoutIp, - cls - ).getClsTestClient().getApiClient() - cls.services = Services().services - # Get Zone, Domain and templates - cls.domain = get_domain(cls.api_client, cls.services) - cls.zone = get_zone(cls.api_client, cls.services) - cls.services['mode'] = cls.zone.networktype - cls.template = get_template( - cls.api_client, - cls.zone.id, - cls.services["ostype"] - ) - cls.services["virtual_machine"]["zoneid"] = cls.zone.id - cls.services["virtual_machine"]["template"] = cls.template.id - - cls.service_offering = ServiceOffering.create( - cls.api_client, - cls.services["service_offering"] - ) - - cls._cleanup = [ - cls.service_offering, - ] - return - - @classmethod - def tearDownClass(cls): - try: - #Cleanup resources used - cleanup_resources(cls.api_client, cls._cleanup) - except Exception as e: - raise Exception("Warning: Exception during cleanup : %s" % e) - return - - def setUp(self): - self.apiclient = self.testClient.getApiClient() - self.dbclient = self.testClient.getDbConnection() - self.account = Account.create( - self.apiclient, - self.services["account"], - admin=True, - domainid=self.domain.id - ) - self.cleanup = [] - return - - def tearDown(self): - try: - self.account.delete(self.apiclient) - cleanup_resources(self.apiclient, self.cleanup) - except Exception as e: - raise Exception("Warning: Exception during cleanup : %s" % e) - return - - @attr(tags=["advanced", "advancedns", "simulator", "network", "api"]) - def test_deployVmSharedNetworkWithoutIpRange(self): - """Test deployVM in shared network without startIp/endIp - """ - - # Steps for validation - # 1. create a shared network using shared network offering but do not - # specify startIp/endIp arguments - # 2. create an account - # 3. deploy a VM in this account using the above network - # Validate the following - # 1. listNetworks should return the created network - # 2. listAccounts to return the created account - # 3. VM deployment should succeed and NIC is in networks address space - # 4. delete the account - - self.debug( - "Fetching default shared network offering from nw offerings") - network_offerings = NetworkOffering.list( - self.apiclient, - listall=True, - guestiptype="Shared", - name="DefaultSharedNetworkOffering", - displaytext="Offering for Shared networks" - ) - self.assertEqual( - isinstance(network_offerings, list), - True, - "Nw offerings should have atleast a shared nw offering" - ) - shared_nw_off = network_offerings[0] - self.debug("Shared netwrk offering: %s" % shared_nw_off.name) - - self.debug("Creating a network from shared network offering") - self.network = Network.create( - self.apiclient, - self.services["network"], - accountid=self.account.name, - domainid=self.account.domainid, - networkofferingid=shared_nw_off.id, - zoneid=self.zone.id - ) - self.debug("Created network with ID: %s" % self.network.id) - - self.debug("Deploying VM in account: %s" % self.account.name) - try: - # Spawn an instance in that network - VirtualMachine.create( - self.apiclient, - self.services["virtual_machine"], - accountid=self.account.name, - domainid=self.account.domainid, - serviceofferingid=self.service_offering.id, - networkids=[str(self.network.id)] - ) - self.debug("Deployed VM in network: %s" % self.network.id) - except Exception as e: - self.fail("Deply Vm in shared network failed! - %s" % e) - return \ No newline at end of file diff --git a/test/integration/component/test_shared_networks.py b/test/integration/component/test_shared_networks.py index 732e1447b50..66a9d266dac 100644 --- a/test/integration/component/test_shared_networks.py +++ b/test/integration/component/test_shared_networks.py @@ -18,13 +18,27 @@ """ P1 tests for shared networks """ #Import Local Modules -import marvin from nose.plugins.attrib import attr -from marvin.cloudstackTestCase import * -from marvin.cloudstackAPI import * -from marvin.integration.lib.utils import * -from marvin.integration.lib.base import * -from marvin.integration.lib.common import * +from marvin.cloudstackTestCase import cloudstackTestCase, unittest +from marvin.integration.lib.base import (Account, + Network, + NetworkOffering, + VirtualMachine, + Project, + PhysicalNetwork, + Domain, + StaticNATRule, + FireWallRule, + ServiceOffering, + PublicIPAddress) +from marvin.integration.lib.utils import (cleanup_resources, + xsplit) +from marvin.integration.lib.common import (get_domain, + get_zone, + get_template, + wait_for_cleanup) +import random + import netaddr class Services: @@ -72,20 +86,20 @@ class Services: "network": { "name": "MySharedNetwork - Test", "displaytext": "MySharedNetwork", - "gateway" :"172.16.15.1", + "gateway" :"", "netmask" :"255.255.255.0", - "startip" :"172.16.15.2", - "endip" :"172.16.15.20", + "startip" :"", + "endip" :"", "acltype" : "Domain", "scope":"all", }, "network1": { "name": "MySharedNetwork - Test1", "displaytext": "MySharedNetwork1", - "gateway" :"172.16.16.1", + "gateway" :"", "netmask" :"255.255.255.0", - "startip" :"172.16.16.21", - "endip" :"172.16.16.41", + "startip" :"", + "endip" :"", "acltype" : "Domain", "scope":"all", }, @@ -134,16 +148,16 @@ class Services: "timeout": 10, "mode": 'advanced' } - + class TestSharedNetworks(cloudstackTestCase): - + @classmethod def setUpClass(cls): cls.api_client = super( TestSharedNetworks, cls ).getClsTestClient().getApiClient() - + cls.services = Services().services # Get Zone, Domain and templates @@ -154,7 +168,7 @@ class TestSharedNetworks(cloudstackTestCase): cls.zone.id, cls.services["ostype"] ) - + cls.services["virtual_machine"]["zoneid"] = cls.zone.id cls.services["virtual_machine"]["template"] = cls.template.id @@ -162,7 +176,7 @@ class TestSharedNetworks(cloudstackTestCase): cls.api_client, cls.services["service_offering"] ) - + cls._cleanup = [ cls.service_offering, ] @@ -180,6 +194,19 @@ class TestSharedNetworks(cloudstackTestCase): def setUp(self): self.api_client = self.testClient.getApiClient() self.dbclient = self.testClient.getDbConnection() + + # Set the subnet number of shared networks randomly prior to execution + # of each test case to avoid overlapping of ip addresses + shared_network_subnet_number = random.randrange(1,254) + + self.services["network"]["gateway"] = "172.16."+str(shared_network_subnet_number)+".1" + self.services["network"]["startip"] = "172.16."+str(shared_network_subnet_number)+".2" + self.services["network"]["endip"] = "172.16."+str(shared_network_subnet_number)+".20" + + self.services["network1"]["gateway"] = "172.16."+str(shared_network_subnet_number + 1)+".1" + self.services["network1"]["startip"] = "172.16."+str(shared_network_subnet_number + 1)+".2" + self.services["network1"]["endip"] = "172.16."+str(shared_network_subnet_number + 1)+".20" + self.cleanup = [] self.cleanup_networks = [] self.cleanup_accounts = [] @@ -194,7 +221,7 @@ class TestSharedNetworks(cloudstackTestCase): cleanup_resources(self.api_client, self.cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) - + #below components is not a part of cleanup because to mandate the order and to cleanup network try: for vm in self.cleanup_vms: @@ -204,16 +231,16 @@ class TestSharedNetworks(cloudstackTestCase): try: for project in self.cleanup_projects: - project.delete(self.api_client) + project.delete(self.api_client) except Exception as e: raise Exception("Warning: Exception during project cleanup : %s" % e) try: for account in self.cleanup_accounts: - account.delete(self.api_client) + account.delete(self.api_client) except Exception as e: raise Exception("Warning: Exception during account cleanup : %s" % e) - + #Wait till all resources created are cleaned up completely and then attempt to delete domains wait_for_cleanup(self.api_client, ["account.cleanup.interval"]) @@ -262,11 +289,11 @@ class TestSharedNetworks(cloudstackTestCase): @attr(tags=["advanced", "advancedns"]) def test_sharedNetworkOffering_01(self): """ Test shared network Offering 01 """ - + # Steps, # 1. create an Admin Account - admin-XABU1 # 2. listPhysicalNetworks in available zone - # 3. createNetworkOffering: + # 3. createNetworkOffering: # - name = "MySharedOffering" # - guestiptype="shared" # - services = {Dns, Dhcp, UserData} @@ -288,9 +315,9 @@ class TestSharedNetworks(cloudstackTestCase): admin=True, domainid=self.domain.id ) - + self.cleanup_accounts.append(self.account) - + #verify that the account got created with state enabled list_accounts_response = Account.list( self.api_client, @@ -314,7 +341,7 @@ class TestSharedNetworks(cloudstackTestCase): ) self.debug("Admin Type account created: %s" % self.account.name) - + #Verify that there should be at least one physical network present in zone. list_physical_networks_response = PhysicalNetwork.list( self.api_client, @@ -332,19 +359,19 @@ class TestSharedNetworks(cloudstackTestCase): ) physical_network = list_physical_networks_response[0] - + self.debug("Physical network found: %s" % physical_network.id) - + self.services["network_offering"]["specifyVlan"] = "True" self.services["network_offering"]["specifyIpRanges"] = "True" - + #Create Network Offering self.shared_network_offering = NetworkOffering.create( self.api_client, self.services["network_offering"], conservemode=False ) - + #Verify that the network offering got created list_network_offerings_response = NetworkOffering.list( self.api_client, @@ -365,14 +392,14 @@ class TestSharedNetworks(cloudstackTestCase): "Disabled", "The network offering created should be bydefault disabled." ) - + #Update network offering state from disabled to enabled. - network_offering_update_response = NetworkOffering.update( - self.shared_network_offering, - self.api_client, - id=self.shared_network_offering.id, - state="enabled" - ) + NetworkOffering.update( + self.shared_network_offering, + self.api_client, + id=self.shared_network_offering.id, + state="enabled" + ) #Verify that the state of the network offering is updated list_network_offerings_response = NetworkOffering.list( self.api_client, @@ -398,11 +425,11 @@ class TestSharedNetworks(cloudstackTestCase): @attr(tags=["advanced", "advancedns"]) def test_sharedNetworkOffering_02(self): """ Test Shared Network Offering 02 """ - + # Steps, # 1. create an Admin Account - admin-XABU1 # 2. listPhysicalNetworks in available zone - # 3. createNetworkOffering: + # 3. createNetworkOffering: # - name = "MySharedOffering" # - guestiptype="shared" # - services = {Dns, Dhcp, UserData} @@ -414,7 +441,7 @@ class TestSharedNetworks(cloudstackTestCase): # 1. listAccounts name=admin-XABU1, state=enabled returns your account # 2. listPhysicalNetworks should return at least one active physical network # 3. createNetworkOffering fails - vlan should be specified in advanced zone - + #Create an account self.account = Account.create( self.api_client, @@ -422,9 +449,9 @@ class TestSharedNetworks(cloudstackTestCase): admin=True, domainid=self.domain.id ) - + self.cleanup_accounts.append(self.account) - + #verify that the account got created with state enabled list_accounts_response = Account.list( self.api_client, @@ -446,9 +473,9 @@ class TestSharedNetworks(cloudstackTestCase): "enabled", "The admin account created is not enabled." ) - + self.debug("Admin type account created: %s" % self.account.name) - + #Verify that there should be at least one physical network present in zone. list_physical_networks_response = PhysicalNetwork.list( self.api_client, @@ -464,14 +491,14 @@ class TestSharedNetworks(cloudstackTestCase): 0, "listPhysicalNetworks should return at least one physical network." ) - + physical_network = list_physical_networks_response[0] - + self.debug("Physical network found: %s" % physical_network.id) - + self.services["network_offering"]["specifyVlan"] = "False" self.services["network_offering"]["specifyIpRanges"] = "False" - + try: #Create Network Offering self.shared_network_offering = NetworkOffering.create( @@ -481,16 +508,17 @@ class TestSharedNetworks(cloudstackTestCase): ) self.fail("Network offering got created with vlan as False in advance mode and shared guest type, which is invalid case.") except Exception as e: - self.debug("Network Offering creation failed with vlan as False in advance mode and shared guest type.") + self.debug("Network Offering creation failed with vlan as False in advance mode and shared guest type. Exception: %s" % + e) @attr(tags=["advanced", "advancedns"]) def test_sharedNetworkOffering_03(self): """ Test Shared Network Offering 03 """ - + # Steps, # 1. create an Admin Account - admin-XABU1 # 2. listPhysicalNetworks in available zone - # 3. createNetworkOffering: + # 3. createNetworkOffering: # - name = "MySharedOffering" # - guestiptype="shared" # - services = {Dns, Dhcp, UserData} @@ -503,7 +531,7 @@ class TestSharedNetworks(cloudstackTestCase): # 2. listPhysicalNetworks should return at least one active physical network # 3. createNetworkOffering fails - ip ranges should be specified when creating shared network offering - + #Create an account self.account = Account.create( self.api_client, @@ -511,9 +539,9 @@ class TestSharedNetworks(cloudstackTestCase): admin=True, domainid=self.domain.id ) - + self.cleanup_accounts.append(self.account) - + #verify that the account got created with state enabled list_accounts_response = Account.list( self.api_client, @@ -535,9 +563,9 @@ class TestSharedNetworks(cloudstackTestCase): "enabled", "The admin account created is not enabled." ) - + self.debug("Admin Type account created: %s" % self.account.name) - + #Verify that there should be at least one physical network present in zone. list_physical_networks_response = PhysicalNetwork.list( self.api_client, @@ -553,14 +581,14 @@ class TestSharedNetworks(cloudstackTestCase): 0, "listPhysicalNetworks should return at least one physical network." ) - + physical_network = list_physical_networks_response[0] - + self.debug("Physical Network found: %s" % physical_network.id) - + self.services["network_offering"]["specifyVlan"] = "True" self.services["network_offering"]["specifyIpRanges"] = "False" - + try: #Create Network Offering self.shared_network_offering = NetworkOffering.create( @@ -570,16 +598,17 @@ class TestSharedNetworks(cloudstackTestCase): ) self.fail("Network offering got created with vlan as True and ip ranges as False in advance mode and with shared guest type, which is invalid case.") except Exception as e: - self.debug("Network Offering creation failed with vlan as true and ip ranges as False in advance mode and with shared guest type.") + self.debug("Network Offering creation failed with vlan as true and ip ranges as False in advance mode and with shared guest type.\ + Exception : %s" % e) @attr(tags=["advanced", "advancedns"]) def test_createSharedNetwork_All(self): """ Test Shared Network ALL """ - + # Steps, # 1. create an Admin Account - admin-XABU1 # 2. listPhysicalNetworks in available zone - # 3. createNetworkOffering: + # 3. createNetworkOffering: # - name = "MySharedOffering" # - guestiptype="shared" # - services = {Dns, Dhcp, UserData} @@ -605,7 +634,7 @@ class TestSharedNetworks(cloudstackTestCase): # 6. No checks reqd # 7. a. listVirtualMachines should show both VMs in running state in the user account and the admin account # b. VM's IPs shoud be in the range of the shared network ip ranges - + #Create admin account self.admin_account = Account.create( self.api_client, @@ -613,9 +642,9 @@ class TestSharedNetworks(cloudstackTestCase): admin=True, domainid=self.domain.id ) - + self.cleanup_accounts.append(self.admin_account) - + #verify that the account got created with state enabled list_accounts_response = Account.list( self.api_client, @@ -637,9 +666,9 @@ class TestSharedNetworks(cloudstackTestCase): "enabled", "The admin account created is not enabled." ) - + self.debug("Admin type account created: %s" % self.admin_account.name) - + #Create an user account self.user_account = Account.create( self.api_client, @@ -647,9 +676,9 @@ class TestSharedNetworks(cloudstackTestCase): admin=False, domainid=self.domain.id ) - + self.cleanup_accounts.append(self.user_account) - + #verify that the account got created with state enabled list_accounts_response = Account.list( self.api_client, @@ -671,27 +700,27 @@ class TestSharedNetworks(cloudstackTestCase): "enabled", "The user account created is not enabled." ) - + self.debug("User type account created: %s" % self.user_account.name) - + physical_network, shared_vlan = self.getFreeVlan(self.api_client, self.zone.id) - + self.debug("Physical network found: %s" % physical_network.id) - + self.services["network_offering"]["specifyVlan"] = "True" self.services["network_offering"]["specifyIpRanges"] = "True" - + #Create Network Offering self.shared_network_offering = NetworkOffering.create( self.api_client, self.services["network_offering"], conservemode=False ) - - #Verify that the network offering got created + + #Verify that the network offering got created list_network_offerings_response = NetworkOffering.list( self.api_client, id=self.shared_network_offering.id @@ -711,17 +740,17 @@ class TestSharedNetworks(cloudstackTestCase): "Disabled", "The network offering created should be bydefault disabled." ) - + self.debug("Shared Network offering created: %s" % self.shared_network_offering.id) - + #Update network offering state from disabled to enabled. - network_offering_update_response = NetworkOffering.update( - self.shared_network_offering, - self.api_client, - id=self.shared_network_offering.id, - state="enabled" - ) - + NetworkOffering.update( + self.shared_network_offering, + self.api_client, + id=self.shared_network_offering.id, + state="enabled" + ) + #Verify that the state of the network offering is updated list_network_offerings_response = NetworkOffering.list( self.api_client, @@ -742,7 +771,7 @@ class TestSharedNetworks(cloudstackTestCase): "Enabled", "The network offering state should get updated to Enabled." ) - + #create network using the shared network offering created self.services["network"]["acltype"] = "Domain" self.services["network"]["networkofferingid"] = self.shared_network_offering.id @@ -755,7 +784,7 @@ class TestSharedNetworks(cloudstackTestCase): networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id, ) - + self.cleanup_networks.append(self.network) list_networks_response = Network.list( @@ -777,18 +806,18 @@ class TestSharedNetworks(cloudstackTestCase): True, "The network is created with ip range but the flag is set to False." ) - + self.debug("Shared Network created for scope domain: %s" % self.network.id) - + self.admin_account_virtual_machine = VirtualMachine.create( self.api_client, self.services["virtual_machine"], networkids=self.network.id, serviceofferingid=self.service_offering.id ) - + self.cleanup_vms.append(self.admin_account_virtual_machine) - + vms = VirtualMachine.list( self.api_client, id=self.admin_account_virtual_machine.id, @@ -804,13 +833,13 @@ class TestSharedNetworks(cloudstackTestCase): 0, "listVirtualMachines returned empty list." ) - + self.debug("Virtual Machine created: %s" % self.admin_account_virtual_machine.id) - + ip_range = list(netaddr.iter_iprange(unicode(self.services["network"]["startip"]), unicode(self.services["network"]["endip"]))) if netaddr.IPAddress(unicode(vms[0].nic[0].ipaddress)) not in ip_range: self.fail("Virtual machine ip should be from the ip range assigned to network created.") - + self.user_account_virtual_machine = VirtualMachine.create( self.api_client, self.services["virtual_machine"], @@ -836,7 +865,7 @@ class TestSharedNetworks(cloudstackTestCase): ) self.debug("Virtual Machine created: %s" % self.user_account_virtual_machine.id) - + ip_range = list(netaddr.iter_iprange(unicode(self.services["network"]["startip"]), unicode(self.services["network"]["endip"]))) if netaddr.IPAddress(unicode(vms[0].nic[0].ipaddress)) not in ip_range: self.fail("Virtual machine ip should be from the ip range assigned to network created.") @@ -844,12 +873,12 @@ class TestSharedNetworks(cloudstackTestCase): @attr(tags=["advanced", "advancedns"]) def test_createSharedNetwork_accountSpecific(self): """ Test Shared Network with scope account """ - + # Steps, # 1. create an Admin Account - admin-XABU1 # create a user account = user-SOPJD # 2. listPhysicalNetworks in available zone - # 3. createNetworkOffering: + # 3. createNetworkOffering: # - name = "MySharedOffering" # - guestiptype="shared" # - services = {Dns, Dhcp, UserData} @@ -874,7 +903,7 @@ class TestSharedNetworks(cloudstackTestCase): # 6. VM deployed in admin account should FAIL to deploy # VM should be deployed in user account only # verify VM's IP is within shared network range - + #Create admin account self.admin_account = Account.create( self.api_client, @@ -884,7 +913,7 @@ class TestSharedNetworks(cloudstackTestCase): ) self.cleanup_accounts.append(self.admin_account) - + #verify that the account got created with state enabled list_accounts_response = Account.list( self.api_client, @@ -906,9 +935,9 @@ class TestSharedNetworks(cloudstackTestCase): "enabled", "The admin account created is not enabled." ) - + self.debug("Admin type account created: %s" % self.admin_account.name) - + #Create an user account self.user_account = Account.create( self.api_client, @@ -916,9 +945,9 @@ class TestSharedNetworks(cloudstackTestCase): admin=False, domainid=self.domain.id ) - + self.cleanup_accounts.append(self.user_account) - + #verify that the account got created with state enabled list_accounts_response = Account.list( self.api_client, @@ -940,13 +969,13 @@ class TestSharedNetworks(cloudstackTestCase): "enabled", "The user account created is not enabled." ) - + self.debug("User type account created: %s" % self.user_account.name) - + physical_network, shared_vlan = self.getFreeVlan(self.api_client, self.zone.id) - + self.debug("Physical Network found: %s" % physical_network.id) - + self.services["network_offering"]["specifyVlan"] = "True" self.services["network_offering"]["specifyIpRanges"] = "True" @@ -955,8 +984,8 @@ class TestSharedNetworks(cloudstackTestCase): self.api_client, self.services["network_offering"], conservemode=False - ) - + ) + #Verify that the network offering got created list_network_offerings_response = NetworkOffering.list( self.api_client, @@ -977,16 +1006,16 @@ class TestSharedNetworks(cloudstackTestCase): "Disabled", "The network offering created should be by default disabled." ) - + self.debug("Shared Network Offering created: %s" % self.shared_network_offering.id) - + #Update network offering state from disabled to enabled. - network_offering_update_response = NetworkOffering.update( - self.shared_network_offering, - self.api_client, - id=self.shared_network_offering.id, - state="enabled" - ) + NetworkOffering.update( + self.shared_network_offering, + self.api_client, + id=self.shared_network_offering.id, + state="enabled" + ) #Verify that the state of the network offering is updated list_network_offerings_response = NetworkOffering.list( self.api_client, @@ -1007,13 +1036,13 @@ class TestSharedNetworks(cloudstackTestCase): "Enabled", "The network offering state should get updated to Enabled." ) - + #create network using the shared network offering created self.services["network"]["acltype"] = "Account" self.services["network"]["networkofferingid"] = self.shared_network_offering.id self.services["network"]["physicalnetworkid"] = physical_network.id self.services["network"]["vlan"] = shared_vlan - + self.network = Network.create( self.api_client, self.services["network"], @@ -1022,9 +1051,9 @@ class TestSharedNetworks(cloudstackTestCase): networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id ) - + self.cleanup_networks.append(self.network) - + list_networks_response = Network.list( self.api_client, id=self.network.id @@ -1044,9 +1073,9 @@ class TestSharedNetworks(cloudstackTestCase): True, "The network is created with ip range but the flag is set to False." ) - + self.debug("Network created: %s" % self.network.id) - + try: self.admin_account_virtual_machine = VirtualMachine.create( self.api_client, @@ -1058,7 +1087,7 @@ class TestSharedNetworks(cloudstackTestCase): ) self.fail("Virtual Machine got created in admin account with network created but the network used is of scope account and for user account.") except Exception as e: - self.debug("Virtual Machine creation failed as network used have scoped only for user account.") + self.debug("Virtual Machine creation failed as network used have scoped only for user account. Exception: %s" % e) self.user_account_virtual_machine = VirtualMachine.create( self.api_client, @@ -1083,7 +1112,7 @@ class TestSharedNetworks(cloudstackTestCase): 0, "listVirtualMachines returned empty list." ) - + ip_range = list(netaddr.iter_iprange(unicode(self.services["network"]["startip"]), unicode(self.services["network"]["endip"]))) if netaddr.IPAddress(unicode(vms[0].nic[0].ipaddress)) not in ip_range: self.fail("Virtual machine ip should be from the ip range assigned to network created.") @@ -1091,14 +1120,14 @@ class TestSharedNetworks(cloudstackTestCase): @attr(tags=["advanced", "advancedns"]) def test_createSharedNetwork_domainSpecific(self): """ Test Shared Network with scope domain """ - + # Steps, # 1. create an Admin Account - admin-XABU1 # create a domain - DOM # create a domain admin account = domadmin-SOPJD # create a user in domain - DOM # 2. listPhysicalNetworks in available zone - # 3. createNetworkOffering: + # 3. createNetworkOffering: # - name = "MySharedOffering" # - guestiptype="shared" # - services = {Dns, Dhcp, UserData} @@ -1123,7 +1152,7 @@ class TestSharedNetworks(cloudstackTestCase): # 6. VM should NOT be deployed in admin account # VM should be deployed in user account and domain admin account # verify VM's IP are within shared network range - + #Create admin account self.admin_account = Account.create( self.api_client, @@ -1131,9 +1160,9 @@ class TestSharedNetworks(cloudstackTestCase): admin=True, domainid=self.domain.id ) - + self.cleanup_accounts.append(self.admin_account) - + #verify that the account got created with state enabled list_accounts_response = Account.list( self.api_client, @@ -1155,21 +1184,21 @@ class TestSharedNetworks(cloudstackTestCase): "enabled", "The admin account created is not enabled." ) - + self.debug("Admin type account created: %s" % self.admin_account.id) - + #create domain self.dom_domain = Domain.create( self.api_client, self.services["domain"], ) - + self.cleanup_domains.append(self.dom_domain) - + #verify that the account got created with state enabled list_domains_response = Domain.list( self.api_client, - id=self.dom_domain.id + id=self.dom_domain.id ) self.assertEqual( isinstance(list_domains_response, list), @@ -1181,9 +1210,9 @@ class TestSharedNetworks(cloudstackTestCase): 0, "listDomains returned empty list." ) - + self.debug("Domain created: %s" % self.dom_domain.id) - + #Create admin account self.domain_admin_account = Account.create( self.api_client, @@ -1191,9 +1220,9 @@ class TestSharedNetworks(cloudstackTestCase): admin=True, domainid=self.dom_domain.id ) - + self.cleanup_accounts.append(self.domain_admin_account) - + #verify that the account got created with state enabled list_accounts_response = Account.list( self.api_client, @@ -1215,9 +1244,9 @@ class TestSharedNetworks(cloudstackTestCase): "enabled", "The domain admin account created is not enabled." ) - + self.debug("Domain admin account created: %s" % self.domain_admin_account.id) - + #Create an user account self.domain_user_account = Account.create( self.api_client, @@ -1225,9 +1254,9 @@ class TestSharedNetworks(cloudstackTestCase): admin=False, domainid=self.dom_domain.id ) - + self.cleanup_accounts.append(self.domain_user_account) - + #verify that the account got created with state enabled list_accounts_response = Account.list( self.api_client, @@ -1249,13 +1278,13 @@ class TestSharedNetworks(cloudstackTestCase): "enabled", "The domain user account created is not enabled." ) - + self.debug("Domain user account created: %s" % self.domain_user_account.id) - + physical_network, shared_vlan = self.getFreeVlan(self.api_client, self.zone.id) - + self.debug("Physical Network found: %s" % physical_network.id) - + self.services["network_offering"]["specifyVlan"] = "True" self.services["network_offering"]["specifyIpRanges"] = "True" @@ -1265,9 +1294,9 @@ class TestSharedNetworks(cloudstackTestCase): self.services["network_offering"], conservemode=False ) - - #Verify that the network offering got created + + #Verify that the network offering got created list_network_offerings_response = NetworkOffering.list( self.api_client, id=self.shared_network_offering.id @@ -1287,17 +1316,17 @@ class TestSharedNetworks(cloudstackTestCase): "Disabled", "The network offering created should be by default disabled." ) - + self.debug("Shared Network Offering created: %s" % self.shared_network_offering.id) - + #Update network offering state from disabled to enabled. - network_offering_update_response = NetworkOffering.update( - self.shared_network_offering, - self.api_client, - id=self.shared_network_offering.id, - state="enabled" - ) - + NetworkOffering.update( + self.shared_network_offering, + self.api_client, + id=self.shared_network_offering.id, + state="enabled" + ) + #Verify that the state of the network offering is updated list_network_offerings_response = NetworkOffering.list( self.api_client, @@ -1318,13 +1347,13 @@ class TestSharedNetworks(cloudstackTestCase): "Enabled", "The network offering state should get updated to Enabled." ) - + #create network using the shared network offering created self.services["network"]["acltype"] = "domain" self.services["network"]["networkofferingid"] = self.shared_network_offering.id self.services["network"]["physicalnetworkid"] = physical_network.id self.services["network"]["vlan"] = shared_vlan - + self.network = Network.create( self.api_client, self.services["network"], @@ -1333,9 +1362,9 @@ class TestSharedNetworks(cloudstackTestCase): networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id ) - + self.cleanup_networks.append(self.network) - + list_networks_response = Network.list( self.api_client, id=self.network.id, @@ -1356,9 +1385,9 @@ class TestSharedNetworks(cloudstackTestCase): True, "The network is created with ip range but the flag is set to False." ) - + self.debug("Shared Network created: %s" % self.network.id) - + try: self.admin_account_virtual_machine = VirtualMachine.create( self.api_client, @@ -1370,7 +1399,7 @@ class TestSharedNetworks(cloudstackTestCase): ) self.fail("Virtual Machine got created in admin account with network specified but the network used is of scope domain and admin account is not part of this domain.") except Exception as e: - self.debug("Virtual Machine creation failed as network used have scoped only for DOM domain.") + self.debug("Virtual Machine creation failed as network used have scoped only for DOM domain. Exception: %s" % e) self.domain_user_account_virtual_machine = VirtualMachine.create( self.api_client, @@ -1396,11 +1425,11 @@ class TestSharedNetworks(cloudstackTestCase): 0, "listVirtualMachines returned empty list." ) - + ip_range = list(netaddr.iter_iprange(unicode(self.services["network"]["startip"]), unicode(self.services["network"]["endip"]))) if netaddr.IPAddress(unicode(vms[0].nic[0].ipaddress)) not in ip_range: self.fail("Virtual machine ip should be from the ip range assigned to network created.") - + self.domain_admin_account_virtual_machine = VirtualMachine.create( self.api_client, self.services["virtual_machine"], @@ -1425,7 +1454,7 @@ class TestSharedNetworks(cloudstackTestCase): 0, "listVirtualMachines returned empty list." ) - + ip_range = list(netaddr.iter_iprange(unicode(self.services["network"]["startip"]), unicode(self.services["network"]["endip"]))) if netaddr.IPAddress(unicode(vms[0].nic[0].ipaddress)) not in ip_range: self.fail("Virtual machine ip should be from the ip range assigned to network created.") @@ -1433,13 +1462,13 @@ class TestSharedNetworks(cloudstackTestCase): @attr(tags=["advanced", "advancedns"]) def test_createSharedNetwork_projectSpecific(self): """ Test Shared Network with scope project """ - + # Steps, # 1. create an Admin Account - admin-XABU1 # create a project - proj-SADJKS # create another project - proj-SLDJK # 2. listPhysicalNetworks in available zone - # 3. createNetworkOffering: + # 3. createNetworkOffering: # - name = "MySharedOffering" # - guestiptype="shared" # - services = {Dns, Dhcp, UserData} @@ -1464,7 +1493,7 @@ class TestSharedNetworks(cloudstackTestCase): # 6. VM should NOT be deployed in admin account and user account # VM should be deployed in project account only # verify VM's IP are within shared network range - + #Create admin account self.admin_account = Account.create( self.api_client, @@ -1472,9 +1501,9 @@ class TestSharedNetworks(cloudstackTestCase): admin=True, domainid=self.domain.id ) - + self.cleanup_accounts.append(self.admin_account) - + #verify that the account got created with state enabled list_accounts_response = Account.list( self.api_client, @@ -1496,21 +1525,21 @@ class TestSharedNetworks(cloudstackTestCase): "enabled", "The admin account created is not enabled." ) - + self.debug("Admin account created: %s" % self.admin_account.id) - + self.services["project"]["name"] = "proj-SADJKS" self.services["project"]["displaytext"] = "proj-SADJKS" - + self.project1 = Project.create( self.api_client, self.services["project"], account=self.admin_account.name, domainid=self.admin_account.domainid ) - + self.cleanup_projects.append(self.project1) - + list_projects_response = Project.list( self.api_client, id=self.project1.id, @@ -1526,21 +1555,21 @@ class TestSharedNetworks(cloudstackTestCase): 0, "listProjects should return at least one." ) - + self.debug("Project created: %s" % self.project1.id) - + self.services["project"]["name"] = "proj-SLDJK" self.services["project"]["displaytext"] = "proj-SLDJK" - + self.project2 = Project.create( self.api_client, self.services["project"], account=self.admin_account.name, domainid=self.admin_account.domainid ) - + self.cleanup_projects.append(self.project2) - + list_projects_response = Project.list( self.api_client, id=self.project2.id, @@ -1556,26 +1585,26 @@ class TestSharedNetworks(cloudstackTestCase): 0, "listProjects should return at least one." ) - + self.debug("Project2 created: %s" % self.project2.id) - + physical_network, shared_vlan = self.getFreeVlan(self.api_client, self.zone.id) - + self.debug("Physical Network found: %s" % physical_network.id) - + self.services["network_offering"]["specifyVlan"] = "True" self.services["network_offering"]["specifyIpRanges"] = "True" - + #Create Network Offering self.shared_network_offering = NetworkOffering.create( self.api_client, self.services["network_offering"], conservemode=False ) - - #Verify that the network offering got created + + #Verify that the network offering got created list_network_offerings_response = NetworkOffering.list( self.api_client, id=self.shared_network_offering.id @@ -1595,15 +1624,15 @@ class TestSharedNetworks(cloudstackTestCase): "Disabled", "The network offering created should be by default disabled." ) - + #Update network offering state from disabled to enabled. - network_offering_update_response = NetworkOffering.update( - self.shared_network_offering, - self.api_client, - id=self.shared_network_offering.id, - state="enabled" - ) - + NetworkOffering.update( + self.shared_network_offering, + self.api_client, + id=self.shared_network_offering.id, + state="enabled" + ) + #Verify that the state of the network offering is updated list_network_offerings_response = NetworkOffering.list( self.api_client, @@ -1624,15 +1653,15 @@ class TestSharedNetworks(cloudstackTestCase): "Enabled", "The network offering state should get updated to Enabled." ) - + self.debug("Shared Network found: %s" % self.shared_network_offering.id) - + #create network using the shared network offering created self.services["network"]["acltype"] = "account" self.services["network"]["networkofferingid"] = self.shared_network_offering.id self.services["network"]["physicalnetworkid"] = physical_network.id self.services["network"]["vlan"] = shared_vlan - + self.network = Network.create( self.api_client, self.services["network"], @@ -1642,7 +1671,7 @@ class TestSharedNetworks(cloudstackTestCase): zoneid=self.zone.id ) self.cleanup_networks.append(self.network) - + list_networks_response = Network.list( self.api_client, id=self.network.id, @@ -1664,9 +1693,9 @@ class TestSharedNetworks(cloudstackTestCase): True, "The network is created with ip range but the flag is set to False." ) - + self.debug("Shared Network created: %s" % self.network.id) - + try: self.project2_admin_account_virtual_machine = VirtualMachine.create( self.api_client, @@ -1679,7 +1708,7 @@ class TestSharedNetworks(cloudstackTestCase): ) self.fail("Virtual Machine got created in admin account with network specified but the network used is of scope project and the project2 is not assigned for the network.") except Exception as e: - self.debug("Virtual Machine creation failed as network used have scoped only for project project1.") + self.debug("Virtual Machine creation failed as network used have scoped only for project project1. Exception: %s" % e) self.project1_admin_account_virtual_machine = VirtualMachine.create( self.api_client, @@ -1705,7 +1734,7 @@ class TestSharedNetworks(cloudstackTestCase): 0, "listVirtualMachines returned empty list." ) - + ip_range = list(netaddr.iter_iprange(unicode(self.services["network"]["startip"]), unicode(self.services["network"]["endip"]))) if netaddr.IPAddress(unicode(vms[0].nic[0].ipaddress)) not in ip_range: self.fail("Virtual machine ip should be from the ip range assigned to network created.") @@ -1714,12 +1743,12 @@ class TestSharedNetworks(cloudstackTestCase): @attr(tags=["advanced", "advancedns"]) def test_createSharedNetwork_usedVlan(self): """ Test Shared Network with used vlan 01 """ - + # Steps, # 1. create an Admin account # 2. create a shared NetworkOffering # 3. enable the network offering - # 4. listPhysicalNetworks + # 4. listPhysicalNetworks # - vlan = guest VLAN range = 10-90 (say) # 5. createNetwork # - name = mysharednetwork, displaytext = mysharednetwork @@ -1733,8 +1762,8 @@ class TestSharedNetworks(cloudstackTestCase): # 2. listNetworkOfferings - name=mysharedoffering , should list offering in disabled state # 3. listNetworkOfferings - name=mysharedoffering, should list enabled offering # 4. listPhysicalNetworks should return at least one active physical network - # 5. network creation should FAIL since VLAN is used for guest networks - + # 5. network creation should FAIL since VLAN is used for guest networks + #Create admin account self.admin_account = Account.create( self.api_client, @@ -1742,9 +1771,9 @@ class TestSharedNetworks(cloudstackTestCase): admin=True, domainid=self.domain.id ) - + self.cleanup_accounts.append(self.admin_account) - + #verify that the account got created with state enabled list_accounts_response = Account.list( self.api_client, @@ -1766,23 +1795,23 @@ class TestSharedNetworks(cloudstackTestCase): "enabled", "The admin account created is not enabled." ) - + self.debug("Domain admin account created: %s" % self.admin_account.id) - + physical_network, shared_vlan = self.getFreeVlan(self.api_client, self.zone.id) - + self.services["network_offering"]["specifyVlan"] = "True" self.services["network_offering"]["specifyIpRanges"] = "True" - + #Create Network Offering self.shared_network_offering = NetworkOffering.create( self.api_client, self.services["network_offering"], conservemode=False ) - - #Verify that the network offering got created + + #Verify that the network offering got created list_network_offerings_response = NetworkOffering.list( self.api_client, id=self.shared_network_offering.id @@ -1802,17 +1831,17 @@ class TestSharedNetworks(cloudstackTestCase): "Disabled", "The network offering created should be bydefault disabled." ) - + self.debug("Shared Network Offering created: %s" % self.shared_network_offering.id) - + #Update network offering state from disabled to enabled. - network_offering_update_response = NetworkOffering.update( - self.shared_network_offering, - self.api_client, - id=self.shared_network_offering.id, - state="enabled" - ) - + NetworkOffering.update( + self.shared_network_offering, + self.api_client, + id=self.shared_network_offering.id, + state="enabled" + ) + #Verify that the state of the network offering is updated list_network_offerings_response = NetworkOffering.list( self.api_client, @@ -1833,14 +1862,14 @@ class TestSharedNetworks(cloudstackTestCase): "Enabled", "The network offering state should get updated to Enabled." ) - + #create network using the shared network offering created self.services["network"]["vlan"] = str.split(str(physical_network.vlan), "-")[0] self.services["network"]["acltype"] = "domain" self.services["network"]["networkofferingid"] = self.shared_network_offering.id self.services["network"]["physicalnetworkid"] = physical_network.id self.services["network"]["vlan"] = shared_vlan - + try: self.network = Network.create( self.api_client, @@ -1850,19 +1879,18 @@ class TestSharedNetworks(cloudstackTestCase): ) self.fail("Network created with used vlan %s id, which is invalid" % shared_vlan) except Exception as e: - self.debug("Network creation failed because the valn id being used by another network.") - + self.debug("Network creation failed because the valn id being used by another network. Exception: %s" % e) @attr(tags=["advanced", "advancedns"]) def test_createSharedNetwork_usedVlan2(self): """ Test Shared Network with used vlan 02 """ - + # Steps, # 1. create an Admin account # 2. create a shared NetworkOffering # 3. enable the network offering - # 4. listPhysicalNetworks + # 4. listPhysicalNetworks # - vlan = guest VLAN range = 10-90 (say) # 5. createNetwork # - name = mysharednetwork, displaytext = mysharednetwork @@ -1879,7 +1907,7 @@ class TestSharedNetworks(cloudstackTestCase): # 4. listPhysicalNetworks should return at least one active physical network # 5. network creation shoud PASS # 6. network creation should FAIL since VLAN is already used by previously created network - + #Create admin account self.admin_account = Account.create( self.api_client, @@ -1888,7 +1916,7 @@ class TestSharedNetworks(cloudstackTestCase): domainid=self.domain.id ) self.cleanup_accounts.append(self.admin_account) - + #verify that the account got created with state enabled list_accounts_response = Account.list( self.api_client, @@ -1910,25 +1938,25 @@ class TestSharedNetworks(cloudstackTestCase): "enabled", "The admin account created is not enabled." ) - + self.debug("Admin account created: %s" % self.admin_account.id) physical_network, shared_ntwk_vlan = self.getFreeVlan(self.api_client, self.zone.id) self.debug("Physical Network found: %s" % physical_network.id) - + self.services["network_offering"]["specifyVlan"] = "True" self.services["network_offering"]["specifyIpRanges"] = "True" - + #Create Network Offering self.shared_network_offering = NetworkOffering.create( self.api_client, self.services["network_offering"], conservemode=False ) - - #Verify that the network offering got created + + #Verify that the network offering got created list_network_offerings_response = NetworkOffering.list( self.api_client, id=self.shared_network_offering.id @@ -1948,17 +1976,17 @@ class TestSharedNetworks(cloudstackTestCase): "Disabled", "The network offering created should be bydefault disabled." ) - + self.debug("Shared Network Offering created: %s" % self.shared_network_offering.id) - + #Update network offering state from disabled to enabled. - network_offering_update_response = NetworkOffering.update( - self.shared_network_offering, - self.api_client, - id=self.shared_network_offering.id, - state="enabled" - ) - + NetworkOffering.update( + self.shared_network_offering, + self.api_client, + id=self.shared_network_offering.id, + state="enabled" + ) + #Verify that the state of the network offering is updated list_network_offerings_response = NetworkOffering.list( self.api_client, @@ -1979,7 +2007,7 @@ class TestSharedNetworks(cloudstackTestCase): "Enabled", "The network offering state should get updated to Enabled." ) - + #create network using the shared network offering created self.services["network"]["acltype"] = "Domain" self.services["network"]["networkofferingid"] = self.shared_network_offering.id @@ -1992,9 +2020,9 @@ class TestSharedNetworks(cloudstackTestCase): networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id, ) - + self.cleanup_networks.append(self.network) - + list_networks_response = Network.list( self.api_client, id=self.network.id @@ -2014,14 +2042,14 @@ class TestSharedNetworks(cloudstackTestCase): True, "The network is created with ip range but the flag is set to False." ) - + self.debug("Network created: %s" % self.network.id) - - self.services["network1"]["vlan"] = self.services["network"]["vlan"] + + self.services["network1"]["vlan"] = self.services["network"]["vlan"] self.services["network1"]["acltype"] = "domain" self.services["network1"]["networkofferingid"] = self.shared_network_offering.id self.services["network1"]["physicalnetworkid"] = physical_network.id - + try: self.network1 = Network.create( self.api_client, @@ -2032,12 +2060,12 @@ class TestSharedNetworks(cloudstackTestCase): self.cleanup_networks.append(self.network1) self.fail("Network got created with used vlan id, which is invalid") except Exception as e: - self.debug("Network creation failed because the valn id being used by another network.") + self.debug("Network creation failed because the valn id being used by another network. Exception: %s" % e) @attr(tags=["advanced", "advancedns"]) def test_deployVM_multipleSharedNetwork(self): """ Test Vm deployment with multiple shared networks """ - + # Steps, # 0. create a user account # 1. Create two shared Networks (scope=ALL, different IP ranges) @@ -2047,7 +2075,7 @@ class TestSharedNetworks(cloudstackTestCase): # 1. shared networks should be created successfully # 2. a. VM should deploy successfully # b. VM should be deployed in both networks and have IP in both the networks - + #Create admin account self.admin_account = Account.create( self.api_client, @@ -2057,7 +2085,7 @@ class TestSharedNetworks(cloudstackTestCase): ) self.cleanup_accounts.append(self.admin_account) - + #verify that the account got created with state enabled list_accounts_response = Account.list( self.api_client, @@ -2079,25 +2107,25 @@ class TestSharedNetworks(cloudstackTestCase): "enabled", "The admin account created is not enabled." ) - + self.debug("Admin account created: %s" % self.admin_account.id) - + physical_network, shared_vlan = self.getFreeVlan(self.api_client, self.zone.id) - + self.debug("Physical Network found: %s" % physical_network.id) - + self.services["network_offering"]["specifyVlan"] = "True" self.services["network_offering"]["specifyIpRanges"] = "True" - + #Create Network Offering self.shared_network_offering = NetworkOffering.create( self.api_client, self.services["network_offering"], conservemode=False ) - - #Verify that the network offering got created + + #Verify that the network offering got created list_network_offerings_response = NetworkOffering.list( self.api_client, id=self.shared_network_offering.id @@ -2117,17 +2145,17 @@ class TestSharedNetworks(cloudstackTestCase): "Disabled", "The network offering created should be bydefault disabled." ) - + self.debug("Shared Network offering created: %s" % self.shared_network_offering.id) - + #Update network offering state from disabled to enabled. - network_offering_update_response = NetworkOffering.update( - self.shared_network_offering, - self.api_client, - id=self.shared_network_offering.id, - state="enabled" - ) - + NetworkOffering.update( + self.shared_network_offering, + self.api_client, + id=self.shared_network_offering.id, + state="enabled" + ) + #Verify that the state of the network offering is updated list_network_offerings_response = NetworkOffering.list( self.api_client, @@ -2148,7 +2176,7 @@ class TestSharedNetworks(cloudstackTestCase): "Enabled", "The network offering state should get updated to Enabled." ) - + #create network using the shared network offering created self.services["network"]["acltype"] = "domain" self.services["network"]["networkofferingid"] = self.shared_network_offering.id @@ -2161,9 +2189,9 @@ class TestSharedNetworks(cloudstackTestCase): networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id, ) - + self.cleanup_networks.append(self.network) - + list_networks_response = Network.list( self.api_client, id=self.network.id @@ -2183,9 +2211,9 @@ class TestSharedNetworks(cloudstackTestCase): True, "The network is created with ip range but the flag is set to False." ) - + self.debug("Shared Network created: %s" % self.network.id) - + self.services["network1"]["acltype"] = "domain" self.services["network1"]["networkofferingid"] = self.shared_network_offering.id self.services["network1"]["physicalnetworkid"] = physical_network.id @@ -2197,9 +2225,9 @@ class TestSharedNetworks(cloudstackTestCase): networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id, ) - + self.cleanup_networks.append(self.network1) - + list_networks_response = Network.list( self.api_client, id=self.network1.id @@ -2221,7 +2249,7 @@ class TestSharedNetworks(cloudstackTestCase): ) self.debug("Network created: %s" % self.network1.id) - + self.network_admin_account_virtual_machine = VirtualMachine.create( self.api_client, self.services["virtual_machine"], @@ -2245,11 +2273,11 @@ class TestSharedNetworks(cloudstackTestCase): 0, "listVirtualMachines returned empty list." ) - + self.debug("Virtual Machine created: %s" % self.network_admin_account_virtual_machine.id) - + self.assertTrue(self.network_admin_account_virtual_machine.nic[0].ipaddress is not None, "ip should be assigned to running virtual machine") - + self.network1_admin_account_virtual_machine = VirtualMachine.create( self.api_client, self.services["virtual_machine"], @@ -2274,28 +2302,28 @@ class TestSharedNetworks(cloudstackTestCase): "listVirtualMachines returned empty list." ) self.debug("Virtual Machine created: %s" % self.network1_admin_account_virtual_machine.id) - + self.assertTrue(self.network1_admin_account_virtual_machine.nic[0].ipaddress is not None, "ip should be assigned to running virtual machine") @attr(tags=["advanced", "advancedns"]) def test_deployVM_isolatedAndShared(self): """ Test VM deployment in shared and isolated networks """ - + # Steps, # 0. create a user account # 1. Create one shared Network (scope=ALL, different IP ranges) - # 2. Create one Isolated Network + # 2. Create one Isolated Network # 3. deployVirtualMachine in both the above networkids within the user account # 4. apply FW rule and enable PF for port 22 for guest VM on isolated network # 5. delete the user account # Validations, # 1. shared network should be created successfully # 2. isolated network should be created successfully - # 3. + # 3. # a. VM should deploy successfully # b. VM should be deployed in both networks and have IP in both the networks # 4. FW and PF should apply successfully, ssh into the VM should work over isolated network - + #Create admin account self.admin_account = Account.create( self.api_client, @@ -2303,9 +2331,9 @@ class TestSharedNetworks(cloudstackTestCase): admin=True, domainid=self.domain.id ) - + self.cleanup_accounts.append(self.admin_account) - + #verify that the account got created with state enabled list_accounts_response = Account.list( self.api_client, @@ -2327,21 +2355,21 @@ class TestSharedNetworks(cloudstackTestCase): "enabled", "The admin account created is not enabled." ) - + self.debug("Admin type account created: %s" % self.admin_account.name) - + self.services["network_offering"]["specifyVlan"] = "True" self.services["network_offering"]["specifyIpRanges"] = "True" - + #Create Network Offering self.shared_network_offering = NetworkOffering.create( self.api_client, self.services["network_offering"], conservemode=False ) - - #Verify that the network offering got created + + #Verify that the network offering got created list_network_offerings_response = NetworkOffering.list( self.api_client, id=self.shared_network_offering.id @@ -2361,17 +2389,17 @@ class TestSharedNetworks(cloudstackTestCase): "Disabled", "The network offering created should be bydefault disabled." ) - + self.debug("Shared Network offering created: %s" % self.shared_network_offering.id) - + #Update network offering state from disabled to enabled. - network_offering_update_response = NetworkOffering.update( - self.shared_network_offering, - self.api_client, - id=self.shared_network_offering.id, - state="enabled" - ) - + NetworkOffering.update( + self.shared_network_offering, + self.api_client, + id=self.shared_network_offering.id, + state="enabled" + ) + #Verify that the state of the network offering is updated list_network_offerings_response = NetworkOffering.list( self.api_client, @@ -2392,22 +2420,22 @@ class TestSharedNetworks(cloudstackTestCase): "Enabled", "The network offering state should get updated to Enabled." ) - + self.isolated_network_offering = NetworkOffering.create( self.api_client, self.services["isolated_network_offering"], conservemode=False ) - + #Update network offering state from disabled to enabled. - network_offering_update_response = NetworkOffering.update( - self.isolated_network_offering, - self.api_client, - id=self.isolated_network_offering.id, - state="enabled" - ) - + NetworkOffering.update( + self.isolated_network_offering, + self.api_client, + id=self.isolated_network_offering.id, + state="enabled" + ) + #Verify that the state of the network offering is updated list_network_offerings_response = NetworkOffering.list( self.api_client, @@ -2428,7 +2456,7 @@ class TestSharedNetworks(cloudstackTestCase): "Enabled", "The isolated network offering state should get updated to Enabled." ) - + self.debug("Isolated Network Offering created: %s" % self.isolated_network_offering.id) physical_network, shared_vlan = self.getFreeVlan(self.api_client, self.zone.id) @@ -2446,9 +2474,9 @@ class TestSharedNetworks(cloudstackTestCase): networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id ) - + self.cleanup_networks.append(self.shared_network) - + list_networks_response = Network.list( self.api_client, id=self.shared_network.id @@ -2470,7 +2498,7 @@ class TestSharedNetworks(cloudstackTestCase): ) self.debug("Shared Network created: %s" % self.shared_network.id) - + self.isolated_network = Network.create( self.api_client, self.services["isolated_network"], @@ -2479,9 +2507,9 @@ class TestSharedNetworks(cloudstackTestCase): networkofferingid=self.isolated_network_offering.id, zoneid=self.zone.id ) - - self.cleanup_networks.append(self.isolated_network) - + + self.cleanup_networks.append(self.isolated_network) + list_networks_response = Network.list( self.api_client, id=self.isolated_network.id @@ -2496,7 +2524,7 @@ class TestSharedNetworks(cloudstackTestCase): 0, "listNetworks returned empty list." ) - + self.debug("Isolated Network created: %s" % self.isolated_network.id) self.shared_network_admin_account_virtual_machine =\ @@ -2524,7 +2552,7 @@ class TestSharedNetworks(cloudstackTestCase): "listVirtualMachines returned empty list." ) self.debug("Virtual Machine created: %s" % self.shared_network_admin_account_virtual_machine.id) - + self.assertTrue(self.shared_network_admin_account_virtual_machine.nic[0].ipaddress is not None, "ip should be assigned to running virtual machine") @@ -2552,11 +2580,11 @@ class TestSharedNetworks(cloudstackTestCase): 0, "listVirtualMachines returned empty list." ) - + self.debug("Virtual Machine created: %s" % self.isolated_network_admin_account_virtual_machine.id) - + self.assertTrue(self.isolated_network_admin_account_virtual_machine.nic[0].ipaddress is not None, "ip should be assigned to running virtual machine") - + self.debug("Associating public IP for account: %s" % self.admin_account.name) self.public_ip = PublicIPAddress.create( self.api_client, @@ -2568,7 +2596,7 @@ class TestSharedNetworks(cloudstackTestCase): self.debug("Associated %s with network %s" % (self.public_ip.ipaddress.ipaddress, self.isolated_network.id)) self.debug("Creating PF rule for IP address: %s" % self.public_ip.ipaddress.ipaddress) - + public_ip = self.public_ip.ipaddress # Enable Static NAT for VM @@ -2577,7 +2605,7 @@ class TestSharedNetworks(cloudstackTestCase): public_ip.id, self.isolated_network_admin_account_virtual_machine.id ) - + self.debug("Enabled static NAT for public IP ID: %s" % public_ip.id) #Create Firewall rule on source NAT fw_rule = FireWallRule.create( @@ -2604,8 +2632,8 @@ class TestSharedNetworks(cloudstackTestCase): len(fw_rules), 0, "Length of fw rules response should not be zero" - ) - + ) + # Should be able to SSH VM try: self.debug("SSH into VM: %s" % self.isolated_network_admin_account_virtual_machine.id) @@ -2616,12 +2644,12 @@ class TestSharedNetworks(cloudstackTestCase): @attr(tags=["advanced", "advancedns"]) def test_networkWithsubdomainaccessTrue(self): """ Test Shared Network with subdomainaccess=True """ - + # Steps, # 1. create Network using shared network offering for scope=Account and subdomainaccess=true. # Validations, # (Expected) API should fail saying that subdomainaccess cannot be given when scope is Account - + #Create admin account self.admin_account = Account.create( self.api_client, @@ -2629,9 +2657,9 @@ class TestSharedNetworks(cloudstackTestCase): admin=True, domainid=self.domain.id ) - + self.cleanup_accounts.append(self.admin_account) - + #verify that the account got created with state enabled list_accounts_response = Account.list( self.api_client, @@ -2652,153 +2680,25 @@ class TestSharedNetworks(cloudstackTestCase): list_accounts_response[0].state, "enabled", "The admin account created is not enabled." - ) - + ) + self.debug("Admin type account created: %s" % self.admin_account.id) - + physical_network, shared_vlan = self.getFreeVlan(self.api_client, self.zone.id) - + self.debug("Physical Network found: %s" % physical_network.id) - + self.services["network_offering"]["specifyVlan"] = "True" self.services["network_offering"]["specifyIpRanges"] = "True" - + #Create Network Offering self.shared_network_offering = NetworkOffering.create( self.api_client, self.services["network_offering"], conservemode=False - ) - + ) - #Verify that the network offering got created - list_network_offerings_response = NetworkOffering.list( - self.api_client, - id=self.shared_network_offering.id - ) - self.assertEqual( - isinstance(list_network_offerings_response, list), - True, - "listNetworkOfferings returned invalid object in response." - ) - self.assertNotEqual( - len(list_network_offerings_response), - 0, - "listNetworkOfferings returned empty list." - ) - self.assertEqual( - list_network_offerings_response[0].state, - "Disabled", - "The network offering created should be bydefault disabled." - ) - - self.debug("Shared Network Offering created: %s" % self.shared_network_offering.id) - - #Update network offering state from disabled to enabled. - network_offering_update_response = NetworkOffering.update( - self.shared_network_offering, - self.api_client, - id=self.shared_network_offering.id, - state="enabled" - ) - #Verify that the state of the network offering is updated - list_network_offerings_response = NetworkOffering.list( - self.api_client, - id=self.shared_network_offering.id - ) - self.assertEqual( - isinstance(list_network_offerings_response, list), - True, - "listNetworkOfferings returned invalid object in response." - ) - self.assertNotEqual( - len(list_network_offerings_response), - 0, - "listNetworkOfferings returned empty list." - ) - self.assertEqual( - list_network_offerings_response[0].state, - "Enabled", - "The network offering state should get updated to Enabled." - ) - - #create network using the shared network offering created - self.services["network"]["acltype"] = "Account" - self.services["network"]["networkofferingid"] = self.shared_network_offering.id - self.services["network"]["physicalnetworkid"] = physical_network.id - self.services["network"]["vlan"] = shared_vlan - self.services["network"]["subdomainaccess"] = "True" - - try: - self.network = Network.create( - self.api_client, - self.services["network"], - accountid=self.admin_account.name, - domainid=self.admin_account.domainid, - networkofferingid=self.shared_network_offering.id, - zoneid=self.zone.id - ) - self.fail("Network creation should fail.") - except: - self.debug("Network creation failed because subdomainaccess parameter was passed when scope was account.") - @attr(tags=["advanced", "advancedns"]) - def test_networkWithsubdomainaccessFalse(self): - """ Test shared Network with subdomainaccess=False """ - - # Steps, - # 1. create Network using shared network offering for scope=Account and subdomainaccess=false - # Validations, - # (Expected) API should fail saying that subdomainaccess cannot be given when scope is Account - - #Create admin account - self.admin_account = Account.create( - self.api_client, - self.services["account"], - admin=True, - domainid=self.domain.id - ) - - self.cleanup_accounts.append(self.admin_account) - - #verify that the account got created with state enabled - list_accounts_response = Account.list( - self.api_client, - id=self.admin_account.id, - listall=True - ) - self.assertEqual( - isinstance(list_accounts_response, list), - True, - "listAccounts returned invalid object in response." - ) - self.assertNotEqual( - len(list_accounts_response), - 0, - "listAccounts returned empty list." - ) - self.assertEqual( - list_accounts_response[0].state, - "enabled", - "The admin account created is not enabled." - ) - - self.debug("Admin type account created: %s" % self.admin_account.id) - - physical_network, shared_vlan = self.getFreeVlan(self.api_client, self.zone.id) - - self.debug("Physical Network found: %s" % physical_network.id) - - self.services["network_offering"]["specifyVlan"] = "True" - self.services["network_offering"]["specifyIpRanges"] = "True" - - #Create Network Offering - self.shared_network_offering = NetworkOffering.create( - self.api_client, - self.services["network_offering"], - conservemode=False - ) - #Verify that the network offering got created list_network_offerings_response = NetworkOffering.list( self.api_client, @@ -2819,16 +2719,16 @@ class TestSharedNetworks(cloudstackTestCase): "Disabled", "The network offering created should be bydefault disabled." ) - + self.debug("Shared Network Offering created: %s" % self.shared_network_offering.id) - + #Update network offering state from disabled to enabled. - network_offering_update_response = NetworkOffering.update( - self.shared_network_offering, - self.api_client, - id=self.shared_network_offering.id, - state="enabled" - ) + NetworkOffering.update( + self.shared_network_offering, + self.api_client, + id=self.shared_network_offering.id, + state="enabled" + ) #Verify that the state of the network offering is updated list_network_offerings_response = NetworkOffering.list( self.api_client, @@ -2849,14 +2749,142 @@ class TestSharedNetworks(cloudstackTestCase): "Enabled", "The network offering state should get updated to Enabled." ) - + #create network using the shared network offering created self.services["network"]["acltype"] = "Account" self.services["network"]["networkofferingid"] = self.shared_network_offering.id self.services["network"]["physicalnetworkid"] = physical_network.id self.services["network"]["vlan"] = shared_vlan - self.services["network"]["subdomainaccess"] = "False" - + self.services["network"]["subdomainaccess"] = "True" + + try: + self.network = Network.create( + self.api_client, + self.services["network"], + accountid=self.admin_account.name, + domainid=self.admin_account.domainid, + networkofferingid=self.shared_network_offering.id, + zoneid=self.zone.id + ) + self.fail("Network creation should fail.") + except: + self.debug("Network creation failed because subdomainaccess parameter was passed when scope was account.") + + @attr(tags=["advanced", "advancedns"]) + def test_networkWithsubdomainaccessFalse(self): + """ Test shared Network with subdomainaccess=False """ + + # Steps, + # 1. create Network using shared network offering for scope=Account and subdomainaccess=false + # Validations, + # (Expected) API should fail saying that subdomainaccess cannot be given when scope is Account + + #Create admin account + self.admin_account = Account.create( + self.api_client, + self.services["account"], + admin=True, + domainid=self.domain.id + ) + + self.cleanup_accounts.append(self.admin_account) + + #verify that the account got created with state enabled + list_accounts_response = Account.list( + self.api_client, + id=self.admin_account.id, + listall=True + ) + self.assertEqual( + isinstance(list_accounts_response, list), + True, + "listAccounts returned invalid object in response." + ) + self.assertNotEqual( + len(list_accounts_response), + 0, + "listAccounts returned empty list." + ) + self.assertEqual( + list_accounts_response[0].state, + "enabled", + "The admin account created is not enabled." + ) + + self.debug("Admin type account created: %s" % self.admin_account.id) + + physical_network, shared_vlan = self.getFreeVlan(self.api_client, self.zone.id) + + self.debug("Physical Network found: %s" % physical_network.id) + + self.services["network_offering"]["specifyVlan"] = "True" + self.services["network_offering"]["specifyIpRanges"] = "True" + + #Create Network Offering + self.shared_network_offering = NetworkOffering.create( + self.api_client, + self.services["network_offering"], + conservemode=False + ) + + #Verify that the network offering got created + list_network_offerings_response = NetworkOffering.list( + self.api_client, + id=self.shared_network_offering.id + ) + self.assertEqual( + isinstance(list_network_offerings_response, list), + True, + "listNetworkOfferings returned invalid object in response." + ) + self.assertNotEqual( + len(list_network_offerings_response), + 0, + "listNetworkOfferings returned empty list." + ) + self.assertEqual( + list_network_offerings_response[0].state, + "Disabled", + "The network offering created should be bydefault disabled." + ) + + self.debug("Shared Network Offering created: %s" % self.shared_network_offering.id) + + #Update network offering state from disabled to enabled. + NetworkOffering.update( + self.shared_network_offering, + self.api_client, + id=self.shared_network_offering.id, + state="enabled" + ) + #Verify that the state of the network offering is updated + list_network_offerings_response = NetworkOffering.list( + self.api_client, + id=self.shared_network_offering.id + ) + self.assertEqual( + isinstance(list_network_offerings_response, list), + True, + "listNetworkOfferings returned invalid object in response." + ) + self.assertNotEqual( + len(list_network_offerings_response), + 0, + "listNetworkOfferings returned empty list." + ) + self.assertEqual( + list_network_offerings_response[0].state, + "Enabled", + "The network offering state should get updated to Enabled." + ) + + #create network using the shared network offering created + self.services["network"]["acltype"] = "Account" + self.services["network"]["networkofferingid"] = self.shared_network_offering.id + self.services["network"]["physicalnetworkid"] = physical_network.id + self.services["network"]["vlan"] = shared_vlan + self.services["network"]["subdomainaccess"] = "False" + try: self.network = Network.create( self.api_client, diff --git a/test/integration/component/test_vpc_vms_deployment.py b/test/integration/component/test_vpc_vms_deployment.py index 0a1321ca276..b01137b1ccd 100644 --- a/test/integration/component/test_vpc_vms_deployment.py +++ b/test/integration/component/test_vpc_vms_deployment.py @@ -272,6 +272,34 @@ class TestVMDeployVPC(cloudstackTestCase): self.debug("VPC network validated - %s" % network.name) return + def getFreeVlan(self, apiclient, zoneid): + """ + Find an unallocated VLAN outside the range allocated to the physical network. + + @note: This does not guarantee that the VLAN is available for use in + the deployment's network gear + @return: physical_network, shared_vlan_tag + """ + list_physical_networks_response = PhysicalNetwork.list( + apiclient, + zoneid=zoneid + ) + assert isinstance(list_physical_networks_response, list) + assert len(list_physical_networks_response) > 0, "No physical networks found in zone %s" % zoneid + + physical_network = list_physical_networks_response[0] + vlans = xsplit(physical_network.vlan, ['-', ',']) + + assert len(vlans) > 0 + assert int(vlans[0]) < int(vlans[-1]), "VLAN range %s was improperly split" % physical_network.vlan + shared_ntwk_vlan = int(vlans[-1]) + random.randrange(1, 20) + if shared_ntwk_vlan > 4095: + shared_ntwk_vlan = int(vlans[0]) - random.randrange(1, 20) + assert shared_ntwk_vlan > 0, "VLAN chosen %s is invalid < 0" % shared_ntwk_vlan + self.debug("Attempting free VLAN %s for shared network creation" % shared_ntwk_vlan) + return shared_ntwk_vlan + + @attr(tags=["advanced", "intervlan"]) def test_01_deploy_vms_in_network(self): """ Test deploy VMs in VPC networks @@ -1995,6 +2023,8 @@ class TestVMDeployVPC(cloudstackTestCase): services=self.services["http_rule"], traffictype='Egress' ) + + vlan = self.getFreeVlan(self.api_client, self.zone.id) self.debug("Creating private gateway in VPC: %s" % vpc.name) private_gateway = PrivateGateway.create( @@ -2002,7 +2032,7 @@ class TestVMDeployVPC(cloudstackTestCase): gateway='10.2.3.1', ipaddress='10.2.3.2', netmask='255.255.255.0', - vlan=678, + vlan=vlan, vpcid=vpc.id ) self.debug("Check if the private gateway created successfully?") @@ -2110,7 +2140,8 @@ class TestVMDeployVPC(cloudstackTestCase): self.assertEqual( public_ips[0].ipaddress, public_ip_6.ipaddress.ipaddress, - "List public Ip for network should list the Ip addr" + "List public Ips %s for network should list the Ip addr %s" + % (public_ips[0].ipaddress, public_ip_6.ipaddress.ipaddress ) ) self.debug("Associating public IP for network: %s" % vpc.name) @@ -2150,13 +2181,14 @@ class TestVMDeployVPC(cloudstackTestCase): traffictype='Egress' ) + vlan = self.getFreeVlan(self.api_client, self.zone.id) self.debug("Creating private gateway in VPC: %s" % vpc.name) private_gateway = PrivateGateway.create( self.apiclient, gateway='10.2.4.1', ipaddress='10.2.4.2', netmask='255.255.255.0', - vlan=678, + vlan=vlan, vpcid=vpc.id ) self.debug("Check if the private gateway created successfully?") @@ -2219,6 +2251,8 @@ class TestVMDeployVPC(cloudstackTestCase): (public_ip_1.ipaddress.ipaddress, e)) result = str(res) + self.debug("result = %s, result.count = %s" % (result, result.count("1 received"))) + self.debug("Public IP = %s" % public_ip_1.ipaddress.ipaddress) self.assertEqual( result.count("1 received"), 1, diff --git a/test/integration/smoke/test_vpc_vpn.py b/test/integration/smoke/test_vpc_vpn.py index c360884ce4c..5e97c79065f 100644 --- a/test/integration/smoke/test_vpc_vpn.py +++ b/test/integration/smoke/test_vpc_vpn.py @@ -24,6 +24,8 @@ from marvin.integration.lib.base import * from marvin.integration.lib.common import * from nose.plugins.attrib import attr +import time + class Services: def __init__(self): self.services = { @@ -77,15 +79,37 @@ class Services: "vpn_user": { "username": "test", "password": "password", + }, + "vpc": { + "name": "vpc_vpn", + "displaytext": "vpc-vpn", + "cidr": "10.1.1.0/24" + }, + "ntwk": { + "name": "tier1", + "displaytext": "vpc-tier1", + "gateway" : "10.1.1.1", + "netmask" : "255.255.255.192" + }, + "vpc2": { + "name": "vpc2_vpn", + "displaytext": "vpc2-vpn", + "cidr": "10.2.1.0/24" + }, + "ntwk2": { + "name": "tier2", + "displaytext": "vpc-tier2", + "gateway" : "10.2.1.1", + "netmask" : "255.255.255.192" } } -class TestVpcVpn(cloudstackTestCase): +class TestVpcRemoteAccessVpn(cloudstackTestCase): @classmethod def setUpClass(cls): - cls.apiclient = super(TestVpcVpn, cls).getClsTestClient().getApiClient() + cls.apiclient = super(TestVpcRemoteAccessVpn, cls).getClsTestClient().getApiClient() cls.services = Services().services cls.zone = get_zone(cls.apiclient, cls.services) cls.domain = get_domain(cls.apiclient) @@ -102,7 +126,7 @@ class TestVpcVpn(cloudstackTestCase): cls.cleanup = [cls.account] @attr(tags=["advanced"]) - def test_vpc_vpn(self): + def test_vpc_remote_access_vpn(self): """Test VPN in VPC""" # 0) Get the default network offering for VPC @@ -112,10 +136,6 @@ class TestVpcVpn(cloudstackTestCase): # 1) Create VPC vpcOffering = VpcOffering.list(self.apiclient,isdefault=True) self.assert_(vpcOffering is not None and len(vpcOffering)>0, "No VPC offerings found") - self.services["vpc"] = {} - self.services["vpc"]["name"] = "vpc-vpn" - self.services["vpc"]["displaytext"] = "vpc-vpn" - self.services["vpc"]["cidr"] = "10.1.1.0/24" vpc = VPC.create( apiclient=self.apiclient, services=self.services["vpc"], @@ -126,33 +146,29 @@ class TestVpcVpn(cloudstackTestCase): domainid=self.domain.id ) self.assert_(vpc is not None, "VPC creation failed") + self.debug("VPC %s created" %(vpc.id)) # 2) Create network in VPC - self.services["vpcnetwork"] = {} - self.services["vpcnetwork"]["name"] = "vpcntwk" - self.services["vpcnetwork"]["displaytext"] = "vpcntwk" ntwk = Network.create( apiclient=self.apiclient, - services=self.services["vpcnetwork"], + services=self.services["ntwk"], accountid=self.account.name, domainid=self.domain.id, networkofferingid=networkOffering[0].id, zoneid=self.zone.id, - vpcid=vpc.id, - gateway="10.1.1.1", - netmask="255.255.255.192" + vpcid=vpc.id ) self.assertIsNotNone(ntwk, "Network failed to create") self.debug("Network %s created in VPC %s" %(ntwk.id, vpc.id)) # 3) Deploy a vm - self.services["virtual_machine"]["networkids"] = ntwk.id vm = VirtualMachine.create(self.apiclient, services=self.services["virtual_machine"], templateid=self.template.id, zoneid=self.zone.id, accountid=self.account.name, domainid= self.domain.id, serviceofferingid=self.service_offering.id, + networkids=ntwk.id ) self.assert_(vm is not None, "VM failed to deploy") self.assert_(vm.state == 'Running', "VM is not running") @@ -190,3 +206,186 @@ class TestVpcVpn(cloudstackTestCase): cleanup_resources(cls.apiclient, cls.cleanup) except Exception, e: raise Exception("Cleanup failed with %s" % e) + +class TestVpcSite2SiteVpn(cloudstackTestCase): + + @classmethod + def setUpClass(cls): + cls.apiclient = super(TestVpcSite2SiteVpn, cls).getClsTestClient().getApiClient() + cls.services = Services().services + cls.zone = get_zone(cls.apiclient, cls.services) + cls.domain = get_domain(cls.apiclient) + cls.service_offering = ServiceOffering.create( + cls.apiclient, + cls.services["service_offering"] + ) + cls.account = Account.create(cls.apiclient, services=cls.services["account"]) + cls.template = get_template( + cls.apiclient, + cls.zone.id, + cls.services["ostype"] + ) + cls.cleanup = [cls.account] + + @attr(tags=["advanced"]) + def test_vpc_site2site_vpn(self): + """Test VPN in VPC""" + + # 0) Get the default network offering for VPC + networkOffering = NetworkOffering.list(self.apiclient, name="DefaultIsolatedNetworkOfferingForVpcNetworks") + self.assert_(networkOffering is not None and len(networkOffering) > 0, "No VPC based network offering") + + # 1) Create VPC + vpcOffering = VpcOffering.list(self.apiclient,isdefault=True) + self.assert_(vpcOffering is not None and len(vpcOffering)>0, "No VPC offerings found") + + vpc1 = VPC.create( + apiclient=self.apiclient, + services=self.services["vpc"], + networkDomain="vpc1.vpn", + vpcofferingid=vpcOffering[0].id, + zoneid=self.zone.id, + account=self.account.name, + domainid=self.domain.id + ) + self.assert_(vpc1 is not None, "VPC creation failed") + self.debug("VPC1 %s created" %(vpc1.id)) + + vpc2 = VPC.create( + apiclient=self.apiclient, + services=self.services["vpc2"], + networkDomain="vpc2.vpn", + vpcofferingid=vpcOffering[0].id, + zoneid=self.zone.id, + account=self.account.name, + domainid=self.domain.id + ) + self.assert_(vpc2 is not None, "VPC2 creation failed") + self.debug("VPC2 %s created" %(vpc1.id)) + + # 2) Create network in VPC + ntwk1 = Network.create( + apiclient=self.apiclient, + services=self.services["ntwk"], + accountid=self.account.name, + domainid=self.domain.id, + networkofferingid=networkOffering[0].id, + zoneid=self.zone.id, + vpcid=vpc1.id + ) + self.assertIsNotNone(ntwk1, "Network failed to create") + self.debug("Network %s created in VPC %s" %(ntwk1.id, vpc1.id)) + + ntwk2 = Network.create( + apiclient=self.apiclient, + services=self.services["ntwk2"], + accountid=self.account.name, + domainid=self.domain.id, + networkofferingid=networkOffering[0].id, + zoneid=self.zone.id, + vpcid=vpc2.id + ) + self.assertIsNotNone(ntwk2, "Network failed to create") + self.debug("Network %s created in VPC %s" %(ntwk2.id, vpc2.id)) + + # 3) Deploy a vm + vm1 = VirtualMachine.create(self.apiclient, services=self.services["virtual_machine"], + templateid=self.template.id, + zoneid=self.zone.id, + accountid=self.account.name, + domainid= self.domain.id, + serviceofferingid=self.service_offering.id, + networkids=ntwk1.id + ) + self.assert_(vm1 is not None, "VM failed to deploy") + self.assert_(vm1.state == 'Running', "VM is not running") + self.debug("VM %s deployed in VPC %s" %(vm1.id, vpc1.id)) + + vm2 = VirtualMachine.create(self.apiclient, services=self.services["virtual_machine"], + templateid=self.template.id, + zoneid=self.zone.id, + accountid=self.account.name, + domainid= self.domain.id, + serviceofferingid=self.service_offering.id, + networkids=ntwk2.id + ) + self.assert_(vm2 is not None, "VM failed to deploy") + self.assert_(vm2.state == 'Running', "VM is not running") + self.debug("VM %s deployed in VPC %s" %(vm2.id, vpc2.id)) + + # 4) Enable Site-to-Site VPN for VPC + cmd=createVpnGateway.createVpnGatewayCmd() + cmd.vpcid=vpc1.id + vpn1_response = self.apiclient.createVpnGateway(cmd) + + self.debug("VPN gateway for VPC %s enabled" % (vpc1.id)) + + cmd=createVpnGateway.createVpnGatewayCmd() + cmd.vpcid=vpc2.id + vpn2_response = self.apiclient.createVpnGateway(cmd) + + self.debug("VPN gateway for VPC %s enabled" %(vpc2.id)) + + # 5) Add VPN Customer gateway info + + src_nat_list = PublicIPAddress.list( + self.apiclient, + account=self.account.name, + domainid=self.account.domainid, + listall=True, + issourcenat=True, + vpcid=vpc1.id + ) + ip1 = src_nat_list[0] + + src_nat_list = PublicIPAddress.list( + self.apiclient, + account=self.account.name, + domainid=self.account.domainid, + listall=True, + issourcenat=True, + vpcid=vpc2.id + ) + ip2 = src_nat_list[0] + + cmd=createVpnCustomerGateway.createVpnCustomerGatewayCmd() + cmd.esppolicy="3des-md5;modp1536" + cmd.ikepolicy="3des-md5;modp1536" + cmd.domainid=self.account.domainid + cmd.account=self.account.name + cmd.ipsecpsk="ipsecpsk" + + cmd.name="Peer VPC1" + cmd.gateway=ip1.ipaddress + cmd.cidrlist=vpc1.cidr + customer1_response = self.apiclient.createVpnCustomerGateway(cmd) + self.debug("VPN customer gateway added for VPC %s enabled" %(vpc1.id)) + + cmd.name="Peer VPC2" + cmd.gateway=ip2.ipaddress + cmd.cidrlist=vpc2.cidr + customer2_response = self.apiclient.createVpnCustomerGateway(cmd) + self.debug("VPN customer gateway added for VPC %s enabled" %(vpc2.id)) + + # 6) Connect two VPCs + cmd = createVpnConnection.createVpnConnectionCmd() + cmd.s2svpngatewayid = vpn2_response.id + cmd.s2scustomergatewayid = customer1_response.id + cmd.passive="true" + vpnconn1_response = self.apiclient.createVpnConnection(cmd) + self.debug("VPN passive connection created for VPC %s" %(vpc2.id)) + + cmd = createVpnConnection.createVpnConnectionCmd() + cmd.s2svpngatewayid = vpn1_response.id + cmd.s2scustomergatewayid = customer2_response.id + vpnconn2_response = self.apiclient.createVpnConnection(cmd) + self.debug("VPN connection created for VPC %s" %(vpc1.id)) + + self.assertEqual(vpnconn2_response.state, "Connected", "Failed to connect between VPCs!") + + @classmethod + def tearDownClass(cls): + try: + cleanup_resources(cls.apiclient, cls.cleanup) + except Exception, e: + raise Exception("Cleanup failed with %s" % e) diff --git a/tools/marvin/marvin/cloudstackTestClient.py b/tools/marvin/marvin/cloudstackTestClient.py index be93f3581cc..3e833c7ecfd 100644 --- a/tools/marvin/marvin/cloudstackTestClient.py +++ b/tools/marvin/marvin/cloudstackTestClient.py @@ -19,6 +19,10 @@ import cloudstackConnection import asyncJobMgr import dbConnection from cloudstackAPI import * +import random +import string +import hashlib +from configGenerator import ConfigManager ''' @Desc : CloudStackTestClient is encapsulated class for getting various \ @@ -48,6 +52,17 @@ class cloudstackTestClient(object): self.createDbConnection(dbSvrDetails.dbSvr, dbSvrDetails.port, dbSvrDetails.user, dbSvrDetails.passwd, dbSvrDetails.db) + ''' + Provides the Configuration Object to users through getConfigParser + The purpose of this object is to parse the config + and provide dictionary of the config so users can + use that configuration.Users can later call getConfig + on this object and it will return the default parsed + config dictionary from default configuration file, + they can overwrite it with providing their own + configuration file as well. + ''' + self.configObj = ConfigManager() self.asyncJobMgr = None self.id = None self.defaultWorkerThreads = defaultWorkerThreads @@ -154,6 +169,9 @@ class cloudstackTestClient(object): def getDbConnection(self): return self.dbConnection + def getConfigParser(self): + return self.configObj + def getApiClient(self): self.apiClient.id = self.identifier return self.apiClient diff --git a/tools/marvin/marvin/codes.py b/tools/marvin/marvin/codes.py index 3da90d66534..b6580d0d199 100644 --- a/tools/marvin/marvin/codes.py +++ b/tools/marvin/marvin/codes.py @@ -30,6 +30,8 @@ @DateAdded: 20th October 2013 """ +RUNNING = "Running" +RECURRING = "RECURRING" ENABLED = "Enabled" NETWORK_OFFERING = "network_offering" ROOT = "ROOT" @@ -37,3 +39,4 @@ INVALID_INPUT = "INVALID INPUT" EMPTY_LIST = "EMPTY_LIST" FAIL = 0 PASS = 1 +MATCH_NOT_FOUND = "ELEMENT NOT FOUND IN THE INPUT" diff --git a/tools/marvin/marvin/config/setup.cfg b/tools/marvin/marvin/config/setup.cfg new file mode 100644 index 00000000000..216314ff6bc --- /dev/null +++ b/tools/marvin/marvin/config/setup.cfg @@ -0,0 +1,228 @@ +# 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. +{ + "zones": [ + { + "name": "Sandbox-simulator", + "guestcidraddress": "10.1.1.0/24", + "dns1": "10.147.28.6", + "physical_networks": [ + { + "broadcastdomainrange": "Zone", + "vlan": "100-200", + "name": "Sandbox-pnet", + "traffictypes": [ + { + "typ": "Guest" + }, + { + "typ": "Management" + }, + { + "typ": "Public" + } + ], + "providers": [ + { + "broadcastdomainrange": "ZONE", + "name": "VirtualRouter" + }, + { + "broadcastdomainrange": "ZONE", + "name": "VpcVirtualRouter" + }, + { + "broadcastdomainrange": "ZONE", + "name": "InternalLbVm" + } + ], + "isolationmethods": [ + "VLAN" + ] + } + ], + "ipranges": [ + { + "startip": "192.168.2.2", + "endip": "192.168.2.200", + "netmask": "255.255.255.0", + "vlan": "50", + "gateway": "192.168.2.1" + } + ], + "networktype": "Advanced", + "pods": [ + { + "endip": "172.16.15.200", + "name": "POD0", + "startip": "172.16.15.2", + "netmask": "255.255.255.0", + "clusters": [ + { + "clustername": "C0", + "hypervisor": "simulator", + "hosts": [ + { + "username": "root", + "url": "http://sim/c0/h0", + "password": "password" + }, + { + "username": "root", + "url": "http://sim/c0/h1", + "password": "password" + } + ], + "clustertype": "CloudManaged", + "primaryStorages": [ + { + "url": "nfs://10.147.28.6:/export/home/sandbox/primary0", + "name": "PS0" + }, + { + "url": "nfs://10.147.28.6:/export/home/sandbox/primary1", + "name": "PS1" + } + ] + }, + { + "clustername": "C1", + "hypervisor": "simulator", + "hosts": [ + { + "username": "root", + "url": "http://sim/c1/h0", + "password": "password" + } + ], + "clustertype": "CloudManaged", + "primaryStorages": [ + { + "url": "nfs://10.147.28.6:/export/home/sandbox/primary2", + "name": "PS2" + } + ] + } + ], + "gateway": "172.16.15.1" + } + ], + "internaldns1": "10.147.28.6", + "secondaryStorages": [ + { + "url": "nfs://10.147.28.6:/export/home/sandbox/secondary", + "provider" : "NFS" + } + ] + } + ], + "dbSvr": { + "dbSvr": "localhost", + "passwd": "cloud", + "db": "cloud", + "port": 3306, + "user": "cloud" + }, + "logger": [ + { + "name": "TestClient", + "file": "/tmp/testclient.log" + }, + { + "name": "TestCase", + "file": "/tmp/testcase.log" + } + ], + "globalConfig": [ + { + "name": "network.gc.wait", + "value": "60" + }, + { + "name": "storage.cleanup.interval", + "value": "300" + }, + { + "name": "vm.op.wait.interval", + "value": "5" + }, + { + "name": "default.page.size", + "value": "10000" + }, + { + "name": "network.gc.interval", + "value": "60" + }, + { + "name": "instance.name", + "value": "QA" + }, + { + "name": "workers", + "value": "10" + }, + { + "name": "account.cleanup.interval", + "value": "600" + }, + { + "name": "guest.domain.suffix", + "value": "sandbox.simulator" + }, + { + "name": "expunge.delay", + "value": "60" + }, + { + "name": "vm.allocation.algorithm", + "value": "random" + }, + { + "name": "expunge.interval", + "value": "60" + }, + { + "name": "expunge.workers", + "value": "3" + }, + { + "name": "check.pod.cidrs", + "value": "true" + }, + { + "name": "secstorage.allowed.internal.sites", + "value": "10.147.28.0/24" + }, + { + "name": "direct.agent.load.size", + "value": "1000" + } + ], + "mgtSvr": [ + { + "mgtSvrIp": "localhost", + "passwd": "password", + "user": "root", + "port": 8096, + "hypervisor": "simulator", + "useHttps": "False", + "certCAPath": "NA", + "certPath": "NA" + } + ] +} diff --git a/tools/marvin/marvin/configGenerator.py b/tools/marvin/marvin/configGenerator.py index 0cfad30569c..631e40fce43 100644 --- a/tools/marvin/marvin/configGenerator.py +++ b/tools/marvin/marvin/configGenerator.py @@ -19,6 +19,7 @@ import json import os from optparse import OptionParser import jsonHelper +from marvin.codes import * class managementServer(object): @@ -82,7 +83,7 @@ class zone(object): self.cacheStorages = [] -class traffictype(object): +class trafficType(object): def __init__(self, typ, labeldict=None): self.typ = typ # Guest/Management/Public if labeldict: @@ -153,7 +154,7 @@ class host(object): self.memory = None -class physical_network(object): +class physicalNetwork(object): def __init__(self): self.name = None self.tags = [] @@ -299,6 +300,126 @@ class bigip(object): for r in req]) +class ConfigManager(object): + + ''' + @Name: configManager + @Desc: 1. It provides the basic configuration facilities to marvin. + 2. User can just add configuration files for his tests, deployment + etc, under one config folder before running their tests. + cs/tools/marvin/marvin/config. + They can remove all hard coded values from code and separate + it out as config at this location. + Either add this to the existing setup.cfg as separate section + or add new configuration. + 3. This will thus removes hard coded tests and separate + data from tests. + 4. This API is provided as an additional facility under + cloudstackTestClient and users can get the + configuration object as similar to apiclient,dbconnection + etc to drive their test. + 5. They just add their configuration for a test, + setup etc,at one single place under configuration dir + and use "getConfigParser" API of cloudstackTestClient + It will give them "configObj".They can either pass their own + config file for parsing to "getConfig" or it will use + default config file @ config/setup.cfg. + 6. They will then get the dictionary of parsed + configuration and can use it further to drive their tests or + config drive + 7. Test features, can drive their setups thus removing hard coded + values. Configuration default file will be under config and as + setup.cfg. + 8. Users can use their own configuration file passed to + "getConfig" API,once configObj is returned. + ''' + + def __init__(self): + self.filePath = "config/config.cfg" + self.parsedDict = None + if self.__verifyFile(self.filePath) is not False: + self.parsedDict = self.__parseConfig(self.filePath) + + def __parseConfig(self, file): + ''' + @Name : __parseConfig + @Description: Parses the Input configuration Json file + and returns a dictionary from the file. + @Input : NA + @Output : Returns the parsed dictionary from json file + Returns None for invalid input or if parsing failed + ''' + config_dict = None + try: + configlines = [] + with open(file, 'r') as fp: + for line in fp: + if len(line) != 0: + ws = line.strip() + if ws[0] not in ["#"]: + configlines.append(ws) + config_dict = json.loads("\n".join(configlines)) + except Exception, e: + #Will replace with log once we have logging done + print "\n Exception occurred under __parseConfig", e + finally: + return config_dict + + def __verifyFile(self, file): + ''' + @Name : __parseConfig + @Description: Parses the Input configuration Json file + and returns a dictionary from the file. + @Input : file NA + @Output : True or False based upon file input validity + and availability + ''' + if file is None or file == '': + return False + if os.path.exists(file) is False: + return False + return True + + def __getSectionData(self, return_dict, section=None): + ''' + @Name: getSectionData + @Desc: Gets the Section data of a particular section + under parsed dictionary + @Input: Parsed Dictionary from configuration file + section to be returned from this dict + @Output:Section matching inside the parsed data + ''' + if return_dict is not None: + inp = return_dict + elif self.parsedDict is None: + return INVALID_INPUT + else: + inp = self.parsedDict + + if section is not None: + return inp.get(section) + else: + return inp + + def getConfig(self, file_path=None, section=None): + ''' + @Name: getConfig + @Desc : Parses and converts the given configuration file to dictionary + @Input : file_path: path where the configuration needs to be passed + section: specific section inside the file + @Output: INVALID_INPUT: This value is returned if the input + is invalid or not able to be parsed + Parsed configuration dictionary from json file + ''' + ret = None + if file not in [None, '']: + if self.__verifyFile(file_path) is False: + return INVALID_INPUT + else: + ret = self.__parseConfig(file_path) + return self.__getSectionData(ret, section) + + def getDeviceUrl(obj): req = zip(obj.__dict__.keys(), obj.__dict__.values()) if obj.hostname: @@ -309,7 +430,7 @@ def getDeviceUrl(obj): return None -def describe_setup_in_basic_mode(): +def descSetupInBasicMode(): '''sample code to generate setup configuration file''' zs = cloudstackConfiguration() @@ -328,9 +449,9 @@ def describe_setup_in_basic_mode(): sgprovider.broadcastdomainrange = 'Pod' sgprovider.name = 'SecurityGroupProvider' - pn = physical_network() + pn = physicalNetwork() pn.name = "test-network" - pn.traffictypes = [traffictype("Guest"), traffictype("Management")] + pn.traffictypes = [trafficType("Guest"), trafficType("Management")] pn.providers.append(sgprovider) z.physical_networks.append(pn) @@ -428,7 +549,7 @@ def describe_setup_in_basic_mode(): return zs -def describe_setup_in_eip_mode(): +def descSetupInEipMode(): """ Setting up an EIP/ELB enabled zone with netscaler provider """ @@ -462,12 +583,12 @@ def describe_setup_in_eip_mode(): ns.hostname = '10.147.40.100' nsprovider.devices.append(ns) - pn = physical_network() + pn = physicalNetwork() pn.name = "test-network" - pn.traffictypes = [traffictype("Guest", + pn.traffictypes = [trafficType("Guest", {"xen": "cloud-guest"}), - traffictype("Management"), - traffictype("Public", {"xen": "cloud-public"})] + trafficType("Management"), + trafficType("Public", {"xen": "cloud-public"})] pn.providers.extend([sgprovider, nsprovider]) z.physical_networks.append(pn) @@ -563,7 +684,7 @@ def describe_setup_in_eip_mode(): return zs -def describe_setup_in_advanced_mode(): +def descSetupInAdvancedMode(): '''sample code to generate setup configuration file''' zs = cloudstackConfiguration() @@ -578,10 +699,10 @@ def describe_setup_in_advanced_mode(): z.guestcidraddress = "10.1.1.0/24" z.vlan = "100-2000" - pn = physical_network() + pn = physicalNetwork() pn.name = "test-network" - pn.traffictypes = [traffictype("Guest"), traffictype("Management"), - traffictype("Public")] + pn.traffictypes = [trafficType("Guest"), trafficType("Management"), + trafficType("Public")] vpcprovider = provider('VpcVirtualRouter') @@ -697,7 +818,7 @@ def describe_setup_in_advanced_mode(): '''sample code to generate setup configuration file''' -def describe_setup_in_advancedsg_mode(): +def descSetupInAdvancedsgMode(): zs = cloudstackConfiguration() for l in range(1): @@ -711,9 +832,9 @@ def describe_setup_in_advancedsg_mode(): z.vlan = "100-2000" z.securitygroupenabled = "true" - pn = physical_network() + pn = physicalNetwork() pn.name = "test-network" - pn.traffictypes = [traffictype("Guest"), traffictype("Management")] + pn.traffictypes = [trafficType("Guest"), trafficType("Management")] #If security groups are reqd sgprovider = provider() @@ -864,10 +985,10 @@ by default is ./datacenterCfg") if options.inputfile: config = getSetupConfig(options.inputfile) if options.advanced: - config = describe_setup_in_advanced_mode() + config = descSetupInAdvancedMode() elif options.advancedsg: - config = describe_setup_in_advancedsg_mode() + config = descSetupInAdvancedsgMode() else: - config = describe_setup_in_basic_mode() + config = descSetupInBasicMode() generate_setup_config(config, options.output) diff --git a/tools/marvin/marvin/integration/lib/base.py b/tools/marvin/marvin/integration/lib/base.py index 4f151378cc9..10c636c7660 100755 --- a/tools/marvin/marvin/integration/lib/base.py +++ b/tools/marvin/marvin/integration/lib/base.py @@ -449,6 +449,14 @@ class VirtualMachine: cmd.id = self.id apiclient.recoverVirtualMachine(cmd) + def restore(self, apiclient, templateid=None): + """Restore the instance""" + cmd = restoreVirtualMachine.restoreVirtualMachineCmd() + cmd.virtualmachineid = self.id + if templateid: + cmd.templateid = templateid + return apiclient.restoreVirtualMachine(cmd) + def get_ssh_client(self, ipaddress=None, reconnect=False, port=None, keyPairFileLocation=None): """Get SSH object of VM""" @@ -1409,6 +1417,9 @@ class ServiceOffering: if "deploymentplanner" in services: cmd.deploymentplanner = services["deploymentplanner"] + if "isvolatile" in services: + cmd.isvolatile = services["isvolatile"] + # Service Offering private to that domain if domainid: cmd.domainid = domainid diff --git a/tools/marvin/marvin/integration/lib/utils.py b/tools/marvin/marvin/integration/lib/utils.py index 7d662af265c..d53c1ae301d 100644 --- a/tools/marvin/marvin/integration/lib/utils.py +++ b/tools/marvin/marvin/integration/lib/utils.py @@ -323,7 +323,7 @@ def is_snapshot_on_nfs(apiclient, dbconn, config, zoneid, snapshotid): def validateList(inp): ''' - @name: validateList + @name: validateList @Description: 1. A utility function to validate whether the input passed is a list 2. The list is empty or not @@ -353,3 +353,43 @@ def validateList(inp): ret[2] = EMPTY_LIST return ret return [PASS, inp[0], None] + +def verifyElementInList(inp, toverify, pos = 0): + ''' + @name: verifyElementInList + @Description: + 1. A utility function to validate + whether the input passed is a list. + The list is empty or not. + If it is list and not empty, verify + whether a given element is there in that list or not + at a given pos + @Input: + I : Input to be verified whether its a list or not + II : Element to verify whether it exists in the list + III : Position in the list at which the input element to verify + default to 0 + @output: List, containing [ Result,Reason ] + Ist Argument('Result') : FAIL : If it is not a list + If it is list but empty + PASS : If it is list and not empty + and matching element was found + IIrd Argument( 'Reason' ): Reason for failure ( FAIL ), + default to None. + INVALID_INPUT + EMPTY_LIST + MATCH_NOT_FOUND + ''' + if toverify is None or toverify == '' \ + or pos is None or pos < -1 or pos == '': + return [FAIL, INVALID_INPUT] + out = validateList(inp) + if out[0] == FAIL: + return [FAIL, out[2]] + if out[0] == PASS: + if len(inp) > pos and inp[pos] == toverify: + return [PASS, None] + else: + return [FAIL, MATCH_NOT_FOUND] + + diff --git a/ui/css/cloudstack3.css b/ui/css/cloudstack3.css index a75027a3acc..ba2439a3ca7 100644 --- a/ui/css/cloudstack3.css +++ b/ui/css/cloudstack3.css @@ -173,6 +173,23 @@ table tbody td.truncated > span { text-overflow: ellipsis; } +/** Multiselect*/ +table thead th.multiselect, +table tbody td.multiselect { + width: 40px; + min-width: 40px; + max-width: 40px; +} + +table thead th.multiselect input, +table tbody td.multiselect input { + margin: 0; +} + +table thead th.multiselect input { + margin-left: 2px; +} + /** Actions table cell*/ table tbody td.actions { width: 130px; @@ -299,23 +316,19 @@ table th div.ui-resizable-handle { /*Login screen*/ body.login { - background: transparent url(../images/bg-login.png) repeat 50% -82px; + background: url(../images/overlay-pattern.png) repeat center, #106CA9 url(../images/bg-login.jpg) no-repeat center; + background-size: auto, cover; } .login { display: block; width: 100%; - height: 245px; - /*+placement:shift 0 100px;*/ + height: 350px; + /*+placement:shift 0 80px;*/ position: relative; left: 0; - top: 100px; - background: #FFFFFF; - /*+box-shadow:0px 3px 5px #D5D5D5;*/ - -moz-box-shadow: 0px 3px 5px #D5D5D5; - -webkit-box-shadow: 0px 3px 5px #D5D5D5; - -o-box-shadow: 0px 3px 5px #D5D5D5; - box-shadow: 0px 3px 5px #D5D5D5; + top: 80px; + background: #053663; } .login .select-language { @@ -324,8 +337,9 @@ body.login { } .login .select-language select { - width: 125px; + width: 260px; border: 1px solid #808080; + margin-top: 30px; /*+border-radius:4px;*/ -moz-border-radius: 4px; -webkit-border-radius: 4px; @@ -351,33 +365,34 @@ body.login { } .login .fields .field label { - font-size: 11px; + font-size: 12px; color: #4E4F53; - /*+placement:displace 10px 12px;*/ + /*+placement:displace 9px 14px;*/ position: absolute; - margin-left: 10px; - margin-top: 12px; + margin-left: 9px; + margin-top: 14px; } .login .fields .field label.error { color: #FF0000; float: right; - left: 204px; + left: 264px; top: 0; } .login .fields input { - width: 204px; + width: 248px; height: 20px; margin: 5px 0 0; - text-indent: 7px; + text-indent: 1px; + font-size: 13px; border: none; - /*+border-radius:4px;*/ - -moz-border-radius: 4px; - -webkit-border-radius: 4px; - -khtml-border-radius: 4px; - border-radius: 4px; - border-radius: 4px 4px 4px 4px; + padding: 5px; + /*+border-radius:3px;*/ + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + -khtml-border-radius: 3px; + border-radius: 3px; /*+box-shadow:inset 0px 1px 1px #4E4E4E;*/ -moz-box-shadow: inset 0px 1px 1px #4E4E4E; -webkit-box-shadow: inset 0px 1px 1px #4E4E4E; @@ -432,7 +447,7 @@ body.login { width: 1000px; height: 100%; margin: auto; - background: #FFFFFF; + background: #053663; } /*About dialog*/ @@ -971,9 +986,9 @@ div.notification-box .container ul { } div.notification-box .container ul li { - height: 40px; + width: 100%; + height: 41px; border-bottom: 1px solid #CECECE; - overflow: auto; overflow-x: hidden; text-indent: 0; font-size: 12px; @@ -983,16 +998,37 @@ div.notification-box .container ul li { } div.notification-box .container ul li.error { - background: url(../images/icons.png) no-repeat 10px -179px; + height: 53px; + background: url(../images/icons.png) no-repeat 10px -171px; +} + +div.notification-box .container ul li.error .subtitle { + display: block; + width: 213px; + height: 10px; + overflow: hidden; + white-space: nowrap; + float: left; + text-overflow: ellipsis; + color: #808080; + text-indent: 0; + padding: 0; + margin: 0; + /*+placement:shift 48px 17px;*/ + position: relative; + left: 48px; + top: 17px; } div.notification-box .container ul li span { float: left; - /*+placement:shift 48px 16px;*/ + /*+placement:shift 48px 15px;*/ position: relative; left: 48px; - top: 16px; + top: 15px; max-width: 202px; + font-size: 14px; + font-weight: 100; overflow: hidden; } @@ -1087,58 +1123,75 @@ div.notification-box .button.close:hover { /*** Corner alert*/ div.notification.corner-alert { - background: #EBE8E8; + background: #FFFFFF; + background: rgba(255, 255, 255, 0.95); + /*+box-shadow:0px 2px 10px #000000;*/ + -moz-box-shadow: 0px 2px 10px #000000; + -webkit-box-shadow: 0px 2px 10px #000000; + -o-box-shadow: 0px 2px 10px #000000; + box-shadow: 0px 2px 10px #000000; width: 300px; - height: 70px; + height: 75px; + /*+border-radius:3px;*/ + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + -khtml-border-radius: 3px; + border-radius: 3px; position: absolute; text-indent: 10px; + padding: 7px 7px 0; font-size: 12px; - border: 1px solid #8F8A8A; /*+opacity:70%;*/ filter: alpha(opacity=70); -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=70); -moz-opacity: 0.7; opacity: 0.7; - overflow: hidden; z-index: 100; - cursor: pointer; + margin: 38px 0 0 -56px; +} + +div.notification.corner-alert .top-arrow { + background: url(../images/sprites.png) no-repeat -580px -1353px; + width: 36px; + height: 15px; + position: absolute; + top: -15px; + left: 50px; } div.notification.corner-alert div.title { width: 100%; height: 33px; - background: url(../images/bg-dialog-header.png); color: #FFFFFF; } div.notification.corner-alert div.title span { - background: url(../images/icons.png) no-repeat -3px -225px; /*+placement:shift 0px 10px;*/ position: relative; left: 0px; top: 10px; - /*+text-shadow:0px 1px 1px #3A3A3A;*/ - -moz-text-shadow: 0px 1px 1px #3A3A3A; - -webkit-text-shadow: 0px 1px 1px #3A3A3A; - -o-text-shadow: 0px 1px 1px #3A3A3A; - text-shadow: 0px 1px 1px #3A3A3A; + color: #6D6D6D; padding: 3px 0 12px 24px; - font-weight: bold; + font-weight: 100; + font-size: 14px; + padding-left: 33px; + background: url(../images/icons.png) no-repeat 3px -223px; } div.notification.corner-alert.error div.title span { - background: url(../images/icons.png) no-repeat -4px -190px; + background: url(../images/icons.png) no-repeat -2px -190px; } div.notification.corner-alert div.message span { position: relative; padding-top: 6px; + font-size: 14px; display: block; -} - -div.notification.corner-alert:hover div.message span { - text-decoration: underline; - color: #5FAAF7; + color: #000000; + /*+placement:shift 17px -2px;*/ + position: relative; + left: 17px; + top: -2px; } /*Tooltips*/ @@ -1309,6 +1362,7 @@ div.list-view td.state.off span { width: 470px; display: inline-block; padding-top: 50px; + margin-left: 8px; } .quick-view-tooltip > div.title { @@ -11715,7 +11769,7 @@ div.ui-dialog div.autoscaler div.field-group div.form-container form div.form-it color: #FFFFFF; font-size: 12px; font-weight: bold; - max-width: 67px; + max-width: 285px; overflow: hidden; white-space: nowrap; /*+placement:shift -1px 0px;*/ @@ -11780,6 +11834,7 @@ div.ui-dialog div.autoscaler div.field-group div.form-container form div.form-it .destroy .icon, .expunge .icon, .remove .icon, +.removeMulti .icon, .delete .icon, .decline .icon, .deleteacllist .icon { diff --git a/ui/dictionary.jsp b/ui/dictionary.jsp index 1bf0eab4648..ed269c8a3a0 100644 --- a/ui/dictionary.jsp +++ b/ui/dictionary.jsp @@ -1133,6 +1133,8 @@ dictionary = { 'label.use.vm.ip': '', 'label.value': '', 'label.vcdcname': '', +'label.vnet': '', +'label.vnet.id': '', 'label.vcenter.cluster': '', 'label.vcenter.datacenter': '', 'label.vcenter.datastore': '', diff --git a/ui/images/sprites.png b/ui/images/sprites.png index f3c8226b64a..778eda23fd0 100644 Binary files a/ui/images/sprites.png and b/ui/images/sprites.png differ diff --git a/ui/index.jsp b/ui/index.jsp index a4e3e4cbcac..56a4b27f6dd 100644 --- a/ui/index.jsp +++ b/ui/index.jsp @@ -1110,7 +1110,7 @@ view-all-title="" view-all-target="systemVms"> -

  • +
  •   @@ -1118,12 +1118,15 @@ view-all-title="" view-all-target="virtualRouters">
  • +
  • + +   + + " + view-all-target="sockets"> +
  • - -
    -
    -
      -
      diff --git a/ui/scripts/accounts.js b/ui/scripts/accounts.js index a754d31b478..7267252bf7f 100644 --- a/ui/scripts/accounts.js +++ b/ui/scripts/accounts.js @@ -66,7 +66,7 @@ add: { label: 'label.add.account', preFilter: function(args) { - if (isAdmin()) + if (isAdmin() || isDomainAdmin()) return true; else return false; @@ -901,7 +901,7 @@ label: 'label.add.user', preFilter: function(args) { - if (isAdmin()) + if (isAdmin() || isDomainAdmin()) return true; else return false; @@ -1409,6 +1409,16 @@ } allowedActions.push("updateResourceCount"); } else if (isDomainAdmin()) { + if (jsonObj.name != g_account) { + allowedActions.push("edit"); //updating networkdomain is allowed on any account, including system-generated default admin account + if (jsonObj.state == "enabled") { + allowedActions.push("disable"); + allowedActions.push("lock"); + } else if (jsonObj.state == "disabled" || jsonObj.state == "locked") { + allowedActions.push("enable"); + } + allowedActions.push("remove"); + } allowedActions.push("updateResourceCount"); } return allowedActions; @@ -1434,6 +1444,14 @@ } } else { if (isSelfOrChildDomainUser(jsonObj.username, jsonObj.accounttype, jsonObj.domainid, jsonObj.iscallerchilddomain)) { + if (isDomainAdmin() && jsonObj.username != g_username) { + allowedActions.push("edit"); + if (jsonObj.state == "enabled") + allowedActions.push("disable"); + if (jsonObj.state == "disabled") + allowedActions.push("enable"); + allowedActions.push("remove"); + } allowedActions.push("changePassword"); allowedActions.push("generateKeys"); } diff --git a/ui/scripts/events.js b/ui/scripts/events.js index 38f7136c140..fdc496e2c45 100644 --- a/ui/scripts/events.js +++ b/ui/scripts/events.js @@ -34,6 +34,7 @@ listView: { id: 'events', label: 'label.menu.events', + multiSelect: true, fields: { description: { label: 'label.description' @@ -58,6 +59,40 @@ actions: { // Remove multiple events + removeMulti: { + label: 'label.delete.events', + isHeader: true, + addRow: false, + isMultiSelectAction: true, + messages: { + confirm: function(args) { + return 'Please confirm you would like to remove the selected events'; + }, + notification: function(args) { + return 'label.delete.events'; + } + }, + action: function(args) { + var events = args.context.events; + + $.ajax({ + url: createURL("deleteEvents"), + data: { + ids: $(events).map(function(index, event) { + return event.id; + }).toArray().join(',') + }, + success: function(data) { + args.response.success(); + $(window).trigger('cloudStack.fullRefresh'); + }, + error:function(data) { + args.response.error(parseXMLHttpResponse(data)); + } + }); + } + }, + remove: { label: 'label.delete.events', isHeader: true, @@ -118,8 +153,7 @@ }); } }, - - // Archive multiple events + archive: { label: 'label.archive.events', isHeader: true, @@ -179,6 +213,41 @@ }); } + }, + + // Archive multiple events + archiveMulti: { + label: 'label.archive.events', + isHeader: true, + addRow: false, + isMultiSelectAction: true, + messages: { + confirm: function(args) { + return 'Please confirm you would like to archive the selected events'; + }, + notification: function(args) { + return 'label.archive.events'; + } + }, + action: function(args) { + var events = args.context.events; + + $.ajax({ + url: createURL("archiveEvents"), + data: { + ids: $(events).map(function(index, event) { + return event.id; + }).toArray().join(',') + }, + success: function(data) { + args.response.success(); + $(window).trigger('cloudStack.fullRefresh'); + }, + error:function(data) { + args.response.error(parseXMLHttpResponse(data)); + } + }); + } } }, @@ -384,6 +453,7 @@ listView: { id: 'alerts', label: 'label.menu.alerts', + multiSelect: true, fields: { description: { label: 'label.description' @@ -399,6 +469,40 @@ actions: { // Remove multiple Alerts + removeMulti: { + label: 'label.delete.alerts', + isHeader: true, + addRow: false, + isMultiSelectAction: true, + messages: { + confirm: function(args) { + return 'Please confirm you would like to remove the selected alerts'; + }, + notification: function(args) { + return 'label.delete.alerts'; + } + }, + action: function(args) { + var events = args.context.alerts; + + $.ajax({ + url: createURL("deleteAlerts"), + data: { + ids: $(events).map(function(index, event) { + return event.id; + }).toArray().join(',') + }, + success: function(data) { + args.response.success(); + $(window).trigger('cloudStack.fullRefresh'); + }, + error:function(data) { + args.response.error(parseXMLHttpResponse(data)); + } + }); + } + }, + remove: { label: 'label.delete.alerts', isHeader: true, @@ -464,6 +568,40 @@ }, // Archive multiple Alerts + archiveMulti: { + label: 'label.archive.alerts', + isHeader: true, + addRow: false, + isMultiSelectAction: true, + messages: { + confirm: function(args) { + return 'Please confirm you would like to archive the selected alerts'; + }, + notification: function(args) { + return 'label.archive.alerts'; + } + }, + action: function(args) { + var events = args.context.alerts; + + $.ajax({ + url: createURL("archiveAlerts"), + data: { + ids: $(events).map(function(index, event) { + return event.id; + }).toArray().join(',') + }, + success: function(data) { + args.response.success(); + $(window).trigger('cloudStack.fullRefresh'); + }, + error:function(data) { + args.response.error(parseXMLHttpResponse(data)); + } + }); + } + }, + archive: { label: 'label.archive.alerts', isHeader: true, diff --git a/ui/scripts/instanceWizard.js b/ui/scripts/instanceWizard.js index d2cde2f270c..5f08218c638 100644 --- a/ui/scripts/instanceWizard.js +++ b/ui/scripts/instanceWizard.js @@ -18,6 +18,7 @@ (function($, cloudStack) { var zoneObjs, hypervisorObjs, featuredTemplateObjs, communityTemplateObjs, myTemplateObjs, featuredIsoObjs, community, networkObjs; var selectedZoneObj, selectedTemplateObj, selectedHypervisor, selectedDiskOfferingObj; + var selectedTemplateOrIso; //'select-template', 'select-iso' var step6ContainerType = 'nothing-to-select'; //'nothing-to-select', 'select-network', 'select-security-group', 'select-advanced-sg'(advanced sg-enabled zone) cloudStack.instanceWizard = { @@ -122,8 +123,8 @@ }); //***** get templates/ISOs (begin) ***** - var selectedTemplate = args.currentData['select-template']; - if (selectedTemplate == 'select-template') { + selectedTemplateOrIso = args.currentData['select-template']; + if (selectedTemplateOrIso == 'select-template') { var hypervisorArray = []; $(hypervisorObjs).each(function(index, item) { hypervisorArray.push(item.name); @@ -174,7 +175,7 @@ } } }); - } else if (selectedTemplate == 'select-iso') { + } else if (selectedTemplateOrIso == 'select-iso') { $.ajax({ url: createURL("listIsos&isofilter=featured&zoneid=" + args.currentData.zoneid + "&bootable=true"), dataType: "json", @@ -216,13 +217,13 @@ var templatesObj = {}; - if (selectedTemplate == 'select-template') { + if (selectedTemplateOrIso == 'select-template') { templatesObj = { featuredtemplates: featuredTemplateObjs, communitytemplates: communityTemplateObjs, mytemplates: myTemplateObjs } - } else if (selectedTemplate == 'select-iso') { + } else if (selectedTemplateOrIso == 'select-iso') { templatesObj = { featuredisos: featuredIsoObjs, communityisos: communityIsoObjs, @@ -239,9 +240,9 @@ hypervisors: hypervisorObjs }, customHidden: function(args) { - if (selectedTemplate == 'select-template') { + if (selectedTemplateOrIso == 'select-template') { return false; //show Root Disk Size field - } else { //selectedTemplate == 'select-iso' + } else { //selectedTemplateOrIso == 'select-iso' return true; //hide Root Disk Size field } } @@ -295,6 +296,7 @@ serviceOfferingObjs = json.listserviceofferingsresponse.serviceoffering; args.response.success({ customFlag: 'iscustomized', + //customFlag: 'offerha', //for testing only data: { serviceOfferings: serviceOfferingObjs } @@ -587,10 +589,28 @@ //step 2: select template array1.push("&templateId=" + args.data.templateid); array1.push("&hypervisor=" + selectedHypervisor); - + + if (args.$wizard.find('input[name=rootDiskSize]').parent().css('display') != 'none') { + if (args.$wizard.find('input[name=rootDiskSize]').val().length > 0) { + array1.push("&rootdisksize=" + args.$wizard.find('input[name=rootDiskSize]').val()); + } + } + //step 3: select service offering array1.push("&serviceOfferingId=" + args.data.serviceofferingid); - + + if (args.$wizard.find('input[name=compute-cpu-cores]').parent().parent().css('display') != 'none') { + if (args.$wizard.find('input[name=compute-cpu-cores]').val().length > 0) { + array1.push("&cpunumber=" + args.$wizard.find('input[name=compute-cpu-cores]').val()); + } + if (args.$wizard.find('input[name=compute-cpu]').val().length > 0) { + array1.push("&cpuspeed=" + args.$wizard.find('input[name=compute-cpu]').val()); + } + if (args.$wizard.find('input[name=compute-memory]').val().length > 0) { + array1.push("&memory=" + args.$wizard.find('input[name=compute-memory]').val()); + } + } + //step 4: select disk offering if (args.data.diskofferingid != null && args.data.diskofferingid != "0") { array1.push("&diskOfferingId=" + args.data.diskofferingid); diff --git a/ui/scripts/instances.js b/ui/scripts/instances.js index ac8605a4f1d..71c5a320bb8 100644 --- a/ui/scripts/instances.js +++ b/ui/scripts/instances.js @@ -16,10 +16,96 @@ // under the License. (function($, cloudStack) { var vmMigrationHostObjs; + + var vmSnapshotAction = function(args) { + var action = { + messages: { + notification: function(args) { + return 'label.action.vmsnapshot.create'; + } + }, + label: 'label.action.vmsnapshot.create', + addRow: 'false', + createForm: { + title: 'label.action.vmsnapshot.create', + fields: { + name: { + label: 'label.name', + isInput: true + }, + description: { + label: 'label.description', + isTextarea: true + }, + snapshotMemory: { + label: 'label.vmsnapshot.memory', + isBoolean: true, + isChecked: false + }, + quiescevm: { + label: 'Quiesce VM', + isBoolean: true, + isChecked: false + } + } + }, + action: function(args) { + var instances = args.context.instances; + + $(instances).map(function(index, instance) { + var array1 = []; + array1.push("&snapshotmemory=" + (args.data.snapshotMemory == "on")); + array1.push("&quiescevm=" + (args.data.quiescevm == "on")); + var displayname = args.data.name; + if (displayname != null && displayname.length > 0) { + array1.push("&name=" + todb(displayname)); + } + var description = args.data.description; + if (description != null && description.length > 0) { + array1.push("&description=" + todb(description)); + } + $.ajax({ + url: createURL("createVMSnapshot&virtualmachineid=" + instance.id + array1.join("")), + dataType: "json", + async: true, + success: function(json) { + var jid = json.createvmsnapshotresponse.jobid; + args.response.success({ + _custom: { + jobId: jid, + getUpdatedItem: function(json) { + return json.queryasyncjobresultresponse.jobresult.virtualmachine; + }, + getActionFilter: function() { + return vmActionfilter; + } + } + }); + } + }); + }); + + }, + notification: { + poll: pollAsyncJobResult + } + }; + + if (args && args.listView) { + $.extend(action, { + isHeader: true, + isMultiSelectAction: true + }); + } + + return action; + }; + cloudStack.sections.instances = { title: 'label.instances', id: 'instances', listView: { + multiSelect: true, section: 'instances', filters: { all: { @@ -181,7 +267,8 @@ notification: { poll: pollAsyncJobResult } - } + }, + snapshot: vmSnapshotAction({ listView: true }) }, dataProvider: function(args) { @@ -246,7 +333,6 @@ success: function(json) { var items = json.listvirtualmachinesresponse.virtualmachine; args.response.success({ - actionFilter: vmActionfilter, data: items }); } @@ -470,68 +556,7 @@ poll: pollAsyncJobResult } }, - snapshot: { - messages: { - notification: function(args) { - return 'label.action.vmsnapshot.create'; - } - }, - label: 'label.action.vmsnapshot.create', - addRow: 'false', - createForm: { - title: 'label.action.vmsnapshot.create', - fields: { - name: { - label: 'label.name', - isInput: true - }, - description: { - label: 'label.description', - isTextarea: true - }, - snapshotMemory: { - label: 'label.vmsnapshot.memory', - isBoolean: true, - isChecked: false - } - } - }, - action: function(args) { - var array1 = []; - array1.push("&snapshotmemory=" + (args.data.snapshotMemory == "on")); - var displayname = args.data.name; - if (displayname != null && displayname.length > 0) { - array1.push("&name=" + todb(displayname)); - } - var description = args.data.description; - if (description != null && description.length > 0) { - array1.push("&description=" + todb(description)); - } - $.ajax({ - url: createURL("createVMSnapshot&virtualmachineid=" + args.context.instances[0].id + array1.join("")), - dataType: "json", - async: true, - success: function(json) { - var jid = json.createvmsnapshotresponse.jobid; - args.response.success({ - _custom: { - jobId: jid, - getUpdatedItem: function(json) { - return json.queryasyncjobresultresponse.jobresult.virtualmachine; - }, - getActionFilter: function() { - return vmActionfilter; - } - } - }); - } - }); - - }, - notification: { - poll: pollAsyncJobResult - } - }, + snapshot: vmSnapshotAction(), destroy: { label: 'label.action.destroy.instance', compactLabel: 'label.destroy', @@ -1789,8 +1814,9 @@ $.ajax({ url: createURL('listNetworks'), data: { - listAll: true, - zoneid: args.context.instances[0].zoneid + zoneid: args.context.instances[0].zoneid, + account: args.context.instances[0].account, + domainid: args.context.instances[0].domainid }, success: function(json) { args.response.success({ diff --git a/ui/scripts/network.js b/ui/scripts/network.js index 12e5389d9e6..4196b108cf3 100755 --- a/ui/scripts/network.js +++ b/ui/scripts/network.js @@ -536,6 +536,48 @@ }, networkDomain: { label: 'label.network.domain' + }, + domain: { + label: 'label.domain', + select: function(args) { + var items = []; + $.ajax({ + url: createURL("listDomains&listAll=true"), + dataType: "json", + async: false, + success: function(json) { + var items = []; + items.push({ + id: "", + description: "" + }); + var domainObjs = json.listdomainsresponse.domain; + $(domainObjs).each(function() { + items.push({ + id: this.id, + description: this.path + }); + }); + args.response.success({ + data: items + }); + } + }); + args.$select.change(function() { + var $form = $(this).closest('form'); + if ($(this).val() == "") { + $form.find('.form-item[rel=account]').hide(); + } else { + $form.find('.form-item[rel=account]').css('display', 'inline-block'); + } + }); + }, + }, + account: { + label: 'label.account', + validation: { + required: true + }, } } }, @@ -575,6 +617,17 @@ }); } + if (args.data.domain != null && args.data.domain.length > 0) { + $.extend(dataObj, { + domainid: args.data.domain + }); + if (args.data.account != null && args.data.account.length > 0) { + $.extend(dataObj, { + account: args.data.account + }); + } + } + $.ajax({ url: createURL('createNetwork'), data: dataObj, @@ -1098,7 +1151,7 @@ } }, vlan: { - label: 'label.vlan.id' + label: 'label.vnet.id' }, broadcasturi: { diff --git a/ui/scripts/plugins.js b/ui/scripts/plugins.js index 50da509eaa8..afeae7c7eaf 100644 --- a/ui/scripts/plugins.js +++ b/ui/scripts/plugins.js @@ -51,7 +51,8 @@ }, addSection: function(section) { cloudStack.sections[section.id] = $.extend(section, { - customIcon: 'plugins/' + section.id + '/icon.png' + customIcon: 'plugins/' + section.id + '/icon.png', + isPlugin: true }); }, extend: function(obj) { diff --git a/ui/scripts/sharedFunctions.js b/ui/scripts/sharedFunctions.js index fb07d3715a9..05d2d9d43cd 100644 --- a/ui/scripts/sharedFunctions.js +++ b/ui/scripts/sharedFunctions.js @@ -766,7 +766,7 @@ var addGuestNetworkDialog = { function isSelfOrChildDomainUser(username, useraccounttype, userdomainid, iscallerchilddomain) { if (username == g_username) { //is self return true; - } else if (isDomainAdmin() && iscallerchilddomain && (useraccounttype == 0)) { //domain admin to user + } else if (isDomainAdmin() && !iscallerchilddomain && (useraccounttype == 0)) { //domain admin to user return true; } else if (isDomainAdmin() && iscallerchilddomain && (userdomainid != g_domainid)) { //domain admin to subdomain admin and user return true; diff --git a/ui/scripts/system.js b/ui/scripts/system.js index 088cb3cff59..15959483367 100644 --- a/ui/scripts/system.js +++ b/ui/scripts/system.js @@ -381,22 +381,9 @@ }, socketInfo: function(data) { - $.ajax({ - url: createURL('listHypervisors'), - success: function(json) { - var hypervisors = json.listhypervisorsresponse.hypervisor; - - complete($.extend(data, { - socketInfo: $(hypervisors).map(function(index, hypervisor) { - return { - name: hypervisor.name, - hosts: 0, - sockets: 0 - }; - }) - })); - } - }); + complete($.extend(data, { + socketCount: 0 + })); } }; @@ -1165,7 +1152,7 @@ label: 'label.state' }, vlan: { - label: 'VLAN Range(s)', + label: 'VLAN/VNI Range(s)', isEditable: true }, tags: { @@ -1397,7 +1384,7 @@ label: 'label.type' }, vlan: { - label: 'label.vlan.id' + label: 'label.vnet.id' }, broadcasturi: { label: 'broadcast URI' @@ -1833,13 +1820,13 @@ }, dedicatedGuestVlanRanges: { - title: 'Dedicated VLAN Ranges', + title: 'Dedicated VLAN/VNI Ranges', listView: { section: 'dedicatedGuestVlanRanges', id: 'dedicatedGuestVlanRanges', fields: { guestvlanrange: { - label: 'VLAN Range(s)' + label: 'VLAN/VNI Range(s)' }, domain: { label: 'label.domain' @@ -1864,17 +1851,17 @@ }, actions: { add: { - label: 'Dedicate VLAN Range', + label: 'Dedicate VLAN/VNI Range', messages: { notification: function(args) { - return 'Dedicate VLAN Range'; + return 'Dedicate VLAN/VNI Range'; } }, createForm: { - title: 'Dedicate VLAN Range', + title: 'Dedicate VLAN/VNI Range', fields: { vlanrange: { - label: 'VLAN Range', + label: 'VLAN/VNI Range', /* select: function(args) { var items = []; if(args.context.physicalNetworks[0].vlan != null && args.context.physicalNetworks[0].vlan.length > 0) { @@ -7131,6 +7118,35 @@ } }); + return listView; + }, + + sockets: function() { + var listView = { + id: 'sockets', + fields: { + hypervisor: { label: 'label.hypervisor' }, + sockets: { label: 'label.sockets' }, + hosts: { label: 'label.hosts' } + }, + dataProvider: function(args) { + $.ajax({ + url: createURL('listHypervisors'), + success: function(json) { + args.response.success({ + data: $(json.listhypervisorsresponse.hypervisor).map(function(index, hypervisor) { + return { + hypervisor: hypervisor.name, + sockets: 0, + hosts: 0 + }; + }) + }); + } + }); + } + }; + return listView; } } diff --git a/ui/scripts/ui-custom/instanceWizard.js b/ui/scripts/ui-custom/instanceWizard.js index 4368ec47ac3..d5203c84d9c 100644 --- a/ui/scripts/ui-custom/instanceWizard.js +++ b/ui/scripts/ui-custom/instanceWizard.js @@ -49,6 +49,7 @@ // Populate data context: context, data: data, + $wizard: $wizard, response: { success: function(args) { var $listView = $('.list-view.instances'); diff --git a/ui/scripts/ui-custom/pluginListing.js b/ui/scripts/ui-custom/pluginListing.js index 1d4a090ff2b..e679c626526 100644 --- a/ui/scripts/ui-custom/pluginListing.js +++ b/ui/scripts/ui-custom/pluginListing.js @@ -52,6 +52,14 @@ var $browser = $('#browser .container'); $plugin.click(function() { + var $mainSection = $('#navigation ul li').filter('.' + plugin.id); + + if ($mainSection.size()) { + $mainSection.click(); + + return; + } + $browser.cloudBrowser('addPanel', { title: plugin.title, $parent: $('.panel:first'), diff --git a/ui/scripts/ui/core.js b/ui/scripts/ui/core.js index 2ae0b64a5d4..06be12b7b6b 100644 --- a/ui/scripts/ui/core.js +++ b/ui/scripts/ui/core.js @@ -61,6 +61,10 @@ ); } + if (args.isPlugin) { + $li.hide(); + } + $li.appendTo($navList); return true; @@ -84,18 +88,25 @@ return $(this).hasClass(sectionID); }); var data = args.sections[sectionID]; + var isPlugin = data.isPlugin; data.$browser = $browser; - $navItem.siblings().removeClass('active'); - $navItem.addClass('active'); // Reset browser panels - $browser.cloudBrowser('removeAllPanels'); + if (!isPlugin) { + $navItem.siblings().removeClass('active'); + $navItem.addClass('active'); + $browser.cloudBrowser('removeAllPanels'); + } + $browser.cloudBrowser('addPanel', { title: '' + _l(data.title) + '' + '', data: '', complete: function($panel, $breadcrumb) { - $breadcrumb.attr('title', _l(data.title)); + if(!isPlugin) { + $breadcrumb.attr('title', _l(data.title)); + } + data.$breadcrumb = $breadcrumb; // Hide breadcrumb if this is the home section diff --git a/ui/scripts/ui/widgets/listView.js b/ui/scripts/ui/widgets/listView.js index 21d03b14e2a..3fa8f5418e6 100644 --- a/ui/scripts/ui/widgets/listView.js +++ b/ui/scripts/ui/widgets/listView.js @@ -767,7 +767,7 @@ hiddenFields = preFilter(); if (multiSelect) { - var $th = $('').appendTo($thead.find('tr')); + var $th = $('').addClass('multiselect').appendTo($thead.find('tr')); var content = $('') .attr('type', 'checkbox') .addClass('multiSelectMasterCheckbox') @@ -1054,7 +1054,8 @@ if (multiSelect) { var $td = $('') - .appendTo($tr); + .addClass('multiselect') + .appendTo($tr); var content = $('') .attr('type', 'checkbox') .addClass('multiSelectCheckbox') @@ -2191,6 +2192,7 @@ false, null, listViewArgs.actions, { + multiSelect: listViewArgs.multiSelect, context: this.data('view-args').context, detailView: listViewArgs.detailView } diff --git a/ui/scripts/ui/widgets/notifications.js b/ui/scripts/ui/widgets/notifications.js index 9b7fc4cce03..5fd91f19641 100644 --- a/ui/scripts/ui/widgets/notifications.js +++ b/ui/scripts/ui/widgets/notifications.js @@ -23,11 +23,12 @@ cornerAlert: function(args, options) { if (!options) options = {}; - var $container = $('#container'); // Put in main container box + var $container = $('#main-area'); // Put in main container box var $cornerAlert = $('
      ').addClass('notification corner-alert') .hide() - .appendTo($container) + .appendTo('html body') .append( + $('
      ').addClass('top-arrow'), $('
      ').addClass('title').append( $('').html( options.error ? options.error : _l('label.task.completed') @@ -49,19 +50,18 @@ .css({ opacity: 0, position: 'absolute', - top: $($container).height(), - left: $($container).width() - $cornerAlert.width() + top: $('#header .notifications').offset().top, + left: $('#header .notifications').offset().left }) .animate({ - opacity: 1, - top: $container.height() - $cornerAlert.height() + opacity: 1 }, { complete: function() { setTimeout(function() { $cornerAlert.fadeOut('fast', function() { $cornerAlert.remove(); }); - }, 5000); + }, 3000); } }) .show(); @@ -124,7 +124,11 @@ }, { error: _l('label.error') }); - $item.removeClass('pending').addClass('error'); + $item.removeClass('pending').addClass('error').append( + $('
      ').addClass('subtitle').html(args && args.message ? + args.message : _l('label.error')) + ); + $item.attr('title', args && args.message ? args.message : _l('label.error')); if (additionalComplete) additionalComplete(); } diff --git a/ui/scripts/vpc.js b/ui/scripts/vpc.js index f25e57dc0a6..2dc916244a0 100644 --- a/ui/scripts/vpc.js +++ b/ui/scripts/vpc.js @@ -2792,7 +2792,12 @@ } }); } - } + }, + passive: { + label: 'Passive', + isBoolean: true, + isChecked: false + } } }, action: function(args) { @@ -2819,7 +2824,8 @@ url: createURL('createVpnConnection'), data: { s2svpngatewayid: vpngatewayid, - s2scustomergatewayid: args.data.vpncustomergatewayid + s2scustomergatewayid: args.data.vpncustomergatewayid, + passive: (args.data.passive == 'on'? true: false) }, success: function(json) { var jid = json.createvpnconnectionresponse.jobid; diff --git a/usage/pom.xml b/usage/pom.xml index 04d16307601..e71a1d07de5 100644 --- a/usage/pom.xml +++ b/usage/pom.xml @@ -119,6 +119,39 @@ + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-antrun-plugin + + [1.7,) + + run + + + + + + + + + + + + diff --git a/utils/src/com/cloud/utils/PropertiesUtil.java b/utils/src/com/cloud/utils/PropertiesUtil.java index 6f3796a9f0b..78d4013ea3d 100755 --- a/utils/src/com/cloud/utils/PropertiesUtil.java +++ b/utils/src/com/cloud/utils/PropertiesUtil.java @@ -41,12 +41,12 @@ public class PropertiesUtil { public static File findConfigFile(String path) { ClassLoader cl = PropertiesUtil.class.getClassLoader(); URL url = cl.getResource(path); - if (url != null) { + if (url != null && "file".equals(url.getProtocol())) { return new File(url.getFile()); } url = ClassLoader.getSystemResource(path); - if (url != null) { + if (url != null && "file".equals(url.getProtocol())) { return new File(url.getFile()); } @@ -57,12 +57,12 @@ public class PropertiesUtil { String newPath = "conf" + (path.startsWith(File.separator) ? "" : "/") + path; url = ClassLoader.getSystemResource(newPath); - if (url != null) { + if (url != null && "file".equals(url.getProtocol())) { return new File(url.getFile()); } url = cl.getResource(newPath); - if (url != null) { + if (url != null && "file".equals(url.getProtocol())) { return new File(url.getFile()); } diff --git a/utils/src/com/cloud/utils/crypt/DBEncryptionUtil.java b/utils/src/com/cloud/utils/crypt/DBEncryptionUtil.java index 2f44c5a4fab..12e5bee05f2 100755 --- a/utils/src/com/cloud/utils/crypt/DBEncryptionUtil.java +++ b/utils/src/com/cloud/utils/crypt/DBEncryptionUtil.java @@ -16,18 +16,13 @@ // under the License.package com.cloud.utils.crypt; package com.cloud.utils.crypt; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; import java.util.Properties; import org.apache.log4j.Logger; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.jasypt.exceptions.EncryptionOperationNotPossibleException; -import org.jasypt.properties.EncryptableProperties; -import com.cloud.utils.PropertiesUtil; +import com.cloud.utils.db.DbProperties; import com.cloud.utils.exception.CloudRuntimeException; public class DBEncryptionUtil { @@ -69,27 +64,16 @@ public class DBEncryptionUtil { } return plain; } - + private static void initialize(){ - final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); - final Properties dbProps; - + final Properties dbProps = DbProperties.getDbProperties(); + if(EncryptionSecretKeyChecker.useEncryption()){ - StandardPBEStringEncryptor encryptor = EncryptionSecretKeyChecker.getEncryptor(); - dbProps = new EncryptableProperties(encryptor); - try { - PropertiesUtil.loadFromFile(dbProps, dbPropsFile); - } catch (FileNotFoundException e) { - throw new CloudRuntimeException("db.properties file not found while reading DB secret key", e); - } catch (IOException e) { - throw new CloudRuntimeException("Erroe while reading DB secret key from db.properties", e); - } - String dbSecretKey = dbProps.getProperty("db.cloud.encrypt.secret"); if(dbSecretKey == null || dbSecretKey.isEmpty()){ throw new CloudRuntimeException("Empty DB secret key in db.properties"); } - + s_encryptor = new StandardPBEStringEncryptor(); s_encryptor.setAlgorithm("PBEWithMD5AndDES"); s_encryptor.setPassword(dbSecretKey); diff --git a/utils/src/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java b/utils/src/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java index 56195de23c8..06391a5c275 100755 --- a/utils/src/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java +++ b/utils/src/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java @@ -27,20 +27,17 @@ import java.net.ServerSocket; import java.net.Socket; import java.util.Properties; -import javax.ejb.Local; +import javax.annotation.PostConstruct; +import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig; -import com.cloud.utils.PropertiesUtil; -import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.component.ComponentLifecycle; -import com.cloud.utils.component.SystemIntegrityChecker; +import com.cloud.utils.db.DbProperties; import com.cloud.utils.exception.CloudRuntimeException; -@Local(value = {SystemIntegrityChecker.class}) -public class EncryptionSecretKeyChecker extends AdapterBase implements SystemIntegrityChecker { +public class EncryptionSecretKeyChecker { private static final Logger s_logger = Logger.getLogger(EncryptionSecretKeyChecker.class); @@ -50,98 +47,92 @@ public class EncryptionSecretKeyChecker extends AdapterBase implements SystemInt private static final String s_envKey = "CLOUD_SECRET_KEY"; private static StandardPBEStringEncryptor s_encryptor = new StandardPBEStringEncryptor(); private static boolean s_useEncryption = false; - - public EncryptionSecretKeyChecker() { - setRunLevel(ComponentLifecycle.RUN_LEVEL_FRAMEWORK_BOOTSTRAP); + + @PostConstruct + public void init() { + /* This will call DbProperties, which will call this to initialize the encryption. Yep, + * round about and annoying */ + DbProperties.getDbProperties(); } - @Override - public void check() { - //Get encryption type from db.properties - final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); - final Properties dbProps = new Properties(); - try { - PropertiesUtil.loadFromFile(dbProps, dbPropsFile); + public void check(Properties dbProps) throws IOException { + String encryptionType = dbProps.getProperty("db.cloud.encryption.type"); - final String encryptionType = dbProps.getProperty("db.cloud.encryption.type"); + s_logger.debug("Encryption Type: "+ encryptionType); - s_logger.debug("Encryption Type: "+ encryptionType); - - if(encryptionType == null || encryptionType.equals("none")){ - return; - } - - if (s_useEncryption) { - s_logger.warn("Encryption already enabled, is check() called twice?"); - return; - } - - s_encryptor.setAlgorithm("PBEWithMD5AndDES"); - String secretKey = null; - - SimpleStringPBEConfig stringConfig = new SimpleStringPBEConfig(); - - if(encryptionType.equals("file")){ - File keyFile = new File(s_keyFile); - if (!keyFile.exists()) { - keyFile = new File(s_altKeyFile); - } - try { - BufferedReader in = new BufferedReader(new FileReader(keyFile)); - secretKey = in.readLine(); - //Check for null or empty secret key - } catch (FileNotFoundException e) { - throw new CloudRuntimeException("File containing secret key not found: "+s_keyFile, e); - } catch (IOException e) { - throw new CloudRuntimeException("Error while reading secret key from: "+s_keyFile, e); - } - - if(secretKey == null || secretKey.isEmpty()){ - throw new CloudRuntimeException("Secret key is null or empty in file "+s_keyFile); - } - - } else if(encryptionType.equals("env")){ - secretKey = System.getenv(s_envKey); - if(secretKey == null || secretKey.isEmpty()){ - throw new CloudRuntimeException("Environment variable "+s_envKey+" is not set or empty"); - } - } else if(encryptionType.equals("web")){ - ServerSocket serverSocket = null; - int port = 8097; - try { - serverSocket = new ServerSocket(port); - } catch (IOException ioex) { - throw new CloudRuntimeException("Error initializing secret key reciever", ioex); - } - s_logger.info("Waiting for admin to send secret key on port "+port); - Socket clientSocket = null; - try { - clientSocket = serverSocket.accept(); - } catch (IOException e) { - throw new CloudRuntimeException("Accept failed on "+port); - } - PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); - BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); - String inputLine; - if ((inputLine = in.readLine()) != null) { - secretKey = inputLine; - } - out.close(); - in.close(); - clientSocket.close(); - serverSocket.close(); - } else { - throw new CloudRuntimeException("Invalid encryption type: "+encryptionType); - } - - stringConfig.setPassword(secretKey); - s_encryptor.setConfig(stringConfig); - s_useEncryption = true; - } catch (FileNotFoundException e) { - throw new CloudRuntimeException("File db.properties not found", e); - } catch (IOException e) { - throw new CloudRuntimeException("Error while reading db.properties", e); + if(encryptionType == null || encryptionType.equals("none")){ + return; } + + if (s_useEncryption) { + s_logger.warn("Encryption already enabled, is check() called twice?"); + return; + } + + s_encryptor.setAlgorithm("PBEWithMD5AndDES"); + String secretKey = null; + + SimpleStringPBEConfig stringConfig = new SimpleStringPBEConfig(); + + if(encryptionType.equals("file")){ + File keyFile = new File(s_keyFile); + if (!keyFile.exists()) { + keyFile = new File(s_altKeyFile); + } + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(keyFile)); + secretKey = in.readLine(); + //Check for null or empty secret key + } catch (FileNotFoundException e) { + throw new CloudRuntimeException("File containing secret key not found: "+s_keyFile, e); + } catch (IOException e) { + throw new CloudRuntimeException("Error while reading secret key from: "+s_keyFile, e); + } finally { + IOUtils.closeQuietly(in); + } + + if(secretKey == null || secretKey.isEmpty()){ + throw new CloudRuntimeException("Secret key is null or empty in file "+s_keyFile); + } + + } else if(encryptionType.equals("env")){ + secretKey = System.getenv(s_envKey); + if(secretKey == null || secretKey.isEmpty()){ + throw new CloudRuntimeException("Environment variable "+s_envKey+" is not set or empty"); + } + } else if(encryptionType.equals("web")){ + ServerSocket serverSocket = null; + int port = 8097; + try { + serverSocket = new ServerSocket(port); + } catch (IOException ioex) { + throw new CloudRuntimeException("Error initializing secret key reciever", ioex); + } + s_logger.info("Waiting for admin to send secret key on port "+port); + Socket clientSocket = null; + try { + clientSocket = serverSocket.accept(); + } catch (IOException e) { + throw new CloudRuntimeException("Accept failed on "+port); + } + PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); + BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + String inputLine; + if ((inputLine = in.readLine()) != null) { + secretKey = inputLine; + } + out.close(); + in.close(); + clientSocket.close(); + serverSocket.close(); + } else { + throw new CloudRuntimeException("Invalid encryption type: "+encryptionType); + } + + stringConfig.setPassword(secretKey); + s_encryptor.setConfig(stringConfig); + s_useEncryption = true; } public static StandardPBEStringEncryptor getEncryptor() { @@ -160,15 +151,4 @@ public class EncryptionSecretKeyChecker extends AdapterBase implements SystemInt s_encryptor.setConfig(stringConfig); s_useEncryption = true; } - - @Override - public boolean start() { - try { - check(); - } catch (Exception e) { - s_logger.error("System integrity check exception", e); - System.exit(1); - } - return true; - } } diff --git a/utils/src/com/cloud/utils/db/DbProperties.java b/utils/src/com/cloud/utils/db/DbProperties.java new file mode 100644 index 00000000000..a5ad383118d --- /dev/null +++ b/utils/src/com/cloud/utils/db/DbProperties.java @@ -0,0 +1,105 @@ +/* + * 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.utils.db; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.apache.commons.io.IOUtils; +import org.apache.log4j.Logger; +import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; +import org.jasypt.properties.EncryptableProperties; + +import com.cloud.utils.PropertiesUtil; +import com.cloud.utils.crypt.EncryptionSecretKeyChecker; + +public class DbProperties { + + private static final Logger log = Logger.getLogger(DbProperties.class); + + private static Properties properties = new Properties(); + private static boolean loaded = false; + + protected static Properties wrapEncryption(Properties dbProps) throws IOException { + EncryptionSecretKeyChecker checker = new EncryptionSecretKeyChecker(); + checker.check(dbProps); + + if ( EncryptionSecretKeyChecker.useEncryption() ) { + return dbProps; + } else { + EncryptableProperties encrProps = new EncryptableProperties(EncryptionSecretKeyChecker.getEncryptor()); + encrProps.putAll(dbProps); + return encrProps; + } + } + + public synchronized static Properties getDbProperties() { + if ( ! loaded ) { + Properties dbProps = new Properties(); + InputStream is = null; + try { + File props = PropertiesUtil.findConfigFile("db.properties"); + if ( props != null && props.exists() ) { + is = new FileInputStream(props); + } + + if ( is == null ) { + is = PropertiesUtil.openStreamFromURL("db.properties"); + } + if ( is == null ) { + System.err.println("Failed to find db.properties"); + log.error("Failed to find db.properties"); + } + + dbProps.load(is); + + EncryptionSecretKeyChecker checker = new EncryptionSecretKeyChecker(); + checker.check(dbProps); + + if (EncryptionSecretKeyChecker.useEncryption()) { + StandardPBEStringEncryptor encryptor = EncryptionSecretKeyChecker.getEncryptor(); + EncryptableProperties encrDbProps = new EncryptableProperties(encryptor); + encrDbProps.putAll(dbProps); + dbProps = encrDbProps; + } + } catch ( IOException e ) { + throw new IllegalStateException("Failed to load db.properties", e); + } finally { + IOUtils.closeQuietly(is); + } + + properties = dbProps; + loaded = true; + } + + return properties; + } + + public synchronized static Properties setDbProperties(Properties props) throws IOException { + if ( loaded ) { + throw new IllegalStateException("DbProperties has already been loaded"); + } + properties = wrapEncryption(props); + loaded = true; + return properties; + } +} diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java index a9536cfb544..784c0316e04 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java @@ -1985,7 +1985,21 @@ public class VirtualMachineMO extends BaseMO { } throw new Exception("Unable to find device controller"); } - + + public List getVirtualDisks() throws Exception { + List virtualDisks = new ArrayList(); + + List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + + for (VirtualDevice device : devices) { + if (device instanceof VirtualDisk) { + virtualDisks.add((VirtualDisk)device); + } + } + + return virtualDisks; + } + public List detachAllDisksExcept(String vmdkBaseName, String deviceBusName) throws Exception { List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device");