Ejemplo n.º 1
0
        private static StatefulServiceBase ReadConfiguration(StatefulServiceContext context)
        {
            var configStore = NativeConfigStore.FabricGetConfigStore();
            var backupRestoreServiceReplicatorAddress = configStore.ReadUnencryptedString("FabricNode", "BackupRestoreServiceReplicatorAddress");

            return(new BackupRestoreService(context, backupRestoreServiceReplicatorAddress));
        }
Ejemplo n.º 2
0
        private SecuritySetting()
        {
            this.configStore = NativeConfigStore.FabricGetConfigStore(this);
            string         serverAuthCredentialTypeName = configStore.ReadUnencryptedString(SecurityConfigSectionName, ServerAuthCredentialTypeName);
            CredentialType serverAuthCredentialType     = CredentialType.None;

            if ((!string.IsNullOrEmpty(serverAuthCredentialTypeName)) &&
                (!Enum.TryParse <CredentialType>(serverAuthCredentialTypeName, out serverAuthCredentialType)))
            {
                EventStoreLogger.Logger.LogWarning(
                    "Unable to convert configuration value serverAuthCredentialTypeName {0} for {1} type.",
                    serverAuthCredentialTypeName,
                    serverAuthCredentialType);
            }

            this.ServerAuthCredentialType = serverAuthCredentialType;
            if (ServerAuthCredentialType == CredentialType.X509)
            {
                this.EndpointProtocol = EndpointProtocol.Https;
            }
            else
            {
                this.EndpointProtocol = EndpointProtocol.Http;
            }

            this.AllowedClientCertThumbprints = null;
            this.AllowedClientIdentities      = null;
            this.AllowedClientCertCommonNames = null;

            this.InitializeFromConfig();
        }
Ejemplo n.º 3
0
        public AADSettings()
        {
            this.configValuesLock  = new RwLock();
            this.nativeConfigStore = NativeConfigStore.FabricGetConfigStore(this);

            this.LoadGlobalDefaultSettings();
        }
Ejemplo n.º 4
0
        private bool IsPackageNearExpiry(PackageDetails currentPackage)
        {
            bool isNearExpiry             = false;
            NativeConfigStore configStore = NativeConfigStore.FabricGetConfigStore();

            string goalStateExpirationReminderInDaysString = configStore.ReadUnencryptedString(DMConstants.UpgradeOrchestrationServiceConfigSectionName, DMConstants.GoalStateExpirationReminderInDays);
            uint   goalStateExpirationReminderInDays;

            if (string.IsNullOrEmpty(goalStateExpirationReminderInDaysString) || !uint.TryParse(goalStateExpirationReminderInDaysString, out goalStateExpirationReminderInDays))
            {
                this.traceSource.WriteInfo(
                    TraceType,
                    "goalStateExpirationReminderInDays value invalid: \"{0}\". Defaulting to {1}.",
                    goalStateExpirationReminderInDaysString,
                    DMConstants.DefaultGoalStateExpirationReminderInDays);
                goalStateExpirationReminderInDays = DMConstants.DefaultGoalStateExpirationReminderInDays;
            }

            if (currentPackage != null && currentPackage.SupportExpiryDate != null)
            {
                isNearExpiry = (currentPackage.SupportExpiryDate - DateTime.UtcNow).Value.TotalDays < goalStateExpirationReminderInDays;
            }

            return(isNearExpiry);
        }
Ejemplo n.º 5
0
 public EncryptionCertConfigHandler(Action <string, string, CancellationToken> encryptionCertChangeCallback,
                                    StatefulService statefulService, CancellationToken runAsyncCancellationToken)
 {
     this.updateCertCallback        = encryptionCertChangeCallback;
     this.runAsyncCancellationToken = runAsyncCancellationToken;
     this.statefulService           = statefulService;
     this.nativeConfigStore         = NativeConfigStore.FabricGetConfigStore();
 }
        public ClusterEndpointSecuritySettingsChangeNotifier(string endpoint, Action <string> updateReplicatorSettingsAction)
        {
            if (updateReplicatorSettingsAction == null)
            {
                throw new ArgumentNullException("updateReplicatorSettingsAction");
            }

            // null is allowed for endpoint
            this.endpoint = endpoint;
            this.updateReplicatorSettingsAction = updateReplicatorSettingsAction;
            this.configStore = NativeConfigStore.FabricGetConfigStore(this);
        }
        static BackupRestoreServiceConfig()
        {
            // Read value from config store
            var configStore = NativeConfigStore.FabricGetConfigStore();

            var apiTimeoutString = configStore.ReadUnencryptedString(BackupRestoreContants.BrsConfigSectionName, BackupRestoreContants.ApiTimeoutKeyName);

            ApiTimeout = String.IsNullOrEmpty(apiTimeoutString) ? BackupRestoreContants.ApiTimeoutInSecondsDefault : TimeSpan.FromSeconds(int.Parse(apiTimeoutString, CultureInfo.InvariantCulture));

            var workItemTimeoutString = configStore.ReadUnencryptedString(BackupRestoreContants.BrsConfigSectionName, WorkItemTimeoutKeyName);

            WorkItemTimeout = String.IsNullOrEmpty(workItemTimeoutString) ? DefaultWorkItemTimeout : TimeSpan.FromSeconds(int.Parse(workItemTimeoutString, CultureInfo.InvariantCulture));
        }
Ejemplo n.º 8
0
        public static void InitializeFromConfigStore(bool forceUpdate = false)
        {
            lock (SyncLock)
            {
                if (configReader != null && !forceUpdate)
                {
                    return;
                }

                configReader = new ConfigReader(NativeConfigStore.FabricGetConfigStore(UpdateHandler));
            }

            InitializeFromConfigStore(configReader);
        }
Ejemplo n.º 9
0
        private void LoadJiterConfig()
        {
            string jitterInSecondsString = null;

            try
            {
                var configStore = NativeConfigStore.FabricGetConfigStore();
                jitterInSecondsString = configStore.ReadUnencryptedString(BackupRestoreContants.BrsConfigSectionName, BackupRestoreContants.JitterInBackupsKeyName);
            }
            catch (Exception) { }

            var jitterInSeconds = String.IsNullOrEmpty(jitterInSecondsString) ? BackupRestoreContants.JitterInBackupsDefault : int.Parse(jitterInSecondsString, CultureInfo.InvariantCulture);

            this.jitter = Math.Abs(jitterInSeconds) * 1000;
        }
Ejemplo n.º 10
0
 private static void Ensure_IgnoreUpdateFailures()
 {
     if (!ignoreUpdateFailures)
     {
         lock (configLock)
         {
             if (!ignoreUpdateFailures)
             {
                 configStore = NativeConfigStore.FabricGetConfigStore();
                 configStore.IgnoreUpdateFailures = true;
                 ignoreUpdateFailures             = true;
             }
         }
     }
 }
Ejemplo n.º 11
0
        public DsmsAzureStorageHelper(string sourceLocation)
        {
            var configStore   = NativeConfigStore.FabricGetConfigStore();
            var ApServiceName = configStore.ReadUnencryptedString(BackupRestoreContants.BrsConfigSectionName, BackupRestoreContants.DsmsAutopilotServiceNameKeyName);

            if (string.IsNullOrEmpty(ApServiceName))
            {
                CredentialManagementClient.Instance.ClientInitialize();
            }
            else
            {
                CredentialManagementClient.Instance.ClientInitializeForAp(ApServiceName);
            }

            this.dsmsCredentials = DsmsStorageCredentials.GetStorageCredentials(sourceLocation);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// This is the main entry point for your service replica.
        /// This method executes when this replica of your service becomes primary and has write status.
        /// </summary>
        /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service replica.</param>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "Enter RunAsync");
            FabricEvents.Events.BackupRestoreEnabled(this.Context.TraceId);

            // TODO: Ensure that the requests dont come in before we do the necessary initializations which are being done below
            await WorkItemHandler.StartAndScheduleWorkItemHandler(this);

            BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "Registering config update handlers now");

            var configUpdateHandler = new ConfigUpdateHandler();

            configStore = NativeConfigStore.FabricGetConfigStore(configUpdateHandler);

            var certConfigHandler = new EncryptionCertConfigHandler(this.EncryptionCertUpdateCallbackAsync, this, cancellationToken);

            encryptionCertConfigStore = NativeConfigStore.FabricGetConfigStore(certConfigHandler);

            await certConfigHandler.InitializeAsync();

            Task <RetentionManager> retentionManagerTask = RetentionManager.CreateOrGetRetentionManager(this);

            BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "Config update handlers registered");

            try
            {
                while (!configUpdateHandler.ProcessRecycleRequired)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    if (this.retentionManager == null && retentionManagerTask.IsCompleted)
                    {
                        this.retentionManager = retentionManagerTask.Result;
                    }
                    await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
                }

                // Process recycle is required, throwing exception from RunAsync
                throw new Exception("Process recycle needed.");
            }
            finally
            {
                this.retentionManager?.StopRetentionManager();
                BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "Exit RunAsync");
            }
        }
Ejemplo n.º 13
0
        private void UpdateTimers()
        {
            try
            {
                NativeConfigStore configStore = NativeConfigStore.FabricGetConfigStore();

                string goalStateFetchIntervalInSecondsString = configStore.ReadUnencryptedString(DMConstants.UpgradeOrchestrationServiceConfigSectionName, DMConstants.GoalStateFetchIntervalInSecondsName);
                int    goalStateFetchIntervalInSeconds;
                if (string.IsNullOrEmpty(goalStateFetchIntervalInSecondsString) || !int.TryParse(goalStateFetchIntervalInSecondsString, out goalStateFetchIntervalInSeconds))
                {
                    this.traceSource.WriteInfo(
                        TraceType,
                        "goalStateFetchIntervalInSeconds value invalid: \"{0}\". Defaulting to {1}.",
                        goalStateFetchIntervalInSecondsString,
                        DMConstants.DefaultGoalStateFetchIntervalInSeconds);
                    goalStateFetchIntervalInSeconds = DMConstants.DefaultGoalStateFetchIntervalInSeconds;
                }

                this.timerInterval = TimeSpan.FromSeconds(goalStateFetchIntervalInSeconds);

                string   goalStateProvisioningTimeOfDayString = configStore.ReadUnencryptedString(DMConstants.UpgradeOrchestrationServiceConfigSectionName, DMConstants.GoalStateProvisioningTimeOfDayName);
                TimeSpan goalStateProvisioningTimeOfDay;
                if (string.IsNullOrEmpty(goalStateProvisioningTimeOfDayString) || !TimeSpan.TryParse(goalStateProvisioningTimeOfDayString, out goalStateProvisioningTimeOfDay))
                {
                    this.traceSource.WriteInfo(
                        TraceType,
                        "goalStateProvisioningTimeOfDay value invalid: \"{0}\". Defaulting to {1}.",
                        goalStateProvisioningTimeOfDayString,
                        DMConstants.DefaultProvisioningTimeOfDay);
                    goalStateProvisioningTimeOfDay = DMConstants.DefaultProvisioningTimeOfDay;
                }

                this.provisioningTimeOfDay = goalStateProvisioningTimeOfDay;
                this.traceSource.WriteInfo(
                    TraceType,
                    "Timers set to: TimerInterval: {0}, ProvisioningTimeOfDay: {1}.",
                    this.timerInterval.ToString(),
                    this.provisioningTimeOfDay.ToString());
            }
            catch (Exception ex)
            {
                this.traceSource.WriteError(TraceType, "UpdateTimers threw {0}", ex.ToString());
                throw;
            }
        }
Ejemplo n.º 14
0
        private bool UseClusterSecuritySettingsForReplicator(IConfigSection configSection)
        {
            NativeConfigStore configStore = NativeConfigStore.FabricGetConfigStore();

            if (EnableEndpointV2Utility.GetValue(configStore))
            {
                TraceType.WriteInfo("Using cluster security settings for replicator because cluster setting EnableEndpointV2 is true");
                return(true);
            }

            if (this.ReadFactoryConfig(configSection, "UseClusterSecuritySettingsForReplicator", false))
            {
                TraceType.WriteInfo("Using cluster security settings for replicator because UseClusterSecuritySettingsForReplicator is true");
                return(true);
            }

            return(false);
        }
Ejemplo n.º 15
0
        public static ITokenValidationProvider Create(string configSection)
        {
            var nativeConfig   = NativeConfigStore.FabricGetConfigStore(null);
            var providersValue = nativeConfig.ReadUnencryptedString(configSection, ProvidersConfigName);
            var providers      = providersValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            if (providers.Length > 1)
            {
                // TVS API currently has no way of specifying which provider should be
                // performing validation of the supplied token
                throw new FabricException(
                          "Multiple TVS validation providers not supported",
                          FabricErrorCode.InvalidConfiguration);
            }

            // DSTS is the default provider for backwards compatibility
            if (providers.Length < 1 || string.Equals(providers[0], DSTSProviderName, StringComparison.OrdinalIgnoreCase))
            {
                TokenValidationServiceFactory.TraceSource.WriteInfo(
                    TraceType,
                    "Creating {0} provider",
                    DSTSProviderName);

                return(new DSTSValidationProvider(configSection));
            }
            else if (string.Equals(providers[0], AADProviderName, StringComparison.OrdinalIgnoreCase))
            {
                TokenValidationServiceFactory.TraceSource.WriteInfo(
                    TraceType,
                    "Creating {0} provider",
                    AADProviderName);

                return(new AADValidationProvider(configSection));
            }
            else
            {
                throw new FabricException(string.Format(CultureInfo.InvariantCulture,
                                                        "Invalid TVS provider '{0}'. Valid providers are '{1}' and '{2}'",
                                                        providers[0],
                                                        DSTSProviderName,
                                                        AADProviderName),
                                          FabricErrorCode.InvalidConfiguration);
            }
        }
Ejemplo n.º 16
0
        public DSTSObjectManager(string configSection)
        {
            this.configSection     = configSection;
            this.reloadLock        = new ReaderWriterLockSlim();
            this.configStore       = NativeConfigStore.FabricGetConfigStore(this);
            this.claimsAuthEnabled = false;

            try
            {
                this.InitializeDSTSObjects();
            }
            catch (Exception e)
            {
                TokenValidationServiceFactory.TraceSource.WriteError(DSTSObjectManager.TraceType,
                                                                     "Failed to update DSTSObjects due to exception {0}, {1}",
                                                                     e.GetType(),
                                                                     e.Message);
                throw;
            }
        }
Ejemplo n.º 17
0
        public static void Main(string[] args)
        {
#if !DotNetCoreClr
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
#endif

            using (FabricRuntime fabricRuntime = FabricRuntime.Create())
            {
                ServiceRuntime.RegisterServiceAsync("EventStoreServiceType", context =>
                                                    new EventStoreService(
                                                        context,
                                                        NativeConfigStore.FabricGetConfigStore().ReadUnencryptedString(
                                                            "FabricNode",
                                                            "EventStoreServiceReplicatorAddress")))
                .GetAwaiter()
                .GetResult();

                Thread.Sleep(Timeout.Infinite);
            }
        }
Ejemplo n.º 18
0
        public static ServiceFactory CreateAndRegister()
        {
            try
            {
                IInfrastructureAgentWrapper agent = new InfrastructureAgentWrapper();

                var configUpdateHandler       = new FactoryConfigUpdateHandler();
                NativeConfigStore configStore = NativeConfigStore.FabricGetConfigStore(configUpdateHandler);

                ServiceFactory factory = new ServiceFactory(agent, configStore, null, configUpdateHandler);

                agent.RegisterInfrastructureServiceFactory(factory);

                return(factory);
            }
            catch (Exception ex)
            {
                TraceType.WriteError("Error registering infrastructure service factory. Cannot continue further. Exception: {0}", ex);
                throw;
            }
        }
Ejemplo n.º 19
0
        internal static string GetGoalStateUri()
        {
            string goalStateUriStr = null;

            /* Test code relies on the settings present in ClusterSettings.json for deployment of a specific version.
             * We need this check for the test code because certain APIs will be invoked before the cluster is even up. */
            string clusterSettingsFilepath = StandaloneUtility.FindFabricResourceFile(DMConstants.ClusterSettingsFileName);

            if (!string.IsNullOrEmpty(clusterSettingsFilepath))
            {
                StandAloneClusterManifestSettings standAloneClusterManifestSettings = JsonConvert.DeserializeObject <StandAloneClusterManifestSettings>(File.ReadAllText(clusterSettingsFilepath));
                if (standAloneClusterManifestSettings.CommonClusterSettings != null && standAloneClusterManifestSettings.CommonClusterSettings.Section != null)
                {
                    SettingsTypeSection settings = standAloneClusterManifestSettings.CommonClusterSettings.Section.ToList().SingleOrDefault(
                        section => section.Name == DMConstants.UpgradeOrchestrationServiceConfigSectionName);
                    if (settings != null)
                    {
                        SettingsTypeSectionParameter goalStatePathParam = settings.Parameter.ToList().SingleOrDefault(param => param.Name == DMConstants.GoalStateFileUrlName);
                        if (goalStatePathParam != null)
                        {
                            goalStateUriStr = goalStatePathParam.Value;
                        }
                    }
                }
            }

            // Check the native config store before using default location. The GoalStateFileUrl may have been overridden by the user.
            if (string.IsNullOrEmpty(goalStateUriStr))
            {
                NativeConfigStore configStore = NativeConfigStore.FabricGetConfigStore();
                goalStateUriStr = configStore.ReadUnencryptedString(DMConstants.UpgradeOrchestrationServiceConfigSectionName, DMConstants.GoalStateFileUrlName);
            }

            if (string.IsNullOrEmpty(goalStateUriStr))
            {
                goalStateUriStr = DMConstants.DefaultGoalStateFileUrl;
            }

            return(goalStateUriStr);
        }
        private UpgradeSystemService(
            string workingDirectory,
            Guid partitionId)
            : base(
                workingDirectory,     // (V2 only)
                DatabaseSubDirectory, // (V2 only)
                DatabaseFileName,     // (both V1 and V2)
                partitionId)          // shared log ID (V2 only)
        {
            this.cancellationTokenSource = null;

            this.configStore      = NativeConfigStore.FabricGetConfigStore();
            this.enableEndpointV2 = EnableEndpointV2Utility.GetValue(configStore);

            this.replicatorAddress = GetReplicatorAddress();
            Trace.WriteInfo(TraceType, "Read UpgradeServiceReplicatorAddress={0}", this.replicatorAddress);

            if (this.enableEndpointV2)
            {
                this.clusterEndpointSecuritySettingsChangeNotifier = new ClusterEndpointSecuritySettingsChangeNotifier(
                    this.replicatorAddress,
                    this.UpdateReplicatorSettingsOnConfigChange);
            }
        }
Ejemplo n.º 21
0
 internal static void InitializeConfigStore()
 {
     configStore = NativeConfigStore.FabricGetConfigStore();
     return;
 }
Ejemplo n.º 22
0
 static ClusterSettingsReader()
 {
     configStore = NativeConfigStore.FabricGetConfigStore();
 }
        private bool IsSkipInitialGoalStateCheck()
        {
            NativeConfigStore configStore = NativeConfigStore.FabricGetConfigStore();

            return(configStore.ReadUnencryptedBool(Constants.SectionName, Constants.SkipInitialGoalStateCheckProperty, UpgradeOrchestrationTrace.TraceSource, TraceType, false /*throwIfInvalid*/));
        }
Ejemplo n.º 24
0
        /// return 0 if program completes successfully, -1 otherwise.
        public static int Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("This is for internal use only");
                return(-1);
            }

#if DEBUG
            // To add a sleep time while debugging add a "Sleep" key (in milliseconds) to the following registry location:  HKLM\\Software\\Microsoft\\Service Fabric
            try
            {
                using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(FabricConstants.FabricRegistryKeyPath, true))
                {
                    var sleepRegVal = registryKey.GetValue("Sleep");

                    if (sleepRegVal != null)
                    {
                        int sleepinms = int.Parse(sleepRegVal.ToString());
                        ImageBuilderExe.TraceSource.WriteNoise(ImageBuilderExe.TraceType, "ImageBuilderExe: Sleep time requested: {0}", sleepinms.ToString());

                        Thread.Sleep(sleepinms);
                    }
                }
            }
            catch (Exception e)
            {
                ImageBuilderExe.TraceSource.WriteNoise(ImageBuilderExe.TraceType, "ImageBuilderExe: Exception code:{0}, msg:{1} when attempting to read registry value \"Sleep\" in {2}.", e.HResult, e.Message, FabricConstants.FabricRegistryKeyPath);
            }
#endif

            // Parameters
            // /schemaPath:<The xsd schema file of Windows Fabric ServiceModel> - optional. Default: <Current Working Directory>\ServiceFabricServiceModel.xsd
            // /workingDir:<The root of working directory of the node> - optional. Default: <Current Working Directory>
            // /storeRoot:<The root path of ImageStore> - optional
            // /output: <The root folder|file where output will be placed> - required
            // /input: <The root folder|file where input will be read from> - required for Delete
            // /progress: <The file where operation progress will be read from> - optional. Used by BuildApplicationType and DownloadAndBuildApplicationType.
            // /operation:<BuildApplicationTypeInfo | BuildApplicationType | BuildApplication | BuildComposeDeployment | ValidateComposeDeployment | UpgradeApplication | GetFabricVersion | ProvisionFabric | UpgradeFabric | Delete | TestErrorDetails | DownloadAndBuildApplicationType> - required
            // /timeout:<ticks> - optional

            /* ImageBuilder arguments for DownloadAndBuildApplicationType */
            // /downloadPath: <path to .sfpkg file from a store that supports GET method> - required
            // /appTypeName:<Application Type Name> - required. Expected application type name in the downloaded package.
            // /appTypeVersion:<Application Type Version> - required. Expected application type version in the downloaded package.
            // /progress: <The file where operation progress will be read from> - optional.
            // /output: <The root folder|file where output will be placed> - required
            // /timeout:<ticks> - optional

            /* ImageBuilder arguments for BuildComposeDeployment */
            // /cf:<Compose File path> - required
            // /of:<Overrides File path> - optional
            // /appTypeName:<Application Type Name> - required
            // /appTypeVersion:<Application Type Version> - required
            // /output: <The root folder|file where output application package will be placed> - required
            // /ocf:<Output Merged compose file path> - required
            // /repoUserName:<Repository User Name> - optional
            // /repoPwd:<Repository Password> - optional
            // /pwdEncrypted:<Is Repository Password encrypted> - optional
            // /cleanup:<Cleanup the compose files> - optional
            // /timeout:<ticks> - optional

            /* ImageBuilder arguments for ValidateComposeDeployment */
            // /cf:<Compose File path> - required
            // /of:<Overrides File path> - optional
            // /appTypeName:<Application Type Name> - optional
            // /appTypeVersion:<Application Type Version> - optional
            // /cleanup:<Cleanup the compose files> - optional
            // /timeout:<ticks> - optional

            /* ImageBuilder arguments for Application */
            // /appTypeName:<Application Type Name> - required for BuildApplication and UpgradeApplication operation
            // /appTypeVersion:<Application Type Version> - required for BuildApplication and UpgradeApplication operation
            // /appId:<Application ID> - required for BuildApplication and UpgradeApplication operation
            // /nameUri:<Name URI> - required for BuildApplication operation
            // /appParam:<semi-colon separated key-value pair>. Multiple such parameters can be passed. Key cannot have ';'.
            // /buildPath: <The root folder of build layout> - required for ApplicationTypeInfo and BuildApplicationType operation
            // /currentAppInstanceVersion: <The current app instance of the Application that needs to be upgraded> - required for UpgradeApplication operation

            /* ImageBuilder arguments for Fabric Upgrade */
            // /codePath: <The path to MSP for FabricUpgrade>
            // /configPath: <The path to ClusterManifest for FabricUpgrade>
            // /currentFabricVersion: <The current FabricVersion>
            // /targetFabricVersion: <The target FabricVersion>
            // /im: <Path to InfrastructureManifest.xml file>
            //

            Dictionary <string, string> commandArgs = null;
            Exception exception        = null;
            string    errorDetailsFile = null;

            try
            {
                commandArgs = ParseParameters(args);

                // Ensure that required parameters are present
                EnsureRequiredCommandLineParameters(commandArgs);

                Dictionary <string, string> applicationParameters = ParseAppParameters(commandArgs);

                errorDetailsFile = commandArgs.ContainsKey(StringConstants.ErrorDetails)
                    ? commandArgs[StringConstants.ErrorDetails]
                    : null;

                string workingDirectory = commandArgs.ContainsKey(StringConstants.WorkingDir)
                    ? commandArgs[StringConstants.WorkingDir]
                    : Directory.GetCurrentDirectory();

                string imageStoreConnectionString;
                if (commandArgs.ContainsKey(StringConstants.StoreRoot))
                {
                    imageStoreConnectionString = commandArgs[StringConstants.StoreRoot];
                }
                else
                {
                    ImageBuilderExe.TraceSource.WriteInfo(ImageBuilderExe.TraceType, "Loading ImageStoreConnectionString from config.");

                    bool isEncrypted;
                    NativeConfigStore configStore = NativeConfigStore.FabricGetConfigStore();
                    var configValue = configStore.ReadString("Management", "ImageStoreConnectionString", out isEncrypted);
                    if (isEncrypted)
                    {
                        var secureString    = NativeConfigStore.DecryptText(configValue);
                        var secureCharArray = FabricValidatorUtility.SecureStringToCharArray(secureString);
                        imageStoreConnectionString = new string(secureCharArray);
                    }
                    else
                    {
                        imageStoreConnectionString = configValue;
                    }

                    if (string.IsNullOrEmpty(imageStoreConnectionString))
                    {
                        throw new ArgumentException(StringResources.Error_MissingImageStoreConnectionStringInManifest);
                    }
                }

                StringBuilder stringToTrace = new StringBuilder();
                foreach (var commandArg in commandArgs)
                {
                    // Skipping tracing StoreRoot since it could be a secret value
                    if (!ImageBuilderUtility.Equals(commandArg.Key, StringConstants.StoreRoot))
                    {
                        stringToTrace.AppendFormat("{0}:{1}", commandArg.Key, commandArg.Value);
                        stringToTrace.AppendLine();
                    }
                }

                ImageBuilderExe.TraceSource.WriteInfo(
                    ImageBuilderExe.TraceType,
                    "ImageBuilderExe called with - {0}",
                    stringToTrace.ToString());

                string currentExecutingDirectory = Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
                string schemaPath = commandArgs.ContainsKey(StringConstants.SchemaPath)
                    ? commandArgs[StringConstants.SchemaPath]
                    : Path.Combine(
                    currentExecutingDirectory,
                    StringConstants.DefaultSchemaPath);

                TimeSpan timeout = commandArgs.ContainsKey(StringConstants.Timeout)
                    ? TimeSpan.FromTicks(long.Parse(commandArgs[StringConstants.Timeout]))
                    : TimeSpan.MaxValue;

                Timer timer = null;
                if (timeout != TimeSpan.MaxValue)
                {
                    ImageBuilderExe.TraceSource.WriteInfo(
                        ImageBuilderExe.TraceType,
                        "ImageBuilderExe enabled timeout monitor: {0}",
                        timeout);

                    timer = new Timer(OnTimeout, errorDetailsFile, timeout, TimeSpan.FromMilliseconds(-1));
                }

                IImageStore imageStore = ImageStoreFactoryProxy.CreateImageStore(
                    imageStoreConnectionString,
                    null,
                    workingDirectory,
                    true /*isInternal*/);

                ImageBuilder imageBuilder = new ImageBuilder(imageStore, schemaPath, workingDirectory);

                string operationValue = commandArgs[StringConstants.Operation];

                bool sfVolumeDiskServiceEnabled = commandArgs.ContainsKey(StringConstants.SFVolumeDiskServiceEnabled)
                        ? ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.SFVolumeDiskServiceEnabled])
                        : false;

                imageBuilder.IsSFVolumeDiskServiceEnabled = sfVolumeDiskServiceEnabled;

                if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationDownloadAndBuildApplicationType))
                {
                    string progressFile = commandArgs.ContainsKey(StringConstants.Progress) ? commandArgs[StringConstants.Progress] : null;
                    bool   shouldSkipChecksumValidation = commandArgs.ContainsKey(StringConstants.DisableChecksumValidation) ? ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.DisableChecksumValidation]) : false;

                    imageBuilder.DownloadAndBuildApplicationType(
                        commandArgs[StringConstants.DownloadPath],
                        commandArgs[StringConstants.AppTypeName],
                        commandArgs[StringConstants.AppTypeVersion],
                        commandArgs[StringConstants.Output],
                        timeout,
                        progressFile,
                        shouldSkipChecksumValidation);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildApplicationTypeInfo))
                {
                    imageBuilder.GetApplicationTypeInfo(commandArgs[StringConstants.BuildPath], timeout, commandArgs[StringConstants.Output]);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildApplicationType))
                {
                    string outputFile   = commandArgs.ContainsKey(StringConstants.Output) ? commandArgs[StringConstants.Output] : null;
                    string progressFile = commandArgs.ContainsKey(StringConstants.Progress) ? commandArgs[StringConstants.Progress] : null;
                    bool   shouldSkipChecksumValidation = commandArgs.ContainsKey(StringConstants.DisableChecksumValidation) ? ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.DisableChecksumValidation]) : false;
                    bool   shouldSkipServerSideCopy     = commandArgs.ContainsKey(StringConstants.DisableServerSideCopy) ? ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.DisableServerSideCopy]) : false;

                    imageBuilder.BuildApplicationType(commandArgs[StringConstants.BuildPath], timeout, outputFile, progressFile, shouldSkipChecksumValidation, shouldSkipServerSideCopy);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildSingleInstanceApplication))
                {
                    bool generateDnsNames = commandArgs.ContainsKey(StringConstants.GenerateDnsNames)
                        ? ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.GenerateDnsNames])
                        : false;

                    bool useOpenNetworkConfig = commandArgs.ContainsKey(StringConstants.UseOpenNetworkConfig)
                        ? ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.UseOpenNetworkConfig])
                        : false;

                    Application application = null;

                    using (StreamReader file = File.OpenText(commandArgs[StringConstants.SingleInstanceApplicationDescription]))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        serializer.Converters.Add(new DiagnosticsSinkJsonConverter());
                        serializer.Converters.Add(new VolumeMountJsonConverter());

                        application =
                            (Application)serializer.Deserialize(file, typeof(Application));
                    }

                    GenerationConfig config = null;
                    if (commandArgs.ContainsKey(StringConstants.GenerationConfig))
                    {
                        using (StreamReader file = File.OpenText(commandArgs[StringConstants.GenerationConfig]))
                        {
                            JsonSerializer serializer = new JsonSerializer();
                            config =
                                (GenerationConfig)serializer.Deserialize(file, typeof(GenerationConfig));
                        }
                    }

                    imageBuilder.BuildSingleInstanceApplication(
                        application,
                        commandArgs[StringConstants.AppTypeName],
                        commandArgs[StringConstants.AppTypeVersion],
                        commandArgs[StringConstants.AppId],
                        new Uri(commandArgs[StringConstants.AppName]),
                        generateDnsNames,
                        timeout,
                        commandArgs[StringConstants.BuildPath],
                        commandArgs[StringConstants.Output],
                        useOpenNetworkConfig,
                        config);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildSingleInstanceApplicationForUpgrade))
                {
                    bool generateDnsNames = commandArgs.ContainsKey(StringConstants.GenerateDnsNames)
                        ? ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.GenerateDnsNames])
                        : false;

                    bool useOpenNetworkConfig = commandArgs.ContainsKey(StringConstants.UseOpenNetworkConfig)
                        ? ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.UseOpenNetworkConfig])
                        : false;

                    Application application = null;

                    using (StreamReader file = File.OpenText(commandArgs[StringConstants.SingleInstanceApplicationDescription]))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        serializer.Converters.Add(new VolumeMountJsonConverter());
                        application =
                            (Application)serializer.Deserialize(file, typeof(Application));
                    }

                    GenerationConfig config = null;
                    if (commandArgs.ContainsKey(StringConstants.GenerationConfig))
                    {
                        using (StreamReader file = File.OpenText(commandArgs[StringConstants.GenerationConfig]))
                        {
                            JsonSerializer serializer = new JsonSerializer();
                            config =
                                (GenerationConfig)serializer.Deserialize(file, typeof(GenerationConfig));
                        }
                    }

                    imageBuilder.BuildSingleInstanceApplicationForUpgrade(
                        application,
                        commandArgs[StringConstants.AppTypeName],
                        commandArgs[StringConstants.CurrentAppTypeVersion],
                        commandArgs[StringConstants.TargetAppTypeVersion],
                        commandArgs[StringConstants.AppId],
                        int.Parse(commandArgs[StringConstants.CurrentAppInstanceVersion], CultureInfo.InvariantCulture),
                        new Uri(commandArgs[StringConstants.AppName]),
                        generateDnsNames,
                        timeout,
                        commandArgs[StringConstants.BuildPath],
                        commandArgs[StringConstants.Output],
                        useOpenNetworkConfig,
                        config);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildApplication))
                {
                    imageBuilder.BuildApplication(
                        commandArgs[StringConstants.AppTypeName],
                        commandArgs[StringConstants.AppTypeVersion],
                        commandArgs[StringConstants.AppId],
                        new Uri(commandArgs[StringConstants.NameUri]),
                        applicationParameters,
                        timeout,
                        commandArgs[StringConstants.Output]);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationUpgradeApplication))
                {
                    imageBuilder.UpgradeApplication(
                        commandArgs[StringConstants.AppId],
                        commandArgs[StringConstants.AppTypeName],
                        int.Parse(commandArgs[StringConstants.CurrentAppInstanceVersion], CultureInfo.InvariantCulture),
                        commandArgs[StringConstants.AppTypeVersion],
                        applicationParameters,
                        timeout,
                        commandArgs[StringConstants.Output]);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationDelete))
                {
                    imageBuilder.Delete(commandArgs[StringConstants.Input], timeout);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationCleanupApplicationPackage))
                {
                    imageBuilder.DeleteApplicationPackage(commandArgs[StringConstants.BuildPath], timeout);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationGetFabricVersion))
                {
                    imageBuilder.GetFabricVersionInfo(
                        commandArgs[StringConstants.CodePath],
                        commandArgs[StringConstants.ConfigPath],
                        timeout,
                        commandArgs[StringConstants.Output]);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationProvisionFabric))
                {
                    string configurationCsvFilePath = Path.Combine(currentExecutingDirectory, StringConstants.ConfigurationsFileName);
                    imageBuilder.ProvisionFabric(
                        commandArgs[StringConstants.CodePath],
                        commandArgs[StringConstants.ConfigPath],
                        configurationCsvFilePath,
                        commandArgs[StringConstants.InfrastructureManifestFile],
                        timeout);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationGetClusterManifest))
                {
                    imageBuilder.GetClusterManifestContents(
                        commandArgs[StringConstants.ConfigVersion],
                        commandArgs[StringConstants.Output],
                        timeout);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationUpgradeFabric))
                {
                    string configurationCsvFilePath = Path.Combine(currentExecutingDirectory, StringConstants.ConfigurationsFileName);

                    imageBuilder.UpgradeFabric(
                        commandArgs[StringConstants.CurrentFabricVersion],
                        commandArgs[StringConstants.TargetFabricVersion],
                        configurationCsvFilePath,
                        timeout,
                        commandArgs[StringConstants.Output]);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationGetManifests))
                {
                    imageBuilder.GetManifests(commandArgs[StringConstants.Input], timeout);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationValidateComposeDeployment))
                {
                    bool cleanupComposeFiles = commandArgs.ContainsKey(StringConstants.CleanupComposeFiles) && ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.CleanupComposeFiles]);

                    HashSet <string> ignoredKeys;
                    imageBuilder.ValidateComposeDeployment(
                        commandArgs[StringConstants.ComposeFilePath],
                        commandArgs.ContainsKey(StringConstants.OverrideFilePath) ? commandArgs[StringConstants.OverrideFilePath] : null,
                        commandArgs.ContainsKey(StringConstants.AppName) ? commandArgs[StringConstants.AppName] : null,
                        commandArgs.ContainsKey(StringConstants.AppTypeName) ? commandArgs[StringConstants.AppTypeName] : null,
                        commandArgs.ContainsKey(StringConstants.AppTypeVersion) ? commandArgs[StringConstants.AppTypeVersion] : null,
                        timeout,
                        out ignoredKeys,
                        cleanupComposeFiles);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildComposeDeployment))
                {
                    bool cleanupComposeFiles          = commandArgs.ContainsKey(StringConstants.CleanupComposeFiles) && ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.CleanupComposeFiles]);
                    bool shouldSkipChecksumValidation = commandArgs.ContainsKey(StringConstants.DisableChecksumValidation) && ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.DisableChecksumValidation]);
                    bool isPasswordEncrypted          = commandArgs.ContainsKey(StringConstants.IsRepositoryPasswordEncrypted) && ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.IsRepositoryPasswordEncrypted]);

                    bool generateDnsNames = commandArgs.ContainsKey(StringConstants.GenerateDnsNames) && ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.GenerateDnsNames]);

                    imageBuilder.BuildComposeDeploymentPackage(
                        commandArgs[StringConstants.ComposeFilePath],
                        commandArgs.ContainsKey(StringConstants.OverrideFilePath) ? commandArgs[StringConstants.OverrideFilePath] : null,
                        timeout,
                        commandArgs.ContainsKey(StringConstants.AppName) ? commandArgs[StringConstants.AppName] : null,
                        commandArgs[StringConstants.AppTypeName],
                        commandArgs[StringConstants.AppTypeVersion],
                        commandArgs.ContainsKey(StringConstants.RepositoryUserName) ? commandArgs[StringConstants.RepositoryUserName] : null,
                        commandArgs.ContainsKey(StringConstants.RepositoryPassword) ? commandArgs[StringConstants.RepositoryPassword] : null,
                        isPasswordEncrypted,
                        generateDnsNames,
                        commandArgs[StringConstants.OutputComposeFilePath],
                        commandArgs[StringConstants.Output],
                        cleanupComposeFiles,
                        shouldSkipChecksumValidation);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildComposeApplicationForUpgrade))
                {
                    bool cleanupComposeFiles          = commandArgs.ContainsKey(StringConstants.CleanupComposeFiles) && ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.CleanupComposeFiles]);
                    bool shouldSkipChecksumValidation = commandArgs.ContainsKey(StringConstants.DisableChecksumValidation) && ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.DisableChecksumValidation]);
                    bool isPasswordEncrypted          = commandArgs.ContainsKey(StringConstants.IsRepositoryPasswordEncrypted) && ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.IsRepositoryPasswordEncrypted]);

                    bool generateDnsNames = commandArgs.ContainsKey(StringConstants.GenerateDnsNames) && ImageBuilderUtility.ConvertString <bool>(commandArgs[StringConstants.GenerateDnsNames]);

                    imageBuilder.BuildComposeDeploymentPackageForUpgrade(
                        commandArgs[StringConstants.ComposeFilePath],
                        commandArgs.ContainsKey(StringConstants.OverrideFilePath) ? commandArgs[StringConstants.OverrideFilePath] : null,
                        timeout,
                        commandArgs.ContainsKey(StringConstants.AppName) ? commandArgs[StringConstants.AppName] : null,
                        commandArgs[StringConstants.AppTypeName],
                        commandArgs[StringConstants.CurrentAppTypeVersion],
                        commandArgs[StringConstants.TargetAppTypeVersion],
                        commandArgs.ContainsKey(StringConstants.RepositoryUserName) ? commandArgs[StringConstants.RepositoryUserName] : null,
                        commandArgs.ContainsKey(StringConstants.RepositoryPassword) ? commandArgs[StringConstants.RepositoryPassword] : null,
                        isPasswordEncrypted,
                        generateDnsNames,
                        commandArgs[StringConstants.OutputComposeFilePath],
                        commandArgs[StringConstants.Output],
                        cleanupComposeFiles,
                        shouldSkipChecksumValidation);
                }
                else if (ImageBuilderUtility.Equals(operationValue, StringConstants.TestErrorDetails))
                {
                    throw new Exception(StringConstants.TestErrorDetails);
                }
                else
                {
                    throw new ArgumentException(
                              string.Format(
                                  CultureInfo.CurrentCulture,
                                  StringResources.Error_ImageBuilderExeCommandLineInvalidOperation,
                                  StringConstants.Operation,
                                  operationValue));
                }
            }
            catch (AggregateException ae)
            {
                exception = ae.InnerException;

                StringBuilder exceptionStringBuilder = new StringBuilder("Aggregate exception has ");
                exceptionStringBuilder.Append(ae.InnerExceptions.Count);
                exceptionStringBuilder.Append(" exceptions. ");
                ae.InnerExceptions.ForEach(innerException => exceptionStringBuilder.AppendLine(innerException.Message));

                ImageBuilderExe.TraceSource.WriteWarning(
                    ImageBuilderExe.TraceType,
                    "AggregateException: {0}",
                    exceptionStringBuilder.ToString());
            }
            catch (Exception e)
            {
                exception = e;
            }

            if (exception != null)
            {
                OnFailure(exception, errorDetailsFile);

                return(unchecked ((int)NativeTypes.FABRIC_ERROR_CODE.FABRIC_E_IMAGEBUILDER_UNEXPECTED_ERROR));
            }
            else
            {
                ImageBuilderExe.TraceSource.WriteInfo(
                    ImageBuilderExe.TraceType,
                    "ImageBuilderExe operation completed successfully.");

                return(0);
            }
        }
        private bool IsFirewallRuleDisabled()
        {
            NativeConfigStore configStore = NativeConfigStore.FabricGetConfigStore();

            return(configStore.ReadUnencryptedBool(Constants.SecuritySectionName, Constants.DisableFirewallRuleForPublicProfilePropertyName, UpgradeOrchestrationTrace.TraceSource, TraceType, false /*throwIfInvalid*/));
        }
Ejemplo n.º 26
0
            /// <summary>
            /// Parses the command line arguments, applies the constraints and generates a structured accessor to the
            /// command line arguments.
            /// </summary>
            /// <param name="args">The command line arguments.</param>
            /// <returns>True if the command line arguments were proper, false otherwise.</returns>
            internal bool Parse(string[] args)
            {
                if (args.Length < 1 || args[0] == "/?")
                {
                    return(false);
                }

                int i = 1;

                while (i != args.Length)
                {
                    switch (args[i])
                    {
                    case "-c":
                        this.connectionString = args[++i];
                        break;

                    case "-f":
                        this.fileName = args[++i];
                        break;

                    case "-x":
                        this.storeTag = args[++i];
                        break;

                    case "-l":
                        this.localTag = args[++i];
                        break;

                    case "-g":
                        this.copyFlag = (CopyFlag)Enum.Parse(typeof(CopyFlag), args[++i]);
                        break;

                    case "-b":
                        this.XStoreMinTransferBPS = int.Parse(args[++i], CultureInfo.InvariantCulture);
                        break;

                    case "-o":
                        this.outputFile = args[++i];
                        break;

                    default:
                        return(false);
                    }

                    i++;
                }

                this.command = (Commands)Enum.Parse(typeof(Commands), args[0]);
                if (string.IsNullOrEmpty(this.connectionString))
                {
                    bool isEncrypted;
                    NativeConfigStore configStore = NativeConfigStore.FabricGetConfigStore();
                    var configValue = configStore.ReadString("Management", "ImageStoreConnectionString", out isEncrypted);
                    if (isEncrypted)
                    {
                        var secureString    = NativeConfigStore.DecryptText(configValue);
                        var secureCharArray = FabricValidatorUtility.SecureStringToCharArray(secureString);
                        this.connectionString = new string(secureCharArray);
                    }
                    else
                    {
                        this.connectionString = configValue;
                    }
                }

                if (this.command == Commands.Delete)
                {
                    if (string.IsNullOrEmpty(this.storeTag) && string.IsNullOrEmpty(this.fileName))
                    {
                        return(false);
                    }
                }
                else if (this.command == Commands.Exists)
                {
                    if (string.IsNullOrEmpty(this.outputFile))
                    {
                        return(false);
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(this.fileName))
                    {
                        if (string.IsNullOrEmpty(this.localTag) || string.IsNullOrEmpty(this.storeTag))
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(this.localTag) || !string.IsNullOrEmpty(this.storeTag))
                        {
                            return(false);
                        }
                    }
                }

                return(true);
            }
Ejemplo n.º 27
0
        private async Task PollGoalStateForCodePackagesAsync(CancellationToken cancellationToken)
        {
            var fabricClient = new FabricClient();

            //// region: Initialization Parameters

            FabricUpgradeProgress upgradeProgress;

            try
            {
                upgradeProgress = await FabricClientRetryHelper.ExecuteFabricActionWithRetryAsync <FabricUpgradeProgress>(
                    () =>
                    fabricClient.ClusterManager.GetFabricUpgradeProgressAsync(TimeSpan.FromMinutes(DMConstants.FabricOperationTimeoutInMinutes), cancellationToken),
                    TimeSpan.FromMinutes(DMConstants.FabricOperationTimeoutInMinutes),
                    cancellationToken).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                this.traceSource.WriteError(TraceType, "GetFabricUpgradeProgressAsync threw: {0}", ex.ToString());
                this.timerInterval = TimeSpan.FromMinutes(DMConstants.FabricUpgradeStatePollIntervalInMinutes);
                return;
            }

            if (!FabricClientWrapper.IsUpgradeCompleted(upgradeProgress.UpgradeState))
            {
                this.timerInterval = TimeSpan.FromMinutes(DMConstants.FabricUpgradeStatePollIntervalInMinutes);
                this.traceSource.WriteInfo(TraceType, "Cannot retrieve cluster version; FabricUpgradeState is currently: {0}. Will retry in {1}.", upgradeProgress.UpgradeState.ToString(), this.timerInterval.ToString());
                return;
            }

            string            currentVersionStr = upgradeProgress.TargetCodeVersion;
            Version           currentVersion    = Version.Parse(currentVersionStr);
            string            packageDropDir    = System.Fabric.Common.Helpers.GetNewTempPath();
            NativeConfigStore configStore       = NativeConfigStore.FabricGetConfigStore();
            string            goalStateUriStr   = configStore.ReadUnencryptedString(DMConstants.UpgradeOrchestrationServiceConfigSectionName, DMConstants.GoalStateFileUrlName);

            if (string.IsNullOrEmpty(goalStateUriStr))
            {
                goalStateUriStr = DMConstants.DefaultGoalStateFileUrl;
            }

            //// endregion

            this.traceSource.WriteInfo(TraceType, "PollCodePackagesFromGoalState currentVersion: {0}, packageDropDir: {1} goalStateUri: {2}", currentVersionStr, packageDropDir, goalStateUriStr);
            try
            {
                Uri    goalStateUri  = null;
                string goalStateJson = null;
                if (!Uri.TryCreate(goalStateUriStr, UriKind.Absolute, out goalStateUri))
                {
                    string errorMessage = string.Format("Cannot parse GoalStateUri: {0}", goalStateUriStr);
                    this.traceSource.WriteError(TraceType, errorMessage);
                    ReleaseAssert.Fail(errorMessage);
                    return;
                }

                if (!(await StandaloneUtility.IsUriReachableAsync(goalStateUri).ConfigureAwait(false)))
                {
                    this.timerInterval = TimeSpan.FromMinutes(DMConstants.FabricGoalStateReachablePollIntervalInMinutes);
                    this.traceSource.WriteWarning(TraceType, "Cannot reach download uri for goal state file: {0}. Will retry in {1}.", goalStateUri.AbsoluteUri, this.timerInterval.ToString());
                    this.EmitGoalStateReachableHealth(fabricClient, false);
                    return;
                }
                else
                {
                    this.EmitGoalStateReachableHealth(fabricClient, true);
                }

                goalStateJson = await GoalStateModel.GetGoalStateFileJsonAsync(goalStateUri).ConfigureAwait(false);

                if (string.IsNullOrEmpty(goalStateJson))
                {
                    this.traceSource.WriteWarning(TraceType, "Loaded goal state JSON is empty.");
                    return;
                }

                GoalStateModel model = GoalStateModel.GetGoalStateModelFromJson(goalStateJson);
                if (model == null || model.Packages == null)
                {
                    this.traceSource.WriteWarning(TraceType, "Goal state JSON could not be deserialized:\n{0}", goalStateJson);
                    return;
                }

                string availableGoalStateVersions = string.Format("Available versions in goal state file: {0}", model.ToString());
                this.traceSource.WriteInfo(TraceType, availableGoalStateVersions);

                IEnumerable <PackageDetails> candidatePackages = model.Packages.Where(
                    package => currentVersion < Version.Parse(package.Version));

                if (candidatePackages.Count() == 0)
                {
                    this.traceSource.WriteInfo(TraceType, "No upgrades available.");
                }

                string         versionCurrentStr = currentVersionStr;
                Version        versionCurrent    = currentVersion;
                PackageDetails targetPackage     = null;
                for (IEnumerable <PackageDetails> availableCandidatePackages = candidatePackages.Where(
                         package => (package.MinVersion == null || Version.Parse(package.MinVersion) <= versionCurrent));
                     availableCandidatePackages.Count() > 0;
                     versionCurrentStr = targetPackage.Version,
                     versionCurrent = Version.Parse(versionCurrentStr),
                     availableCandidatePackages = candidatePackages.Where(
                         package => (versionCurrent < Version.Parse(package.Version) &&
                                     (package.MinVersion == null || Version.Parse(package.MinVersion) <= versionCurrent))))
                {
                    if (!IsVersionUpgradeable(versionCurrentStr, model))
                    {
                        this.traceSource.WriteInfo(TraceType, "Version {0} is not upgradeable.", versionCurrentStr);
                        break;
                    }

                    int numPackages = availableCandidatePackages.Count();
                    if (numPackages == 0)
                    {
                        this.traceSource.WriteInfo(TraceType, "No upgrade available.");
                        return;
                    }
                    else if (numPackages == 1)
                    {
                        targetPackage = availableCandidatePackages.First();
                    }
                    else
                    {
                        Version maxVersion = StandaloneGoalStateProvisioner.ZeroVersion;
                        foreach (PackageDetails package in availableCandidatePackages)
                        {
                            Version targetVersion;
                            if (!Version.TryParse(package.Version, out targetVersion))
                            {
                                this.traceSource.WriteWarning(TraceType, "Package {0} version could not be parsed. Trying another one.", package.Version);
                                continue;
                            }

                            if (targetVersion > maxVersion)
                            {
                                targetPackage = package;
                                maxVersion    = targetVersion;
                            }
                        }
                    }

                    try
                    {
                        if (await this.IsPackageProvisionedAsync(targetPackage.Version, fabricClient, cancellationToken).ConfigureAwait(false))
                        {
                            this.traceSource.WriteInfo(TraceType, "Package {0} is already provisioned.", targetPackage.Version);
                            continue;
                        }
                    }
                    catch (Exception ex)
                    {
                        this.traceSource.WriteError(TraceType, "PackageIsProvisioned for {0} threw: {1}", targetPackage.Version, ex.ToString());
                    }

                    string packageLocalDownloadPath = Path.Combine(packageDropDir, string.Format(DMConstants.SFPackageDropNameFormat, targetPackage.Version));
                    if (await StandaloneUtility.DownloadPackageAsync(targetPackage.Version, targetPackage.TargetPackageLocation, packageLocalDownloadPath).ConfigureAwait(false))
                    {
                        try
                        {
                            this.traceSource.WriteInfo(TraceType, "Copying and provisioning version {0} from {1}.", targetPackage.Version, packageLocalDownloadPath);
                            await ProvisionPackageAsync(targetPackage.Version, packageLocalDownloadPath, cancellationToken).ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            this.traceSource.WriteError(TraceType, "ProvisionPackageAsync for {0}, package {1} threw: {2}", targetPackage.Version, packageLocalDownloadPath, ex.ToString());
                        }
                    }
                }

                // Determine if current version is latest/doesn't have expiry date. If package expiring, post cluster health warning.
                PackageDetails currentPackage = model.Packages.Where(package => package.Version == currentVersionStr).FirstOrDefault();
                if (currentPackage != null && currentPackage.SupportExpiryDate != null && !currentPackage.IsGoalPackage && !this.IsAutoupgradeInstallEnabled() && this.IsPackageNearExpiry(currentPackage))
                {
                    this.traceSource.WriteWarning(TraceType, "Current version {0} expires {1}; emitting cluster warning.", currentVersionStr, currentPackage.SupportExpiryDate);
                    this.EmitClusterVersionSupportedHealth(fabricClient, false, currentVersionStr, currentPackage.SupportExpiryDate);
                }
                else
                {
                    this.traceSource.WriteInfo(TraceType, "Current version {0} is supported. Cluster health OK.", currentVersionStr);
                    this.EmitClusterVersionSupportedHealth(fabricClient, true, null, null);
                }

                if (targetPackage != null &&
                    !string.IsNullOrEmpty(targetPackage.Version) &&
                    this.IsAutoupgradeInstallEnabled())
                {
                    try
                    {
                        // fire off an upgrade.
                        this.StartCodeUpgrade(targetPackage.Version, fabricClient);
                    }
                    catch (Exception ex)
                    {
                        this.traceSource.WriteError(TraceType, "StartCodeUpgrade for version {0} threw: {1}", targetPackage.Version, ex.ToString());
                    }
                }
            }
            finally
            {
                if (Directory.Exists(packageDropDir))
                {
                    try
                    {
                        FabricDirectory.Delete(packageDropDir, true, true);
                    }
                    catch
                    {
                    }
                }
            }
        }
Ejemplo n.º 28
0
 private HostingConfig()
 {
     this.hostingSettings = HostingSettings.LoadHostingSettings();
     this.configLock      = new RwLock();
     this.configStore     = NativeConfigStore.FabricGetConfigStore(this);
 }
Ejemplo n.º 29
0
        public static int Main(string[] args)
        {
            FabricEvents.ExtensionsEvents traceSource = new FabricEvents.ExtensionsEvents(FabricEvents.Tasks.BackupRestoreService);

            int status = 0;

            var codePackageActivationContext = FabricRuntime.GetActivationContext();
            var configStore = NativeConfigStore.FabricGetConfigStore();
            var serverAuthCredentialTypeName     = configStore.ReadUnencryptedString(BackupRestoreContants.SecurityConfigSectionName, BackupRestoreContants.ServerAuthCredentialTypeName);
            var serverAuthCredentialType         = CredentialType.None;
            EndpointResourceDescription endpoint = null;

            try
            {
                endpoint = codePackageActivationContext.GetEndpoint(BackupRestoreContants.RestEndPointName);
            }
            catch (FabricElementNotFoundException)
            {
                traceSource.WriteWarning(TraceType, "Endpoint not found for EndpointName{0}", BackupRestoreContants.RestEndPointName);
                throw;
            }

            if (!string.IsNullOrEmpty(serverAuthCredentialTypeName) && !Enum.TryParse(serverAuthCredentialTypeName, out serverAuthCredentialType))
            {
                traceSource.WriteWarning(TraceType, "Unable to convert configuration value serverAuthCredentialTypeName {0} for {1} type.", serverAuthCredentialTypeName, serverAuthCredentialType);
            }

            if (serverAuthCredentialType == CredentialType.X509 || serverAuthCredentialType == CredentialType.Claims)
            {
                // Get server auth details

                var aclServerAuthX509StoreName = configStore.ReadUnencryptedString(BackupRestoreContants.FabricNodeConfigSectionName, BackupRestoreContants.ServerAuthX509StoreName);
                var aclCertValueFindTypeName   = configStore.ReadUnencryptedString(BackupRestoreContants.FabricNodeConfigSectionName, BackupRestoreContants.ServerAuthX509FindType);
                var aclCertValue          = configStore.ReadUnencryptedString(BackupRestoreContants.FabricNodeConfigSectionName, BackupRestoreContants.ServerAuthX509FindValue);
                var aclCertValueSecondary = configStore.ReadUnencryptedString(BackupRestoreContants.FabricNodeConfigSectionName, BackupRestoreContants.ServerAuthX509FindValueSecondary);

                var storeName                = StoreName.My;
                var x509FindType             = X509FindType.FindByThumbprint;
                X509Certificate2 certificate = null;

                if (!string.IsNullOrEmpty(aclServerAuthX509StoreName) && !Enum.TryParse(aclServerAuthX509StoreName, out storeName))
                {
                    traceSource.WriteWarning(TraceType, "Unable to Convert configuration aclServerAuthX509StoreName value {0} for {1} type.", aclServerAuthX509StoreName, storeName.GetType().ToString());
                    throw new InvalidEnumArgumentException(string.Format("Unable to Convert configuration aclCertValueFindTypeName value {0} for {1} type.", aclServerAuthX509StoreName, x509FindType.GetType()));
                }

                if (!string.IsNullOrEmpty(aclCertValueFindTypeName) && !Enum.TryParse(aclCertValueFindTypeName, out x509FindType))
                {
                    traceSource.WriteWarning(TraceType, "Unable to Convert configuration aclCertValueFindTypeName value {0} for {1} type.", aclServerAuthX509StoreName, x509FindType.GetType().ToString());
                    throw new InvalidEnumArgumentException(string.Format("Unable to Convert configuration aclCertValueFindTypeName value {0} for {1} type.", aclServerAuthX509StoreName, x509FindType.GetType()));
                }

                if (!string.IsNullOrWhiteSpace(aclCertValue))
                {
                    // Get certificate.
                    var store = new X509Store(storeName, StoreLocation.LocalMachine);

                    try
                    {
                        store.Open(OpenFlags.ReadOnly);

                        traceSource.WriteInfo(
                            TraceType,
                            "Finding applicable certificate for Acling. StoreName: {0}, StoreLocation: LocalMachine, X509FindType: {1}, X509FindValue: {2}.",
                            storeName,
                            x509FindType,
                            aclCertValue);

                        var certCollections = store.Certificates.Find(x509FindType, aclCertValue, false /*load self-signed cert*/);
                        if (certCollections.Count > 0)
                        {
                            certificate = certCollections[0];
                        }
                        else if (!string.IsNullOrWhiteSpace(aclCertValueSecondary))
                        {
                            traceSource.WriteInfo(
                                TraceType,
                                "Finding applicable certificate for Acling using Secondary cert config. StoreName: {0}, StoreLocation: LocalMachine, X509FindType: {1}, X509FindValue: {2}.",
                                storeName,
                                x509FindType,
                                aclCertValueSecondary);

                            var certCollectionsSecondary = store.Certificates.Find(x509FindType, aclCertValueSecondary, false /*load self-signed cert*/);
                            if (certCollectionsSecondary.Count > 0)
                            {
                                certificate = certCollectionsSecondary[0];
                            }
                        }
                        else
                        {
                            traceSource.WriteWarning(TraceType, "No matching certificate found. Thumbprint value: {0}, StoreName: {1}, StoreLocation: {2}", aclCertValue, aclServerAuthX509StoreName, StoreLocation.LocalMachine);
                        }
                    }
                    finally
                    {
                        store.Close();
                    }
                }
                else
                {
                    traceSource.WriteWarning(TraceType, "Invalid configuration for certificate. Thumbprint value: {0}, StoreName: {1}, StoreLocation: {2}", aclCertValue, aclServerAuthX509StoreName, StoreLocation.LocalMachine);
                }

                if (certificate != null)
                {
                    PortAclUtility.BindCertificate(endpoint.IpAddressOrFqdn, endpoint.Port, certificate.GetCertHash());
                }
            }

            // Do URL ACLing
            CodePackage codePackage = codePackageActivationContext.GetCodePackageObject("Code");
            string      daclString  = "D:(A;;GX;;;NS)";

            try
            {
                var runAsAccountName = configStore.ReadUnencryptedString(BackupRestoreContants.FabricNodeRunAsSectionName, BackupRestoreContants.RunAsAccountNameConfig);
                if (!string.IsNullOrEmpty(runAsAccountName))
                {
                    traceSource.WriteInfo(TraceType, "runAsAccountName for ACLing: {0} for CredentialType Windows", runAsAccountName);
                    daclString = GetAllowDaclFromUserName(runAsAccountName);
                }
            }
            catch (IdentityNotMappedException ex)
            {
                traceSource.WriteWarning(TraceType, "Failed to resolve NTAccount: {0}, Exception: {1}", codePackage.EntryPointRunAsPolicy.UserName, ex);
                throw;
            }
            catch (SystemException ex)
            {
                traceSource.WriteWarning(TraceType, "Failed to resolve NTAccount: {0}, Exception: {1}", codePackage.EntryPointRunAsPolicy.UserName, ex);
                throw;
            }

            var fabricBrsSecuritySetting = SecuritySetting.GetClusterSecurityDetails();
            var listeningAddress         = String.Format(CultureInfo.InvariantCulture, "{0}://+:{1}/", fabricBrsSecuritySetting.EndpointProtocol, endpoint.Port);

            traceSource.WriteInfo(TraceType, "ListeningAddress: {0} ,DaclString: {1} for ACLing", listeningAddress, daclString);
            PortAclUtility.ReserveUrl(listeningAddress, daclString);

            return(status);
        }
Ejemplo n.º 30
0
        public bool IsAutoupgradeInstallEnabled()
        {
            NativeConfigStore configStore = NativeConfigStore.FabricGetConfigStore();

            return(configStore.ReadUnencryptedBool(DMConstants.UpgradeOrchestrationServiceConfigSectionName, DMConstants.AutoupgradeInstallEnabledName, UpgradeOrchestrationTrace.TraceSource, TraceType, false /*throwIfInvalid*/));
        }