/// <summary>
 /// Deletes the artifacts associated with an import task using the bucket name
 /// and key prefix to the artifacts in Amazon S3. No check is performed to
 /// determine whether the associated conversion task is in progress.
 /// </summary>
 /// <param name="region">
 /// The region containing the bucket where the image file artifacts were stored
 /// </param>
 /// <param name="bucketName">The name of the bucket containing the artifacts</param>
 /// <param name="keyPrefix">The common key prefix of the artifacts</param>
 /// <param name="progressCallback">Optional progress callback</param>
 /// <remarks>
 /// An Amazon S3 client will be constructed using the specified region and
 /// default profile credentials.
 /// </remarks>
 public static void DeleteImageArtifacts(RegionEndpoint region,
                                         string bucketName,
                                         string keyPrefix,
                                         CleanupProgressCallback progressCallback)
 {
     DeleteImageArtifacts(ServiceClientHelpers.CreateServiceFromAssembly <ICoreAmazonS3>(ServiceClientHelpers.S3_ASSEMBLY_NAME, ServiceClientHelpers.S3_SERVICE_CLASS_NAME, region), bucketName, keyPrefix, progressCallback);
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Attempts to get a service client at runtime which cannot be made a project reference.
        /// </summary>
        private T CreateClient <T>(string serviceClassName, string serviceConfigName, string parentAssemblyName) where T : class
        {
            try
            {
                var serviceConfig = ServiceClientHelpers.CreateServiceConfig(
                    parentAssemblyName,
                    serviceConfigName);

                serviceConfig.RegionEndpoint = RegionEndpoint.GetBySystemName(Region);

                if (Options?.ProxySettings != null)
                {
                    serviceConfig.SetWebProxy(Options.ProxySettings);
                }

                var serviceClient = ServiceClientHelpers.CreateServiceFromAssembly <T>(
                    parentAssemblyName,
                    serviceClassName,
                    new AnonymousAWSCredentials(), serviceConfig) as T;

                return(serviceClient);
            }
            catch (Exception e)
            {
                var msg = string.Format(CultureInfo.CurrentCulture,
                                        "Assembly {0} could not be found or loaded. This assembly must be available at runtime to use {1}.",
                                        parentAssemblyName,
                                        GetType().AssemblyQualifiedName);

                var exception = new InvalidOperationException(msg, e);
                _logger.Error(exception, exception.Message);
                throw exception;
            }
        }
        private CredentialsRefreshState Authenticate(ICredentials userCredential, TimeSpan credentialDuration)
        {
            CredentialsRefreshState state;

            var configuredRegion = !string.IsNullOrEmpty(ProfileData.Region) ? ProfileData.Region : AWSConfigs.AWSRegion;
            var region           = string.IsNullOrEmpty(configuredRegion)
                                ? DefaultSTSClientRegion
                                : RegionEndpoint.GetBySystemName(configuredRegion);

            ICoreAmazonSTS coreSTSClient = null;

            try
            {
                var stsConfig = ServiceClientHelpers.CreateServiceConfig(ServiceClientHelpers.STS_ASSEMBLY_NAME,
                                                                         ServiceClientHelpers.STS_SERVICE_CONFIG_NAME);
                stsConfig.RegionEndpoint = region;
                if (_proxySettings != null)
                {
                    stsConfig.SetWebProxy(_proxySettings);
                }

                coreSTSClient
                    = ServiceClientHelpers.CreateServiceFromAssembly <ICoreAmazonSTS>(ServiceClientHelpers.STS_ASSEMBLY_NAME,
                                                                                      ServiceClientHelpers.STS_SERVICE_CLASS_NAME,
                                                                                      new AnonymousAWSCredentials(),
                                                                                      stsConfig);
            }
            catch (Exception e)
            {
                var msg = string.Format(CultureInfo.CurrentCulture,
                                        "Assembly {0} could not be found or loaded. This assembly must be available at runtime to use this profile class.",
                                        ServiceClientHelpers.STS_ASSEMBLY_NAME);
                throw new InvalidOperationException(msg, e);
            }

            try
            {
                var credentials
                    = coreSTSClient.CredentialsFromSAMLAuthentication(ProfileData.EndpointSettings.Endpoint.ToString(),
                                                                      ProfileData.EndpointSettings.AuthenticationType,
                                                                      ProfileData.RoleArn,
                                                                      credentialDuration,
                                                                      userCredential);

                ProfileData.PersistSession(credentials);

                state = new CredentialsRefreshState(credentials, credentials.Expires);
            }
            catch (Exception e)
            {
                var wrappedException = new AmazonClientException("Credential generation from SAML authentication failed.", e);

                var logger = Logger.GetLogger(typeof(StoredProfileFederatedCredentials));
                logger.Error(wrappedException, wrappedException.Message);

                throw wrappedException;
            }

            return(state);
        }
        /// <summary>
        /// Gets a client to be used for AssumeRoleWithWebIdentity requests.
        /// </summary>
        /// <returns>The STS client.</returns>
        protected virtual ICoreAmazonSTS_WebIdentity CreateClient()
        {
            var configuredRegion = AWSConfigs.AWSRegion;
            var region           = string.IsNullOrEmpty(configuredRegion) ? _defaultSTSClientRegion : RegionEndpoint.GetBySystemName(configuredRegion);

            try
            {
                var stsConfig = ServiceClientHelpers.CreateServiceConfig(ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CONFIG_NAME);
                stsConfig.RegionEndpoint = region;

                if (_options?.ProxySettings != null)
                {
                    stsConfig.SetWebProxy(_options.ProxySettings);
                }

                return(ServiceClientHelpers.CreateServiceFromAssembly <ICoreAmazonSTS_WebIdentity>(
                           ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CLASS_NAME, new AnonymousAWSCredentials(), region));
            }
            catch (Exception e)
            {
                var msg = string.Format(CultureInfo.CurrentCulture,
                                        "Assembly {0} could not be found or loaded. This assembly must be available at runtime to use Amazon.Runtime.AssumeRoleAWSCredentials.",
                                        ServiceClientHelpers.STS_ASSEMBLY_NAME);
                throw new InvalidOperationException(msg, e);
            }
        }
        protected override CredentialsRefreshState GenerateNewCredentials()
        {
            var            configuredRegion = AWSConfigs.AWSRegion;
            var            region           = string.IsNullOrEmpty(configuredRegion) ? DefaultSTSClientRegion : RegionEndpoint.GetBySystemName(configuredRegion);
            ICoreAmazonSTS coreSTSClient    = null;

            try
            {
                var stsConfig = ServiceClientHelpers.CreateServiceConfig(ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CONFIG_NAME);
                stsConfig.RegionEndpoint = region;

                if (Options != null && Options.ProxySettings != null)
                {
                    stsConfig.SetWebProxy(Options.ProxySettings);
                }

                coreSTSClient = ServiceClientHelpers.CreateServiceFromAssembly <ICoreAmazonSTS>(
                    ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CLASS_NAME, SourceCredentials, stsConfig);
            }
            catch (Exception e)
            {
                var msg = string.Format(CultureInfo.CurrentCulture,
                                        "Assembly {0} could not be found or loaded. This assembly must be available at runtime to use Amazon.Runtime.AssumeRoleAWSCredentials.",
                                        ServiceClientHelpers.STS_ASSEMBLY_NAME);
                var exception = new InvalidOperationException(msg, e);
                Logger.GetLogger(typeof(AssumeRoleAWSCredentials)).Error(exception, exception.Message);
                throw exception;
            }

            var credentials = coreSTSClient.CredentialsFromAssumeRoleAuthentication(RoleArn, RoleSessionName, Options);

            _logger.InfoFormat("New credentials created for assume role that expire at {0}", credentials.Expiration.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture));
            return(new CredentialsRefreshState(credentials, credentials.Expiration));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Instantiates an SigV4a signer using CRT's SigV4a implementation
        /// </summary>
        /// <param name="signPayload">Whether to sign the request's payload</param>
        public AWS4aSignerCRTWrapper(bool signPayload)
        {
            if (_awsSigV4AProvider == null)
            {
                lock (_lock)
                {
                    if (_awsSigV4AProvider == null)
                    {
                        try
                        {
                            var crtWrapperTypeInfo = ServiceClientHelpers.LoadTypeFromAssembly(CRT_WRAPPER_ASSEMBLY_NAME, CRT_WRAPPER_CLASS_NAME);
                            var constructor        = crtWrapperTypeInfo.GetConstructor(new ITypeInfo[]
                            {
                                TypeFactory.GetTypeInfo(typeof(bool))
                            });

                            _awsSigV4AProvider = constructor.Invoke(new object[] { signPayload }) as IAWSSigV4aProvider;
                        }
                        catch (FileNotFoundException)
                        {
                            throw new AWSCommonRuntimeException
                                  (
                                      string.Format(CultureInfo.InvariantCulture, "Attempting to make a request that requires an implementation of AWS Signature V4a. " +
                                                    $"Add a reference to the {CRT_WRAPPER_NUGET_PACKGE_NAME} NuGet package to your project to include the AWS Signature V4a signer.")
                                  );
                        }
                    }
                }
            }
        }
Ejemplo n.º 7
0
        protected override CredentialsRefreshState GenerateNewCredentials()
        {
            var configuredRegion = AWSConfigs.AWSRegion;
            var region           = string.IsNullOrEmpty(configuredRegion) ? DefaultSTSClientRegion : RegionEndpoint.GetBySystemName(configuredRegion);

            Amazon.SecurityToken.Model.Credentials cc = null;
            try
            {
                var stsConfig = ServiceClientHelpers.CreateServiceConfig(ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CONFIG_NAME);
                stsConfig.RegionEndpoint = region;

                var stsClient = new AmazonSecurityTokenServiceClient(new AnonymousAWSCredentials());

                OidcToken oidcToken = SourceCredentials.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(TargetAudience).WithTokenFormat(OidcTokenFormat.Standard)).Result;

                TargetAssumeRoleRequest.WebIdentityToken = oidcToken.GetAccessTokenAsync().Result;

                AssumeRoleWithWebIdentityResponse sessionTokenResponse = stsClient.AssumeRoleWithWebIdentityAsync(TargetAssumeRoleRequest).Result;

                cc = sessionTokenResponse.Credentials;
                _logger.InfoFormat("New credentials created for assume role that expire at {0}", cc.Expiration.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture));
                return(new CredentialsRefreshState(new ImmutableCredentials(cc.AccessKeyId, cc.SecretAccessKey, cc.SessionToken), cc.Expiration));
            }
            catch (Exception e)
            {
                var msg       = "Error exchanging Google OIDC token for AWS STS ";
                var exception = new InvalidOperationException(msg, e);
                Logger.GetLogger(typeof(GoogleCompatCredentials)).Error(exception, exception.Message);
                throw exception;
            }
        }
 /// <summary>
 /// Deletes the artifacts associated with an import task using a presigned
 /// url to address the manifest for the import. No check is performed to
 /// determine whether the associated conversion task is in progress.
 /// </summary>
 /// <param name="awsCredentials">
 /// Credentials to use to instantiate the Amazon EC2 and Amazon S3 clients needed to
 /// complete the operation.
 /// </param>
 /// <param name="region">
 /// The region containing the bucket where the image file artifacts were stored
 /// </param>
 /// <param name="manifestUrl">
 /// Presigned URL to the import manifest file
 /// </param>
 /// <param name="progressCallback">Optional progress callback</param>
 public static void DeleteImageArtifacts(AWSCredentials awsCredentials,
                                         RegionEndpoint region,
                                         string manifestUrl,
                                         CleanupProgressCallback progressCallback)
 {
     DeleteImageArtifacts(ServiceClientHelpers.CreateServiceFromAssembly <ICoreAmazonS3>(ServiceClientHelpers.S3_ASSEMBLY_NAME, ServiceClientHelpers.S3_SERVICE_CLASS_NAME, awsCredentials, region),
                          manifestUrl,
                          progressCallback);
 }
 /// <summary>
 /// Deletes the image file artifacts associated with the specified conversion task.
 /// If the task is still active, ignoreActiveTask must be set true to enable artifact
 /// deletion, which will cause the task to fail. Use this option at your own risk.
 /// </summary>
 /// <param name="region">
 /// The region containing the bucket where the image file artifacts were stored
 /// </param>
 /// <param name="conversionTaskId">
 /// The ID of the conversion task that used the image file
 /// </param>
 /// <param name="ignoreActiveTask">
 /// If true the artifacts are deleted even if the conversion task is still in progress
 /// </param>
 /// <param name="progressCallback">Optional progress callback</param>
 /// <remarks>
 /// Amazon EC2 and S3 clients will be constructed using the specified region and
 /// default credentials.
 /// </remarks>
 public static void DeleteImageArtifacts(RegionEndpoint region,
                                         string conversionTaskId,
                                         bool ignoreActiveTask,
                                         CleanupProgressCallback progressCallback)
 {
     DeleteImageArtifacts(new AmazonEC2Client(region),
                          ServiceClientHelpers.CreateServiceFromAssembly <ICoreAmazonS3>(ServiceClientHelpers.S3_ASSEMBLY_NAME, ServiceClientHelpers.S3_SERVICE_CLASS_NAME, region),
                          conversionTaskId,
                          ignoreActiveTask,
                          progressCallback);
 }
Ejemplo n.º 10
0
        internal ICoreAmazonS3 GetClient(RegionEndpoint region)
        {
            ICoreAmazonS3 output;

            if (!this.clientsByRegion.TryGetValue(region.SystemName, out output))
            {
                output = ServiceClientHelpers.CreateServiceFromAssembly <ICoreAmazonS3>(ServiceClientHelpers.S3_ASSEMBLY_NAME, ServiceClientHelpers.S3_SERVICE_CLASS_NAME, this.ddbClient);
                this.clientsByRegion.Add(region.SystemName, output);
            }
            return(output);
        }
Ejemplo n.º 11
0
        private CredentialsRefreshState Authenticate(ICredentials userCredential)
        {
            CredentialsRefreshState state;

            var region = Options.STSRegion;

            if (region == null && !string.IsNullOrEmpty(AWSConfigs.AWSRegion))
            {
                region = RegionEndpoint.GetBySystemName(AWSConfigs.AWSRegion);
            }
            else
            {
                region = DefaultSTSClientRegion;
            }

            ICoreAmazonSTS coreSTSClient = null;

            try
            {
                var stsConfig = ServiceClientHelpers.CreateServiceConfig(
                    ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CONFIG_NAME);

                stsConfig.RegionEndpoint = region;
                if (Options.ProxySettings != null)
                {
                    stsConfig.SetWebProxy(Options.ProxySettings);
                }

                coreSTSClient = ServiceClientHelpers.CreateServiceFromAssembly <ICoreAmazonSTS>(
                    ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CLASS_NAME,
                    new AnonymousAWSCredentials(), stsConfig);
            }
            catch (Exception e)
            {
                var msg = string.Format(CultureInfo.CurrentCulture,
                                        "Assembly {0} could not be found or loaded. This assembly must be available at runtime to use this profile class.",
                                        ServiceClientHelpers.STS_ASSEMBLY_NAME);
                throw new InvalidOperationException(msg, e);
            }

            var samlCoreSTSClient
#if NETSTANDARD
                = coreSTSClient as ICoreAmazonSTS_SAML;

            if (coreSTSClient == null)
            {
                throw new NotImplementedException("The currently loaded version of AWSSDK.SecurityToken doesn't support SAML authentication.");
            }
Ejemplo n.º 12
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                string containerName = Container != null ? Container.Name : ResourceId.Split('/')[8];
                ConfirmAction(
                    Force.IsPresent,
                    string.Format(Resources.RegisterContainerWarning, containerName),
                    Resources.RegisterContainerMessage,
                    containerName, () =>
                {
                    base.ExecuteCmdlet();

                    ResourceIdentifier resourceIdentifier = new ResourceIdentifier(VaultId);
                    string vaultName = resourceIdentifier.ResourceName;
                    string vaultResourceGroupName = resourceIdentifier.ResourceGroupName;

                    PsBackupProviderManager providerManager =
                        new PsBackupProviderManager(new Dictionary <Enum, object>()
                    {
                        { VaultParams.VaultName, vaultName },
                        { VaultParams.ResourceGroupName, vaultResourceGroupName },
                        { ContainerParams.Name, containerName },
                        { ContainerParams.ContainerType, ServiceClientHelpers.GetServiceClientWorkloadType(WorkloadType).ToString() },
                        { ContainerParams.BackupManagementType, BackupManagementType.ToString() },
                        { ContainerParams.Container, Container }
                    }, ServiceClientAdapter);

                    IPsBackupProvider psBackupProvider =
                        providerManager.GetProviderInstance(WorkloadType, BackupManagementType);
                    psBackupProvider.RegisterContainer();

                    // List containers
                    string backupManagementType = BackupManagementType.ToString();
                    ODataQuery <BMSContainerQueryObject> queryParams = new ODataQuery <BMSContainerQueryObject>(
                        q => q.FriendlyName == containerName &&
                        q.BackupManagementType == backupManagementType);

                    var listResponse = ServiceClientAdapter.ListContainers(queryParams,
                                                                           vaultName: vaultName, resourceGroupName: vaultResourceGroupName);
                    var containerModels = ConversionHelpers.GetContainerModelList(listResponse);
                    WriteObject(containerModels, enumerateCollection: true);
                });
            }, ShouldProcess(ResourceId, VerbsLifecycle.Register));
        }
Ejemplo n.º 13
0
        private static ICoreAmazonKMS CreateFromExistingClient(AmazonServiceClient existingClient, string feature)
        {
            ICoreAmazonKMS coreKMSClient = null;

            try
            {
                coreKMSClient = ServiceClientHelpers.CreateServiceFromAssembly <ICoreAmazonKMS>(
                    ServiceClientHelpers.KMS_ASSEMBLY_NAME, ServiceClientHelpers.KMS_SERVICE_CLASS_NAME,
                    existingClient);
            }
            catch (Exception e)
            {
                var msg = string.Format(CultureInfo.CurrentCulture,
                                        "Error instantiating {0} from assembly {1}.  " +
                                        "The assembly and class must be available at runtime in order to use {2}.",
                                        ServiceClientHelpers.KMS_SERVICE_CLASS_NAME, ServiceClientHelpers.KMS_ASSEMBLY_NAME, feature);
                throw new InvalidOperationException(msg, e);
            }

            return(coreKMSClient);
        }
Ejemplo n.º 14
0
        internal DownloadFileCommand(ArchiveTransferManager manager, string vaultName, string archiveId, string filePath, DownloadOptions options)
        {
            this.manager   = manager;
            this.vaultName = vaultName;
            this.archiveId = archiveId;
            this.filePath  = filePath;
            this.options   = options;

            var glacierClient = this.manager.GlacierClient as AmazonGlacierClient;

            if (glacierClient == null)
            {
                throw new InvalidOperationException("This can only be called using an AmazonGlacierClient");
            }

            this.snsClient = ServiceClientHelpers.CreateServiceFromAnother <AmazonSimpleNotificationServiceClient, AmazonSimpleNotificationServiceConfig>(glacierClient);
            this.sqsClient = ServiceClientHelpers.CreateServiceFromAnother <AmazonSQSClient, AmazonSQSConfig>(glacierClient);

            if (this.options == null)
            {
                this.options = new DownloadOptions();
            }
        }
Ejemplo n.º 15
0
        private CredentialsRefreshState Authenticate(ICredentials userCredential)
        {
            CredentialsRefreshState state;

            var region = Options.STSRegion;

            if (region == null && !string.IsNullOrEmpty(AWSConfigs.AWSRegion))
            {
                region = RegionEndpoint.GetBySystemName(AWSConfigs.AWSRegion);
            }
            else
            {
                region = DefaultSTSClientRegion;
            }

            ICoreAmazonSTS coreSTSClient = null;

            try
            {
                var stsConfig = ServiceClientHelpers.CreateServiceConfig(
                    ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CONFIG_NAME);

                stsConfig.RegionEndpoint = region;
                if (Options.ProxySettings != null)
                {
                    stsConfig.SetWebProxy(Options.ProxySettings);
                }

                coreSTSClient = ServiceClientHelpers.CreateServiceFromAssembly <ICoreAmazonSTS>(
                    ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CLASS_NAME,
                    new AnonymousAWSCredentials(), stsConfig);
            }
            catch (Exception e)
            {
                var msg = string.Format(CultureInfo.CurrentCulture,
                                        "Assembly {0} could not be found or loaded. This assembly must be available at runtime to use this profile class.",
                                        ServiceClientHelpers.STS_ASSEMBLY_NAME);
                throw new InvalidOperationException(msg, e);
            }

            try
            {
                var credentials = coreSTSClient.CredentialsFromSAMLAuthentication(SAMLEndpoint.EndpointUri.ToString(),
                                                                                  SAMLEndpoint.AuthenticationType.ToString(), RoleArn, MaximumCredentialTimespan, userCredential);

                RegisterRoleSession(credentials);

                state = new CredentialsRefreshState(credentials, credentials.Expires);
            }
            catch (Exception e)
            {
                var wrappedException = new AmazonClientException("Credential generation from SAML authentication failed.", e);

                var logger = Logger.GetLogger(typeof(FederatedAWSCredentials));
                logger.Error(wrappedException, wrappedException.Message);

                throw wrappedException;
            }

            return(state);
        }
Ejemplo n.º 16
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                base.ExecuteCmdlet();

                ResourceIdentifier resourceIdentifier = new ResourceIdentifier(VaultId);
                string vaultName         = resourceIdentifier.ResourceName;
                string resourceGroupName = resourceIdentifier.ResourceGroupName;

                WriteDebug(string.Format("Input params - Name:{0}, " +
                                         "WorkloadType: {1}, BackupManagementType:{2}, " +
                                         "ParameterSetName: {3}",
                                         Name == null ? "NULL" : Name,
                                         WorkloadType.HasValue ? WorkloadType.ToString() : "NULL",
                                         BackupManagementType.HasValue ?
                                         BackupManagementType.ToString() : "NULL",
                                         this.ParameterSetName));

                if (ParameterSetName == PolicyNameParamSet)
                {
                    // validate policyName
                    PolicyCmdletHelpers.ValidateProtectionPolicyName(Name);

                    // query service
                    ServiceClientModel.ProtectionPolicyResource policy =
                        PolicyCmdletHelpers.GetProtectionPolicyByName(
                            Name,
                            ServiceClientAdapter,
                            vaultName: vaultName,
                            resourceGroupName: resourceGroupName);
                    if (policy == null)
                    {
                        throw new ArgumentException(string.Format(Resources.PolicyNotFoundException, Name));
                    }

                    WriteObject(ConversionHelpers.GetPolicyModel(policy));
                }
                else
                {
                    List <PolicyBase> policyList     = new List <PolicyBase>();
                    string serviceClientProviderType = null;

                    switch (this.ParameterSetName)
                    {
                    case WorkloadParamSet:
                        if (WorkloadType == Models.WorkloadType.AzureVM)
                        {
                            serviceClientProviderType =
                                ServiceClientHelpers.GetServiceClientProviderType(Models.WorkloadType.AzureVM);
                        }
                        else if (WorkloadType == Models.WorkloadType.AzureSQLDatabase)
                        {
                            serviceClientProviderType = ServiceClientHelpers.GetServiceClientProviderType(Models.WorkloadType.AzureSQLDatabase);
                        }
                        else if (WorkloadType == Models.WorkloadType.AzureFiles)
                        {
                            serviceClientProviderType = ServiceClientHelpers.GetServiceClientProviderType(Models.WorkloadType.AzureFiles);
                        }
                        else if (WorkloadType == Models.WorkloadType.MSSQL)
                        {
                            serviceClientProviderType = ServiceClientHelpers.GetServiceClientProviderType(Models.WorkloadType.MSSQL);
                        }
                        break;

                    case WorkloadBackupMangementTypeParamSet:
                        if (WorkloadType == Models.WorkloadType.AzureVM)
                        {
                            if (BackupManagementType != Models.BackupManagementType.AzureVM)
                            {
                                throw new ArgumentException(
                                    Resources.AzureVMUnsupportedBackupManagementTypeException);
                            }
                            serviceClientProviderType = ServiceClientHelpers.
                                                        GetServiceClientProviderType(Models.WorkloadType.AzureVM);
                        }
                        else if (WorkloadType == Models.WorkloadType.AzureSQLDatabase)
                        {
                            if (BackupManagementType != Models.BackupManagementType.AzureSQL)
                            {
                                throw new ArgumentException(
                                    Resources.AzureSqlUnsupportedBackupManagementTypeException);
                            }
                            serviceClientProviderType =
                                ServiceClientHelpers.GetServiceClientProviderType(
                                    Models.WorkloadType.AzureSQLDatabase);
                        }
                        else if (WorkloadType == Models.WorkloadType.AzureFiles)
                        {
                            if (BackupManagementType != Models.BackupManagementType.AzureStorage)
                            {
                                throw new ArgumentException(
                                    Resources.AzureFileUnsupportedBackupManagementTypeException);
                            }
                            serviceClientProviderType =
                                ServiceClientHelpers.GetServiceClientProviderType(
                                    Models.WorkloadType.AzureFiles);
                        }
                        else if (WorkloadType == Models.WorkloadType.AzureFiles)
                        {
                            if (BackupManagementType != Models.BackupManagementType.AzureStorage)
                            {
                                throw new ArgumentException(
                                    Resources.AzureFileUnsupportedBackupManagementTypeException);
                            }
                            serviceClientProviderType =
                                ServiceClientHelpers.GetServiceClientProviderType(
                                    Models.WorkloadType.AzureFiles);
                        }
                        else if (WorkloadType == Models.WorkloadType.MSSQL)
                        {
                            if (BackupManagementType != Models.BackupManagementType.AzureWorkload)
                            {
                                throw new ArgumentException(
                                    Resources.AzureFileUnsupportedBackupManagementTypeException);
                            }
                            serviceClientProviderType =
                                ServiceClientHelpers.GetServiceClientProviderType(
                                    Models.WorkloadType.MSSQL);
                        }
                        else
                        {
                            throw new ArgumentException(string.Format(
                                                            Resources.UnsupportedWorkloadBackupManagementTypeException,
                                                            WorkloadType.ToString(),
                                                            BackupManagementType.ToString()));
                        }
                        break;

                    default:
                        break;
                    }

                    var backupManagementTypeFilter = serviceClientProviderType;


                    ODataQuery <ServiceClientModel.ProtectionPolicyQueryObject> queryParams
                        = new ODataQuery <ServiceClientModel.ProtectionPolicyQueryObject>(
                              q => q.BackupManagementType == backupManagementTypeFilter);

                    WriteDebug("going to query service to get list of policies");
                    List <ServiceClientModel.ProtectionPolicyResource> respList =
                        ServiceClientAdapter.ListProtectionPolicy(
                            queryParams,
                            vaultName: vaultName,
                            resourceGroupName: resourceGroupName);
                    WriteDebug("Successfully got response from service");

                    policyList = ConversionHelpers.GetPolicyModelList(respList);
                    WriteObject(policyList, enumerateCollection: true);
                }
            });
        }
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                base.ExecuteCmdlet();

                ResourceIdentifier resourceIdentifier = new ResourceIdentifier(VaultId);
                string vaultName         = resourceIdentifier.ResourceName;
                string resourceGroupName = resourceIdentifier.ResourceGroupName;

                // initialize values to default
                DateTime rangeStart = DateTime.UtcNow.AddDays(-1);
                DateTime rangeEnd   = DateTime.UtcNow;

                if (From.HasValue)
                {
                    rangeStart = From.Value;
                }

                if (!From.HasValue && To.HasValue)
                {
                    throw new Exception(Resources.JobFromNotProvided);
                }

                if (To.HasValue)
                {
                    rangeEnd = To.Value;
                }

                if (rangeStart.Kind != DateTimeKind.Utc || rangeEnd.Kind != DateTimeKind.Utc)
                {
                    throw new Exception(Resources.JobTimeFiltersShouldBeSpecifiedInUtc);
                }

                // validate filters
                if (rangeEnd <= rangeStart)
                {
                    throw new Exception(Resources.JobToShouldBeGreaterThanFrom);
                }
                else if (rangeEnd.Subtract(rangeStart) > TimeSpan.FromDays(30))
                {
                    throw new Exception(Resources.JobAllowedDateTimeRangeExceeded);
                }
                else if (rangeStart > DateTime.UtcNow)
                {
                    throw new Exception(Resources.JobStartTimeShouldBeLessThanCurrent);
                }

                // validate JobId and Job objects
                if (!string.IsNullOrEmpty(JobId))
                {
                    // if JobId and Job are provided together and they don't match then throw exception
                    if (Job != null && JobId != Job.JobId)
                    {
                        throw new Exception(Resources.JobJobIdAndJobMismatch);
                    }
                }
                else if (Job != null)
                {
                    JobId = Job.JobId;
                }

                List <JobBase> result = new List <JobBase>();

                WriteDebug(string.Format("Filters provided are: StartTime - {0} " +
                                         "EndTime - {1} Status - {2} Operation - {3} Type - {4} UseSecondaryRegion - {5}",
                                         From,
                                         To,
                                         Status,
                                         Operation,
                                         BackupManagementType,
                                         UseSecondaryRegion.ToString()));

                int resultCount = 0;

                if (UseSecondaryRegion.IsPresent)
                {
                    ARSVault vault         = ServiceClientAdapter.GetVault(resourceGroupName, vaultName);
                    string secondaryRegion = BackupUtils.regionMap[vault.Location];

                    WriteDebug(" Getting CRR jobs from secondary region: " + secondaryRegion);
                    var adapterResponse = ServiceClientAdapter.GetCrrJobs(VaultId,
                                                                          JobId,
                                                                          ServiceClientHelpers.GetServiceClientJobStatus(Status),
                                                                          Operation.ToString(),
                                                                          rangeStart,
                                                                          rangeEnd,
                                                                          ServiceClientHelpers.GetServiceClientBackupManagementType(BackupManagementType),
                                                                          secondaryRegion);

                    JobConversions.AddServiceClientJobsToPSList(
                        adapterResponse, result, ref resultCount);
                }
                else
                {
                    var adapterResponse = ServiceClientAdapter.GetJobs(
                        JobId,
                        ServiceClientHelpers.GetServiceClientJobStatus(Status),
                        Operation.ToString(),
                        rangeStart,
                        rangeEnd,
                        ServiceClientHelpers.GetServiceClientBackupManagementType(
                            BackupManagementType),
                        vaultName: vaultName,
                        resourceGroupName: resourceGroupName);

                    JobConversions.AddServiceClientJobsToPSList(
                        adapterResponse, result, ref resultCount);
                }

                WriteDebug("Number of jobs fetched: " + result.Count);
                WriteObject(result, enumerateCollection: true);
            });
        }
Ejemplo n.º 18
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                base.ExecuteCmdlet();

                WriteDebug(string.Format("Input params - Name:{0}, " +
                                         "WorkloadType: {1}, BackupManagementType:{2}, " +
                                         "ParameterSetName: {3}",
                                         Name == null ? "NULL" : Name,
                                         WorkloadType.HasValue ? WorkloadType.ToString() : "NULL",
                                         BackupManagementType.HasValue ?
                                         BackupManagementType.ToString() : "NULL",
                                         this.ParameterSetName));

                if (this.ParameterSetName == PolicyNameParamSet)
                {
                    // validate policyName
                    PolicyCmdletHelpers.ValidateProtectionPolicyName(Name);

                    // query service
                    ServiceClientModel.ProtectionPolicyResponse policy =
                        PolicyCmdletHelpers.GetProtectionPolicyByName(
                            Name,
                            ServiceClientAdapter);
                    if (policy == null)
                    {
                        throw new ArgumentException(string.Format(Resources.PolicyNotFoundException, Name));
                    }

                    WriteObject(ConversionHelpers.GetPolicyModel(policy.Item));
                }
                else
                {
                    List <PolicyBase> policyList     = new List <PolicyBase>();
                    string serviceClientProviderType = null;

                    switch (this.ParameterSetName)
                    {
                    case WorkloadParamSet:
                        if (WorkloadType == Models.WorkloadType.AzureVM)
                        {
                            serviceClientProviderType =
                                ServiceClientHelpers.GetServiceClientProviderType(Models.WorkloadType.AzureVM);
                        }
                        break;

                    case WorkloadBackupMangementTypeParamSet:
                        if (WorkloadType == Models.WorkloadType.AzureVM)
                        {
                            if (BackupManagementType != Models.BackupManagementType.AzureVM)
                            {
                                throw new ArgumentException(
                                    Resources.AzureVMUnsupportedBackupManagementTypeException);
                            }
                            serviceClientProviderType = ServiceClientHelpers.
                                                        GetServiceClientProviderType(Models.WorkloadType.AzureVM);
                        }
                        else
                        {
                            throw new ArgumentException(string.Format(
                                                            Resources.UnsupportedWorkloadBackupManagementTypeException,
                                                            WorkloadType.ToString(),
                                                            BackupManagementType.ToString()));
                        }
                        break;

                    default:
                        break;
                    }

                    ServiceClientModel.ProtectionPolicyQueryParameters queryParams =
                        new ServiceClientModel.ProtectionPolicyQueryParameters()
                    {
                        BackupManagementType = serviceClientProviderType
                    };

                    WriteDebug("going to query service to get list of policies");
                    ServiceClientModel.ProtectionPolicyListResponse respList =
                        ServiceClientAdapter.ListProtectionPolicy(queryParams);
                    WriteDebug("Successfully got response from service");

                    policyList = ConversionHelpers.GetPolicyModelList(respList);
                    WriteObject(policyList, enumerateCollection: true);
                }
            });
        }
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                base.ExecuteCmdlet();

                // initialize values to default
                DateTime rangeStart = DateTime.UtcNow.AddDays(-1);
                DateTime rangeEnd   = DateTime.UtcNow;

                if (From.HasValue)
                {
                    rangeStart = From.Value;
                }

                if (!From.HasValue && To.HasValue)
                {
                    throw new Exception(Resources.JobFromNotProvided);
                }

                if (To.HasValue)
                {
                    rangeEnd = To.Value;
                }

                if (rangeStart.Kind != DateTimeKind.Utc || rangeEnd.Kind != DateTimeKind.Utc)
                {
                    throw new Exception(Resources.JobTimeFiltersShouldBeSpecifiedInUtc);
                }

                // validate filters
                if (rangeEnd <= rangeStart)
                {
                    throw new Exception(Resources.JobToShouldBeGreaterThanFrom);
                }
                else if (rangeEnd.Subtract(rangeStart) > TimeSpan.FromDays(30))
                {
                    throw new Exception(Resources.JobAllowedDateTimeRangeExceeded);
                }

                // validate JobId and Job objects
                if (!string.IsNullOrEmpty(JobId))
                {
                    // if JobId and Job are provided together and they don't match then throw exception
                    if (Job != null && JobId != Job.JobId)
                    {
                        throw new Exception(Resources.JobJobIdAndJobMismatch);
                    }
                }
                else if (Job != null)
                {
                    JobId = Job.JobId;
                }

                List <JobBase> result = new List <JobBase>();

                WriteDebug(string.Format("Filters provided are: StartTime - {0} " +
                                         "EndTime - {1} Status - {2} Operation - {3} Type - {4}",
                                         From,
                                         To,
                                         Status,
                                         Operation,
                                         BackupManagementType));

                int resultCount     = 0;
                var adapterResponse = ServiceClientAdapter.GetJobs(JobId,
                                                                   Status.HasValue ? Status.ToString() : null,
                                                                   Operation.HasValue ? Operation.ToString() : null,
                                                                   rangeStart,
                                                                   rangeEnd,
                                                                   BackupManagementType.HasValue ?
                                                                   Helpers.JobConversions.GetJobTypeForService(BackupManagementType.Value) : null);
                JobConversions.AddServiceClientJobsToPSList(adapterResponse, result, ref resultCount);

                while (!string.IsNullOrEmpty(adapterResponse.ItemList.NextLink))
                {
                    if (resultCount >= JobConstants.MaximumJobsToFetch)
                    {
                        // trace a warning that there are more jobs and user has to refine filters.
                        WriteWarning(Resources.JobRefineFilters);
                        break;
                    }

                    string skipToken;
                    ServiceClientHelpers.GetSkipTokenFromNextLink(
                        adapterResponse.ItemList.NextLink, out skipToken);
                    if (skipToken != null)
                    {
                        adapterResponse = ServiceClientAdapter.GetJobs(JobId,
                                                                       Status.HasValue ? Status.ToString() : null,
                                                                       Operation.HasValue ? Operation.ToString() : null,
                                                                       rangeStart,
                                                                       rangeEnd,
                                                                       BackupManagementType.HasValue ?
                                                                       Helpers.JobConversions.GetJobTypeForService(BackupManagementType.Value) : null,
                                                                       null,
                                                                       skipToken);
                        JobConversions.AddServiceClientJobsToPSList(adapterResponse, result, ref resultCount);
                    }
                    else
                    {
                        break;
                    }
                }

                WriteDebug("Number of jobs fetched: " + result.Count);
                WriteObject(result, enumerateCollection: true);
            });
        }
        /// <summary>
        /// Lists protected items protected by the recovery services vault according to the provider data
        /// </summary>
        /// <returns>List of protected items</returns>
        public List <ItemBase> ListProtectedItems()
        {
            ContainerBase container =
                (ContainerBase)this.ProviderData[ItemParams.Container];
            string name = (string)this.ProviderData[ItemParams.AzureVMName];
            ItemProtectionStatus protectionStatus =
                (ItemProtectionStatus)this.ProviderData[ItemParams.ProtectionStatus];
            ItemProtectionState status =
                (ItemProtectionState)this.ProviderData[ItemParams.ProtectionState];

            Models.WorkloadType workloadType =
                (Models.WorkloadType) this.ProviderData[ItemParams.WorkloadType];

            ProtectedItemListQueryParam queryParams = new ProtectedItemListQueryParam();

            queryParams.DatasourceType       = ServiceClientModel.WorkloadType.VM;
            queryParams.BackupManagementType = ServiceClientModel.BackupManagementType.AzureIaasVM.ToString();

            List <ProtectedItemResource> protectedItems = new List <ProtectedItemResource>();
            string            skipToken         = null;
            PaginationRequest paginationRequest = null;

            do
            {
                var listResponse = ServiceClientAdapter.ListProtectedItem(queryParams, paginationRequest);
                protectedItems.AddRange(listResponse.ItemList.Value);

                ServiceClientHelpers.GetSkipTokenFromNextLink(listResponse.ItemList.NextLink, out skipToken);
                if (skipToken != null)
                {
                    paginationRequest           = new PaginationRequest();
                    paginationRequest.SkipToken = skipToken;
                }
            } while (skipToken != null);

            // 1. Filter by container
            if (container != null)
            {
                protectedItems = protectedItems.Where(protectedItem =>
                {
                    Dictionary <UriEnums, string> dictionary = HelperUtils.ParseUri(protectedItem.Id);
                    string containerUri = HelperUtils.GetContainerUri(dictionary, protectedItem.Id);
                    return(containerUri.Contains(container.Name));
                }).ToList();
            }

            List <ProtectedItemResponse> protectedItemGetResponses = new List <ProtectedItemResponse>();

            // 2. Filter by item's friendly name
            if (!string.IsNullOrEmpty(name))
            {
                protectedItems = protectedItems.Where(protectedItem =>
                {
                    Dictionary <UriEnums, string> dictionary = HelperUtils.ParseUri(protectedItem.Id);
                    string protectedItemUri = HelperUtils.GetProtectedItemUri(dictionary, protectedItem.Id);
                    return(protectedItemUri.ToLower().Contains(name.ToLower()));
                }).ToList();

                GetProtectedItemQueryParam getItemQueryParams = new GetProtectedItemQueryParam();
                getItemQueryParams.Expand = "extendedinfo";

                for (int i = 0; i < protectedItems.Count; i++)
                {
                    Dictionary <UriEnums, string> dictionary = HelperUtils.ParseUri(protectedItems[i].Id);
                    string containerUri     = HelperUtils.GetContainerUri(dictionary, protectedItems[i].Id);
                    string protectedItemUri = HelperUtils.GetProtectedItemUri(dictionary, protectedItems[i].Id);

                    var getResponse = ServiceClientAdapter.GetProtectedItem(containerUri, protectedItemUri, getItemQueryParams);
                    protectedItemGetResponses.Add(getResponse);
                }
            }

            List <ItemBase> itemModels = ConversionHelpers.GetItemModelList(protectedItems);

            if (!string.IsNullOrEmpty(name))
            {
                for (int i = 0; i < itemModels.Count; i++)
                {
                    AzureVmItemExtendedInfo extendedInfo = new AzureVmItemExtendedInfo();
                    var serviceClientExtendedInfo        = ((AzureIaaSVMProtectedItem)protectedItemGetResponses[i].Item.Properties).ExtendedInfo;
                    if (serviceClientExtendedInfo.OldestRecoveryPoint.HasValue)
                    {
                        extendedInfo.OldestRecoveryPoint = serviceClientExtendedInfo.OldestRecoveryPoint;
                    }
                    extendedInfo.PolicyState                  = serviceClientExtendedInfo.PolicyInconsistent.ToString();
                    extendedInfo.RecoveryPointCount           = serviceClientExtendedInfo.RecoveryPointCount;
                    ((AzureVmItem)itemModels[i]).ExtendedInfo = extendedInfo;
                }
            }

            // 3. Filter by item's Protection Status
            if (protectionStatus != 0)
            {
                itemModels = itemModels.Where(itemModel =>
                {
                    return(((AzureVmItem)itemModel).ProtectionStatus == protectionStatus);
                }).ToList();
            }

            // 4. Filter by item's Protection State
            if (status != 0)
            {
                itemModels = itemModels.Where(itemModel =>
                {
                    return(((AzureVmItem)itemModel).ProtectionState == status);
                }).ToList();
            }

            // 5. Filter by workload type
            if (workloadType != 0)
            {
                itemModels = itemModels.Where(itemModel =>
                {
                    return(itemModel.WorkloadType == workloadType);
                }).ToList();
            }

            return(itemModels);
        }
Ejemplo n.º 21
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                base.ExecuteCmdlet();

                // initialize values to default
                DateTime rangeStart = DateTime.UtcNow.AddDays(-1);
                DateTime rangeEnd   = DateTime.UtcNow;

                if (From.HasValue)
                {
                    rangeStart = From.Value;
                }

                if (!From.HasValue && To.HasValue)
                {
                    throw new Exception(Resources.JobFromNotProvided);
                }

                if (To.HasValue)
                {
                    rangeEnd = To.Value;
                }

                if (rangeStart.Kind != DateTimeKind.Utc || rangeEnd.Kind != DateTimeKind.Utc)
                {
                    throw new Exception(Resources.JobTimeFiltersShouldBeSpecifiedInUtc);
                }

                // validate filters
                if (rangeEnd <= rangeStart)
                {
                    throw new Exception(Resources.JobToShouldBeGreaterThanFrom);
                }
                else if (rangeEnd.Subtract(rangeStart) > TimeSpan.FromDays(30))
                {
                    throw new Exception(Resources.JobAllowedDateTimeRangeExceeded);
                }
                else if (rangeStart > DateTime.UtcNow)
                {
                    throw new Exception(Resources.JobStartTimeShouldBeLessThanCurrent);
                }

                // validate JobId and Job objects
                if (!string.IsNullOrEmpty(JobId))
                {
                    // if JobId and Job are provided together and they don't match then throw exception
                    if (Job != null && JobId != Job.JobId)
                    {
                        throw new Exception(Resources.JobJobIdAndJobMismatch);
                    }
                }
                else if (Job != null)
                {
                    JobId = Job.JobId;
                }

                List <JobBase> result = new List <JobBase>();

                WriteDebug(string.Format("Filters provided are: StartTime - {0} " +
                                         "EndTime - {1} Status - {2} Operation - {3} Type - {4}",
                                         From,
                                         To,
                                         Status,
                                         Operation,
                                         BackupManagementType));

                int resultCount = 0;

                ServiceClientModel.JobStatus?jobStatus = null;
                jobStatus = Status.HasValue ? (Status.ToEnum <ServiceClientModel.JobStatus>())
                            : default(ServiceClientModel.JobStatus?);

                var adapterResponse = ServiceClientAdapter.GetJobs(JobId,
                                                                   Status.HasValue ? Status.ToEnum <ServiceClientModel.JobStatus>() :
                                                                   default(ServiceClientModel.JobStatus?),
                                                                   Operation.ToString(),
                                                                   rangeStart,
                                                                   rangeEnd,
                                                                   ServiceClientHelpers.GetServiceClientBackupManagementType(
                                                                       BackupManagementType));

                JobConversions.AddServiceClientJobsToPSList(
                    adapterResponse, result, ref resultCount);

                WriteDebug("Number of jobs fetched: " + result.Count);
                WriteObject(result, enumerateCollection: true);
            });
        }