Beispiel #1
0
        private void LoadSettingsFromUnreliableTransportSettingsFile(string filePath)
        {
            if (File.Exists(filePath) == true)
            {
                try
                {
                    using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        using (StreamReader file = new StreamReader(fileStream))
                        {
                            string specificationString;

                            while ((specificationString = file.ReadLine()) != null)
                            {
                                UnreliableTransportSpecification specification = new UnreliableTransportSpecification();
                                if (Constants.ErrorCode_Success == ParseSpecificationFromINI(specificationString, ref specification))
                                {
                                    Specification.Add(specification);
                                }
                                else
                                {
                                    DeployerTrace.WriteWarning("Skipping malformed line in UnreliableTransportSettings File, value = [{0}]", specificationString);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    DeployerTrace.WriteError("Unable to read Unreliable Settings file because {0}", e);
                    throw;
                }
            }
        }
        internal static void RemoveFirewallRule()
        {
            DeployerTrace.WriteInfo("Removing firewall rule {0} if it exists...", FirewallRuleName);

            try
            {
#if !DotNetCoreClrLinux
                INetFwPolicy2 fwPolicy2 = GetFirewallPolicy();
                if (fwPolicy2 == null)
                {
                    DeployerTrace.WriteWarning(StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorGettingFirewallPolicy2);
                    return;
                }

                bool exists = DoesFirewallRuleExist(fwPolicy2);
                if (!exists)
                {
                    DeployerTrace.WriteInfo("Firewall rule {0} doesn't exist. Nothing to remove", FirewallRuleName);
                    return;
                }

                fwPolicy2.Rules.Remove(FirewallRuleName);
#else
                INetFwRules rules = NetFwRules.GetAllRules();
                rules.Remove(FirewallRuleName);
#endif
                DeployerTrace.WriteInfo("Firewall rule {0} removed", FirewallRuleName);
            }
            catch (Exception ex)
            {
                DeployerTrace.WriteWarning(StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorRemovingFirewallRule, FirewallRuleName, ex);
            }
        }
        private static void NetCloseResource(string path)
        {
            const int MAX_PREFERRED_LENGTH = -1;
            int       readEntries;
            int       totalEntries;
            IntPtr    buffer = IntPtr.Zero;

            // Enumerate all resouces in this path that are open remotly
            int enumerateStatus = NativeMethods.NetFileEnum(null, path, null, 3, ref buffer, MAX_PREFERRED_LENGTH, out readEntries, out totalEntries, IntPtr.Zero);

            if (enumerateStatus == NativeMethods.ERROR_SUCCESS)
            {
                NativeMethods.FILE_INFO_3 fileInfo = new NativeMethods.FILE_INFO_3();
                for (int index = 0; index < readEntries; index++)
                {
                    IntPtr bufferPtr = new IntPtr(buffer.ToInt64() + (index * Marshal.SizeOf(fileInfo)));
                    fileInfo = (NativeMethods.FILE_INFO_3)Marshal.PtrToStructure(bufferPtr, typeof(NativeMethods.FILE_INFO_3));
                    int fileCloseStatus = NativeMethods.NetFileClose(null, fileInfo.fi3_id);
                    if (fileCloseStatus != NativeMethods.ERROR_SUCCESS)
                    {
                        DeployerTrace.WriteWarning(string.Format("Could not close resource {0}. Error code: {1}", fileInfo.fi3_pathname, fileCloseStatus));
                    }
                }

                NativeMethods.NetApiBufferFree(buffer);
            }
        }
        internal static IPAddress GetSubnetMask(NetworkInterface nic, IPAddress ipAddress, string networkAdapterName)
        {
            DeployerTrace.WriteInfo("Getting subnet mask for IP address {0} and network adapter {1}", ipAddress, networkAdapterName);

            IPInterfaceProperties ipProperties = nic.GetIPProperties();

            if (ipProperties == null)
            {
                var message = string.Format(
                    CultureInfo.CurrentUICulture,
                    StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorGettingSubnetMask1, networkAdapterName);

                DeployerTrace.WriteWarning(message);
                throw new InvalidOperationException(message);
            }

            UnicastIPAddressInformationCollection ipInfos = ipProperties.UnicastAddresses;

            foreach (UnicastIPAddressInformation ipInfo in ipInfos)
            {
                // ToString() is the only valid way to get the IP address. There is no other explicit property
                if (string.Equals(ipInfo.Address.ToString(), ipAddress.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    DeployerTrace.WriteInfo("Successfully obtained subnet mask {0} for IP address {1} and network adapter {2}", ipInfo.IPv4Mask, ipAddress, networkAdapterName);
                    return(ipInfo.IPv4Mask);
                }
            }

            var message2 = string.Format(
                CultureInfo.CurrentUICulture,
                StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorGettingSubnetMask2, ipAddress, networkAdapterName);

            DeployerTrace.WriteWarning(message2);
            throw new InvalidOperationException(message2);
        }
Beispiel #5
0
        public void Merge(UnreliableTransportSettings unreliableTransportSettings)
        {
            Dictionary <string, UnreliableTransportSpecification> specificationsDictionary = new Dictionary <string, UnreliableTransportSpecification>();

            // populate dictionary with this settings
            foreach (var specification in Specification)
            {
                specificationsDictionary.Add(specification.Name, specification);
            }

            // now we merge the settings with precedence of specifications coming from this
            foreach (var specification in unreliableTransportSettings.Specification)
            {
                if (specificationsDictionary.ContainsKey(specification.Name) == false)
                {
                    specificationsDictionary.Add(specification.Name, specification);
                }
                else
                {
                    specificationsDictionary[specification.Name] = specification;
                    DeployerTrace.WriteWarning("Conflicting Unreliable Transport Behavior when merging named {0}. Replacing with new behavior", specification.Name);
                }
            }

            // removing previous specifications to populate with ones in dictionary
            Specification.Clear();
            Specification.AddRange(specificationsDictionary.Values);
        }
        /// <summary>
        /// Gets a new IP address to be reassigned to <see cref="SFNetworkAdapterName"/>.
        /// The new IP address is 1 more than Docker's DNS IP address.
        /// </summary>
        internal static IPAddress GetNewIPAddressForSFNic(IPAddress dockerDnsIPAddress)
        {
            var bytes = dockerDnsIPAddress.GetAddressBytes();

            try
            {
                checked
                {
                    bytes[3] += 1;
                }

                var newIP = new IPAddress(bytes);

                var message =
                    "New IP address for network adapter {0} is: {1}".ToFormat(SFNetworkAdapterName, newIP);
                DeployerTrace.WriteInfo(message);

                return(newIP);
            }
            catch (OverflowException ex)
            {
                var message = string.Format(
                    CultureInfo.CurrentUICulture,
                    StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorGettingNewIPAddress, SFNetworkAdapterName, dockerDnsIPAddress, ex);
                DeployerTrace.WriteWarning(message);
                throw;
            }
        }
        internal static IPAddress GetFirstUnicastAddress(NetworkInterface nic, string networkAdapterName)
        {
            DeployerTrace.WriteInfo("Getting first unicast address for network adapter {0}", networkAdapterName);

            IPInterfaceProperties ipProperties = nic.GetIPProperties();

            if (ipProperties == null)
            {
                var message = string.Format(
                    CultureInfo.CurrentUICulture,
                    StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorGettingSubnetMask1, networkAdapterName);

                DeployerTrace.WriteWarning(message);
                throw new InvalidOperationException(message);
            }

            UnicastIPAddressInformationCollection ipInfos = ipProperties.UnicastAddresses;

            foreach (UnicastIPAddressInformation ipInfo in ipInfos)
            {
                return(ipInfo.Address);
            }

            var message2 = string.Format(
                CultureInfo.CurrentUICulture,
                StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorGettingSubnetMask2, networkAdapterName);

            DeployerTrace.WriteWarning(message2);
            throw new InvalidOperationException(message2);
        }
Beispiel #8
0
 private static void RemoveNodeConfigurationXCopy(string machineName, bool deleteLog, string nodeName)
 {
     try
     {
         string fabricDataRoot = Utility.GetFabricDataRoot(machineName);
         if (string.IsNullOrEmpty(fabricDataRoot))
         {
             DeployerTrace.WriteWarning("FabricDataRoot on machine {0} is empty or not present; no current installation likely exists", machineName);
         }
         else
         {
             DeployerTrace.WriteInfo("FabricDataRoot on machine {0} is {1}", machineName, fabricDataRoot);
             FabricDeployerServiceController.GetServiceInStoppedState(machineName, Constants.FabricInstallerServiceName);
             WriteTargetInformationFile(fabricDataRoot, machineName, deleteLog, nodeName);
             RunInstallerService(machineName);
         }
         FabricDeployerServiceController.DeleteFabricInstallerService(machineName);
         Utility.DeleteRegistryKeyTree(machineName);
     }
     catch (TimeoutException)
     {
         DeployerTrace.WriteError("FabricInstallerSvc timeout on machine {0}. Cleaning up to avoid environment corruption.", machineName);
         SuppressExceptions(() => { FabricDeployerServiceController.StopHostSvc(machineName); });
         SuppressExceptions(() => { FabricDeployerServiceController.DeleteFabricHostService(machineName); });
         SuppressExceptions(() => { FabricDeployerServiceController.StopInstallerSvc(machineName); });
         SuppressExceptions(() => { FabricDeployerServiceController.DeleteFabricInstallerService(machineName); });
         SuppressExceptions(() => { Utility.DeleteRegistryKeyTree(machineName); });
         throw;
     }
 }
Beispiel #9
0
        internal static T GetRegistryKeyValue <T>(
            RegistryKey baseRegistryKey,
            string keyName,
            string valueName,
            T defaultValue)
        {
            baseRegistryKey.Validate("baseRegistryKey");
            keyName.Validate("keyName");
            valueName.Validate("valueName");

            DeployerTrace.WriteInfo("Getting key-value data for key name: {0}, value name: {1}", keyName, valueName);

            using (RegistryKey registryKey = baseRegistryKey.OpenSubKey(keyName))
            {
                if (registryKey == null)
                {
                    string message = "Error opening registry sub key: {0}, using default value: {1}".ToFormat(keyName, defaultValue);
                    DeployerTrace.WriteWarning(message);
                    return(defaultValue);
                }

                T value = (T)Registry.GetValue(registryKey.Name, valueName, defaultValue);

                DeployerTrace.WriteInfo(
                    "Value successfully obtained. Key name: {0}, reg value name: {1}, reg value: {2}", keyName,
                    valueName, value);
                return(value);
            }
        }
Beispiel #10
0
        internal static FileStream GetExclusiveFilestream(string fileName, FileMode fileMode = FileMode.Create, uint retryCount = Constants.FileOpenDefaultRetryAttempts)
        {
            FileStream fileStream = null;

            for (var i = 0; ; i += 1)
            {
                try
                {
                    fileStream = new FileStream(fileName, fileMode, FileAccess.ReadWrite, FileShare.None);
                    break;
                }
                catch (IOException e)
                {
                    if (i == retryCount)
                    {
                        throw;
                    }
                    DeployerTrace.WriteWarning("Transient error - {0}", e.Message);
                }

                Thread.Sleep(TimeSpan.FromMilliseconds(i * Constants.FileOpenDefaultRetryIntervalMilliSeconds));
            }
#if DotNetCoreClrLinux
            Helpers.UpdateFilePermission(fileName);
#endif
            return(fileStream);
        }
        private static async Task ExecuteAsync(Action func, string funcName)
        {
            for (int i = 0; i < MaxRetries; i++)
            {
                DeployerTrace.WriteInfo("Executing {0}, attempt {1} of {2}", funcName, i + 1, MaxRetries);

                try
                {
                    // all operations are idempotent, so retry from beginning is okay
                    func();
                    DeployerTrace.WriteInfo("Successfully completed {0}", funcName);
                    break;
                }
                catch (Exception ex)
                {
                    string message = string.Format(
                        CultureInfo.CurrentUICulture,
                        StringResources.Warning_FabricDeployer_DockerDnsSetup_RetryMessage1, funcName, i + 1, MaxRetries, ex);

                    if (i == MaxRetries - 1)
                    {
                        message += string.Format(CultureInfo.CurrentUICulture, StringResources.Warning_FabricDeployer_DockerDnsSetup_RetryExhausted, Environment.NewLine);
                        DeployerTrace.WriteWarning(message);
                        throw;
                    }

                    message += string.Format(CultureInfo.CurrentUICulture, StringResources.Warning_FabricDeployer_DockerDnsSetup_RetryContinue, Environment.NewLine);
                    DeployerTrace.WriteWarning(message);
                }

                await Task.Delay(TimeSpan.FromSeconds(RetryDelayInSeconds));
            }
        }
Beispiel #12
0
        protected override void OnExecuteOperation(DeploymentParameters parameters, ClusterManifestType targetClusterManifest, Infrastructure infrastructure)
        {
            DeployerTrace.UpdateConsoleLevel(EventLevel.Verbose);

            try
            {
                string currentNodeIPAddressOrFQDN = string.Empty;
                if ((infrastructure != null) && (infrastructure.InfrastructureNodes != null))
                {
                    foreach (var infraNode in infrastructure.InfrastructureNodes)
                    {
                        if (NetworkApiHelper.IsAddressForThisMachine(infraNode.IPAddressOrFQDN))
                        {
                            currentNodeIPAddressOrFQDN = infraNode.IPAddressOrFQDN;
                            break;
                        }
                    }
                }

                new DockerDnsHelper(parameters, currentNodeIPAddressOrFQDN).SetupAsync().GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                DeployerTrace.WriteWarning(
                    StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorContinuing2,
                    ex);
            }
        }
        private static void AclCert(CertId certId, string accountName)
        {
            X509Store store = null;

            try
            {
                store = new X509Store(certId.StoreName, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite | OpenFlags.OpenExistingOnly);

                X509Certificate2Collection certs = store.Certificates.Find(ConvertToX509FindType(certId.FindType), certId.FindValue, validOnly: false);
                if (certs == null || certs.Count == 0)
                {
                    DeployerTrace.WriteInfo("AclCert is skipped for {0} because it's not installed", certId);
                    return;
                }

                foreach (X509Certificate2 cert in certs)
                {
                    if (cert.PrivateKey == null)
                    {
                        DeployerTrace.WriteWarning("AclCert is skipped for {0} because its private key is null", certId);
                        continue;
                    }

                    RSACryptoServiceProvider privateKey = cert.PrivateKey as RSACryptoServiceProvider;
                    if (privateKey == null)
                    {
                        DeployerTrace.WriteWarning("AclCert is skipped for {0} because its private key type {1} is not supported ", certId, cert.PrivateKey.GetType());
                        continue;
                    }

                    CspParameters csp = new CspParameters(privateKey.CspKeyContainerInfo.ProviderType, privateKey.CspKeyContainerInfo.ProviderName, privateKey.CspKeyContainerInfo.KeyContainerName);
                    csp.Flags     = CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore;
                    csp.KeyNumber = (int)privateKey.CspKeyContainerInfo.KeyNumber;
#if !DotNetCoreClr
                    csp.CryptoKeySecurity = privateKey.CspKeyContainerInfo.CryptoKeySecurity;

                    CryptoKeyAccessRule accessRule = new CryptoKeyAccessRule(accountName, CryptoKeyRights.FullControl, AccessControlType.Allow);
                    csp.CryptoKeySecurity.AddAccessRule(accessRule);
#endif

                    using (RSACryptoServiceProvider newCsp = new RSACryptoServiceProvider(csp))
                    {
                        DeployerTrace.WriteInfo("AclCert success: {0}", certId);
                    }
                }
            }
            catch (Exception ex)
            {
                DeployerTrace.WriteError("AclCert error with {0}: {1}", certId, ex);
            }
            finally
            {
                if (store != null)
                {
                    store.Close();
                }
            }
        }
        internal static void AclClusterLevelCerts(ClusterManifestType clusterManifest)
        {
            DeployerTrace.WriteInfo("AclClusterLevelCerts: Enter");

            ClusterManifestTypeNodeType[] nodeTypes = clusterManifest.NodeTypes;
            if (nodeTypes == null)
            {
                DeployerTrace.WriteWarning("AclClusterLevelCerts: No node type is defined on the cluster manifest.");
                return;
            }

            IEnumerable <FabricCertificateType> certs = nodeTypes.Where(nodeType => nodeType.Certificates != null).Select(nodeType => nodeType.Certificates)
                                                        .SelectMany(certificates => new FabricCertificateType[]
            {
                certificates.ClientCertificate,
                certificates.ClusterCertificate,
                certificates.ServerCertificate
            }).Where(cert => cert != null);

            if (!certs.Any())
            {
                DeployerTrace.WriteWarning("AclClusterLevelCerts: No load cert is defined.");
                return;
            }

            List <CertId> certIds = new List <CertId>();

            foreach (FabricCertificateType cert in certs)
            {
                certIds.Add(new CertId(cert.X509FindType, cert.X509FindValue, cert.X509StoreName));
                if (!string.IsNullOrWhiteSpace(cert.X509FindValueSecondary) &&
                    cert.X509FindValueSecondary != cert.X509FindValue)
                {
                    certIds.Add(new CertId(cert.X509FindType, cert.X509FindValueSecondary, cert.X509StoreName));
                }
            }

            string accountName  = "NT AUTHORITY\\NETWORK SERVICE";
            string runasAccount = TryGetRunAsAccountName(clusterManifest);

            if (runasAccount != null)
            {
                accountName = runasAccount;
            }

            List <CertId> acledCertIds = new List <CertId>();

            foreach (CertId certId in certIds)
            {
                if (!acledCertIds.Any(p => p.Equals(certId)))
                {
                    DeployerTrace.WriteInfo("AclClusterLevelCerts: processing {0}", certId);
                    AclCert(certId, accountName);
                    acledCertIds.Add(certId);
                    DeployerTrace.WriteInfo("AclClusterLevelCerts: {0} processed", certId);
                }
            }
        }
Beispiel #15
0
 internal static string GetTempPath(string machineName)
 {
     try
     {
         return(GetTempPathInner(machineName));
     }
     catch (Exception exception)
     {
         DeployerTrace.WriteWarning(exception.ToString());
         throw;
     }
 }
Beispiel #16
0
 private static void SuppressExceptions(ExceptionExpectedMethod method)
 {
     try
     {
         method();
     }
     catch (Exception ex)
     {
         // Suppress any exception
         DeployerTrace.WriteWarning(String.Format("RemoveNodeConfigOperation Suppressed exception: {0}", ex));
     }
 }
Beispiel #17
0
        private static void DeletePlaScheduledTask(string taskName)
        {
            var args      = string.Format(@"/delete /tn \Microsoft\Windows\PLA\{0} /f", taskName);
            var errorCode = Utility.ExecuteCommand("schtasks", args);

            if (errorCode != SchtasksSuccessExitCode)
            {
                DeployerTrace.WriteWarning(
                    "Unable to remove scheduled task for performance counters. The command \"schtasks {0}\" failed with error code {1}.",
                    args,
                    errorCode);
            }
        }
        public async Task CleanupAsync()
        {
            DeployerTrace.WriteInfo("Starting DockerDnsHelper.CleanupAsync");

            try
            {
                await ExecuteAsync(CleanupInternal, "DockerDnsHelper.CleanupAsync");
            }
            catch (Exception ex)
            {
                DeployerTrace.WriteWarning(StringResources.Warning_FabricDeployer_DockerDnsSetup_CleanupError, ex);
            }

            DeployerTrace.WriteInfo("Completed DockerDnsHelper.CleanupAsync");
        }
        private static void CollectEventLogs()
        {
            DeployerTrace.WriteInfo(StringResources.Info_CollectingErrorLogs);
            EventLogQuery adminQuery       = new EventLogQuery(Constants.ServiceFabricAdminEventLogName, PathType.LogName, "*[System/Level=2]");
            EventLogQuery operationalQuery = new EventLogQuery(Constants.ServiceFabricOperationalEventLogName, PathType.LogName, "*[System/Level=2]");

            try
            {
                using (EventLogReader adminReader = new EventLogReader(adminQuery), operationalReader = new EventLogReader(operationalQuery))
                {
                    string path = Path.Combine(Utility.GetTempPath("localhost"), Constants.EventLogsFileName);
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }

                    DeployerTrace.WriteInfo(StringResources.Info_CopyingEventLogs, path);
                    using (StreamWriter tw = File.CreateText(path))
                    {
                        EventRecord adminEventRecord;
                        EventRecord operationalEventRecord;
                        while ((adminEventRecord = adminReader.ReadEvent()) != null)
                        {
                            tw.WriteLine(String.Format("{0} - {1} - {2} - {3}",
                                                       adminEventRecord.TimeCreated,
                                                       Environment.MachineName,
                                                       adminEventRecord.LevelDisplayName,
                                                       adminEventRecord.FormatDescription()));
                        }

                        while ((operationalEventRecord = operationalReader.ReadEvent()) != null)
                        {
                            tw.WriteLine(String.Format("{0} - {1} - {2} - {3}",
                                                       operationalEventRecord.TimeCreated,
                                                       Environment.MachineName,
                                                       operationalEventRecord.LevelDisplayName,
                                                       operationalEventRecord.FormatDescription()));
                        }
                    }
                }
            }
            catch (EventLogException e)
            {
                DeployerTrace.WriteWarning(StringResources.Error_IssueOccursWhenGetEventLogs, e);
            }
        }
        internal static IPAddress GetIPAddress(int interfaceIndex, bool throwOnError = true)
        {
            DeployerTrace.WriteInfo("Getting IP address for InterfaceIndex: {0}", interfaceIndex);

            string script    = "(Get-NetIPConfiguration -InterfaceIndex {0}).IPv4Address.IPAddress".ToFormat(interfaceIndex);
            var    psObjects = Utility.ExecutePowerShellScript(script, true);

            if (psObjects == null || psObjects.Count != 1 || psObjects[0] == null)
            {
                string message = string.Format(
                    CultureInfo.CurrentUICulture,
                    StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorGettingIPAddressForInterfaceIndex, interfaceIndex);
                DeployerTrace.WriteWarning(message);

                if (throwOnError)
                {
                    throw new InvalidOperationException(message);
                }

                return(null);
            }

            string ipAddress = psObjects[0].ToString();

            DeployerTrace.WriteInfo("Successfully obtained IP address: {0}", ipAddress);

            IPAddress ip;
            bool      status = IPAddress.TryParse(ipAddress, out ip);

            if (!status)
            {
                string message = string.Format(
                    CultureInfo.CurrentUICulture,
                    StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorParsingIPAddressForInterfaceIndex, ipAddress, interfaceIndex);
                DeployerTrace.WriteWarning(message);

                if (throwOnError)
                {
                    throw new InvalidOperationException(message);
                }

                return(null);
            }

            return(ip);
        }
        internal bool ValidateContainersFeature()
        {
            if (IsContainersFeaturePresent())
            {
                DeployerTrace.WriteInfo("{0} feature present", ContainersFeatureName);
                return(true);
            }

            // on a system where the above checks fail for some reason, then we can at least move forward
            if (deploymentParameters.ContinueIfContainersFeatureNotInstalled)
            {
                DeployerTrace.WriteWarning(StringResources.Warning_FabricDeployer_DockerDnsSetup_FeatureNotPresentContinuing, ContainersFeatureName);
                return(true);
            }

            DeployerTrace.WriteInfo("{0} feature not present. Not continuing further", ContainersFeatureName);
            return(false);
        }
        private void CleanupInternal()
        {
#if !DotNetCoreClr // Disable compiling on windows for now. Need to correct when porting FabricDeployer for windows.
            bool proceed = ValidateContainersFeature();
            if (!proceed)
            {
                return;
            }
#endif

            CleanupPersistedNetworkDetail(new List <string> {
                DnsServerIPAddressRegValue
            });
            RemoveFirewallRule();

#if !DotNetCoreClr // Disable compiling on windows for now. Need to correct when porting FabricDeployer for windows.
            NetworkInterface nic = GetNetworkAdapter(SFNetworkAdapterName);

            if (nic != null)
            {
                int interfaceIndex = GetInterfaceIndex(nic, SFNetworkAdapterName, false);
                if (interfaceIndex == -1)
                {
                    DeployerTrace.WriteWarning(StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorGettingInterfaceIndex, SFNetworkAdapterName);
                    return;
                }

                IPAddress ipAddress = GetIPAddress(interfaceIndex, false);
                if (ipAddress == null)
                {
                    DeployerTrace.WriteWarning(StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorGettingIPAddress, SFNetworkAdapterName);
                    return;
                }

                RemoveIPAddress(ipAddress, interfaceIndex);
                RemoveNetworkAdapter(SFNetworkAdapterName);
            }
            else
            {
                DeployerTrace.WriteWarning(StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorGettingNetworkAdapter3, SFNetworkAdapterName);
            }
#endif
        }
        public static bool IsContainersFeaturePresent()
        {
            try
            {
                DismPackageFeatureState featureState = DismHelper.GetFeatureState(ContainersFeatureName);

                switch (featureState)
                {
                case DismPackageFeatureState.DismStateInstallPending:
                case DismPackageFeatureState.DismStateInstalled:
                case DismPackageFeatureState.DismStateSuperseded:
                    return(true);
                }
            }
            catch (COMException ex)
            {
                // Dism COM errors aren't well understood yet across different OSes. TODO Handle specific error codes and throw the rest
                DeployerTrace.WriteWarning(StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorGettingFeatureState1, ContainersFeatureName, ex);
            }
            catch (DllNotFoundException ex)
            {
                // This happens on platforms that don't have dismapi.dll
                // https://technet.microsoft.com/en-us/library/hh825186.aspx
                DeployerTrace.WriteWarning(
                    StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorGettingFeatureState2,
                    ContainersFeatureName,
                    ex);
            }
            catch (Exception ex)
            {
                // Swallowing all!
                // Setup for Docker isn't a mainline scenario currently. Hence try and continue.
                // If an exception is thrown on an OS that has Docker, and setup doesn't continue, we have mitigation
                // steps on the VM by setting ContinueIfContainersFeatureNotInstalled.
                // E.g. FabricDeployer.exe /operation:DockerDnsSetup /continueIfContainersFeatureNotInstalled:true
                DeployerTrace.WriteWarning(
                    StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorGettingFeatureState3,
                    ContainersFeatureName,
                    ex);
            }

            return(false);
        }
Beispiel #24
0
        internal static void RemoveRegistryKeyValues(RegistryKey baseRegistryKey, string keyName, IList <string> valueNames)
        {
            baseRegistryKey.Validate("baseRegistryKey");
            keyName.Validate("keyName");
            valueNames.Validate("valueNames");

            DeployerTrace.WriteInfo("Removing key-value data for key name {0}", keyName);

            using (RegistryKey registryKey = baseRegistryKey.OpenSubKey(keyName, true))
            {
                if (registryKey == null)
                {
                    string message = "Error opening registry sub key. Continuing. Registry values have to be cleaned up manually. Reg key: {0}".ToFormat(keyName);
                    DeployerTrace.WriteWarning(message);
                    return;
                }

                foreach (var v in valueNames)
                {
                    try
                    {
                        registryKey.DeleteValue(v, false);

                        DeployerTrace.WriteInfo(
                            "Successfully created reg value. Reg key: {0}, reg value name: {1}",
                            keyName,
                            v);
                    }
                    catch (Exception ex)
                    {
                        string message =
                            "Error creating reg value. Continuing. This needs to be cleaned up manually. Reg key: {0}, reg value name: {1}, exception: {2}".ToFormat(
                                keyName,
                                v,
                                ex);

                        DeployerTrace.WriteWarning(message);
                    }
                }
            }

            DeployerTrace.WriteInfo("Key-value(s) successfully deleted for key name {0}", keyName);
        }
        internal static int GetInterfaceIndex(NetworkInterface nic, string networkAdapterName, bool throwOnError = true)
        {
            DeployerTrace.WriteInfo("Calling GetIPProperties() for network adapter {0}", networkAdapterName);
            IPInterfaceProperties ipProperties = nic.GetIPProperties();

            if (ipProperties == null)
            {
                var message = string.Format(
                    CultureInfo.CurrentUICulture,
                    StringResources.Warning_FabricDeployer_DockerDnsSetup_GetIPPropertiesError, networkAdapterName);

                DeployerTrace.WriteWarning(message);

                if (throwOnError)
                {
                    throw new InvalidOperationException(message);
                }

                return(-1);
            }

            DeployerTrace.WriteInfo("Calling GetIPv4Properties() for network adapter {0}", networkAdapterName);
            IPv4InterfaceProperties ipv4Properties = ipProperties.GetIPv4Properties();

            if (ipv4Properties == null)
            {
                var message = string.Format(
                    CultureInfo.CurrentUICulture,
                    StringResources.Warning_FabricDeployer_DockerDnsSetup_GetIPv4PropertiesError, networkAdapterName);

                DeployerTrace.WriteWarning(message);

                if (throwOnError)
                {
                    throw new InvalidOperationException(message);
                }

                return(-1);
            }

            DeployerTrace.WriteInfo("Returning InterfaceIndex: {0} for network adapter {1}", ipv4Properties.Index, networkAdapterName);
            return(ipv4Properties.Index);
        }
Beispiel #26
0
        internal static void DeleteRegistryKeyTree(string machineName)
        {
            try
            {
                DeployerTrace.WriteInfo("Deleting Fabric registry key tree for machine {0}", machineName);
                RegistryKey baseKey = string.IsNullOrEmpty(machineName)
                    ? Registry.LocalMachine
                    : RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName);

                if (baseKey.OpenSubKey(FabricConstants.FabricRegistryKeyPath) != null)
                {
                    baseKey.DeleteSubKeyTree(FabricConstants.FabricRegistryKeyPath);
                }
            }
            catch (ArgumentException e)
            {
                DeployerTrace.WriteWarning("Trying to delete registry key tree threw ArgumentException: {0}", e.ToString());
            }
        }
Beispiel #27
0
        internal static string GetCurrentCodeVersion(string packageLocation)
        {
#if DotNetCoreClrLinux
            string currentAssembly = typeof(Utility).GetTypeInfo().Assembly.Location;
            string versionFile     = Path.Combine(Path.GetDirectoryName(currentAssembly), "ClusterVersion");
            string codeVersion     = File.ReadAllText(versionFile);
            return(codeVersion);
#else
            if (string.IsNullOrEmpty(packageLocation))
            {
                string currentAssembly = typeof(Utility).GetTypeInfo().Assembly.Location;
                string fabricPath      = Path.Combine(Path.GetDirectoryName(currentAssembly), Constants.FabricExe);

                if (!File.Exists(fabricPath))
                {
                    DeployerTrace.WriteWarning("{0} Fabric Path doesn't exist", fabricPath);

                    string codePath = GetFabricCodePath();
                    if (!string.IsNullOrEmpty(codePath))
                    {
                        fabricPath = Path.Combine(codePath, Constants.FabricExe);
                        if (!File.Exists(fabricPath))
                        {
                            DeployerTrace.WriteWarning("{0} Code Path doesn't exist", fabricPath);
                            codePath = null;
                        }
                    }

                    if (string.IsNullOrEmpty(codePath))
                    {
                        string errorMessage = string.Format("Fabric.exe not found in current execution assembly directory. CurrentAssembly : {0}, Fabric Path : {1}", currentAssembly, fabricPath);
                        throw new InvalidOperationException(errorMessage);
                    }
                }
                var versionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(fabricPath);
                return(string.Format(CultureInfo.InvariantCulture, Constants.FabricVersions.CodeVersionPattern, versionInfo.ProductMajorPart, versionInfo.ProductMinorPart, versionInfo.ProductBuildPart, versionInfo.ProductPrivatePart));
            }
            else
            {
                return(CabFileOperations.GetCabVersion(packageLocation));
            }
#endif
        }
 private static void DeleteTargetInformationFile(string targetInformationFile)
 {
     if (FabricFile.Exists(targetInformationFile))
     {
         try
         {
             DeployerTrace.WriteInfo("Attempting to delete TargetInformationFile.");
             FabricFile.Delete(targetInformationFile, true);
         }
         catch (Exception ex)
         {
             DeployerTrace.WriteError("Failed to delete: {0}. Exception: {1}.", targetInformationFile, ex);
             throw;
         }
     }
     else
     {
         DeployerTrace.WriteWarning("TargetInformationFile does not exist.");
     }
 }
Beispiel #29
0
        internal static bool IsContainersFeaturePresent()
        {
            try
            {
                DismPackageFeatureState featureState = DismHelper.GetFeatureState(Constants.ContainersFeatureName);

                switch (featureState)
                {
                case DismPackageFeatureState.DismStateInstallPending:
                case DismPackageFeatureState.DismStateInstalled:
                case DismPackageFeatureState.DismStateSuperseded:
                    return(true);
                }
            }
            catch (COMException ex)
            {
                // Dism COM errors aren't well understood yet across different OSes. TODO Handle specific error codes and throw the rest
                DeployerTrace.WriteWarning("Error getting feature state for feature {0}. Treating feature as not present and continuing. Exception: {1}", Constants.ContainersFeatureName, ex);
            }
            catch (DllNotFoundException ex)
            {
                // This happens on platforms that don't have dismapi.dll
                // https://technet.microsoft.com/en-us/library/hh825186.aspx
                DeployerTrace.WriteWarning(
                    "Error getting feature state for feature {0}. This usually means that the platform doesn't support DISM APIs. " +
                    "Treating feature as not present and continuing. Exception: {1}",
                    Constants.ContainersFeatureName,
                    ex);
            }
            catch (Exception ex)
            {
                // Swallowing all!
                DeployerTrace.WriteWarning(
                    "Unexpected error getting feature state for feature {0}. " +
                    "Treating feature as not present and continuing. Exception: {1}",
                    Constants.ContainersFeatureName,
                    ex);
            }

            return(false);
        }
        internal static void CleanupPersistedNetworkDetail(IList <string> valueNames)
        {
            try
            {
#if !DotNetCoreClrLinux
                Utility.RemoveRegistryKeyValues(Registry.LocalMachine, FabricConstants.FabricRegistryKeyPath, valueNames);
#else
                foreach (var name in valueNames)
                {
                    string path = Path.Combine(FabricEtcConfigPath, name);
                    File.Delete(path);
                }
#endif
                DeployerTrace.WriteInfo("Persisted network details cleaned up");
            }
            catch (Exception ex)
            {
                // best effort
                DeployerTrace.WriteWarning(StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorCleaningNetworkDetails, ex);
            }
        }