Ejemplo n.º 1
0
        public virtual void Backup()
        {
            logger("Start to Backup");
            string destDir = Path.Combine(this.args.BackupFolder, this.args.AppName);
            string dstName = DateTime.Now.ToString("Backup_yyyyMMdd_HHmmss");

            destDir = Path.Combine(destDir, dstName);
            this.args.RestorePath = destDir;
            DirectoryInfo directoryInfo = new DirectoryInfo(this.args.AppFolder);
            string        fullName      = directoryInfo.FullName;

            if (directoryInfo.Parent != null)
            {
                fullName = directoryInfo.Parent.FullName;
            }
            CopyHelper.DirectoryCopy(this.args.AppFolder, destDir, true, fullName, directoryInfo.Name, this.args.BackUpIgnoreList);
            //打包成zip
            var zipFile = Path.Combine(this.args.BackupFolder, this.args.AppName, dstName + ".zip");

            ZipFile.CreateFromDirectory(destDir, zipFile);
            //清除原来的目录
            Directory.Delete(destDir, true);
            //这里保持原来的目录结构 为了清除逻辑
            Directory.CreateDirectory(destDir);
            File.Move(zipFile, Path.Combine(destDir, dstName + ".zip"));

            logger("Success Backup to folder:" + destDir);
        }
Ejemplo n.º 2
0
        public virtual void Backup()
        {
            string destDir = Path.Combine(this.args.BackupFolder, this.args.AppName);

            destDir = Path.Combine(destDir, DateTime.Now.ToString("Backup_yyyyMMdd_HHmmss"));
            this.args.RestorePath = destDir;
            CopyHelper.DirectoryCopy(this.args.AppFolder, destDir, true);
        }
Ejemplo n.º 3
0
        public virtual void Backup()
        {
            logger("Start to Backup");
            string destDir = Path.Combine(this.args.BackupFolder, this.args.AppName);

            destDir = Path.Combine(destDir, DateTime.Now.ToString("Backup_yyyyMMdd_HHmmss"));
            this.args.RestorePath = destDir;
            DirectoryInfo directoryInfo = new DirectoryInfo(this.args.AppFolder);
            string        fullName      = directoryInfo.FullName;

            if (directoryInfo.Parent != null)
            {
                fullName = directoryInfo.Parent.FullName;
            }
            CopyHelper.DirectoryCopy(this.args.AppFolder, destDir, true, fullName, this.args.BackUpIgnoreList);
            logger("Success Backup to folder:" + destDir);
        }
Ejemplo n.º 4
0
        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);
            }
        }
Ejemplo n.º 5
0
        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);
            }
        }
Ejemplo n.º 6
0
 public virtual void Deploy()
 {
     CopyHelper.DirectoryCopy(this.args.DeployFolder, this.args.AppFolder, true);
 }
Ejemplo n.º 7
0
 public virtual void Restore()
 {
     CopyHelper.DirectoryCopy(this.args.RestorePath, this.args.AppFolder, true);
 }
Ejemplo n.º 8
0
        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();
                }
            }
        }
Ejemplo n.º 9
0
 public virtual void Deploy()
 {
     logger("Start to Deploy");
     CopyHelper.DirectoryCopy(this.args.DeployFolder, this.args.AppFolder, true);
     logger("Success Deploy from folder:[" + this.args.DeployFolder + "] to folder [" + this.args.AppFolder + "]");
 }
Ejemplo n.º 10
0
 public virtual void Restore()
 {
     logger("Start to Restore");
     CopyHelper.DirectoryCopy(this.args.RestorePath, this.args.AppFolder, true);
     logger("Success Restore from folder:[" + this.args.RestorePath + "] to folder:[" + this.args.AppFolder + "]");
 }
Ejemplo n.º 11
0
        /// <summary>
        /// 部署
        /// </summary>
        /// <param name="context"></param>
        /// <param name="filePath">所属单页面的根目录文件夹</param>
        /// <param name="saveFile">保存到单页面根目录文件夹下的zip的委托</param>
        /// <param name="backupAction">备份委托</param>
        /// <returns></returns>
        private static async Task Deploy(HttpContext context, string filePath, Action <string> saveFile, Action backupAction)
        {
            //保存到的目的文件
            var guidFile = Path.Combine(filePath, "new.zip");

            //解压后的文件夹
            var destFolder = Path.Combine(filePath, "new");

            try
            {
                //看是否有人在处理了?
                if (File.Exists(guidFile))
                {
                    //查看是否创建了超过1分钟了
                    if ((DateTime.Now - new FileInfo(guidFile).CreationTime).TotalMinutes > 1)
                    {
                        File.Delete(guidFile);
                    }
                    else
                    {
                        //说明有人正在处理
                        await context.Response.WriteAsync("please wait 5 sencods and retry");

                        return;
                    }
                }

                //真是处理前就先删除
                if (Directory.Exists(destFolder))
                {
                    Directory.Delete(destFolder, true);
                }

                //保存到guidFile文件
                saveFile(guidFile);

                //解压zip
                ZipFile.ExtractToDirectory(guidFile, destFolder);

                var copyFromFolder = destFolder;
                var indexFile      = Path.Combine(destFolder, "index.html");

                //查看是否有index.html
                if (!File.Exists(indexFile))
                {
                    //可能是有二级目录 找到哪个里面存在
                    var subFolders = Directory.GetFiles(destFolder, "index.html", SearchOption.AllDirectories);
                    if (subFolders.Length == 1)
                    {
                        // ReSharper disable once PossibleNullReferenceException
                        copyFromFolder = new FileInfo(subFolders.First()).Directory.FullName;
                    }
                    else
                    {
                        await context.Response.WriteAsync("can not found index.html in zip file");

                        return;
                    }
                }

                //替换文件
                CopyHelper.DirectoryCopy(copyFromFolder, filePath, true);

                //备份为了能快速回滚
                backupAction();

                await context.Response.WriteAsync("success");
            }
            finally
            {
                File.Delete(guidFile);
                Directory.Delete(destFolder, true);
            }
        }