コード例 #1
0
        public async Task <Unit> Handle(DeleteSiteCommand request, CancellationToken cancellationToken)
        {
            var account = await _context.Set <Account>()
                          .FirstOrDefaultAsync(x => !x.IsDeleted && x.UrlFriendlyName == request.AccountUrlFriendlyName, cancellationToken);

            if (account == null)
            {
                throw new EntityNotFoundException(nameof(Account), request.AccountUrlFriendlyName);
            }

            var site = await _context.Set <Site>()
                       .Include(x => x.Machine)
                       .FirstOrDefaultAsync(x => x.UrlFriendlyName == request.UrlFriendlyName, cancellationToken);

            if (site == null)
            {
                throw new EntityNotFoundException(nameof(Site), request.UrlFriendlyName);
            }

            var machine = site.Machine;

            machine.Terminate = true;

            _context.Set <Site>().Remove(site);

            await _context.SaveChangesAsync(cancellationToken);

            return(await Task.FromResult(Unit.Value));
        }
        public async Task <long> Handle(CreateOrUpdateInstanceSettingsTemplateCommand request, CancellationToken cancellationToken)
        {
            MachineConfig instanceSettingsTemplate;

            if (request.Id > 0)
            {
                instanceSettingsTemplate = await _context.Set <MachineConfig>()
                                           .FirstOrDefaultAsync(x => x.IsTemplate && x.Id == request.Id, cancellationToken);

                if (instanceSettingsTemplate == null)
                {
                    throw new EntityNotFoundException(nameof(MachineConfig), request.Id);
                }
            }
            else
            {
                instanceSettingsTemplate = new MachineConfig()
                {
                    IsTemplate = true
                };
                _context.Set <MachineConfig>().Add(instanceSettingsTemplate);
            }

            Mapper.Map(request, instanceSettingsTemplate);

            await _context.SaveChangesAsync(cancellationToken);

            return(instanceSettingsTemplate.Id);
        }
コード例 #3
0
        public async Task <long> Handle(CreateOrUpdateLicenseTemplateCommand request, CancellationToken cancellationToken)
        {
            LicenseConfig licenseTemplate;

            if (request.Id > 0)
            {
                licenseTemplate = await _context.Set <LicenseConfig>()
                                  .FirstOrDefaultAsync(x => x.IsTemplate && x.Id == request.Id, cancellationToken);

                if (licenseTemplate == null)
                {
                    throw new EntityNotFoundException(nameof(LicenseConfig), request.Id);
                }
            }
            else
            {
                licenseTemplate = new LicenseConfig()
                {
                    IsTemplate = true
                };
                _context.Set <LicenseConfig>().Add(licenseTemplate);
            }

            Mapper.Map(request, licenseTemplate);
            await _context.SaveChangesAsync(cancellationToken);

            return(licenseTemplate.Id);
        }
コード例 #4
0
        public async Task <List <AccountListingDto> > Handle(GetAllAccountsQuery request, CancellationToken cancellationToken)
        {
            var accounts = await _context.Set <Account>()
                           .Include(x => x.Contact)
                           .Include(x => x.Class)
                           .Include(x => x.Billing)
                           .Include(x => x.LicenseConfig)
                           .Include(x => x.MachineConfig)
                           .Where(x => !x.IsDeleted && !x.IsTemplate)
                           .ToListAsync(cancellationToken);

            var instanceSettingsTemplates = await _context.Set <MachineConfig>().Where(x => x.IsTemplate).OrderByDescending(x => x.Id).ToListAsync(cancellationToken);

            var accountDtos = new List <AccountListingDto>();

            foreach (var account in accounts)
            {
                var matched    = instanceSettingsTemplates.FirstOrDefault(x => MatchTemplate(x, account.MachineConfig));
                var accountDto = Mapper.Map <AccountListingDto>(account);
                accountDto.BundleVersion = matched == null ? "Custom" : matched.Name;
                accountDtos.Add(accountDto);
            }

            return(await Task.FromResult(accountDtos));
        }
コード例 #5
0
        private async Task LibraryFileValid(CreateAccountCommand command, CustomContext context, CancellationToken cancellationToken)
        {
            var mmaClass = await _context.Set <Class>().FirstOrDefaultAsync(x => x.Id == command.ClassId, cancellationToken);

            if (mmaClass == null)
            {
                context.AddFailure("Invalid MMA class");
            }


            var libraryFiles = await _context.Set <File>().Where(x => command.MainLibraryFiles.Contains(x.Id)).ToListAsync(cancellationToken);

            foreach (var libraryFile in libraryFiles)
            {
                try
                {
                    if (!await _libraryFileService.FileExists(libraryFile.Url))
                    {
                        context.AddFailure($"Library file {libraryFile.Name} doesn't exist on S3");
                    }
                }
                catch (Exception e)
                {
                    // Ignore
                }

                if (mmaClass != null && mmaClass.IsProduction && libraryFile.ReleaseStage != ReleaseStage.Released)
                {
                    context.AddFailure($"Library file {libraryFile.Name} must not be used for production account(s)");
                }
            }
        }
コード例 #6
0
        public async Task <IEnumerable <CreatableMachineDto> > Handle(GetCreatableMachinesForAccountQuery request, CancellationToken cancellationToken)
        {
            var account = await _context.Set <Account>()
                          .Include(x => x.LicenseConfig)
                          .Include(x => x.Sites)
                          .FirstOrDefaultAsync(x => !x.IsDeleted && !x.IsTemplate && x.Id == request.Id, cancellationToken);

            if (account == null)
            {
                throw new EntityNotFoundException(nameof(Account), request.Id);
            }

            var machines = await _context.Set <Machine>().Where(x => x.AccountId == account.Id)
                           .ToListAsync(cancellationToken);

            var licenseConfig = account.LicenseConfig;

            var sites = account.Sites;

            var creatableMachines = new List <CreatableMachineDto>();
            var launcherMachine   = machines.FirstOrDefault(x => x.IsLauncher);

            if (launcherMachine == null)
            {
                var site = licenseConfig.InstancePolicy == ServerInstancePolicy.AllInOne
                    ? sites.FirstOrDefault()
                    : null;

                creatableMachines.Add(new CreatableMachineDto()
                {
                    IsLauncher   = true,
                    IsSiteMaster = licenseConfig.InstancePolicy == ServerInstancePolicy.AllInOne,
                    Name         = AccountUtils.GenerateMachineName(account.UrlFriendlyName, licenseConfig.InstancePolicy, "Launcher"),
                    SiteId       = site?.Id,
                    SiteName     = site?.UrlFriendlyName
                });
            }

            if (licenseConfig.InstancePolicy == ServerInstancePolicy.InstancePerSiteMaster)
            {
                foreach (var site in sites)
                {
                    var machine = machines.FirstOrDefault(x => x.SiteName == site.UrlFriendlyName);
                    if (machine == null)
                    {
                        creatableMachines.Add(new CreatableMachineDto()
                        {
                            IsLauncher   = false,
                            IsSiteMaster = true,
                            Name         = AccountUtils.GenerateMachineName(account.UrlFriendlyName, licenseConfig.InstancePolicy, site.UrlFriendlyName),
                            SiteId       = site.Id,
                            SiteName     = site.UrlFriendlyName
                        });
                    }
                }
            }

            return(creatableMachines);
        }
コード例 #7
0
        public async Task UpdateStatus()
        {
            Machine machine;

            if (_task?.MachineId == null ||
                (machine = await _context.Set <Machine>().FirstOrDefaultAsync(x => x.Id == _task.MachineId.Value)) == null)
            {
                return;
            }

            var machineId = _task.MachineId.Value;

            var operations = await _context.Set <Operation>().Include(x => x.Type).Where(x => x.MachineId == machineId)
                             .OrderBy(x => x.Timestamp).ToListAsync();

            if (!operations.Any())
            {
                _task.Status   = SaasTaskStatus.Queued;
                _task.Progress = 0;
                return;
            }

            var terminalOperation = operations.FirstOrDefault(x => x.TypeName == OperationList.Last());

            if (terminalOperation != null && terminalOperation.Status == "SUCCESS")
            {
                _task.Progress = 100;
                _task.Status   = SaasTaskStatus.Completed;
                return;
            }

            var activeOperation = operations.FindLast(x => x.Active);

            var lastOperation = operations.Last();

            if (activeOperation != null)
            {
                _task.Status       = SaasTaskStatus.Running;
                _task.StatusDetail = activeOperation.Type.Description;
            }

            if (lastOperation != null)
            {
                var success        = lastOperation.Status == "SUCCESS";
                var operationIndex = Array.IndexOf(OperationList, lastOperation.TypeName);
                if (operationIndex > -1)
                {
                    _task.Progress = (operationIndex + (success ? 1 : 0)) * 100 / OperationList.Length;
                }

                if (lastOperation.Status == "FAILURE" && machine.NeedsAdmin)
                {
                    _task.Status = SaasTaskStatus.Failed;
                    return;
                }
            }
        }
コード例 #8
0
        public async Task <AccountDto> Handle(GetAccountQuery request, CancellationToken cancellationToken)
        {
            var account = await _context.Set <Account>()
                          .Include(x => x.Contact)
                          .Include(x => x.Class)
                          .Include(x => x.Billing)
                          .Include(x => x.LicenseConfig)
                          .Include(x => x.MachineConfig)
                          .Include(x => x.BackupConfig)
                          .Include(x => x.IdleSchedules)
                          .Include(x => x.Sites)
                          .Where(x => x.Id == request.Id)
                          .FirstOrDefaultAsync(cancellationToken);

            if (account == null)
            {
                throw new EntityNotFoundException(nameof(Account), request.Id);
            }

            var accountDto = Mapper.Map <AccountDto>(account);

            var machineConfigDto = accountDto.MachineConfig;
            var libraryFileIds   = machineConfigDto.MainLibraryFileIds;

            var libraryFiles = await _context.Set <File>().Where(x => x.Id != 0 && libraryFileIds.Contains(x.Id)).ToListAsync(cancellationToken);

            machineConfigDto.MainLibraryFiles = Mapper.Map <FileDto[]>(libraryFiles.ToArray());

            if (machineConfigDto.MainLibraryFileId.HasValue && machineConfigDto.MainLibraryFileId != 0)
            {
                var mainLibraryFile = await _context.Set <File>()
                                      .FirstOrDefaultAsync(x => x.Id == machineConfigDto.MainLibraryFileId, cancellationToken);

                machineConfigDto.MainLibraryFile = Mapper.Map <FileDto>(mainLibraryFile);
            }

            if (machineConfigDto.AccountLibraryFileId.HasValue && machineConfigDto.AccountLibraryFileId != 0)
            {
                var accountLibraryFile = await _context.Set <File>()
                                         .FirstOrDefaultAsync(x => x.Id == machineConfigDto.AccountLibraryFileId, cancellationToken);

                machineConfigDto.AccountLibraryFile = Mapper.Map <FileDto>(accountLibraryFile);
            }

            var instanceSettingsTemplates = await _context.Set <MachineConfig>().Where(x => x.IsTemplate).OrderByDescending(x => x.Id).ToListAsync(cancellationToken);

            var matched = instanceSettingsTemplates.FirstOrDefault(x => MatchTemplate(x, account.MachineConfig));

            machineConfigDto.BundleVersion = matched == null ? "Custom" : matched.Name;

            return(await Task.FromResult(accountDto));
        }
コード例 #9
0
        public async Task <SiteStatusDto> Handle(GetSiteStatusQuery request, CancellationToken cancellationToken)
        {
            var account = await _context.Set <Account>()
                          .FirstOrDefaultAsync(x => !x.IsDeleted && x.UrlFriendlyName == request.AccountUrlFriendlyName, cancellationToken);

            if (account == null)
            {
                throw new EntityNotFoundException(nameof(Account), request.AccountUrlFriendlyName);
            }

            var site = await _context.Set <Site>()
                       .Include(x => x.Machine)
                       .FirstOrDefaultAsync(x => x.AccountId == account.Id && x.UrlFriendlyName == request.UrlFriendlyName, cancellationToken);

            if (site == null)
            {
                throw new EntityNotFoundException(nameof(Site), request.UrlFriendlyName);
            }

            var machine = site.Machine;

            if (machine == null)
            {
                return(null);
            }

            var desiredState = await _context.Set <State>()
                               .FirstOrDefaultAsync(x => x.MachineId == machine.Id && x.Desired, cancellationToken);

            var instance = await _context.Set <CloudInstance>()
                           .OrderByDescending(x => x.Timestamp)
                           .FirstOrDefaultAsync(x => x.MachineId == machine.Id && x.Active, cancellationToken);

            var activeOperation = await _context.Set <Operation>()
                                  .Include(x => x.Type)
                                  .FirstOrDefaultAsync(x => x.MachineId == machine.Id && x.Active, cancellationToken);

            var activeTasks = _taskTrackingService.GetActiveTasksForSite(site.Id);

            var currentTask = activeTasks.FirstOrDefault();

            var siteStatus = new SiteStatusDto()
            {
                ActiveTask     = currentTask,
                InstanceStatus = instance?.Status,
                SiteStatus     = GetSiteStatus(machine, instance, currentTask, activeOperation)
            };

            return(await Task.FromResult(siteStatus));
        }
コード例 #10
0
        public async Task Handle(AccountCreatedEvent notification, CancellationToken cancellationToken)
        {
            try
            {
                var desiredState = notification.Account.Machines.First().States.First(x => x.Desired);
                _context.Set <HistoricalDesiredState>().Add(Mapper.Map <HistoricalDesiredState>(desiredState));

                await _context.SaveChangesAsync(cancellationToken);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
            }
        }
コード例 #11
0
        public async Task <Unit> Handle(DeleteLibraryFileCommand command, CancellationToken cancellationToken)
        {
            var file = await _context.Set <File>().FirstOrDefaultAsync(x => x.Id == command.Id, cancellationToken);

            if (file == null)
            {
                throw new EntityNotFoundException(nameof(File), command.Id);
            }

            _context.Set <File>().Remove(file);
            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
コード例 #12
0
        private async Task IdleScheduleNotConflictWithBackupSettings(UpdateIdleScheduleCommand command, CustomContext context, CancellationToken cancellationToken)
        {
            var account = await _context.Set <Account>()
                          .Include(x => x.BackupConfig)
                          .FirstOrDefaultAsync(x => x.Id == command.AccountId, cancellationToken);

            if (account == null || account.IsDeleted)
            {
                context.AddFailure("Accounts not found");
                return;
            }

            var idleSchedules = command.IdleSchedules;
            var backupTimes   = DeserializeBackupTimes(account.BackupConfig.Times);

            foreach (var backupTime in backupTimes)
            {
                foreach (var idleSchedule in idleSchedules)
                {
                    var from = idleSchedule.StopAt;
                    var to   = from.AddHours(idleSchedule.ResumeAfter);
                    if (backupTime <= to && backupTime >= from)
                    {
                        context.AddFailure(new ValidationFailure("idleSchedules", "Idle schedule has conflict with backup settings", idleSchedule));
                    }
                }
            }
        }
コード例 #13
0
        public async Task <SiteServerStatusDto> Handle(GetSiteServerStatusForMachineQuery query, CancellationToken cancellationToken)
        {
            var machine = await _context.Set <Machine>()
                          .Include(x => x.Account)
                          .Include("Account.MachineConfig")
                          .FirstOrDefaultAsync(x => x.Id == query.Id, cancellationToken);

            if (machine == null)
            {
                throw new EntityNotFoundException(nameof(Machine), query.Id);
            }

            var scheme        = machine.Account.MachineConfig.EnableSsl ? "https" : "http";
            var baseDomainUrl = "";

            using (var httpClient = new HttpClient()
            {
                BaseAddress = new Uri($"{scheme}://{machine.SiteName}.{machine.Account.UrlFriendlyName}.{baseDomainUrl}:8080")
            })
            {
                var response = await httpClient.GetAsync("irm/rest/v1.14/server-status", cancellationToken);

                if (!response.IsSuccessStatusCode)
                {
                    throw new CommandException();
                }

                var serverStatus = JsonConvert.DeserializeObject <SiteServerStatusDto>(await response.Content.ReadAsStringAsync());

                return(serverStatus);
            }
        }
コード例 #14
0
        public async Task <PagedData <CommitDto> > Handle(GetCommitsForRepoQuery request, CancellationToken cancellationToken)
        {
            var queryable = _context.Set <Commit>()
                            .Where(x => x.Repo == request.Repo);

            if (request.BranchId.HasValue)
            {
                queryable = queryable.Where(x => x.Branch != null && x.BranchId == request.BranchId);
            }

            if (request.TagOnly)
            {
                queryable = queryable.Where(x => x.Tag != null && x.Tag != string.Empty);
            }

            if (!string.IsNullOrWhiteSpace(request.Search))
            {
                queryable = queryable.Where(x => x.FullHash.Contains(request.Search));
            }

            var total = await queryable.CountAsync(cancellationToken);

            var cloudInstances = await queryable
                                 .OrderByDescending(x => x.Timestamp)
                                 .Skip(request.StartIndex)
                                 .Take(request.Limit)
                                 .ToListAsync(cancellationToken);

            return(new PagedData <CommitDto> {
                Items = Mapper.Map <IEnumerable <CommitDto> >(cloudInstances),
                TotalItems = total,
                StartIndex = request.StartIndex,
                Limit = request.Limit
            });
        }
コード例 #15
0
        public async Task <IEnumerable <AccountInfoDto> > Handle(GetInfoForAllAccountsQuery query, CancellationToken cancellationToken)
        {
            var accounts = await _context.Set <Account>()
                           .Include(x => x.Machines)
                           .Where(x => !x.IsDeleted && !x.IsTemplate)
                           .ToListAsync(cancellationToken);

            return(accounts.Select(x => {
                var managed = x.Machines.Count(y => y.Managed.HasValue && y.Managed.Value);

                var manualMaintenance = x.Machines.Count(y => y.Managed.HasValue && y.Managed.Value &&
                                                         y.ManualMaintenance.HasValue && y.ManualMaintenance.Value);

                var idle = x.Machines.Count(y => y.Managed.HasValue && y.Managed.Value &&
                                            y.Idle.HasValue && y.Idle.Value);

                var stop = x.Machines.Count(y => y.Managed.HasValue && y.Managed.Value && y.Stop);

                var needsAdmin = x.Machines.Count(y => y.Managed.HasValue && y.Managed.Value && y.NeedsAdmin);
                var turbo = x.Machines.Count(y => y.Managed.HasValue && y.Managed.Value && y.Turbo.HasValue && y.Turbo.Value);


                return new AccountInfoDto
                {
                    Id = x.Id,
                    MachineCount = x.Machines.Count,
                    NeedsAdmin = needsAdmin,
                    ManualMaintenance = manualMaintenance,
                    Managed = managed,
                    Turbo = turbo,
                    Idle = idle,
                    Stop = stop
                };
            }));
        }
コード例 #16
0
        public async Task <Unit> Handle(ForcePopulateForMachineCommand command, CancellationToken cancellationToken)
        {
            var machine = await _context.Set <Machine>()
                          .Include(x => x.CloudInstances)
                          .FirstOrDefaultAsync(x => x.Id == command.Id, cancellationToken);

            if (machine == null)
            {
                throw new EntityNotFoundException(nameof(Machine), command.Id);
            }

            if (!machine.CloudInstances.Any())
            {
                throw new CommandException("Machine has no instance");
            }

            foreach (var instance in machine.CloudInstances)
            {
                if (command.PopulateLauncher)
                {
                    instance.LauncherPopulated = false;
                }

                if (command.PopulateSiteMaster)
                {
                    instance.SiteMasterPopulated = false;
                }

                instance.AltString = command.AltString;
            }

            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
コード例 #17
0
        public async Task <IEnumerable <SiteDto> > Handle(GetAllSitesForAccountQuery request, CancellationToken cancellationToken)
        {
            var sites = await _context.Set <Site>()
                        .Where(x => x.AccountId == request.Id)
                        .ToListAsync(cancellationToken);

            return(await Task.FromResult(Mapper.Map <IEnumerable <SiteDto> >(sites)));
        }
コード例 #18
0
        public async Task <List <PackageDto> > Handle(GetAllLibraryPackagesQuery request, CancellationToken cancellationToken)
        {
            var packages = await _context.Set <Package>().ToListAsync(cancellationToken);

            var dtos = Mapper.Map <List <PackageDto> >(packages);

            return(dtos);
        }
コード例 #19
0
        public async Task <IEnumerable <BackupConfigDto> > Handle(GetAllBackupSettingsTemplatesQuery request, CancellationToken cancellationToken)
        {
            var backupSettingsTemplates = await _context.Set <BackupConfig>()
                                          .Include(x => x.Account)
                                          .Where(x => x.Account == null || !x.Account.IsDeleted)
                                          .ToListAsync(cancellationToken);

            return(Mapper.Map <List <BackupConfigDto> >(backupSettingsTemplates));
        }
コード例 #20
0
        public async Task <IEnumerable <MachineDto> > Handle(GetAllMachinesForAccountQuery request, CancellationToken cancellationToken)
        {
            var query = _context.Set <Machine>()
                        .Include(x => x.Class)
                        .Include(x => x.CloudInstanceType)
                        .Where(x => (request.Id.HasValue && x.AccountId.HasValue && x.AccountId == request.Id) || x.Account.UrlFriendlyName == request.UrlFriendlyName)
                        .Select(x => new
            {
                x,
                Class             = x.Class,
                CloudInstances    = x.CloudInstances.Where(y => y.Active),
                CloudInstanceType = x.CloudInstanceType,
                Operations        = x.Operations.Where(y => y.Active),
                OperationTypes    = x.Operations.Select(y => y.Type)
            });


            var machines = query
                           .AsEnumerable()
                           .Select(x => x.x)
                           .ToList();

            var machineIds = machines.Select(x => x.Id).ToArray();
            var states     = await _context.Set <State>().Where(x => x.Desired && x.MachineId.HasValue && machineIds.Contains(x.MachineId.Value)).ToListAsync(cancellationToken);

            machines.ForEach(machine =>
            {
                machine.States = states.Where(x => x.MachineId == machine.Id).ToList();
            });

            var instanceSettingsTemplates = await _context.Set <MachineConfig>().Where(x => x.IsTemplate).OrderByDescending(x => x.Id).ToListAsync(cancellationToken);

            var machineDtos = new List <MachineDto>();

            foreach (var machine in machines)
            {
                var machineDto = Mapper.Map <MachineDto>(machine);
                var matched    = instanceSettingsTemplates.FirstOrDefault(x => MatchTemplate(x, machine));
                machineDto.BundleVersion = matched == null ? "Custom" : matched.Name;
                machineDtos.Add(machineDto);
            }

            return(machineDtos);
        }
コード例 #21
0
        public async Task <IEnumerable <OperationDto> > Handle(GetAllOperationsForMachineQuery request, CancellationToken cancellationToken)
        {
            var operations = await _context.Set <Operation>()
                             .Include(x => x.Type)
                             .Where(x => x.MachineId == request.Id)
                             .OrderByDescending(x => x.Timestamp)
                             .ToListAsync(cancellationToken);

            return(Mapper.Map <IEnumerable <OperationDto> >(operations));
        }
コード例 #22
0
 private async Task AddUserOperation(string type, long machineId, string user, CancellationToken cancellationToken)
 {
     _context.Set <UserOperation>().Add(new UserOperation
     {
         TypeName  = type,
         MachineId = machineId,
         Timestamp = DateTimeOffset.UtcNow,
         User      = user,
     });
     await _context.SaveChangesAsync(cancellationToken);
 }
コード例 #23
0
        public async Task <Unit> Handle(SendMessageCommand command, CancellationToken cancellationToken)
        {
            var machineIds = command.Machines ?? new List <long>();

            if (command.Accounts != null && command.Accounts.Any())
            {
                var machines = await _context.Set <Machine>()
                               .Where(x => x.AccountId.HasValue && command.Accounts.Contains(x.AccountId.Value))
                               .ToListAsync();

                machineIds = machineIds.Union(machines.Select(x => x.Id)).Distinct();
            }

            if (command.AccountUrlNames != null && command.AccountUrlNames.Any())
            {
                var machines = await _context.Set <Machine>()
                               .Include(x => x.Account)
                               .Where(x => x.AccountId.HasValue && command.AccountUrlNames.Contains(x.Account.UrlFriendlyName))
                               .ToListAsync();

                machineIds = machineIds.Union(machines.Select(x => x.Id)).Distinct();
            }

            var messages = machineIds.Select(x => new Message()
            {
                MachineId    = x,
                Title        = command.Title,
                Body         = command.Body,
                ExpiresAfter = 10,
                Timestamp    = DateTimeOffset.Now
            });

            foreach (var message in messages)
            {
                _context.Set <Message>().Add(message);
            }

            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
コード例 #24
0
        public async Task <Unit> Handle(QueueOperationsCommand command, CancellationToken cancellationToken)
        {
            var machine = await _context.Set <Machine>()
                          .FirstOrDefaultAsync(x => x.Id == command.Id, cancellationToken);

            if (machine == null)
            {
                throw new EntityNotFoundException(nameof(Machine), command.Id);
            }

            var runningOperation = await _context.Set <Operation>().FirstOrDefaultAsync(x => x.MachineId == machine.Id && (x.Active || x.Status.ToLower() == "running"), cancellationToken);

            if (runningOperation != null)
            {
                throw new CommandException();
            }

            var operationTypeName = command.Operations.FirstOrDefault();
            var operationType     = await _context.Set <OperationType>()
                                    .FirstOrDefaultAsync(x => x.Name == operationTypeName, cancellationToken);

            if (operationType == null || !(operationType.CanBeManual.HasValue && operationType.CanBeManual.Value))
            {
                throw new CommandException();
            }

            var forcedOperation = new Operation()
            {
                Type      = operationType,
                Active    = true,
                Timestamp = DateTimeOffset.Now,
                Status    = "FORCED",
                MachineId = command.Id,
                TypeName  = operationTypeName
            };

            _context.Set <Operation>().Add(forcedOperation);
            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
コード例 #25
0
        public VersionInfo Resolve(string software, string versionMode, VersionInfo version, string currentVersion = null, string defaultVersion = null)
        {
            switch (versionMode)
            {
            case null:
            case VersionModes.None:
                return(new VersionInfo(defaultVersion));

            case VersionModes.Skip:
                return(new VersionInfo(currentVersion));

            case VersionModes.Latest:
                var repo       = SoftwareRepoMappings[software];
                var branchName = version?.Branch;
                var query      = !branchName.IsNullOrWhiteSpace() ?
                                 _context.Set <Commit>().Include(x => x.Branch).Where(x => x.Branch.Name == branchName) :
                                 _context.Set <Commit>().Include(x => x.Branch).Where(x => x.Branch.Stable);

                query = query.Where(x => x.Repo == repo);

                var latestCommit = query.OrderByDescending(x => x.Timestamp).FirstOrDefault();

                return(new VersionInfo {
                    Branch = latestCommit?.Branch.Name, Hash = latestCommit?.ShortHash
                });


            default:
                return(version);
            }
        }
コード例 #26
0
        public async Task <IEnumerable <AccountDto> > Handle(GetAllGeneralTemplatesQuery request, CancellationToken cancellationToken)
        {
            var generalTemplates = await _context.Set <Account>()
                                   .Include(x => x.Contact)
                                   .Include(x => x.Billing)
                                   .Include(x => x.BackupConfig)
                                   .Include(x => x.LicenseConfig)
                                   .Include(x => x.MachineConfig)
                                   .Where(x => !x.IsDeleted)
                                   .ToListAsync(cancellationToken);

            return(Mapper.Map <List <AccountDto> >(generalTemplates));
        }
コード例 #27
0
        public async Task <IEnumerable <MachineConfigDto> > Handle(GetAllInstanceSettingsTemplatesQuery request, CancellationToken cancellationToken)
        {
            var licenseTemplates = await _context.Set <MachineConfig>()
                                   .Include(x => x.Account)
                                   .Where(x => x.Account == null || (x.Account != null && !x.Account.IsDeleted))
                                   .ToListAsync(cancellationToken);

            var allLibraryFileIds = licenseTemplates.SelectMany(x => x.MainLibraryFiles.DeserializeArray <long>())
                                    .Union(licenseTemplates.Where(x => x.AccountLibraryFile.HasValue).Select(x => x.AccountLibraryFile.Value)).Distinct();

            var libraryFiles = await _context.Set <File>()
                               .Where(x => x.Id != 0 && allLibraryFileIds.Contains(x.Id))
                               .ToListAsync(cancellationToken);

            var libraryFileMap = Mapper.Map <IEnumerable <FileDto> >(libraryFiles).ToDictionary(x => x.Id, x => x);

            var licenseTemplateDtos = Mapper.Map <List <MachineConfigDto> >(licenseTemplates);

            foreach (var licenseTemplateDto in licenseTemplateDtos)
            {
                licenseTemplateDto.MainLibraryFiles = licenseTemplateDto.MainLibraryFileIds.Select(x =>
                {
                    FileDto mainLibraryFile;
                    return(libraryFileMap.TryGetValue(x, out mainLibraryFile) ? mainLibraryFile : null);
                }).Where(x => x != null).ToArray();

                if (licenseTemplateDto.AccountLibraryFileId.HasValue)
                {
                    FileDto accountLibraryFile;
                    licenseTemplateDto.AccountLibraryFile =
                        libraryFileMap.TryGetValue(licenseTemplateDto.AccountLibraryFileId.Value, out accountLibraryFile)
                            ? accountLibraryFile
                            : null;
                }
            }

            return(licenseTemplateDtos);
        }
コード例 #28
0
        public async Task <Unit> Handle(ResetLastOperationCommand request, CancellationToken cancellationToken)
        {
            var machine = await _context.Set <Machine>().FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken);

            if (machine == null)
            {
                throw new EntityNotFoundException(nameof(Machine), request.Id);
            }

            var activeOperation = await _context.Set <Operation>().OrderByDescending(x => x.Timestamp)
                                  .FirstOrDefaultAsync(x => x.MachineId == request.Id && x.Active, cancellationToken);

            if (activeOperation == null)
            {
                throw new CommandException($"MachineDto {request.Id} has no active operation");
            }

            _context.Set <Operation>().Remove(activeOperation);

            await _context.SaveChangesAsync(cancellationToken);

            return(await Task.FromResult(Unit.Value));
        }
コード例 #29
0
        public async Task <MachineConfigDto> Handle(GetInstanceSettingsForAccountQuery query, CancellationToken cancellationToken)
        {
            var machineConfig = await _context.Set <MachineConfig>().Include(x => x.Account)
                                .FirstOrDefaultAsync(x => x.Account != null && x.Account.Id == query.Id, cancellationToken);

            var machineConfigDto = Mapper.Map <MachineConfigDto>(machineConfig);

            var libraryFileIds = machineConfigDto.MainLibraryFileIds;

            var libraryFiles = await _context.Set <File>().Where(x => x.Id != 0 && libraryFileIds.Contains(x.Id)).ToListAsync(cancellationToken);

            machineConfigDto.MainLibraryFiles = Mapper.Map <FileDto[]>(libraryFiles.ToArray());

            if (machineConfigDto.MainLibraryFileId.HasValue)
            {
                var mainLibraryFile = await _context.Set <File>()
                                      .FirstOrDefaultAsync(x => x.Id == machineConfigDto.MainLibraryFileId, cancellationToken);

                machineConfigDto.MainLibraryFile = Mapper.Map <FileDto>(mainLibraryFile);
            }

            if (machineConfigDto.AccountLibraryFileId.HasValue)
            {
                var accountLibraryFile = await _context.Set <File>()
                                         .FirstOrDefaultAsync(x => x.Id == machineConfigDto.AccountLibraryFileId, cancellationToken);

                machineConfigDto.AccountLibraryFile = Mapper.Map <FileDto>(accountLibraryFile);
            }

            var instanceSettingsTemplates = await _context.Set <MachineConfig>().Where(x => x.IsTemplate).OrderByDescending(x => x.Id).ToListAsync(cancellationToken);

            var matched = instanceSettingsTemplates.FirstOrDefault(x => MatchTemplate(x, machineConfig));

            machineConfigDto.BundleVersion = matched == null ? "Custom" : matched.Name;

            return(machineConfigDto);
        }
コード例 #30
0
        private async Task CanCreateNewSite(CreateSiteCommand command, CustomContext context, CancellationToken cancellationToken)
        {
            var account = await _context.Set <Account>()
                          .Include(x => x.LicenseConfig)
                          .Include(x => x.Sites)
                          .FirstOrDefaultAsync(x => x.UrlFriendlyName == command.AccountUrlFriendlyName, cancellationToken);

            if (account == null || account.IsDeleted)
            {
                context.AddFailure("Accounts not found");
                return;
            }

            if (!account.IsActive)
            {
                context.AddFailure("Accounts has been deactivated");
                return;
            }

            if (account.LicenseConfig.MaxSites <= account.Sites.Count)
            {
                context.AddFailure("Maximum site limit has been reached");
            }
        }