private async Task <NexusConfig> GetSignatureKeyAsync(CancellationToken cancellationToken)
        {
            ApplicationSettings applicationSettings =
                await _applicationSettingsStore.GetApplicationSettings(cancellationToken);

            NexusConfig nexusConfig = applicationSettings.NexusConfig;

            return(nexusConfig);
        }
Exemple #2
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.Yield();

            ApplicationSettings applicationSettings =
                await _applicationSettingsStore.GetApplicationSettings(stoppingToken);

            if (!applicationSettings.AutoDeploy.Enabled)
            {
                _logger.Debug("Auto deploy is disabled");
                return;
            }

            if (!applicationSettings.AutoDeploy.PollingEnabled)
            {
                _logger.Debug("Auto deploy polling is disabled");
                return;
            }

            await Task.Delay(TimeSpan.FromSeconds(_autoDeployConfiguration.StartupDelayInSeconds), stoppingToken);

            while (!stoppingToken.IsCancellationRequested)
            {
                var deploymentTargets = await GetDeploymentTargetsWithAutoDeployEnabled(stoppingToken);

                if (deploymentTargets.IsDefaultOrEmpty)
                {
                    _logger.Verbose(
                        "Found no deployment targets with auto deployment enabled, waiting {DelayInSeconds} seconds",
                        _autoDeployConfiguration.EmptyTargetsDelayInSeconds);

                    await Task.Delay(
                        TimeSpan.FromSeconds(_autoDeployConfiguration.EmptyTargetsDelayInSeconds),
                        stoppingToken);

                    continue;
                }

                var targetsWithUrl = deploymentTargets.Where(target => target.Url is {}).ToImmutableArray();
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.Yield();

            ApplicationSettings applicationSettings =
                await _applicationSettingsStore.GetApplicationSettings(stoppingToken);

            if (!applicationSettings.HostAgentEnabled)
            {
                _logger.Information("Host agent is disabled");
                return;
            }

            string?exePath = applicationSettings.AgentExe;

            if (string.IsNullOrWhiteSpace(applicationSettings.AgentExe))
            {
                _logger.Debug("No agent exe has been specified");

                var currentVersion = await GetCurrentVersionAsync();

                NuGetPackageVersion nuGetPackageVersion = currentVersion is {}
        public async Task Handle(PackageUpdatedEvent notification, CancellationToken cancellationToken)
        {
            if (!(await _applicationSettingsStore.GetApplicationSettings(cancellationToken)).AutoDeploy.Enabled)
            {
                _logger.Information("Auto deploy is disabled, skipping package web hook notification");
                return;
            }

            PackageVersion packageIdentifier = notification.PackageVersion;

            if (packageIdentifier is null)
            {
                throw new ArgumentException(nameof(packageIdentifier));
            }

            _logger.Information("Received hook for package {Package}", packageIdentifier);

            IReadOnlyCollection <DeploymentTarget> deploymentTargets =
                (await _targetSource.GetDeploymentTargetsAsync(stoppingToken: cancellationToken))
                .SafeToReadOnlyCollection();

            DeploymentTarget[] withAutoDeploy = deploymentTargets.Where(target => target.AutoDeployEnabled).ToArray();

            if (!withAutoDeploy.Any())
            {
                _logger.Information("No target has auto deploy enabled");
            }
            else
            {
                foreach (DeploymentTarget deploymentTarget in withAutoDeploy)
                {
                    if (deploymentTarget.PackageId.Equals(
                            packageIdentifier.PackageId,
                            StringComparison.OrdinalIgnoreCase))
                    {
                        if (deploymentTarget.NuGet.NuGetConfigFile is {} &&
        public async Task <IReadOnlyCollection <PackageVersion> > GetPackageVersionsAsync(
            string packageId,
            bool useCache                       = true,
            bool includePreReleased             = false,
            string?nugetPackageSource           = null,
            string?nugetConfigFile              = null,
            CancellationToken cancellationToken = default)
        {
            string cacheKey = GetCacheKey(nugetConfigFile, nugetPackageSource, packageId);

            _logger.Verbose("Using package cache key {Key}", cacheKey);

            if (useCache)
            {
                var packages = await _memoryCache.Get <PackageVersions>(cacheKey, _logger, cancellationToken);

                _logger.Debug(
                    "Returning packages from cache with key {Key} for package id {PackageId}",
                    cacheKey,
                    packageId);

                if (packages?.Versions.Length > 0)
                {
                    return(packages.Versions
                           .Select(version => new PackageVersion(packageId, SemanticVersion.Parse(version)))
                           .ToImmutableArray());
                }
            }

            var addedPackages = (await _packageService.GetPackageVersionsAsync(packageId, useCache,
                                                                               includePreReleased, nugetPackageSource, nugetConfigFile, cancellationToken)).ToArray();

            if (addedPackages.Length > 0)
            {
                ApplicationSettings settings =
                    await _applicationSettingsStore.GetApplicationSettings(CancellationToken.None);

                var cacheTime = settings.CacheTime;

                string[] versions = addedPackages
                                    .Select(version => version.Version.ToNormalizedString())
                                    .ToArray();

                var packageVersions = new PackageVersions {
                    Versions = versions
                };

                await _memoryCache.Set(cacheKey, packageVersions, _logger, cancellationToken);

                _logger.Debug(
                    "Cached {Packages} packages with key {CacheKey} for {Duration} seconds",
                    addedPackages.Length,
                    cacheKey,
                    cacheTime.TotalSeconds.ToString("F0", CultureInfo.InvariantCulture));
            }
            else
            {
                _logger.Debug("Added no packages to in-memory cache for cache key {CacheKey}", cacheKey);
            }

            return(addedPackages);
        }
        public async Task <AppVersion?> GetAppMetadataAsync(
            [NotNull] DeploymentTarget target,
            CancellationToken cancellationToken)
        {
            if (target is null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            string cacheKey = GetCacheKey(target.Id);

            if (_customMemoryCache.TryGetValue(cacheKey, out AppVersion? appMetadata))
            {
                _logger.Verbose("App metadata fetched from cache {CacheKey}", cacheKey);
                return(appMetadata);
            }

            ApplicationSettings applicationSettings =
                await _applicationSettingsStore.GetApplicationSettings(cancellationToken);

            var targetMetadataTimeout = target.MetadataTimeout ?? applicationSettings.ApplicationSettingsCacheTimeout;

            using (CancellationTokenSource cancellationTokenSource = _timeoutHelper.CreateCancellationTokenSource(
                       targetMetadataTimeout))
            {
                if (_logger.IsEnabled(LogEventLevel.Verbose))
                {
                    cancellationTokenSource.Token.Register(() =>
                    {
                        _logger.Verbose(
                            "{Method} for {Target}, cancellation token invoked out after {Seconds} seconds",
                            nameof(GetAppMetadataAsync),
                            target,
                            targetMetadataTimeout.TotalSeconds.ToString("F1"));
                    });
                }

                using var linkedTokenSource =
                          CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cancellationTokenSource.Token);
                Task <(HttpResponseMessage?, string?)> metadataTask =
                    GetApplicationMetadataTask(target, linkedTokenSource.Token);

                Task <IReadOnlyCollection <PackageVersion> > allowedPackagesTask =
                    GetAllowedPackagesAsync(target, linkedTokenSource.Token);

                await Task.WhenAll(metadataTask, allowedPackagesTask);

                (var response, string?message) = await metadataTask;

                IReadOnlyCollection <PackageVersion> packages = await allowedPackagesTask;

                if (response is null)
                {
                    return(new AppVersion(
                               target,
                               message ?? $"Could not get application metadata from target {target.Url}, no response",
                               packages));
                }

                if (!response.IsSuccessStatusCode)
                {
                    return(new AppVersion(
                               target,
                               message ??
                               $"Could not get application metadata from target {target.Url}, status code not successful {response.StatusCode}",
                               packages));
                }

                appMetadata =
                    await GetAppVersionAsync(response, target, packages, linkedTokenSource.Token);

                response.Dispose();
            }

            if (appMetadata.SemanticVersion is { })