Exemplo n.º 1
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);
     }
 }
Exemplo n.º 2
0
        public static bool RunJibExe(string publishPath, string rootPath, DockerImageConfig config2,
                                     NLog.Logger logger, Func <bool> checkCancel = null)
        {
            var config = DockerImageConfigGo.get(config2);
            //判断当前运行目录有没有jib.exe文件
            var jibExe = Path.Combine(rootPath, "jib.exe");

            if (!File.Exists(jibExe))
            {
                logger.Error($"can not found :{jibExe}");
                return(false);
            }

            config.ImageLayersFolder = publishPath;
            var dockerImageCache = Path.Combine(new DirectoryInfo(publishPath).Parent.FullName, "dockerImage_cache");

            config.ApplicationLayersCacheDirectory = dockerImageCache;
            //转成一个json文件
            var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

            string projectPramPath = "";
            string tarFolder       = "";

            //通过tarimage判断是打包到本地还是publish到远程
            try
            {
                var bash = "";
                if (ImageReference.Parse(config.TargetImage) == null)
                {
                    var output = config.TargetImage;
                    config.TargetImage = Path.GetFileNameWithoutExtension(config.TargetImage);
                    tarFolder          = Path.GetDirectoryName(output);
                    var projectPram = JsonConvert.SerializeObject(config);
                    var md5         = CodingHelper.MD5(projectPram);
                    projectPramPath = Path.Combine(path, md5 + "_param.json");
                    File.WriteAllText(projectPramPath, projectPram, Encoding.UTF8);
                    //打包到本地文件
                    bash = $"tar --outputfile=\"{output}\" --configfile=\"{projectPramPath}\"";
                }
                else
                {
                    var projectPram = JsonConvert.SerializeObject(config);
                    var md5         = CodingHelper.MD5(projectPram);
                    projectPramPath = Path.Combine(path, md5 + "_param.json");
                    File.WriteAllText(projectPramPath, projectPram, Encoding.UTF8);
                    //发布到远程
                    bash = $"push --configfile=\"{projectPramPath}\"";
                }


                return(RunDotnetExternalExe(rootPath, $"jib.exe", bash, logger, checkCancel, true));
            }
            finally
            {
                LogEventInfo publisEvent = new LogEventInfo(LogLevel.Info, "", "global pull image cache folder  ==> ");
                publisEvent.Properties["ShowLink"] = "file://%LOCALAPPDATA%/fibdotnet";
                publisEvent.LoggerName             = "rich_docker_image_log";
                logger.Log(publisEvent);

                LogEventInfo publisEvent2 = new LogEventInfo(LogLevel.Info, "", "local build image cache folder  ==> ");
                publisEvent2.Properties["ShowLink"] = "file://" + dockerImageCache.Replace("\\", "\\\\");
                publisEvent2.LoggerName             = "rich_docker_image_log";
                logger.Log(publisEvent2);

                if (!string.IsNullOrEmpty(tarFolder))
                {
                    LogEventInfo publisEvent3 =
                        new LogEventInfo(LogLevel.Info, "", "local build image tar folder  ==> ");
                    publisEvent3.Properties["ShowLink"] = "file://" + tarFolder.Replace("\\", "\\\\");
                    publisEvent3.LoggerName             = "rich_docker_image_log";
                    logger.Log(publisEvent3);
                }

                try
                {
                    File.Delete(projectPramPath);
                }
                catch (Exception e)
                {
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 打包文件夹
        /// </summary>
        /// <param name="sourceDirectoryName"></param>
        /// <param name="compressionLevel"></param>
        /// <param name="includeBaseDirectory"></param>
        /// <returns></returns>
        public static byte[] DoCreateFromDirectory(string sourceDirectoryName, CompressionLevel?compressionLevel, bool includeBaseDirectory, List <string> ignoreList = null, Func <int, bool> progress = null, Logger logger = null, Dictionary <string, Tuple <string, bool> > chineseFileParser = null)
        {
            //if (ignoreList != null)
            //{
            //    ignoreList.Add("/.git?");
            //}
            var haveFile = false;

            sourceDirectoryName = Path.GetFullPath(sourceDirectoryName);
            using (var outStream = new MemoryStream())
            {
                using (ZipArchive destination = new ZipArchive(outStream, ZipArchiveMode.Create, false))
                {
                    bool          flag          = true;
                    DirectoryInfo directoryInfo = new DirectoryInfo(sourceDirectoryName);
                    string        fullName      = directoryInfo.FullName;
                    if (includeBaseDirectory && directoryInfo.Parent != null)
                    {
                        fullName = directoryInfo.Parent.FullName;
                    }
                    var allFile       = FindFileDir(sourceDirectoryName);
                    var allFileLength = allFile.Count();
                    var index         = 0;
                    foreach (FileSystemInfo enumerateFileSystemInfo in allFile)
                    {
                        index++;
                        var lastProgressNumber = (((long)index * 100 / allFileLength));
                        if (progress != null)
                        {
                            var r = progress.Invoke((int)lastProgressNumber);
                            if (r)
                            {
                                throw new Exception("deploy task was canceled!");
                            }
                        }

                        flag = false;
                        int    length          = enumerateFileSystemInfo.FullName.Length - fullName.Length;
                        string entryName       = EntryFromPath(enumerateFileSystemInfo.FullName, fullName.Length, length);
                        var    mathchEntryName = includeBaseDirectory? entryName.Substring(directoryInfo.Name.Length): "/" + entryName;
                        if (ignoreList != null && ignoreList.Count > 0)
                        {
                            var haveMatch = false;
                            foreach (var ignorRule in ignoreList)
                            {
                                try
                                {
                                    if (ignorRule.StartsWith("*"))
                                    {
                                        var ignorRule2 = ignorRule.Substring(1);
                                        if (mathchEntryName.EndsWith(ignorRule2))
                                        {
                                            haveMatch = true;
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        var isMatch = Regex.Match(mathchEntryName, ignorRule, RegexOptions.IgnoreCase);//忽略大小写
                                        if (isMatch.Success)
                                        {
                                            haveMatch = true;
                                            break;
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    throw new Exception($"Ignore Rule 【{ignorRule}】 regular error:" + ex.Message);
                                }
                            }

                            if (haveMatch)
                            {
                                continue;
                            }
                        }
                        if (enumerateFileSystemInfo is FileInfo)
                        {
                            if (entryName.Contains("Dockerfile"))
                            {
                                logger?.Info($"Find Dockerfile In Package: {entryName}");
                            }
                            haveFile = true;

                            //如果文件名称包含中文的 记录下
                            if (chineseFileParser != null)
                            {
                                var newName   = enumerateFileSystemInfo.Name;
                                var isChinese = false;
                                //只需要看文件有没有中文
                                if (ChineseReg.IsMatch(newName))
                                {
                                    newName   = CodingHelper.MD5(enumerateFileSystemInfo.Name);
                                    isChinese = true;
                                }

                                var newFolder = entryName.Replace(enumerateFileSystemInfo.Name, "");
                                //是哪个文件夹下的
                                var temp = "";
                                if (!string.IsNullOrEmpty(newFolder) && chineseFileParser.TryGetValue(newFolder, out var folderChinese))
                                {
                                    temp = newFolder;//说明文件夹有中文 被替换 temp 是有中文的
                                    //文件夹被转化过
                                    newFolder = folderChinese.Item1 + "/";
                                    isChinese = true;
                                }

                                var newmathchEntryName = !string.IsNullOrEmpty(newFolder) ? newFolder + newName : newName;
                                if (isChinese)
                                {
                                    if (!string.IsNullOrEmpty(temp))
                                    {
                                        var newmathchEntryName1 = temp + newName;
                                        if (!entryName.Equals(newmathchEntryName1))
                                        {
                                            chineseFileParser.Add(entryName, new Tuple <string, bool>(newmathchEntryName1, false));
                                        }
                                    }
                                    else
                                    {
                                        chineseFileParser.Add(entryName, new Tuple <string, bool>(newmathchEntryName, false));
                                    }
                                }
                                DoCreateEntryFromFile(destination, enumerateFileSystemInfo.FullName, newmathchEntryName, compressionLevel);
                            }
                            else
                            {
                                DoCreateEntryFromFile(destination, enumerateFileSystemInfo.FullName, entryName, compressionLevel);
                            }
                        }
                        else
                        {
                            //文件夹名称也会乱码
                            DirectoryInfo possiblyEmptyDir = enumerateFileSystemInfo as DirectoryInfo;
                            if (chineseFileParser != null)
                            {
                                var arr       = entryName.Split('/');
                                var newarr    = new List <string>();
                                var isChinese = false;
                                foreach (var item in arr)
                                {
                                    if (string.IsNullOrEmpty(item))
                                    {
                                        newarr.Add(item);
                                        continue;
                                    }
                                    //如果文件夹里面含有中文
                                    if (ChineseReg.IsMatch(item))
                                    {
                                        newarr.Add(CodingHelper.MD5(item));
                                        isChinese = true;
                                    }
                                    else
                                    {
                                        newarr.Add(item);
                                    }
                                }

                                if (isChinese)
                                {
                                    var newmathchEntryName = string.Join("/", newarr);
                                    chineseFileParser.Add(entryName + "/", new Tuple <string, bool>(newmathchEntryName, true));
                                }
                            }
                            if (possiblyEmptyDir != null && IsDirEmpty(possiblyEmptyDir))
                            {
                                destination.CreateEntry(entryName + s_pathSeperator.ToString());
                            }
                        }
                    }

                    if ((includeBaseDirectory & flag))
                    {
                        string str = directoryInfo.Name;
                        destination.CreateEntry(str + s_pathSeperator.ToString());
                    }
                }
                if (!haveFile)
                {
                    throw new Exception("no file was packaged!");
                }
                return(outStream.ToArray());
            }
        }