Example #1
0
        /// <summary>
        /// Restores the size, position, and state of a window.
        /// </summary>
        /// <typeparam name="T">The type of the window.</typeparam>
        /// <param name="window">A window.</param>
        /// <param name="windowSize">The size, position, and state to restore.</param>
        /// <param name="options">Options for performing the restore. (Optional.)</param>
        public static void Restore <T>(this T window, WindowSize windowSize, RestoreOptions options = RestoreOptions.None)
            where T : Window, IRestorableWindow
        {
            if (window == null || windowSize == null)
            {
                return;
            }

            // Restore size and position
            window.RestoreBounds(windowSize.RestoreBounds);

            // Restore state
            if (windowSize.WindowState == WindowState.Minimized && !options.HasFlag(RestoreOptions.AllowMinimized))
            {
                window.RestoreState(
                    windowSize.RestoreWindowState,
                    windowSize.RestoreWindowState,
                    windowSize.IsFullScreen);
            }
            else
            {
                window.RestoreState(
                    windowSize.WindowState,
                    windowSize.RestoreWindowState,
                    windowSize.IsFullScreen);
            }

            // If the window is restored to a size or position that is not on the screen, center the window
            if (!window.IsOnScreen())
            {
                window.CenterOnScreen();
            }
        }
Example #2
0
        /// <summary>
        /// Restores the size, position, and state of a window from its persisted size, position, and state.
        /// </summary>
        /// <typeparam name="T">The type of the window.</typeparam>
        /// <param name="window">A window.</param>
        /// <param name="options">Options for performing the restore. (Optional.)</param>
        public static void RestoreFromSettings <T>(this T window, RestoreOptions options = RestoreOptions.None)
            where T : Window, IRestorableWindow
        {
            WindowSize windowSize = window.PersistedSize;

            window.Restore(windowSize, options);
        }
Example #3
0
        internal RestorePlan CreateRestorePlan(DatabaseRestorePlanner planner, RestoreOptions restoreOptions)
        {
            this.CreateOrUpdateRestorePlanException = null;
            RestorePlan ret = null;

            try
            {
                ret = planner.CreateRestorePlan(restoreOptions);
                if (ret == null || ret.RestoreOperations.Count == 0)
                {
                    this.ActiveException = planner.GetBackupDeviceReadErrors();
                }
            }
            catch (Exception ex)
            {
                this.ActiveException = ex;
                this.CreateOrUpdateRestorePlanException = this.ActiveException;
            }
            finally
            {
            }


            return(ret);
        }
Example #4
0
        /// <summary>
        /// Restores the size, position, and state of a window from another window of the same type.
        /// </summary>
        /// <remarks>
        /// This method offsets the window position slightly so that the two windows do not overlap.
        /// </remarks>
        /// <typeparam name="T">The type of the window.</typeparam>
        /// <param name="window">A window.</param>
        /// <param name="otherWindow">The window from which to copy the size, position, and state.</param>
        /// <param name="options">Options for performing the restore. (Optional.)</param>
        public static void RestoreFromWindow <T>(this T window, T otherWindow, RestoreOptions options = RestoreOptions.None)
            where T : Window, IRestorableWindow
        {
            WindowSize windowSize       = WindowSize.FromWindow(otherWindow);
            WindowSize offsetWindowSize = windowSize.Offset();

            window.Restore(offsetWindowSize, options);
        }
Example #5
0
        private int Restore(RestoreOptions options)
        {
            string fullPath    = Path.GetFullPath(options.InputFile);
            string json        = File.ReadAllText(fullPath);
            var    inputConfig = JsonConvert.DeserializeObject <DisplayConfigInfo>(json, CreateJsonSettings());

            Api.SetDisplayConfig(inputConfig !, SetDisplayConfigFlags.Apply | SetDisplayConfigFlags.UseSuppliedDisplayConfig);
            Console.WriteLine($"Restored display configuration from {fullPath}");
            return(ExitCodeOk);
        }
Example #6
0
        //HttpClientFactory
        public RestoreCommand(RestoreOptions options)
        {
            _options = options;

            EnsureDepsFileName(_options.DepsFile);

            _http = new HttpClient()
            {
                Timeout = TimeSpan.FromSeconds(30)
            };
        }
Example #7
0
        private static object Restore(RestoreOptions opts)
        {
            try
            {
                new RestoreCommand(opts).Execute().Wait();
            }
            catch (Exception ex)
            {
                MessageHelper.Error(ex.ToString());
                MessageHelper.Warning("Use \"nustore restore --help\" for help info...");
            }

            return(null);
        }
 public void TestRestoreBackup()
 {
     RunTest((client) =>
     {
         var backupLocation    = "local";
         var backup            = client.BackupLocations.CreateBackup(ResourceGroupName, backupLocation);
         var restoreOperations = new RestoreOptions
         {
             DecryptionCertBase64   = "decryptionCert",
             DecryptionCertPassword = "******"
         };
         Assert.NotNull(backup);
         client.Backups.Restore(backupLocation, ResourceGroupName, ExtractName(backup.Name), restoreOperations);
     });
 }
Example #9
0
        /// <summary>
        /// Restores the size, position, and state of a window from another visible window of the same type, or from
        /// the app settings if there is no other visible window of the same type.
        /// </summary>
        /// <remarks>
        /// This method offsets the window position slightly so that the two windows do not overlap.
        /// </remarks>
        /// <typeparam name="T">The type of the window.</typeparam>
        /// <param name="window">A window.</param>
        /// <param name="options">Options for performing the restore. (Optional.)</param>
        public static void RestoreFromSibling <T>(this T window, RestoreOptions options = RestoreOptions.None)
            where T : Window, IRestorableWindow
        {
            WindowSize windowSize = WindowSize.FromSiblingOfWindow(window);

            if (windowSize != null)
            {
                WindowSize offsetWindowSize = windowSize.Offset();
                window.Restore(offsetWindowSize, options);
            }
            else
            {
                window.RestoreFromSettings(options);
            }
        }
        public override void Run(IEnumerable <string> args)
        {
            string[] a = args.ToArray();

            string root = a.Length > 1
                              ? Path.GetFullPath(a[1])
                              : Directory.GetCurrentDirectory();

            RestoreOptions options = new RestoreOptions();

            ArgumentSyntaxParser.Parse(a.Skip(1).ToArray(), options);

            ProjectCleanSubSystem.Clean(root);

            Restore(root, options.Origin);
        }
Example #11
0
 public static void RestoreFile(RestoreOptions opts)
 {
     try
     {
         var    bcore        = LoadCore();
         string bsname       = GetBackupSetName(opts.BSName, bcore.SrcDependencies);
         string restorepath  = opts.Path;
         bool   absolutepath = false;
         if (opts.RestorePath != null)
         {
             restorepath  = opts.RestorePath;
             absolutepath = true;
         }
         bcore.RestoreFileOrDirectory(bsname, opts.Path, restorepath, opts.BackupHash, absolutepath);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
     }
 }
        private IRestoreDatabaseTaskDataObject CreateRestoreDatabaseTaskDataObject(GeneralRequestDetails optionValues)
        {
            var restoreDataObject = new RestoreDatabaseTaskDataObjectStub();

            restoreDataObject.CloseExistingConnections = optionValues.GetOptionValue <bool>(RestoreOptionsHelper.CloseExistingConnections);
            restoreDataObject.DataFilesFolder          = optionValues.GetOptionValue <string>(RestoreOptionsHelper.DataFileFolder);
            restoreDataObject.DbFiles = optionValues.GetOptionValue <List <DbFile> >("DbFiles");
            restoreDataObject.DefaultDataFileFolder   = optionValues.GetOptionValue <string>("DefaultDataFileFolder");
            restoreDataObject.DefaultLogFileFolder    = optionValues.GetOptionValue <string>("DefaultLogFileFolder");
            restoreDataObject.DefaultBackupFolder     = optionValues.GetOptionValue <string>("DefaultBackupFolder");
            restoreDataObject.IsTailLogBackupPossible = optionValues.GetOptionValue <bool>("IsTailLogBackupPossible");
            restoreDataObject.IsTailLogBackupWithNoRecoveryPossible = optionValues.GetOptionValue <bool>("IsTailLogBackupWithNoRecoveryPossible");
            restoreDataObject.DefaultStandbyFile         = optionValues.GetOptionValue <string>("GetDefaultStandbyFile");
            restoreDataObject.DefaultTailLogbackupFile   = optionValues.GetOptionValue <string>("GetDefaultTailLogbackupFile");
            restoreDataObject.LogFilesFolder             = optionValues.GetOptionValue <string>(RestoreOptionsHelper.LogFileFolder);
            restoreDataObject.RelocateAllFiles           = optionValues.GetOptionValue <bool>(RestoreOptionsHelper.RelocateDbFiles);
            restoreDataObject.TailLogBackupFile          = optionValues.GetOptionValue <string>("TailLogBackupFile");
            restoreDataObject.SourceDatabaseName         = optionValues.GetOptionValue <string>(RestoreOptionsHelper.SourceDatabaseName);
            restoreDataObject.TargetDatabaseName         = optionValues.GetOptionValue <string>(RestoreOptionsHelper.TargetDatabaseName);
            restoreDataObject.TailLogWithNoRecovery      = optionValues.GetOptionValue <bool>("TailLogWithNoRecovery");
            restoreDataObject.OverwriteTargetDatabase    = optionValues.GetOptionValue <bool>("CanChangeTargetDatabase");
            restoreDataObject.DefaultSourceDbName        = optionValues.GetOptionValue <string>("DefaultSourceDbName");
            restoreDataObject.SourceDbNames              = optionValues.GetOptionValue <List <string> >("SourceDbNames");
            restoreDataObject.DefaultTargetDbName        = optionValues.GetOptionValue <string>("DefaultTargetDbName");
            restoreDataObject.BackupTailLog              = optionValues.GetOptionValue <bool>(RestoreOptionsHelper.BackupTailLog);
            restoreDataObject.CanDropExistingConnections = optionValues.GetOptionValue <bool>("CanDropExistingConnections");
            restoreDataObject.RestoreParams              = optionValues as RestoreParams;
            restoreDataObject.RestorePlan = null;
            RestoreOptions restoreOptions = new RestoreOptions();

            restoreOptions.KeepReplication   = optionValues.GetOptionValue <bool>(RestoreOptionsHelper.KeepReplication);
            restoreOptions.ReplaceDatabase   = optionValues.GetOptionValue <bool>(RestoreOptionsHelper.ReplaceDatabase);
            restoreOptions.SetRestrictedUser = optionValues.GetOptionValue <bool>(RestoreOptionsHelper.SetRestrictedUser);
            restoreOptions.StandByFile       = optionValues.GetOptionValue <string>(RestoreOptionsHelper.StandbyFile);
            restoreOptions.RecoveryState     = optionValues.GetOptionValue <DatabaseRecoveryState>(RestoreOptionsHelper.RecoveryState);
            restoreDataObject.RestoreOptions = restoreOptions;


            return(restoreDataObject);
        }
Example #13
0
        private static void Restore(RestoreOptions restoreOptions)
        {
            restoreOptions.LoLDirectory = SetLoLDirectory(restoreOptions.LoLDirectory);
            if (!Directory.Exists(restoreOptions.LoLDirectory))
            {
                Console.WriteLine("The specified directory is invalid.");
                return;
            }

            try
            {
                RestoreBackup(restoreOptions.LoLDirectory);
                Console.WriteLine("Restore completed successfully.");
            }

            catch (IOException)
            {
                Console.WriteLine("Unable to access the League of Legends directory. " +
                                  "Make sure that League of Legends is closed.");
            }

            catch (AggregateException)
            {
                Console.WriteLine("Failed to revert the changes made to League of Legends.");
            }
        }
        /// <summary>
        /// Restore a backup.
        /// </summary>
        /// <param name='location'>
        /// Name of the backup location.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Name of the resource group.
        /// </param>
        /// <param name='backup'>
        /// Name of the backup.
        /// </param>
        /// <param name='restoreOptions'>
        /// Restore options.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public async Task <AzureOperationResponse> RestoreWithHttpMessagesAsync(string location, string resourceGroupName, string backup, RestoreOptions restoreOptions, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Send request
            AzureOperationResponse _response = await BeginRestoreWithHttpMessagesAsync(location, resourceGroupName, backup, restoreOptions, customHeaders, cancellationToken).ConfigureAwait(false);

            return(await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false));
        }
Example #15
0
 public RestoreService(RestoreOptions options)
 {
     Options = options;
 }
Example #16
0
        static async Task <int> CommandPromoteAsync([NotNull] PromoteOptions options, [NotNull] ISnapFilesystem filesystem,
                                                    [NotNull] ISnapAppReader snapAppReader, [NotNull] ISnapAppWriter snapAppWriter, [NotNull] INuGetPackageSources nuGetPackageSources,
                                                    [NotNull] INugetService nugetService, [NotNull] IDistributedMutexClient distributedMutexClient,
                                                    [NotNull] ISnapPackageManager snapPackageManager, [NotNull] ISnapPack snapPack, [NotNull] ISnapOsSpecialFolders specialFolders,
                                                    [NotNull] ISnapNetworkTimeProvider snapNetworkTimeProvider, [NotNull] ISnapExtractor snapExtractor, [NotNull] ISnapOs snapOs,
                                                    [NotNull] ISnapxEmbeddedResources snapxEmbeddedResources, [NotNull] ICoreRunLib coreRunLib,
                                                    [NotNull] ILog logger, [NotNull] string workingDirectory, CancellationToken cancellationToken)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (filesystem == null)
            {
                throw new ArgumentNullException(nameof(filesystem));
            }
            if (snapAppReader == null)
            {
                throw new ArgumentNullException(nameof(snapAppReader));
            }
            if (snapAppWriter == null)
            {
                throw new ArgumentNullException(nameof(snapAppWriter));
            }
            if (nuGetPackageSources == null)
            {
                throw new ArgumentNullException(nameof(nuGetPackageSources));
            }
            if (nugetService == null)
            {
                throw new ArgumentNullException(nameof(nugetService));
            }
            if (distributedMutexClient == null)
            {
                throw new ArgumentNullException(nameof(distributedMutexClient));
            }
            if (snapPackageManager == null)
            {
                throw new ArgumentNullException(nameof(snapPackageManager));
            }
            if (snapPack == null)
            {
                throw new ArgumentNullException(nameof(snapPack));
            }
            if (specialFolders == null)
            {
                throw new ArgumentNullException(nameof(specialFolders));
            }
            if (snapNetworkTimeProvider == null)
            {
                throw new ArgumentNullException(nameof(snapNetworkTimeProvider));
            }
            if (snapExtractor == null)
            {
                throw new ArgumentNullException(nameof(snapExtractor));
            }
            if (snapOs == null)
            {
                throw new ArgumentNullException(nameof(snapOs));
            }
            if (snapxEmbeddedResources == null)
            {
                throw new ArgumentNullException(nameof(snapxEmbeddedResources));
            }
            if (coreRunLib == null)
            {
                throw new ArgumentNullException(nameof(coreRunLib));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (workingDirectory == null)
            {
                throw new ArgumentNullException(nameof(workingDirectory));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (nugetService == null)
            {
                throw new ArgumentNullException(nameof(nugetService));
            }

            var stopWatch = new Stopwatch();

            stopWatch.Restart();

            options.Channel = string.IsNullOrWhiteSpace(options.Channel) ? null : options.Channel;

            if (options.Channel != null && !options.Channel.IsValidChannelName())
            {
                logger.Error($"Invalid channel name: {options.Channel}");
                return(1);
            }

            var(snapApps, snapApp, error, _) = BuildSnapAppFromDirectory(filesystem, snapAppReader,
                                                                         nuGetPackageSources, options.Id, options.Rid, workingDirectory);
            if (snapApp == null)
            {
                if (!error)
                {
                    logger.Error($"Unable to find snap with id: {options.Id}. Rid: {options.Rid}.");
                }

                return(1);
            }

            var installersDirectory = BuildInstallersDirectory(filesystem, workingDirectory, snapApps.Generic, snapApp);
            var packagesDirectory   = BuildPackagesDirectory(filesystem, workingDirectory, snapApps.Generic, snapApp);

            var promoteBaseChannel = snapApp.Channels.SingleOrDefault(x => string.Equals(x.Name, options.Channel, StringComparison.OrdinalIgnoreCase));

            if (promoteBaseChannel == null)
            {
                logger.Error($"Unable to find channel: {options.Channel}.");
                return(1);
            }

            MaybeOverrideLockToken(snapApps, logger, options.Id, options.LockToken);

            if (string.IsNullOrWhiteSpace(snapApps.Generic.Token))
            {
                logger.Error("Please specify a lock token in your snapx.yml file. It's sufficient to generate random UUID (Guid).");
                return(1);
            }

            await using var distributedMutex = WithDistributedMutex(distributedMutexClient, logger, snapApps.BuildLockKey(snapApp), cancellationToken);

            logger.Info('-'.Repeat(TerminalBufferWidth));

            var tryAcquireRetries = options.LockRetries == -1 ? int.MaxValue : options.LockRetries;

            if (!await distributedMutex.TryAquireAsync(TimeSpan.FromSeconds(15), tryAcquireRetries))
            {
                logger.Info('-'.Repeat(TerminalBufferWidth));
                return(1);
            }

            var channelsStr = string.Join(", ", snapApp.Channels.Select(x => x.Name));

            logger.Info('-'.Repeat(TerminalBufferWidth));
            logger.Info($"Snap id: {options.Id}");
            logger.Info($"Rid: {options.Rid}");
            logger.Info($"Source channel: {options.Channel}");
            logger.Info($"Channels: {channelsStr}");
            logger.Info('-'.Repeat(TerminalBufferWidth));

            logger.Info("Downloading releases nupkg.");
            var(snapAppsReleases, _, releasesMemoryStream) = await snapPackageManager.GetSnapsReleasesAsync(snapApp, logger, cancellationToken);

            if (releasesMemoryStream != null)
            {
                await releasesMemoryStream.DisposeAsync();
            }
            if (snapAppsReleases == null)
            {
                logger.Error($"Unknown error downloading releases nupkg: {snapApp.BuildNugetReleasesFilename()}.");
                return(1);
            }

            var snapAppChannelReleases = snapAppsReleases.GetReleases(snapApp, promoteBaseChannel);

            var mostRecentRelease = snapAppChannelReleases.GetMostRecentRelease();

            if (mostRecentRelease == null)
            {
                logger.Error($"Unable to find any releases in channel: {promoteBaseChannel.Name}.");
                return(1);
            }

            snapApp.Version = mostRecentRelease.Version;

            var currentChannelIndex = mostRecentRelease.Channels.FindIndex(channelName => channelName == promoteBaseChannel.Name);
            var promotableChannels  = snapApp.Channels
                                      .Skip(currentChannelIndex + 1)
                                      .Select(channel =>
            {
                var releasesThisChannel = snapAppsReleases.GetReleases(snapApp, channel);
                if (releasesThisChannel.Any(x => mostRecentRelease.IsFull ? x.IsFull : x.IsDelta && x.Version == snapApp.Version))
                {
                    return(null);
                }

                return(channel);
            })
                                      .Where(x => x != null)
                                      .ToList();

            if (!promotableChannels.Any())
            {
                logger.Info($"Version {snapApp.Version} is already promoted to all channels.");
                return(0);
            }

            var promoteToChannels = new List <SnapChannel>();

            if (options.ToAllRemainingChannels)
            {
                promoteToChannels.AddRange(promotableChannels);
            }
            else
            {
                promoteToChannels.Add(promotableChannels.First());
            }

            var promoteToChannelsStr = string.Join(", ", promoteToChannels.Select(x => x.Name));

            if (!logger.Prompt("y|yes",
                               $"You are about to promote {snapApp.Id} ({snapApp.Version}) to the following " +
                               $"channel{(promoteToChannels.Count > 1 ? "s" : string.Empty)}: {promoteToChannelsStr}. " +
                               "Do you want to continue? [y|n]", infoOnly: options.YesToAllPrompts)
                )
            {
                return(1);
            }

            foreach (var snapRelease in snapAppChannelReleases.Where(x => x.Version <= mostRecentRelease.Version))
            {
                foreach (var promoteToChannel in promoteToChannels)
                {
                    if (!snapRelease.Channels.Contains(promoteToChannel.Name))
                    {
                        snapRelease.Channels.Add(promoteToChannel.Name);
                    }
                }
            }

            logger.Info("Building releases nupkg.");

            var nowUtc = await SnapUtility.RetryAsync(async() => await snapNetworkTimeProvider.NowUtcAsync(), 3, 1500);

            if (!nowUtc.HasValue)
            {
                logger.Error($"Unknown error while retrieving NTP timestamp from server: {snapNetworkTimeProvider}");
                return(1);
            }

            snapAppsReleases.LastWriteAccessUtc = nowUtc.Value;

            await using var releasesPackageMemoryStream = snapPack.BuildReleasesPackage(snapApp, snapAppsReleases);
            logger.Info("Finished building releases nupkg.");

            var restoreOptions = new RestoreOptions
            {
                Id                  = options.Id,
                Rid                 = options.Rid,
                BuildInstallers     = false,
                RestoreStrategyType = SnapPackageManagerRestoreType.Default
            };

            var restoreSuccess = 0 == await CommandRestoreAsync(
                restoreOptions, filesystem, snapAppReader, snapAppWriter, nuGetPackageSources,
                snapPackageManager, snapOs, snapxEmbeddedResources, coreRunLib, snapPack,
                logger, workingDirectory, cancellationToken
                );

            if (!restoreSuccess)
            {
                return(1);
            }

            await using var tmpDir = new DisposableDirectory(specialFolders.NugetCacheDirectory, filesystem);
            var releasesPackageFilename     = snapApp.BuildNugetReleasesFilename();
            var releasesPackageAbsolutePath = filesystem.PathCombine(tmpDir.WorkingDirectory, releasesPackageFilename);
            await filesystem.FileWriteAsync(releasesPackageMemoryStream, releasesPackageAbsolutePath, cancellationToken);

            if (!options.SkipInstallers && snapApp.Target.Installers.Any())
            {
                foreach (var channel in promoteToChannels)
                {
                    var snapAppInstaller = new SnapApp(snapApp);
                    snapAppInstaller.SetCurrentChannel(channel.Name);

                    var fullNupkgAbsolutePath = filesystem.PathCombine(packagesDirectory, snapApp.BuildNugetFullFilename());

                    if (snapApp.Target.Installers.Any(x => x.HasFlag(SnapInstallerType.Offline)))
                    {
                        logger.Info('-'.Repeat(TerminalBufferWidth));

                        var(installerOfflineSuccess, canContinueIfError, installerOfflineExeAbsolutePath) = await BuildInstallerAsync(logger, snapOs,
                                                                                                                                      snapxEmbeddedResources, snapAppWriter, snapAppInstaller, coreRunLib,
                                                                                                                                      installersDirectory, fullNupkgAbsolutePath, releasesPackageAbsolutePath,
                                                                                                                                      true, cancellationToken);

                        if (!installerOfflineSuccess)
                        {
                            if (!canContinueIfError || !logger.Prompt("y|yes", "Installer was not built. Do you still want to continue? (y|n)", infoOnly: options.YesToAllPrompts))
                            {
                                logger.Info('-'.Repeat(TerminalBufferWidth));
                                logger.Error("Unknown error building offline installer.");
                                return(1);
                            }
                        }
                        else
                        {
                            var installerOfflineExeStat = filesystem.FileStat(installerOfflineExeAbsolutePath);
                            logger.Info($"Successfully built offline installer. File size: {installerOfflineExeStat.Length.BytesAsHumanReadable()}.");
                        }
                    }

                    if (snapApp.Target.Installers.Any(x => x.HasFlag(SnapInstallerType.Web)))
                    {
                        logger.Info('-'.Repeat(TerminalBufferWidth));

                        var(installerWebSuccess, canContinueIfError, installerWebExeAbsolutePath) = await BuildInstallerAsync(logger, snapOs, snapxEmbeddedResources, snapAppWriter, snapAppInstaller, coreRunLib,
                                                                                                                              installersDirectory, null, releasesPackageAbsolutePath,
                                                                                                                              false, cancellationToken);

                        if (!installerWebSuccess)
                        {
                            if (!canContinueIfError ||
                                !logger.Prompt("y|yes", "Installer was not built. Do you still want to continue? (y|n)", infoOnly: options.YesToAllPrompts))
                            {
                                logger.Info('-'.Repeat(TerminalBufferWidth));
                                logger.Error("Unknown error building web installer.");
                                return(1);
                            }
                        }
                        else
                        {
                            var installerWebExeStat = filesystem.FileStat(installerWebExeAbsolutePath);
                            logger.Info($"Successfully built web installer. File size: {installerWebExeStat.Length.BytesAsHumanReadable()}.");
                        }
                    }
                }
            }

            logger.Info('-'.Repeat(TerminalBufferWidth));

            foreach (var(channel, packageSource) in promoteToChannels.Select(snapChannel =>
            {
                var packageSource = nuGetPackageSources.Items.Single(x => x.Name == snapChannel.PushFeed.Name);
                return(snapChannel, packageSource);
            }).DistinctBy(x => x.packageSource.SourceUri))
            {
                logger.Info($"Uploading releases nupkg to feed: {packageSource.Name}.");

                await PushPackageAsync(nugetService, filesystem, distributedMutex, nuGetPackageSources, packageSource,
                                       channel, releasesPackageAbsolutePath, logger, cancellationToken);

                var skipInitialBlock = packageSource.IsLocalOrUncPath();

                await BlockUntilSnapUpdatedReleasesNupkgAsync(logger, snapPackageManager,
                                                              snapAppsReleases, snapApp, channel, TimeSpan.FromSeconds(15), cancellationToken, skipInitialBlock, options.SkipAwaitUpdate);

                logger.Info($"Successfully uploaded releases nupkg to channel: {channel.Name}.");
                logger.Info('-'.Repeat(TerminalBufferWidth));
            }

            logger.Info($"Promote completed in {stopWatch.Elapsed.TotalSeconds:0.0}s.");

            await CommandListAsync(new ListOptions { Id = snapApp.Id }, filesystem, snapAppReader,
                                   nuGetPackageSources, nugetService, snapExtractor, snapPackageManager, logger, workingDirectory, cancellationToken);

            return(0);
        }
 /// <summary>
 /// Restore a backup.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='location'>
 /// Name of the backup location.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Name of the resource group.
 /// </param>
 /// <param name='backup'>
 /// Name of the backup.
 /// </param>
 /// <param name='restoreOptions'>
 /// Restore options.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task BeginRestoreAsync(this IBackupsOperations operations, string location, string resourceGroupName, string backup, RestoreOptions restoreOptions, CancellationToken cancellationToken = default(CancellationToken))
 {
     (await operations.BeginRestoreWithHttpMessagesAsync(location, resourceGroupName, backup, restoreOptions, null, cancellationToken).ConfigureAwait(false)).Dispose();
 }
        /// <summary>
        /// Restore a backup.
        /// </summary>
        /// <param name='location'>
        /// Name of the backup location.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Name of the resource group.
        /// </param>
        /// <param name='backup'>
        /// Name of the backup.
        /// </param>
        /// <param name='restoreOptions'>
        /// Restore options.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse> BeginRestoreWithHttpMessagesAsync(string location, string resourceGroupName, string backup, RestoreOptions restoreOptions, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (location == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "location");
            }
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (backup == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "backup");
            }
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (restoreOptions == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "restoreOptions");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("location", location);
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("backup", backup);
                tracingParameters.Add("restoreOptions", restoreOptions);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "BeginRestore", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Backup.Admin/backupLocations/{location}/backups/{backup}/restore").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{backup}", System.Uri.EscapeDataString(backup));
            List <string> _queryParameters = new List <string>();

            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (restoreOptions != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(restoreOptions, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 202)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Example #19
0
        static async Task <int> CommandRestoreAsync([NotNull] RestoreOptions restoreOptions,
                                                    [NotNull] ISnapFilesystem filesystem, [NotNull] ISnapAppReader snapAppReader, ISnapAppWriter snapAppWriter,
                                                    [NotNull] INuGetPackageSources nuGetPackageSources, [NotNull] ISnapPackageManager snapPackageManager,
                                                    [NotNull] ISnapOs snapOs, [NotNull] ISnapxEmbeddedResources snapxEmbeddedResources, [NotNull] ICoreRunLib coreRunLib,
                                                    [NotNull] ISnapPack snapPack, [NotNull] ILog logger,
                                                    [NotNull] string workingDirectory, CancellationToken cancellationToken)
        {
            if (restoreOptions == null)
            {
                throw new ArgumentNullException(nameof(restoreOptions));
            }
            if (filesystem == null)
            {
                throw new ArgumentNullException(nameof(filesystem));
            }
            if (snapAppReader == null)
            {
                throw new ArgumentNullException(nameof(snapAppReader));
            }
            if (nuGetPackageSources == null)
            {
                throw new ArgumentNullException(nameof(nuGetPackageSources));
            }
            if (snapPackageManager == null)
            {
                throw new ArgumentNullException(nameof(snapPackageManager));
            }
            if (snapOs == null)
            {
                throw new ArgumentNullException(nameof(snapOs));
            }
            if (snapxEmbeddedResources == null)
            {
                throw new ArgumentNullException(nameof(snapxEmbeddedResources));
            }
            if (coreRunLib == null)
            {
                throw new ArgumentNullException(nameof(coreRunLib));
            }
            if (snapPack == null)
            {
                throw new ArgumentNullException(nameof(snapPack));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (workingDirectory == null)
            {
                throw new ArgumentNullException(nameof(workingDirectory));
            }
            var stopwatch = new Stopwatch();

            stopwatch.Restart();

            var(snapApps, snapAppTargets, errorBuildingSnapApps, _) = BuildSnapAppsesFromDirectory(filesystem, snapAppReader,
                                                                                                   nuGetPackageSources, workingDirectory, requirePushFeed: false);

            if (!snapApps.Apps.Any() || errorBuildingSnapApps)
            {
                return(1);
            }

            if (restoreOptions.Id != null)
            {
                snapAppTargets.RemoveAll(x =>
                                         !string.Equals(x.Id, restoreOptions.Id, StringComparison.OrdinalIgnoreCase));
            }

            if (restoreOptions.Rid != null)
            {
                snapAppTargets.RemoveAll(x =>
                                         !string.Equals(x.Target.Rid, restoreOptions.Rid, StringComparison.OrdinalIgnoreCase));
            }

            if (!snapAppTargets.Any())
            {
                logger.Error($"Unable to restore application {restoreOptions.Id} because it does not exist.");
                return(1);
            }

            if (restoreOptions.BuildInstallers)
            {
                restoreOptions.RestoreStrategyType = SnapPackageManagerRestoreType.Default;
            }

            var applicationNames = snapAppTargets.Select(x => x.Id).Distinct().ToList();
            var rids             = snapAppTargets.Select(x => x.Target.Rid).Distinct().ToList();

            logger.Info($"Applications that will be restored: {string.Join(", ", applicationNames)}. Runtime identifiers (RID): {string.Join(", ", rids)}.");

            var releasePackages = new Dictionary <string, (SnapAppsReleases snapReleases, PackageSource packageSource)>();

            foreach (var snapApp in snapAppTargets)
            {
                var packagesDirectory         = BuildPackagesDirectory(filesystem, workingDirectory, snapApps.Generic, snapApp);
                var installersDirectory       = BuildInstallersDirectory(filesystem, workingDirectory, snapApps.Generic, snapApp);
                var releasesNupkgAbsolutePath = filesystem.PathCombine(filesystem.DirectoryGetParent(packagesDirectory), snapApp.BuildNugetReleasesFilename());

                filesystem.DirectoryCreateIfNotExists(packagesDirectory);
                filesystem.DirectoryCreateIfNotExists(installersDirectory);

                logger.Info('-'.Repeat(TerminalBufferWidth));
                logger.Info($"Id: {snapApp.Id}.");
                logger.Info($"Rid: {snapApp.Target.Rid}");
                logger.Info($"Packages directory: {packagesDirectory}");
                logger.Info($"Restore strategy: {restoreOptions.RestoreStrategyType}");
                logger.Info($"Restore installers: {(restoreOptions.BuildInstallers ? "yes" : "no")}");

                SnapAppsReleases snapAppsReleases;
                PackageSource    packageSource;
                if (releasePackages.TryGetValue(snapApp.Id, out var cached))
                {
                    snapAppsReleases = cached.snapReleases;
                    packageSource    = cached.packageSource;
                }
                else
                {
                    logger.Info($"Downloading releases nupkg for application {snapApp.Id}");

                    // ReSharper disable once UseDeconstruction
                    var uncached = await snapPackageManager.GetSnapsReleasesAsync(snapApp, logger, cancellationToken);

                    if (uncached.snapAppsReleases == null)
                    {
                        logger.Error($"Failed to download releases nupkg for application {snapApp.Id}");
                        continue;
                    }

                    await using (uncached.releasesMemoryStream)
                    {
                        await filesystem.FileWriteAsync(uncached.releasesMemoryStream, releasesNupkgAbsolutePath, cancellationToken);
                    }

                    snapAppsReleases = uncached.snapAppsReleases;
                    packageSource    = uncached.packageSource;
                    releasePackages.Add(snapApp.Id, (uncached.snapAppsReleases, uncached.packageSource));

                    logger.Info($"Downloaded releases nupkg. Current version: {snapAppsReleases.Version}.");
                }

                foreach (var snapChannel in snapAppsReleases.GetChannels(snapApp))
                {
                    logger.Info('-'.Repeat(TerminalBufferWidth));
                    logger.Info($"Restoring channel {snapChannel.Name}.");

                    var snapAppReleases = snapAppsReleases.GetReleases(snapApp, snapChannel);
                    if (!snapAppReleases.Any())
                    {
                        logger.Info($"Skipping restore for channel {snapChannel.Name} because no releases was found.");
                        continue;
                    }

                    var restoreSummary = await snapPackageManager.RestoreAsync(packagesDirectory, snapAppReleases, packageSource,
                                                                               restoreOptions.RestoreStrategyType,
                                                                               logger : logger, cancellationToken : cancellationToken,
                                                                               checksumConcurrency : restoreOptions.RestoreConcurrency,
                                                                               downloadConcurrency : restoreOptions.DownloadConcurrency);

                    if (!restoreSummary.Success || !restoreOptions.BuildInstallers)
                    {
                        continue;
                    }

                    var mostRecentSnapRelease = snapAppReleases.GetMostRecentRelease();

                    var snapAppInstaller = new SnapApp(snapAppReleases.App)
                    {
                        Version = mostRecentSnapRelease.Version
                    };

                    snapAppInstaller.SetCurrentChannel(snapChannel.Name);

                    if (restoreOptions.BuildInstallers ||
                        snapApp.Target.Installers.Any(x => x.HasFlag(SnapInstallerType.Web)))
                    {
                        logger.Info('-'.Repeat(TerminalBufferWidth));

                        await BuildInstallerAsync(logger, snapOs, snapxEmbeddedResources, snapAppWriter, snapAppInstaller, coreRunLib,
                                                  installersDirectory, null, releasesNupkgAbsolutePath, false, cancellationToken);
                    }

                    if (restoreOptions.BuildInstallers ||
                        snapApp.Target.Installers.Any(x => x.HasFlag(SnapInstallerType.Offline)))
                    {
                        logger.Info('-'.Repeat(TerminalBufferWidth));

                        var fullNupkgAbsolutePath = filesystem.PathCombine(packagesDirectory, mostRecentSnapRelease.BuildNugetFullFilename());

                        await BuildInstallerAsync(logger, snapOs, snapxEmbeddedResources, snapAppWriter, snapAppInstaller, coreRunLib,
                                                  installersDirectory, fullNupkgAbsolutePath, releasesNupkgAbsolutePath, true, cancellationToken);
                    }

                    logger.Info($"Finished restoring channel {snapChannel.Name}.");
                    logger.Info('-'.Repeat(TerminalBufferWidth));
                }
            }

            logger.Info('-'.Repeat(TerminalBufferWidth));
            logger.Info($"Restore completed in {stopwatch.Elapsed.TotalSeconds:0.0}s.");

            return(0);
        }
 /// <summary>
 /// Restore a backup.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='location'>
 /// Name of the backup location.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Name of the resource group.
 /// </param>
 /// <param name='backup'>
 /// Name of the backup.
 /// </param>
 /// <param name='restoreOptions'>
 /// Restore options.
 /// </param>
 public static void BeginRestore(this IBackupsOperations operations, string location, string resourceGroupName, string backup, RestoreOptions restoreOptions)
 {
     operations.BeginRestoreAsync(location, resourceGroupName, backup, restoreOptions).GetAwaiter().GetResult();
 }