Example #1
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            var            freq     = BackupRestoreUtils.StringToFrequencyUnit(FrequencyUnit);
            BackupSchedule schedule = new BackupSchedule(
                FrequencyInterval, freq,
                KeepAtLeastOneBackup.IsPresent,
                RetentionPeriodInDays, StartTime);
            BackupRequest request = new BackupRequest()
            {
                Enabled           = true,
                StorageAccountUrl = this.StorageAccountUrl,
                BackupSchedule    = schedule,
                Databases         = this.Databases,
            };

            WebsitesClient.UpdateWebAppBackupConfiguration(ResourceGroupName, Name, Slot, request);
            var config = new AzureWebAppBackupConfiguration()
            {
                Name = this.Name,
                ResourceGroupName     = this.ResourceGroupName,
                StorageAccountUrl     = this.StorageAccountUrl,
                FrequencyInterval     = this.FrequencyInterval,
                FrequencyUnit         = this.FrequencyUnit,
                RetentionPeriodInDays = this.RetentionPeriodInDays,
                StartTime             = this.StartTime,
                KeepAtLeastOneBackup  = this.KeepAtLeastOneBackup.IsPresent,
                Databases             = this.Databases,
                Enabled = true
            };

            WriteObject(config);
        }
Example #2
0
        public bool IsToBeProcessed(BackupSchedule backupSchedule)
        {
            try
            {
                var cron           = new CronExpression(backupSchedule.Cron);
                var tenant         = TenantManager.GetTenant(backupSchedule.TenantId);
                var tenantTimeZone = tenant.TimeZone;
                var culture        = tenant.GetCulture();
                Thread.CurrentThread.CurrentCulture = culture;

                var lastBackupTime = backupSchedule.LastBackupTime.Equals(default)
        public static AzureWebAppBackupConfiguration BackupRequestToAppBackupConfiguration(BackupRequest configuration, string resourceGroupName, string name, string slot)
        {
            if (configuration == null)
            {
                return(new AzureWebAppBackupConfiguration());
            }
            BackupSchedule schedule = configuration.BackupSchedule;

            DatabaseBackupSetting[] databases = null;
            bool?enabled = configuration.Enabled;

            if (configuration.Databases != null)
            {
                databases = configuration.Databases.ToArray();
            }

            int?     frequencyInterval     = null;
            string   frequencyUnit         = null;
            int?     retentionPeriodInDays = null;
            DateTime?startTime             = null;
            bool?    keepAtLeastOneBackup  = null;

            if (schedule != null)
            {
                frequencyInterval = schedule.FrequencyInterval;
                if (schedule.FrequencyUnit != null)
                {
                    frequencyUnit = schedule.FrequencyUnit.ToString();
                }
                retentionPeriodInDays = schedule.RetentionPeriodInDays;
                startTime             = schedule.StartTime;
                keepAtLeastOneBackup  = schedule.KeepAtLeastOneBackup;
            }

            return(new AzureWebAppBackupConfiguration()
            {
                Name = name,
                ResourceGroupName = resourceGroupName,
                StorageAccountUrl = configuration.StorageAccountUrl,
                FrequencyInterval = frequencyInterval,
                FrequencyUnit = frequencyUnit,
                RetentionPeriodInDays = retentionPeriodInDays,
                StartTime = startTime,
                Databases = databases,
                KeepAtLeastOneBackup = keepAtLeastOneBackup,
                Enabled = enabled
            });
        }
Example #4
0
        public bool IsToBeProcessed(BackupSchedule backupSchedule)
        {
            try
            {
                if (BackupHelper.ExceedsMaxAvailableSize(backupSchedule.TenantId))
                {
                    throw new Exception("Backup file exceed " + backupSchedule.TenantId);
                }

                var cron           = new CronExpression(backupSchedule.Cron);
                var tenant         = TenantManager.GetTenant(backupSchedule.TenantId);
                var tenantTimeZone = tenant.TimeZone;
                var culture        = tenant.GetCulture();
                Thread.CurrentThread.CurrentCulture = culture;

                var lastBackupTime = backupSchedule.LastBackupTime.Equals(default)
Example #5
0
 public void StartScheduledBackup(BackupSchedule schedule)
 {
     lock (ProgressQueue.SynchRoot)
     {
         var item = ProgressQueue.GetItems().OfType <BackupProgressItem>().FirstOrDefault(t => t.TenantId == schedule.TenantId);
         if (item != null && item.IsCompleted)
         {
             ProgressQueue.Remove(item);
             item = null;
         }
         if (item == null)
         {
             item = FactoryProgressItem.CreateBackupProgressItem(schedule, false, TempFolder, Limit, CurrentRegion, ConfigPaths);
             ProgressQueue.Add(item);
         }
     }
 }
        /// <summary>
        /// Create Schedule for a Backup
        /// </summary>
        private BackupSchedule CreateBackupSchedule(
            string deviceName,
            string backupPolicyName,
            string name,
            RecurrenceType recurrenceType,
            DateTime startTime)
        {
            // Initialize defaults
            ScheduleStatus            scheduleStatus  = ScheduleStatus.Enabled;
            int                       recurrenceValue = 1;
            long                      retentionCount  = 1;
            List <SSModels.DayOfWeek> weeklyDays      = new List <SSModels.DayOfWeek>()
            {
                SSModels.DayOfWeek.Friday,
                SSModels.DayOfWeek.Thursday,
                SSModels.DayOfWeek.Monday
            };

            var schedule = new BackupSchedule()
            {
                BackupType         = BackupType.CloudSnapshot,
                Kind               = Kind.Series8000,
                RetentionCount     = retentionCount,
                ScheduleStatus     = scheduleStatus,
                StartTime          = startTime,
                ScheduleRecurrence = new ScheduleRecurrence(
                    recurrenceType,
                    recurrenceValue)
            };

            // Set the week days for the weekly schedule
            if (schedule.ScheduleRecurrence.RecurrenceType == RecurrenceType.Weekly)
            {
                schedule.ScheduleRecurrence.WeeklyDaysList =
                    weeklyDays.Select(d => (SSModels.DayOfWeek?)d).ToList();
            }

            return(this.Client.BackupSchedules.CreateOrUpdate(
                       deviceName.GetDoubleEncoded(),
                       backupPolicyName.GetDoubleEncoded(),
                       name.GetDoubleEncoded(),
                       schedule,
                       this.ResourceGroupName,
                       this.ManagerName));
        }
Example #7
0
        private bool CreateBackupSchedule(BackupSchedule backupSchedule)
        {
            if (CoreBaseSettings.Standalone)
            {
                TenantExtra.DemandControlPanelPermission();
            }
            var storageType   = backupSchedule.StorageType == null ? BackupStorageType.Documents : (BackupStorageType)Int32.Parse(backupSchedule.StorageType);
            var storageParams = backupSchedule.StorageParams == null ? new Dictionary <string, string>() : backupSchedule.StorageParams.ToDictionary(r => r.Key.ToString(), r => r.Value.ToString());
            var backupStored  = backupSchedule.BackupsStored == null ? 0 : Int32.Parse(backupSchedule.BackupsStored);
            var cron          = new CronParams()
            {
                Period = backupSchedule.CronParams.Period == null ? BackupPeriod.EveryDay : (BackupPeriod)Int32.Parse(backupSchedule.CronParams.Period),
                Hour   = backupSchedule.CronParams.Hour == null ? 0 : Int32.Parse(backupSchedule.CronParams.Hour),
                Day    = backupSchedule.CronParams.Day == null ? 0 : Int32.Parse(backupSchedule.CronParams.Day),
            };

            BackupHandler.CreateSchedule(storageType, storageParams, backupStored, cron, backupSchedule.BackupMail);
            return(true);
        }
        /// <summary>
        /// Helper method to create backup policy for a given set of volumes.
        /// </summary>
        private BackupPolicy CreateBackupPolicy(string deviceName, string name, IList <string> volumeIds)
        {
            var bp = new BackupPolicy()
            {
                Kind      = Kind.Series8000,
                VolumeIds = volumeIds
            };

            var backupPolicy = this.Client.BackupPolicies.CreateOrUpdate(
                deviceName.GetDoubleEncoded(),
                name.GetDoubleEncoded(),
                bp,
                this.ResourceGroupName,
                this.ManagerName);

            Assert.NotNull(backupPolicy);
            Assert.Equal(backupPolicy.SchedulesCount, 0);

            List <string> scheduleNames = new List <string>()
            {
                "schedule1",
                "schedule2",
            };

            // Create a backup schedule
            BackupSchedule bs1 = CreateBackupSchedule(deviceName, backupPolicy.Name, scheduleNames.ElementAt(0), RecurrenceType.Daily, TestConstants.Schedule1StartTime);
            BackupSchedule bs2 = CreateBackupSchedule(deviceName, backupPolicy.Name, scheduleNames.ElementAt(1), RecurrenceType.Weekly, TestConstants.Schedule2StartTime);

            //validate one of the schedules
            var schedule = this.Client.BackupSchedules.Get(
                deviceName.GetDoubleEncoded(),
                backupPolicy.Name.GetDoubleEncoded(),
                scheduleNames.First().GetDoubleEncoded(),
                this.ResourceGroupName,
                this.ManagerName);

            Assert.True(schedule != null && schedule.Name.Equals(scheduleNames.First()) &&
                        schedule.ScheduleRecurrence.RecurrenceType.Equals(RecurrenceType.Daily), "Schedule creation was not successful.");

            return(backupPolicy);
        }
Example #9
0
 public void SaveBackupSchedule(BackupSchedule schedule)
 {
     BackupContext.AddOrUpdate(r => r.Schedules, schedule);
     BackupContext.SaveChanges();
 }
        /// <summary>
        /// Creates or updates the backup schedule.
        /// </summary>
        /// <param name='deviceName'>
        /// The device name
        /// </param>
        /// <param name='backupPolicyName'>
        /// The backup policy name.
        /// </param>
        /// <param name='backupScheduleName'>
        /// The backup schedule name.
        /// </param>
        /// <param name='parameters'>
        /// The backup schedule.
        /// </param>
        /// <param name='resourceGroupName'>
        /// The resource group name
        /// </param>
        /// <param name='managerName'>
        /// The manager name
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <BackupSchedule> > BeginCreateOrUpdateWithHttpMessagesAsync(string deviceName, string backupPolicyName, string backupScheduleName, BackupSchedule parameters, string resourceGroupName, string managerName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (deviceName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "deviceName");
            }
            if (backupPolicyName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "backupPolicyName");
            }
            if (backupScheduleName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "backupScheduleName");
            }
            if (parameters == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
            }
            if (parameters != null)
            {
                parameters.Validate();
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (managerName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "managerName");
            }
            if (managerName != null)
            {
                if (managerName.Length > 50)
                {
                    throw new ValidationException(ValidationRules.MaxLength, "managerName", 50);
                }
                if (managerName.Length < 2)
                {
                    throw new ValidationException(ValidationRules.MinLength, "managerName", 2);
                }
            }
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("deviceName", deviceName);
                tracingParameters.Add("backupPolicyName", backupPolicyName);
                tracingParameters.Add("backupScheduleName", backupScheduleName);
                tracingParameters.Add("parameters", parameters);
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("managerName", managerName);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backupPolicies/{backupPolicyName}/schedules/{backupScheduleName}").ToString();

            _url = _url.Replace("{deviceName}", deviceName);
            _url = _url.Replace("{backupPolicyName}", backupPolicyName);
            _url = _url.Replace("{backupScheduleName}", backupScheduleName);
            _url = _url.Replace("{subscriptionId}", Client.SubscriptionId);
            _url = _url.Replace("{resourceGroupName}", resourceGroupName);
            _url = _url.Replace("{managerName}", managerName);
            List <string> _queryParameters = new List <string>();

            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Client.ApiVersion));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new System.Net.Http.HttpRequestMessage();

            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("PUT");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (parameters != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
                _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 202)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <BackupSchedule>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <BackupSchedule>(_responseContent, Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        /// <summary>
        /// Creates or updates the backup schedule.
        /// </summary>
        /// <param name='deviceName'>
        /// The device name
        /// </param>
        /// <param name='backupPolicyName'>
        /// The backup policy name.
        /// </param>
        /// <param name='backupScheduleName'>
        /// The backup schedule name.
        /// </param>
        /// <param name='parameters'>
        /// The backup schedule.
        /// </param>
        /// <param name='resourceGroupName'>
        /// The resource group name
        /// </param>
        /// <param name='managerName'>
        /// The manager name
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public async Task <AzureOperationResponse <BackupSchedule> > CreateOrUpdateWithHttpMessagesAsync(string deviceName, string backupPolicyName, string backupScheduleName, BackupSchedule parameters, string resourceGroupName, string managerName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Send Request
            AzureOperationResponse <BackupSchedule> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(deviceName, backupPolicyName, backupScheduleName, parameters, resourceGroupName, managerName, customHeaders, cancellationToken).ConfigureAwait(false);

            return(await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false));
        }
 /// <summary>
 /// Creates or updates the backup schedule.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='deviceName'>
 /// The device name
 /// </param>
 /// <param name='backupPolicyName'>
 /// The backup policy name.
 /// </param>
 /// <param name='backupScheduleName'>
 /// The backup schedule name.
 /// </param>
 /// <param name='parameters'>
 /// The backup schedule.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The resource group name
 /// </param>
 /// <param name='managerName'>
 /// The manager name
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <BackupSchedule> BeginCreateOrUpdateAsync(this IBackupSchedulesOperations operations, string deviceName, string backupPolicyName, string backupScheduleName, BackupSchedule parameters, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(deviceName, backupPolicyName, backupScheduleName, parameters, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Creates or updates the backup schedule.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='deviceName'>
 /// The device name
 /// </param>
 /// <param name='backupPolicyName'>
 /// The backup policy name.
 /// </param>
 /// <param name='backupScheduleName'>
 /// The backup schedule name.
 /// </param>
 /// <param name='parameters'>
 /// The backup schedule.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The resource group name
 /// </param>
 /// <param name='managerName'>
 /// The manager name
 /// </param>
 public static BackupSchedule BeginCreateOrUpdate(this IBackupSchedulesOperations operations, string deviceName, string backupPolicyName, string backupScheduleName, BackupSchedule parameters, string resourceGroupName, string managerName)
 {
     return(operations.BeginCreateOrUpdateAsync(deviceName, backupPolicyName, backupScheduleName, parameters, resourceGroupName, managerName).GetAwaiter().GetResult());
 }
Example #14
0
 public bool CreateBackupScheduleFromForm([FromForm] BackupSchedule backupSchedule)
 {
     return(CreateBackupSchedule(backupSchedule));
 }
Example #15
0
 public bool CreateBackupScheduleFromBody([FromBody] BackupSchedule backupSchedule)
 {
     return(CreateBackupSchedule(backupSchedule));
 }