示例#1
0
        /// <summary>
        /// This method generates the error file
        /// </summary>
        /// <param name="connectionString">The SFTP connection string</param>
        /// <param name="destPath">The complete path of the file to be created</param>
        /// <param name="content">The file contents</param>
        /// <returns></returns>
        private async Task CreateFile(string destPath, string content)
        {
            using (SftpClient sftp = CreateClient())
            {
                sftp.Connect();
                using (var streamWriter = sftp.CreateText(destPath))
                {
                    await streamWriter.WriteLineAsync(content);

                    streamWriter.Close();
                }
                sftp.Disconnect();
            }
        }
示例#2
0
 private bool CreateArgsFile(string path)
 {
     try
     {
         using (var writer = _sftpClient.CreateText(path))
         {
             var obj = new LinuxArgModel
             {
                 Remark = Remark ?? string.Empty,
                 Mac    = CodingHelper.GetMacAddress(),
                 Ip     = CodingHelper.GetLocalIPAddress(),
                 Pc     = Environment.MachineName
             };
             writer.WriteLine(JsonConvert.SerializeObject(obj));
             writer.Flush();
         }
         return(true);
     }
     catch (Exception ex)
     {
         _logger($"create deploy remark file fail: {path},err:{ex.Message}", NLog.LogLevel.Error);
         return(false);
     }
 }
示例#3
0
        private void SaveUniqueCode(DeployInfo info, SftpClient sftpClient)
        {
            var config = new ServerConfig
            {
                FloorId  = info.FloorId,
                MasterId = info.MasterId,
                Alias    = info.ServerAlias
            };

            var json = JsonConvert.SerializeObject(config);

            using (var fs = sftpClient.CreateText("/home/pi/Desktop/sp/config.json", Encoding.UTF8))
            {
                fs.Write(json);
            }
        }
示例#4
0
        public void UpdateConfig(DeployInfo info, ServerConfig newConfig)
        {
            using (var client = new SftpClient(info.Host, info.Port, info.UserName, info.Password))
            {
                client.Connect();

                var exists = client.Exists("/home/pi/Desktop/sp/config.json");
                if (exists)
                {
                    client.DeleteFile("/home/pi/Desktop/sp/config.json");
                }

                var json = JsonConvert.SerializeObject(newConfig);

                using (var fs = client.CreateText("/home/pi/Desktop/sp/config.json", Encoding.UTF8))
                {
                    fs.Write(json);
                }
            }
        }
示例#5
0
 //サーバー上にテキストファイルを作成(引数:Textに文字を入れると作成されたファイルに記述されます)
 public bool File_Create(string To_File, bool IsOverWrite, string Text = "", bool IsErrorLogMode = false)
 {
     if (!IsConnected)
     {
         return(false);
     }
     else if (!SFTP_Server.IsConnected)
     {
         SFTP_Server.Connect();
     }
     try
     {
         if (SFTP_Server.Exists(To_File) && !IsOverWrite)
         {
             return(true);
         }
         using (StreamWriter ostream = SFTP_Server.CreateText(To_File))
         {
             try
             {
                 ostream.Write(Text);
             }
             finally
             {
                 ostream.Close();
             }
         }
         return(true);
     }
     catch (Exception e)
     {
         if (IsErrorLogMode)
         {
             Sub_Code.Error_Log_Write(e.Message);
         }
         return(false);
     }
 }
示例#6
0
        private bool CreateDockerFile(string path)
        {
            try
            {
                string dllName = NetCoreENTRYPOINT;

                string sdkVersion = NetCoreVersion;
                if (string.IsNullOrEmpty(sdkVersion))
                {
                    sdkVersion = "2.1";
                }

                string port = NetCorePort;
                if (string.IsNullOrEmpty(port))
                {
                    port = "5000";
                }


                string environment = NetCoreEnvironment;

                _logger($"create docker file: {path}", NLog.LogLevel.Info);
                using (var writer = _sftpClient.CreateText(path))
                {
                    writer.WriteLine($"FROM microsoft/dotnet:{sdkVersion}-aspnetcore-runtime");
                    _logger($"FROM microsoft/dotnet:{sdkVersion}-aspnetcore-runtime", NLog.LogLevel.Info);

                    writer.WriteLine($"COPY . /publish");
                    _logger($"COPY . /publish", NLog.LogLevel.Info);

                    writer.WriteLine($"WORKDIR /publish");
                    _logger($"WORKDIR /publish", NLog.LogLevel.Info);

                    writer.WriteLine($"ENV ASPNETCORE_URLS=http://*:{port}");
                    _logger($"ENV ASPNETCORE_URLS=http://*:{port}", NLog.LogLevel.Info);

                    if (!string.IsNullOrEmpty(environment))
                    {
                        writer.WriteLine($"ENV ASPNETCORE_ENVIRONMENT={environment}");
                        _logger($"ENV ASPNETCORE_ENVIRONMENT={environment}", NLog.LogLevel.Info);
                    }

                    writer.WriteLine($"EXPOSE {port}");
                    _logger($"EXPOSE {port}", NLog.LogLevel.Info);

                    var excuteLine = $"ENTRYPOINT [\"dotnet\", \"{dllName}\"]";
                    //var excuteCMDLine = $"CMD [\"--server.urls\", \"http://*:{port}\"";

                    //if (!string.IsNullOrEmpty(environment))
                    //{
                    //     excuteCMDLine+= $",\"--environment\", \"{environment}\"";
                    //}
                    //excuteCMDLine+="]";
                    writer.WriteLine(excuteLine);
                    _logger(excuteLine, NLog.LogLevel.Info);
                    //writer.WriteLine(excuteCMDLine);
                    //_logger(excuteCMDLine);

                    if (!string.IsNullOrEmpty(this.Volume))
                    {
                        writer.WriteLine(volumeProfix + this.Volume + "@");
                        _logger(volumeProfix + this.Volume + "@", NLog.LogLevel.Info);
                    }

                    writer.Flush();
                }
                _logger($"create docker file success: {path}", NLog.LogLevel.Info);
                return(true);
            }
            catch (Exception ex)
            {
                _logger($"create docker file fail: {path},err:{ex.Message}", NLog.LogLevel.Error);
                return(false);
            }
        }
示例#7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="publishFolder">deploy文件目录</param>
        /// <param name="isrollBack"></param>
        /// <param name="isDefaultDockfile">上传的时候没有DockerFile要创建</param>
        public void DoDockerCommand(string publishFolder, bool isrollBack = false, bool isDefaultDockfile = false, string publishName = "publish")
        {
            string port        = string.Empty;
            string server_port = string.Empty;

            if (!publishFolder.EndsWith("/"))
            {
                publishFolder = publishFolder + "/";
            }
            //先查看本地是否有dockerFile
            var dockFilePath  = publishFolder + "Dockerfile";
            var dockFilePath2 = $"{(string.IsNullOrEmpty(publishName) ? "" : publishName + "/")}Dockerfile";
            // ReSharper disable once SimplifyConditionalTernaryExpression
            var isExistDockFile = isDefaultDockfile ? false : _sftpClient.Exists(dockFilePath2);

            //如果本地存在dockerfile 那么就根据此创建image
            //如果不存在的话 就根据当前的netcore sdk的版本 进行创建相对应的 dockfile

            if (!isExistDockFile)
            {
                if (isrollBack)
                {
                    _logger($"dockerFile is not exist: {dockFilePath}", LogLevel.Error);
                    return;
                }


                if (!isDefaultDockfile)
                {
                    var createDockerFileResult = CreateDockerFile(dockFilePath);
                    if (!createDockerFileResult)
                    {
                        return;
                    }
                }
            }
            else
            {
                //如果项目中存在dockerFile 那么check 该DockerFile的Expose是否配置了 没有配置就报错
                try
                {
                    var dockerFileText = _sftpClient.ReadAllText(dockFilePath);
                    if (string.IsNullOrEmpty(dockerFileText))
                    {
                        _logger($"dockerFile is empty: {dockFilePath}", LogLevel.Error);
                        return;
                    }
                    var needAddPort = false;
                    var newPort     = string.Empty;
                    var newPortA    = dockerFileText.Split(new string[] { "EXPOSE " }, StringSplitOptions.None);
                    if (newPortA.Length != 2)
                    {
                        needAddPort = true;
                    }
                    else
                    {
                        if (!newPortA[0].EndsWith("#"))
                        {
                            foreach (var item in newPortA[1].Trim())
                            {
                                if (Char.IsDigit(item))
                                {
                                    newPort += item;
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(newPort))
                    {
                        needAddPort = true;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(NetCorePort) && !this.ContainerPort.Equals(newPort))
                        {
                            _logger($"EXPOSE in dockerFile is defined,will use【{newPort}】replace【{ContainerPort}】", LogLevel.Warning);
                        }
                        else
                        {
                            _logger($"EXPOSE in dockerFile is : 【{newPort}】", LogLevel.Info);
                        }
                    }

                    //如果dockfile里面没有配置EXPOST 就用界面上提供的
                    port = needAddPort ? ContainerPort : newPort;

                    var volumeInDockerFile = string.Empty;
                    var volumeExist        = dockerFileText.Split(new string[] { volumeProfix }, StringSplitOptions.None);
                    if (volumeExist.Length == 2)
                    {
                        var temp2 = volumeExist[1].Split('@');
                        if (temp2.Length == 2)
                        {
                            volumeInDockerFile = temp2[0];
                        }
                    }

                    if (!string.IsNullOrEmpty(volumeInDockerFile))
                    {
                        //dockerFIle里面有配置 volume
                        if (!string.IsNullOrEmpty(Volume) && !Volume.Equals(volumeInDockerFile))
                        {
                            _logger($"Volume in dockerFile is defined,will use【{volumeInDockerFile}】replace【{Volume}】", LogLevel.Warning);
                        }
                        else
                        {
                            _logger($"Volume in dockerFile is : 【{volumeInDockerFile}】", LogLevel.Info);
                        }

                        Volume = volumeInDockerFile;
                    }

                    var serverPostDockerFile      = string.Empty;
                    var serverPostDockerFileExist = dockerFileText.Split(new string[] { serverPortProfix }, StringSplitOptions.None);
                    if (serverPostDockerFileExist.Length == 2)
                    {
                        var temp2 = serverPostDockerFileExist[1].Split('@');
                        if (temp2.Length > 0)
                        {
                            serverPostDockerFile = temp2[0];
                        }
                    }

                    if (!string.IsNullOrEmpty(serverPostDockerFile))
                    {
                        //dockerFIle里面有配置 ServerPort
                        if (!string.IsNullOrEmpty(NetCorePort) && !ServerPort.Equals(serverPostDockerFile))
                        {
                            _logger($"ServerPort in dockerFile is defined,will use【{serverPostDockerFile}】replace【{ServerPort}】", LogLevel.Warning);
                        }
                        else
                        {
                            _logger($"ServerPort in dockerFile is : 【{serverPostDockerFile}】", LogLevel.Info);
                        }

                        server_port = serverPostDockerFile;
                    }
                    else
                    {
                        server_port = needAddPort ? ServerPort : port;
                    }

                    if (!string.IsNullOrEmpty(NetCoreEnvironment) || needAddPort)
                    {
                        var allLines        = _sftpClient.ReadAllLines(dockFilePath).ToList();
                        var entryPointIndex = 0;
                        var haveEnv         = false;
                        for (int i = 0; i < allLines.Count; i++)
                        {
                            var line = allLines[i];
                            if (line.Trim().StartsWith("ENTRYPOINT"))
                            {
                                entryPointIndex = i;
                            }

                            if (line.StartsWith("ENV ASPNETCORE_ENVIRONMENT"))
                            {
                                haveEnv = true;
                            }
                        }


                        if (entryPointIndex > 0)
                        {
                            if (needAddPort)
                            {
                                allLines.Insert(entryPointIndex, "EXPOSE " + port);
                                _logger($"Add EXPOSE " + port + $" to dockerFile  : 【{dockFilePath}】", LogLevel.Info);
                            }

                            if (!haveEnv && !string.IsNullOrEmpty(NetCoreEnvironment))
                            {
                                allLines.Insert(entryPointIndex, "ENV ASPNETCORE_ENVIRONMENT " + NetCoreEnvironment);
                                _logger($"Add ENV ASPNETCORE_ENVIRONMENT " + NetCoreEnvironment + $" to dockerFile  : 【{dockFilePath}】", LogLevel.Info);
                            }

                            //没有发现包含环境变量 就添加进去
                            using (var writer = _sftpClient.CreateText(dockFilePath))
                            {
                                foreach (var line in allLines)
                                {
                                    writer.WriteLine(line);
                                }
                                writer.Flush();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger($"parse param in dockerFile fail: {dockFilePath},err:{ex.Message}", LogLevel.Error);
                    return;
                }
            }

            //执行docker build 生成一个镜像
            var dockerBuildResult = RunSheell($"docker build --no-cache --rm -t {PorjectName}:{ClientDateTimeFolderName} -f {dockFilePath} {publishFolder} ");

            if (!dockerBuildResult)
            {
                _logger($"build image fail", LogLevel.Error);
                return;
            }

            var continarName = "d_" + PorjectName;


            //先发送退出命令
            //https://stackoverflow.com/questions/40742192/how-to-do-gracefully-shutdown-on-dotnet-with-docker

            SshCommand r1 = null;

            try
            {
                r1 = _sshClient.RunCommand($"docker stop -t 10 {continarName}");
                if (r1.ExitStatus == 0)
                {
                    _logger($"docker stop -t 10 {continarName}", LogLevel.Info);
                }

                Thread.Sleep(5000);
            }
            catch (Exception)
            {
                //ignore
            }

            try
            {
                //查看容器有没有在runing 如果有就干掉它
                r1 = _sshClient.RunCommand($"docker rm -f {continarName}");
                if (r1.ExitStatus == 0)
                {
                    _logger($"docker rm -f {continarName}", LogLevel.Info);
                }
            }
            catch (Exception)
            {
                //ignore
            }


            if (string.IsNullOrEmpty(port))
            {
                port = ContainerPort;
            }

            if (string.IsNullOrEmpty(server_port))
            {
                server_port = ServerPort;
            }

            string volume = GetVolume();

            // 根据image启动一个容器
            var dockerRunRt = RunSheell($"docker run --name {continarName}{volume} -d --restart=always -p {server_port}:{port} {PorjectName}:{ClientDateTimeFolderName}");

            if (!dockerRunRt)
            {
                _logger($"docker run fail", LogLevel.Error);
                return;
            }

            //把旧的image给删除
            r1 = _sshClient.RunCommand("docker images --format '{{.Repository}}:{{.Tag}}:{{.ID}}' | grep '^" + PorjectName + ":'");
            if (r1.ExitStatus == 0 && !string.IsNullOrEmpty(r1.Result))
            {
                var deleteImageArr = r1.Result.Split('\n');
                var clearOldImages = false;
                foreach (var imageName in deleteImageArr)
                {
                    if (imageName.StartsWith($"{PorjectName}:{ClientDateTimeFolderName}:"))
                    {
                        //当前版本
                        continue;
                    }

                    var imageArr = imageName.Split(':');
                    if (imageArr.Length == 3)
                    {
                        var r2 = _sshClient.RunCommand($"docker rmi {imageArr[2]}");
                        if (r2.ExitStatus == 0)
                        {
                            if (!clearOldImages)
                            {
                                _logger($"start to clear old images of name:{PorjectName}", LogLevel.Info);
                                clearOldImages = true;
                            }
                            _logger($"docker rmi {imageArr[2]} [{imageName}]", LogLevel.Info);
                        }
                    }
                }
            }


            try
            {
                //查看是否有<none>的image 把它删掉 因为我们创建image的时候每次都会覆盖所以会产生一些没有的image
                _sshClient.RunCommand($"if docker images -f \"dangling=true\" | grep ago --quiet; then docker rmi -f $(docker images -f \"dangling=true\" -q); fi");
            }
            catch (Exception)
            {
                //igore
            }

            ClearOldHistroy();
        }
示例#8
0
 public void CreateTextTest1()
 {
     ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
     SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
     string path = string.Empty; // TODO: Initialize to an appropriate value
     StreamWriter expected = null; // TODO: Initialize to an appropriate value
     StreamWriter actual;
     actual = target.CreateText(path);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }