DeployFile GeneratePcFile(DeployContext ctx, DotNetProject netProject, LinuxDeployData data, DotNetProjectConfiguration conf)
        {
            string libs     = "-r:@ProgramFiles@/" + Path.GetFileName(conf.CompiledOutputName);
            string requires = "";
            string version  = netProject.Version;

            if (string.IsNullOrEmpty(version) && netProject.ParentSolution != null)
            {
                version = netProject.ParentSolution.Version;
            }

            string file = ctx.CreateTempFile();

            using (StreamWriter sw = new StreamWriter(file))
            {
                sw.WriteLine("Name: " + netProject.Name);
                sw.WriteLine("Description: " + (String.IsNullOrEmpty(netProject.Description) ? netProject.Name : netProject.Description));
                sw.WriteLine("Version: " + version);
                sw.WriteLine();
                sw.WriteLine("Requires: " + requires);
                sw.WriteLine("Libs: " + libs);
            }
            string     outfile = netProject.Name.ToLower() + ".pc";
            DeployFile df      = new DeployFile(netProject, file, outfile, LinuxTargetDirectory.PkgConfig);

            df.ContainsPathReferences = true;
            df.DisplayName            = GettextCatalog.GetString("pkg-config file for {0}", netProject.Name);
            return(df);
        }
示例#2
0
        public EditPackageDialog(Package package)
        {
            this.Build();

            this.package = package;
            target       = package.PackageBuilder.Clone();
            this.Title   = target.Description;

            this.Icon      = ImageService.GetIcon(target.Icon, Gtk.IconSize.Menu).ToPixbuf();
            entryName.Text = package.Name;

            targetBox.PackStart(new PackageBuilderEditor(target), true, true, 0);

            entrySelector.Fill(target, null);
            entrySelector.SetSelection(target.RootSolutionItem, target.GetChildEntries());

            DeployContext ctx = target.CreateDeployContext();

            if (ctx == null)
            {
                pageFiles.Hide();
            }
            else
            {
                ctx.Dispose();
            }
        }
示例#3
0
 public string Invoke(DeployContext model)
 {
     using (ZipArchive archive = new ZipArchive(model.ZipStream))
     {
         foreach (var file in archive.Entries)
         {
             int count = 0;
             while (true)
             {
                 count += 1;
                 try
                 {
                     string targetPath = Path.Combine(model.DeployFolder, file.FullName);
                     Directory.CreateDirectory(Path.GetDirectoryName(targetPath));
                     file.ExtractToFile(targetPath, true);
                     count = 0;
                     break;
                 }
                 catch (Exception ex)
                 {
                     if (count > 5)
                     {
                         throw ex;
                     }
                     else
                     {
                         System.Threading.Thread.Sleep(1000);
                     }
                 }
             }
         }
     }
     return($"Deploy succeed");
 }
示例#4
0
        public string Invoke(DeployContext model)
        {
            int count = 0;

            while (true)
            {
                count += 1;
                try
                {
                    provider.StartAppPool(model.AppPoolName);
                    count = 0;
                    return($"Start app pool {model.AppPoolName} succeed");
                }
                catch (Exception ex)
                {
                    if (count > 5)
                    {
                        throw ex;
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(2000);
                    }
                }
            }
        }
示例#5
0
        private void RunDeployment(IConf conf, IDeployEvents callback, DeployContext context, byte[] files)
        {
            using (var session = _dsFactory.CreateSessionObj(conf, _user)) {
                _logger.Info(string.Format("Session for '{0}' is opened", _sessionKey));

                var deploySteps      = new List <IDeployer>();
                var failedValidators = new List <IValidator>();
                var exceptionHandler = _dsFactory.CreateDeployExHandlerObj(callback, conf, _logger, session);
                try {
                    conf.PackageManager.BytesToZip(files, conf.PackagePaths.Survey);
                    _logger.Info(string.Format("Zip files was unpacked to '{0}'", conf.PackagePaths.Survey));

                    DeployExecutor.Validate(_dsFactory.CreateValidatorsList(conf), failedValidators, callback, conf.Survey.DeployMode);
                    _logger.Info(string.Format("Validation process is complete. Found '{0}' error(s)", failedValidators.Count));
                    if (failedValidators.Any())
                    {
                        throw new ValidationException("Validation at " + String.Join(", ", failedValidators.Select(v => v.Name).ToArray()) + " failed.");
                    }

                    DeployExecutor.Deploy(_dsFactory.CreateDeployersList(conf), deploySteps, callback, conf.Survey.DeployMode);
                    _logger.Info(string.Format("Deploy is finished for '{0}'", _sessionKey));

                    session.Commit();
                    _logger.Info(string.Format("Session for '{0}' is commited successfully", _sessionKey));
                } catch (ValidationException exception) {
                    exceptionHandler.HandleValidation(exception, callback);
                } catch (DeployException exception) {
                    exceptionHandler.HandleDeploy(exception, callback, deploySteps, GetRollbackAction(context));
                } catch (Exception exception) {
                    exceptionHandler.HandleUnknown(exception, callback);
                }
            }
        }
        public void Execute(DeployContext context)
        {
            CreateScriptFile(context);

            using (var p = new Process())
            {
                // Redirect the output stream of the child process.
                p.StartInfo.UseShellExecute        = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError  = true;
                p.StartInfo.WorkingDirectory       = _config.TempFolder;
                p.StartInfo.FileName       = @"C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe";
                p.StartInfo.CreateNoWindow = true;

                p.StartInfo.Arguments = string.Format("-NoProfile -ExecutionPolicy Unrestricted -File asimov_generated.ps1");

                p.Start();

                p.StandardOutput.RedirectOutput(str => context.Log.Info(str));
                p.StandardError.RedirectOutput(str => context.Log.Info(str));

                p.WaitForExit((int)TimeSpan.FromMinutes(40).TotalMilliseconds);

                if (p.ExitCode != 0)
                {
                    throw new DeployException("Powershell script did not complete successfully");
                }
            }
        }
        public override DeployFileCollection GetProjectDeployFiles(DeployContext ctx, Project project,
                                                                   ConfigurationSelector configuration)
        {
            DeployFileCollection files = base.GetProjectDeployFiles(ctx, project, configuration);

            AspNetAppProject aspProj = project as AspNetAppProject;

            //none of this needs to happen if it's just happening during solution build
            if (aspProj == null || ctx.ProjectBuildOnly)
            {
                return(files);
            }

            //audit the DeployFiles to make sure they're allowed and laid out for ASP.NET
            foreach (DeployFile df in files)
            {
                //rewrite ProgramFiles target to ASP.NET's "bin" target
                if (df.TargetDirectoryID == TargetDirectory.ProgramFiles)
                {
                    df.RelativeTargetPath = Path.Combine("bin", df.RelativeTargetPath);
                }
            }

            //add all ASP.NET files marked as content. They go relative to the application root, which we assume to be ProgramFiles
            foreach (ProjectFile pf in aspProj.Files)
            {
                if (pf.BuildAction == BuildAction.Content)
                {
                    files.Add(new DeployFile(aspProj, pf.FilePath, pf.ProjectVirtualPath, TargetDirectory.ProgramFiles));
                }
            }

            return(files);
        }
		public override void CopyFiles (IProgressMonitor monitor, IFileReplacePolicy replacePolicy, FileCopyConfiguration copyConfig, DeployFileCollection deployFiles, DeployContext context)
		{
			DirectoryInfo tempDir = null;
			try {
				tempDir = CreateTempDir ();
			} catch (Exception e) {
				monitor.ReportError (GettextCatalog.GetString ("Could not create temporary directory."), e);
				return;
			}
			
			try {
				MountTempDirectory (copyConfig, tempDir.FullName);
			} catch (Exception e) {
				monitor.ReportError (GettextCatalog.GetString ("Could not mount FUSE filesystem."), e);
				RemoveTempDirIfEmpty (tempDir);
				return;
			}
			
			try {
				base.InternalCopyFiles (monitor, replacePolicy, copyConfig, deployFiles, context, tempDir.FullName);
			} finally {
				try {
					//unmount the fuse directory
					RunFuseCommand ("fusermount", string.Format ("-u \"{0}\"", tempDir.FullName));
				} catch (Exception e) {
					monitor.ReportError (GettextCatalog.GetString ("Could not unmount FUSE filesystem."), e);
				}
				RemoveTempDirIfEmpty (tempDir);
			}
		}
        public void Execute(DeployContext context)
        {
            CreateScriptFile(context);

            using (var p = new Process())
            {
                // Redirect the output stream of the child process.
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.WorkingDirectory = _config.TempFolder;
                p.StartInfo.FileName = @"C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe";
                p.StartInfo.CreateNoWindow = true;

                p.StartInfo.Arguments = string.Format("-NoProfile -ExecutionPolicy Unrestricted -File asimov_generated.ps1");

                p.Start();

                Redirect(p.StandardOutput, str => context.Log.Info(str));
                Redirect(p.StandardError, str => context.Log.Info(str));

                p.WaitForExit((int)TimeSpan.FromMinutes(20).TotalMilliseconds);

                if (p.ExitCode != 0)
                    throw new DeployException("Powershell script did not complete successfully");
            }
        }
        internal ClientImpersonationContext(DeployContext context, bool throwOnError)
        {
            var zero = IntPtr.Zero;

            try
            {
                if (context != null)
                {
                    zero = context.ImpersonationToken;
                }
                else
                {
                    zero = HostingEnvironment.ApplicationIdentityToken;
                }
            }
            catch { if (throwOnError)
                    {
                        throw;
                    }
            }
            if (zero != IntPtr.Zero)
            {
                ImpersonateToken(new HandleRef(this, zero));
            }
        }
示例#11
0
        protected override string OnResolveDirectory(DeployContext ctx, string folderId)
        {
            /*string prefix_var = generateAutotools ? "@prefix@" : "$(prefix)";
             * string package_var = generateAutotools ? "@PACKAGE@" : "$(PACKAGE)";*/
            //FIXME: Temp till we find a proper solution
            string prefix_var  = "@prefix@";
            string package_var = "@PACKAGE@";

            switch (folderId)
            {
            case TargetDirectory.ProgramFilesRoot:
                return("@expanded_libdir@");

            case TargetDirectory.ProgramFiles:
                return("@expanded_libdir@/" + package_var);

            case TargetDirectory.Binaries:
                return("@expanded_bindir@");

            case TargetDirectory.CommonApplicationDataRoot:
                return("@expanded_datadir@");

            case TargetDirectory.CommonApplicationData:
                return("@expanded_datadir@/" + package_var);

            case TargetDirectory.IncludeRoot:
                return(prefix_var + "/include");

            case TargetDirectory.Include:
                return(prefix_var + "/include/" + package_var);
            }
            return(null);
        }
示例#12
0
        private void InstallService(DeployContext context)
        {
            if (string.IsNullOrEmpty(_installableConfig.TargetPath))
            {
                _installableConfig.TargetPath = Path.Combine(@"\Services", context.DeployUnit.Name);
            }

            CleanPhysicalPath(context);

            CopyFiles(context);

            if (!string.IsNullOrEmpty(_installableConfig.Install))
            {
                InstallServiceUsingInstallCommandFromConfig(context);
            }
            else if (_installableConfig.InstallType.Equals("NServiceBus", StringComparison.InvariantCultureIgnoreCase))
            {
                InstallNServiceBusHandler(context);
            }
            else if (_installableConfig.InstallType.Equals("TopShelf", StringComparison.InvariantCultureIgnoreCase))
            {
                InstallTopShelfService(context);
            }
            else
            {
                context.Log.Info($"Asimov Install was not able to do it's job! Check 'Installable' config for '{context.DeployUnit.Name}'.");
            }
        }
示例#13
0
        protected override bool OnBuild(IProgressMonitor monitor, DeployContext ctx)
        {
            string   consMsg;
            IConsole cons;

            if (ExternalConsole)
            {
                cons    = ExternalConsoleFactory.Instance.CreateConsole(CloseConsoleWhenDone);
                consMsg = GettextCatalog.GetString("(in external terminal)");
            }
            else
            {
                cons    = new MonitorConsole(monitor);
                consMsg = "";
            }

            monitor.Log.WriteLine(GettextCatalog.GetString("Executing: {0} {1} {2}", Command, Arguments, consMsg));
            IProcessAsyncOperation process = Runtime.ProcessService.StartConsoleProcess(Command, Arguments, workingDirectory, cons, null);

            process.WaitForCompleted();

            if (cons is MonitorConsole)
            {
                ((MonitorConsole)cons).Dispose();
            }
            return(true);
        }
        protected override bool OnBuild(ProgressMonitor monitor, DeployContext ctx)
        {
            string             sourceFile;
            SolutionFolderItem entry = RootSolutionItem;

            if (entry is SolutionFolder)
            {
                sourceFile = entry.ParentSolution.FileName;
            }
            else
            {
                sourceFile = ((SolutionItem)entry).FileName;
            }

            AggregatedProgressMonitor mon = new AggregatedProgressMonitor();

            mon.AddSlaveMonitor(monitor, MonitorAction.WriteLog | MonitorAction.ReportError | MonitorAction.ReportWarning | MonitorAction.ReportSuccess);

            string tmpFolder = FileService.CreateTempDirectory();

            try {
                string tf = Path.GetFileNameWithoutExtension(targetFile);
                if (tf.EndsWith(".tar"))
                {
                    tf = Path.GetFileNameWithoutExtension(tf);
                }

                string folder = FileService.GetFullPath(Path.Combine(tmpFolder, tf));
                Directory.CreateDirectory(folder);

                // Export the project

                SolutionFolderItem[] ents   = GetChildEntries();
                string[]             epaths = new string [ents.Length];
                for (int n = 0; n < ents.Length; n++)
                {
                    epaths [n] = ents [n].ItemId;
                }

                var r = Services.ProjectService.Export(mon, sourceFile, epaths, folder, FileFormat).Result;
                if (string.IsNullOrEmpty(r))
                {
                    return(false);
                }

                // Create the archive
                string td = Path.GetDirectoryName(targetFile);
                if (!Directory.Exists(td))
                {
                    Directory.CreateDirectory(td);
                }
                DeployService.CreateArchive(mon, tmpFolder, targetFile);
            }
            finally {
                Directory.Delete(tmpFolder, true);
            }
            monitor.Log.WriteLine(GettextCatalog.GetString("Created file: {0}", targetFile));
            return(true);
        }
示例#15
0
 private void CleanPhysicalPath(DeployContext context)
 {
     if (DirectoryUtil.Exists(_installableConfig.TargetPath))
     {
         context.Log.InfoFormat("Cleaning folder {0}", _installableConfig.TargetPath);
         DirectoryUtil.Clean(_installableConfig.TargetPath);
     }
 }
示例#16
0
 private static Action <IDeployer> GetRollbackAction(DeployContext context)
 {
     if (context.Mode == DeployMode.Install)
     {
         return(d => d.InstallRollback());
     }
     return(d => d.UpdateRollback());
 }
示例#17
0
 public AutotoolsContext(DeployContext deployContext, string base_directory, string[] configs, MakefileType type)
 {
     this.deployContext = deployContext;
     template_dir       = Path.Combine(Path.GetDirectoryName(typeof(AutotoolsContext).Assembly.Location), "templates");
     base_dir           = base_directory;
     configurations     = configs;
     makefileType       = type;
 }
示例#18
0
 public string Invoke(DeployContext model)
 {
     if (model.AllowDeployKey != model.DeployKey)
     {
         throw new UnauthorizedAccessException("Unauthorized");
     }
     return("Authorized");
 }
示例#19
0
        public void Execute(DeployContext context)
        {
            var deployUnit = (FileCopyDeployUnit)context.DeployUnit;

            if (deployUnit.CleanTargetPath)
                DirectoryUtil.Clean(deployUnit.TargetPath);

            DirectoryUtil.CopyDirectory(context.TempFolderWithNewVersionFiles, deployUnit.TargetPath);
        }
示例#20
0
        private static void StopService(DeployContext context, ServiceController controller)
        {
            context.Log.InfoFormat("Stopping service {0}", controller.ServiceName);

            if (controller.Status == ServiceControllerStatus.Running)
            {
                ProcessAwareServiceController.StopServiceAndWaitForExit(controller.ServiceName);
            }
        }
        private static void Beep(DeployContext context, string type)
        {
            if (context.NoBeeps)
                return;

            BeepConfig beep;
            if (context.ApplicationContext.UserConfig.Beeps.TryGetValue(type, out beep))
                Buzzer.Beep(beep.Frequency, beep.Duration, beep.Pulses, beep.DutyCycle);
        }
示例#22
0
 public string Invoke(DeployContext model)
 {
     using (FileStream fs = new FileStream(model.ZipFileName, FileMode.CreateNew))
     {
         model.ZipStream.CopyTo(fs);
         fs.Flush();
     };
     return($"Zip has been save to 『{model.ZipFileName}』");
 }
        internal static void GenerateMakefiles(SolutionItem entry, Solution solution)
        {
            if (solution == null)
            {
                AlertButton generateMakefilesButton = new AlertButton(GettextCatalog.GetString("_Generate Makefiles"));
                if (MessageService.AskQuestion(GettextCatalog.GetString("Generating Makefiles is not supported for single projects. Do you want to generate them for the full solution - '{0}' ?", entry.ParentSolution.Name),
                                               AlertButton.Cancel,
                                               generateMakefilesButton) == generateMakefilesButton)
                {
                    solution = ((SolutionItem)entry).ParentSolution;
                }
                else
                {
                    return;
                }
            }

            DeployContext    ctx     = null;
            IProgressMonitor monitor = null;

            GenerateMakefilesDialog dialog = new GenerateMakefilesDialog(solution);

            try
            {
                if (MessageService.RunCustomDialog(dialog) != (int)Gtk.ResponseType.Ok)
                {
                    return;
                }

                SolutionDeployer deployer = new SolutionDeployer(dialog.GenerateAutotools);
                if (deployer.HasGeneratedFiles(solution))
                {
                    string msg = GettextCatalog.GetString("{0} already exist for this solution.  Would you like to overwrite them?", dialog.GenerateAutotools ? "Autotools files" : "Makefiles");
                    if (MonoDevelop.Ide.MessageService.AskQuestion(msg, AlertButton.Cancel, AlertButton.OverwriteFile) != AlertButton.OverwriteFile)
                    {
                        return;
                    }
                }

                ctx     = new DeployContext(new TarballDeployTarget(dialog.GenerateAutotools), "Linux", null);
                monitor = IdeApp.Workbench.ProgressMonitors.GetToolOutputProgressMonitor(true);
                deployer.GenerateFiles(ctx, solution, dialog.DefaultConfiguration, monitor);
            }
            finally
            {
                dialog.Destroy();
                if (ctx != null)
                {
                    ctx.Dispose();
                }
                if (monitor != null)
                {
                    monitor.Dispose();
                }
            }
        }
        public void Execute(DeployContext context)
        {
            var maxAge = TimeSpan.FromDays(1);

            DirectoryUtil.CleanOldFiles(_asimovConfig.DownloadFolder, maxAge);

            var packageSource = _asimovConfig.GetPackageSourceFor(context.DeployUnit);

            context.TempFolderWithNewVersionFiles = packageSource.CopyAndExtractToTempFolder(context.NewVersion.Id, context.DeployUnit.PackageInfo, _asimovConfig.TempFolder, _asimovConfig.DownloadFolder);
        }
        private static void StopService(DeployContext context, ServiceController controller)
        {
            context.Log.InfoFormat("Stopping service {0}", controller.ServiceName);

            if (controller.Status == ServiceControllerStatus.Running)
                controller.Stop();

            controller.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMinutes(10));
            Thread.Sleep(2500);
        }
示例#26
0
        //[Produces("multipart/form-data")]
        public string Post()
        {
            try
            {
                List <ISeqTask> tasks = new List <ISeqTask>()
                {
                    new CheckKey(),
                    new SaveZip(),
                    new StopWebSite(),
                    new StopAppPool(),
                    new Deploy(),
                    new StartAppPool(),
                    new StartWebSite(),
                };
                Console.WriteLine("------Start Deployment " + DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss") + "------");
                var provider      = Request.Content.ReadAsMultipartAsync <InMemoryMultipartFormDataStreamProvider>(new InMemoryMultipartFormDataStreamProvider()).Result;
                var deployContext = new DeployContext()
                {
                    DeployFolder      = provider.FormData.GetValues("DeployFolder")[0],
                    SaveZipFolder     = provider.FormData.GetValues("SaveZipFolder")[0],
                    DeployKey         = provider.FormData.GetValues("DeployKey")[0],
                    DeployDescription = provider.FormData.GetValues("DeployDescription")[0],
                    WebSite           = ConfigurationManager.AppSettings["WebSite"],
                    AppPoolName       = ConfigurationManager.AppSettings["AppPoolName"],
                    ZipFileName       = (provider.FormData.GetValues("SaveZipFolder")[0] + @"\" +
                                         provider.Files[0].Headers.ContentDisposition.FileName).Replace(@"\\", @"\")
                                        .Replace(".zip", $"_{provider.FormData.GetValues("DeployDescription")[0] + "_" + Guid.NewGuid().ToString()}.zip"),
                    ZipStream      = provider.Files[0].ReadAsStreamAsync().Result,
                    AllowDeployKey = ConfigurationManager.AppSettings["AllowDeployKey"]
                };

                if (OnDeploying)
                {
                    Console.WriteLine("Deploy service is working..");
                    return("Deploy service is working..");
                }
                else
                {
                    OnDeploying = true;
                    foreach (var task in tasks)
                    {
                        Console.WriteLine(task.Invoke(deployContext));
                    }
                    OnDeploying = false;
                    Console.WriteLine("Success");
                    return("Success");
                }
            }
            catch (Exception ex)
            {
                OnDeploying = false;
                Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
                return(ex.Message);
            }
        }
示例#27
0
        public void Execute(DeployContext context)
        {
            var deployUnit = (FileCopyDeployUnit)context.DeployUnit;

            if (deployUnit.CleanTargetPath)
            {
                DirectoryUtil.Clean(deployUnit.TargetPath);
            }

            DirectoryUtil.CopyDirectory(context.TempFolderWithNewVersionFiles, deployUnit.TargetPath);
        }
        private static void StopService(DeployContext context, ServiceController controller)
        {
            context.Log.InfoFormat("Stopping service {0}", controller.ServiceName);

            if (controller.Status == ServiceControllerStatus.Running)
            {
                controller.Stop();
            }

            controller.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMinutes(10));
            Thread.Sleep(2500);
        }
 private void CleanSitePhysicalPath(DeployContext context, bool cleanDeploy)
 {
     if (cleanDeploy)
     {
         context.Log.Info("Cleaning site physical path...");
         DirectoryUtil.Clean(context.PhysicalPath);
     }
     else
     {
         context.Log.Info("Clean deploy disabled, skipping cleaning step");
     }
 }
示例#30
0
 private void CleanSitePhysicalPath(DeployContext context, bool cleanDeploy)
 {
     if (cleanDeploy)
     {
         context.Log.Info("Cleaning site physical path...");
         DirectoryUtil.Clean(context.PhysicalPath);
     }
     else
     {
         context.Log.Info("Clean deploy disabled, skipping cleaning step");
     }
 }
示例#31
0
        private void InstallServiceUsingInstallCommandFromConfig(DeployContext context)
        {
            var parameters = context.ParameterValues.Concat(new[]
            {
                new KeyValuePair <string, object>("ServiceName", _service.ServiceName)
            });

            ProcessUtil.ExecutePowershellScript(
                _installableConfig.TargetPath,
                _installableConfig.Install,
                parameters,
                context.Log, new [] { _installableConfig.ScriptsDir });
        }
		protected override bool OnBuild (ProgressMonitor monitor, DeployContext ctx)
		{
			string tmpFolder = null;

			try {
				SolutionConfigurationSelector conf = (SolutionConfigurationSelector) configuration;
				var bt = RootSolutionItem as IBuildTarget;
				if (bt != null) {
					BuildResult res = bt.Build (monitor, conf).Result;
					if (res.ErrorCount > 0) {
						foreach (BuildError e in res.Errors)
							monitor.ReportError (e.ToString (), null);
						monitor.ReportError (GettextCatalog.GetString ("The source project failed to build."), null);
						return false;
					}
				}
				
				tmpFolder = FileService.CreateTempDirectory ();
				
				string tf = Path.GetFileNameWithoutExtension (targetFile);
				if (tf.EndsWith (".tar")) tf = Path.GetFileNameWithoutExtension (tf);
				string folder = FileService.GetFullPath (Path.Combine (tmpFolder, tf));
				
				// Export the binary files
				DeployFileCollection deployFiles = GetDeployFiles (ctx, conf);
				foreach (DeployFile file in deployFiles) {
					string tfile = Path.Combine (folder, file.ResolvedTargetFile);
					string tdir = FileService.GetFullPath (Path.GetDirectoryName (tfile));
					if (!Directory.Exists (tdir))
						Directory.CreateDirectory (tdir);
					File.Copy (file.SourcePath, tfile, true);
				}
				
				// Create the archive
				string td = Path.GetDirectoryName (targetFile);
				if (!Directory.Exists (td))
					Directory.CreateDirectory (td);
				DeployService.CreateArchive (monitor, tmpFolder, targetFile);
			}
			catch (Exception ex) {
				monitor.ReportError ("Package creation failed", ex);
				LoggingService.LogError ("Package creation failed", ex);
				return false;
			}
			finally {
				if (tmpFolder != null)
					Directory.Delete (tmpFolder, true);
			}
			monitor.Log.WriteLine (GettextCatalog.GetString ("Created file: {0}", targetFile));
			return true;
		}
示例#33
0
        public string GetDirectory(DeployContext context, string folderId)
        {
            if (folderId == TargetDirectory.ProgramFiles)
            {
                return(string.Empty);
            }

            // While this would seem to be what the deploy API expects, for a web deploy it could
            // produces results the user wouldn't expect
            //if (context.Prefix != null)
            //	directory = Path.Combine (context.Prefix, directory);

            return(null);
        }
示例#34
0
        public void Deploy()
        {
            var deployContext = new DeployContext {
                UriName = _serviceData.Uri,
                DirectoryName = _serviceData.Directory,
                DatabaseName = _serviceData.Database,
                Mode = _serviceData.Mode
            };

            Console.WriteLine(deployContext.Mode == DeployMode.Install ? "Install is started." : "Update is started.");

            Deploy(deployContext, MD5.Create().ComputeHash(_serviceData.Files));

            Console.WriteLine("Please wait until this procedure is completed.");
        }
 public override string ResolveDirectory(DeployContext context, string folderId)
 {
     if (context.Platform == "Linux")
     {
         if (folderId == LinuxTargetDirectory.PkgConfig)
         {
             return(Path.Combine(context.GetDirectory(TargetDirectory.ProgramFilesRoot), "pkgconfig"));
         }
         if (folderId == LinuxTargetDirectory.DesktopApplications)
         {
             return(Path.Combine(context.GetDirectory(TargetDirectory.CommonApplicationDataRoot), "applications"));
         }
     }
     return(base.ResolveDirectory(context, folderId));
 }
示例#36
0
        public void Deploy()
        {
            var deployContext = new DeployContext {
                UriName       = _serviceData.Uri,
                DirectoryName = _serviceData.Directory,
                DatabaseName  = _serviceData.Database,
                Mode          = _serviceData.Mode
            };

            Console.WriteLine(deployContext.Mode == DeployMode.Install ? "Install is started." : "Update is started.");

            Deploy(deployContext, MD5.Create().ComputeHash(_serviceData.Files));

            Console.WriteLine("Please wait until this procedure is completed.");
        }
示例#37
0
        private void InstallTopShelfService(DeployContext context)
        {
            context.Log.InfoFormat("Service is marked as TopShelf, running install");

            var exePath = $"{_installableConfig.TargetPath}\\{_installableConfig.AssemblyName ?? context.DeployUnit.Name}.exe";

            context.Log.Info($"Installing: {exePath}");

            var args = new List <string> {
                "install"
            };

            args.AddRange(context.ParameterValues.Select(credential => $"-{credential.Key}={credential.Value}"));

            ProcessUtil.ExecuteCommand(exePath, args.ToArray(), context.Log);
        }
        private static ExecutionNode BuildFeatureNode(string featureName, DeployContext context)
        {
            FeatureConfig feature;
            if (!context.FeaturesConfig.TryGet(featureName, out feature))
                throw new SoftFailureException(string.Format("Cannot find feature {0}", featureName));

            var node = new ExecutionNode(string.Format("Begin feature {0}", featureName), string.Format("End feature {0}", featureName));
            foreach (var taskConfig in feature.Recipe)
            {
                var task = context.TaskManager.CreateTask(taskConfig);
                var replacer = new VariableReplacer(context.ApplicationContext, feature, taskConfig);
                node.AddChild(new ExecutionNode(task, new TaskExecutionContext(context.RunContext, feature, taskConfig, replacer)));
            }

            return node;
        }
		protected override bool OnBuild (IProgressMonitor monitor, DeployContext ctx)
		{
			string sourceFile;
			SolutionItem entry = RootSolutionItem;
			if (entry is SolutionFolder)
				sourceFile = entry.ParentSolution.FileName;
			else
				sourceFile = ((SolutionEntityItem)entry).FileName;
			
			AggregatedProgressMonitor mon = new AggregatedProgressMonitor ();
			mon.AddSlaveMonitor (monitor, MonitorAction.WriteLog|MonitorAction.ReportError|MonitorAction.ReportWarning|MonitorAction.ReportSuccess);
			
			string tmpFolder = FileService.CreateTempDirectory ();
			
			try {
				string tf = Path.GetFileNameWithoutExtension (targetFile);
				if (tf.EndsWith (".tar")) tf = Path.GetFileNameWithoutExtension (tf);
				
				string folder = FileService.GetFullPath (Path.Combine (tmpFolder, tf));
				Directory.CreateDirectory (folder);
				
				// Export the project
				
				SolutionItem[] ents = GetChildEntries ();
				string[] epaths = new string [ents.Length];
				for (int n=0; n<ents.Length; n++)
					epaths [n] = ents [n].ItemId;
				
				Services.ProjectService.Export (mon, sourceFile, epaths, folder, FileFormat);
				if (!mon.AsyncOperation.Success)
					return false;
				
				// Create the archive
				string td = Path.GetDirectoryName (targetFile);
				if (!Directory.Exists (td))
					Directory.CreateDirectory (td);
				DeployService.CreateArchive (mon, tmpFolder, targetFile);
			}
			finally {
				Directory.Delete (tmpFolder, true);
			}
			if (monitor.AsyncOperation.Success)
				monitor.Log.WriteLine (GettextCatalog.GetString ("Created file: {0}", targetFile));
			return true;
		}
        private static void StopService(DeployContext context, ServiceController controller)
        {
            var killProcess = context.ParameterValues.Any(a => a.Key == "ForceKillServiceProcess" && (a.Value == null || a.Value.ToString().ToLower() == "true"));

            context.Log.InfoFormat("Stopping service {0} {1}", controller.ServiceName, killProcess ? "forcefully" : "");

            if (killProcess)
            {
                controller.KillServiceProcess();
            }
            else
            {
                if (controller.Status == ServiceControllerStatus.Running)
                {
                    controller.StopServiceAndWaitForExit(DefaultStopTimeout);
                }
            }
        }
        private void CreateScriptFile(DeployContext context)
        {
            var deployUnit = (PowerShellDeployUnit) context.DeployUnit;

            var filePath = Path.Combine(_config.TempFolder, "asimov_generated.ps1");
            using (var fs = new StreamWriter(filePath, false, Encoding.UTF8))
            {
                var script = new StringBuilder(deployUnit.Script)
                    .Replace("%TEMP_FOLDER%", _config.TempFolder)
                    .Replace("%MACHINE_NAME%", Environment.MachineName);

                foreach (var parameter in context.DeployUnit.DeployParameters)
                {
                    var value = context.ParameterValues.GetValue(parameter.Name);
                    parameter.ApplyToPowershellScript(script, value);
                }

                fs.Write(script);
            }
        }
        public void Execute(DeployContext context)
        {
            var deployUnit = (WindowsServiceDeployUnit) context.DeployUnit;

            using (var controller = new ServiceController(deployUnit.ServiceName))
            {
                StopService(context, controller);

                context.PhysicalPath = WindowsServiceUtil.GetWindowsServicePath(deployUnit.ServiceName);

                CleanPhysicalPath(context);

                CopyNewFiles(context);

                context.Log.InfoFormat("Starting service {0}", deployUnit.ServiceName);
                controller.Start();

                controller.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMinutes(1));
            }
        }
		public override void CopyFiles (IProgressMonitor monitor, IFileReplacePolicy replacePolicy, FileCopyConfiguration copyConfig, DeployFileCollection deployFiles, DeployContext context)
		{
			DirectoryInfo tempDir = null;
			try {
				tempDir = CreateTempDir ();
			} catch (Exception e) {
				monitor.ReportError (GettextCatalog.GetString ("Could not create temporary directory."), e);
				return;
			}
			
			try {
				MountTempDirectory (monitor, copyConfig, tempDir.FullName);
			} catch (Exception e) {
				monitor.ReportError (GettextCatalog.GetString ("Could not mount FUSE filesystem."), e);
				RemoveTempDirIfEmpty (tempDir);
				return;
			}
			
			try {
				base.InternalCopyFiles (monitor, replacePolicy, copyConfig, deployFiles, context, tempDir.FullName);
			} finally {
				//unmount the filesystem
				try {
					string escapedDir = tempDir.FullName.Replace ("\"", "\\\"");
					string cmd, args;
					
					if (PropertyService.IsMac) {
						cmd = "umount";
						args = string.Format ("\"{0}\"", escapedDir);
					} else {
						cmd = "fusermount";
						args = string.Format ("-u \"{0}\"", escapedDir);
					}
					RunFuseCommand (monitor, cmd, args);
				} catch (Exception e) {
					LoggingService.LogError (GettextCatalog.GetString ("Could not unmount FUSE filesystem."), e);
					monitor.ReportError (GettextCatalog.GetString ("Could not unmount FUSE filesystem."), e);
				}
				RemoveTempDirIfEmpty (tempDir);
			}
		}
        public void Execute(DeployContext context)
        {
            var deployUnit = (WebSiteDeployUnit) context.DeployUnit;
            var webServer = deployUnit.GetWebServer();

            var siteData = webServer.GetInfo();
            if (siteData == null)
                throw new DeployException("Site not found: " + deployUnit.SiteName);

            context.Log.Info("Stopping AppPool...");
            webServer.StopAppPool();

            context.PhysicalPath = siteData.PhysicalPath;

            CleanSitePhysicalPath(context, deployUnit.CleanDeploy);

            CopyNewFilesToPhysicalPath(context);

            context.Log.Info("Starting AppPool...");
            webServer.StartAppPool();
        }
            public StateHash Run(DeployContext context, StateHash hash, ICacheManager cacheManager, bool first = true, bool last = true)
            {
                if (mLogPre != null)
                    context.ApplicationContext.Log.Log(mLogPre);

                if (mTransform != null)
                {
                    var stopWatch = new Stopwatch();
                    stopWatch.Start();
                    hash = mTransform.RunTransform(hash, context.DryRun, context.ApplicationContext.Log);
                    stopWatch.Stop();

                    if (!context.DryRun)
                    {
                        var rhf = GetResumeHashFile(context);
                        File.WriteAllText(rhf.FullName, hash.ToHexString());
                    }

                    if (!first && !last && stopWatch.Elapsed >= context.ApplicationContext.UserConfig.Cache.MinDeployTime)
                    {
                        foreach (var db in context.ApplicationContext.ProjectConfig.Databases)
                        {
                            cacheManager.Add(context.ApplicationContext.UserConfig.Databases.Connection, db, hash);
                        }
                    }
                }
                else if (mChildren.Count > 0)
                {
                    using (context.ApplicationContext.Log.IndentScope())
                    {
                        for (var i = 0; i < mChildren.Count; i++)
                        {
                            var child = mChildren[i];
                            hash = child.Run(context, hash, cacheManager, first, last && i == mChildren.Count - 1);
                            first = false;
                        }
                    }
                }

                if (mLogPost != null)
                    context.ApplicationContext.Log.Log(mLogPost);

                return hash;
            }
            public Tuple<ExecutionNode, StateHash, bool, StateHash> Calculate(DeployContext context, StateHash hash, StateHash startingHash, ICacheManager cacheManager)
            {
                if (mTransform != null)
                {
                    hash = mTransform.CalculateTransform(hash);
                    if (hash == startingHash)
                        return Tuple.Create((ExecutionNode)null, hash, true, (StateHash)null);

                    var backups = GetCachedBackups(cacheManager, hash, context.ApplicationContext.ProjectConfig.Databases);
                    if (backups != null)
                    {
                        var node = new ExecutionNode("Restoring state from cache...", "Cache restored");
                        node.AddChild(new ExecutionNode(new RestoreDatabasesTransform(context.ApplicationContext.UserConfig.Databases.Connection, backups, hash)));

                        return Tuple.Create(node, hash, true, hash);
                    }
                }
                else if (mChildren.Count > 0)
                {
                    var result = new ExecutionNode(mLogPre, mLogPost);
                    var changed = false;
                    StateHash cacheHash = null;

                    foreach (var child in mChildren)
                    {
                        var calc = child.Calculate(context, hash, startingHash, cacheManager);
                        if (calc.Item3)
                        {
                            changed = true;
                            result.mChildren.Clear();
                        }

                        if (calc.Item1 != null)
                            result.mChildren.Add(calc.Item1);

                        hash = calc.Item2;
                        if (calc.Item4 != null)
                            cacheHash = calc.Item4;
                    }

                    if (result.mChildren.Count == 0)
                        result = null;

                    return Tuple.Create(result, hash, changed, cacheHash);
                }

                return Tuple.Create(this, hash, false, (StateHash)null);
            }
        private static void RunCore(DeployContext context)
        {
            Beep(context, "start");

            var plan = ActionPlan.Build(context.RunContext);

            var root = new ExecutionNode("Begin deploy", "Deploy completed");
            root.AddChild(BuildRestoreDatabasesNode(plan.Databases, context));

            foreach (var release in plan.Releases)
            {
                var releaseNode = BuildReleaseNode(release, context);
                root.AddChild(releaseNode);
            }

            var hash = StateHash.Empty;
            try
            {
                StateHash startingHash = null;
                if (context.Resume)
                {
                    startingHash = LoadResumeHash(context);
                }

                var improved = root.Calculate(context, hash, startingHash, context.CacheManager);
                if (improved.Item3)
                {
                    root = improved.Item1;
                    if (improved.Item4 != null)
                    {
                        context.CacheManager.UpdateHits(context.ApplicationContext.ProjectConfig.Databases.Select(x => Tuple.Create(x, improved.Item4)));
                    }
                }

                var sink = new CheckingRequirementSink(context.ApplicationContext.Log);
                root.GetRequirements(sink);
                if (sink.Finish())
                    throw new SoftFailureException("Command aborted due to unmet requirements.");

                root.Run(context, startingHash ?? hash, context.CacheManager);

                if (!context.DryRun)
                    CleanResumeHash(context);
            }
            catch (SoftFailureException ex)
            {
                Beep(context, "error");
                throw new SoftFailureException("Blocking error detected", ex);
            }

            Beep(context, "success");
        }
        private static StateHash LoadResumeHash(DeployContext context)
        {
            var file = GetResumeHashFile(context);
            if (!file.Exists)
                throw new SoftFailureException("Cannot find resume hash");

            using (var fs = file.OpenRead())
            using (var r = new StreamReader(fs))
            {
                var line = r.ReadLine();
                try
                {
                    return StateHash.FromHexString(line);
                }
                catch (Exception ex)
                {
                    throw new SoftFailureException("Invalid resume hash format", ex);
                }
            }
        }
 private static FileInfo GetResumeHashFile(DeployContext context)
 {
     return new FileInfo(Path.Combine(context.ApplicationContext.ProjectRoot, ".dbbm.resume"));
 }
        private static ExecutionNode BuildReleaseNode(ReleaseConfig release, DeployContext context)
        {
            var node = new ExecutionNode(string.Format("Begin release {0}", release.Name), string.Format("End release {0}", release.Name));
            foreach (var feature in release.Features)
            {
                node.AddChild(BuildFeatureNode(feature, context));
            }

            return node;
        }
示例#51
0
		internal void InternalCopyFiles (IProgressMonitor monitor, IFileReplacePolicy replacePolicy, FileCopyConfiguration copyConfig, DeployFileCollection deployFiles, DeployContext context, string realPrefix)
		{
			string targetDirectory = ((LocalFileCopyConfiguration) copyConfig).TargetDirectory;
			
			if (string.IsNullOrEmpty (copyConfig.FriendlyLocation) || string.IsNullOrEmpty (targetDirectory))
				throw new InvalidOperationException ("Cannot deploy to unconfigured location.");
			
			List<DeployFileConf> files = new List<DeployFileConf> ();
			long totalFileSize = 0;
			
			//pre-scan: ask all copy/replace questions first so user doesn't have to wait, and get 
			foreach (DeployFile df in deployFiles) {
				if (!context.IncludeFile (df))
					continue;
				
				DeployFileConf dfc = new DeployFileConf ();
				files.Add (dfc);
				dfc.SourceFile = df.SourcePath;
				dfc.FileSize = FileSize (dfc.SourceFile);
				totalFileSize += dfc.FileSize;
				
				string relativeTarget = context.GetResolvedPath (df.TargetDirectoryID, df.RelativeTargetPath);
				if (relativeTarget == null)
					throw new InvalidOperationException (GettextCatalog.GetString ("Could not resolve target directory ID \"{0}\"", df.TargetDirectoryID));
				dfc.TargetFile = Path.Combine (targetDirectory, relativeTarget);
				
				//this is a bit hacky; it's an internal hook to the BaseFuseFileCopyHandler implementation a level up the inheritance heirarchy
				//Essentailly we are aliasing the path so that  BaseFuseFileCopyHandler can use LocalFileCopyHandler to do the local copying 
				//after the temp FUSE directory is mounted
				if (!string.IsNullOrEmpty (realPrefix)) {
					dfc.InternalTargetFile = Path.Combine (realPrefix, context.GetResolvedPath (df.TargetDirectoryID, df.RelativeTargetPath));
				} else {
					dfc.InternalTargetFile = dfc.TargetFile;
				}
				
				if (FileExists (dfc.InternalTargetFile)) {
					dfc.SourceModified = File.GetLastWriteTime (dfc.SourceFile);
					dfc.TargetModified = GetTargetModificationTime (dfc.InternalTargetFile);
					dfc.ReplaceMode = replacePolicy.GetReplaceAction (dfc.SourceFile, dfc.SourceModified, dfc.TargetFile, dfc.TargetModified);
					if (dfc.ReplaceMode == FileReplaceMode.Abort) {
						monitor.Log.WriteLine (GettextCatalog.GetString ("Deployment aborted: target file {0} already exists.", dfc.TargetFile));
						throw new OperationCanceledException ();
					}
				}
			}
			
			//PROBLEM: monitor takes ints, file sizes are longs
			//HOWEVER: longs are excessively long for a progress bar
			//SOLUTION: assume total task has a length of 1000 (longer than this is probably unnecessary for a progress bar),
			//  and set up a callback system for translating the actual long number of bytes into a portion of this
			const int progressBarLength = 1000;
			long stepSize = totalFileSize / progressBarLength;
			long carry = 0; 
			monitor.BeginTask (copyConfig.FriendlyLocation, progressBarLength);
			CopyReportCallback copyCallback = delegate (long bytes) {
				if (monitor.IsCancelRequested)
					return false;
				int steps = (int) (bytes / stepSize);
				carry += bytes % stepSize;
				if (carry > stepSize) {
					steps += 1;
					carry -= stepSize;
				}
				if (steps > 0)
					monitor.Step (steps);
				return true;
			};
			
			//now the actual copy
			foreach (DeployFileConf file in files) {
				//abort the copy if cancelling
				if (monitor.IsCancelRequested)
					break;
				
				EnsureDirectoryExists (Path.GetDirectoryName (file.InternalTargetFile));
				
				if (file.ReplaceMode != FileReplaceMode.NotSet) {
					switch (file.ReplaceMode) {
					case FileReplaceMode.Skip:
						monitor.Log.WriteLine (GettextCatalog.GetString ("Skipped {0}: file exists.", file.TargetFile));
						copyCallback (file.FileSize);
						continue; //next file
					
					case FileReplaceMode.Replace:
						monitor.Log.WriteLine (GettextCatalog.GetString ("Replaced {0}.", file.TargetFile));
						break;
					
					case FileReplaceMode.ReplaceOlder:
						if (file.SourceModified > file.TargetModified) {
							monitor.Log.WriteLine (GettextCatalog.GetString ("Replacing {0}: existing file is older.", file.TargetFile));
						} else {
							if (file.SourceModified == file.TargetModified)
								monitor.Log.WriteLine (GettextCatalog.GetString ("Skipped {0}: existing file is the same age.", file.TargetFile));
							else
								monitor.Log.WriteLine (GettextCatalog.GetString ("Skipped {0}: existing file is newer.", file.TargetFile));
							copyCallback (file.FileSize);
							continue; //next file
						}
						break;
					}
				}
				else {
					monitor.Log.WriteLine (GettextCatalog.GetString ("Deployed file {0}.", file.TargetFile));
				}
				
				CopyFile (file.SourceFile, file.InternalTargetFile, copyCallback);
			}
			
			monitor.EndTask ();
		}
示例#52
0
		public virtual void CopyFiles (IProgressMonitor monitor, IFileReplacePolicy replacePolicy, FileCopyConfiguration copyConfig, DeployFileCollection deployFiles, DeployContext context)
		{
			InternalCopyFiles (monitor, replacePolicy, copyConfig, deployFiles, context, null);
		}
 private void CleanPhysicalPath(DeployContext context)
 {
     context.Log.InfoFormat("Cleaning folder {0}", context.PhysicalPath);
     DirectoryUtil.Clean(context.PhysicalPath);
 }
 private void CopyNewFiles(DeployContext context)
 {
     context.Log.InfoFormat("Copying new files");
     DirectoryUtil.CopyDirectory(context.TempFolderWithNewVersionFiles, context.PhysicalPath);
 }
示例#55
0
		protected override bool OnBuild (IProgressMonitor monitor, DeployContext ctx)
		{
			string consMsg;
			IConsole cons;
			if (ExternalConsole) {
				cons = ExternalConsoleFactory.Instance.CreateConsole (CloseConsoleWhenDone);
				consMsg = GettextCatalog.GetString ("(in external terminal)");
			} else {
				cons = new MonitorConsole (monitor);
				consMsg = "";
			}
			
			monitor.Log.WriteLine (GettextCatalog.GetString ("Executing: {0} {1} {2}", Command, Arguments, consMsg));
			IProcessAsyncOperation process = Runtime.ProcessService.StartConsoleProcess (Command, Arguments, workingDirectory, cons, null);
			
			process.WaitForCompleted ();
			
			if (cons is MonitorConsole) {
				((MonitorConsole)cons).Dispose ();
			}
			return true;
		}
		protected override string OnResolveDirectory (DeployContext ctx, string folderId)
		{
			return ".";
		}
        private void CopyNewFilesToPhysicalPath(DeployContext context)
        {
            context.Log.Info("Copying files...");

            DirectoryUtil.CopyDirectory(context.TempFolderWithNewVersionFiles, context.PhysicalPath);
        }
 private static void CleanResumeHash(DeployContext context)
 {
     var file = GetResumeHashFile(context);
     file.Delete();
 }
 private static ExecutionNode BuildRestoreDatabasesNode(DatabaseBackupInfo[] databases, DeployContext context)
 {
     var node = new ExecutionNode("Restoring databases...", "All databases restored!");
     node.AddChild(new ExecutionNode(new RestoreDatabasesTransform(context.ApplicationContext.UserConfig.Databases.Connection, databases)));
     return node;
 }
 private bool beginCFSession(DeployContext context)
 {
     context.CFClient = new Mono.CFoundry.Client(context.Endpoint, true);
     return context.CFClient.Login(context.Username, context.Password);
 }