Exemplo n.º 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;
                }
            }
        }
Exemplo n.º 2
0
        private void GenerateCodeDeployment()
        {
            if (!this.nodeSettings.DeploymentFoldersInfo.IsCodeDeploymentNeeded)
            {
                return;
            }

            foreach (string service in this.servicesToBeDeployed)
            {
                string destinationFolder = this.nodeSettings.DeploymentFoldersInfo.GetCodeDeploymentDirectory(service);
                string sourceFolder      = this.nodeSettings.DeploymentFoldersInfo.GetInstalledBinaryDirectory(service);
                if (IsCodeDeploymentNeeded(service, sourceFolder, destinationFolder))
                {
                    try
                    {
                        FabricDirectory.Copy(sourceFolder, destinationFolder, true);
                    }
                    catch (Exception e)
                    {
                        DeployerTrace.WriteError("Code deployment failed because: {0}. Source folder: {1}. destinationFolder: {2}", e, sourceFolder, destinationFolder);
                        throw;
                    }
                }
            }
        }
Exemplo n.º 3
0
        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);
            }
        }
        private void EnsureImageStoreForSingleMachineDeployment(string defaultImageStoreRoot)
        {
            SettingsOverridesTypeSection managementSection = this.manifest.FabricSettings.FirstOrDefault(
                section => section.Name.Equals(Constants.SectionNames.Management, StringComparison.OrdinalIgnoreCase));

            SettingsOverridesTypeSectionParameter imageStoreParameter = null;

            if (managementSection != null)
            {
                imageStoreParameter = managementSection.Parameter.FirstOrDefault(
                    parameter => parameter.Name.Equals(Constants.ParameterNames.ImageStoreConnectionString, StringComparison.OrdinalIgnoreCase));
            }

            if (imageStoreParameter == null)
            {
                return;
            }

            SecureString imageStoreRoot = fabricValidator.ImageStoreConnectionString;

            char[] secureImageStoreChars = Utility.SecureStringToCharArray(imageStoreRoot);

            if ((secureImageStoreChars == null) || (new string(secureImageStoreChars)).Equals(Constants.DefaultTag, StringComparison.OrdinalIgnoreCase))
            {
                var imageStoreIncomingFolder = Path.Combine(defaultImageStoreRoot, Constants.DefaultImageStoreIncomingFolderName);
                if (!Directory.Exists(imageStoreIncomingFolder))
                {
                    Directory.CreateDirectory(imageStoreIncomingFolder);
                }
                DeployerTrace.WriteInfo("Default ImageStore incoming folder: {0}", imageStoreIncomingFolder);

                imageStoreParameter.Value       = string.Format(CultureInfo.InvariantCulture, "{0}{1}", System.Fabric.FabricValidatorConstants.FileImageStoreConnectionStringPrefix, defaultImageStoreRoot);
                imageStoreParameter.IsEncrypted = false;
            }
        }
Exemplo n.º 5
0
        internal void ExecuteOperation(string containerNetworkName, string containerServiceArguments, string fabricDataRoot, DeploymentOperations operation = DeploymentOperations.None)
        {
            if (operation == DeploymentOperations.UpdateInstanceId)
            {
                DeployerTrace.WriteInfo("Skipping Container network clean up invoked in context: {0}", operation);
                return;
            }

            if (!Utility.IsContainersFeaturePresent())
            {
                DeployerTrace.WriteInfo("Skipping container network clean up since containers feature has been disabled.");
                return;
            }

#if !DotNetCoreClrLinux
            if (!Utility.IsContainerNTServicePresent())
            {
                DeployerTrace.WriteInfo("Skipping container network clean up since containers NT service is not installed.");
                return;
            }
#endif

            // Wire server check is being made for the edge cluster scenario,
            // so that clean up is a noop. Wire server is not explicitly needed
            // for the clean up process.
            if (!IsWireServerAvailable())
            {
                DeployerTrace.WriteInfo("Skipping container network clean up since wire server is not available.");
                return;
            }

            containerNetworkName      = (!string.IsNullOrEmpty(containerNetworkName)) ? (containerNetworkName) : (FlatNetworkConstants.NetworkName);
            containerServiceArguments = (!string.IsNullOrEmpty(containerServiceArguments)) ? (containerServiceArguments) : (FlatNetworkConstants.ContainerServiceArguments);

            if (string.IsNullOrEmpty(fabricDataRoot))
            {
                fabricDataRoot = Utility.GetFabricDataRoot();
                DeployerTrace.WriteInfo("Fabric data root passed in was empty, using environment fabric data root instead: {0}.", fabricDataRoot);
            }

            DeployerTrace.WriteInfo("Container network clean up invoked in context: {0}", operation);

            bool containerServiceRunning = false;
            if (operation == DeploymentOperations.Update || operation == DeploymentOperations.UpdateInstanceId)
            {
                containerServiceRunning = IsContainerServiceRunning();
                DeployerTrace.WriteInfo("Container service running: {0}", containerServiceRunning);
            }

            if (CleanupContainerNetwork(containerNetworkName, containerServiceArguments, fabricDataRoot, containerServiceRunning))
            {
                DeployerTrace.WriteInfo("Successfully cleaned up container network.");
            }
            else
            {
                string message = "Failed to clean up container network.";
                DeployerTrace.WriteError(message);
                throw new InvalidDeploymentException(message);
            }
        }
        // Checks if current node should be removed for Windows Server deployments only.
        private bool ShouldRemoveCurrentNode(string nodeName, ClusterManifestType clusterManifest)
        {
            var infrastructureType = clusterManifest.Infrastructure.Item as ClusterManifestTypeInfrastructureWindowsServer;

            // For deployments that are not standalone, this section will not be present. Continue update operation for this node as is.
            if (infrastructureType == null)
            {
                DeployerTrace.WriteInfo("Node section not found in cluster manifest infrastructure section.");
                return(false);
            }

            if (nodeName == null)
            {
                return(false);
            }
            else
            {
                var nodesToBeRemovedSection = clusterManifest.FabricSettings.FirstOrDefault(section => section.Name.Equals(Constants.SectionNames.Setup, StringComparison.OrdinalIgnoreCase) &&
                                                                                            section.Parameter != null &&
                                                                                            section.Parameter.Any(parameter => parameter.Name.Equals(Constants.ParameterNames.NodesToBeRemoved)));
                List <string> nodesToRemove = new List <string>();
                if (nodesToBeRemovedSection != null)
                {
                    nodesToRemove = nodesToBeRemovedSection.Parameter.First(parameter => parameter.Name.Equals(Constants.ParameterNames.NodesToBeRemoved, StringComparison.OrdinalIgnoreCase)).Value.Split(',').Select(p => p.Trim()).ToList();
                }

                bool isNodeToBeRemoved = !infrastructureType.NodeList.Any(n => n.NodeName == nodeName) && nodesToRemove.Contains(nodeName);
                DeployerTrace.WriteInfo("Checking if current node needs to be removed : {0}", isNodeToBeRemoved);
                return(isNodeToBeRemoved);
            }
        }
Exemplo n.º 7
0
        private static void RemoveLogicalDirectoies(ClusterManifestType clusterManifest, FabricNodeType[] nodelist, string machineName)
        {
            List <LogicalDirectoryType[]> LogicalDirectoriesSetForThisMachine = new List <LogicalDirectoryType[]>();

            foreach (var node in nodelist)
            {
                var LogicalDirectory = clusterManifest.NodeTypes.Where(nodeType => nodeType.Name == node.NodeTypeRef).First().LogicalDirectories;
                if (LogicalDirectory != null)
                {
                    LogicalDirectoriesSetForThisMachine.Add(LogicalDirectory);
                }
            }

            if (LogicalDirectoriesSetForThisMachine.Any())
            {
                foreach (LogicalDirectoryType[] LogicalDirectories in LogicalDirectoriesSetForThisMachine)
                {
                    foreach (LogicalDirectoryType dir in LogicalDirectories)
                    {
                        try
                        {
                            Helpers.DeleteDirectoryIfExist(dir.MappedTo, machineName);
                        }
                        catch (Exception e)
                        {
                            DeployerTrace.WriteError(StringResources.Error_FailedToRemoveLogicalDirectory, dir.MappedTo, machineName, e);
                        }
                    }
                }
            }
        }
Exemplo n.º 8
0
        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);
        }
Exemplo n.º 9
0
        internal static int GetPrefixLength(IPAddress subnetMask, string networkAdapterName)
        {
            subnetMask.Validate("subnetMask");

            DeployerTrace.WriteInfo("Getting prefix length of subnet mask {0} and network adapter {1}", subnetMask, networkAdapterName);

            byte[] bytes = subnetMask.GetAddressBytes();

            int count = 0;

            foreach (var b in bytes)
            {
                // preferring over right-shift till b is 0, since right-shift may pad with 1 in some cases
                byte mask = 1;
                for (byte i = 0; i < sizeof(byte) * 8; i++, mask <<= 1)
                {
                    if ((b & mask) != 0)
                    {
                        count++;
                    }
                }
            }

            DeployerTrace.WriteInfo("Successfully obtained prefix length of subnet mask {0} and network adapter {1}. Prefix length: {2}", subnetMask, networkAdapterName, count);
            return(count);
        }
Exemplo n.º 10
0
        internal static void RemoveNetworkAdapter(string networkAdapterName)
        {
            DeployerTrace.WriteInfo("Removing network adapter {0}...", networkAdapterName);

            string script = "Remove-VMNetworkAdapter -Name {0} -ManagementOS -SwitchName {1}"
                            .ToFormat(networkAdapterName, SwitchName);

            var psObjects = Utility.ExecutePowerShellScript(script, false);

            if (psObjects != null)
            {
                DeployerTrace.WriteInfo("PowerShell Invoke completed and returned {0} objects", psObjects.Count);

                foreach (var psObject in psObjects)
                {
                    DeployerTrace.WriteInfo("{0}", psObject);
                }
            }
            else
            {
                DeployerTrace.WriteInfo("PowerShell Invoke completed and returned null");
            }

            DeployerTrace.WriteInfo("Network adapter {0} removed successfully", networkAdapterName);
        }
Exemplo n.º 11
0
        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);
        }
Exemplo n.º 12
0
        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));
            }
        }
        internal static void DeleteService(string machineName, string serviceName)
        {
            IntPtr svcHandle = IntPtr.Zero;

            try
            {
                svcHandle = GetServiceHandle(machineName, serviceName, null, false);
                if (svcHandle == IntPtr.Zero)
                {
                    return;
                }

                if (NativeMethods.DeleteService(svcHandle) == false)
                {
                    string errorMessage = string.Format(CultureInfo.InvariantCulture,
                                                        StringResources.Error_DeleteServiceReturnsErrorCodeWhileDeletingFabricInstallerService, machineName, Utility.GetWin32ErrorMessage(Marshal.GetLastWin32Error()));
                    DeployerTrace.WriteError(errorMessage);
                    throw new InvalidOperationException(errorMessage);
                }
            }
            finally
            {
                if (svcHandle != IntPtr.Zero)
                {
                    NativeMethods.CloseServiceHandle(svcHandle);
                }
            }
        }
Exemplo n.º 14
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);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Retrieves network interface that is on the given subnet.
        /// </summary>
        public static NetworkInterface GetNetworkInterfaceOnSubnet(string subnet)
        {
            DeployerTrace.WriteInfo("Getting network interface with ip address on subnet {0}.", subnet);

            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                IPAddress ipv4Address;
                IPAddress ipv4Mask;
                GetDefaultIPV4AddressAndMask(nic, out ipv4Address, out ipv4Mask);

                // Calculate subnet by ANDing ip address and mask
                var networkAddress       = GetNetworkAddress(ipv4Address, ipv4Mask);
                var networkAddressString = (networkAddress != null) ? (networkAddress.ToString()) : (string.Empty);

                DeployerTrace.WriteInfo("Network broadcast ip {0}", networkAddressString);

                if (string.Equals(networkAddressString, subnet))
                {
                    DeployerTrace.WriteInfo("Network interface with ip address on subnet {0} successfully obtained, name: {1}", subnet, nic.Name);
                    return(nic);
                }
            }

            DeployerTrace.WriteInfo("Unable to detect network interface with ip address on subnet {0}.", subnet);
            return(null);
        }
Exemplo n.º 16
0
        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);
            }
        }
Exemplo n.º 17
0
        private static void RemoveNodeConfigurationInner(bool deleteLog, FabricPackageType fabricPackageType, string machineName)
        {
            var parameters = new Dictionary <string, dynamic>
            {
                { DeploymentParameters.MachineNameString, machineName }
            };

            // Create DeploymentParameters object with conditional retrieval of FabricBinRoot (to work around infinite recursion due to invalid reflection)
            bool setBinRoot           = fabricPackageType != FabricPackageType.XCopyPackage;
            var  deploymentParameters = new DeploymentParameters(setBinRoot);

            deploymentParameters.DeleteLog             = deleteLog;
            deploymentParameters.DeploymentPackageType = fabricPackageType;
            deploymentParameters.SetParameters(parameters, DeploymentOperations.RemoveNodeConfig);

            try
            {
                DeploymentOperation.ExecuteOperation(deploymentParameters);
            }
            catch (Exception e)
            {
                DeployerTrace.WriteError("{0}", e.ToString());
                throw;
            }
        }
Exemplo n.º 18
0
        public DockerDnsHelper(DeploymentParameters parameters, string ipAddressOrFQDN)
        {
            DeployerTrace.WriteInfo("DockerDnsHelper current node IPAddressOrFQDN <{0}>", ipAddressOrFQDN);

            this.deploymentParameters = parameters ?? new DeploymentParameters();
            this.nodeIPAddressOrFQDN  = string.IsNullOrEmpty(ipAddressOrFQDN) ? string.Empty : ipAddressOrFQDN;
        }
Exemplo n.º 19
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);
        }
Exemplo n.º 20
0
        /// <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;
            }
        }
Exemplo n.º 21
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;
     }
 }
Exemplo n.º 22
0
        /// <summary>
        /// Checks that the network interface has the expected ip address.
        /// This is usually needed after the network has been set up, to allow time to plumb ip address.
        /// </summary>
        /// <param name="networkInterface"></param>
        /// <param name="expectedAddress"></param>
        /// <returns></returns>
        public static bool IsIPAddressMatching(NetworkInterface networkInterface, IPAddress expectedAddress)
        {
            bool matching = false;

            for (int i = 0; i < 5; i++)
            {
                DeployerTrace.WriteInfo("Waiting to match ip address {0} on network interface {1}.", expectedAddress.ToString(), networkInterface.Name);

                Thread.Sleep(3000);

                IPAddress ipv4Address = null;
                IPAddress ipv4Mask    = null;
                Utility.GetDefaultIPV4AddressAndMask(networkInterface, out ipv4Address, out ipv4Mask);

                if (ipv4Address != null && IPAddress.Equals(ipv4Address, expectedAddress))
                {
                    matching = true;
                    break;
                }
            }

            DeployerTrace.WriteInfo("Matched ip address {0} on network interface {1}:{2}.", expectedAddress.ToString(), networkInterface.Name, matching);

            return(matching);
        }
Exemplo n.º 23
0
        public static int Main(string[] args)
        {
            string argsString = string.Join(" ", args);

            try
            {
                DeployerTrace.WriteInfo("Deployer called with {0}", argsString);
                DeploymentParameters parameters = CommandLineInfo.Parse(args);
                DeploymentOperation.ExecuteOperation(parameters, false);
                return(Constants.ErrorCode_Success);
            }
            catch (FabricHostRestartRequiredException e)
            {
                DeployerTrace.WriteInfo(e.ToString());
                return(Constants.ErrorCode_RestartRequired);
            }
            catch (FabricHostRestartNotRequiredException e)
            {
                DeployerTrace.WriteInfo(e.ToString());
                return(Constants.ErrorCode_RestartNotRequired);
            }
            catch (Exception e)
            {
                DeployerTrace.WriteError("Deployer failed with args: {0}", argsString);
                DeployerTrace.WriteError(e.ToString());
                return(Constants.ErrorCode_Failure);
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Retrieves last boot up time using WMI.
        /// </summary>
        /// <returns></returns>
        public static DateTime GetNodeLastBootUpTimeFromSystem()
        {
            DateTime lastBootUpTime = DateTime.MinValue.ToUniversalTime();

            try
            {
                var searcher           = new ManagementObjectSearcher("SELECT LastBootUpTime FROM Win32_OperatingSystem WHERE Primary = 'true'");
                var nodeInfoCollection = searcher.Get();
                if (nodeInfoCollection != null)
                {
                    var nodeInfoArray = new ManagementBaseObject[nodeInfoCollection.Count];
                    nodeInfoCollection.CopyTo(nodeInfoArray, 0);
                    if (nodeInfoArray.Length == 1)
                    {
                        lastBootUpTime = ManagementDateTimeConverter.ToDateTime(nodeInfoArray[0]["LastBootUpTime"].ToString()).ToUniversalTime();
                    }
                }
            }
            catch (Exception ex)
            {
                DeployerTrace.WriteError("Failed to retrieve node last boot up time exception {0}", ex);
            }

            return(lastBootUpTime);
        }
Exemplo n.º 25
0
        private int DeploySeedInfoFile()
        {
            Dictionary <string, string> seedMapping = infrastructure.VoteMappings;

            if (seedMapping == null)
            {
                return(Constants.ErrorCode_Success);
            }
            string dataRoot         = nodeSettings.DeploymentFoldersInfo.DataRoot;
            string seedInfoFileName = Path.Combine(dataRoot, Constants.FileNames.SeedInfo);

            try
            {
                using (FileStream fileStream = new FileStream(seedInfoFileName, FileMode.Create, FileAccess.Write, FileShare.Read))
                {
                    using (TextWriter writer = new StreamWriter(fileStream))
                    {
                        writer.WriteLine(Constants.SectionNames.SeedMapping);
                        seedMapping.ForEach(pair => writer.WriteLine("  {0} = {1}", pair.Key, pair.Value));
                    }
                }
                DeployerTrace.WriteInfo("Generated SeedInfoFile successfully");
            }
            catch (Exception e)
            {
                DeployerTrace.WriteError("Unable to generated SeedInfoFile because {0}", e);
                throw;
            }
            return(Constants.ErrorCode_Success);
        }
Exemplo n.º 26
0
        internal static int ExecuteCommand(string command, string arguments, TimeSpan timeout)
        {
            string workingDir = Directory.GetCurrentDirectory();

            DeployerTrace.WriteInfo("Executing command: {0} {1}", command, arguments);
            using (Process p = new Process())
            {
                p.StartInfo.FileName         = command;
                p.StartInfo.Arguments        = arguments;
                p.StartInfo.UseShellExecute  = false;
                p.StartInfo.CreateNoWindow   = true;
                p.StartInfo.WorkingDirectory = workingDir;
                p.Start();

                if (timeout == TimeSpan.MaxValue)
                {
                    p.WaitForExit();
                }
                else
                {
                    if (!p.WaitForExit((int)timeout.TotalMilliseconds))
                    {
                        p.Kill();
                        DeployerTrace.WriteInfo("Execution of command {0} {1} timedout after {2} milliseconds", command, arguments, timeout.TotalMilliseconds);
                        return(Constants.ErrorCode_Failure);
                    }
                }

                return(p.ExitCode);
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// This method copies the latest ClusterSettings File to Fabric Data.
        /// The latest copy is determined by the version number in the filename.
        /// If the version number is the same in fabric data root and fabric code path, the one in fabric data root is copied.
        /// </summary>
        private void CopyClusterSettingsToFabricData()
        {
            string sourceClusterSettingsPathInFabricDataRoot = Directory.EnumerateFiles(this.nodeSettings.DeploymentFoldersInfo.DataRoot, Constants.FileNames.ClusterSettings).SingleOrDefault();
            string sourceClusterSettingsPathInFabricCode     = Directory.EnumerateFiles(FabricEnvironment.GetCodePath(), Constants.FileNames.ClusterSettings).SingleOrDefault();
            var    destClusterSettingsPath = Path.Combine(this.nodeSettings.DeploymentFoldersInfo.DataDeploymentDirectory, Constants.FileNames.ClusterSettings);

            if (sourceClusterSettingsPathInFabricDataRoot == null && sourceClusterSettingsPathInFabricCode != null)
            {
                try
                {
                    File.Copy(sourceClusterSettingsPathInFabricCode, destClusterSettingsPath, true);
                }
                catch (Exception e)
                {
                    DeployerTrace.WriteError("Code deployment failed because: {0}. Source Path: {1}. destinationFolder: {2}", e, sourceClusterSettingsPathInFabricCode, destClusterSettingsPath);
                    throw;
                }
            }
            else if (sourceClusterSettingsPathInFabricDataRoot != null && sourceClusterSettingsPathInFabricCode != null)
            {
                try
                {
                    File.Copy(sourceClusterSettingsPathInFabricDataRoot, destClusterSettingsPath, true);
                }
                catch (Exception e)
                {
                    DeployerTrace.WriteError("Code deployment failed because: {0}. Source Path: {1}. destinationFolder: {2}", e, sourceClusterSettingsPathInFabricCode, destClusterSettingsPath);
                    throw;
                }
            }
        }
Exemplo n.º 28
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);
            }
        }
        private void CopyBaselinePackageIfPathExists(string bootstrapPackagePath, string fabricDataRoot, FabricPackageType fabricPackageType, string machineName)
        {
            string targetPath = Helpers.GetRemotePath(fabricDataRoot, machineName);

            DeployerTrace.WriteInfo("Copying {0} from {1} to {2}", fabricPackageType == FabricPackageType.MSI ? "BootstrapMSI" : "Standalone CAB", bootstrapPackagePath, fabricDataRoot);
            if (fabricPackageType == FabricPackageType.XCopyPackage)
            {
                targetPath = Path.Combine(targetPath, Constants.FileNames.BaselineCab);
            }
            else
            {
                targetPath = Path.Combine(targetPath, Path.GetFileName(bootstrapPackagePath));
            }

            using (FileStream sourceStream = File.Open(bootstrapPackagePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (FileStream destStream = File.Create(targetPath))
                {
                    sourceStream.CopyTo(destStream);
                }
            }
            if (!File.Exists(targetPath))
            {
                string message = string.Format(StringResources.Error_SFErrorCreatingCab, targetPath, machineName);
                DeployerTrace.WriteError(message);
                throw new FileNotFoundException(message);
            }
            string adminConfigPath = Environment.GetEnvironmentVariable(Constants.FabricTestAdminConfigPath);

            if (!string.IsNullOrEmpty(adminConfigPath))
            {
                CopyNewAdminConfigToFabricDataRoot(fabricDataRoot, adminConfigPath, machineName);
            }
        }
Exemplo n.º 30
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);
        }