/// <summary>
        /// Serializes the object to JSON.
        /// </summary>
        /// <param name="writer">The <see cref="T: Newtonsoft.Json.JsonWriter" /> to write to.</param>
        /// <param name="obj">The object to serialize to JSON.</param>
        internal static void Serialize(JsonWriter writer, ApplicationUpdateDescription obj)
        {
            // Required properties are always serialized, optional properties are serialized when not null.
            writer.WriteStartObject();
            if (obj.Flags != null)
            {
                writer.WriteProperty(obj.Flags, "Flags", JsonWriterExtensions.WriteStringValue);
            }

            if (obj.RemoveApplicationCapacity != null)
            {
                writer.WriteProperty(obj.RemoveApplicationCapacity, "RemoveApplicationCapacity", JsonWriterExtensions.WriteBoolValue);
            }

            if (obj.MinimumNodes != null)
            {
                writer.WriteProperty(obj.MinimumNodes, "MinimumNodes", JsonWriterExtensions.WriteLongValue);
            }

            if (obj.MaximumNodes != null)
            {
                writer.WriteProperty(obj.MaximumNodes, "MaximumNodes", JsonWriterExtensions.WriteLongValue);
            }

            if (obj.ApplicationMetrics != null)
            {
                writer.WriteEnumerableProperty(obj.ApplicationMetrics, "ApplicationMetrics", ApplicationMetricDescriptionConverter.Serialize);
            }

            writer.WriteEndObject();
        }
        public UpdateApplicationRequest(
            IFabricClient fabricClient,
            ApplicationUpdateDescription updateDescription,
            TimeSpan timeout)
            : base(fabricClient, timeout)
        {
            ThrowIf.Null(updateDescription, "ApplicationUpdateDescription");

            this.UpdateDescription = updateDescription;

            this.ConfigureErrorCodes();
        }
Exemple #3
0
        protected void UpdateApplicationInstance(
            Uri applicationName,
            bool removeApplicationCapacity,
            long?minimumNodes,
            long?maximumNodes,
            string[] metrics)
        {
            var clusterConnection = this.GetClusterConnection();

            try
            {
                var updateDescription = new ApplicationUpdateDescription(applicationName);

                updateDescription.RemoveApplicationCapacity = removeApplicationCapacity;

                updateDescription.MinimumNodes = minimumNodes;
                updateDescription.MaximumNodes = maximumNodes;

                if (metrics != null)
                {
                    updateDescription.Metrics = new List <ApplicationMetricDescription>();
                    foreach (var scaleoutMetric in metrics)
                    {
                        updateDescription.Metrics.Add(this.ParseScaleoutMetric(scaleoutMetric));
                    }
                }

                ApplicationUpdateDescription.Validate(updateDescription);
                clusterConnection.UpdateApplicationAsync(
                    updateDescription,
                    this.GetTimeout(),
                    this.GetCancellationToken()).Wait();
                this.WriteObject(this.FormatOutput(updateDescription));
            }
            catch (ArgumentException exception)
            {
                this.ThrowTerminatingError(
                    exception,
                    Constants.UpdateApplicationInstanceErrorId,
                    clusterConnection);
            }
            catch (AggregateException aggregateException)
            {
                aggregateException.Handle((ae) =>
                {
                    this.ThrowTerminatingError(
                        ae,
                        Constants.UpdateApplicationInstanceErrorId,
                        clusterConnection);
                    return(true);
                });
            }
        }
Exemple #4
0
        /// <inheritdoc/>
        protected override void ProcessRecordInternal()
        {
            var applicationUpdateDescription = new ApplicationUpdateDescription(
                flags: this.Flags,
                removeApplicationCapacity: this.RemoveApplicationCapacity,
                minimumNodes: this.MinimumNodes,
                maximumNodes: this.MaximumNodes,
                applicationMetrics: this.ApplicationMetrics);

            this.ServiceFabricClient.Applications.UpdateApplicationAsync(
                applicationId: this.ApplicationId,
                applicationUpdateDescription: applicationUpdateDescription,
                serverTimeout: this.ServerTimeout,
                cancellationToken: this.CancellationToken).GetAwaiter().GetResult();

            Console.WriteLine("Success!");
        }
        /// <inheritdoc />
        public Task UpdateApplicationAsync(
            string applicationId,
            ApplicationUpdateDescription applicationUpdateDescription,
            long?serverTimeout = 60,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            applicationId.ThrowIfNull(nameof(applicationId));
            applicationUpdateDescription.ThrowIfNull(nameof(applicationUpdateDescription));
            serverTimeout?.ThrowIfOutOfInclusiveRange("serverTimeout", 1, 4294967295);
            var requestId = Guid.NewGuid().ToString();
            var url       = "Applications/{applicationId}/$/Update";

            url = url.Replace("{applicationId}", applicationId);
            var queryParams = new List <string>();

            // Append to queryParams if not null.
            serverTimeout?.AddToQueryParameters(queryParams, $"timeout={serverTimeout}");
            queryParams.Add("api-version=8.1");
            url += "?" + string.Join("&", queryParams);

            string content;

            using (var sw = new StringWriter())
            {
                ApplicationUpdateDescriptionConverter.Serialize(new JsonTextWriter(sw), applicationUpdateDescription);
                content = sw.ToString();
            }

            HttpRequestMessage RequestFunc()
            {
                var request = new HttpRequestMessage()
                {
                    Method  = HttpMethod.Post,
                    Content = new StringContent(content, Encoding.UTF8),
                };

                request.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
                return(request);
            }

            return(this.httpClient.SendAsync(RequestFunc, url, requestId, cancellationToken));
        }
        public override async Task UpdateAsync(IOperationDescription description, IFabricOperationResult result, IOperationContext context)
        {
            Trace.WriteInfo(TraceType, "UpdateAsync called");
            description.ThrowIfNull(nameof(description));
            result.ThrowIfNull(nameof(result));
            result.OperationStatus.ThrowIfNull(nameof(result.OperationStatus));
            result.QueryResult.ThrowIfNull(nameof(result.QueryResult));
            context.ThrowIfNull(nameof(context));

            string errorMessage;
            if (!this.ValidObjectType<ApplicationOperationDescription>(description, out errorMessage))
            {
                throw new InvalidCastException(errorMessage);
            }

            if (!this.ValidObjectType<ApplicationFabricQueryResult>(result.QueryResult, out errorMessage))
            {
                throw new InvalidCastException(errorMessage);
            }

            var appDescription = (ApplicationOperationDescription)description;
            appDescription.TypeVersion.ThrowIfNullOrWhiteSpace(nameof(appDescription.TypeVersion));
            appDescription.ApplicationUri.ThrowIfNull(nameof(appDescription.ApplicationUri));
            var appResult = (ApplicationFabricQueryResult)result.QueryResult;

            var healthPolicy = new ApplicationHealthPolicy();
            var defaultServiceTypeHealthPolicy = new ServiceTypeHealthPolicy();
            if (appDescription.UpgradePolicy?.ApplicationHealthPolicy != null)
            {
                healthPolicy.ConsiderWarningAsError =
                    appDescription.UpgradePolicy.ApplicationHealthPolicy.ConsiderWarningAsError;
                healthPolicy.MaxPercentUnhealthyDeployedApplications =
                    appDescription.UpgradePolicy.ApplicationHealthPolicy.MaxPercentUnhealthyDeployedApplications;

                if (appDescription.UpgradePolicy.ApplicationHealthPolicy.DefaultServiceTypeHealthPolicy != null)
                {
                    defaultServiceTypeHealthPolicy.MaxPercentUnhealthyPartitionsPerService =
                        appDescription.UpgradePolicy.ApplicationHealthPolicy.DefaultServiceTypeHealthPolicy
                            .MaxPercentUnhealthyPartitionsPerService;
                    defaultServiceTypeHealthPolicy.MaxPercentUnhealthyReplicasPerPartition =
                        appDescription.UpgradePolicy.ApplicationHealthPolicy.DefaultServiceTypeHealthPolicy
                            .MaxPercentUnhealthyReplicasPerPartition;
                    defaultServiceTypeHealthPolicy.MaxPercentUnhealthyServices =
                        appDescription.UpgradePolicy.ApplicationHealthPolicy.DefaultServiceTypeHealthPolicy
                            .MaxPercentUnhealthyServices;
                    healthPolicy.DefaultServiceTypeHealthPolicy = defaultServiceTypeHealthPolicy;
                }
            }

            var monitoringPolicy = new RollingUpgradeMonitoringPolicy();
            if (appDescription.UpgradePolicy?.RollingUpgradeMonitoringPolicy != null)
            {
                monitoringPolicy.FailureAction =
                    (UpgradeFailureAction) Enum.Parse(
                        typeof (UpgradeFailureAction),
                        appDescription.UpgradePolicy.RollingUpgradeMonitoringPolicy.FailureAction.ToString(),
                        true);
                monitoringPolicy.HealthCheckRetryTimeout =
                    appDescription.UpgradePolicy.RollingUpgradeMonitoringPolicy.HealthCheckRetryTimeout;
                monitoringPolicy.HealthCheckStableDuration =
                    appDescription.UpgradePolicy.RollingUpgradeMonitoringPolicy.HealthCheckStableDuration;
                monitoringPolicy.HealthCheckWaitDuration =
                    appDescription.UpgradePolicy.RollingUpgradeMonitoringPolicy.HealthCheckWaitDuration;
                monitoringPolicy.UpgradeDomainTimeout =
                    appDescription.UpgradePolicy.RollingUpgradeMonitoringPolicy.UpgradeDomainTimeout;
                monitoringPolicy.UpgradeTimeout = appDescription.UpgradePolicy.RollingUpgradeMonitoringPolicy.UpgradeTimeout;
            }

            var policyDescription = new MonitoredRollingApplicationUpgradePolicyDescription()
            {
                UpgradeMode = RollingUpgradeMode.Monitored,
                HealthPolicy = healthPolicy,
                MonitoringPolicy = monitoringPolicy
            };

            if (appDescription.UpgradePolicy != null)
            {
                if (appDescription.UpgradePolicy.ForceRestart.HasValue)
                {
                    policyDescription.ForceRestart = appDescription.UpgradePolicy.ForceRestart.Value;
                }

                if (appDescription.UpgradePolicy.UpgradeReplicaSetCheckTimeout.HasValue)
                {
                    policyDescription.UpgradeReplicaSetCheckTimeout = appDescription.UpgradePolicy.UpgradeReplicaSetCheckTimeout.Value;
                }
            }

            // Update
            var updateDescription = new ApplicationUpdateDescription(appDescription.ApplicationUri)
            {
                RemoveApplicationCapacity = appDescription.RemoveApplicationCapacity
            };

            if (appDescription.MinimumNodes.HasValue)
            {
                updateDescription.MinimumNodes = appDescription.MinimumNodes.Value;
            }

            if (appDescription.MaximumNodes.HasValue)
            {
                updateDescription.MaximumNodes = appDescription.MaximumNodes.Value;
            }

            if (appDescription.Metrics != null && appDescription.Metrics.Any())
            {
                updateDescription.Metrics = new List<ApplicationMetricDescription>();
                foreach (var metric in appDescription.Metrics)
                {
                    updateDescription.Metrics.Add(
                        new ApplicationMetricDescription()
                        {
                            Name = metric.Name,
                            MaximumNodeCapacity = metric.MaximumCapacity,
                            NodeReservationCapacity = metric.ReservationCapacity,
                            TotalApplicationCapacity = metric.TotalApplicationCapacity
                        });
                }
            }

            Trace.WriteInfo(
                TraceType,
                "UpdateAsync: Updating application. Name: {0}. Timeout: {1}",
                updateDescription.ApplicationName,
                context.OperationTimeout);
            await this.fabricClient.ApplicationManager.UpdateApplicationAsync(
                updateDescription,
                context.OperationTimeout,
                context.CancellationToken);
            Trace.WriteInfo(TraceType, "UpdateAsync: Application update call accepted");

            // Upgrade
            var upgradeDescription = new ApplicationUpgradeDescription()
            {
                ApplicationName = appDescription.ApplicationUri,
                TargetApplicationTypeVersion = appDescription.TypeVersion,
                UpgradePolicyDescription = policyDescription
            };

            if (appDescription.Parameters != null)
            {
                upgradeDescription.ApplicationParameters.Add(appDescription.Parameters.ToNameValueCollection());
            }

            try
            {
                Trace.WriteInfo(
                    TraceType,
                    "UpdateAsync: Upgrading application. Name: {0}. Version: {1}. TargetVersion: {2}. Timeout: {3}",
                    upgradeDescription.ApplicationName,
                    appResult.Application.ApplicationTypeVersion,
                    upgradeDescription.TargetApplicationTypeVersion,
                    context.OperationTimeout);
                await this.fabricClient.ApplicationManager.UpgradeApplicationAsync(
                    upgradeDescription,
                    context.OperationTimeout,
                    context.CancellationToken);
                Trace.WriteInfo(TraceType, "UpdateAsync: Application upgrade call accepted");
            }
            catch (FabricException fe)
            {
                if (fe.ErrorCode == FabricErrorCode.ApplicationAlreadyInTargetVersion)
                {
                    Trace.WriteInfo(TraceType, "UpdateAsync: Application already in target version: {0}.", upgradeDescription.TargetApplicationTypeVersion);
                    return;
                }

                if (fe.ErrorCode == FabricErrorCode.ApplicationUpgradeInProgress)
                {
                    Trace.WriteInfo(TraceType, "UpdateAsync: Application upgrade in progress with same version: {0}", upgradeDescription.TargetApplicationTypeVersion);                 
                }
                else
                {
                    Trace.WriteError(TraceType, "UpdateAsync: Application upgrade encountered an exception: {0}", fe);
                    throw;
                }                
            }
            catch (Exception e)
            {
                Trace.WriteInfo(TraceType, "UpdateAsync: Application upgrade encountered an exception: {0}", e);
                throw;
            }

            // UpgradeUpdate
            ApplicationUpgradeProgress upgradeProgress = null;
            try
            {
                upgradeProgress = await this.fabricClient.ApplicationManager.GetApplicationUpgradeProgressAsync(
                        appDescription.ApplicationUri,
                        context.OperationTimeout,
                        context.CancellationToken);
            }
            catch (Exception)
            {
                Trace.WriteWarning(
                    TraceType,
                    "UpdateAsync: Failed to get the application upgrade progress to determine the parameters for upgrade update. Need to retry the operation. Application Name: {0}",
                    appDescription.ApplicationUri);

                throw new FabricTransientException();
            }
                       
            ApplicationUpgradeUpdateDescription upgradeUpdateDescription;
            if (upgradeProgress.UpgradeState == ApplicationUpgradeState.RollingBackInProgress)
            {
                // During rollback we can only change below properties
                upgradeUpdateDescription = new ApplicationUpgradeUpdateDescription()
                {
                    ApplicationName = appDescription.ApplicationUri,
                    UpgradeReplicaSetCheckTimeout = appDescription.UpgradePolicy.UpgradeReplicaSetCheckTimeout,
                    ForceRestart = appDescription.UpgradePolicy.ForceRestart
                };
            }
            else
            {
                upgradeUpdateDescription = new ApplicationUpgradeUpdateDescription()
                {
                    ApplicationName = appDescription.ApplicationUri,
                    UpgradeDomainTimeout = monitoringPolicy.UpgradeDomainTimeout,
                    UpgradeTimeout = monitoringPolicy.UpgradeTimeout,
                    HealthCheckRetryTimeout = monitoringPolicy.HealthCheckRetryTimeout,
                    HealthCheckWaitDuration = monitoringPolicy.HealthCheckWaitDuration,
                    HealthCheckStableDuration = monitoringPolicy.HealthCheckStableDuration,
                    UpgradeReplicaSetCheckTimeout = policyDescription.UpgradeReplicaSetCheckTimeout,
                    ForceRestart = policyDescription.ForceRestart,
                    FailureAction = monitoringPolicy.FailureAction,
                    HealthPolicy = healthPolicy
                };
            }

            try
            {               

                Trace.WriteInfo(
                    TraceType,
                    "UpdateAsync: Updating application upgrade in progress. Name: {0}. Timeout: {1}",
                    upgradeUpdateDescription.ApplicationName,
                    context.OperationTimeout);
                await this.fabricClient.ApplicationManager.UpdateApplicationUpgradeAsync(
                    upgradeUpdateDescription,
                    context.OperationTimeout,
                    context.CancellationToken);
                Trace.WriteInfo(TraceType, "UpdateAsync: Update application upgrade call accepted");
            }
            catch (FabricException fe)
            {
                if (fe.ErrorCode == FabricErrorCode.ApplicationNotUpgrading)
                {
                    Trace.WriteInfo(TraceType, "UpdateAsync: No application upgrade in progress");
                    return;
                }
            }
            catch (Exception e)
            {
                Trace.WriteInfo(TraceType, "UpdateAsync: Update application upgrade encountered an exception: {0}", e);
                throw;
            }
        }