/// <summary>
        /// Creates docker network using the cns plugin.
        /// </summary>
        /// <param name="networkName"></param>
        /// <returns></returns>
        private bool CreateNetwork(string networkName)
        {
            bool success = false;

            DeployerTrace.WriteInfo("Creating network Name:{0} using cns plugin.", networkName);

            try
            {
                string dockerNetworkId   = string.Empty;
                string dockerNetworkName = string.Empty;
                if (GetNetwork(networkName, out dockerNetworkName, out dockerNetworkId) && !string.IsNullOrEmpty(dockerNetworkId))
                {
                    DeployerTrace.WriteInfo("Skipping network creation since network {0} already exists.", networkName);
                    return(true);
                }

                // Initialize network configuration
                var initReq = new InitializeRequest
                {
                    Location    = FlatNetworkConstants.NetworkEnvAzure,
                    NetworkType = FlatNetworkConstants.UnderlayNetworkType
                };

                var initRes = httpClient.PostAsync(
                    FlatNetworkConstants.NetworkEnvInitializationUrl,
                    new StringContent(JsonConvert.SerializeObject(initReq), Encoding.UTF8, "application/json")
                    ).GetAwaiter().GetResult();

                string response = initRes.Content.ReadAsStringAsync().GetAwaiter().GetResult();

                if (!initRes.IsSuccessStatusCode)
                {
                    DeployerTrace.WriteError("Failed to initialize network environment Name:{0} error details {1}.", networkName, response);
                    return(success);
                }

                var initResult = JsonConvert.DeserializeObject <CnsResponse>(response);
                if (initResult.ReturnCode != 0)
                {
                    DeployerTrace.WriteWarning(
                        "Network Name:{0} environment initialize returned error code {1}, message {2}",
                        networkName,
                        initResult.ReturnCode,
                        initResult.Message);
                    return(success);
                }

                // Create network
                var createNetworkReq = new CreateNetworkRequest
                {
                    NetworkName = networkName
                };

                var createNetworkRes = httpClient.PostAsync(
                    FlatNetworkConstants.NetworkCreateUrl,
                    new StringContent(JsonConvert.SerializeObject(createNetworkReq), Encoding.UTF8, "application/json")
                    ).GetAwaiter().GetResult();

                response = createNetworkRes.Content.ReadAsStringAsync().GetAwaiter().GetResult();

                if (!createNetworkRes.IsSuccessStatusCode)
                {
                    DeployerTrace.WriteError("Failed to create network Name:{0} error details {1}.", networkName, response);
                    return(success);
                }

                var createNetworkResult = JsonConvert.DeserializeObject <CnsResponse>(response);
                if (createNetworkResult.ReturnCode != 0)
                {
                    DeployerTrace.WriteWarning(
                        "Network Name:{0} network create returned error code {1}, message {2}",
                        networkName,
                        createNetworkResult.ReturnCode,
                        createNetworkResult.Message);
                    return(success);
                }

                success = true;
                DeployerTrace.WriteInfo("Network Name:{0} created successfully.", networkName);
            }
            catch (Exception ex)
            {
                DeployerTrace.WriteError("Failed to create network Name:{0} exception {1}.", networkName, ex);
            }

            return(success);
        }
        internal void ExecuteOperation(DeploymentParameters parameters, ClusterManifestType clusterManifest, Infrastructure infrastructure)
        {
#if !DotNetCoreClrLinux
            if (!(clusterManifest.Infrastructure.Item is ClusterManifestTypeInfrastructureWindowsAzure) &&
                !(clusterManifest.Infrastructure.Item is ClusterManifestTypeInfrastructurePaaS))
#else
            if (!(clusterManifest.Infrastructure.Item is ClusterManifestTypeInfrastructurePaaS))
#endif
            {
                DeployerTrace.WriteInfo("Skipping container network set up since we are not on Azure.");
                return;
            }

            if (!parameters.ContainerNetworkSetup)
            {
                DeployerTrace.WriteInfo("Skipping container network set up since it has been disabled.");
                return;
            }

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

            if (!Utility.IsContainerServiceInstalled())
            {
                DeployerTrace.WriteInfo("Skipping container network set up since containers service is not installed.");
                return;
            }

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

            if (!IsWireServerAvailable())
            {
                DeployerTrace.WriteInfo("Skipping container network set up since wire server is not available.");
                return;
            }

            var networkName = (!string.IsNullOrEmpty(parameters.ContainerNetworkName)) ? (parameters.ContainerNetworkName)
                : (FlatNetworkConstants.NetworkName);

            var containerServiceArguments = (parameters.UseContainerServiceArguments) ? (parameters.ContainerServiceArguments)
                : (FlatNetworkConstants.ContainerServiceArguments);

            DeployerTrace.WriteInfo("Container network set up invoked in context: {0}", parameters.Operation);

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

#if !DotNetCoreClrLinux
            containerServiceArguments = (parameters.EnableContainerServiceDebugMode)
                ? (string.Format("{0} {1}", containerServiceArguments, FlatNetworkConstants.ContainerProviderServiceDebugModeArg))
                : containerServiceArguments;
            if (SetupContainerNetwork(networkName, containerServiceArguments, parameters.FabricDataRoot, containerServiceRunning))
#else
            if (SetupContainerNetwork(networkName, containerServiceArguments, parameters.FabricDataRoot, parameters.FabricBinRoot, containerServiceRunning))
#endif
            {
                DeployerTrace.WriteInfo("Successfully set up container network.");
            }
            else
            {
                string message = "Failed to set up container network.";
                DeployerTrace.WriteError(message);
                throw new InvalidDeploymentException(message);
            }
        }
        /// <summary>
        /// Installs the azure network driver. This is the driver used to create the
        /// flat network to which containers with static IPs are added.
        /// </summary>
        private bool InstallNetworkDriver(string fabricBinRoot)
        {
            bool success = false;

            DeployerTrace.WriteInfo("Installing the network driver.");

            try
            {
                var pluginFullPath = Path.Combine(Path.Combine(fabricBinRoot, @"Fabric/Fabric.Code"), FlatNetworkConstants.NetworkDriverPlugin);
                DeployerTrace.WriteInfo("Network driver plugin path is {0}.", pluginFullPath);

                bool running;
                int  processId = 0;
                IsProcessRunning(FlatNetworkConstants.NetworkDriverPlugin, out running, out processId);
                if (running)
                {
                    DeployerTrace.WriteInfo("Skipping installation of network driver since it is already installed.");
                    return(true);
                }

                // Remove the azure vnet sock file if it exists.
                var command     = string.Format("sudo rm -f {0}", FlatNetworkConstants.AzureVnetPluginSockPath);
                int returnvalue = NativeHelper.system(command);
                if (returnvalue != 0)
                {
                    DeployerTrace.WriteInfo("Failed to execute command {0} return value {1}", command, returnvalue);
                    return(success);
                }

                DeployerTrace.WriteInfo("Successfully executed command \"{0}\".", command);

                // check ebtables dependency
                bool ebtablesInstalled = false;
                if (IsPackageInstalled(FlatNetworkConstants.EbtablesPackageName))
                {
                    DeployerTrace.WriteInfo("Ebtables package installed.");
                    ebtablesInstalled = true;
                }
                else
                {
                    DeployerTrace.WriteInfo("Ebtables package not installed.");
                }

                // start up cns plugin
                if (ebtablesInstalled)
                {
                    command     = string.Format("{0} {1}&", "sudo", pluginFullPath);
                    returnvalue = NativeHelper.system(command);
                    if (returnvalue != 0)
                    {
                        DeployerTrace.WriteInfo("Failed to execute command {0} with return value {1}.", command, returnvalue);
                        return(success);
                    }

                    DeployerTrace.WriteInfo("Successfully executed command \"{0}\".", command);

                    // Check if network driver is installed
                    for (int i = 0; i < Constants.ApiRetryAttempts; i++)
                    {
                        bool processRunning = false;
                        int  pid            = -1;
                        IsProcessRunning(FlatNetworkConstants.NetworkDriverPlugin, out processRunning, out pid);
                        if (processRunning)
                        {
                            DeployerTrace.WriteInfo("Successfully installed network driver.");
                            success = true;
                            break;
                        }
                        else
                        {
                            Thread.Sleep(Constants.ApiRetryIntervalMilliSeconds);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DeployerTrace.WriteError("Failed to install network driver exception {0}", ex);
            }

            return(success);
        }