public string Deploy(FormHandler.FormItem fileItem) { //按照项目名称 不能并发发布 if (!string.IsNullOrEmpty(ProjectName)) { var key = (ProviderName ?? string.Empty) + ProjectName; if (!locker.TryGetValue(key, out var ReaderWriterLockSlim)) { ReaderWriterLockSlim = new ReaderWriterLockSlim(); locker.TryAdd(key, ReaderWriterLockSlim); } if (ReaderWriterLockSlim.IsWriteLockHeld) { return($"{ProjectName} is deploying!,please wait for senconds!"); } ReaderWriterLockSlim.EnterWriteLock(); try { return(ExcuteDeploy(fileItem)); } finally { ReaderWriterLockSlim.ExitWriteLock(); } } else { return(ExcuteDeploy(fileItem)); } }
private string ExcuteDeploy(FormHandler.FormItem fileItem) { var re = DeployExcutor(fileItem); try { if (_formHandler == null) { return(re); } if (!string.IsNullOrEmpty(re)) { //发布出错了 删除此次版本号 //new Task(() => //{ // try // { // Directory.Delete(ProjectPublishFolder, true); // } // catch (Exception) // { // //ignore // } //}).Start(); return(re); } if (string.IsNullOrEmpty(ProjectPublishFolder) || !Directory.Exists(ProjectPublishFolder)) { return(re); } //保存参数 var formArgs = _formHandler.FormItems.Where(r => r.FileBody == null || r.FileBody.Length < 1).ToList(); if (formArgs.Any()) { var path = Path.Combine(ProjectPublishFolder, "antdeploy_args.json"); var content = JsonConvert.SerializeObject(formArgs); File.WriteAllText(path, content, Encoding.UTF8); } } catch (Exception) { //ignore } return(re); }
private string ExcuteDeploy(FormHandler.FormItem fileItem) { var re = DeployExcutor(fileItem); try { if (_formHandler == null) { return(re); } if (!string.IsNullOrEmpty(re)) { return(re); } if (string.IsNullOrEmpty(ProjectPublishFolder) || !Directory.Exists(ProjectPublishFolder)) { return(re); } //保存参数 var formArgs = _formHandler.FormItems.Where(r => r.FileBody == null || r.FileBody.Length < 1).ToList(); if (formArgs.Any()) { var path = Path.Combine(ProjectPublishFolder, "antdeploy_args.json"); var content = JsonConvert.SerializeObject(formArgs); File.WriteAllText(path, content, Encoding.UTF8); } SaveCurrentVersion(ProjectPublishFolder); } catch (Exception) { //ignore } var projectRootPath = new DirectoryInfo(ProjectPublishFolder).Parent; if (projectRootPath == null || !projectRootPath.Exists) { return(re); } //每次发布完成后清理老的发布历史记录 只清理自己项目的 //防止别的项目正在回滚到某个版本,你这边发现这个版本已经过时了就删除了 Setting.ClearOldFolders(ProviderName.Equals("iis") || ProjectName.Equals("linux"), projectRootPath.Name, Log); return(re); }
public override string DeployExcutor(FormHandler.FormItem fileItem) { return(null); }
public override string DeployExcutor(FormHandler.FormItem fileItem) { var projectPath = Path.Combine(Setting.PublishWindowServicePathFolder, _serviceName); _projectPublishFolder = Path.Combine(projectPath, !string.IsNullOrEmpty(_dateTimeFolderName) ? _dateTimeFolderName : DateTime.Now.ToString("yyyyMMddHHmmss")); EnsureProjectFolder(projectPath); EnsureProjectFolder(_projectPublishFolder); try { var filePath = Path.Combine(_projectPublishFolder, fileItem.FileName); using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { fs.Write(fileItem.FileBody, 0, fileItem.FileBody.Length); } if (!File.Exists(filePath)) { return("publish file save fail"); } Log("agent version ==>" + AntDeployAgentWindows.Version.VERSION); Log("upload success ==>" + filePath); //解压 try { Log("start unzip file"); ZipFile.ExtractToDirectory(filePath, _projectPublishFolder); } catch (Exception ex) { return("unzip publish file error:" + ex.Message); } Log("unzip success ==>" + _projectPublishFolder); var deployFolder = Path.Combine(_projectPublishFolder, "publish"); if (!Directory.Exists(deployFolder)) { if (Directory.Exists(_projectPublishFolder)) { var temp = new DirectoryInfo(_projectPublishFolder); var tempFolderList = temp.GetDirectories(); if (tempFolderList.Length == 1) { deployFolder = tempFolderList.First().FullName; } } } if (!Directory.Exists(deployFolder)) { return("unzip publish file error,Path not found:" + deployFolder); } //查找 Windows Service 里面是否存在该服务 var service = WindowServiceHelper.GetWindowServiceByName(this._serviceName); if (!string.IsNullOrEmpty(service.Item2)) { return(service.Item2); } if (service.Item1 == null) { //if (!_isProjectInstallService) //{ // return $"windowService : {_serviceName} not found"; //} Log($"windowService : {_serviceName} not found,start to create!"); //创建发布目录 var firstDeployFolder = string.IsNullOrEmpty(_physicalPath)? Path.Combine(projectPath, "deploy"):_physicalPath; EnsureProjectFolder(firstDeployFolder); if (Directory.Exists(firstDeployFolder)) { Log($"deploy folder create success : {firstDeployFolder} "); } else { return($"DeployFolder : {firstDeployFolder} create error!"); } //复制文件到发布目录 CopyHelper.DirectoryCopy(deployFolder, firstDeployFolder, true); Log($"copy files success from [{deployFolder}] to [{firstDeployFolder}]"); //部署windows service var execFullPath = Path.Combine(firstDeployFolder, _serviceExecName); if (!File.Exists(execFullPath)) { try { Directory.Delete(firstDeployFolder, true); } catch (Exception) { } return($"windows service exec file not found : {execFullPath} "); } //安装服务 Log($"start to install windows service"); Log($"service name:{_serviceName}"); Log($"service path:{execFullPath}"); try { ServiceInstaller.InstallAndStart(_serviceName, _serviceName, execFullPath); Log($"install windows service success"); Log($"start windows service success"); return(string.Empty); } catch (Exception e2) { return($"install windows service fail:" + e2.Message); } //var installResult = WindowServiceHelper.InstallWindowsService(execFullPath); //if (!string.IsNullOrEmpty(installResult)) //{ // try{ Directory.Delete(firstDeployFolder, true);}catch (Exception) {} // return installResult; //} ////部署成功 启动服务 //Log($"start windows service : " + _serviceName); //var startResult = WindowServiceHelper.StartService(_serviceName,120); //if (!string.IsNullOrEmpty(startResult)) //{ // try{ Directory.Delete(firstDeployFolder, true);}catch (Exception) {} // return startResult; //} //Log($"start windows service success"); //return string.Empty; } var projectLocationFolder = string.Empty; var projectLocation = WindowServiceHelper.GetWindowServiceLocation(this._serviceName); if (string.IsNullOrEmpty(projectLocation)) { return($"can not find executable path of service:{_serviceName}"); } try { projectLocation = projectLocation.Replace("\"", ""); projectLocationFolder = new FileInfo(projectLocation).DirectoryName; if (!Directory.Exists(projectLocationFolder)) { //如果目录不存在 那么就重新建立 EnsureProjectFolder(projectLocationFolder); } } catch (Exception) { return("ServiceFolder is not correct ===> " + projectLocationFolder); } Log("Start to deploy Windows Service:"); Log("ServiceName ===>" + _serviceName); Log("ServiceFolder ===> " + projectLocationFolder); Arguments args = new Arguments { DeployType = "WindowsService", BackupFolder = Setting.BackUpWindowServicePathFolder, AppName = _serviceName, AppFolder = projectLocationFolder, DeployFolder = deployFolder, WaitForWindowsServiceStopTimeOut = _waitForServiceStopTimeOut, BackUpIgnoreList = this._backUpIgnoreList }; var ops = new OperationsWINDOWSSERVICE(args, Log); try { ops.Execute(); try { //如果是增量的话 要把复制过来 if (_isIncrement) { Log("Increment deploy start to backup..."); //projectLocation.Item1 转到 increment 的目录 var incrementFolder = Path.Combine(_projectPublishFolder, "increment"); EnsureProjectFolder(incrementFolder); DirectoryInfo directoryInfo = new DirectoryInfo(projectLocationFolder); string fullName = directoryInfo.FullName; if (directoryInfo.Parent != null) { fullName = directoryInfo.Parent.FullName; } CopyHelper.DirectoryCopy(projectLocationFolder, incrementFolder, true, fullName, directoryInfo.Name, this._backUpIgnoreList); Log("Increment deploy backup success..."); } } catch (Exception ex3) { Log("Increment deploy folder backup fail:" + ex3.Message); } Log("Deploy WindowsService Execute Success"); } catch (Exception ex) { try { //ops.Rollback(); return($"publish to WindowsService err:{ex.Message}"); } catch (Exception ex2) { return($"publish to WindowsService err:{ex.Message},rollback fail:{ex2.Message}"); } } return(string.Empty); } catch (Exception ex) { return(ex.Message); } }
public override string DeployExcutor(FormHandler.FormItem fileItem) { var projectPath = Path.Combine(Setting.PublishIIsPathFolder, _projectName); _projectPublishFolder = Path.Combine(projectPath, !string.IsNullOrEmpty(_dateTimeFolderName) ? _dateTimeFolderName : DateTime.Now.ToString("yyyyMMddHHmmss")); EnsureProjectFolder(projectPath); EnsureProjectFolder(_projectPublishFolder); try { var isNetcore = _sdkTypeName.ToLower().Equals("netcore"); var filePath = Path.Combine(_projectPublishFolder, fileItem.FileName); using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { fs.Write(fileItem.FileBody, 0, fileItem.FileBody.Length); } if (!File.Exists(filePath)) { return("publish file save fail"); } #if NETCORE Log("netcore agent version ==>" + AntDeployAgentWindows.Version.VERSION); #else Log("netframework agent version ==>" + AntDeployAgentWindows.Version.VERSION); #endif Log("upload success ==>" + filePath); //解压 try { Log("start unzip file"); ZipFile.ExtractToDirectory(filePath, _projectPublishFolder); } catch (Exception ex) { return("unzip publish file error:" + ex.Message); } Log("unzip success ==>" + _projectPublishFolder); var deployFolder = Path.Combine(_projectPublishFolder, "publish"); if (!Directory.Exists(deployFolder)) { if (Directory.Exists(_projectPublishFolder)) { var temp = new DirectoryInfo(_projectPublishFolder); var tempFolderList = temp.GetDirectories(); if (tempFolderList.Length == 1) { deployFolder = tempFolderList.First().FullName; } } } if (!Directory.Exists(deployFolder)) { return("unzip publish file error,Path not found:" + deployFolder); } //查找 IIS 里面是否存在 var siteArr = _webSiteName.Split('/'); if (siteArr.Length > 2) { return($"website level limit is 2!"); } var level1 = siteArr[0]; var level2 = siteArr.Length == 2 ? siteArr[1] : string.Empty; var isSiteExistResult = IISHelper.IsSiteExist(level1, level2); if (!string.IsNullOrEmpty(isSiteExistResult.Item3)) { return($"【Error】 : {isSiteExistResult.Item3}"); } var tempPhysicalPath = string.Empty; if (_useTempPhysicalPath) { tempPhysicalPath = Path.Combine(_projectPublishFolder, "_deploy_"); } var iisVersion = IISHelper.GetIISVersion(); if (iisVersion > 0) { Log($"IIS_Version : {iisVersion} "); } if (!isSiteExistResult.Item1)//一级都不存在 { if (iisVersion <= 6) { return($"website : {_webSiteName} not found,start to create,but iis verison is too low!"); } //准备好目录 if (string.IsNullOrEmpty(_port)) { if (IISHelper.IsDefaultWebSite(level1)) { _port = "80"; } else { return($"website : {_webSiteName} not found,start to create,but port is required!"); } } Log($"website : {_webSiteName} not found,start to create!"); //创建发布目录 var firstDeployFolder = string.IsNullOrEmpty(_physicalPath)? Path.Combine(projectPath, "deploy"):_physicalPath; EnsureProjectFolder(firstDeployFolder); if (Directory.Exists(firstDeployFolder)) { Log($"deploy folder create success : {firstDeployFolder} "); } else { return($"DeployFolder : {firstDeployFolder} create error!"); } var rt = IISHelper.InstallSite(level1, firstDeployFolder, _port, (string.IsNullOrEmpty(_poolName) ? _projectName : _poolName), isNetcore, _poolAlwaysRunning); if (string.IsNullOrEmpty(rt)) { Log($"create website : {level1} success "); } else { return($"create website : {level1} error: {rt} "); } if (!string.IsNullOrEmpty(level2)) { //创建一级 但是一级需要一个空的目录 //创建二级虚拟目录 二级的目录才是正常程序所在目录 var level2Folder = Path.Combine(firstDeployFolder, level2); EnsureProjectFolder(level2Folder); var rt2 = IISHelper.InstallVirtualSite(level1, level2, level2Folder, (string.IsNullOrEmpty(_poolName) ? _projectName : _poolName), isNetcore, _poolAlwaysRunning); if (string.IsNullOrEmpty(rt2)) { Log($"create virtualSite :{level2} Of Website : {level1} success "); } else { return($"create virtualSite :{level2} website : {level1} error: {rt2} "); } //复制文件到发布目录 CopyHelper.ProcessXcopy(deployFolder, level2Folder, Log); if (_useTempPhysicalPath) { EnsureProjectFolder(tempPhysicalPath); CopyHelper.ProcessXcopy(deployFolder, tempPhysicalPath, Log); } Log($"copy files success from [{deployFolder}] to [{level2Folder}]"); return(String.Empty); } else { //只需要一级 就是程序所在目录 //复制文件到发布目录 CopyHelper.ProcessXcopy(deployFolder, firstDeployFolder, Log); if (_useTempPhysicalPath) { EnsureProjectFolder(tempPhysicalPath); CopyHelper.ProcessXcopy(deployFolder, tempPhysicalPath, Log); } Log($"copy files success from [{deployFolder}] to [{firstDeployFolder}]"); return(String.Empty); } } else if (isSiteExistResult.Item1 && !isSiteExistResult.Item2 && !string.IsNullOrEmpty(level2)) { if (IISHelper.GetIISVersion() <= 6) { return($"website : {_webSiteName} not found,start to create,but iis verison is too low!"); } //有一级 但是需要创建二级 Log($"website : {_webSiteName} not found,start to create!"); //创建发布目录 var firstDeployFolder = string.IsNullOrEmpty(_physicalPath)? Path.Combine(projectPath, "deploy"):_physicalPath; EnsureProjectFolder(firstDeployFolder); Log($"deploy folder create success : {firstDeployFolder} "); var level2Folder = Path.Combine(firstDeployFolder, level2); EnsureProjectFolder(level2Folder); var rt2 = IISHelper.InstallVirtualSite(level1, level2, level2Folder, (string.IsNullOrEmpty(_poolName) ? _projectName : _poolName), isNetcore, _poolAlwaysRunning); if (string.IsNullOrEmpty(rt2)) { Log($"create virtualSite :{level2} Of Website : {level1} success "); } else { return($"create virtualSite :{level2} website : {level1} error: {rt2} "); } //复制文件到发布目录 CopyHelper.ProcessXcopy(deployFolder, level2Folder, Log); if (_useTempPhysicalPath) { EnsureProjectFolder(tempPhysicalPath); CopyHelper.ProcessXcopy(deployFolder, tempPhysicalPath, Log); } Log($"copy files success from [{deployFolder}] to [{level2Folder}]"); return(String.Empty); } //下面的逻辑就是网站已经存在了 所以就有冲突的风险 var projectLocation = IISHelper.GetWebSiteLocationInIIS(level1, level2, Log); if (projectLocation == null) { return($"read info from iis error"); } if (string.IsNullOrEmpty(projectLocation.Item1)) { return($"website : {_webSiteName} not found in iis"); } if (!Directory.Exists(projectLocation.Item1)) { //如果目录不存在 那么就重新建立 EnsureProjectFolder(projectLocation.Item1); } Log("Start to deploy IIS:"); Log("SiteName ===>" + _webSiteName + $"[{projectLocation.Item2}]"); Log("SiteFolder ===> " + projectLocation.Item1); Log("SiteApplicationPoolName ===> " + projectLocation.Item3); Arguments args = new Arguments { DeployType = "IIS", BackupFolder = Setting.BackUpIIsPathFolder, AppName = _projectName, ApplicationPoolName = projectLocation.Item3, AppFolder = projectLocation.Item1, DeployFolder = deployFolder, SiteName = projectLocation.Item2, BackUpIgnoreList = this._backUpIgnoreList, NoBackup = !Setting.NeedBackUp }; //是否采用 每次都更换新的物理路径的方式 if (_useTempPhysicalPath) { args.NoStop = true; args.NoStart = true; args.UseTempPhysicalPath = true; args.Site1 = level1; args.Site2 = level2; args.TempPhysicalPath = Path.Combine(_projectPublishFolder, "_deploy_"); EnsureProjectFolder(args.TempPhysicalPath); } else if (_useOfflineHtm) { args.NoStop = true; args.NoStart = true; args.UseOfflineHtm = true; } else if (_isNoStopWebSite) { args.NoStop = true; args.NoStart = true; } var ops = new OperationsIIS(args, Log); try { ops.Execute(); try { //如果是增量的话 要把复制过来 if (!args.UseTempPhysicalPath && _isIncrement) { Log("Increment deploy start to backup..."); //projectLocation.Item1 转到 increment 的目录 var incrementFolder = Path.Combine(_projectPublishFolder, "increment"); EnsureProjectFolder(incrementFolder); DirectoryInfo directoryInfo = new DirectoryInfo(projectLocation.Item1); string fullName = directoryInfo.FullName; if (directoryInfo.Parent != null) { fullName = directoryInfo.Parent.FullName; } new Task(() => { CopyHelper.DirectoryCopy(projectLocation.Item1, incrementFolder, true, fullName, directoryInfo.Name, this._backUpIgnoreList); }).Start(); Log("Increment deploy backup success..."); } } catch (Exception ex3) { Log("Increment deploy folder backup fail:" + ex3.Message); } Log("Deploy IIS Execute Success"); } catch (Exception ex) { try { //ops.Rollback(); return($"publish to iis err:{ex.Message}"); } catch (Exception ex2) { return($"publish to iis err:{ex.Message},rollback fail:{ex2.Message}"); } } return(string.Empty); } catch (Exception ex) { return(ex.Message); } }
public abstract string DeployExcutor(FormHandler.FormItem fileItem);
public override string DeployExcutor(FormHandler.FormItem fileItem) { var projectPath = Path.Combine(Setting.PublishLinuxPathFolder, _serviceName); _projectPublishFolder = Path.Combine(projectPath, !string.IsNullOrEmpty(_dateTimeFolderName) ? _dateTimeFolderName : DateTime.Now.ToString("yyyyMMddHHmmss")); EnsureProjectFolder(projectPath); EnsureProjectFolder(_projectPublishFolder); try { var filePath = Path.Combine(_projectPublishFolder, fileItem.FileName); using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { fs.Write(fileItem.FileBody, 0, fileItem.FileBody.Length); } if (!File.Exists(filePath)) { return("publish file save fail"); } #if NETCORE if (!System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Log("linux agent version ==>" + AntDeployAgentWindows.Version.VERSION); } else { Log("netcore agent version ==>" + AntDeployAgentWindows.Version.VERSION); } #else Log("netframework agent version ==>" + AntDeployAgentWindows.Version.VERSION); #endif Log("upload success ==>" + filePath); //解压 try { Log("start unzip file"); ZipFile.ExtractToDirectory(filePath, _projectPublishFolder); } catch (Exception ex) { return("unzip publish file error:" + ex.Message); } Log("unzip success ==>" + _projectPublishFolder); var deployFolder = Path.Combine(_projectPublishFolder, "publish"); if (!Directory.Exists(deployFolder)) { if (Directory.Exists(_projectPublishFolder)) { var temp = new DirectoryInfo(_projectPublishFolder); var tempFolderList = temp.GetDirectories(); if (tempFolderList.Length == 1) { deployFolder = tempFolderList.First().FullName; } } } if (!Directory.Exists(deployFolder)) { return("unzip publish file error,Path not found:" + deployFolder); } //查找 Service 里面是否存在该服务 var service = LinuxServiceHelper.GetLinuxService(this._serviceName); if (!string.IsNullOrEmpty(service.Item1)) { //运行命令出错了 return(service.Item1); } if (string.IsNullOrEmpty(service.Item2))//没有找到该服务的workingFolder 可能是service描述文件内容不对,可能是服务不存在 { Log($"systemctlService : {_serviceName} not found,start to create!"); //创建发布目录 var firstDeployFolder = string.IsNullOrEmpty(_physicalPath) ? Path.Combine(projectPath, "deploy") : _physicalPath; EnsureProjectFolder(firstDeployFolder); if (Directory.Exists(firstDeployFolder)) { Log($"deploy folder create success : {firstDeployFolder} "); } else { return($"DeployFolder : {firstDeployFolder} create error!"); } //复制文件到发布目录 CopyHelper.ProcessXcopy(deployFolder, firstDeployFolder, Log); Log($"copy files success from [{deployFolder}] to [{firstDeployFolder}]"); //linux service var execFullPath = Path.Combine(firstDeployFolder, _serviceExecName); if (!File.Exists(execFullPath)) { //try { Directory.Delete(firstDeployFolder, true); } catch (Exception) { } return($"systemctl service exec file not found : {execFullPath}"); } //安装服务 Log($"start to install systemctl service"); Log($"service name:{_serviceName}"); Log($"service path:{execFullPath}"); Log($"service description:{_serviceDescription ?? string.Empty}"); try { var err = LinuxServiceHelper.CreateServiceFileAndRun(this._serviceName, firstDeployFolder, _serviceExecName, (_serviceDescription ?? string.Empty), _env, execFullPath, string.IsNullOrEmpty(_serviceStartType) || _serviceStartType.Equals("Auto"), _notify, Log); if (!string.IsNullOrEmpty(err)) { return(err); } //检查是否成功了? var runSuccess = false; Thread.Sleep(5000); CopyHelper.RunCommand($"sudo systemctl status {this._serviceName}", null, (msg) => { if (!string.IsNullOrEmpty(msg)) { this.Log(msg); var msg1 = msg.ToLower(); if (msg1.Contains("activating (start)")) { runSuccess = true; } else if (msg1.Contains("active:") && msg1.Contains("running")) { runSuccess = true; } } }); if (!runSuccess) { return($"install linux service fail"); } Log($"install systemctl service success"); return(string.Empty); } catch (Exception e2) { return($"install linux service fail:" + e2.Message); } } var projectLocationFolder = service.Item2; try { if (!Directory.Exists(projectLocationFolder)) { //如果目录不存在 那么就重新建立 EnsureProjectFolder(projectLocationFolder); } } catch (Exception) { return("ServiceFolder is not correct ===> " + projectLocationFolder); } if (string.IsNullOrEmpty(projectLocationFolder)) { return("ServiceFolder is not correct ===> " + projectLocationFolder); } var fullExcutePath = Path.Combine(projectLocationFolder, _serviceExecName); if (!File.Exists(fullExcutePath)) { return($"systemctl service exec file not found : {fullExcutePath}"); } //保证有service描述文件 等后面实际要用到 LinuxServiceHelper.CreateServiceFile(this._serviceName, projectLocationFolder, _serviceExecName, (_serviceDescription ?? string.Empty), _env, this._notify, Log); Arguments args = new Arguments { DeployType = "Linux", BackupFolder = Setting.BackUpLinuxPathFolder, AppName = _serviceName, AppFolder = projectLocationFolder, TempPhysicalPath = Path.Combine(projectLocationFolder, $"{_serviceName}.service"),//服务文件描述 DeployFolder = deployFolder, ApplicationPoolName = fullExcutePath, BackUpIgnoreList = this._backUpIgnoreList, UseOfflineHtm = string.IsNullOrEmpty(_serviceStartType) || _serviceStartType.Equals("Auto"), NoBackup = !Setting.NeedBackUp, Site1 = _env }; Log("Start to deploy linux Service:"); Log("ServiceName ===>" + _serviceName); Log("ServiceFolder ===> " + projectLocationFolder); if (_isNoStopWebSite) { args.NoStop = true; args.NoStart = true; } var ops = new OperationsLinux(args, Log); try { ops.Execute(); try { //如果是增量的话 要把复制过来 if (_isIncrement) { Log("Increment deploy start to backup..."); //projectLocation.Item1 转到 increment 的目录 var incrementFolder = Path.Combine(_projectPublishFolder, "increment"); EnsureProjectFolder(incrementFolder); if (this._backUpIgnoreList != null && this._backUpIgnoreList.Any()) { var excludFrom = Path.Combine(_projectPublishFolder, "exclude.log"); File.WriteAllLines(excludFrom, this._backUpIgnoreList); //存到文件里面去 要指定排除 CopyHelper.ProcessXcopy(projectLocationFolder, incrementFolder, excludFrom, Log); } else { CopyHelper.ProcessXcopy(projectLocationFolder, incrementFolder, Log); } Log("Increment deploy backup success..."); } } catch (Exception ex3) { Log("Increment deploy folder backup fail:" + ex3.Message); } Log("Deploy linux service Execute Success"); } catch (Exception ex) { try { //ops.Rollback(); return($"publish to linux service err:{ex.Message}"); } catch (Exception ex2) { return($"publish to linux service err:{ex.Message},rollback fail:{ex2.Message}"); } } return(string.Empty); } catch (Exception ex) { return(ex.Message); } }
public override string DeployExcutor(FormHandler.FormItem fileItem) { var projectPath = Path.Combine(Setting.PublishWindowServicePathFolder, _serviceName); _projectPublishFolder = Path.Combine(projectPath, !string.IsNullOrEmpty(_dateTimeFolderName) ? _dateTimeFolderName : DateTime.Now.ToString("yyyyMMddHHmmss")); EnsureProjectFolder(projectPath); EnsureProjectFolder(_projectPublishFolder); var deployFolder = string.Empty; try { var _zipFile = Path.Combine(_projectPublishFolder, fileItem.FileName); using (var fs = new FileStream(_zipFile, FileMode.Create, FileAccess.Write)) { fs.Write(fileItem.FileBody, 0, fileItem.FileBody.Length); } if (!File.Exists(_zipFile)) { return("publish file save fail"); } #if NETCORE Log("netcore agent version ==>" + Version.VERSION); #else Log("netframework agent version ==>" + Version.VERSION); #endif Log("upload success ==>" + _zipFile); //解压 try { Log("start unzip file"); ZipFile.ExtractToDirectory(_zipFile, _projectPublishFolder); } catch (Exception ex) { return("unzip publish file error:" + ex.Message); } Log("unzip success ==>" + _projectPublishFolder); deployFolder = findUploadFolder(_projectPublishFolder, true); if (!Directory.Exists(deployFolder)) { return("unzip publish file error,Path not found:" + deployFolder); } //查找 Windows Service 里面是否存在该服务 var service = WindowServiceHelper.GetWindowServiceByName(this._serviceName); if (!string.IsNullOrEmpty(service.Item2)) { return(service.Item2); } if (service.Item1 == null) { Log($"windowService : {_serviceName} not found,start to create!"); //创建发布目录 var firstDeployFolder = string.IsNullOrEmpty(_physicalPath) ? Path.Combine(projectPath, "deploy") : _physicalPath; EnsureProjectFolder(firstDeployFolder); if (Directory.Exists(firstDeployFolder)) { Log($"deploy folder create success : {firstDeployFolder} "); } else { return($"DeployFolder : {firstDeployFolder} create error!"); } //复制文件到发布目录 CopyHelper.ProcessXcopy(deployFolder, firstDeployFolder, Log); Log($"copy files success from [{deployFolder}] to [{firstDeployFolder}]"); //部署windows service var execFullPath = Path.Combine(firstDeployFolder, _serviceExecName); if (!File.Exists(execFullPath)) { try { Directory.Delete(firstDeployFolder, true); } catch (Exception) { } return($"windows service exec file not found : {execFullPath} "); } //安装服务 Log($"start to install windows service"); Log($"service name:{_serviceName}"); Log($"service path:{execFullPath}"); Log($"service startType:{(!string.IsNullOrEmpty(_serviceStartType) ? _serviceStartType : "Auto")}"); Log($"service description:{_serviceDescription ?? string.Empty}"); try { if (_useNssm) { var rt = ServiceInstaller.NssmInstallAndStart(_serviceName, _param, execFullPath, _serviceStartType, _serviceDescription, Log); if (!rt) { return("use nssm install windows service fail"); } } else { ServiceInstaller.InstallAndStart(_serviceName, _serviceName, execFullPath + (string.IsNullOrEmpty(_param) ? "" : " " + _param), _serviceStartType, _serviceDescription); } Log($"install windows service success"); Log($"start windows service success"); return(string.Empty); } catch (Exception e2) { Thread.Sleep(5000); var isStart = WindowServiceHelper.IsStart(_serviceName); if (isStart) { Log($"install windows service success"); Log($"start windows service success"); return(string.Empty); } return($"install windows service fail:" + e2.Message); } } var projectLocationFolder = string.Empty; var projectLocation = WindowServiceHelper.GetWindowServiceLocation(this._serviceName); if (string.IsNullOrEmpty(projectLocation)) { return($"can not find executable path of service:{_serviceName}"); } //处理使用 nssm 安装的 Windows 服务程序 if (projectLocation.EndsWith("nssm.exe", true, CultureInfo.CurrentCulture)) { Log("service is installed by NSSM process."); var _nssmOutput = ""; var rt = ProcessHepler.RunExternalExe(projectLocation, $"get {_serviceName} Application", output => { _nssmOutput += Regex.Replace(output, @"\0", ""); }); if (!rt || string.IsNullOrEmpty(_nssmOutput.Trim())) { return($"can not find real executable path of nssm service:{_serviceName}"); } projectLocation = _nssmOutput; } Log($"project location:{projectLocation}"); try { projectLocation = projectLocation.Replace("\"", ""); projectLocationFolder = new FileInfo(projectLocation).DirectoryName; if (!Directory.Exists(projectLocationFolder)) { //如果目录不存在 那么就重新建立 EnsureProjectFolder(projectLocationFolder); } } catch (Exception) { return("ServiceFolder is not correct ===> " + projectLocationFolder); } Arguments args = new Arguments { DeployType = "WindowsService", BackupFolder = Setting.BackUpWindowServicePathFolder, AppName = _serviceName, AppFolder = projectLocationFolder, DeployFolder = deployFolder, WaitForWindowsServiceStopTimeOut = _waitForServiceStopTimeOut, BackUpIgnoreList = this._backUpIgnoreList, NoBackup = !Setting.NeedBackUp }; if (_serviceName.ToLower().Equals("antdeployagentwindowsservice")) { return(UpdateSelft(args)); } Log("Start to deploy Windows Service:"); Log("ServiceName ===>" + _serviceName); Log("ServiceFolder ===> " + projectLocationFolder); if (_isNoStopWebSite) { args.NoStop = true; args.NoStart = true; } var ops = new OperationsWINDOWSSERVICE(args, Log); try { ops.Execute(); try { //如果是增量的话 要把复制过来 if (_isIncrement) { Log("Increment deploy start to backup..."); //projectLocation.Item1 转到 increment 的目录 var incrementFolder = Path.Combine(_projectPublishFolder, "increment"); EnsureProjectFolder(incrementFolder); DirectoryInfo directoryInfo = new DirectoryInfo(projectLocationFolder); string fullName = directoryInfo.FullName; if (directoryInfo.Parent != null) { fullName = directoryInfo.Parent.FullName; } CopyHelper.DirectoryCopy(projectLocationFolder, incrementFolder, true, fullName, directoryInfo.Name, this._backUpIgnoreList); Log("Increment deploy backup success..."); } } catch (Exception ex3) { Log("Increment deploy folder backup fail:" + ex3.Message); } Log("Deploy WindowsService Execute Success"); } catch (Exception ex) { try { //ops.Rollback(); return($"publish to WindowsService err:{ex.Message}"); } catch (Exception ex2) { return($"publish to WindowsService err:{ex.Message},rollback fail:{ex2.Message}"); } } return(string.Empty); } catch (Exception ex) { return(ex.Message); } finally { if (!string.IsNullOrEmpty(deployFolder) && Directory.Exists(deployFolder)) { new Task(() => { try { Directory.Delete(deployFolder, true); } catch (Exception) { //ignore } }).Start(); } } }