Пример #1
0
        public void DownloadPackage(
            string packageId,
            IVersion version,
            Uri feedUri,
            ICredentials feedCredentials,
            string targetFilePath,
            int maxDownloadAttempts,
            TimeSpan downloadAttemptBackoff,
            Action <string, IVersion, Uri, ICredentials, string> action)
        {
            if (maxDownloadAttempts <= 0)
            {
                throw new ArgumentException($"The number of download attempts should be greater than zero, but was {maxDownloadAttempts}", nameof(maxDownloadAttempts));
            }

            var tempTargetFilePath = targetFilePath + Download.NuGetPackageDownloader.DownloadingExtension;

            // The RetryTracker is a bit finicky to set up...
            var numberOfRetriesOnFailure = maxDownloadAttempts - 1;
            var retry = new RetryTracker(numberOfRetriesOnFailure, timeLimit: null, retryInterval: new LinearRetryInterval(downloadAttemptBackoff));

            while (retry.Try())
            {
                Log.Verbose($"Downloading package (attempt {retry.CurrentTry} of {maxDownloadAttempts})");

                try
                {
                    action(packageId, version, feedUri, feedCredentials, tempTargetFilePath);
                    fileSystem.MoveFile(tempTargetFilePath, targetFilePath);
                    return;
                }
                catch (Exception ex)
                {
                    if (ex is WebException webException &&
                        webException.Response is HttpWebResponse response &&
                        response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        throw new Exception($"Unable to download package: {webException.Message}", ex);
                    }
                    Log.Verbose($"Attempt {retry.CurrentTry} of {maxDownloadAttempts}: {ex.Message}");

                    fileSystem.DeleteFile(tempTargetFilePath, FailureOptions.IgnoreFailure);
                    fileSystem.DeleteFile(targetFilePath, FailureOptions.IgnoreFailure);

                    if (retry.CanRetry())
                    {
                        var wait = TimeSpan.FromMilliseconds(retry.Sleep());
                        Log.Verbose($"Going to wait {wait.TotalSeconds}s before attempting the download from the external feed again.");
                        Thread.Sleep(wait);
                    }
                    else
                    {
                        var helpfulFailure = $"The package {packageId} version {version} could not be downloaded from the external feed '{feedUri}' after making {maxDownloadAttempts} attempts over a total of {Math.Floor(retry.TotalElapsed.TotalSeconds)}s. Make sure the package is pushed to the external feed and try the deployment again. For a detailed troubleshooting guide go to http://g.octopushq.com/TroubleshootMissingPackages";
                        helpfulFailure += $"{Environment.NewLine}{ex}";

                        throw new Exception(helpfulFailure, ex);
                    }
                }
            }
        }
Пример #2
0
        void DeleteExtractionSource(JournalEntry deployment, List <JournalEntry> preservedEntries)
        {
            if (string.IsNullOrWhiteSpace(deployment.ExtractedFrom) ||
                !fileSystem.FileExists(deployment.ExtractedFrom) ||
                preservedEntries.Any(entry => deployment.ExtractedFrom.Equals(entry.ExtractedFrom, StringComparison.Ordinal)))
            {
                return;
            }

            Log.Info($"Removing package file '{deployment.ExtractedFrom}'");
            fileSystem.DeleteFile(deployment.ExtractedFrom, FailureOptions.IgnoreFailure);
        }
Пример #3
0
        public void Install(RunningDeployment deployment)
        {
            var features = deployment.Variables.GetStrings(SpecialVariables.Package.EnabledFeatures)
                           .Where(s => !string.IsNullOrWhiteSpace(s)).ToList();

            if (!features.Contains(SpecialVariables.Features.CustomScripts))
            {
                return;
            }

            foreach (ScriptSyntax scriptType in Enum.GetValues(typeof(ScriptSyntax)))
            {
                var    scriptName = SpecialVariables.Action.CustomScripts.GetCustomScriptStage(deploymentStage, scriptType);
                string error;
                var    scriptBody = deployment.Variables.Get(scriptName, out error);
                if (!string.IsNullOrEmpty(error))
                {
                    Log.VerboseFormat(
                        "Parsing script for phase {0} with Octostache returned the following error: `{1}`",
                        deploymentStage,
                        error);
                }

                if (string.IsNullOrWhiteSpace(scriptBody))
                {
                    continue;
                }

                if (!scriptEngine.GetSupportedTypes().Contains(scriptType))
                {
                    throw new CommandException($"{scriptType} scripts are not supported on this platform ({deploymentStage})");
                }

                var scriptFile  = Path.Combine(deployment.CurrentDirectory, scriptName);
                var scriptBytes = scriptType == ScriptSyntax.Bash
                    ? scriptBody.EncodeInUtf8NoBom()
                    : scriptBody.EncodeInUtf8Bom();
                fileSystem.WriteAllBytes(scriptFile, scriptBytes);

                // Execute the script
                Log.VerboseFormat("Executing '{0}'", scriptFile);
                var result = scriptEngine.Execute(new Script(scriptFile), deployment.Variables, commandLineRunner);

                if (result.ExitCode != 0)
                {
                    throw new CommandException($"{deploymentStage} script returned non-zero exit code: {result.ExitCode}");
                }

                if (result.HasErrors && deployment.Variables.GetFlag(SpecialVariables.Action.FailScriptOnErrorOutput, false))
                {
                    throw new CommandException($"{deploymentStage} script returned zero exit code but had error output.");
                }

                if (deployment.Variables.GetFlag(SpecialVariables.DeleteScriptsOnCleanup, true))
                {
                    // And then delete it (this means if the script failed, it will persist, which may assist debugging)
                    fileSystem.DeleteFile(scriptFile, FailureOptions.IgnoreFailure);
                }
            }
        }
Пример #4
0
        public void ApplyRetention()
        {
            try
            {
                using (AcquireSemaphore())
                {
                    journalRepository.Load();
                    var packagesToRemove = retentionAlgorithm.GetPackagesToRemove(journalRepository.GetAllJournalEntries());
                    foreach (var package in packagesToRemove)
                    {
                        if (string.IsNullOrWhiteSpace(package.Path.Value) || !fileSystem.FileExists(package.Path.Value))
                        {
                            log.Verbose($"Package at {package.Path} not found.");
                        }
                        else
                        {
                            Log.Verbose($"Removing package file '{package.Path}'");
                            fileSystem.DeleteFile(package.Path.Value, FailureOptions.IgnoreFailure);
                        }

                        journalRepository.RemovePackageEntry(package);
                    }
                    journalRepository.Commit();
                }
            }
            catch (Exception ex)
            {
                Log.Info(ex.Message);
            }
        }
Пример #5
0
        public void Install(RunningDeployment deployment)
        {
            Log.Info("Config file: " + deployment.Variables.Get(SpecialVariables.Action.Azure.Output.ConfigurationFile));

            Log.SetOutputVariable("OctopusAzureServiceName", deployment.Variables.Get(SpecialVariables.Action.Azure.CloudServiceName), deployment.Variables);
            Log.SetOutputVariable("OctopusAzureStorageAccountName", deployment.Variables.Get(SpecialVariables.Action.Azure.StorageAccountName), deployment.Variables);
            Log.SetOutputVariable("OctopusAzureSlot", deployment.Variables.Get(SpecialVariables.Action.Azure.Slot), deployment.Variables);
            Log.SetOutputVariable("OctopusAzurePackageUri", deployment.Variables.Get(SpecialVariables.Action.Azure.UploadedPackageUri), deployment.Variables);
            Log.SetOutputVariable("OctopusAzureDeploymentLabel", deployment.Variables.Get(SpecialVariables.Action.Name) + " v" + deployment.Variables.Get(SpecialVariables.Release.Number), deployment.Variables);
            Log.SetOutputVariable("OctopusAzureSwapIfPossible", deployment.Variables.Get(SpecialVariables.Action.Azure.SwapIfPossible, defaultValue: false.ToString()), deployment.Variables);
            Log.SetOutputVariable("OctopusAzureUseCurrentInstanceCount", deployment.Variables.Get(SpecialVariables.Action.Azure.UseCurrentInstanceCount), deployment.Variables);

            // The script name 'DeployToAzure.ps1' is used for backwards-compatibility
            var scriptFile = Path.Combine(deployment.CurrentDirectory, "DeployToAzure.ps1");

            // The user may supply the script, to override behaviour
            if (!fileSystem.FileExists(scriptFile))
            {
                fileSystem.OverwriteFile(scriptFile, embeddedResources.GetEmbeddedResourceText("Calamari.Azure.Scripts.DeployAzureCloudService.ps1"));
            }

            var result = scriptEngine.Execute(scriptFile, deployment.Variables, commandLineRunner);

            fileSystem.DeleteFile(scriptFile, FailureOptions.IgnoreFailure);

            if (result.ExitCode != 0)
            {
                throw new CommandException(string.Format("Script '{0}' returned non-zero exit code: {1}", scriptFile,
                                                         result.ExitCode));
            }
        }
Пример #6
0
        void DeleteScripts(RunningDeployment deployment)
        {
            var scripts = FindScripts(deployment);

            foreach (var script in scripts)
            {
                fileSystem.DeleteFile(script, DeletionOptions.TryThreeTimesIgnoreFailure);
            }
        }
        protected void DeleteScripts(RunningDeployment deployment)
        {
            var scripts = FindScripts(deployment);

            foreach (var script in scripts)
            {
                fileSystem.DeleteFile(script, FailureOptions.IgnoreFailure);
            }
        }
Пример #8
0
 public void DeleteLock(string lockFilePath)
 {
     try
     {
         fileSystem.DeleteFile(lockFilePath);
     }
     catch (Exception)
     {
         // ignored - handled in create
     }
 }
        protected void Run(RunningDeployment deployment)
        {
            var features = deployment.Variables.GetStrings(SpecialVariables.Package.EnabledFeatures).Where(s => !string.IsNullOrWhiteSpace(s)).ToList();

            if (!features.Any())
            {
                return;
            }

            var assembly = typeof(FeatureScriptConventionBase).GetTypeInfo().Assembly;
            var embeddedResourceNames = new HashSet <string>(embeddedResources.GetEmbeddedResourceNames(assembly));

            foreach (var featureScript in features.SelectMany(GetScriptNames))
            {
                // Determine the embedded-resource name
                var scriptEmbeddedResource = GetEmbeddedResourceName(featureScript);

                // If there is a matching embedded resource
                if (!embeddedResourceNames.Contains(scriptEmbeddedResource))
                {
                    continue;
                }

                var scriptFile = Path.Combine(deployment.CurrentDirectory, featureScript);

                // To execute the script, we need a physical file on disk.
                // If one already exists, we don't recreate it, as this provides a handy
                // way to override behaviour.
                if (!fileSystem.FileExists(scriptFile))
                {
                    Log.VerboseFormat("Creating '{0}' from embedded resource", scriptFile);
                    fileSystem.OverwriteFile(scriptFile, embeddedResources.GetEmbeddedResourceText(assembly, scriptEmbeddedResource));
                }
                else
                {
                    Log.WarnFormat("Did not overwrite '{0}', it was already on disk", scriptFile);
                }

                // Execute the script
                Log.VerboseFormat("Executing '{0}'", scriptFile);
                var result = scriptEngine.Execute(new Script(scriptFile), deployment.Variables, commandLineRunner);

                // And then delete it
                Log.VerboseFormat("Deleting '{0}'", scriptFile);
                fileSystem.DeleteFile(scriptFile, FailureOptions.IgnoreFailure);

                if (result.ExitCode != 0)
                {
                    throw new CommandException(string.Format("Script '{0}' returned non-zero exit code: {1}", scriptFile,
                                                             result.ExitCode));
                }
            }
        }
Пример #10
0
        public void Install(RunningDeployment deployment)
        {
            var features = deployment.Variables.GetStrings(SpecialVariables.Package.EnabledFeatures).Where(s => !string.IsNullOrWhiteSpace(s)).ToList();

            if (!features.Any())
            {
                return;
            }

            var embeddedResourceNames = new HashSet <string>(embeddedResources.GetEmbeddedResourceNames());

            foreach (var featureScript in features.SelectMany(GetScriptNames))
            {
                // Determine the embedded-resource name
                var scriptEmbeddedResource = GetEmbeddedResourceName(featureScript);

                // If there is a matching embedded resource
                if (!embeddedResourceNames.Contains(scriptEmbeddedResource))
                {
                    continue;
                }

                var scriptFile = Path.Combine(deployment.CurrentDirectory, featureScript);

                // To execute the script, we need a physical file on disk.
                // If one already exists, we don't recreate it, as this provides a handy
                // way to override behaviour.
                if (!fileSystem.FileExists(scriptFile))
                {
                    fileSystem.OverwriteFile(scriptFile, embeddedResources.GetEmbeddedResourceText(scriptEmbeddedResource));
                }

                // Execute the script
                Log.VerboseFormat("Executing '{0}'", scriptFile);
                var result = scriptEngineSelector.SelectEngine(scriptFile).Execute(scriptFile, deployment.Variables, commandLineRunner);

                // And then delete it
                fileSystem.DeleteFile(scriptFile, DeletionOptions.TryThreeTimesIgnoreFailure);

                if (result.ExitCode != 0)
                {
                    throw new CommandException(string.Format("Script '{0}' returned non-zero exit code: {1}", scriptFile,
                                                             result.ExitCode));
                }
            }
        }
Пример #11
0
        public void ApplyRetentionPolicy(string retentionPolicySet, int?days, int?releases)
        {
            var deployments = deploymentJournal.GetAllJournalEntries().Where(x => x.RetentionPolicySet == retentionPolicySet);

            if (days.HasValue && days.Value > 0)
            {
                deployments = deployments.Where(x => x.InstalledOn < clock.GetUtcTime().AddDays(-days.Value)).ToList();
            }
            else if (releases.HasValue && releases.Value > 0)
            {
                var skipped = 0;

                // Keep the current release, plus specified releases value
                // Unsuccessful releases are not included in the count of releases to keep
                deployments = deployments
                              .OrderByDescending(x => x.InstalledOn)
                              .SkipWhile((x) => (x.WasSuccessful ? skipped++ : skipped) <= releases.Value)
                              .ToList();
            }

            foreach (var deployment in deployments)
            {
                if (fileSystem.DirectoryExists(deployment.ExtractedTo))
                {
                    Log.VerboseFormat("Removing directory '{0}'", deployment.ExtractedTo);
                    fileSystem.PurgeDirectory(deployment.ExtractedTo, DeletionOptions.TryThreeTimesIgnoreFailure);

                    try
                    {
                        fileSystem.DeleteDirectory(deployment.ExtractedTo);
                    }
                    catch (Exception ex)
                    {
                        Log.VerboseFormat("Could not delete directory '{0}' because some files could not be deleted: {1}", deployment.ExtractedFrom, ex.Message);
                    }
                }

                if (!string.IsNullOrWhiteSpace(deployment.ExtractedFrom) && fileSystem.FileExists(deployment.ExtractedFrom))
                {
                    Log.VerboseFormat("Removing package file '{0}'", deployment.ExtractedFrom);
                    fileSystem.DeleteFile(deployment.ExtractedFrom, DeletionOptions.TryThreeTimesIgnoreFailure);
                }
            }

            deploymentJournal.RemoveJournalEntries(deployments.Select(x => x.Id));
        }
Пример #12
0
        public void Install(RunningDeployment deployment)
        {
            var features = deployment.Variables.GetStrings(SpecialVariables.Package.EnabledFeatures).Where(s => !string.IsNullOrWhiteSpace(s)).ToList();

            if (!features.Contains(SpecialVariables.Features.CustomScripts))
            {
                return;
            }

            foreach (var scriptName in scriptEngine.GetSupportedExtensions()
                     .Select(extension => GetScriptName(deploymentStage, extension)))
            {
                string error;
                var    scriptBody = deployment.Variables.Get(scriptName, out error);
                if (!string.IsNullOrEmpty(error))
                {
                    Log.VerboseFormat("Parsing script for phase {0} with Octostache returned the following error: `{1}`", deploymentStage, error);
                }

                if (string.IsNullOrWhiteSpace(scriptBody))
                {
                    continue;
                }

                var scriptFile = Path.Combine(deployment.CurrentDirectory, scriptName);

                fileSystem.OverwriteFile(scriptFile, scriptBody, Encoding.UTF8);

                // Execute the script
                Log.VerboseFormat("Executing '{0}'", scriptFile);
                var result = scriptEngine.Execute(new Script(scriptFile), deployment.Variables, commandLineRunner);

                if (result.ExitCode != 0)
                {
                    throw new CommandException(string.Format("Script '{0}' returned non-zero exit code: {1}", scriptFile,
                                                             result.ExitCode));
                }

                if (deployment.Variables.GetFlag(SpecialVariables.DeleteScriptsOnCleanup, true))
                {
                    // And then delete it (this means if the script failed, it will persist, which may assist debugging)
                    fileSystem.DeleteFile(scriptFile, FailureOptions.IgnoreFailure);
                }
            }
        }
Пример #13
0
        public void Install(RunningDeployment deployment)
        {
            var variables = deployment.Variables;

            // Set output variables for our script to access.
            log.SetOutputVariable("PublishProfileFile", variables.Get(SpecialVariables.Action.ServiceFabric.PublishProfileFile, "PublishProfiles\\Cloud.xml"), variables);
            log.SetOutputVariable("DeployOnly", variables.Get(SpecialVariables.Action.ServiceFabric.DeployOnly, defaultValue: false.ToString()), variables);
            log.SetOutputVariable("UnregisterUnusedApplicationVersionsAfterUpgrade", variables.Get(SpecialVariables.Action.ServiceFabric.UnregisterUnusedApplicationVersionsAfterUpgrade, defaultValue: false.ToString()), variables);
            log.SetOutputVariable("OverrideUpgradeBehavior", variables.Get(SpecialVariables.Action.ServiceFabric.OverrideUpgradeBehavior, defaultValue: "None"), variables);
            log.SetOutputVariable("OverwriteBehavior", variables.Get(SpecialVariables.Action.ServiceFabric.OverwriteBehavior, defaultValue: "SameAppTypeAndVersion"), variables);
            log.SetOutputVariable("SkipPackageValidation", variables.Get(SpecialVariables.Action.ServiceFabric.SkipPackageValidation, defaultValue: false.ToString()), variables);
            log.SetOutputVariable("CopyPackageTimeoutSec", variables.Get(SpecialVariables.Action.ServiceFabric.CopyPackageTimeoutSec, defaultValue: 0.ToString()), variables);
            SetRegisterApplicationTypeTimeout(variables);


            // Package should have been extracted to the staging dir (as per the ExtractPackageToStagingDirectoryConvention).
            var targetPath = Path.Combine(Environment.CurrentDirectory, "staging");

            log.SetOutputVariable("ApplicationPackagePath", targetPath, variables);

            if (deployment.Variables.GetFlag(SpecialVariables.Action.ServiceFabric.LogExtractedApplicationPackage))
            {
                LogExtractedPackage(deployment.CurrentDirectory);
            }

            // The user may supply the script, to override behaviour.
            var scriptFile = Path.Combine(deployment.CurrentDirectory, "DeployToServiceFabric.ps1");

            if (!fileSystem.FileExists(scriptFile))
            {
                // Use our bundled version.
                fileSystem.OverwriteFile(scriptFile, embeddedResources.GetEmbeddedResourceText(GetType().Assembly, $"{GetType().Assembly.GetName().Name}.Scripts.DeployAzureServiceFabricApplication.ps1"));
            }

            var result = scriptEngine.Execute(new Script(scriptFile), deployment.Variables, commandLineRunner);

            fileSystem.DeleteFile(scriptFile, FailureOptions.IgnoreFailure);

            if (result.ExitCode != 0)
            {
                throw new CommandException(string.Format("Script '{0}' returned non-zero exit code: {1}", scriptFile,
                                                         result.ExitCode));
            }
        }
Пример #14
0
        void ExecuteFeatureScripts(RunningDeployment deployment, string feature, HashSet <string> embeddedResourceNames)
        {
            foreach (var featureScript in GetScriptNames(feature))
            {
                // Determine the embedded-resource name
                var scriptEmbeddedResource = GetEmbeddedResourceName(featureScript);

                // If there is a matching embedded resource
                if (!embeddedResourceNames.Contains(scriptEmbeddedResource))
                {
                    continue;
                }

                var scriptFile = Path.Combine(deployment.CurrentDirectory, featureScript);

                // To execute the script, we need a physical file on disk.
                // If one already exists, we don't recreate it, as this provides a handy
                // way to override behaviour.
                if (!fileSystem.FileExists(scriptFile))
                {
                    Log.VerboseFormat("Creating '{0}' from embedded resource", scriptFile);
                    fileSystem.OverwriteFile(scriptFile, embeddedResources.GetEmbeddedResourceText(Assembly, scriptEmbeddedResource));
                }
                else
                {
                    Log.WarnFormat("Did not overwrite '{0}', it was already on disk", scriptFile);
                }

                // Execute the script
                Log.VerboseFormat("Executing '{0}'", scriptFile);
                var result = scriptEngine.Execute(new Script(scriptFile), deployment.Variables, commandLineRunner);

                // And then delete it
                Log.VerboseFormat("Deleting '{0}'", scriptFile);
                fileSystem.DeleteFile(scriptFile, FailureOptions.IgnoreFailure);

                if (result.ExitCode != 0)
                {
                    throw new CommandException(string.Format("Script '{0}' returned non-zero exit code: {1}", scriptFile, result.ExitCode));
                }
            }
        }
Пример #15
0
        public void Install(RunningDeployment deployment)
        {
            var features = deployment.Variables.GetStrings(SpecialVariables.Package.EnabledFeatures).Where(s => !string.IsNullOrWhiteSpace(s)).ToList();

            if (!features.Contains(SpecialVariables.Features.CustomScripts))
            {
                return;
            }

            foreach (var scriptName in scriptEngineSelector.GetSupportedExtensions()
                     .Select(extension => GetScriptName(deploymentStage, extension)))
            {
                var scriptBody = deployment.Variables.Get(scriptName);

                if (string.IsNullOrWhiteSpace(scriptBody))
                {
                    continue;
                }

                var scriptFile = Path.Combine(deployment.CurrentDirectory, scriptName);

                fileSystem.OverwriteFile(scriptFile, scriptBody);

                // Execute the script
                Log.VerboseFormat("Executing '{0}'", scriptFile);
                var result = scriptEngineSelector.SelectEngine(scriptFile).Execute(scriptFile, deployment.Variables, commandLineRunner);

                if (result.ExitCode != 0)
                {
                    throw new CommandException(string.Format("Script '{0}' returned non-zero exit code: {1}", scriptFile,
                                                             result.ExitCode));
                }

                // And then delete it (this means if the script failed, it will persist, which may assist debugging)
                fileSystem.DeleteFile(scriptFile, DeletionOptions.TryThreeTimesIgnoreFailure);
            }
        }
Пример #16
0
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);
            string deltaFilePath;
            string newFilePath;
            string basisFilePath;

            try
            {
                ValidateParameters(out basisFilePath, out deltaFilePath, out newFilePath);
                fileSystem.EnsureDiskHasEnoughFreeSpace(PackageStore.GetPackagesDirectory());

                var tempNewFilePath = newFilePath + ".partial";
#if USE_OCTODIFF_EXE
                var factory = new OctoDiffCommandLineRunner();
#else
                var factory = new OctoDiffLibraryCallRunner();
#endif
                var octoDiff = factory.OctoDiff
                               .Action("patch")
                               .PositionalArgument(basisFilePath)
                               .PositionalArgument(deltaFilePath)
                               .PositionalArgument(tempNewFilePath);

                if (skipVerification)
                {
                    octoDiff.Flag("skip-verification");
                }

                if (showProgress)
                {
                    octoDiff.Flag("progress");
                }

                Log.Info("Applying delta to {0} with hash {1} and storing as {2}", basisFilePath, fileHash, newFilePath);

                var result = factory.Execute();
                if (result.ExitCode != 0)
                {
                    fileSystem.DeleteFile(tempNewFilePath, FailureOptions.ThrowOnFailure);
                    throw new CommandLineException("OctoDiff", result.ExitCode, result.Errors);
                }

                File.Move(tempNewFilePath, newFilePath);

                if (!File.Exists(newFilePath))
                {
                    throw new CommandException($"Failed to apply delta file {deltaFilePath} to {basisFilePath}");
                }
            }
            catch (Exception e) when(e is CommandLineException || e is CommandException)
            {
                Log.ServiceMessages.DeltaVerificationError(e.Message);
                return(0);
            }

            var package = PackagePhysicalFileMetadata.Build(newFilePath);
            if (package == null)
            {
                return(0);
            }

            Log.ServiceMessages.DeltaVerification(newFilePath, package.Hash, package.Size);
            return(0);
        }
Пример #17
0
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);
            string deltaFilePath;
            string newFilePath;
            string basisFilePath;

            ValidateParameters(out basisFilePath, out deltaFilePath, out newFilePath);
            fileSystem.EnsureDiskHasEnoughFreeSpace(packageStore.GetPackagesDirectory());

            var tempNewFilePath = newFilePath + ".partial";

#if USE_OCTODIFF_EXE
            var factory = new OctoDiffCommandLineRunner();
#else
            var factory = new OctoDiffLibraryCallRunner();
#endif
            var octoDiff = factory.OctoDiff
                           .Action("patch")
                           .PositionalArgument(basisFilePath)
                           .PositionalArgument(deltaFilePath)
                           .PositionalArgument(tempNewFilePath);

            if (skipVerification)
            {
                octoDiff.Flag("skip-verification");
            }

            if (showProgress)
            {
                octoDiff.Flag("progress");
            }

            Log.Info("Applying delta to {0} with hash {1} and storing as {2}", basisFilePath, fileHash, newFilePath);

            var result = factory.Execute();
            if (result.ExitCode != 0)
            {
                fileSystem.DeleteFile(tempNewFilePath, FailureOptions.ThrowOnFailure);
                throw new CommandLineException("OctoDiff", result.ExitCode, result.Errors);
            }

            File.Move(tempNewFilePath, newFilePath);

            if (!File.Exists(newFilePath))
            {
                throw new CommandException("Failed to apply delta file " + deltaFilePath + " to " +
                                           basisFilePath);
            }

            var package = packageStore.GetPackage(newFilePath);
            if (package == null)
            {
                return(0);
            }

            using (var file = new FileStream(package.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var size = file.Length;
                Log.ServiceMessages.DeltaVerification(package.FullPath, package.Metadata.Hash, size);
            }

            return(0);
        }
Пример #18
0
 public void Dispose()
 {
     fileSystem.DeleteFile(filePath, FailureOptions.IgnoreFailure);
 }
Пример #19
0
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);
            string deltaFilePath;
            string newFilePath;
            string basisFilePath;

            ValidateParameters(out basisFilePath, out deltaFilePath, out newFilePath);
            fileSystem.EnsureDiskHasEnoughFreeSpace(packageStore.GetPackagesDirectory());

            var commandLineRunner = new CommandLineRunner(new SplitCommandOutput(new ConsoleCommandOutput(),
                                                                                 new ServiceMessageCommandOutput(new VariableDictionary())));

            var tempNewFilePath = newFilePath + ".partial";
            var executable      = FindOctoDiffExecutable();
            var octoDiff        = CommandLine.Execute(executable)
                                  .Action("patch")
                                  .PositionalArgument(basisFilePath)
                                  .PositionalArgument(deltaFilePath)
                                  .PositionalArgument(tempNewFilePath);

            if (skipVerification)
            {
                octoDiff.Flag("skip-verification");
            }

            if (showProgress)
            {
                octoDiff.Flag("progress");
            }

            Log.Info("Applying delta to {0} with hash {1} and storing as {2}", basisFilePath, fileHash,
                     newFilePath);

            var result = commandLineRunner.Execute(octoDiff.Build());

            if (result.ExitCode != 0)
            {
                fileSystem.DeleteFile(tempNewFilePath, DeletionOptions.TryThreeTimes);
                throw new CommandLineException(executable, result.ExitCode, result.Errors);
            }

            File.Move(tempNewFilePath, newFilePath);

            if (!File.Exists(newFilePath))
            {
                throw new CommandException("Failed to apply delta file " + deltaFilePath + " to " +
                                           basisFilePath);
            }

            var package = packageStore.GetPackage(newFilePath);

            if (package == null)
            {
                return(0);
            }

            using (var file = new FileStream(package.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var size = file.Length;
                Log.ServiceMessages.DeltaVerification(package.FullPath, package.Metadata.Hash, size);
            }

            return(0);
        }