public TaskState(RemoteTask task, TaskState parentState, string message = "Internal Error (xunit runner): No status reported", TaskResult result = TaskResult.Inconclusive) { Task = task; Message = message; Result = result; ParentState = parentState; }
public void Failed(IExample example, Exception exception) { LastResult = TaskResult.Exception; _server.TaskOutput(CurrentTask, "Failed:", TaskOutputType.STDERR); _server.TaskOutput(CurrentTask, exception.ToString(), TaskOutputType.STDERR); _server.TaskFinished(CurrentTask, exception.ToString(), TaskResult.Exception); }
private static void AssertTaskFinishedCalled(FakeRemoteTaskServer.TaskFinishedParameters taskFinishedCall, RemoteTask remoteTask, string message, TaskResult result) { Assert.Equal(remoteTask, taskFinishedCall.RemoteTask); Assert.Equal(message, taskFinishedCall.Message); Assert.Equal(result, taskFinishedCall.Result); }
public RemoteTaskWrapper(RemoteTask remoteTask, IRemoteTaskServer server) { RemoteTask = remoteTask; this.server = server; result = TaskResult.Inconclusive; }
/// <summary> /// Initializes the <see cref="TaskContext"/> /// </summary> /// <param name="associatedData"></param> public TaskContext(ITask task, object associatedData) { Task = task; Result = new TaskResult(); AssociatedData = associatedData; _progress = 0; }
public void EndTarget(IObsoleteTask task, string name, IBounceCommand command, TaskResult result) { if (logOptions.ReportTargetEnd) { if (result == TaskResult.Success) { StdOut.WriteLine("{0} target: {1}", command.PastTense, name); } else { StdErr.WriteLine("failed to {0} target: {1}", command.InfinitiveTense, name); } } }
public void EndTask(IObsoleteTask task, IBounceCommand command, TaskResult result) { if (logOptions.ReportTaskEnd && task.IsLogged && command.IsLogged) { if (result == TaskResult.Success) { StdOut.WriteLine("{0} task: {1}", command.PastTense, task); } else { StdErr.WriteLine("failed to {0} task: {1}", command.InfinitiveTense, task); } } }
public void ScenarioFailed(Scenario scenario, string successPart, string failedPart, string message) { Output(successPart + " [" + failedPart + "] -- failed"); Output("----------"); Output(message); _server.TaskException(_remoteTask, new[] {new TaskException("StorEvil failure", message, ""),}); Result = TaskResult.Exception; }
internal static TaskResult AddDirectoyByNameToZip(Task task, TaskResult result) { var zip = (ZipFile)Get(task, 0, result); foreach (var value in ((List<object>)Get(task, 1, result))) { zip.AddDirectoryByName(value.ToString()); } return Next(task, result); }
public StorEvilTaskRunner(IRemoteTaskServer server) : base(server) { Logger.Log("StorEvilTaskRunner constructed"); server.ClientMessage("TaskRunner starting"); //_isDebug = server.GetConfiguration().IsInInternalDebug; _result = TaskResult.Success; }
public void TaskCompleted() { TaskResult result = new TaskResult(); result.gridPosition = gridPosition; result.completionTime = Time.time - creationTime; result.TimeoutTime = LifeTime; result.completionPercentage = repetitionNr / TotalReps; GameManager.Instance.TaskCompleted(result); }
public void CouldNotInterpret(Scenario scenario, string line) { Output("Could not interpret:\r\n" + line); var suggestion = new ImplementationHelper().Suggest(line); Output("You could try the following:"); Output(suggestion); Result = TaskResult.Skipped; }
public void TaskFinished(RemoteTask remoteTask, string message, TaskResult result, TimeSpan duration) { Debug.Assert(result != TaskResult.Inconclusive); clientController.TaskFinished(remoteTask); if (result == TaskResult.Skipped) server.TaskExplain(remoteTask, message); if (duration >= TimeSpan.Zero) server.TaskDuration(remoteTask, duration); server.TaskFinished(remoteTask, message, result); }
public override void ExecuteRecursive(TaskExecutionNode node) { try { _result = ExecuteRecursiveInternal(node).Status; } catch (Exception ex) { Logger.Log(ex.ToString()); } }
public void SetMethodTasks(ICollection<XunitTestMethodTask> value) { if (value == null || value.Count == 0) { classResult = TaskResult.Inconclusive; methodTasks = new Dictionary<string, XunitTestMethodTask>(); } else { methodTasks = value.ToDictionary(x => x.ShortName); } }
public override TaskResult Execute(TaskExecutionNode node) { if (node.RemoteTask is RunScenarioTask) { var result = ExecuteScenario(node); if (result.Status != TaskResult.Success) _result = result.Status; return result.Status; } return TaskResult.Success; }
public override void ExecuteRecursive(TaskExecutionNode node) { try { Logger.Log("ExecuteRecursive"); Logger.Log(node.RemoteTask.RunnerID); _result = ExecuteRecursiveInternal(node).Status; } catch (Exception ex) { Logger.Log(ex.ToString()); } }
// Called when a class failure is encountered (i.e., when a fixture from IUseFixture throws an // exception during construction or System.IDisposable.Dispose) // Called after all tests within the class have been started and finished public bool ClassFailed(string className, string exceptionType, string message, string stackTrace) { var methodMessage = string.Format("Class failed in {0}", className); foreach (var methodTask in methodTasks.Values) { server.TaskException(methodTask, new[] { new TaskException(null, methodMessage, null) } ); server.TaskFinished(methodTask, methodMessage, TaskResult.Error); } server.TaskException(classTask, ExceptionConverter.ConvertExceptions(exceptionType, message, stackTrace, out classFinishMessage)); classResult = TaskResult.Exception; // Let's carry on running tests - I guess if it were a catastrophic error, we could chose to abort return true; }
public void Failed(TaskException[] exceptions, string exceptionMessage, string childMessage = null) { if (childMessage != null) { Reset(); var childExceptions = new[] { new TaskException(null, childMessage, null) }; foreach (var child in children ?? EmptyList<RemoteTaskWrapper>.InstanceList) child.Error(childExceptions, childMessage); } if (result == TaskResult.Inconclusive) { result = TaskResult.Exception; message = exceptionMessage; server.TaskException(RemoteTask, exceptions); } }
public void Finished(decimal durationInSeconds = 0, bool childTestsFailed = false) { // Result is based on child tasks if (result == TaskResult.Inconclusive) { result = childTestsFailed ? TaskResult.Exception : TaskResult.Success; message = childTestsFailed ? "One or more child tests failed" : string.Empty; } // Only finish once - so a test can share a test case's task if (!finished) { var duration = TimeSpan.FromSeconds((double) durationInSeconds); if (duration >= TimeSpan.Zero) server.TaskDuration(RemoteTask, duration); server.TaskFinished(RemoteTask, message, result); } finished = true; }
// Merge 2 TaskResults get the worst result. // Succeeded -> SucceededWithIssues -> Failed/Canceled/Skipped/Abandoned // SucceededWithIssues -> Failed/Canceled/Skipped/Abandoned // Failed -> Failed // Canceled -> Canceled // Skipped -> Skipped // Abandoned -> Abandoned public static TaskResult MergeTaskResults(TaskResult? currentResult, TaskResult comingResult) { if (currentResult == null) { return comingResult; } // current result is Failed/Canceled/Skip/Abandoned if (currentResult >= TaskResult.Failed) { return currentResult.Value; } // comming result is bad than current result if (comingResult >= currentResult) { return comingResult; } return currentResult.Value; }
public override IEnumerator GetGameObjectAsync(IOut <GameObject> gameObject) { TaskResult <GameObject> task = new TaskResult <GameObject>(); yield return(base.GetGameObjectAsync(task)); GameObject gObj = task.Get(); if (texture != null) { // Set the custom texture SkinnedMeshRenderer skinnedMeshRenderer = gObj.GetComponentInChildren <SkinnedMeshRenderer>(); skinnedMeshRenderer.material.mainTexture = texture; } // Change size Vector3 scale = gObj.transform.localScale; const float factor = 1.25f; gObj.transform.localScale = new Vector3(scale.x * factor, scale.y * factor, scale.z * factor); gameObject.Set(gObj); yield break; }
public async Task ExecuteUnderLockAsyncOfT_AvoidsOverlappingActions() { var firstEntered = new AsyncManualResetEvent(); var firstRelease = new AsyncManualResetEvent(); var secondEntered = new AsyncManualResetEvent(); var instance = CreateInstance(); Task firstAction() => instance.ExecuteUnderLockAsync(async(ct) => { firstEntered.Set(); await firstRelease; return(string.Empty); }, CancellationToken.None); Task secondAction() => Task.Run(() => instance.ExecuteUnderLockAsync((ct) => { secondEntered.Set(); return(TaskResult.Null <string>()); }, CancellationToken.None)); await AssertNoOverlap(firstAction, secondAction, firstEntered, firstRelease, secondEntered); }
/// <summary> /// Initializes the user using a valid user token /// </summary> public static async Task <TaskResult> InitializeUser(string token, LocalStorageService storage, IMapper mapper) { string response = await Http.GetStringAsync($"User/GetUserWithToken?token={token}"); TaskResult <User> result = JsonConvert.DeserializeObject <TaskResult <User> >(response); if (result.Success) { User = result.Data; UserSecretToken = token; Console.WriteLine($"Initialized user {User.Username}"); // Store token for future use await StoreToken(storage); // Refresh user planet membership await RefreshPlanetsAsync(mapper); return(new TaskResult(true, "Initialized user successfully!")); } return(new TaskResult(false, "An error occured retrieving the user.")); }
public async Task <TaskResult> SetRedisKey(string key, string value) { TaskResult taskResult = new TaskResult(); try { ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("10.0.75.1:6379"); int databaseNumber = 0; object asyncState = taskResult; IDatabase db = redis.GetDatabase(databaseNumber, asyncState); taskResult.Succeeded = await db.StringSetAsync(key, value); await db.KeyExpireAsync(key, DateTime.Now.AddMinutes(10)); return(taskResult); } catch (Exception ex) { taskResult.Exception = ex; taskResult.Message = "Erreur lors de l'enregitrement des données"; taskResult.Succeeded = false; return(taskResult); } }
public TaskResult Execute(TaskInstance taskInstance) { var taskResult = new TaskResult(); try { StartActiveNotifier(taskInstance.Id); TaskUtilities.UpdateTaskInstanceStatus(taskInstance.Id, _repositoryFactory, TaskInstanceStatues.InProgress, null); int instanceConfigurationId = Convert.ToInt16(taskInstance.Parameters["InstanceConfigurationId"]); var newAutoBook = new AutoBookDomainObject() { TimeCreated = DateTime.UtcNow, Locked = false, Status = AutoBookStatuses.Provisioning, InstanceConfigurationId = instanceConfigurationId }; _autoBooks.Create(newAutoBook); TaskUtilities.UpdateTaskInstanceStatus(taskInstance.Id, _repositoryFactory, TaskInstanceStatues.CompletedSuccess, DateTime.UtcNow); taskResult.Status = TaskInstanceStatues.CompletedSuccess; } catch (Exception exception) { TaskUtilities.UpdateTaskInstanceStatus(taskInstance.Id, _repositoryFactory, TaskInstanceStatues.CompletedError, DateTime.UtcNow); taskResult.Status = TaskInstanceStatues.CompletedError; taskResult.Exception = exception; } finally { StopActiveNotifier(); } return(taskResult); }
public void Execute(ExecutionEventListener eventListener) { TaskExecutionContext context = new TaskExecutionContext(); context.LastTaskResult = null; context.Events = eventListener; eventListener.Log(ExecutionEventListener.LogLevel.Info, "Main", "Start", "Reflow engine started execution"); eventListener.Log(ExecutionEventListener.LogLevel.Verbose, "Main", "Start", string.Format("There are {0} task(s) to be executed.", this.Tasks.Count)); eventListener.Log(ExecutionEventListener.LogLevel.Debug, "Main", "Start", "Starting tasks ..."); // Lots of TODO: here foreach (ITask task in this.Tasks) { eventListener.Log(ExecutionEventListener.LogLevel.Info, task.Name, "Begin", string.Format("Starting task {0}... ", task.Name)); context.Current = task; TaskResult result = task.Execute(context); eventListener.Log(ExecutionEventListener.LogLevel.Info, task.Name, "End", string.Format("Task {0} Complete. ", task.Name)); context.LastTaskResult = result; } context.Current = null; eventListener.Log(ExecutionEventListener.LogLevel.Info, "Main", "End", "Reflow engine execution complete"); }
public async Task <ActionResult <CertificateTypeViewModel> > RemoveCertificateTypeAsync( Guid id) { if (id == Guid.Empty) { return(BadRequest("No valid id.")); } try { CertificateType oldCertificateType = (await certificateService.GetCertificateTypeAsync(id)).Data; if (oldCertificateType == null) { return(NotFound("CertificateType not found")); } TaskResult <CertificateType> result = await certificateService.RemoveCertificateTypeAsync(oldCertificateType); if (!result.Succeeded) { return(UnprocessableEntity(new ErrorViewModel { Type = Type.Error, Message = result.Message })); } return(Ok(CertificateTypeViewModel.CreateVm(result.Data))); } catch (Exception ex) { string message = GetType().Name + "Error in " + nameof(RemoveCertificateTypeAsync); logger.LogError(ex, message); return(UnprocessableEntity(new ErrorViewModel { Type = Type.Error, Message = message })); } }
/// <summary> /// /// </summary> /// <returns></returns> public TaskResult Process() { _importHistoryRepository.Add(new ImportHistory("broker-transactions", "broker.service")); var importTrackers = _importTrackerRepository .GetAll() .GetData <List <ImportTracker> >() .Where(x => x.Status != "Retry"); var imports = _importRepository .GetAll() .Result .GetData <List <Import> >() .Where(import => !importTrackers.Contains(new ImportTracker(import.Symbol))) .OrderBy(i => i.Symbol) .ToList(); var taskResult = new TaskResult { IsSuccessful = true }; taskResult.SetData(imports); return(taskResult); }
public static ITaskResult ToTaskResult(this Task task) { var status = task.Status; if (status != TaskStatus.RanToCompletion && status != TaskStatus.Canceled && status != TaskStatus.Faulted) { throw new ArgumentException($"The task is not completed and is in '{status}' state.", nameof(task)); } var exception = (task.Exception is AggregateException aggregateException && aggregateException.InnerExceptions?.Count == 1) ? aggregateException.InnerException : task.Exception; var valueType = task.GetResultType(); if (valueType == null || valueType == typeof(void) || valueType == TaskAccessor.VoidTaskResultType || valueType == typeof(object)) { return(new TaskResult { Value = status == TaskStatus.RanToCompletion ? task.GetResult() : null, Exception = status == TaskStatus.Faulted ? exception : null, IsCanceled = status == TaskStatus.Canceled }); } else { return(TaskResult.Create( valueType, status == TaskStatus.RanToCompletion ? task.GetResult() : null, status == TaskStatus.Faulted ? exception : null, status == TaskStatus.Canceled)); } }
/// <summary> /// Bulks the async. /// </summary> /// <returns>The async.</returns> public async Task <Result> GetAll() { var queryViewRequest = new QueryViewRequest("query", "all") .Configure(c => c.IncludeDocs(true)); var response = await Views.QueryAsync <Import>(queryViewRequest); var imports = response .Rows .Select(row => row.Value) // iad to resort to this, freakin framework works finicky .ToList(); var result = new TaskResult { IsSuccessful = true, Messages = new List <string> { response.Error, response.Reason } } .SetData(imports); return(result); }
public Task <LoadBalancedConnection> GetConnection( [NotNull] string database, [CanBeNull] string connectionName = null, [CanBeNull] bool?ensureIdentical = null, CancellationToken cancellationToken = default(CancellationToken)) { if (database == null) { throw new ArgumentNullException("database"); } DatabaseElement db = Databases[database]; if ((db == null) || (!db.Enabled)) { return(TaskResult <LoadBalancedConnection> .FromException( new LoggingException( () => Resources.DatabaseConfiguration_GetSqlProgram_DatabaseIdNotFound, database))); } return(db.GetConnection(connectionName, ensureIdentical, cancellationToken)); }
public override Task <TaskResult> Process(TaskInfo task) { if (!(task is DecodeUrlTaskInfo)) { throw new ArgumentException($"Expected DecodeUrlTaskInfo but passed {task.GetType().Name}"); } var result = new TaskResult(false); var taskInfo = (DecodeUrlTaskInfo)task; var cacheParam = taskInfo.CacheKey; if (string.IsNullOrEmpty(cacheParam)) { Info("Cache key is missing."); return(result.Failed()); } //if EncodedUrl is specified, use that as the input url, otherwise use the current url var url = taskInfo.Url ?? CurrentBrowser.Driver.Url; var decode = HttpUtility.UrlDecode(url); result.Success = decode != null != task.IsNegated; Storage.Cache.Add(cacheParam, decode); return(result.Result()); }
/// <summary> /// Sleep for a specified number of milliseconds /// </summary> public override async Task <TaskResult> ExecuteTask(TaskParameters parameters) { var result = new TaskResult(); try { // Read and validate millisecond delay value: var millisecondsDelay = parameters.Get <int>("MillisecondsDelay", int.TryParse) ?? 0; if (millisecondsDelay <= 0) { throw new ArgumentException("Missing or invalid MillisecondsDelay"); } // Await specified delay, and return success: await Task.Delay(millisecondsDelay); result.Success = true; } catch (Exception ex) { result.AddException(ex); } return(result); }
public TaskResult <UserDetail> Validate(UserDetail user) { TaskResult <UserDetail> result; try { var _user = _userRepository.GetSingle((x) => x.UserName == user.USerName && x.Password == user.Password); result = new TaskResult <UserDetail> { state = StatusState.DoneState, Data = new UserDetail { Id = _user.Id, USerName = _user.UserName } }; } catch (Exception e) { Logger.Instance.LogException(e); result = new TaskResult <UserDetail> { state = StatusState.CancelState, Data = null }; } return(result); }
/// <summary> /// Process the specified t. /// </summary> /// <returns>The process.</returns> /// <param name="t">T.</param> public async Task <Result> Process(List <Transaction> transactions) { //collect new created transactions var newTransactions = new List <Transaction>(); foreach (var transaction in transactions) { if (transaction.PositionId == null) { transaction.PositionId = "0"; } var result = await _transactionRepository.PutAsync(transaction) as TaskResult; if (result.IsSuccessful.Value && result.StatusCode.ToLower() == "created") { newTransactions.Add(result.GetData <Transaction>()); } } var taskResult = new TaskResult { IsSuccessful = true }.SetData(transactions); return(taskResult); }
public TaskResult <bool> DeleteById(int id) { TaskResult <bool> result = null; try { if (id != 0) { User findedItem = _userRepository.GetSingle(a => a.Id == id); if (findedItem != null) { _userRepository.Delete(findedItem); _userRepository.SaveChanges(); result = new TaskResult <bool> { Data = true }; } else { throw new Exception(); } } else { throw new Exception(); } } catch (Exception e) { Logger.Instance.LogException(e); result = new TaskResult <bool> { Data = false }; } return(result); }
public Task <DatabaseSchema> GetSchema( [NotNull] string database, [CanBeNull] string connectionName = null, bool forceReload = false, CancellationToken cancellationToken = default(CancellationToken)) { if (database == null) { throw new ArgumentNullException("database"); } DatabaseElement db = Databases[database]; if ((db == null) || (!db.Enabled)) { return(TaskResult <DatabaseSchema> .FromException( new LoggingException( () => Resources.DatabaseConfiguration_GetSqlProgram_DatabaseIdNotFound, database))); } return(db.GetSchema(connectionName, forceReload, cancellationToken)); }
IEnumerator SpawnAsync() { var stringToLog = spawnInfo.spawnType == SpawnInfo.SpawnType.ClassId ? spawnInfo.classId : spawnInfo.techType.ToString(); var task = new TaskResult <GameObject>(); yield return(GetPrefabAsync(task)); if (task.Get() is null) { Logger.Error($"no prefab found for {stringToLog}; process for Coordinated Spawn canceled."); Destroy(gameObject); } var obj = UWE.Utils.InstantiateDeactivated(task.Get(), spawnInfo.spawnPosition, spawnInfo.rotation); LargeWorld.main.streamer.cellManager.RegisterEntity(obj); obj.SetActive(true); Destroy(gameObject); }
/// <summary> /// Returns the primary channel of the planet /// </summary> public async Task <ClientPlanetChatChannel> GetPrimaryChannelAsync(IMapper mapper) { string json = await ClientUserManager.Http.GetStringAsync($"Planet/GetPrimaryChannel?planetid={Id}" + $"&userid={ClientUserManager.User.Id}" + $"&token={ClientUserManager.UserSecretToken}"); TaskResult <PlanetChatChannel> channelResult = JsonConvert.DeserializeObject <TaskResult <PlanetChatChannel> >(json); if (channelResult == null) { Console.WriteLine($"Failed to retrieve primary channel for planet {Id}."); return(null); } if (!channelResult.Success) { Console.WriteLine($"Failed to retrieve primary channel for planet {Id}: {channelResult.Message}"); } // Map to new ClientPlanetChatChannel channel = mapper.Map <ClientPlanetChatChannel>(channelResult.Data); return(channel); }
public override Task <TaskResult> Process(TaskInfo task) { if (!(task is NavigateTaskInfo)) { throw new ArgumentException($"Expected NavigateTaskInfo but passed {task.GetType().Name}"); } var result = new TaskResult(false); var taskInfo = (NavigateTaskInfo)task; var url = Utilities.ConfigureUrl(taskInfo.Url); if (string.IsNullOrEmpty(url)) { return(result.Failed()); } Info($"Launching url '{url}'"); Storage.Summary.LogData[SummaryFields.LaunchUrl] = url; CurrentBrowser.Driver.Navigate().GoToUrl(url); // Adding a wait after redirect to resolve page lookup and logs not found issue Thread.Sleep(2000); return(result.Success()); }
/// <summary> /// Delete the specified session, name and key. /// </summary> /// <returns>The delete.</returns> /// <param name="session">Session.</param> /// <param name="name">Name.</param> /// <param name="key">Key.</param> public async Task <TaskResult <bool> > Delete(Session session, StoreKey name, string key) { Guard.Argument(session, nameof(session)).NotNull(); Guard.Argument(name, nameof(name)).In(new StoreKey[] { StoreKey.AddressKey, StoreKey.HashKey, StoreKey.PublicKey, StoreKey.SecretKey, StoreKey.TransactionIdKey }); Guard.Argument(key, nameof(key)).NotNull().NotEmpty(); using (await deleteMutex.LockAsync()) { try { var vault = await vaultServiceClient.GetDataAsync(session.Identifier, session.MasterKey, $"wallets/{session.Identifier.ToUnSecureString()}/wallet"); if (vault.Data.TryGetValue(store.ToString(), out object d)) { var wallet = (JArray)d; var jToken = wallet.FirstOrDefault(x => x.Value <string>(name.ToString()) == key); if (jToken != null) { wallet.RemoveAt(wallet.IndexOf(jToken)); await vaultServiceClient.SaveDataAsync(session.Identifier, session.MasterKey, $"wallets/{session.Identifier.ToUnSecureString()}/wallet", vault.Data); } } } catch (Exception ex) { logger.LogError(ex.Message); return(TaskResult <bool> .CreateFailure(ex)); } } return(TaskResult <bool> .CreateSuccess(true)); }
public IEnumerator <TaskStatus> FooProc(MentalTask bwxTask, Atom y) { Task _bwxTask = null; Context _bwxContext = null; Message _bwxMsg; Clause _bwxClause = null; Atom _bwxSubject = null; TaskResult _bwxResult = null; Begin(bwxTask); { if (bwxTask.Context.Exists(y, Ent_likes, Ent_RockMusic)) { if (bwxTask.Context.Exists(Ent_Bob, Ent_knows, y)) { { _bwxMsg = new Message(MessageKind.Add, null, null, new Clause(Ent_Belief, Ent_Bob, Ent_likes, y)); Post(bwxTask.Process, _bwxMsg); } } } } yield return(Succeed(bwxTask.Process, bwxTask.Message)); }
public TaskResult Run() { if (!Monitor.TryEnter(ExecutionLock, 1)) { var m = string.Format("{0} - skipped due to concurrent execution", jobName); Log.Info(m); return(TaskResult.Warning(m)); } try { return(innerTask.Run()); } catch (Exception ex) { var m = string.Format("{0} - stopped with an exception: {1}", jobName, ex.Message); Log.Error(m, ex); throw; } finally { Monitor.Exit(ExecutionLock); } }
public JobCompletedEvent( Guid jobId, TaskResult result) : this(0, jobId, result) { }
/// <summary> /// Starts a new thread with the given task. /// </summary> /// <param name="task"> /// The task. /// </param> private void ExecuteTaskAction(Task task) { try { Func <Dictionary <string, string> > actionToCall; lock (task) { actionToCall = task.Action; task.TaskData.Started = DateTime.Now; using (var db = new LibiadaWebEntities()) { CalculationTask databaseTask = db.CalculationTask.Single(t => t.Id == task.TaskData.Id); databaseTask.Started = DateTime.Now; databaseTask.Status = TaskState.InProgress; db.Entry(databaseTask).State = EntityState.Modified; db.SaveChanges(); } signalrHub.Send(TaskEvent.ChangeStatus, task.TaskData); } // executing action Dictionary <string, string> result = actionToCall(); lock (task) { task.TaskData.Completed = DateTime.Now; task.TaskData.ExecutionTime = task.TaskData.Completed - task.TaskData.Started; TaskResult[] results = result.Select(r => new TaskResult { Key = r.Key, Value = r.Value, TaskId = task.TaskData.Id }).ToArray(); task.TaskData.TaskState = TaskState.Completed; using (var db = new LibiadaWebEntities()) { db.TaskResult.AddRange(results); CalculationTask databaseTask = db.CalculationTask.Single(t => (t.Id == task.TaskData.Id)); databaseTask.Completed = DateTime.Now; databaseTask.Status = TaskState.Completed; db.Entry(databaseTask).State = EntityState.Modified; db.SaveChanges(); } signalrHub.Send(TaskEvent.ChangeStatus, task.TaskData); } } catch (ThreadAbortException) { // TODO: implement an exception handling/logging } catch (Exception e) { string errorMessage = e.Message; string stackTrace = e.StackTrace; while (e.InnerException != null) { e = e.InnerException; errorMessage += $"{Environment.NewLine} {e.Message}"; } lock (task) { var taskData = task.TaskData; taskData.Completed = DateTime.Now; taskData.ExecutionTime = taskData.Completed - taskData.Started; taskData.TaskState = TaskState.Error; var error = new { Message = errorMessage, StackTrace = stackTrace }; TaskResult taskResult = new TaskResult { Key = "Error", Value = JsonConvert.SerializeObject(error), TaskId = taskData.Id }; using (var db = new LibiadaWebEntities()) { db.TaskResult.Add(taskResult); CalculationTask databaseTask = db.CalculationTask.Single(t => (t.Id == taskData.Id)); databaseTask.Completed = DateTime.Now; databaseTask.Status = TaskState.Error; db.Entry(databaseTask).State = EntityState.Modified; db.SaveChanges(); } signalrHub.Send(TaskEvent.ChangeStatus, taskData); } } finally { ManageTasks(); } }
public async Task <int> LocalRunAsync(CommandSettings command, CancellationToken token) { Trace.Info(nameof(LocalRunAsync)); // Warn preview. _term.WriteLine("This command is currently in preview. The interface and behavior will change in a future version."); if (!command.Unattended) { _term.WriteLine("Press Enter to continue."); _term.ReadLine(); } HostContext.RunMode = RunMode.Local; // Resolve the YAML file path. string ymlFile = command.GetYml(); if (string.IsNullOrEmpty(ymlFile)) { string[] ymlFiles = Directory.GetFiles(Directory.GetCurrentDirectory()) .Where((string filePath) => { return(filePath.EndsWith(".yml", IOUtil.FilePathStringComparison)); }) .ToArray(); if (ymlFiles.Length > 1) { throw new Exception($"More than one .yml file exists in the current directory. Specify which file to use via the --'{Constants.Agent.CommandLine.Args.Yml}' command line argument."); } ymlFile = ymlFiles.FirstOrDefault(); } if (string.IsNullOrEmpty(ymlFile)) { throw new Exception($"Unable to find a .yml file in the current directory. Specify which file to use via the --'{Constants.Agent.CommandLine.Args.Yml}' command line argument."); } // Load the YAML file. var parseOptions = new ParseOptions { MaxFiles = 10, MustacheEvaluationMaxResultLength = 512 * 1024, // 512k string length MustacheEvaluationTimeout = TimeSpan.FromSeconds(10), MustacheMaxDepth = 5, }; var pipelineParser = new PipelineParser(new PipelineTraceWriter(), new PipelineFileProvider(), parseOptions); if (command.WhatIf) { pipelineParser.DeserializeAndSerialize( defaultRoot: Directory.GetCurrentDirectory(), path: ymlFile, mustacheContext: null, cancellationToken: HostContext.AgentShutdownToken); return(Constants.Agent.ReturnCode.Success); } YamlContracts.Process process = pipelineParser.LoadInternal( defaultRoot: Directory.GetCurrentDirectory(), path: ymlFile, mustacheContext: null, cancellationToken: HostContext.AgentShutdownToken); ArgUtil.NotNull(process, nameof(process)); // Verify the current directory is the root of a git repo. string repoDirectory = Directory.GetCurrentDirectory(); if (!Directory.Exists(Path.Combine(repoDirectory, ".git"))) { throw new Exception("Unable to run the build locally. The command must be executed from the root directory of a local git repository."); } // Verify at least one phase was found. if (process.Phases == null || process.Phases.Count == 0) { throw new Exception($"No phases or steps were discovered from the file: '{ymlFile}'"); } // Filter the phases. string phaseName = command.GetPhase(); if (!string.IsNullOrEmpty(phaseName)) { process.Phases = process.Phases .Cast <YamlContracts.Phase>() .Where(x => string.Equals(x.Name, phaseName, StringComparison.OrdinalIgnoreCase)) .Cast <YamlContracts.IPhase>() .ToList(); if (process.Phases.Count == 0) { throw new Exception($"Phase '{phaseName}' not found."); } } // Verify a phase was specified if more than one phase was found. if (process.Phases.Count > 1) { throw new Exception($"More than one phase was discovered. Use the --{Constants.Agent.CommandLine.Args.Phase} argument to specify a phase."); } // Get the matrix. var phase = process.Phases[0] as YamlContracts.Phase; var queueTarget = phase.Target as QueueTarget; // Filter to a specific matrix. string matrixName = command.GetMatrix(); if (!string.IsNullOrEmpty(matrixName)) { if (queueTarget?.Matrix != null) { queueTarget.Matrix = queueTarget.Matrix.Keys .Where(x => string.Equals(x, matrixName, StringComparison.OrdinalIgnoreCase)) .ToDictionary(keySelector: x => x, elementSelector: x => queueTarget.Matrix[x]); } if (queueTarget?.Matrix == null || queueTarget.Matrix.Count == 0) { throw new Exception($"Job configuration matrix '{matrixName}' not found."); } } // Verify a matrix was specified if more than one matrix was found. if (queueTarget?.Matrix != null && queueTarget.Matrix.Count > 1) { throw new Exception($"More than one job configuration matrix was discovered. Use the --{Constants.Agent.CommandLine.Args.Matrix} argument to specify a matrix."); } // Get the URL - required if missing tasks. string url = command.GetUrl(suppressPromptIfEmpty: true); if (string.IsNullOrEmpty(url)) { if (!TestAllTasksCached(process, token)) { url = command.GetUrl(suppressPromptIfEmpty: false); } } if (!string.IsNullOrEmpty(url)) { // Initialize and store the HTTP client. var credentialManager = HostContext.GetService <ICredentialManager>(); // Get the auth type. On premise defaults to negotiate (Kerberos with fallback to NTLM). // Hosted defaults to PAT authentication. string defaultAuthType = UrlUtil.IsHosted(url) ? Constants.Configuration.PAT : (Constants.Agent.Platform == Constants.OSPlatform.Windows ? Constants.Configuration.Integrated : Constants.Configuration.Negotiate); string authType = command.GetAuth(defaultValue: defaultAuthType); ICredentialProvider provider = credentialManager.GetCredentialProvider(authType); provider.EnsureCredential(HostContext, command, url); _taskStore.HttpClient = new TaskAgentHttpClient(new Uri(url), provider.GetVssCredentials(HostContext)); } var configStore = HostContext.GetService <IConfigurationStore>(); AgentSettings settings = configStore.GetSettings(); // Create job message. JobInfo job = (await ConvertToJobMessagesAsync(process, repoDirectory, token)).Single(); IJobDispatcher jobDispatcher = null; try { jobDispatcher = HostContext.CreateService <IJobDispatcher>(); job.RequestMessage.Environment.Variables[Constants.Variables.Agent.RunMode] = RunMode.Local.ToString(); jobDispatcher.Run(job.RequestMessage); Task jobDispatch = jobDispatcher.WaitAsync(token); if (!Task.WaitAll(new[] { jobDispatch }, job.Timeout)) { jobDispatcher.Cancel(job.CancelMessage); // Finish waiting on the job dispatch task. The call to jobDispatcher.WaitAsync dequeues // the job dispatch task. In the cancel flow, we need to continue awaiting the task instance // (queue is now empty). await jobDispatch; } // Translate the job result to an agent return code. TaskResult jobResult = jobDispatcher.GetLocalRunJobResult(job.RequestMessage); switch (jobResult) { case TaskResult.Succeeded: case TaskResult.SucceededWithIssues: return(Constants.Agent.ReturnCode.Success); default: return(Constants.Agent.ReturnCode.TerminatedError); } } finally { if (jobDispatcher != null) { await jobDispatcher.ShutdownAsync(); } } }
private async Task <TaskResult> CompleteJobAsync(IJobServer jobServer, IExecutionContext jobContext, AgentJobRequestMessage message, TaskResult?taskResult = null) { // Clean TEMP. _tempDirectoryManager?.CleanupTempDirectory(jobContext); jobContext.Section(StringUtil.Loc("StepFinishing", message.JobName)); TaskResult result = jobContext.Complete(taskResult); try { await ShutdownQueue(throwOnFailure : true); } catch (Exception ex) { Trace.Error($"Caught exception from {nameof(JobServerQueue)}.{nameof(_jobServerQueue.ShutdownAsync)}"); Trace.Error("This indicate a failure during publish output variables. Fail the job to prevent unexpected job outputs."); Trace.Error(ex); result = TaskResultUtil.MergeTaskResults(result, TaskResult.Failed); } if (!jobContext.Features.HasFlag(PlanFeatures.JobCompletedPlanEvent)) { Trace.Info($"Skip raise job completed event call from worker because Plan version is {message.Plan.Version}"); return(result); } Trace.Info("Raising job completed event."); var jobCompletedEvent = new JobCompletedEvent(message.RequestId, message.JobId, result); var completeJobRetryLimit = 5; var exceptions = new List <Exception>(); while (completeJobRetryLimit-- > 0) { try { await jobServer.RaisePlanEventAsync(message.Plan.ScopeIdentifier, message.Plan.PlanType, message.Plan.PlanId, jobCompletedEvent, default(CancellationToken)); return(result); } catch (TaskOrchestrationPlanNotFoundException ex) { Trace.Error($"TaskOrchestrationPlanNotFoundException received, while attempting to raise JobCompletedEvent for job {message.JobId}."); Trace.Error(ex); return(TaskResult.Failed); } catch (TaskOrchestrationPlanSecurityException ex) { Trace.Error($"TaskOrchestrationPlanSecurityException received, while attempting to raise JobCompletedEvent for job {message.JobId}."); Trace.Error(ex); return(TaskResult.Failed); } catch (Exception ex) { Trace.Error($"Catch exception while attempting to raise JobCompletedEvent for job {message.JobId}, job request {message.RequestId}."); Trace.Error(ex); exceptions.Add(ex); } // delay 5 seconds before next retry. await Task.Delay(TimeSpan.FromSeconds(5)); } // rethrow exceptions from all attempts. throw new AggregateException(exceptions); }
public abstract void CompleteTask(TaskResult result);
/// <summary> /// Initializes a new instance of the DateTimeResult class /// with the specified Microsoft.Phone.Tasks.TaskResult. /// </summary> /// <param name="taskResult">Associated Microsoft.Phone.Tasks.TaskResult</param> public DateTimeResult(TaskResult taskResult) : base(taskResult) { }
internal static TaskResult TaskStop(Task task, TaskResult result) { Util.Running = false; return Next(task, result); }
public void Start() { while (true) { if (State.ExpirationDate.HasValue) { int result = DateTime.Compare(DateTime.Today, State.ExpirationDate.Value); if (result > 0) { #if DEBUG Logging.Write("TransportService", "Payload Expired. Exiting."); #endif Environment.Exit(0); } } #if DEBUG Logging.Write("TransportService", "Starting Loop.."); Logging.Write("TransportService", "Clearing Completed Tasks.."); #endif foreach (RunningTask task in State.RunningTasks.ToList()) { if (task.Task.IsFaulted) { TaskResult result = new TaskResult(); result.TaskName = task.TaskName; result.Success = false; result.Complete = true; if (String.IsNullOrEmpty(task.Task.Exception.InnerException.Message)) { result.Message = "Task encountered an error, but no error message is available"; } else { result.Message = task.Task.Exception.InnerException.Message; } State.ResultQueue.Add(result); } if (task.Task.IsCompleted) { State.RunningTasks.Remove(task); } } string message = ""; string response = ""; if (!String.IsNullOrEmpty(State.Name)) { message = State.CryptoService.CreateAgentMessage(); response = PrimaryTransport.Beacon(State.Name, message); } else { message = State.CryptoService.CreateStagingMessage(); response = PrimaryTransport.Stage(State.PayloadName, State.StagingId, message); } #if DEBUG Logging.Write("TransportService", $"Got response: {response.ToString()}"); #endif if (response == "ERROR") { Attempts++; if (Attempts > State.MaxAttempts) { Environment.Exit(0); } } else { if (String.IsNullOrEmpty(response)) { #if DEBUG Logging.Write("TransportService", "Empty message recieved"); #endif } else { #if DEBUG Logging.Write("TransportService", "Announcing Message.."); #endif OnMessageRecieved(this, new MessageRecievedArgs(response)); } } double sleep = State.Sleep; // Here we account for jitter if (State.Jitter > 0 && State.Jitter <= 1) { double offset = State.Sleep * State.Jitter; Random random = new Random(); double result = random.NextDouble() * (offset - (offset * -1)) + (offset * -1); sleep = sleep + result; } sleep = (sleep * 1000); #if DEBUG Logging.Write("TransportService", $"Sleeping for {Convert.ToInt32(sleep)} milliseconds"); #endif Thread.Sleep(Convert.ToInt32(sleep)); } }
public void EndTask(IObsoleteTask task, IBounceCommand command, TaskResult result) { output.WriteLine(TeamCityFormatter.FormatTeamCityMessage("progressFinish", task.SmallDescription)); }
public void EndTarget(IObsoleteTask task, string name, IBounceCommand command, TaskResult result) { output.WriteLine(TeamCityFormatter.FormatTeamCityMessageWithFields("buildStatus", "status", result == TaskResult.Success? "SUCCESS": "FAILURE")); output.WriteLine(TeamCityFormatter.FormatTeamCityMessage("progressFinish", name)); }
internal static TaskResult WriteIntoFile(Task task, TaskResult result) { File.AppendAllText(Get(task, 0, result).ToString(), Get(task, 1, result).ToString()); return Next(task, result); }
/// <summary> /// Initializes a new instance of the AudioResult class /// with the specified Microsoft.Phone.Tasks.TaskResult. /// </summary> /// <param name="taskResult">Associated Microsoft.Phone.Tasks.TaskResult</param> public AudioResult(TaskResult taskResult) : base(taskResult) { }
/// <summary> /// Initializes a new instance of the VideoResult class /// with the specified Microsoft.Phone.Tasks.TaskResult. /// </summary> /// <param name="taskResult">Associated Microsoft.Phone.Tasks.TaskResult</param> public VideoResult(TaskResult taskResult) : base(taskResult) { }
/// <summary> /// Initializes a new instance of the PickResult class /// with the specified Microsoft.Phone.Tasks.TaskResult. /// </summary> /// <param name="taskResult">Associated Microsoft.Phone.Tasks.TaskResult</param> public PickResult(TaskResult taskResult) : base(taskResult) { }
private void ImportState(Interface.Struct.TechniteState state) { taskParameter = 0; lastResources = resources; resources = state.resources; taskResult = (TaskResult)state.taskResult; this.state = new CompressedState(state.state).Decoded; transitionState = TransitionState.Preserved; if (taskResult == Technite.TaskResult.OperationWindowMissed) { if (++windowMissedThisRound < MaxLogPerRound) Out.Log(Significance.Unusual, "Operation Window Missed on " + nextTask + " of " + this); } if (taskResult != TaskResult.MoreWorkNeeded) nextTask = Task.None; }