/// <summary>
        /// Create a new VM network with specified parameters using VTN on demand.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        /// <param name="vMSubnetName">Name of VM Subnet to create.</param>
        /// <param name="vMNetworkName">Name of VM network to create.</param>
        /// <param name="maxNumberOfPorts">Maximum number of ports.</param>
        /// <param name="ipSubnets">IP pools to use.</param>
        /// <param name="logicalNetworkDefinitionId">ID of logical network definition
        /// to associate with.</param>
        /// <param name="connection">VSEM connection.</param>
        /// <param name="vtnName">VTN name.</param>
        /// <returns>VM network if successful, else null.</returns>
        public VMNetwork CreateVMNetwork(TransactionManager txnMng,
            string vMSubnetName,
            string vMNetworkName,
            long? maxNumberOfPorts,
            IPSubnet[] ipSubnets,
            Guid logicalNetworkDefinitionId,
            VSEMConnection connection,
            out string vtnName)
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder("\"txnMng\":" + JavaScriptSerializer.Serialize(txnMng));
            json.Append(" \"ipSubnets\":" + JavaScriptSerializer.Serialize(ipSubnets));
            json.Append("\"maxNumberOfPorts\":\"" + maxNumberOfPorts + "\"");
            json.Append("\"vMNetworkName\":\"" + vMNetworkName + "\"");
            json.Append("\"vMSubnetName\":\"" + vMSubnetName + "\"");
            json.Append("\"logicalNetworkDefinitionId\":\"" + logicalNetworkDefinitionId + "\"");
            ODLVSEMETW.EventWriteStartLibrary(MethodBase.GetCurrentMethod().Name,
                json.ToString());
            if (txnMng == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'transaction' is null or invalid.");
                throw new ArgumentException("The parameter 'transaction' is null or invalid.");
            }

            if (string.IsNullOrEmpty(vMNetworkName)) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'vMNetworkName' is null or invalid.");
                throw new ArgumentException("The parameter 'vMNetworkName' is null or invalid.");
            }
            if (logicalNetworkDefinitionId == Guid.Empty) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'logicalNetworkDefinitionId' is null or invalid.");
                throw new ArgumentException(
                    "The parameter 'logicalNetworkDefinitionId' is null or invalid.");
            }
            if (connection == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'connection' is null or invalid.");
                throw new ArgumentException("The parameter 'connection' is null or invalid.");
            }

            string VtnHostName = this.ConnectionString;

            if (VtnHostName.StartsWith(@"https://", StringComparison.Ordinal)) {
                VtnHostName = VtnHostName.Substring(8);
            }

            VtnHostName = VtnHostName.Split('.', ':').First();

            var vMNetworkConfig = new VMNetworkConfig(VtnHostName);
            txnMng.SetConfigManager(vMNetworkConfig, TransactionManager.OpenMode.WriteMode);

            var LogicalNetworkConfig = new LogicalNetworkConfig(VtnHostName);
            txnMng.SetConfigManager(LogicalNetworkConfig, TransactionManager.OpenMode.ReadMode);
            if (LogicalNetworkConfig.LogicalNetworks.Count == 0) {
                ODLVSEMETW.EventWriteConfigManagerFileIOError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "LogicalNetwork.config {0}",
                    configFileIOErrorValidationMessage));
                throw new InvalidOperationException(
                    string.Format(CultureInfo.CurrentCulture,
                    "LogicalNetwork.config {0}",
                    configFileIOErrorValidationMessage));
            }

            var logicalNetName = VSEMODLConstants.LOGICAL_NETWORK_NAME;
            logicalNetName += VtnHostName;
            var fabricNwDef = LogicalNetworkConfig.LogicalNetworks.First(
                log => log.Name.Equals(logicalNetName)).LogicalNetworkDefinitions.FirstOrDefault(
                fabnw => fabnw.Id == logicalNetworkDefinitionId);
            if (fabricNwDef == null) {
                ODLVSEMETW.EventWriteGetFabricNetworkDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "Logical network definition '{0}' not found.",
                    logicalNetworkDefinitionId.ToString("B")));
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                     "Logical network definition '{0}' not found.",
                logicalNetworkDefinitionId.ToString("B")));
            }

            ODLVSEMETW.EventWriteReturnLibrary(string.Format(CultureInfo.CurrentCulture,
                "VSEMLogicalNetworkDefinition is retrieved by ID: {0}",
                logicalNetworkDefinitionId.ToString("B")),
                string.Empty);

            if (!fabricNwDef.SupportsVMNetworkProvisioning) {
                ODLVSEMETW.EventWriteSupportsVMNetworkProvisioningError(
                    "Logical network does not support VM network creation.",
                    string.Empty);
                throw new InvalidOperationException(
                    "Logical network does not support VM network creation.");
            }

            vtnName = this.CreateUniqueNameForVTN(vMNetworkName);

            Vtn vtn = new Vtn(this.ConnectionString, this.Credential);
            vtn.AddVtn(vtnName);

            ODLVSEMETW.EventWriteReturnODLLibrary(string.Format(CultureInfo.CurrentCulture,
                "VTN '{0}' is created",
                vtnName),
                string.Empty);

            VMNetwork vmNet = CreateVtnVmNetwork(vMNetworkName);
            vmNet.LogicalNetwork = fabricNwDef.LogicalNetworkId;
            if (vmNet == null) {
                ODLVSEMETW.EventWriteProcessFailedVMNetworkError(
                    MethodBase.GetCurrentMethod().Name,
                    "Failed to create VM Network.");
                throw new InvalidOperationException("Failed to create VM Network.");
            }
            ODLVSEMETW.EventWriteSuccessVmNetwork(MethodBase.GetCurrentMethod().Name,
                    "VM Network Successfully Created.");

            // Create the VM Subnet
            vMNetworkConfig.VMNetwork.VmNetworks.Add(vmNet);
            if (vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo == null) {
                vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo =
                    new List<VMNetworkInfo>();
            }

            vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo.Add(
                new VMNetworkInfo {
                    VMNetworkID = vmNet.Id,
                    VMNetworkName = vmNet.Name,
                    VTNName = vtnName,
                    VMSubnetInfo = new List<VMSubnetInfo>(),
                    CreatedFrom = "SCVMM",
                    VMNetworkOriginalName = vmNet.Name
                });

            var vsemvmnetworkDefinition = new VSEMVMSubnetManagement(
                this.ConnectionString, this.Credential);
            ODLVSEMETW.EventWriteCreateVMsubNetwork(MethodBase.GetCurrentMethod().Name,
                    "VM Sub Network creation process started.");
            string vbrName = string.Empty;
            VMSubnet vmNetworkDef =
                vsemvmnetworkDefinition.CreateVMNetworkDefinitionforVtn(
                txnMng,
                LogicalNetworkConfig,
                vMNetworkConfig,
                vMSubnetName,
                vmNet.Id,
                maxNumberOfPorts,
                ipSubnets,
                logicalNetworkDefinitionId,
                connection,
                out vtnName,
                out vbrName);

            Controller odl = new Controller(this.ConnectionString, this.Credential);
            odl.UpdateStartupConfiguration();
            string output = "\"vmNet\":" + JavaScriptSerializer.Serialize(vmNet);
            ODLVSEMETW.EventWriteReturnODLLibrary("Return from ODL Library.", output);

            ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name,
                output);
            return vmNet;
        }
        /// <summary>
        /// This function is responsible to remove the information about the
        /// vm network(s) for the connection.
        /// </summary>
        protected override void DoODLVSEMCmdlet()
        {
            TransactionManager txnMng = new TransactionManager();
            txnMng.StartTransaction();
            var ope = TransactionManager.Operation.None;
            bool needRefresh = false;
            VSEMVMSubnetManagement vSEMVmNetworkDefinitionManagement = null;
            try {
                var JavaScriptSerializer = new JavaScriptSerializer();
                JavaScriptSerializer.MaxJsonLength = int.MaxValue;
                StringBuilder json = new StringBuilder("\"VMSubnetId\":\"" + this.VMSubnetId + "\"");
                ODLVSEMETW.EventWriteDoCmdlet(this.CmdletName,
                    "Removing VMSubnet.",
                    json.ToString());
                string connectionString =
                this.conn.ConnectionString.Split(',').FirstOrDefault();
                vSEMVmNetworkDefinitionManagement =
                    new VSEMVMSubnetManagement(connectionString,
                this.conn.Credential);
                needRefresh = vSEMVmNetworkDefinitionManagement.RemoveVmNetworkDefinition(
                    txnMng,
                    this.VMSubnetId,
                    this.conn,
                    out this.name);
                ODLVSEMETW.EventWriteReturnLibrary(string.Format(CultureInfo.CurrentCulture,
                "VM Subnet with ID: {0} is removed",
                this.VMSubnetId.ToString("B")),
                string.Empty);

                ope = TransactionManager.Operation.Commit;
            } catch (Exception ex) {
                ope = TransactionManager.Operation.Rollback;
                if (!string.IsNullOrEmpty(this.name)
                    && string.Compare(ex.GetType().ToString(), "System.Net.WebException", StringComparison.Ordinal) == 0) {
                    ODLVSEMETW.EventWriteFailedCmdlet(string.Format(CultureInfo.CurrentCulture,
                        "Due to some problem in connection with ODL, VSEM VM Subnet '{0}' removal process is terminated in the middle of the request. vBridge may have been deleted from ODL, Please check. Please retry and delete VM Subnet if inconsistency is created.",
                    this.name),
                    string.Empty);
                    Exception exception = VSEMODLExceptionUtil.ConvertExceptionToVSEMException(
                        new System.Net.WebException(string.Format(CultureInfo.CurrentCulture,
                            "Due to some problem in connection with ODL, VSEM VM Subnet '{0}' removal process is terminated in the middle of the request. vBridge may have been deleted from ODL, Please check. Please retry and delete VM Subnet if inconsistency is created.",
                            this.name),
                            ex));
                    ODLVSEMETW.EventWriteFailedCmdlet(this.CmdletName, exception.GetType() + " : " + ex.Message);
                    ope = TransactionManager.Operation.Rollback;
                    throw exception;
                } else {
                    ODLVSEMETW.EventWriteFailedCmdlet(
                        "VSEM VM Subnet removal is failed.",
                        string.Empty);
                    Exception exception = VSEMODLExceptionUtil.ConvertExceptionToVSEMException(ex);
                    ODLVSEMETW.EventWriteFailedCmdlet(this.CmdletName, exception.GetType() + " : " + exception.Message);
                    ope = TransactionManager.Operation.Rollback;
                    throw exception;
                }
            } finally {
                txnMng.EndTransaction(ope);
                ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, string.Empty);
            }
        }
예제 #3
0
        /// <summary>
        /// This function is responsible for creating a VM Subnet.
        /// </summary>
        protected override void DoODLVSEMCmdlet()
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder(" \"IPSubnets\":" + JavaScriptSerializer.Serialize(this.IPSubnets));
            json.Append("\"MaxNumberOfPorts\":\"" + this.MaxNumberOfPorts + "\"");
            json.Append("\"Name\":\"" + this.Name + "\"");
            json.Append("\"VMNetworkId\":\"" + this.VMNetworkId + "\"");
            json.Append("\"LogicalNetworkDefinitionId\":\"" + this.LogicalNetworkDefinitionId + "\"");
            ODLVSEMETW.EventWriteDoCmdlet(this.CmdletName,
                    "Creating VM Subnet.",
                    json.ToString());
            TransactionManager txnMng = new TransactionManager();
            txnMng.StartTransaction();
            var ope = TransactionManager.Operation.None;
            string vtnName = string.Empty;
            string vbrName = string.Empty;
            VMSubnet nw = null;
            string connectionString =
                this.conn.ConnectionString.Split(',').FirstOrDefault();
            VSEMVMSubnetManagement vSEMVMSubnetManagement =
                new VSEMVMSubnetManagement(connectionString,
                    this.conn.Credential);
            try {
                nw = vSEMVMSubnetManagement.CreateVMNetworkDefinition(txnMng,
                    this.Name,
                    this.VMNetworkId,
                    this.MaxNumberOfPorts,
                    this.IPSubnets,
                    this.LogicalNetworkDefinitionId,
                    this.conn,
                    out vtnName,
                    out vbrName);
                ODLVSEMETW.EventWriteReturnLibrary("VM Subnet is created.",
                    string.Empty);

                ope = TransactionManager.Operation.Commit;
            }
            catch (Exception ex) {
                    Exception userException = ex;
                    ODLVSEMETW.EventWriteFailedCmdlet(
                        "VM Subnet creation is failed. ODL changes rollback is started.",
                        string.Empty);
                    ope = TransactionManager.Operation.Rollback;
                    try {
                        if (!string.IsNullOrEmpty(vtnName) && !string.IsNullOrEmpty(vbrName)) {
                            vSEMVMSubnetManagement.RemoveVmNetworkDefinition(
                                vtnName, vbrName);
                            ODLVSEMETW.EventWriteFailedCmdlet(
                                "VM Subnet creation is failed. ODL changes are successfully rolled back.",
                                string.Empty);
                        }
                    } catch (Exception excep) {
                        // VM Network Creation Process is terminated in the middle of the request. VTN
                        ODLVSEMETW.EventWriteFailedCmdlet(
                            string.Format(
                            CultureInfo.CurrentCulture,
                            "Due to some problem in connection with ODL, VSEM VM Subnet creation process terminated in the middle of the request. vBridge '{0}' may have been created on ODL, Please check. If inconsistency is created, Please delete the vBridge from ODL to maintain the consistency between ODL and SCVMM.\n{1}",
                            vbrName,
                            excep.Message),
                            string.Empty);
                        userException = new System.Net.WebException(string.Format(
                            CultureInfo.CurrentCulture,
                            "Due to some problem in connection with ODL, VSEM VM Subnet creation process terminated in the middle of the request. vBridge '{0}' may have been created on ODL, Please check. If inconsistency is created, Please delete the vBridge from ODL to maintain the consistency between ODL and SCVMM.",
                            vbrName),
                            ex);
                    }
                    Exception exception = VSEMODLExceptionUtil.ConvertExceptionToVSEMException(userException);
                    ODLVSEMETW.EventWriteFailedCmdlet(this.CmdletName, exception.GetType() + " : " + ex.Message);
                    throw exception;
            } finally {
                txnMng.EndTransaction(ope);

                string output = "\"VMSubnet\":" + JavaScriptSerializer.Serialize(nw);
                ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, output);
                this.WriteObject(nw);
            }
        }