public async Task GetAllWorkedOnRepairTaskFilteredByCustomer() { User customer = new User { UserName = "******" }; await this.UserManager.CreateAsync(customer); await this.RoleManager.CreateAsync(new AppRole { Name = StringConstants.CustomerUserRole }); await this.UserManager.AddToRoleAsync(customer, StringConstants.CustomerUserRole); RepairTask[] repairTasks = new RepairTask[3]; for (int i = 0; i < repairTasks.Length; i++) { repairTasks[i] = new RepairTask { User = customer, Status = Status.WorkedOn }; } this.dbContext.RepairTasks.AddRange(repairTasks); this.dbContext.SaveChanges(); Assert.Equal(repairTasks.Length, this.RepairTaskService.GetWorkedOnPerCustomerAsync(customer.UserName).GetAwaiter().GetResult().ToArray().Length); }
public async Task GetNoRepairTasksFilteredPerCustomerSinceThereAreNoneThatAreWorkedOn() { User customer = new User { UserName = "******" }; await this.UserManager.CreateAsync(customer); await this.RoleManager.CreateAsync(new AppRole { Name = StringConstants.CustomerUserRole }); await this.UserManager.AddToRoleAsync(customer, StringConstants.CustomerUserRole); RepairTask[] repairTasks = new RepairTask[3]; for (int i = 0; i < repairTasks.Length; i++) { repairTasks[i] = new RepairTask { User = customer, Status = Status.Pending }; } this.dbContext.RepairTasks.AddRange(repairTasks); this.dbContext.SaveChanges(); Assert.Empty(await this.RepairTaskService.GetWorkedOnPerCustomerAsync(customer.UserName)); }
public async Task CanUpdateARepairTaskRequiredPartsQuantity() { RepairTask repairTask = new RepairTask { Id = 1, PartsRequired = new Part[] { new Part { Type = PartType.CarBody, Quantity = 10 } } }; this.dbContext.RepairTasks.Add(repairTask); this.dbContext.SaveChanges(); RepairTaskEditInputModel inputModel = new RepairTaskEditInputModel { IsCarBodyPart = true, CarBodyPartAmount = 5, Id = 1 }; await this.RepairTaskService.TryUpdateRepairTaskAsync(inputModel); Assert.Equal(inputModel.CarBodyPartAmount, repairTask.PartsRequired.First().Quantity); }
public void Complete(RepairTask task) { Validate(task); Update(task, RepairTaskState.Completed, RepairTaskResult.Succeeded); }
/// <summary> /// Prepares the claimed repair tasks belonging to POS as per the TaskApprovalPolicy /// </summary> /// <returns>Task for the asynchronous operation</returns> internal async Task PrepareRepairTasks(CancellationToken cancellationToken) { NodeList nodeList = await this.fabricClient.QueryManager.GetNodeListAsync(null, null, this.DefaultTimeoutForOperation, cancellationToken); IList <RepairTask> claimedTaskList = await this.GetClaimedRepairTasks(nodeList, cancellationToken); switch (RmPolicy) { case TaskApprovalPolicy.NodeWise: { RepairTaskList processingTaskList = await this.GetRepairTasksUnderProcessing(cancellationToken); if (!processingTaskList.Any()) { if (claimedTaskList.Any()) { IList <RepairTask> completedTasks = await this.GetCompletedRepairTasks(nodeList, cancellationToken); TimeSpan?timePastAfterCompletedTask = null; if (completedTasks.Any()) { RepairTask lastCompletedTask = completedTasks.Aggregate((curMax, task) => (task.CompletedTimestamp > curMax.CompletedTimestamp ? task : curMax)); timePastAfterCompletedTask = DateTime.UtcNow - lastCompletedTask?.CompletedTimestamp; } if (!timePastAfterCompletedTask.HasValue || timePastAfterCompletedTask.Value > MinWaitTimeBetweenNodes) { RepairTask oldestClaimedTask = claimedTaskList.Aggregate( (curMin, task) => (task.CreatedTimestamp < curMin.CreatedTimestamp ? task : curMin)); ServiceEventSource.Current.VerboseMessage( "Out of {0} claimed tasks, Oldest repair task = {0} with node = {1} will be prepared", claimedTaskList.Count, oldestClaimedTask.TaskId, oldestClaimedTask.Target); this.StartPreparingRepairTask(oldestClaimedTask); } else { ServiceEventSource.Current.VerboseMessage( "Waiting for another {0} to pass in order to start the next repair task.", MinWaitTimeBetweenNodes - timePastAfterCompletedTask.Value); } } } break; } case TaskApprovalPolicy.UpgradeDomainWise: { string currentUpgradeDomain = await this.GetCurrentUpgradeDomainUnderProcessing(nodeList, cancellationToken); ServiceEventSource.Current.VerboseMessage(String.Format("{0} repair tasks were found in claimed state", claimedTaskList.Count)); // Below line can be enabled for debugging // rmHelper.PrintRepairTasks(claimedTaskList); foreach (var claimedTask in claimedTaskList) { string udName = this.GetUpgradeDomainOfRepairTask(claimedTask, nodeList); if (string.IsNullOrEmpty(currentUpgradeDomain)) { currentUpgradeDomain = udName; } if (udName == currentUpgradeDomain) { this.StartPreparingRepairTask(claimedTask); } } break; } default: { string errorMessage = String.Format("Illegal RmPolicy found: {0}", RmPolicy); ServiceEventSource.Current.ErrorMessage(errorMessage); throw new InvalidOperationException(errorMessage); } } }
public override void InitializeTasks() { base.InitializeTasks(); SiegeTask.Enable(); TimingAttackTask.Enable(); WorkerScoutTask.Enable(); DefenseTask.Enable(); BunkerDefendersTask.Enable(); SupplyDepotTask.Enable(); ArmyRavenTask.Enable(); RepairTask.Enable(); ReplenishBuildingSCVTask.Enable(); ClearBlockedExpandsTask.Enable(); HomeRepairTask.Enable(); TransformTask.Enable(); if (TankDefenseTasks.Count == 0) { foreach (Base b in Bot.Main.BaseManager.Bases) { if (b == Natural || b == Main) { continue; } TankDefenseTasks.Add(new DefenseSquadTask(b, UnitTypes.SIEGE_TANK) { MaxDefenders = 2 }); LiberatorDefenseTasks.Add(new DefenseSquadTask(b, UnitTypes.LIBERATOR) { MaxDefenders = 1 }); VikingDefenseTasks.Add(new DefenseSquadTask(b, UnitTypes.VIKING_FIGHTER) { MaxDefenders = 1 }); } } foreach (DefenseSquadTask task in TankDefenseTasks) { Task.Enable(task); } foreach (DefenseSquadTask task in LiberatorDefenseTasks) { Task.Enable(task); } foreach (DefenseSquadTask task in VikingDefenseTasks) { Task.Enable(task); } DefenseSquadTask.Enable(false, UnitTypes.CYCLONE); foreach (DefenseSquadTask task in DefenseSquadTask.Tasks) { task.MaxDefenders = 2; } if (CycloneDefenseTasks == null) { CycloneDefenseTasks = DefenseSquadTask.GetDefenseTasks(UnitTypes.CYCLONE); } DefenseSquadTask.Enable(CycloneDefenseTasks, false, false); foreach (DefenseSquadTask task in CycloneDefenseTasks) { task.MaxDefenders = 1; task.Priority = 8; } }
private static string GenerateJobContextId(RepairTask task) { return(string.Format("{0}@{1:O}", task.TaskId, task.CreatedTimestamp)); }
/// <summary> /// Serializes the object to JSON. /// </summary> /// <param name="writer">The <see cref="T: Newtonsoft.Json.JsonWriter" /> to write to.</param> /// <param name="obj">The object to serialize to JSON.</param> internal static void Serialize(JsonWriter writer, RepairTask obj) { // Required properties are always serialized, optional properties are serialized when not null. writer.WriteStartObject(); writer.WriteProperty(obj.State, "State", StateConverter.Serialize); writer.WriteProperty(obj.TaskId, "TaskId", JsonWriterExtensions.WriteStringValue); writer.WriteProperty(obj.Action, "Action", JsonWriterExtensions.WriteStringValue); writer.WriteProperty(obj.ResultStatus, "ResultStatus", ResultStatusConverter.Serialize); writer.WriteProperty(obj.PreparingHealthCheckState, "PreparingHealthCheckState", RepairTaskHealthCheckStateConverter.Serialize); writer.WriteProperty(obj.RestoringHealthCheckState, "RestoringHealthCheckState", RepairTaskHealthCheckStateConverter.Serialize); if (obj.Version != null) { writer.WriteProperty(obj.Version, "Version", JsonWriterExtensions.WriteStringValue); } if (obj.Description != null) { writer.WriteProperty(obj.Description, "Description", JsonWriterExtensions.WriteStringValue); } if (obj.Flags != null) { writer.WriteProperty(obj.Flags, "Flags", JsonWriterExtensions.WriteIntValue); } if (obj.Target != null) { writer.WriteProperty(obj.Target, "Target", RepairTargetDescriptionBaseConverter.Serialize); } if (obj.Executor != null) { writer.WriteProperty(obj.Executor, "Executor", JsonWriterExtensions.WriteStringValue); } if (obj.ExecutorData != null) { writer.WriteProperty(obj.ExecutorData, "ExecutorData", JsonWriterExtensions.WriteStringValue); } if (obj.Impact != null) { writer.WriteProperty(obj.Impact, "Impact", RepairImpactDescriptionBaseConverter.Serialize); } if (obj.ResultCode != null) { writer.WriteProperty(obj.ResultCode, "ResultCode", JsonWriterExtensions.WriteIntValue); } if (obj.ResultDetails != null) { writer.WriteProperty(obj.ResultDetails, "ResultDetails", JsonWriterExtensions.WriteStringValue); } if (obj.History != null) { writer.WriteProperty(obj.History, "History", RepairTaskHistoryConverter.Serialize); } if (obj.PerformPreparingHealthCheck != null) { writer.WriteProperty(obj.PerformPreparingHealthCheck, "PerformPreparingHealthCheck", JsonWriterExtensions.WriteBoolValue); } if (obj.PerformRestoringHealthCheck != null) { writer.WriteProperty(obj.PerformRestoringHealthCheck, "PerformRestoringHealthCheck", JsonWriterExtensions.WriteBoolValue); } writer.WriteEndObject(); }
public async Task <int> CreateRepairTaskAsync(RepairTaskInputModel repairTaskInputModel, User user) { RepairTask repairTask = new RepairTask { Status = Status.Pending, User = user }; if (repairTaskInputModel.IsCarBodyPart) { if (this.partService.PartTypeExists(PartType.CarBody) == false) { throw new ArgumentNullException(); } Part part = new Part { Quantity = repairTaskInputModel.CarBodyPartAmount, Type = PartType.CarBody }; repairTask.PartsRequired.Add(part); } if (repairTaskInputModel.IsChassisPart) { if (this.partService.PartTypeExists(PartType.Chassis) == false) { throw new ArgumentNullException(); } Part part = new Part { Type = PartType.Chassis, Quantity = repairTaskInputModel.ChassisPartAmount }; repairTask.PartsRequired.Add(part); } if (repairTaskInputModel.IsElectronicPart) { if (this.partService.PartTypeExists(PartType.Electronic) == false) { throw new ArgumentNullException(); } Part part = new Part { Type = PartType.Electronic, Quantity = repairTaskInputModel.ElectronicPartAmount }; repairTask.PartsRequired.Add(part); } if (repairTaskInputModel.IsInteriorPart) { if (this.partService.PartTypeExists(PartType.Interior) == false) { throw new ArgumentNullException(); } Part part = new Part { Type = PartType.Interior, Quantity = repairTaskInputModel.InteriorPartAmount }; repairTask.PartsRequired.Add(part); } this.dbContext.RepairTasks.Add(repairTask); if (await this.dbContext.SaveChangesAsync() == 0) { throw new ApplicationException(); } return(repairTask.Id); }
public static void DeleteTask(RepairTask task, FabricClient.RepairManagementClient repairManager) { var t = repairManager.DeleteRepairTaskAsync(task.TaskId, 0); t.Wait(); }
/// <summary> /// Updates a repair task. /// </summary> /// <param name="repairTask">The modified repair task.</param> /// <returns><para>The new version number of the repair task.</para></returns> public Task <Int64> UpdateRepairExecutionStateAsync(RepairTask repairTask) { return(this.UpdateRepairExecutionStateAsync(repairTask, FabricClient.DefaultTimeout, CancellationToken.None)); }
private void Onebox_Successful_CorrectRepairOrder(string property, bool reportOK) { LogHelper.Log("Starting test {0}", property); // Inject error Node node = GetHealthyNode(_fabricClient); DateTime lastHealthyAt = DateTime.Now; MockWatchdog watchdog = new MockWatchdog(_fabricClient.HealthManager, node.NodeName); watchdog.ReportError(property); int currentIndex = -1; MockRepairExecutor executor = null; // timeout is 2 times the longest policy plusplus a little extra time to account for software delays due to onebox environments DateTime timeout = DateTime.Now + Executors.Last().ActionTime + Executors.Last().ActionTime + TimeSpan.FromMinutes(3); while (DateTime.Now < timeout) { // Wait for PE to schedule the task RepairTask createdTask = PollingForAnyCreatedTask(node); Assert.IsNotNull(createdTask, "There should be a new repair task"); if (executor == null || executor.IsExecutable(createdTask) == false) { ++currentIndex; while (Executors[currentIndex].IsEnabled == false) { LogHelper.Log("Skipping disabled repair executor {0}", Executors[currentIndex].Name); ++currentIndex; if (currentIndex >= Executors.Count()) { Assert.Fail("No subsequent enabled executor"); } } } executor = Executors[currentIndex]; Assert.IsTrue(executor.IsEnabled, "Current executor '{0}' should be enabled", executor.Name); Assert.IsTrue(executor.IsExecutable(createdTask), "Task should be executable by current repair executor {0}", executor.Name); Assert.IsTrue(DateTime.Now - lastHealthyAt > executor.ActionTime, "Processing time should be bigger than executor's action time ({0} seconds)", executor.ActionTime.TotalSeconds); executor.Complete(createdTask); if (reportOK) { // Report OK in the middle to make sure that the escalation happens even in the flip // flopping case where after a repair a machine stays healthy for a shortwhile and then reports error again. Thread.Sleep(_actionSchedulingInterval); watchdog.ReportOk(property); // wait for the next action to happen Thread.Sleep(_actionSchedulingInterval); // give additional time to deal with any delays Thread.Sleep(TimeSpan.FromMilliseconds(5)); // Flop it back to error watchdog.ReportError(property); Thread.Sleep(TimeSpan.FromMilliseconds(5)); } } // By going thru the loop we should have reached the last executor Assert.IsTrue(executor.ActionTime == Executors.Last().ActionTime); }
/// <summary> /// Begins execution of a single repair by sending the request to Windows Azure /// </summary> /// <param name="repairTask">The repair task.</param> private void ExecuteRepair(RepairTask repairTask) { string targetRoleInstance = null; string targetNodeName = GetTargetNodeName(repairTask); if (targetNodeName != null) { targetRoleInstance = targetNodeName.TranslateNodeNameToRoleInstance(); } InfrastructureServiceMaintenanceAction?action = GetMaintenanceAction(repairTask.Action); if (action == null) { // Reject due to bad target or action this.UpdateRepairToRestoring( repairTask, RepairTaskResult.Failed, "Approved repair has invalid parameters"); } else { // Ready to execute long commitVersion = this.UpdateRepairToExecuting(repairTask); Exception exception = null; try { this.managementClient.RequestMaintenance( targetRoleInstance, action.Value, repairTask.TaskId, GenerateJobContextId(repairTask)); Trace.WriteInfo( TraceType, "Successfully requested maintenance in ExecuteRepair. Target role instance: {0}, action: {1}, repair task Id: {2}", targetRoleInstance, action.Value, repairTask.TaskId); } catch (KeyNotFoundException ex) { // Request failed; bad role instance ID. Fail the repair task. exception = ex; Trace.WriteWarning( TraceType, "Request maintenance failed in ExecuteRepair due to role instance name not being found. Target role instance: {0}, action: {1}, repair task Id: {2}, exception: {3}", targetRoleInstance, action.Value, repairTask.TaskId, ex); } catch (ManagementException ex) { // Request failed; due to MR. Fail the repair task. exception = ex; Trace.WriteWarning( TraceType, "Request maintenance failed in ExecuteRepair due to management protocol. Target role instance: {0}, action: {1}, repair task Id: {2}, exception: {3}", targetRoleInstance, action.Value, repairTask.TaskId, ex); } if (exception != null) { // Must specify commit version of the previous update. repairTask.Version = commitVersion; this.UpdateRepairToRestoring( repairTask, RepairTaskResult.Failed, "RequestMaintenance failed; check target name"); } } }
public bool IsExecutable(RepairTask scheduledTask) { return(Name.Equals(scheduledTask.Action)); }
/// <summary> /// <para>Creates a new repair task.</para> /// </summary> /// <param name = "repairTask" > /// <para> The description of the repair task to be created.</para> /// </param> /// <returns> /// <para>The version number of the newly-created repair task.</para> /// </returns> public Task <Int64> CreateRepairTaskAsync(RepairTask repairTask) { return(this.CreateRepairTaskAsync(repairTask, FabricClient.DefaultTimeout, CancellationToken.None)); }
private void Validate(RepairTask task) { Assert.IsNotNull(task, "Repair task must be not null"); Assert.IsTrue(IsExecutable(task), "Repair task must be executable by this Executor"); }
private static RepairTask Unwrap(IRepairTask repairTask) { RepairTask unwrappedRepairTask = ((ServiceFabricRepairTask)repairTask).Unwrap(); return(unwrappedRepairTask); }
public async Task <bool> TryUpdateRepairTaskAsync(RepairTaskEditInputModel repairTaskEditInputModel) { RepairTask repairTask = this.GetById(repairTaskEditInputModel.Id); if (repairTaskEditInputModel.IsCarBodyPart) { if (this.partService.PartTypeExists(PartType.CarBody) == false) { throw new ApplicationException(); } Part part = this.GetPartByPartTypeAndRepairTaskId(PartType.CarBody, repairTask.Id); if (part == null) { part = new Part { Type = PartType.CarBody, }; repairTask.PartsRequired.Add(part); } part.Quantity = repairTaskEditInputModel.CarBodyPartAmount; } if (repairTaskEditInputModel.IsChassisPart) { if (this.partService.PartTypeExists(PartType.Chassis) == false) { throw new ArgumentNullException(); } Part part = this.GetPartByPartTypeAndRepairTaskId(PartType.Chassis, repairTask.Id); if (part == null) { part = new Part { Type = PartType.Chassis, }; repairTask.PartsRequired.Add(part); } part.Quantity = repairTaskEditInputModel.ChassisPartAmount; } if (repairTaskEditInputModel.IsElectronicPart) { if (this.partService.PartTypeExists(PartType.Electronic) == false) { throw new ArgumentNullException(); } Part part = this.GetPartByPartTypeAndRepairTaskId(PartType.Electronic, repairTask.Id); if (part == null) { part = new Part { Type = PartType.Electronic, }; repairTask.PartsRequired.Add(part); } ; part.Quantity = repairTaskEditInputModel.ElectronicPartAmount; } if (repairTaskEditInputModel.IsInteriorPart) { if (this.partService.PartTypeExists(PartType.Interior) == false) { throw new ArgumentNullException(); } Part part = this.GetPartByPartTypeAndRepairTaskId(PartType.Interior, repairTask.Id); if (part == null) { part = new Part { Type = PartType.Interior, }; repairTask.PartsRequired.Add(part); } ; part.Quantity = repairTaskEditInputModel.InteriorPartAmount; } //for(int i = 0; i < repairTask.PartsRequired.ToList().Count; i++) { // Part part = repairTask.PartsRequired.ToList()[i]; // if (part.Quantity == 0) { // repairTask.PartsRequired.Remove(part); // } //} //foreach (Part part in repairTask.PartsRequired.ToList()) { // if (part.Quantity == 0) { // repairTask.PartsRequired.Remove(part); // } //} if (repairTask.PartsRequired.All(x => x.Quantity == 0)) { return(false); } else { this.dbContext.Parts.RemoveRange(repairTask.PartsRequired.Where(x => x.Quantity == 0)); } if (await this.dbContext.SaveChangesAsync() == 0) { throw new ApplicationException(); } return(true); }
public async Task GenerateReceiptAsync(ICollection <User> techniciansHavingWrokedOnRepairTask, string customerId, RepairTask repairTask) { decimal totalPrice = 0.0m; foreach (User technician in techniciansHavingWrokedOnRepairTask) { if (await this.userManager.IsInRoleAsync(technician, StringConstants.NoviceTechnicianUserRole)) { totalPrice += IntegerConstants.NoviceTechnicianPriceRate; } else if (await this.userManager.IsInRoleAsync(technician, StringConstants.AverageTechnicianUserRole)) { totalPrice += IntegerConstants.AverageTechnicianPriceRate; } else if (await this.userManager.IsInRoleAsync(technician, StringConstants.AdvancedTechnicianUserRole)) { totalPrice += IntegerConstants.AdvancedTechnicianPriceRate; } else if (await this.userManager.IsInRoleAsync(technician, StringConstants.ExpertTechnicianUserRole)) { totalPrice += IntegerConstants.ExpertTechnicianPriceRate; } else { throw new ApplicationException(); } } User customer = await this.userManager.FindByIdAsync(customerId); bool isCorporateCustomer = await this.userManager.IsInRoleAsync(customer, StringConstants.CorporateCustomerUserRole); if (isCorporateCustomer) { totalPrice *= IntegerConstants.CorporateClientPriceReduction; } Receipt receipt = new Receipt { UserId = customerId, TotalPrice = totalPrice }; await this.dbContext.Receipts.AddAsync(receipt); if (await this.dbContext.SaveChangesAsync() == 0) { throw new ApplicationException(); } repairTask.ReceiptId = receipt.Id; List <ExpertReceipt> expertsReceipts = new List <ExpertReceipt>(); foreach (User technician in techniciansHavingWrokedOnRepairTask) { expertsReceipts.Add(new ExpertReceipt { UserId = technician.Id, ReceiptId = receipt.Id }); } await this.dbContext .ExpertsReceipts .AddRangeAsync(expertsReceipts); if (await this.dbContext.SaveChangesAsync() == 0) { throw new ApplicationException(); } }
public RepairTask GetById(int id) { RepairTask repairTask = this.dbContext.RepairTasks.FirstOrDefault(t => t.Id == id); return(repairTask); }
public ServiceFabricRepairTask(RepairTask repairTask) { this.repairTask = repairTask.Validate("repairTask"); }
public void Add(RepairTask task) { _stack.Push(task); }
public void Add(RepairTask task) { _queue.Enqueue(task); }