示例#1
0
        public IEnumerable <CodePackageEntity> GetFaultableCodePackages()
        {
            var faultTolerantCodePackages = new List <CodePackageEntity>();

            foreach (var codePackage in this.GetAllCodePackages().Where(cp => !IsDummyCodePackage(cp)))
            {
                var node = this.Nodes.FirstOrDefault(n => n.CurrentNodeInfo.NodeName == codePackage.NodeName);
                ReleaseAssert.AssertIf(
                    node == null,
                    "Node entity {0} not found for code package {1}:{2}:{3}",
                    codePackage.NodeName,
                    codePackage.ParentApplicationEntity.Application.ApplicationName,
                    codePackage.CodePackageResult.ServiceManifestName,
                    codePackage.CodePackageResult.CodePackageName);

                if (node != null)
                {
                    bool isCodePackageFaultable =
                        this.UnsafeModeEnabled
                        ? codePackage.IsAvailableToFault
                        : !codePackage.IsUnsafeToFault;

                    if (isCodePackageFaultable)
                    {
                        faultTolerantCodePackages.Add(codePackage);
                    }
                }
            }

            return(faultTolerantCodePackages);
        }
示例#2
0
        public override ClusterState ClusterUpgradeRolledbackOrFailed()
        {
            this.TraceLogger.WriteWarning(
                TraceType,
                "ClusterUpgradeRolledbackOrFailed called for {0} initiated upgrade. TargetCsmVersion: {1}, TargetWrpVersion: {2}",
                this.IsAdminInitiatedUpgrade() ? "Admin" : "User",
                this.TargetCsmConfig.Version.Version,
                this.TargetWrpConfig.Version);

            this.ClusterResource.ClusterState = ClusterProvisioningState.Ready;

            if (this.IsAdminInitiatedUpgrade())
            {
                this.ClusterResource.TargetWrpConfigUpgradeFailed = true;
            }
            else
            {
                this.ClusterResource.TargetCsmConfigUpgradeFailed = true;

                if (this.ClusterResource.TargetWrpConfig != null &&
                    this.ClusterResource.TargetWrpConfig.IsUserSet)
                {
                    ReleaseAssert.AssertIf(
                        !this.ClusterResource.TargetWrpConfig.Equals(this.TargetWrpConfig),
                        "For UserInitiatedUpgrade TargetWrpConfig should be used if it is user set");

                    this.ClusterResource.TargetWrpConfigUpgradeFailed = true;
                }
            }

            this.OnSimpleClusterUpgradeRolledbackOrFailed();

            return(this.ClusterResource.Current);
        }
示例#3
0
        protected void GenerateAndEnqueueRandomActions(WorkloadList workloadInfo, Guid activityId = default(Guid))
        {
            this.UpdateDice(workloadInfo);
            string workloadName = this.workloadDice.NextRoll().Trim();

            ReleaseAssert.AssertIf(string.IsNullOrEmpty(workloadName), "Workload name cannot be null or empty.");

            bool isRunning = workloadInfo.GetWorkLoadState(workloadName);

            workloadInfo.FlipWorkloadState(workloadName);

            StateTransitionAction workloadScriptAction = null;

            if (isRunning)
            {
                workloadScriptAction = WorkloadStateTransitionAction.CreateStopWorkloadAction(workloadName);

                TestabilityTrace.TraceSource.WriteInfo(this.TraceType, "{0}: Workload {1} has been chosen for Stop-Workload", activityId, workloadName);
            }
            else
            {
                workloadScriptAction = WorkloadStateTransitionAction.CreateStartWorkloadAction(workloadName);

                TestabilityTrace.TraceSource.WriteInfo(this.TraceType, "{0}: Workload {1} has been chosen for Start-Workload", activityId, workloadName);
            }

            this.EnqueueAction(workloadScriptAction);
        }
示例#4
0
        /// <summary>
        /// <para>Gets the value of the property.</para>
        /// </summary>
        /// <typeparam name="T">
        /// <para>The type of the property value.</para>
        /// </typeparam>
        /// <returns>
        /// <para>The value of the property as type <typeparamref name="T"/>.</para>
        /// </returns>
        public unsafe T GetValue <T>()
        {
            ReleaseAssert.AssertIf(this.Metadata == null, StringResources.Error_MetadataNotSet);

            Type requestedType = typeof(T);

            if (requestedType != typeof(object))
            {
                if (!NamedProperty.TypeMapping.ContainsKey(requestedType))
                {
                    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, StringResources.Error_TypeNotSupported_Formatted, requestedType));
                }

                if (NamedProperty.TypeMapping[requestedType] != this.Metadata.TypeId)
                {
                    throw new InvalidOperationException(
                              string.Format(
                                  CultureInfo.CurrentCulture,
                                  StringResources.Error_PropertyTypeMismatch_Formatted,
                                  this.Metadata.TypeId,
                                  requestedType));
                }
            }

            if (!this.includesValue)
            {
                throw new FabricException(
                          StringResources.Error_EmptyProperty,
                          FabricErrorCode.PropertyValueEmpty);
            }

            return((T)this.value);
        }
        public NodeEntity GetUpNodeToFault(Guid activityId = default(Guid))
        {
            // Say, we have three node types: FrontEnd (3 nodes), Application (3 nodes), and BackEnd (5 nodes).
            // If we include only FrontEnd node type in the NodeTypeInclusionFilter
            // then 3 (this.FaultReadyLiveNodesCount) < 8 (this.MinLiveNodesCount) and no NodeRestart faults happen.
            // The leftside of the following inequality (>) should include all currently alive nodes, hence the addition of liveExcludedNodesCount.
            if (this.FaultReadyLiveNodesCount + this.LiveExcludedNodesCount > this.MinLiveNodesCount)
            {
                bool selectSeedNode = false;

                if (this.FaultReadyLiveSeedNodesCount + this.LiveExcludedSeedNodesCount > this.MinLiveSeedNodesCount)
                {
                    selectSeedNode = this.random.NextDouble() < (this.SeedNodesCount / (double)this.ClusterNodesCount);
                }

                var chosenListOfFaultReadyNodes = this.GetSortedListNodesInfo(selectSeedNode, true /*UpNodes*/).Where(kvp => kvp.Value == true /*IsAvailableToFault*/).ToList();

                if (chosenListOfFaultReadyNodes.Any())
                {
                    var chosenNode = this.GetRandomFrom(chosenListOfFaultReadyNodes);
                    ReleaseAssert.AssertIfNot(chosenNode.Value, "Should not have chosen in transition node");
                    var clusterNode = this.ClusterNodes.FirstOrDefault(n => n.CurrentNodeInfo.NodeName == chosenNode.Key);
                    ReleaseAssert.AssertIf(clusterNode == null, "Cluster node with name {0} should exist in local structure", chosenNode.Key);
                    return(clusterNode);
                }
            }

            return(null);
        }
        private bool SelectReadySecondary(ReplicaEntity replica)
        {
            var statefulReplica = replica.Replica as StatefulServiceReplica;

            ReleaseAssert.AssertIf(statefulReplica == null, "Replica type should be stateful");
            return(statefulReplica.ReplicaRole == ReplicaRole.ActiveSecondary && replica.IsAvailableToFault);
        }
        /// <summary>
        /// This is the internal launch point which FAS will call into. Depending on the situation,
        /// this function will decide if CI needs to be enabled, and if yes, will start it.
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        internal async Task InternalLaunchAsync(CancellationToken token)
        {
            if (!(await this.IsCurrentDeploymentOneboxAsync(token).ConfigureAwait(false)))
            {
                this.logger.LogMessage("Cluster Analysis can only be Enabled in One box Environment. Skipping Cluster Analysis Launch");
                return;
            }

            // Get current status.
            var persistedStatus = await this.GetCurrentStatusAsync(token).ConfigureAwait(false);

            if (persistedStatus.UserDesiredState == FeatureState.Stopped)
            {
                this.logger.LogMessage("User Desired State is Stopped. Skipping Cluster Analysis Launch");
                return;
            }

            // Get the config from our store.
            var persistedConfig = await this.GetCurrentConfigurationAsync(token).ConfigureAwait(false);

            ReleaseAssert.AssertIf(persistedStatus.UserDesiredState == FeatureState.Running && persistedConfig == null, "Invalid State. When Desired State == Running, Config can't be null");

            if (persistedConfig == null)
            {
                this.logger.LogMessage("No Stored Config. Using Auto start default configs to Launch CI");
                persistedConfig = this.GetAutoStartLaunchConfig();
            }

            this.logger.LogMessage("Launching Cluster Analysis with Config: {0}", persistedConfig);
            await this.StartClusterAnalysisInternalAsync(endUserCall : false, configuration : persistedConfig, token : token).ConfigureAwait(false);
        }
        private static void InitializeFabricAssemblies()
        {
            fabricAssemblies = new HashSet <string>();

            HashSet <string> featureNames = new HashSet <string>(new string[] { "WinFabCommonBinaries", "WinFabRuntime" });

            foreach (var entry in ArtifactsSpecificationDescription.Entries)
            {
                if (!featureNames.Contains(entry.Feature, StringComparer.OrdinalIgnoreCase))
                {
                    continue;
                }

                if (!entry.FileName.EndsWith("dll", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                // We need to consider only native dlls
                if (entry.SigningCertificateType == ArtifactsSpecificationDescription.SigningCertificateType.Native)
                {
                    fabricAssemblies.Add(entry.FileName);
                }
            }

            ReleaseAssert.AssertIf(fabricAssemblies.Count() == 0, "FabricAssemblies count read from ArtifactsSpecification.csv cannot be 0.");
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            ResourceId resourceId = value as ResourceId;

            ReleaseAssert.AssertIf(resourceId == null, "This converter should be called only for ResourceId");

            writer.WriteValue(resourceId.ToStringOriginal());
        }
示例#10
0
        internal static async Task <bool> IsUriReachableAsync(
            Uri uri,
            string requestMethod     = DMConstants.HttpMethodHead,
            int operationTimeoutInMs = DMConstants.UriReachableTimeoutInMs,
            int requestTimeoutInMs   = DMConstants.UriRequestTimeoutInMs,
            int retryIntervalInMs    = DMConstants.UriReachableRetryIntervalInMs)
        {
            ReleaseAssert.AssertIf(uri == null, "uri cannot be null for IsUriReachableAsync.");
            if (uri.IsFile)
            {
                FileInfo fi = new FileInfo(uri.LocalPath);
                return(fi.Exists);
            }
            else
            {
                if (string.IsNullOrWhiteSpace(uri.Host))
                {
                    return(false);
                }

                var timeout = new System.Fabric.Common.TimeoutHelper(TimeSpan.FromMilliseconds(operationTimeoutInMs));
                while (!System.Fabric.Common.TimeoutHelper.HasExpired(timeout))
                {
                    WebRequest request = WebRequest.Create(uri);
#if !DotNetCoreClrLinux
                    request.Timeout = requestTimeoutInMs;
#endif
                    request.Method = requestMethod;
                    try
                    {
                        using (WebResponse response = await request.GetResponseAsync().ConfigureAwait(false))
                        {
                            if (response is HttpWebResponse)
                            {
                                if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
                                {
                                    return(true);
                                }

                                return(false);
                            }
                            else
                            {
                                return(response.ContentLength > 0);
                            }
                        }
                    }
                    catch (WebException ex)
                    {
                        SFDeployerTrace.WriteNoise(StringResources.Error_SFUriUnreachable_Formatted, uri, ex.Message);
                    }

                    System.Threading.Thread.Sleep(retryIntervalInMs);
                }
            }

            return(false);
        }
示例#11
0
 /// <summary>
 /// Selected partition constructor
 /// </summary>
 /// <param name="serviceName">Service name URI</param>
 /// <param name="partitionId">Partition id</param>
 internal SelectedPartition(Uri serviceName, Guid partitionId)
 {
     ReleaseAssert.AssertIf(
         ((serviceName != null && partitionId == Guid.Empty) ||
          (serviceName == null && partitionId != Guid.Empty)),
         "Both should be null or neither");
     this.ServiceName = serviceName;
     this.PartitionId = partitionId;
 }
示例#12
0
        /// <summary>
        /// Move secondary replica result constructor.
        /// </summary>
        /// <param name="currentSecondaryNodeName">Current node name where secodary replica exist.</param>
        /// <param name="newSecondaryNodeName">New node name where secondary replica need to move.</param>
        /// <param name="selectedPartition">Selected partion result object</param>
        internal MoveSecondaryResult(string currentSecondaryNodeName, string newSecondaryNodeName, SelectedPartition selectedPartition)
        {
            ReleaseAssert.AssertIf(string.IsNullOrEmpty(currentSecondaryNodeName), "Current secondary node name cannot be null or empty");

            this.CurrentSecondaryNodeName = currentSecondaryNodeName;
            this.NewSecondaryNodeName     = newSecondaryNodeName;
            ReleaseAssert.AssertIfNull(selectedPartition, "Selected partition cannot be null");
            this.SelectedPartition = selectedPartition;
        }
示例#13
0
        /// <summary>
        /// Selected replica constructor
        /// </summary>
        /// <param name="replicaOrInstanceId">Replica or instance id</param>
        /// <param name="partitionSelectorResult">Partition selector result</param>
        internal SelectedReplica(long replicaOrInstanceId, SelectedPartition partitionSelectorResult)
        {
            ReleaseAssert.AssertIf(
                ((replicaOrInstanceId != 0 && partitionSelectorResult == SelectedPartition.None) ||
                 (replicaOrInstanceId == 0 && partitionSelectorResult != SelectedPartition.None)),
                "Both should be null or neither");

            this.SelectedPartition   = partitionSelectorResult;
            this.ReplicaOrInstanceId = replicaOrInstanceId;
        }
        private unsafe void FromNative(IntPtr nativeSettingsPtr)
        {
            ReleaseAssert.AssertIf(nativeSettingsPtr == IntPtr.Zero, string.Format(CultureInfo.CurrentCulture, StringResources.Error_NativeDataNull_Formatted, "nativeSettingsPtr"));

            var nativeSettings = (NativeTypes.FABRIC_KEY_VALUE_STORE_REPLICA_SETTINGS_V2 *)nativeSettingsPtr;

            this.WorkingDirectory          = NativeTypes.FromNativeString(nativeSettings->WorkingDirectory);
            this.SharedLogSettings         = new SharedLogSettings(nativeSettings->SharedLogSettings);
            this.SecondaryNotificationMode = (KeyValueStoreReplica.SecondaryNotificationMode)nativeSettings->SecondaryNotificationMode;
        }
示例#15
0
        public StepBase(FabricClient fabricClient, ActionStateBase stepState, TimeSpan requestTimeout, TimeSpan operationTimeout)
        {
            ReleaseAssert.AssertIf(fabricClient == null, "fabricClient should not be null");
            ReleaseAssert.AssertIf(stepState == null, "'stepState' should not be null");

            this.FabricClient     = fabricClient;
            this.State            = stepState;
            this.RequestTimeout   = requestTimeout;
            this.OperationTimeout = operationTimeout;
        }
        private static SystemFabricClient GetSystemFabricClient(IFabricTestabilityClient client)
        {
            var fabricClientHelper = client as FabricClientHelper;

            ReleaseAssert.AssertIf(fabricClientHelper == null, "Unexpected type for IFabricTestabilityClient: {0}", client.GetType());
            var systemFabricCient = fabricClientHelper.GetFabricClientObject(FabricClientTypes.System) as SystemFabricClient;

            ReleaseAssert.AssertIf(systemFabricCient == null, "Unexpected type for FabricClientObject: {0}", systemFabricCient.GetType());
            return(systemFabricCient);
        }
示例#17
0
        public FabricValidatorBlackbird(ClusterManifestType clusterManifest, List <InfrastructureNodeType> infrastructureInformation, WindowsFabricSettings windowsFabricSettings)
            : base(clusterManifest, infrastructureInformation, windowsFabricSettings)
        {
            ReleaseAssert.AssertIf(clusterManifest == null, "clusterManifest should be non-null");

            ReleaseAssert.AssertIfNot(
                clusterManifest.Infrastructure.Item is ClusterManifestTypeInfrastructureBlackbird,
                "Only ClusterManifestTypeInfrastructureBlackbird is supported by ServerDeployer");

            this.IsScaleMin = infrastructureInformation != null && FabricValidatorUtility.IsNodeListScaleMin(this.infrastructureInformation);
        }
示例#18
0
        internal static unsafe ClusterHealthChunk FromNativeResult(NativeClient.IFabricGetClusterHealthChunkResult nativeResult)
        {
            var nativePtr = nativeResult.get_ClusterHealthChunk();

            ReleaseAssert.AssertIf(nativePtr == IntPtr.Zero, string.Format(CultureInfo.CurrentCulture, StringResources.Error_NativeDataNull_Formatted, "ClusterHealthChunk"));

            var retval = FromNative(*(NativeTypes.FABRIC_CLUSTER_HEALTH_CHUNK *)nativePtr);

            GC.KeepAlive(nativeResult);
            return(retval);
        }
示例#19
0
        internal static unsafe DeployedServicePackageHealth FromNativeResult(NativeClient.IFabricDeployedServicePackageHealthResult nativeResult)
        {
            var nativePtr = nativeResult.get_DeployedServicePackageHealth();

            ReleaseAssert.AssertIf(nativePtr == IntPtr.Zero, string.Format(CultureInfo.CurrentCulture, StringResources.Error_NativeDataNull_Formatted, "DeployedServicePackageHealth"));

            var retval = FromNative((NativeTypes.FABRIC_DEPLOYED_SERVICE_PACKAGE_HEALTH *)nativePtr);

            GC.KeepAlive(nativeResult);
            return(retval);
        }
示例#20
0
        internal static unsafe ReplicaHealth FromNativeResult(NativeClient.IFabricReplicaHealthResult nativeResult)
        {
            var nativePtr = nativeResult.get_ReplicaHealth();

            ReleaseAssert.AssertIf(nativePtr == IntPtr.Zero, string.Format(CultureInfo.CurrentCulture, StringResources.Error_NativeDataNull_Formatted, "ReplicaHealth"));

            var retval = FromNative((NativeTypes.FABRIC_REPLICA_HEALTH *)nativePtr);

            GC.KeepAlive(nativeResult);
            return(retval);
        }
        public FabricValidatorServer(ClusterManifestType clusterManifest, List <InfrastructureNodeType> infrastructureInformation, WindowsFabricSettings windowsFabricSettings)
            : base(clusterManifest, infrastructureInformation, windowsFabricSettings)
        {
            ReleaseAssert.AssertIf(clusterManifest == null, "clusterManifest should be non-null");
#if DotNetCoreClrLinux
            var infrastructure = clusterManifest.Infrastructure.Item as ClusterManifestTypeInfrastructureLinux;
#else
            var infrastructure = clusterManifest.Infrastructure.Item as ClusterManifestTypeInfrastructureWindowsServer;
#endif
            ReleaseAssert.AssertIf(infrastructure == null, "Invalid infrastructure item type {0}", clusterManifest.Infrastructure.Item.GetType());
            this.IsScaleMin = infrastructure.IsScaleMin;
        }
示例#22
0
        internal static unsafe SystemApplicationHealthEvaluation FromNative(IntPtr nativeHealthEvaluationValuePtr)
        {
            ReleaseAssert.AssertIf(nativeHealthEvaluationValuePtr == IntPtr.Zero, string.Format(CultureInfo.CurrentCulture, StringResources.Error_NativeDataNull_Formatted, "nativeHealthEvaluationValue"));
            var nativeHealthEvaluation = *(NativeTypes.FABRIC_SYSTEM_APPLICATION_HEALTH_EVALUATION *)nativeHealthEvaluationValuePtr;

            var managedHealthEvaluation = new SystemApplicationHealthEvaluation();

            managedHealthEvaluation.Description           = NativeTypes.FromNativeString(nativeHealthEvaluation.Description);
            managedHealthEvaluation.AggregatedHealthState = (HealthState)nativeHealthEvaluation.AggregatedHealthState;
            managedHealthEvaluation.UnhealthyEvaluations  = HealthEvaluation.FromNativeList(nativeHealthEvaluation.UnhealthyEvaluations);

            return(managedHealthEvaluation);
        }
        private unsafe void FromNative(IntPtr nativeSettingsPtr)
        {
            ReleaseAssert.AssertIf(nativeSettingsPtr == IntPtr.Zero, string.Format(CultureInfo.CurrentCulture, StringResources.Error_NativeDataNull_Formatted, "nativeSettingsPtr"));

            var nativeSettings = (NativeTypes.KTLLOGGER_SHARED_LOG_SETTINGS *)nativeSettingsPtr;

            this.ContainerPath        = NativeTypes.FromNativeString(nativeSettings->ContainerPath);
            this.ContainerId          = new Guid(NativeTypes.FromNativeString(nativeSettings->ContainerId));
            this.LogSizeInBytes       = nativeSettings->LogSize;
            this.MaximumNumberStreams = nativeSettings->MaximumNumberStreams;
            this.MaximumRecordSize    = nativeSettings->MaximumRecordSize;
            this.CreateFlags          = nativeSettings->CreateFlags;
        }
        internal static unsafe DeployedServicePackagesHealthEvaluation FromNative(IntPtr nativeHealthEvaluationValuePtr)
        {
            ReleaseAssert.AssertIf(nativeHealthEvaluationValuePtr == IntPtr.Zero, string.Format(CultureInfo.CurrentCulture, StringResources.Error_NativeDataNull_Formatted, "nativeHealthEvaluationValue"));
            var nativeHealthEvaluation = *(NativeTypes.FABRIC_DEPLOYED_SERVICE_PACKAGES_HEALTH_EVALUATION *)nativeHealthEvaluationValuePtr;

            var managedHealthEvaluation = new DeployedServicePackagesHealthEvaluation();

            managedHealthEvaluation.Description           = NativeTypes.FromNativeString(nativeHealthEvaluation.Description);
            managedHealthEvaluation.AggregatedHealthState = (HealthState)nativeHealthEvaluation.AggregatedHealthState;
            managedHealthEvaluation.UnhealthyEvaluations  = HealthEvaluation.FromNativeList(nativeHealthEvaluation.UnhealthyEvaluations);
            managedHealthEvaluation.TotalCount            = (long)nativeHealthEvaluation.TotalCount;

            return(managedHealthEvaluation);
        }
示例#25
0
        static double GetRuntimeVersion()
        {
            var currentVersion = FabricRuntime.FabricRuntimeFactory.GetCurrentRuntimeVersion();

            ReleaseAssert.AssertIf(String.IsNullOrEmpty(currentVersion), "Runtime version fetched is empty or null");

            var splitVersions = currentVersion.Split('.');

            ReleaseAssert.AssertIf(splitVersions.Length < 2, "Runtime version fetched incorrectly");

            var majorMinorVersion = splitVersions[0] + "." + splitVersions[1];

            return(Double.Parse(majorMinorVersion, CultureInfo.InvariantCulture));
        }
示例#26
0
        public FabricValidator(ClusterManifestType clusterManifest, List <InfrastructureNodeType> infrastructureInformation, WindowsFabricSettings windowsFabricSettings)
        {
            ReleaseAssert.AssertIf(clusterManifest == null, "clusterManifest should be non-null");
            this.clusterManifest           = clusterManifest;
            this.infrastructureInformation = infrastructureInformation;
            this.StoreName = windowsFabricSettings.StoreName;
            this.DoMachineAndNodeHaveSameIPInScaleMin = true;
            this.IsSingleMachineDeployment            = true;

            this.fabricSettingsValidator = new FabricSettingsValidator(
                windowsFabricSettings,
                clusterManifest,
                this.infrastructureInformation);
        }
        public IEnumerable <Task> StartProcessing(CancellationToken token)
        {
            Trace.WriteInfo(TraceType, "StartProcessing called");

            ReleaseAssert.AssertIf(
                this.streamingTask != null && !this.streamingTask.IsCompleted,
                "StartProcessing should be called only once");

            this.streamingTask = this.RunStreamChannelAsync(token);

            return(new List <Task>()
            {
                this.streamingTask
            });
        }
        internal static unsafe NodesHealthEvaluation FromNative(IntPtr nativeHealthEvaluationValuePtr)
        {
            ReleaseAssert.AssertIf(nativeHealthEvaluationValuePtr == IntPtr.Zero, string.Format(CultureInfo.CurrentCulture, StringResources.Error_NativeDataNull_Formatted, "nativeHealthEvaluationValue"));
            var nativeHealthEvaluation = *(NativeTypes.FABRIC_NODES_HEALTH_EVALUATION *)nativeHealthEvaluationValuePtr;

            var managedHealthEvaluation = new NodesHealthEvaluation();

            managedHealthEvaluation.Description              = NativeTypes.FromNativeString(nativeHealthEvaluation.Description);
            managedHealthEvaluation.AggregatedHealthState    = (HealthState)nativeHealthEvaluation.AggregatedHealthState;
            managedHealthEvaluation.UnhealthyEvaluations     = HealthEvaluation.FromNativeList(nativeHealthEvaluation.UnhealthyEvaluations);
            managedHealthEvaluation.TotalCount               = (long)nativeHealthEvaluation.TotalCount;
            managedHealthEvaluation.MaxPercentUnhealthyNodes = nativeHealthEvaluation.MaxPercentUnhealthyNodes;

            return(managedHealthEvaluation);
        }
        private unsafe void FromNative(IntPtr nativeSettingsPtr)
        {
            ReleaseAssert.AssertIf(nativeSettingsPtr == IntPtr.Zero, string.Format(CultureInfo.CurrentCulture, StringResources.Error_NativeDataNull_Formatted, "nativeSettingsPtr"));

            var nativeSettings = (NativeTypes.FABRIC_CLIENT_SETTINGS *)nativeSettingsPtr;

            this.PartitionLocationCacheLimit     = (long)nativeSettings->PartitionLocationCacheLimit;
            this.ServiceChangePollInterval       = TimeSpan.FromSeconds((double)nativeSettings->ServiceChangePollIntervalInSeconds);
            this.ConnectionInitializationTimeout = TimeSpan.FromSeconds((double)nativeSettings->ConnectionInitializationTimeoutInSeconds);
            this.KeepAliveInterval        = TimeSpan.FromSeconds((double)nativeSettings->KeepAliveIntervalInSeconds);
            this.HealthOperationTimeout   = TimeSpan.FromSeconds((double)nativeSettings->HealthOperationTimeoutInSeconds);
            this.HealthReportSendInterval = TimeSpan.FromSeconds((double)nativeSettings->HealthReportSendIntervalInSeconds);

            if (nativeSettings->Reserved != IntPtr.Zero)
            {
                var castedEx1 = (NativeTypes.FABRIC_CLIENT_SETTINGS_EX1 *)nativeSettings->Reserved;

                if (castedEx1->ClientFriendlyName != IntPtr.Zero)
                {
                    this.ClientFriendlyName = NativeTypes.FromNativeString(castedEx1->ClientFriendlyName);
                }

                this.PartitionLocationCacheBucketCount = castedEx1->PartitionLocationCacheBucketCount;
                this.HealthReportRetrySendInterval     = TimeSpan.FromSeconds((double)castedEx1->HealthReportRetrySendIntervalInSeconds);

                if (castedEx1->Reserved != IntPtr.Zero)
                {
                    var castedEx2 = (NativeTypes.FABRIC_CLIENT_SETTINGS_EX2 *)castedEx1->Reserved;

                    this.NotificationGatewayConnectionTimeout = TimeSpan.FromSeconds((double)castedEx2->NotificationGatewayConnectionTimeoutInSeconds);
                    this.NotificationCacheUpdateTimeout       = TimeSpan.FromSeconds((double)castedEx2->NotificationCacheUpdateTimeoutInSeconds);

                    if (castedEx2->Reserved != IntPtr.Zero)
                    {
                        var castedEx3 = (NativeTypes.FABRIC_CLIENT_SETTINGS_EX3 *)castedEx2->Reserved;

                        this.AuthTokenBufferSize = castedEx3->AuthTokenBufferSize;

                        if (castedEx3->Reserved != IntPtr.Zero)
                        {
                            var castedEx4 = (NativeTypes.FABRIC_CLIENT_SETTINGS_EX4 *)castedEx3->Reserved;

                            this.ConnectionIdleTimeout = TimeSpan.FromSeconds((double)castedEx4->ConnectionIdleTimeoutInSeconds);
                        }
                    }
                }
            }
        }
        internal static unsafe UpgradeDomainDeployedApplicationsHealthEvaluation FromNative(IntPtr nativeHealthEvaluationValuePtr)
        {
            ReleaseAssert.AssertIf(nativeHealthEvaluationValuePtr == IntPtr.Zero, string.Format(CultureInfo.CurrentCulture, StringResources.Error_NativeDataNull_Formatted, "nativeHealthEvaluationValue"));
            var nativeHealthEvaluation = *(NativeTypes.FABRIC_UPGRADE_DOMAIN_DEPLOYED_APPLICATIONS_HEALTH_EVALUATION *)nativeHealthEvaluationValuePtr;

            var managedHealthEvaluation = new UpgradeDomainDeployedApplicationsHealthEvaluation();

            managedHealthEvaluation.Description           = NativeTypes.FromNativeString(nativeHealthEvaluation.Description);
            managedHealthEvaluation.AggregatedHealthState = (HealthState)nativeHealthEvaluation.AggregatedHealthState;
            managedHealthEvaluation.UpgradeDomainName     = NativeTypes.FromNativeString(nativeHealthEvaluation.UpgradeDomainName);
            managedHealthEvaluation.UnhealthyEvaluations  = HealthEvaluation.FromNativeList(nativeHealthEvaluation.UnhealthyEvaluations);
            managedHealthEvaluation.TotalCount            = (long)nativeHealthEvaluation.TotalCount;
            managedHealthEvaluation.MaxPercentUnhealthyDeployedApplications = nativeHealthEvaluation.MaxPercentUnhealthyDeployedApplications;

            return(managedHealthEvaluation);
        }