Ejemplo n.º 1
0
        public bool UninstallExtension(string id)
        {
            string installationDirectory = GetInstallationDirectory(id);

            SiteExtensionInfo info = GetLocalExtension(id, checkLatest: false);

            if (info == null || !FileSystemHelpers.DirectoryExists(info.LocalPath))
            {
                throw new DirectoryNotFoundException(installationDirectory);
            }

            var externalCommandFactory = new ExternalCommandFactory(_environment, _settings, installationDirectory);

            string uninstallScript = Path.Combine(installationDirectory, _uninstallScriptName);

            if (FileSystemHelpers.FileExists(uninstallScript))
            {
                OperationManager.Attempt(() =>
                {
                    Executable exe = externalCommandFactory.BuildCommandExecutable(uninstallScript,
                                                                                   installationDirectory,
                                                                                   _settings.GetCommandIdleTimeout(), NullLogger.Instance);
                    exe.ExecuteWithProgressWriter(NullLogger.Instance, _traceFactory.GetTracer(), String.Empty);
                });
            }

            OperationManager.Attempt(() => CleanupSiteExtensionJobs(id));

            OperationManager.Attempt(() => FileSystemHelpers.DeleteFileSafe(GetNuGetPackageFile(info.Id, info.Version)));

            OperationManager.Attempt(() => FileSystemHelpers.DeleteDirectorySafe(installationDirectory));

            return(GetLocalExtension(id, checkLatest: false) == null);
        }
Ejemplo n.º 2
0
        private DeploymentStatusFile(string id, IEnvironment environment, IOperationLock statusLock, XDocument document = null)
        {
            _activeFile = Path.Combine(environment.DeploymentsPath, Constants.ActiveDeploymentFile);
            _statusFile = Path.Combine(environment.DeploymentsPath, id, StatusFile);
            _statusLock = statusLock;

            Id = id;

            SiteName = GetSiteName(environment);
            HostName = System.Environment.GetEnvironmentVariable("HTTP_HOST");

            if (document != null)
            {
                Initialize(document);
            }

            // Ensure that the status file is created before we enter this code block
            Task ensureLogFileExists = Task.Run(() =>
                                                OperationManager.Attempt(() =>
            {
                if (!FileSystemHelpers.FileExists(_statusFile))
                {
                    throw new FileNotFoundException("Status file doesn't exist. Will wait for 1 second and retry");
                }
            }, 2, 250));
        }
Ejemplo n.º 3
0
        private IEnumerable <WebHook> ReadWebHooksFromFile()
        {
            string fileContent = null;

            if (!FileSystemHelpers.FileExists(_hooksFilePath))
            {
                return(Enumerable.Empty <WebHook>());
            }

            OperationManager.Attempt(() => fileContent = FileSystemHelpers.ReadAllText(_hooksFilePath));

            if (!String.IsNullOrEmpty(fileContent))
            {
                try
                {
                    // It is possible for Deserialize to not throw and return null.
                    return(JsonConvert.DeserializeObject <IEnumerable <WebHook> >(fileContent, JsonSerializerSettings) ?? Enumerable.Empty <WebHook>());
                }
                catch (JsonSerializationException ex)
                {
                    _tracer.TraceError(ex);
                }
            }

            return(Enumerable.Empty <WebHook>());
        }
Ejemplo n.º 4
0
        public void Save(IFileSystem fileSystem)
        {
            if (String.IsNullOrEmpty(Id))
            {
                throw new InvalidOperationException();
            }

            var document = new XDocument(new XElement("deployment",
                                                      new XElement("id", Id),
                                                      new XElement("author", Author),
                                                      new XElement("deployer", Deployer),
                                                      new XElement("authorEmail", AuthorEmail),
                                                      new XElement("message", Message),
                                                      new XElement("status", Status),
                                                      new XElement("statusText", StatusText),
                                                      new XElement("lastSuccessEndTime", LastSuccessEndTime),
                                                      new XElement("receivedTime", ReceivedTime),
                                                      new XElement("startTime", StartTime),
                                                      new XElement("endTime", EndTime),
                                                      new XElement("complete", Complete.ToString())
                                                      ));

            // Retry saves to the file to make it robust incase of failure
            OperationManager.Attempt(() =>
            {
                using (Stream stream = fileSystem.File.Create(_path))
                {
                    document.Save(stream);
                }
            });
        }
Ejemplo n.º 5
0
        public override async Task Build(DeploymentContext context)
        {
            // A console worker consists of the console worker site and the binaries to run.
            // Tree looks like so:
            // site\
            //   wwwroot\
            //     global.asax     (this contains the worker site's logic)
            //     web.config
            //   bin\
            //     run_worker.cmd  (the startup script for the worker process, this will contain the command to run as the worker)
            //     %worker files%  (these are the deployed user files to use for the worker process)

            string destinationPath   = context.BuildTempPath;
            string consoleWorkerPath = Path.Combine(Environment.ScriptPath, "ConsoleWorker");

            CopyFileFromTemplate(consoleWorkerPath, destinationPath, "global.asax");
            CopyFileFromTemplate(consoleWorkerPath, destinationPath, "web.config");

            string scriptDirectoryPath = Path.Combine(destinationPath, "bin");
            string scriptFilePath      = Path.Combine(scriptDirectoryPath, "run_worker.cmd");
            string scriptContent       = "@echo off\n{0}\n".FormatInvariant(Command);

            OperationManager.Attempt(() =>
            {
                FileSystemHelpers.EnsureDirectory(scriptDirectoryPath);
                File.WriteAllText(scriptFilePath, scriptContent);
            });

            await base.Build(context);
        }
Ejemplo n.º 6
0
        public static void RemoveAppOfflineIfLeft(IEnvironment environment, IOperationLock deploymentLock, ITracer tracer)
        {
            string appOfflineFile = null;

            try
            {
                appOfflineFile = Path.Combine(environment.WebRootPath, Constants.AppOfflineFileName);
                if (FileSystemHelpers.FileExists(appOfflineFile))
                {
                    var appOfflineContent = OperationManager.Attempt(() => FileSystemHelpers.ReadAllText(appOfflineFile));
                    if (appOfflineContent.Contains(Constants.AppOfflineKuduContent))
                    {
                        if (deploymentLock != null && deploymentLock.IsHeld)
                        {
                            tracer.Trace($"Deployment lock is held, will not remove {appOfflineFile}");
                        }
                        else
                        {
                            tracer.Trace($"Removing leftover {appOfflineFile}");
                            OperationManager.Attempt(() => FileSystemHelpers.DeleteFile(appOfflineFile));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                tracer.TraceError($"Error removing leftover {appOfflineFile} with {ex}");
            }
        }
Ejemplo n.º 7
0
        public void Log(IDictionary <string, object> siteExtensionLogEvent)
        {
            using (_tracer.Step("Site Extension Log"))
            {
                try
                {
                    // TODO: Consider doing cleanup only once per X minutes
                    HandleCleanup();

                    string message = JsonConvert.SerializeObject(siteExtensionLogEvent, JsonSerializerSettings);

                    _tracer.Trace("{0}", message);

                    OperationManager.Attempt(() =>
                    {
                        using (var streamWriter = new StreamWriter(_fileSystem.File.Open(_currentPath, FileMode.Append, FileAccess.Write, FileShare.Read)))
                        {
                            streamWriter.WriteLine(message);
                        }
                    });
                }
                catch (Exception ex)
                {
                    _tracer.TraceError(ex);
                }
            }
        }
Ejemplo n.º 8
0
        private IEnumerable <WebHook> ReadWebHooksFromFile()
        {
            string fileContent = null;

            if (!_fileSystem.File.Exists(_hooksFilePath))
            {
                return(Enumerable.Empty <WebHook>());
            }

            OperationManager.Attempt(() => fileContent = _fileSystem.File.ReadAllText(_hooksFilePath));

            if (!String.IsNullOrEmpty(fileContent))
            {
                try
                {
                    return(JsonConvert.DeserializeObject <IEnumerable <WebHook> >(fileContent, JsonSerializerSettings));
                }
                catch (JsonSerializationException ex)
                {
                    _tracer.TraceError(ex);
                }
            }

            return(Enumerable.Empty <WebHook>());
        }
Ejemplo n.º 9
0
        private DiagnosticsSettings ReadSettings()
        {
            if (FileSystemHelpers.FileExists(_path))
            {
                try
                {
                    string fileContent = null;
                    OperationManager.Attempt(() => fileContent = FileSystemHelpers.ReadAllTextFromFile(_path));

                    var settings = JsonConvert.DeserializeObject <DiagnosticsSettings>(fileContent);
                    if (settings == null)
                    {
                        throw new InvalidOperationException($"File '{_path}' content is empty or contains only white spaces.");
                    }

                    return(settings);
                }
                catch (Exception ex)
                {
                    _tracer.TraceError(ex);

                    // there must be corrupted value, delete file to reset everything to default
                    FileSystemHelpers.DeleteFileSafe(_path);
                }
            }

            return(new DiagnosticsSettings());
        }
Ejemplo n.º 10
0
        public static DeploymentStatusFile Open(string id, IEnvironment environment, IAnalytics analytics, IOperationLock statusLock)
        {
            return(statusLock.LockOperation(() =>
            {
                string path = Path.Combine(environment.DeploymentsPath, id, StatusFile);

                if (!FileSystemHelpers.FileExists(path))
                {
                    return null;
                }

                try
                {
                    // In case we read status file in middle of a write, attempt to
                    // read it again. Don't fail the status get request
                    XDocument document = OperationManager.Attempt(() => LoadXmlStatusFile(path), 2, 250);
                    return new DeploymentStatusFile(id, environment, statusLock, document);
                }
                catch (Exception ex)
                {
                    // in the scenario where w3wp is abruptly terminated while xml is being written,
                    // we may end up with corrupted xml.  we will handle the error and remove the problematic directory.
                    analytics.UnexpectedException(ex);

                    FileSystemHelpers.DeleteDirectorySafe(Path.GetDirectoryName(path), ignoreErrors: true);

                    // it is ok to return null as callers already handle null.
                    return null;
                }
            }, "Getting deployment status", DeploymentStatusManager.LockTimeout));
        }
Ejemplo n.º 11
0
        public bool UninstallExtension(string id)
        {
            string installationDirectory = GetInstallationDirectory(id);

            if (!FileSystemHelpers.DirectoryExists(installationDirectory))
            {
                throw new DirectoryNotFoundException(installationDirectory);
            }

            OperationManager.Attempt(() =>
            {
                var externalCommandFactory = new ExternalCommandFactory(_environment, _settings, installationDirectory);
                string uninstallScript     = Path.Combine(installationDirectory, _uninstallScriptName);
                if (FileSystemHelpers.FileExists(uninstallScript))
                {
                    Executable exe = externalCommandFactory.BuildCommandExecutable(uninstallScript, installationDirectory,
                                                                                   _settings.GetCommandIdleTimeout(), NullLogger.Instance);
                    exe.ExecuteWithProgressWriter(NullLogger.Instance, _traceFactory.GetTracer(), String.Empty);
                }

                FileSystemHelpers.DeleteDirectorySafe(installationDirectory);
            });

            return(!FileSystemHelpers.DirectoryExists(installationDirectory));
        }
Ejemplo n.º 12
0
        public void Save()
        {
            if (String.IsNullOrEmpty(Id))
            {
                throw new InvalidOperationException();
            }

            var document = new XDocument(new XElement("deployment",
                                                      new XElement("id", Id),
                                                      new XElement("author", XmlUtility.Sanitize(Author)),
                                                      new XElement("deployer", Deployer),
                                                      new XElement("authorEmail", AuthorEmail),
                                                      new XElement("message", XmlUtility.Sanitize(Message)),
                                                      new XElement("progress", Progress),
                                                      new XElement("status", Status),
                                                      new XElement("statusText", StatusText),
                                                      new XElement("lastSuccessEndTime", LastSuccessEndTime),
                                                      new XElement("receivedTime", ReceivedTime),
                                                      new XElement("startTime", StartTime),
                                                      new XElement("endTime", EndTime),
                                                      new XElement("complete", Complete.ToString()),
                                                      new XElement("is_temp", IsTemporary.ToString()),
                                                      new XElement("is_readonly", IsReadOnly.ToString())
                                                      ));

            _statusLock.LockOperation(() =>
            {
                using (Stream stream = FileSystemHelpers.CreateFile(_statusFile))
                {
                    document.Save(stream);
                }

                OperationManager.Attempt(() =>
                {
                    // Used for ETAG
                    if (FileSystemHelpers.FileExists(_activeFile))
                    {
                        FileSystemHelpers.SetLastWriteTimeUtc(_activeFile, DateTime.UtcNow);
                    }
                    else
                    {
                        FileSystemHelpers.WriteAllText(_activeFile, String.Empty);
                    }
                });

                OperationManager.Attempt(() =>
                {
                    // enable the feature thru configuration
                    if (ScmHostingConfigurations.DeploymentStatusCompleteFileEnabled && Complete)
                    {
                        FileSystemHelpers.CopyFile(_statusFile, _statusCompleteFile);
                    }
                    else if (FileSystemHelpers.FileExists(_statusCompleteFile))
                    {
                        FileSystemHelpers.DeleteFile(_statusCompleteFile);
                    }
                });
            }, "Updating deployment status", DeploymentStatusManager.LockTimeout);
        }
Ejemplo n.º 13
0
        public async Task <bool> UninstallExtension(string id)
        {
            ITracer tracer = _traceFactory.GetTracer();

            string installationDirectory = GetInstallationDirectory(id);

            SiteExtensionInfo info = await GetLocalExtension(id, checkLatest : false);

            if (info == null || !FileSystemHelpers.DirectoryExists(info.LocalPath))
            {
                tracer.TraceError("Site extension {0} not found.", id);
                throw new DirectoryNotFoundException(installationDirectory);
            }

            if (IsInstalledToWebRoot(id))
            {
                // special handling for package that install in wwwroot instead of under site extension folder
                tracer.Trace("Clear all content in wwwroot");
                OperationManager.Attempt(() => FileSystemHelpers.DeleteDirectoryContentsSafe(_environment.WebRootPath));
            }
            else
            {
                // default action for site extension uninstall

                // only site extension has below infomation
                var externalCommandFactory = new ExternalCommandFactory(_environment, _settings, installationDirectory);

                string uninstallScript = Path.Combine(installationDirectory, _uninstallScriptName);

                if (FileSystemHelpers.FileExists(uninstallScript))
                {
                    using (tracer.Step("Execute uninstall.cmd"))
                    {
                        OperationManager.Attempt(() =>
                        {
                            Executable exe = externalCommandFactory.BuildCommandExecutable(uninstallScript,
                                                                                           installationDirectory,
                                                                                           _settings.GetCommandIdleTimeout(), NullLogger.Instance);
                            exe.ExecuteWithProgressWriter(NullLogger.Instance, _traceFactory.GetTracer(), String.Empty);
                        });
                    }
                }

                using (tracer.Step("Remove site extension job"))
                {
                    OperationManager.Attempt(() => CleanupSiteExtensionJobs(id));
                }
            }

            using (tracer.Step("Delete site extension package, directory and arm settings"))
            {
                OperationManager.Attempt(() => FileSystemHelpers.DeleteFileSafe(GetNuGetPackageFile(info.Id, info.Version)));
                OperationManager.Attempt(() => FileSystemHelpers.DeleteDirectorySafe(installationDirectory));
                SiteExtensionStatus armSettings = new SiteExtensionStatus(_environment.SiteExtensionSettingsPath, id, tracer);
                await armSettings.RemoveStatus();
            }

            return(await GetLocalExtension(id, checkLatest : false) == null);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// <para>1. Download package</para>
        /// <para>2. Generate xdt file if not exist</para>
        /// <para>3. Deploy site extension job</para>
        /// <para>4. Execute install.cmd if exist</para>
        /// </summary>
        private async Task <UIPackageMetadata> InstallExtension(UIPackageMetadata package, string installationDirectory, string feedUrl)
        {
            ITracer tracer = _traceFactory.GetTracer();

            try
            {
                if (FileSystemHelpers.DirectoryExists(installationDirectory))
                {
                    FileSystemHelpers.DeleteDirectorySafe(installationDirectory);
                }

                SourceRepository remoteRepo = GetRemoteRepository(feedUrl);

                // Copy content folder
                // Copy nupkg file for package list/lookup
                FileSystemHelpers.CreateDirectory(installationDirectory);
                // package path from local repo
                string packageLocalFilePath = GetNuGetPackageFile(package.Identity.Id, package.Identity.Version.ToString());
                using (tracer.Step("Download site extension: {0}", package.Identity))
                {
                    await remoteRepo.DownloadPackageToFolder(package.Identity, installationDirectory, pathToLocalCopyOfNudpk : packageLocalFilePath);
                }

                // If there is no xdt file, generate default.
                using (tracer.Step("Check if applicationhost.xdt file existed."))
                {
                    GenerateApplicationHostXdt(installationDirectory, '/' + package.Identity.Id, isPreInstalled: false, tracer: tracer);
                }

                using (tracer.Step("Trigger site extension job"))
                {
                    OperationManager.Attempt(() => DeploySiteExtensionJobs(package.Identity.Id));
                }

                var    externalCommandFactory = new ExternalCommandFactory(_environment, _settings, installationDirectory);
                string installScript          = Path.Combine(installationDirectory, _installScriptName);
                if (FileSystemHelpers.FileExists(installScript))
                {
                    using (tracer.Step("Execute install.cmd"))
                    {
                        OperationManager.Attempt(() =>
                        {
                            Executable exe = externalCommandFactory.BuildCommandExecutable(installScript,
                                                                                           installationDirectory,
                                                                                           _settings.GetCommandIdleTimeout(), NullLogger.Instance);
                            exe.ExecuteWithProgressWriter(NullLogger.Instance, _traceFactory.GetTracer(), String.Empty);
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                tracer.TraceError(ex);
                FileSystemHelpers.DeleteDirectorySafe(installationDirectory);
                throw;
            }

            return(await _localRepository.GetLatestPackageById(package.Identity.Id));
        }
Ejemplo n.º 15
0
        private IPackage InstallExtension(IPackage package, string installationDirectory)
        {
            try
            {
                if (FileSystemHelpers.DirectoryExists(installationDirectory))
                {
                    FileSystemHelpers.DeleteDirectorySafe(installationDirectory);
                }

                foreach (IPackageFile file in package.GetContentFiles())
                {
                    // It is necessary to place applicationHost.xdt under site extension root.
                    string contentFilePath = file.Path.Substring("content/".Length);
                    string fullPath        = Path.Combine(installationDirectory, contentFilePath);
                    FileSystemHelpers.CreateDirectory(Path.GetDirectoryName(fullPath));
                    using (Stream writeStream = FileSystemHelpers.OpenWrite(fullPath), readStream = file.GetStream())
                    {
                        OperationManager.Attempt(() => readStream.CopyTo(writeStream));
                    }
                }

                // If there is no xdt file, generate default.
                GenerateApplicationHostXdt(installationDirectory, '/' + package.Id, isPreInstalled: false);

                OperationManager.Attempt(() => DeploySiteExtensionJobs(package.Id));

                var    externalCommandFactory = new ExternalCommandFactory(_environment, _settings, installationDirectory);
                string installScript          = Path.Combine(installationDirectory, _installScriptName);
                if (FileSystemHelpers.FileExists(installScript))
                {
                    OperationManager.Attempt(() =>
                    {
                        Executable exe = externalCommandFactory.BuildCommandExecutable(installScript,
                                                                                       installationDirectory,
                                                                                       _settings.GetCommandIdleTimeout(), NullLogger.Instance);
                        exe.ExecuteWithProgressWriter(NullLogger.Instance, _traceFactory.GetTracer(), String.Empty);
                    });
                }

                // Copy nupkg file for package list/lookup
                FileSystemHelpers.CreateDirectory(installationDirectory);
                string packageFilePath = GetNuGetPackageFile(package.Id, package.Version.ToString());
                using (
                    Stream readStream = package.GetStream(), writeStream = FileSystemHelpers.OpenWrite(packageFilePath))
                {
                    OperationManager.Attempt(() => readStream.CopyTo(writeStream));
                }
            }
            catch (Exception ex)
            {
                ITracer tracer = _traceFactory.GetTracer();
                tracer.TraceError(ex);
                FileSystemHelpers.DeleteDirectorySafe(installationDirectory);
                throw;
            }

            return(_localRepository.FindPackage(package.Id));
        }
Ejemplo n.º 16
0
        private void CacheJobBinaries(IJobLogger logger)
        {
            if (WorkingDirectory != null)
            {
                try
                {
                    int currentHash = CalculateHashForJob(JobBinariesPath);
                    int lastHash    = CalculateHashForJob(WorkingDirectory);

                    if (lastHash == currentHash)
                    {
                        return;
                    }
                }
                catch (Exception ex)
                {
                    // Log error and ignore it as it's not critical to cache job binaries
                    logger.LogError("Failed to calculate hash for WebJob: " + ex);
                    _analytics.UnexpectedException(ex);
                }
            }

            SafeKillAllRunningJobInstances(logger);

            if (FileSystemHelpers.DirectoryExists(JobTempPath))
            {
                FileSystemHelpers.DeleteDirectorySafe(JobTempPath, ignoreErrors: true);
            }

            if (FileSystemHelpers.DirectoryExists(JobTempPath))
            {
                logger.LogWarning("Failed to delete temporary directory");
            }

            try
            {
                OperationManager.Attempt(() =>
                {
                    var tempJobInstancePath = Path.Combine(JobTempPath, Path.GetRandomFileName());

                    FileSystemHelpers.CopyDirectoryRecursive(JobBinariesPath, tempJobInstancePath);
                    UpdateAppConfigs(tempJobInstancePath);

                    WorkingDirectory = tempJobInstancePath;
                });
            }
            catch (Exception ex)
            {
                //Status = "Worker is not running due to an error";
                //TraceError("Failed to copy bin directory: " + ex);
                logger.LogError("Failed to copy job files: " + ex);
                _analytics.UnexpectedException(ex);

                // job disabled
                WorkingDirectory = null;
            }
        }
Ejemplo n.º 17
0
        private static void WriteStreamToFile(Stream stream, string filePath)
        {
            string packageFolderPath = Path.GetDirectoryName(filePath);

            FileSystemHelpers.EnsureDirectory(packageFolderPath);
            using (Stream writeStream = FileSystemHelpers.OpenWrite(filePath))
            {
                OperationManager.Attempt(() => stream.CopyTo(writeStream));
            }
        }
        public void AttemptExecutesAction()
        {
            // Arrange
            bool   actionInvoked = false;
            Action action        = () => { actionInvoked = true; };

            // Act
            OperationManager.Attempt(action);

            // Assert
            Assert.True(actionInvoked);
        }
Ejemplo n.º 19
0
        private static void GenerateApplicationHostXdt(string installationDirectory, string relativeUrl, bool isPreInstalled)
        {
            // If there is no xdt file, generate default.
            FileSystemHelpers.CreateDirectory(installationDirectory);
            string xdtPath = Path.Combine(installationDirectory, _applicationHostFile);

            if (!FileSystemHelpers.FileExists(xdtPath))
            {
                string xdtContent = CreateDefaultXdtFile(relativeUrl, isPreInstalled);
                OperationManager.Attempt(() => FileSystemHelpers.WriteAllText(xdtPath, xdtContent));
            }
        }
Ejemplo n.º 20
0
 protected void NotifyShutdownJob()
 {
     try
     {
         FileSystemHelpers.EnsureDirectory(Path.GetDirectoryName(_shutdownNotificationFilePath));
         OperationManager.Attempt(() => FileSystemHelpers.WriteAllText(_shutdownNotificationFilePath, DateTime.UtcNow.ToString()));
     }
     catch (Exception ex)
     {
         TraceFactory.GetTracer().TraceError(ex);
         _analytics.UnexpectedException(ex);
     }
 }
Ejemplo n.º 21
0
        public static TestRepository Clone(string repositoryName, string source = null, IDictionary <string, string> environments = null, bool noCache = false)
        {
            string commitId = null;

            if (source == null)
            {
                TestRepositoryInfo repoInfo = TestRepositories.Get(repositoryName);
                source   = repoInfo.Url;
                commitId = repoInfo.CommitId;
            }

            return(OperationManager.Attempt(() => CloneInternal(repositoryName, source, commitId, environments, noCache)));
        }
Ejemplo n.º 22
0
        public bool UninstallExtension(string id)
        {
            string installationDirectory = GetInstallationDirectory(id);

            if (!FileSystemHelpers.DirectoryExists(installationDirectory))
            {
                throw new DirectoryNotFoundException(installationDirectory);
            }

            OperationManager.Attempt(() => FileSystemHelpers.DeleteDirectorySafe(installationDirectory));

            return(!FileSystemHelpers.DirectoryExists(installationDirectory));
        }
        public static GitDeploymentResult GitDeploy(this ApplicationManager appManager, string localRepoPath, string localBranchName = "master", string remoteBranchName = "master", int retries = 3)
        {
            return(OperationManager.Attempt(() =>
            {
                GitDeploymentResult result = Git.GitDeploy(appManager.DeploymentManager, appManager.ServiceUrl, localRepoPath, appManager.GitUrl, localBranchName, remoteBranchName);

                string traceFile = String.Format("git-push-{0:MM-dd-H-mm-ss}.txt", DateTime.Now);

                appManager.Save(traceFile, result.GitTrace);

                return result;
            }, retries));
        }
        public void AttemptRetriesAtMostSpecifiedTimesIfActionThrows()
        {
            // Arrange
            int    numInvocations = 0;
            var    exception      = new Exception();
            Action action         = () => { numInvocations++; throw exception; };

            // Act
            var output = Assert.Throws <Exception>(() => OperationManager.Attempt(action, retries: 2, delayBeforeRetry: 10));

            // Assert
            Assert.Same(exception, output);
            Assert.Equal(2, numInvocations);
        }
Ejemplo n.º 25
0
        public IPackage InstallExtension(IPackage package, string installationDirectory)
        {
            try
            {
                if (FileSystemHelpers.DirectoryExists(installationDirectory))
                {
                    FileSystemHelpers.DeleteDirectorySafe(installationDirectory);
                }

                foreach (IPackageFile file in package.GetContentFiles())
                {
                    // It is necessary to place applicationHost.xdt under site extension root.
                    string contentFilePath = file.Path.Substring("content/".Length);
                    string fullPath        = Path.Combine(installationDirectory, contentFilePath);
                    FileSystemHelpers.CreateDirectory(Path.GetDirectoryName(fullPath));
                    using (Stream writeStream = FileSystemHelpers.OpenWrite(fullPath), readStream = file.GetStream())
                    {
                        OperationManager.Attempt(() => readStream.CopyTo(writeStream));
                    }
                }

                // If there is no xdt file, generate default.
                string xdtPath = Path.Combine(installationDirectory, "applicationHost.xdt");
                if (!FileSystemHelpers.FileExists(xdtPath))
                {
                    string xdtContent = CreateDefaultXdtFile(package.Id);
                    OperationManager.Attempt(() => FileSystemHelpers.WriteAllText(xdtPath, xdtContent));
                }

                // Copy nupkg file for package list/lookup
                FileSystemHelpers.CreateDirectory(installationDirectory);
                string packageFilePath = Path.Combine(installationDirectory,
                                                      String.Format("{0}.{1}.nupkg", package.Id, package.Version));
                using (
                    Stream readStream = package.GetStream(), writeStream = FileSystemHelpers.OpenWrite(packageFilePath))
                {
                    OperationManager.Attempt(() => readStream.CopyTo(writeStream));
                }
            }
            catch (Exception ex)
            {
                ITracer tracer = _traceFactory.GetTracer();
                tracer.TraceError(ex);
                FileSystemHelpers.DeleteDirectorySafe(installationDirectory);
                return(null);
            }


            return(_localRepository.FindPackage(package.Id));
        }
Ejemplo n.º 26
0
        internal T ExecuteGenericGitCommandWithRetryAndCatchingWellKnownGitErrors <T>(Func <T> func)
        {
            // 3 retries with 1s interval
            return(OperationManager.Attempt(func, delayBeforeRetry: 1000, shouldRetry: ex =>
            {
                string error = ex.Message;
                if (RetriableFetchFailures.Any(retriableFailureMessage => error.Contains(retriableFailureMessage)))
                {
                    _tracerFactory.GetTracer().Trace("Retry due to {0}", error);
                    return true;
                }

                return false;
            }));
        }
Ejemplo n.º 27
0
        private static void GenerateApplicationHostXdt(string installationDirectory, string relativeUrl, ITracer tracer = null)
        {
            // If there is no xdt file, generate default.
            FileSystemHelpers.CreateDirectory(installationDirectory);
            string xdtPath = Path.Combine(installationDirectory, Constants.ApplicationHostXdtFileName);

            if (!FileSystemHelpers.FileExists(xdtPath))
            {
                if (tracer != null)
                {
                    tracer.Trace("Missing xdt file, creating one.");
                }

                string xdtContent = CreateDefaultXdtFile(relativeUrl, "%XDT_EXTENSIONPATH%");
                OperationManager.Attempt(() => FileSystemHelpers.WriteAllText(xdtPath, xdtContent));
            }
        }
Ejemplo n.º 28
0
        public async Task <bool> UninstallExtension(string id)
        {
            ITracer tracer = _traceFactory.GetTracer();

            string installationDirectory = GetInstallationDirectory(id);

            SiteExtensionInfo info = await GetLocalExtension(id, checkLatest : false);

            if (info == null || !FileSystemHelpers.DirectoryExists(info.LocalPath))
            {
                tracer.TraceError("Site extension {0} not found.", id);
                throw new DirectoryNotFoundException(installationDirectory);
            }

            var externalCommandFactory = new ExternalCommandFactory(_environment, _settings, installationDirectory);

            string uninstallScript = Path.Combine(installationDirectory, _uninstallScriptName);

            if (FileSystemHelpers.FileExists(uninstallScript))
            {
                using (tracer.Step("Execute uninstall.cmd"))
                {
                    OperationManager.Attempt(() =>
                    {
                        Executable exe = externalCommandFactory.BuildCommandExecutable(uninstallScript,
                                                                                       installationDirectory,
                                                                                       _settings.GetCommandIdleTimeout(), NullLogger.Instance);
                        exe.ExecuteWithProgressWriter(NullLogger.Instance, _traceFactory.GetTracer(), String.Empty);
                    });
                }
            }

            using (tracer.Step("Remove site extension job"))
            {
                OperationManager.Attempt(() => CleanupSiteExtensionJobs(id));
            }

            using (tracer.Step("Delete site extension package and directory"))
            {
                OperationManager.Attempt(() => FileSystemHelpers.DeleteFileSafe(GetNuGetPackageFile(info.Id, info.Version)));
                OperationManager.Attempt(() => FileSystemHelpers.DeleteDirectorySafe(installationDirectory));
            }

            return(await GetLocalExtension(id, checkLatest : false) == null);
        }
Ejemplo n.º 29
0
 protected void SafeLogToFile(string path, string content, bool isAppend = true)
 {
     try
     {
         if (isAppend)
         {
             OperationManager.Attempt(() => FileSystemHelpers.AppendAllTextToFile(path, content));
         }
         else
         {
             OperationManager.Attempt(() => FileSystemHelpers.WriteAllTextToFile(path, content));
         }
     }
     catch (Exception ex)
     {
         TraceFactory.GetTracer().TraceError(ex);
     }
 }
Ejemplo n.º 30
0
        private void OnChanged(object sender, FileSystemEventArgs e, HttpContext context)
        {
            if (e.ChangeType == WatcherChangeTypes.Changed && MatchFilters(e.FullPath))
            {
                // reading the delta of file changed, retry if failed.
                IEnumerable <string> lines = null;
                OperationManager.Attempt(() =>
                {
                    lines = GetChanges(e);
                }, 3, 100);

                if (lines.Count() > 0)
                {
                    _lastTraceTime = DateTime.UtcNow;
                    NotifyClient(lines, context);
                }
            }
        }