private async STT.Task <Data.TaskStatus> ProcessTaskAsync(TaskEntity taskToExecute, List <ResultEntity> resultEntityList, SteamfitterContext steamfitterContext, CancellationToken ct)
        {
            var overallStatus = Data.TaskStatus.succeeded;
            var tasks         = new List <STT.Task <string> >();
            var xref          = new Dictionary <int, ResultEntity>();

            foreach (var resultEntity in resultEntityList)
            {
                resultEntity.InputString = resultEntity.InputString.Replace("{moid}", resultEntity.VmId.ToString());
                resultEntity.InputString = resultEntity.InputString.Replace("{VmName}", resultEntity.VmName);
                if (resultEntity.VmId != null && resultEntity.VmName == "")
                {
                    resultEntity.VmName = _stackStormService.GetVmName((Guid)resultEntity.VmId);
                }
                resultEntity.Status     = TaskStatus.pending;
                resultEntity.StatusDate = DateTime.UtcNow;
                // if no expiration is set, us the maximum allowed by the TaskProcessMaxWaitSeconds setting
                resultEntity.ExpirationSeconds = resultEntity.ExpirationSeconds <= 0 ? _vmTaskProcessingOptions.CurrentValue.TaskProcessMaxWaitSeconds : resultEntity.ExpirationSeconds;
                var task = await RunTask(taskToExecute, resultEntity, ct);

                tasks.Add(task);
                xref[task.Id] = resultEntity;
                await steamfitterContext.SaveChangesAsync();

                _engineHub.Clients.Group(EngineGroups.SystemGroup).SendAsync(EngineMethods.ResultUpdated, _mapper.Map <ViewModels.Result>(resultEntity));
            }
            foreach (var bucket in AsCompletedBuckets(tasks))
            {
                try
                {
                    var task         = await bucket;
                    var resultEntity = xref[task.Id];
                    resultEntity.ActualOutput = task.Result == null ? "" : task.Result.ToString();
                    resultEntity.Status       = ProcessResult(resultEntity, ct);
                    resultEntity.StatusDate   = DateTime.UtcNow;
                    if (resultEntity.Status != Data.TaskStatus.succeeded)
                    {
                        if (overallStatus != Data.TaskStatus.failed)
                        {
                            overallStatus = resultEntity.Status;
                        }
                    }
                    await steamfitterContext.SaveChangesAsync();

                    _engineHub.Clients.Group(EngineGroups.SystemGroup).SendAsync(EngineMethods.ResultUpdated, _mapper.Map <ViewModels.Result>(resultEntity));
                }
                catch (OperationCanceledException)
                {
                    _logger.LogInformation("the executing task was cancelled");
                }
                catch (Exception ex)
                {
                    _logger.LogInformation(ex, "the executing task caused an exception");
                }
            }
            return(overallStatus);
        }
예제 #2
0
        public async STT.Task <ViewModels.User> CreateAsync(ViewModels.User user, CancellationToken ct)
        {
            if (!(await _authorizationService.AuthorizeAsync(_user, null, new FullRightsRequirement())).Succeeded)
            {
                throw new ForbiddenException();
            }

            var userEntity = _mapper.Map <UserEntity>(user);

            _context.Users.Add(userEntity);
            await _context.SaveChangesAsync(ct);

            return(await GetAsync(user.Id, ct));
        }
예제 #3
0
        public async Task <ViewModels.Permission> CreateAsync(ViewModels.Permission permission, CancellationToken ct)
        {
            if (!(await _authorizationService.AuthorizeAsync(_user, null, new FullRightsRequirement())).Succeeded)
            {
                throw new ForbiddenException();
            }

            permission.DateCreated = DateTime.UtcNow;
            var permissionEntity = Mapper.Map <PermissionEntity>(permission);

            _context.Permissions.Add(permissionEntity);
            await _context.SaveChangesAsync(ct);

            return(await GetAsync(permissionEntity.Id, ct));
        }
예제 #4
0
        public async STT.Task <ViewModels.ScenarioTemplate> CreateAsync(ViewModels.ScenarioTemplate scenarioTemplate, CancellationToken ct)
        {
            if (!(await _authorizationService.AuthorizeAsync(_user, null, new ContentDeveloperRequirement())).Succeeded)
            {
                throw new ForbiddenException();
            }

            scenarioTemplate.DateCreated = DateTime.UtcNow;
            var scenarioTemplateEntity = _mapper.Map <ScenarioTemplateEntity>(scenarioTemplate);

            //TODO: add permissions
            // var scenarioTemplateAdminPermission = await _context.Permissions
            //     .Where(p => p.Key == PlayerClaimTypes.ScenarioTemplateAdmin.ToString())
            //     .FirstOrDefaultAsync();

            // if (scenarioTemplateAdminPermission == null)
            //     throw new EntityNotFoundException<Permission>($"{PlayerClaimTypes.ScenarioTemplateAdmin.ToString()} Permission not found.");

            _context.ScenarioTemplates.Add(scenarioTemplateEntity);
            await _context.SaveChangesAsync(ct);

            scenarioTemplate = await GetAsync(scenarioTemplateEntity.Id, ct);

            _engineHub.Clients.All.SendAsync(EngineMethods.ScenarioTemplateCreated, scenarioTemplate);

            return(scenarioTemplate);
        }
예제 #5
0
        public async Task <IEnumerable <FileEntity> > SaveAsync(IEnumerable <IFormFile> files, CancellationToken ct)
        {
            if (!(await _authorizationService.AuthorizeAsync(_user, null, new ContentDeveloperRequirement())).Succeeded)
            {
                throw new ForbiddenException();
            }

            var list = new List <FileEntity>();

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    var filePath = $"{_options.LocalDirectory}{formFile.FileName}";
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        // write file
                        await formFile.CopyToAsync(stream);

                        // not a zip? zip it!
                        if (!Path.GetExtension(formFile.FileName).Equals(".zip", StringComparison.InvariantCultureIgnoreCase))
                        {
                            filePath = this.Zip(filePath, formFile.FileName);
                        }

                        //build return obj
                        var item = new FileEntity();
                        item.Name        = formFile.Name;
                        item.Length      = formFile.Length;
                        item.DateCreated = DateTime.UtcNow;
                        item.StoragePath = filePath;
                        list.Add(item);
                    }
                }
            }

            //save to db
            if (list.Count > 0)
            {
                _context.Files.AddRange(list);
                await _context.SaveChangesAsync(ct);
            }

            return(list);
        }
예제 #6
0
        private async STT.Task <UserEntity> ValidateUser(Guid subClaim, string nameClaim, bool update)
        {
            var user = await _context.Users
                       .Where(u => u.Id == subClaim)
                       .SingleOrDefaultAsync();

            var anyUsers = await _context.Users.AnyAsync();

            if (update)
            {
                if (user == null)
                {
                    user = new UserEntity
                    {
                        Id   = subClaim,
                        Name = nameClaim ?? "Anonymous"
                    };

                    // First user is default SystemAdmin
                    if (!anyUsers)
                    {
                        var systemAdminPermission = await _context.Permissions.Where(p => p.Key == SteamfitterClaimTypes.SystemAdmin.ToString()).FirstOrDefaultAsync();

                        if (systemAdminPermission != null)
                        {
                            user.UserPermissions.Add(new UserPermissionEntity(user.Id, systemAdminPermission.Id));
                        }
                    }

                    _context.Users.Add(user);
                    await _context.SaveChangesAsync();
                }
                else
                {
                    if (nameClaim != null && user.Name != nameClaim)
                    {
                        user.Name = nameClaim;
                        _context.Update(user);
                        await _context.SaveChangesAsync();
                    }
                }
            }

            return(user);
        }
예제 #7
0
        public async Task <ViewModels.DispatchTask> CreateAsync(ViewModels.DispatchTask dispatchTask, CancellationToken ct)
        {
            if (!(await _authorizationService.AuthorizeAsync(_user, null, new ContentDeveloperRequirement())).Succeeded)
            {
                throw new ForbiddenException();
            }
            if (dispatchTask.VmMask != "" && dispatchTask.VmList.Count > 0)
            {
                throw new InvalidOperationException("A DispatchTask cannot have BOTH a VmMask and a VmList!");
            }
            // convert the list of vm guids into a comma separated string and save it in VmMask
            if (dispatchTask.VmList.Count() > 0)
            {
                var vmIdString = "";
                foreach (var vmId in dispatchTask.VmList)
                {
                    vmIdString = vmIdString + vmId + ",";
                }
                dispatchTask.VmMask = vmIdString.Remove(vmIdString.Count() - 1);
            }
            dispatchTask.DateCreated = DateTime.UtcNow;
            dispatchTask.CreatedBy   = _user.GetId();
            dispatchTask.UserId      = _user.GetId();
            var dispatchTaskEntity = Mapper.Map <DispatchTaskEntity>(dispatchTask);

            _context.DispatchTasks.Add(dispatchTaskEntity);
            await _context.SaveChangesAsync(ct);

            return(await GetAsync(dispatchTaskEntity.Id, ct));
        }
        public async STT.Task <SAVM.VmCredential> CreateAsync(SAVM.VmCredential vmCredential, CancellationToken ct)
        {
            if (!(await _authorizationService.AuthorizeAsync(_user, null, new ContentDeveloperRequirement())).Succeeded)
            {
                throw new ForbiddenException();
            }

            if (vmCredential.ScenarioTemplateId == null && vmCredential.ScenarioId == null)
            {
                throw new ArgumentException("A VmCredential MUST be associated to either a Scenario Template or a Scenario.");
            }

            vmCredential.DateCreated = DateTime.UtcNow;
            vmCredential.CreatedBy   = _user.GetId();
            var vmCredentialEntity = _mapper.Map <VmCredentialEntity>(vmCredential);

            _context.VmCredentials.Add(vmCredentialEntity);
            await _context.SaveChangesAsync(ct);

            vmCredential = await GetAsync(vmCredentialEntity.Id, ct);

            return(vmCredential);
        }
예제 #9
0
        public async Task <ViewModels.DispatchTaskResult> CreateAsync(ViewModels.DispatchTaskResult dispatchTaskResult, CancellationToken ct)
        {
            if (!(await _authorizationService.AuthorizeAsync(_user, null, new ContentDeveloperRequirement())).Succeeded)
            {
                throw new ForbiddenException();
            }

            dispatchTaskResult.DateCreated = DateTime.UtcNow;
            dispatchTaskResult.CreatedBy   = _user.GetId();
            var dispatchTaskResultEntity = Mapper.Map <DispatchTaskResultEntity>(dispatchTaskResult);

            //TODO: add permissions
            // var DispatchTaskResultAdminPermission = await _context.Permissions
            //     .Where(p => p.Key == PlayerClaimTypes.DispatchTaskResultAdmin.ToString())
            //     .FirstOrDefaultAsync();

            // if (DispatchTaskResultAdminPermission == null)
            //     throw new EntityNotFoundException<Permission>($"{PlayerClaimTypes.DispatchTaskResultAdmin.ToString()} Permission not found.");

            _context.DispatchTaskResults.Add(dispatchTaskResultEntity);
            await _context.SaveChangesAsync(ct);

            return(await GetAsync(dispatchTaskResultEntity.Id, ct));
        }
예제 #10
0
        public async STT.Task <SAVM.Task> CreateAsync(SAVM.Task task, CancellationToken ct)
        {
            if (!(await _authorizationService.AuthorizeAsync(_user, null, new ContentDeveloperRequirement())).Succeeded)
            {
                throw new ForbiddenException();
            }
            var vmListCount = task.VmList != null ? task.VmList.Count : 0;

            if (vmListCount > 0)
            {
                if (task.VmMask != "")
                {
                    throw new InvalidOperationException("A Task cannot have BOTH a VmMask and a VmList!");
                }
                // convert the list of vm guids into a comma separated string and save it in VmMask
                var vmIdString = "";
                foreach (var vmId in task.VmList)
                {
                    vmIdString = vmIdString + vmId + ",";
                }
                task.VmMask = vmIdString.Remove(vmIdString.Count() - 1);
            }
            if (task.ActionParameters.Keys.Any(key => key == "Moid"))
            {
                task.ActionParameters["Moid"] = "{moid}";
            }
            task.DateCreated      = DateTime.UtcNow;
            task.CreatedBy        = _user.GetId();
            task.UserId           = _user.GetId();
            task.Iterations       = task.Iterations > 0 ? task.Iterations : 1;
            task.CurrentIteration = 0;
            var taskEntity = _mapper.Map <TaskEntity>(task);

            _context.Tasks.Add(taskEntity);
            await _context.SaveChangesAsync(ct);

            task = await GetAsync(taskEntity.Id, ct);

            _engineHub.Clients.All.SendAsync(EngineMethods.TaskCreated, task);

            return(task);
        }
예제 #11
0
        public async STT.Task <ViewModels.Scenario> GetMineAsync(CancellationToken ct)
        {
            if (!(await _authorizationService.AuthorizeAsync(_user, null, new ContentDeveloperRequirement())).Succeeded)
            {
                throw new ForbiddenException();
            }

            var item = await _context.Scenarios.Include(st => st.VmCredentials)
                       .SingleOrDefaultAsync(o => o.Id == _user.GetId(), ct);

            if (item == null)
            {
                var createdDate = DateTime.UtcNow;
                var id          = _user.GetId();
                var name        = _user.Claims.FirstOrDefault(c => c.Type == "name").Value;
                item = new ScenarioEntity()
                {
                    Id           = id,
                    Name         = $"{name} User Scenario",
                    Description  = "Personal Task Builder Scenario",
                    StartDate    = createdDate,
                    EndDate      = createdDate.AddYears(100),
                    Status       = ScenarioStatus.active,
                    OnDemand     = false,
                    DateCreated  = createdDate,
                    DateModified = createdDate,
                    CreatedBy    = id,
                    ModifiedBy   = id
                };
                _context.Scenarios.Add(item);
                await _context.SaveChangesAsync(ct);
            }

            return(_mapper.Map <SAVM.Scenario>(item));
        }