Ejemplo n.º 1
0
        /// <summary>
        /// Reads exported metadata json file and deploys all the source resources into destination subscription.
        /// </summary>
        /// <param name="parameters"> Collection of key value paired input parameters <example>
        /// Operation "Import" SourceSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" DestinationSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07"
        /// DestinationDCName "West US" SourcePublishSettingsFilePath "D:\\PublishSettings.PublishSettings" SourceCertificateThumbprint "2180d782768926ee0e5ddbcc6e8d2efa8ddb98c7"
        /// DestinationPublishSettingsFilePath "D:\\PublishSettings.PublishSettings" DestinationCertificateThumbprint "2180d782768926ee0e5ddbcc6e8d2efa8ddb98c7"
        /// ImportMetadataFilePath "D:\\DataCenterMigration\mydata.json" MapperXmlFilePath "D:\\DataCenterMigration\mydata.xml" DestinationPrefixName "dc"
        /// RetryCount "5" MinBackoff "3" MaxBackoff "3" DeltaBackoff "90" QuietMode "True" RollBackOnFailure "True" ResumeImport "True" </example></param>
        public void ImportSubscriptionMetadata(IDictionary <string, string> parameters)
        {
            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            Logger.Info(methodName, ProgressResources.ExecutionStarted);
            bool boolValue;

            if (!parameters.Keys.Contains(Constants.Parameters.QuietMode))
            {
                quietMode = false;
            }
            else
            {
                quietMode = bool.TryParse(parameters[Constants.Parameters.QuietMode], out boolValue) ? boolValue : false;
            }

            Logger.Info(methodName, string.Format(ProgressResources.ImportMetadataStarted, parameters[Constants.Parameters.ImportMetadataFilePath]));
            ReportProgress(string.Format(ProgressResources.ImportMetadataStarted, parameters[Constants.Parameters.ImportMetadataFilePath]));

            // Validate the input paramters and export them into parameters class.
            ImportParameters importParameters = ConfigurationReader.ValidateAndConvertImportParameters(parameters, true);

            // Import metadata.
            ResourceImporter importer = new ResourceImporter(importParameters, this);

            importer.ImportSubscriptionMetadata();

            ReportProgress(ProgressResources.ImportMetadataCompleted);

            Logger.Info(methodName, ProgressResources.ImportMetadataCompleted);
            Logger.Info(methodName, ProgressResources.ExecutionCompleted);
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Constructor class
 /// </summary>
 /// <param name="parameters">Input parameters for import functionality.</param>
 /// <param name="dcMigration">DCMigration class object to report progress.</param>
 public ResourceImporter(ImportParameters parameters, DCMigrationManager dcMigration)
 {
     // Set export parameters.
     importParameters = parameters;
     this.dcMigration = dcMigration;
     helper = new ResourceNameMapperHelper();
 }
Ejemplo n.º 3
0
 public RollBack(ImportParameters importParameters, Subscription subscription, DCMigrationManager dcMigrationManager,
     ResourceImporter resourceImporter)
 {
     this.subscription = subscription;
     this.importParameters = importParameters;
     this.dcMigrationManager = dcMigrationManager;
     this.resourceImporter = resourceImporter;
 }
Ejemplo n.º 4
0
 public RollBack(ImportParameters importParameters, Subscription subscription, DCMigrationManager dcMigrationManager,
                 ResourceImporter resourceImporter)
 {
     this.subscription       = subscription;
     this.importParameters   = importParameters;
     this.dcMigrationManager = dcMigrationManager;
     this.resourceImporter   = resourceImporter;
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Combination of Export and Import functionality.
        /// Exports information about source subscription and stores the metadata into 'SourceDataCenterName-MM-DD-YYYY-hh-mm.json format
        /// on specified ExportMetadataFolderPath.
        /// Reads exported metadata json file and deploys all the source resources into destination subscription.
        /// </summary>
        /// <param name="parameters"> Collection of key value paired input parameters <example> Operation "Migrate"
        /// SourceSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" DestinationSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" SourceDCName "East Asia"
        /// DestinationDCName "West US" SourcePublishSettingsFilePath "D:\\PublishSettings.PublishSettings" SourceCertificateThumbprint "2180d782768926ee0e5ddbcc6e8d2efa8ddb98c7"
        /// DestinationPublishSettingsFilePath "D:\\PublishSettings.PublishSettings" DestinationCertificateThumbprint "2180d782768926ee0e5ddbcc6e8d2efa8ddb98c7"
        /// ExportMetadataFolderPath "D:\\DataCenterMigration" DestinationPrefixName "dc" RetryCount "5" MinBackoff "3" MaxBackoff "3" DeltaBackoff "90"
        /// QuietMode "True" RollBackOnFailure "True" </example></param>
        public void MigrateSubscription(IDictionary <string, string> parameters)
        {
            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            Logger.Info(methodName, ProgressResources.ExecutionStarted);
            bool boolValue;

            if (!parameters.Keys.Contains(Constants.Parameters.QuietMode))
            {
                quietMode = false;
            }
            else
            {
                quietMode = bool.TryParse(parameters[Constants.Parameters.QuietMode], out boolValue) ? boolValue : false;
            }

            ReportProgress(ProgressResources.ExportMetadataStarted);
            Logger.Info(methodName, ProgressResources.ExportMetadataStarted);

            // Validate the input paramters and export them into parameters class.
            ExportParameters exportParameters = ConfigurationReader.ValidateAndConvertExportParameters(parameters);

            // Validate the input paramters and export them into parameters class.
            ImportParameters importParameters = ConfigurationReader.ValidateAndConvertImportParameters(parameters, false);

            // Export metadata.
            ResourceExporter exporter     = new ResourceExporter(exportParameters, this);
            Subscription     subscription = exporter.ExportSubscriptionMetadata();

            File.WriteAllText(exportParameters.ExportMetadataFolderPath,
                              JsonConvert.SerializeObject(subscription, Formatting.Indented));
            ReportProgress(string.Format(ProgressResources.ExportMetadataCompleted, exportParameters.ExportMetadataFolderPath));
            Logger.Info(methodName, string.Format(ProgressResources.ExportMetadataCompleted, exportParameters.ExportMetadataFolderPath));
            Logger.Info(methodName, ProgressResources.ExecutionCompleted);

            importParameters.ImportMetadataFilePath = exportParameters.ExportMetadataFolderPath;
            // Import metadata.
            Logger.Info(methodName, string.Format(ProgressResources.ImportMetadataStarted, importParameters.ImportMetadataFilePath));
            ReportProgress(string.Format(ProgressResources.ImportMetadataStarted, importParameters.ImportMetadataFilePath));

            ResourceImporter importer = new ResourceImporter(importParameters, this);

            importer.ImportSubscriptionMetadata();

            ReportProgress(ProgressResources.ImportMetadataCompleted);
            Logger.Info(methodName, ProgressResources.ImportMetadataCompleted);

            Logger.Info(methodName, ProgressResources.ExecutionCompleted);
        }
Ejemplo n.º 6
0
            /// <summary>
            /// Validates and converts input paramters into <see cref="ImportParameters"/> class.
            /// </summary>
            /// <param name="parameters">Collection of input parameters stored in key value pairs
            /// <example> Operation "Import" SourceSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07"
            /// DestinationSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" DestinationDCName "West US"
            /// SourcePublishSettingsFilePath "D:\\PublishSettings.PublishSettings"
            /// DestinationPublishSettingsFilePath "D:\\PublishSettings.PublishSettings"
            /// ImportMetadataFilePath "D:\\DataCenterMigration\mydata.json" DestinationPrefixName "dc" QuietMode "True"
            /// RollBackOnFailure "True" ResumeImport "True" </example> </param>
            /// <param name="validateForImport">True if the function will be called for imort functionality.
            /// False if it is called for Migrate functionality</param>
            /// <returns>Parameters required for import functionality</returns>
            internal static ImportParameters ValidateAndConvertImportParameters(IDictionary<string, string> parameters,
            bool validateForImport)
            {
            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
            Logger.Info(methodName, ProgressResources.ExecutionStarted);
            Logger.Info(methodName, ProgressResources.ParameterValidationStarted);

            #region Check for missing required parameters
            // SourcePublishSettingsFilePath/ CertificateThumbprint
            if (!parameters.Keys.Contains(Constants.Parameters.SourcePublishSettingsFilePath) && !parameters.Keys.Contains(Constants.Parameters.SourceCertificateThumbprint))
            {
                throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Source, Constants.AppConfigArguments));
            }

            // DestinationPublishSettingsFilePath
            if (!parameters.Keys.Contains(Constants.Parameters.DestinationPublishSettingsFilePath) && !parameters.Keys.Contains(Constants.Parameters.DestinationCertificateThumbprint))
            {
                throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Destination, Constants.AppConfigArguments));
            }

            // SourceSubscriptionID
            if (!parameters.Keys.Contains(Constants.Parameters.SourceSubscriptionID))
            {
                throw new ValidationException(string.Format(StringResources.MissingRequiredParameter,
                    Constants.Parameters.SourceSubscriptionID, Constants.AppConfigArguments));
            }

            // DestinationSubscriptionID
            if (!parameters.Keys.Contains(Constants.Parameters.DestinationSubscriptionID))
            {
                throw new ValidationException(string.Format(StringResources.MissingRequiredParameter,
                    Constants.Parameters.DestinationSubscriptionID, Constants.AppConfigArguments));
            }

            // DestinationDCName
            if (!parameters.Keys.Contains(Constants.Parameters.DestinationDCName))
            {
                throw new ValidationException(string.Format(StringResources.MissingRequiredParameter,
                    Constants.Parameters.DestinationDCName, Constants.AppConfigArguments));
            }

            //DestinationPrefixName & MapperXmlFilePath.
            if (!validateForImport)
            {
                if (!parameters.Keys.Contains(Constants.Parameters.DestinationPrefixName))
                {
                    throw new ValidationException(string.Format(StringResources.MissingRequiredParameter,
                        Constants.Parameters.DestinationPrefixName, Constants.AppConfigArguments));
                }
            }
            else
            {
                if (!parameters.Keys.Contains(Constants.Parameters.DestinationPrefixName) &&
                    !parameters.Keys.Contains(Constants.Parameters.MapperXmlFilePath))
                {
                    throw new ValidationException(string.Format(StringResources.MissingMapperAndPrefix,
                       StringResources.Destination, Constants.AppConfigArguments));
                }
            }

            #endregion

            #region Check for null or empty values
            //SourcePublishSettingsFilePath
            if ((parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath) && string.IsNullOrEmpty(parameters[Constants.Parameters.SourcePublishSettingsFilePath]))
                  || (parameters.ContainsKey(Constants.Parameters.SourceCertificateThumbprint) && string.IsNullOrEmpty(parameters[Constants.Parameters.SourceCertificateThumbprint])))
            {
                throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Source, Constants.AppConfigArguments));
            }

            // DestinationPublishSettingsFilePath
            if ((parameters.ContainsKey(Constants.Parameters.DestinationPublishSettingsFilePath) && string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationPublishSettingsFilePath]))
                  || (parameters.ContainsKey(Constants.Parameters.DestinationCertificateThumbprint) && string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationCertificateThumbprint])))
            {
                throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Destination, Constants.AppConfigArguments));
            }

            // ImportMetadataFilePath
            if (validateForImport && (string.IsNullOrEmpty(parameters[Constants.Parameters.ImportMetadataFilePath])))
            {
                throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter,
                    Constants.Parameters.ImportMetadataFilePath));
            }
            // DestinationSubscriptionID
            if (string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationSubscriptionID]))
            {
                throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter,
                    Constants.Parameters.DestinationSubscriptionID));
            }

            // DestinationDCName
            if (string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationDCName]))
            {
                throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter, Constants.Parameters.DestinationDCName));
            }

            //DestinationPrefixName & MapperXmlFilePath.
            if (!validateForImport)
            {
                if (string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationPrefixName]))
                {
                    throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter, Constants.Parameters.DestinationPrefixName));
                }
            }
            else
            {
                if ((parameters.ContainsKey(Constants.Parameters.DestinationPrefixName) &&
                    string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationPrefixName])) ||
                    (parameters.ContainsKey(Constants.Parameters.MapperXmlFilePath)
                    && string.IsNullOrEmpty(parameters[Constants.Parameters.MapperXmlFilePath])))
                {
                    throw new ValidationException(string.Format(StringResources.MissingMapperAndPrefix,
                       StringResources.Destination, Constants.AppConfigArguments));
                }
            }

            #endregion

            #region Validate parameter's value.

            // Validate SourcePublishSettingsFilePath
            if ((parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath) && !File.Exists(parameters[Constants.Parameters.SourcePublishSettingsFilePath])))
            {
                throw new ValidationException(string.Format(StringResources.InvalidParameterValue,
                    Constants.Parameters.SourcePublishSettingsFilePath),
                    new FileNotFoundException(StringResources.PublishSettingsFilePathParamException));
            }

            // Validate DestinationPublishSettingsFilePath
            if ((parameters.ContainsKey(Constants.Parameters.DestinationPublishSettingsFilePath) && !File.Exists(parameters[Constants.Parameters.DestinationPublishSettingsFilePath])))
            {
                throw new ValidationException(string.Format(StringResources.InvalidParameterValue,
                    Constants.Parameters.DestinationPublishSettingsFilePath),
                    new FileNotFoundException(StringResources.PublishSettingsFilePathParamException));
            }

            string importMapperXmlFilePath = string.Empty;
            string destinationPrefix = string.Empty;
            // Validate MapperXmlFilePath if provided
            if (validateForImport && parameters.ContainsKey(Constants.Parameters.MapperXmlFilePath))
            {
                importMapperXmlFilePath = parameters[Constants.Parameters.MapperXmlFilePath];

                if (!File.Exists(importMapperXmlFilePath))
                {
                    throw new ValidationException(string.Format(StringResources.InvalidParameterValue,
                        Constants.Parameters.MapperXmlFilePath),
                        new FileNotFoundException(StringResources.MapperFilePathParamException));
                }
                if (!Path.GetExtension(importMapperXmlFilePath).Equals(Constants.MapperFileExtension, StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new ValidationException(string.Format(StringResources.InvalidExtensionMapperFile,
                        Constants.Parameters.MapperXmlFilePath),
                        new FileNotFoundException(StringResources.MapperFilePathParamException));
                }
            }
            destinationPrefix = parameters.Keys.Contains(Constants.Parameters.DestinationPrefixName) ?
                                    parameters[Constants.Parameters.DestinationPrefixName].ToLower() :
                                    Constants.DestinationPrefixValue;

            // Validate ImportMetadataFilePath
            if (validateForImport)
            {
                if (!string.IsNullOrEmpty(parameters[Constants.Parameters.ImportMetadataFilePath]))
                {
                    string filePath = parameters[Constants.Parameters.ImportMetadataFilePath];

                    if (!File.Exists(filePath))
                    {
                        throw new ValidationException(string.Format(StringResources.InvalidParameterValue,
                            Constants.Parameters.ImportMetadataFilePath),
                            new FileNotFoundException(StringResources.ImportMetadataFilePathParamException));
                    }
                    if (!Path.GetExtension(filePath).Equals(Constants.MetadataFileExtension, StringComparison.InvariantCultureIgnoreCase))
                    {
                        throw new ValidationException(string.Format(StringResources.InvalidExtensionMetadataFile,
                            Constants.Parameters.ImportMetadataFilePath),
                            new FileNotFoundException(StringResources.ImportMetadataFilePathParamException));
                    }
                }
            }

            bool rollBackBoolValue;
            bool resumeImportBoolValue;
            int retryCount;
            Double minBackOff;
            Double maxBackOff;
            Double deltaBackOff;

            if (!parameters.Keys.Contains(Constants.Parameters.RollBackOnFailure))
            {
                rollBackBoolValue = false;
            }
            else
            {
                bool.TryParse(parameters[Constants.Parameters.RollBackOnFailure], out rollBackBoolValue);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.ResumeImport))
            {
                resumeImportBoolValue = false;
            }
            else
            {
                bool.TryParse(parameters[Constants.Parameters.ResumeImport], out resumeImportBoolValue);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.RetryCount))
            {
                retryCount = Int32.Parse(Constants.RetryCountDefault);
            }
            else
            {
                Int32.TryParse(parameters[Constants.Parameters.RetryCount], out retryCount);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.MinBackoff))
            {
                minBackOff = Double.Parse(Constants.MinBackoffDefault);
            }
            else
            {
                Double.TryParse(parameters[Constants.Parameters.MinBackoff], out minBackOff);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.MaxBackoff))
            {
                maxBackOff = Double.Parse(Constants.MaxBackoffDefault);
            }
            else
            {
                Double.TryParse(parameters[Constants.Parameters.MaxBackoff], out maxBackOff);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.DeltaBackoff))
            {
                deltaBackOff = Double.Parse(Constants.DeltaBackoffDefault);
            }
            else
            {
                Double.TryParse(parameters[Constants.Parameters.DeltaBackoff], out deltaBackOff);
            }
            // Validate SourcePublishSettings File
            PublishSettings sourcePublishSettingsFile = null;
            PublishSetting sourceSubscription = null;

            if (parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath))
            {
                try
                {
                    var fileContents = File.ReadAllText(parameters[Constants.Parameters.SourcePublishSettingsFilePath]);
                    sourcePublishSettingsFile = new PublishSettings(fileContents);
                }
                catch (Exception xmlEx)
                {
                    throw new ValidationException(string.Format(StringResources.XMLParsingException + " =>" + xmlEx.Message,
                        parameters[Constants.Parameters.SourcePublishSettingsFilePath]));
                }

                // Check whether sourceSubscriptionId exists in publish settings file
                sourceSubscription = sourcePublishSettingsFile.Subscriptions.FirstOrDefault(a =>
                    string.Compare(a.Id, parameters[Constants.Parameters.SourceSubscriptionID], StringComparison.InvariantCultureIgnoreCase) == 0);
                if (sourceSubscription == null)
                {
                    throw new ValidationException(string.Format(StringResources.SubscriptionIdParamException, parameters[Constants.Parameters.SourceSubscriptionID], parameters[Constants.Parameters.SourcePublishSettingsFilePath]));
                }
            }
            else
            {
                string thumbprint = parameters[Constants.Parameters.SourceCertificateThumbprint];
                X509Certificate2 certificate = GetStoreCertificate(thumbprint);
                if (!certificate.HasPrivateKey)
                {
                    throw new ValidationException(string.Format(
                        StringResources.MissingPrivateKeyInCertificate, StringResources.Source, thumbprint));
                }
                var sourceCredentials = new CertificateCloudCredentials(parameters[Constants.Parameters.SourceSubscriptionID],
                      certificate);
                string sourceSubscriptionName = null;
                using (var client = new ManagementClient(sourceCredentials))
                {
                    BaseParameters baseParams = new BaseParameters()
                    {
                        RetryCount = retryCount,
                        MinBackOff = TimeSpan.FromSeconds(minBackOff),
                        MaxBackOff = TimeSpan.FromSeconds(maxBackOff),
                        DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff)
                    };
                    SubscriptionGetResponse subscriptionResponse = Retry.RetryOperation(() => client.Subscriptions.Get(), baseParams, ResourceType.None);
                    sourceSubscriptionName = subscriptionResponse.SubscriptionName;
                }
                sourceSubscription = new PublishSetting()
                {
                    Id = parameters[Constants.Parameters.SourceSubscriptionID],
                    Name = sourceSubscriptionName,
                    ServiceUrl = new Uri(Constants.ServiceManagementUrlValue),
                    Credentials = sourceCredentials
                };
            }

            // Validate DestinationPublishSettings File
            PublishSettings destPublishSettingsFile = null;
            PublishSetting destSubscription = null;

            if (parameters.ContainsKey(Constants.Parameters.DestinationPublishSettingsFilePath))
            {
                try
                {
                    var fileContents = File.ReadAllText(parameters[Constants.Parameters.DestinationPublishSettingsFilePath]);
                    destPublishSettingsFile = new PublishSettings(fileContents);
                }
                catch (Exception xmlEx)
                {
                    throw new ValidationException(string.Format(StringResources.XMLParsingException + " =>" + xmlEx.Message,
                        parameters[Constants.Parameters.DestinationPublishSettingsFilePath]));
                }
                // Check whether destSubscriptionId exists in publish settings file
                destSubscription = destPublishSettingsFile.Subscriptions.FirstOrDefault(a =>
                    string.Compare(a.Id, parameters[Constants.Parameters.DestinationSubscriptionID], StringComparison.InvariantCultureIgnoreCase) == 0);
                if (destSubscription == null)
                {
                    throw new ValidationException(string.Format(StringResources.SubscriptionIdParamException, parameters[Constants.Parameters.DestinationSubscriptionID], parameters[Constants.Parameters.DestinationPublishSettingsFilePath]));
                }
            }
            else
            {
                string thumbprint = parameters[Constants.Parameters.DestinationCertificateThumbprint];
                X509Certificate2 certificate = GetStoreCertificate(thumbprint);
                if (!certificate.HasPrivateKey)
                {
                    throw new ValidationException(string.Format(
                        StringResources.MissingPrivateKeyInCertificate, StringResources.Destination, thumbprint));
                }
                var destCredentials = new CertificateCloudCredentials(parameters[Constants.Parameters.DestinationSubscriptionID],
                       certificate);
                string destSubscriptionName = null;
                using (var client = new ManagementClient(destCredentials))
                {
                    BaseParameters baseParams = new BaseParameters()
                    {
                        RetryCount = retryCount,
                        MinBackOff = TimeSpan.FromSeconds(minBackOff),
                        MaxBackOff = TimeSpan.FromSeconds(maxBackOff),
                        DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff)
                    };
                    SubscriptionGetResponse subscriptionResponse = Retry.RetryOperation(() => client.Subscriptions.Get(),
                      baseParams, ResourceType.None);
                    destSubscriptionName = subscriptionResponse.SubscriptionName;
                }
                destSubscription = new PublishSetting()
                {
                    Id = parameters[Constants.Parameters.DestinationSubscriptionID],
                    Name = destSubscriptionName,
                    ServiceUrl = new Uri(Constants.ServiceManagementUrlValue),
                    Credentials = destCredentials
                };
            }

            // Check whether DestinationDCName exists in subscription
            List<string> locations = ExportDataCenterLocations(destSubscription.Credentials, retryCount, minBackOff, maxBackOff, deltaBackOff);

            bool destinationLocationNamePresent = locations.Any((l => string.Compare(l,
                 parameters[Constants.Parameters.DestinationDCName],
                 StringComparison.CurrentCultureIgnoreCase) == 0));

            if (!destinationLocationNamePresent)
            {
                throw new ValidationException(string.Format(StringResources.DCParamException,
                    parameters[Constants.Parameters.DestinationDCName]));
            }

            // Valiadte DestinationPrefixName
            if (parameters.ContainsKey(Constants.Parameters.DestinationPrefixName) &&
                (parameters[Constants.Parameters.DestinationPrefixName].Length < 1 || parameters[Constants.Parameters.DestinationPrefixName].Length > 5))
            {
                throw new ValidationException(string.Format(StringResources.InvalidDestinationPrefixName,
                    parameters[Constants.Parameters.DestinationPrefixName]));
            }
            #endregion

            // Stores validated parameters in class.
            ImportParameters importParams = new ImportParameters()
            {
                DestinationDCName = parameters[Constants.Parameters.DestinationDCName],
                ImportMetadataFilePath = (!validateForImport) ? null : parameters[Constants.Parameters.ImportMetadataFilePath],
                MapperXmlFilePath = importMapperXmlFilePath,
                DestinationPrefixName = destinationPrefix,
                DestinationSubscriptionSettings = destSubscription,
                RollBackOnFailure = rollBackBoolValue,
                ResumeImport = resumeImportBoolValue,
                RetryCount = retryCount,
                MinBackOff = TimeSpan.FromSeconds(minBackOff),
                MaxBackOff = TimeSpan.FromSeconds(maxBackOff),
                DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff),
                SourceSubscriptionSettings = sourceSubscription
            };

            Logger.Info(methodName, ProgressResources.ParametersValidationCompleted);
            return importParams;
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Gets list of affinity group operation response from MS azure using API call.
        /// </summary>
        /// <param name="credentials">Subscription Cloud Credentials</param>
        /// <param name="importParameters">object of <see cref="ImportParameters"/> which contains the input parameters passed for import functionality </param>
        /// <returns>List of affinity group operation response for subscription </returns>
        private static AffinityGroupListResponse GetAffinityGroupListResponseFromMSAzure(SubscriptionCloudCredentials credentials, ImportParameters importParameters)
        {
            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            Logger.Info(methodName, ProgressResources.GetAffinityGroupsFromMSAzureStarted, ResourceType.AffinityGroup.ToString());
            using (var client = new ManagementClient(credentials))
            {
                // Call management API to get list of affinity groups.
                AffinityGroupListResponse agResponse = Retry.RetryOperation(() => client.AffinityGroups.List(),
                                                                            (BaseParameters)importParameters,
                                                                            ResourceType.AffinityGroup);
                Logger.Info(methodName, ProgressResources.GetAffinityGroupsFromMSAzureCompleted, ResourceType.AffinityGroup.ToString());
                return(agResponse);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Validates and converts input paramters into <see cref="ImportParameters"/> class.
        /// </summary>
        /// <param name="parameters">Collection of input parameters stored in key value pairs
        /// <example> Operation "Import" SourceSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07"
        /// DestinationSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" DestinationDCName "West US"
        /// SourcePublishSettingsFilePath "D:\\PublishSettings.PublishSettings"
        /// DestinationPublishSettingsFilePath "D:\\PublishSettings.PublishSettings"
        /// ImportMetadataFilePath "D:\\DataCenterMigration\mydata.json" DestinationPrefixName "dc" QuietMode "True"
        /// RollBackOnFailure "True" ResumeImport "True" </example> </param>
        /// <param name="validateForImport">True if the function will be called for imort functionality.
        /// False if it is called for Migrate functionality</param>
        /// <returns>Parameters required for import functionality</returns>
        internal static ImportParameters ValidateAndConvertImportParameters(IDictionary <string, string> parameters,
                                                                            bool validateForImport)
        {
            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            Logger.Info(methodName, ProgressResources.ExecutionStarted);
            Logger.Info(methodName, ProgressResources.ParameterValidationStarted);

            #region Check for missing required parameters
            // SourcePublishSettingsFilePath/ CertificateThumbprint
            if (!parameters.Keys.Contains(Constants.Parameters.SourcePublishSettingsFilePath) && !parameters.Keys.Contains(Constants.Parameters.SourceCertificateThumbprint))
            {
                throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Source, Constants.AppConfigArguments));
            }

            // DestinationPublishSettingsFilePath
            if (!parameters.Keys.Contains(Constants.Parameters.DestinationPublishSettingsFilePath) && !parameters.Keys.Contains(Constants.Parameters.DestinationCertificateThumbprint))
            {
                throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Destination, Constants.AppConfigArguments));
            }

            // SourceSubscriptionID
            if (!parameters.Keys.Contains(Constants.Parameters.SourceSubscriptionID))
            {
                throw new ValidationException(string.Format(StringResources.MissingRequiredParameter,
                                                            Constants.Parameters.SourceSubscriptionID, Constants.AppConfigArguments));
            }

            // DestinationSubscriptionID
            if (!parameters.Keys.Contains(Constants.Parameters.DestinationSubscriptionID))
            {
                throw new ValidationException(string.Format(StringResources.MissingRequiredParameter,
                                                            Constants.Parameters.DestinationSubscriptionID, Constants.AppConfigArguments));
            }

            // DestinationDCName
            if (!parameters.Keys.Contains(Constants.Parameters.DestinationDCName))
            {
                throw new ValidationException(string.Format(StringResources.MissingRequiredParameter,
                                                            Constants.Parameters.DestinationDCName, Constants.AppConfigArguments));
            }

            //DestinationPrefixName & MapperXmlFilePath.
            if (!validateForImport)
            {
                if (!parameters.Keys.Contains(Constants.Parameters.DestinationPrefixName))
                {
                    throw new ValidationException(string.Format(StringResources.MissingRequiredParameter,
                                                                Constants.Parameters.DestinationPrefixName, Constants.AppConfigArguments));
                }
            }
            else
            {
                if (!parameters.Keys.Contains(Constants.Parameters.DestinationPrefixName) &&
                    !parameters.Keys.Contains(Constants.Parameters.MapperXmlFilePath))
                {
                    throw new ValidationException(string.Format(StringResources.MissingMapperAndPrefix,
                                                                StringResources.Destination, Constants.AppConfigArguments));
                }
            }

            #endregion

            #region Check for null or empty values
            //SourcePublishSettingsFilePath
            if ((parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath) && string.IsNullOrEmpty(parameters[Constants.Parameters.SourcePublishSettingsFilePath])) ||
                (parameters.ContainsKey(Constants.Parameters.SourceCertificateThumbprint) && string.IsNullOrEmpty(parameters[Constants.Parameters.SourceCertificateThumbprint])))
            {
                throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Source, Constants.AppConfigArguments));
            }

            // DestinationPublishSettingsFilePath
            if ((parameters.ContainsKey(Constants.Parameters.DestinationPublishSettingsFilePath) && string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationPublishSettingsFilePath])) ||
                (parameters.ContainsKey(Constants.Parameters.DestinationCertificateThumbprint) && string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationCertificateThumbprint])))
            {
                throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Destination, Constants.AppConfigArguments));
            }

            // ImportMetadataFilePath
            if (validateForImport && (string.IsNullOrEmpty(parameters[Constants.Parameters.ImportMetadataFilePath])))
            {
                throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter,
                                                            Constants.Parameters.ImportMetadataFilePath));
            }
            // DestinationSubscriptionID
            if (string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationSubscriptionID]))
            {
                throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter,
                                                            Constants.Parameters.DestinationSubscriptionID));
            }

            // DestinationDCName
            if (string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationDCName]))
            {
                throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter, Constants.Parameters.DestinationDCName));
            }

            //DestinationPrefixName & MapperXmlFilePath.
            if (!validateForImport)
            {
                if (string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationPrefixName]))
                {
                    throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter, Constants.Parameters.DestinationPrefixName));
                }
            }
            else
            {
                if ((parameters.ContainsKey(Constants.Parameters.DestinationPrefixName) &&
                     string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationPrefixName])) ||
                    (parameters.ContainsKey(Constants.Parameters.MapperXmlFilePath) &&
                     string.IsNullOrEmpty(parameters[Constants.Parameters.MapperXmlFilePath])))
                {
                    throw new ValidationException(string.Format(StringResources.MissingMapperAndPrefix,
                                                                StringResources.Destination, Constants.AppConfigArguments));
                }
            }

            #endregion

            #region Validate parameter's value.

            // Validate SourcePublishSettingsFilePath
            if ((parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath) && !File.Exists(parameters[Constants.Parameters.SourcePublishSettingsFilePath])))
            {
                throw new ValidationException(string.Format(StringResources.InvalidParameterValue,
                                                            Constants.Parameters.SourcePublishSettingsFilePath),
                                              new FileNotFoundException(StringResources.PublishSettingsFilePathParamException));
            }

            // Validate DestinationPublishSettingsFilePath
            if ((parameters.ContainsKey(Constants.Parameters.DestinationPublishSettingsFilePath) && !File.Exists(parameters[Constants.Parameters.DestinationPublishSettingsFilePath])))
            {
                throw new ValidationException(string.Format(StringResources.InvalidParameterValue,
                                                            Constants.Parameters.DestinationPublishSettingsFilePath),
                                              new FileNotFoundException(StringResources.PublishSettingsFilePathParamException));
            }

            string importMapperXmlFilePath = string.Empty;
            string destinationPrefix       = string.Empty;
            // Validate MapperXmlFilePath if provided
            if (validateForImport && parameters.ContainsKey(Constants.Parameters.MapperXmlFilePath))
            {
                importMapperXmlFilePath = parameters[Constants.Parameters.MapperXmlFilePath];

                if (!File.Exists(importMapperXmlFilePath))
                {
                    throw new ValidationException(string.Format(StringResources.InvalidParameterValue,
                                                                Constants.Parameters.MapperXmlFilePath),
                                                  new FileNotFoundException(StringResources.MapperFilePathParamException));
                }
                if (!Path.GetExtension(importMapperXmlFilePath).Equals(Constants.MapperFileExtension, StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new ValidationException(string.Format(StringResources.InvalidExtensionMapperFile,
                                                                Constants.Parameters.MapperXmlFilePath),
                                                  new FileNotFoundException(StringResources.MapperFilePathParamException));
                }
            }
            destinationPrefix = parameters.Keys.Contains(Constants.Parameters.DestinationPrefixName) ?
                                parameters[Constants.Parameters.DestinationPrefixName].ToLower() :
                                Constants.DestinationPrefixValue;

            // Validate ImportMetadataFilePath
            if (validateForImport)
            {
                if (!string.IsNullOrEmpty(parameters[Constants.Parameters.ImportMetadataFilePath]))
                {
                    string filePath = parameters[Constants.Parameters.ImportMetadataFilePath];

                    if (!File.Exists(filePath))
                    {
                        throw new ValidationException(string.Format(StringResources.InvalidParameterValue,
                                                                    Constants.Parameters.ImportMetadataFilePath),
                                                      new FileNotFoundException(StringResources.ImportMetadataFilePathParamException));
                    }
                    if (!Path.GetExtension(filePath).Equals(Constants.MetadataFileExtension, StringComparison.InvariantCultureIgnoreCase))
                    {
                        throw new ValidationException(string.Format(StringResources.InvalidExtensionMetadataFile,
                                                                    Constants.Parameters.ImportMetadataFilePath),
                                                      new FileNotFoundException(StringResources.ImportMetadataFilePathParamException));
                    }
                }
            }

            bool   rollBackBoolValue;
            bool   resumeImportBoolValue;
            int    retryCount;
            Double minBackOff;
            Double maxBackOff;
            Double deltaBackOff;

            if (!parameters.Keys.Contains(Constants.Parameters.RollBackOnFailure))
            {
                rollBackBoolValue = false;
            }
            else
            {
                bool.TryParse(parameters[Constants.Parameters.RollBackOnFailure], out rollBackBoolValue);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.ResumeImport))
            {
                resumeImportBoolValue = false;
            }
            else
            {
                bool.TryParse(parameters[Constants.Parameters.ResumeImport], out resumeImportBoolValue);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.RetryCount))
            {
                retryCount = Int32.Parse(Constants.RetryCountDefault);
            }
            else
            {
                Int32.TryParse(parameters[Constants.Parameters.RetryCount], out retryCount);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.MinBackoff))
            {
                minBackOff = Double.Parse(Constants.MinBackoffDefault);
            }
            else
            {
                Double.TryParse(parameters[Constants.Parameters.MinBackoff], out minBackOff);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.MaxBackoff))
            {
                maxBackOff = Double.Parse(Constants.MaxBackoffDefault);
            }
            else
            {
                Double.TryParse(parameters[Constants.Parameters.MaxBackoff], out maxBackOff);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.DeltaBackoff))
            {
                deltaBackOff = Double.Parse(Constants.DeltaBackoffDefault);
            }
            else
            {
                Double.TryParse(parameters[Constants.Parameters.DeltaBackoff], out deltaBackOff);
            }
            // Validate SourcePublishSettings File
            PublishSettings sourcePublishSettingsFile = null;
            PublishSetting  sourceSubscription        = null;

            if (parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath))
            {
                try
                {
                    var fileContents = File.ReadAllText(parameters[Constants.Parameters.SourcePublishSettingsFilePath]);
                    sourcePublishSettingsFile = new PublishSettings(fileContents);
                }
                catch (Exception xmlEx)
                {
                    throw new ValidationException(string.Format(StringResources.XMLParsingException + " =>" + xmlEx.Message,
                                                                parameters[Constants.Parameters.SourcePublishSettingsFilePath]));
                }

                // Check whether sourceSubscriptionId exists in publish settings file
                sourceSubscription = sourcePublishSettingsFile.Subscriptions.FirstOrDefault(a =>
                                                                                            string.Compare(a.Id, parameters[Constants.Parameters.SourceSubscriptionID], StringComparison.InvariantCultureIgnoreCase) == 0);
                if (sourceSubscription == null)
                {
                    throw new ValidationException(string.Format(StringResources.SubscriptionIdParamException, parameters[Constants.Parameters.SourceSubscriptionID], parameters[Constants.Parameters.SourcePublishSettingsFilePath]));
                }
            }
            else
            {
                string           thumbprint  = parameters[Constants.Parameters.SourceCertificateThumbprint];
                X509Certificate2 certificate = GetStoreCertificate(thumbprint);
                if (!certificate.HasPrivateKey)
                {
                    throw new ValidationException(string.Format(
                                                      StringResources.MissingPrivateKeyInCertificate, StringResources.Source, thumbprint));
                }
                var sourceCredentials = new CertificateCloudCredentials(parameters[Constants.Parameters.SourceSubscriptionID],
                                                                        certificate);
                string sourceSubscriptionName = null;
                using (var client = new ManagementClient(sourceCredentials))
                {
                    BaseParameters baseParams = new BaseParameters()
                    {
                        RetryCount   = retryCount,
                        MinBackOff   = TimeSpan.FromSeconds(minBackOff),
                        MaxBackOff   = TimeSpan.FromSeconds(maxBackOff),
                        DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff)
                    };
                    SubscriptionGetResponse subscriptionResponse = Retry.RetryOperation(() => client.Subscriptions.Get(), baseParams, ResourceType.None);
                    sourceSubscriptionName = subscriptionResponse.SubscriptionName;
                }
                sourceSubscription = new PublishSetting()
                {
                    Id          = parameters[Constants.Parameters.SourceSubscriptionID],
                    Name        = sourceSubscriptionName,
                    ServiceUrl  = new Uri(Constants.ServiceManagementUrlValue),
                    Credentials = sourceCredentials
                };
            }

            // Validate DestinationPublishSettings File
            PublishSettings destPublishSettingsFile = null;
            PublishSetting  destSubscription        = null;

            if (parameters.ContainsKey(Constants.Parameters.DestinationPublishSettingsFilePath))
            {
                try
                {
                    var fileContents = File.ReadAllText(parameters[Constants.Parameters.DestinationPublishSettingsFilePath]);
                    destPublishSettingsFile = new PublishSettings(fileContents);
                }
                catch (Exception xmlEx)
                {
                    throw new ValidationException(string.Format(StringResources.XMLParsingException + " =>" + xmlEx.Message,
                                                                parameters[Constants.Parameters.DestinationPublishSettingsFilePath]));
                }
                // Check whether destSubscriptionId exists in publish settings file
                destSubscription = destPublishSettingsFile.Subscriptions.FirstOrDefault(a =>
                                                                                        string.Compare(a.Id, parameters[Constants.Parameters.DestinationSubscriptionID], StringComparison.InvariantCultureIgnoreCase) == 0);
                if (destSubscription == null)
                {
                    throw new ValidationException(string.Format(StringResources.SubscriptionIdParamException, parameters[Constants.Parameters.DestinationSubscriptionID], parameters[Constants.Parameters.DestinationPublishSettingsFilePath]));
                }
            }
            else
            {
                string           thumbprint  = parameters[Constants.Parameters.DestinationCertificateThumbprint];
                X509Certificate2 certificate = GetStoreCertificate(thumbprint);
                if (!certificate.HasPrivateKey)
                {
                    throw new ValidationException(string.Format(
                                                      StringResources.MissingPrivateKeyInCertificate, StringResources.Destination, thumbprint));
                }
                var destCredentials = new CertificateCloudCredentials(parameters[Constants.Parameters.DestinationSubscriptionID],
                                                                      certificate);
                string destSubscriptionName = null;
                using (var client = new ManagementClient(destCredentials))
                {
                    BaseParameters baseParams = new BaseParameters()
                    {
                        RetryCount   = retryCount,
                        MinBackOff   = TimeSpan.FromSeconds(minBackOff),
                        MaxBackOff   = TimeSpan.FromSeconds(maxBackOff),
                        DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff)
                    };
                    SubscriptionGetResponse subscriptionResponse = Retry.RetryOperation(() => client.Subscriptions.Get(),
                                                                                        baseParams, ResourceType.None);
                    destSubscriptionName = subscriptionResponse.SubscriptionName;
                }
                destSubscription = new PublishSetting()
                {
                    Id          = parameters[Constants.Parameters.DestinationSubscriptionID],
                    Name        = destSubscriptionName,
                    ServiceUrl  = new Uri(Constants.ServiceManagementUrlValue),
                    Credentials = destCredentials
                };
            }

            // Check whether DestinationDCName exists in subscription
            List <string> locations = ExportDataCenterLocations(destSubscription.Credentials, retryCount, minBackOff, maxBackOff, deltaBackOff);

            bool destinationLocationNamePresent = locations.Any((l => string.Compare(l,
                                                                                     parameters[Constants.Parameters.DestinationDCName],
                                                                                     StringComparison.CurrentCultureIgnoreCase) == 0));

            if (!destinationLocationNamePresent)
            {
                throw new ValidationException(string.Format(StringResources.DCParamException,
                                                            parameters[Constants.Parameters.DestinationDCName]));
            }

            // Valiadte DestinationPrefixName
            if (parameters.ContainsKey(Constants.Parameters.DestinationPrefixName) &&
                (parameters[Constants.Parameters.DestinationPrefixName].Length < 1 || parameters[Constants.Parameters.DestinationPrefixName].Length > 5))
            {
                throw new ValidationException(string.Format(StringResources.InvalidDestinationPrefixName,
                                                            parameters[Constants.Parameters.DestinationPrefixName]));
            }
            #endregion

            // Stores validated parameters in class.
            ImportParameters importParams = new ImportParameters()
            {
                DestinationDCName               = parameters[Constants.Parameters.DestinationDCName],
                ImportMetadataFilePath          = (!validateForImport) ? null : parameters[Constants.Parameters.ImportMetadataFilePath],
                MapperXmlFilePath               = importMapperXmlFilePath,
                DestinationPrefixName           = destinationPrefix,
                DestinationSubscriptionSettings = destSubscription,
                RollBackOnFailure               = rollBackBoolValue,
                ResumeImport = resumeImportBoolValue,
                RetryCount   = retryCount,
                MinBackOff   = TimeSpan.FromSeconds(minBackOff),
                MaxBackOff   = TimeSpan.FromSeconds(maxBackOff),
                DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff),
                SourceSubscriptionSettings = sourceSubscription
            };

            Logger.Info(methodName, ProgressResources.ParametersValidationCompleted);
            return(importParams);
        }