public async Task <string[]> GetItemLog(string id, int limit) { var logPath = ManagedCertificateLog.GetLogPath(id); if (System.IO.File.Exists(logPath)) { try { // TODO: use reverse stream reader for large files var log = System.IO.File.ReadAllLines(logPath) .Reverse() .Take(limit) .Reverse() .ToArray(); return(log); } catch (Exception exp) { return(new string[] { $"Failed to read log: {exp}" }); } } else { return(new string[] { "" }); } }
private void LogMessage(string managedItemId, string msg, LogItemType logType = LogItemType.GeneralInfo) { ManagedCertificateLog.AppendLog(managedItemId, new ManagedCertificateLogItem { EventDate = DateTime.UtcNow, LogItemType = LogItemType.GeneralInfo, Message = msg }); }
public async Task <StatusMessage> RevokeCertificate(string managedItemId) { DebugLog(); var managedCertificate = await _certifyManager.GetManagedCertificate(managedItemId); var result = await _certifyManager.RevokeCertificate( ManagedCertificateLog.GetLogger(managedCertificate.Id), managedCertificate ); return(result); }
/// <summary> /// Get the applicable Account Details for this managed item /// </summary> /// <param name="item"></param> /// <returns>Account Details or null if there is no matching account</returns> private async Task <AccountDetails> GetAccountDetailsForManagedItem(ManagedCertificate item) { var accounts = await GetAccountRegistrations(); if (item == null) { // if not using a specific managed item, get first account details we have var a = accounts .Where(ac => ac.IsStagingAccount == false && !string.IsNullOrEmpty(ac.Email)) .FirstOrDefault(); if (a != null) { return(a); } else { // fallback to first staging account return(accounts.Where(ac => ac.IsStagingAccount == true).FirstOrDefault()); } } // determine the current current contact var currentCA = CoreAppSettings.Current.DefaultCertificateAuthority ?? StandardCertAuthorities.LETS_ENCRYPT; if (item != null) { if (!string.IsNullOrEmpty(item.CertificateAuthorityId)) { currentCA = item.CertificateAuthorityId; } } // get current account details for this CA (depending on whether this managed certificate uses staging mode or not) var matchingAccount = accounts.FirstOrDefault(a => a.CertificateAuthorityId == currentCA && a.IsStagingAccount == item.UseStagingMode); if (matchingAccount == null) { var log = ManagedCertificateLog.GetLogger(item.Id, new Serilog.Core.LoggingLevelSwitch(Serilog.Events.LogEventLevel.Error)); log?.Error($"Failed to match ACME account for managed certificate. Cannot continue request. :: {item.Name} CA: {currentCA} {(item.UseStagingMode ? "[Staging Mode]" : "[Production]")}"); } return(matchingAccount); }
public async Task <CertificateRequestResult> BeginCertificateRequest(string managedItemId, bool resumePaused) { DebugLog(); var managedCertificate = await _certifyManager.GetManagedCertificate(managedItemId); var progressState = new RequestProgressState(RequestState.Running, "Starting..", managedCertificate); var progressIndicator = new Progress <RequestProgressState>(progressState.ProgressReport); //begin monitoring progress _certifyManager.BeginTrackingProgress(progressState); //begin request var result = await _certifyManager.PerformCertificateRequest( ManagedCertificateLog.GetLogger(managedCertificate.Id), managedCertificate, progressIndicator, resumePaused ); return(result); }
public void Dispose() => ManagedCertificateLog.DisposeLoggers();
private async Task <List <ActionStep> > PerformTaskList(ILog log, bool isPreviewOnly, bool skipDeferredTasks, CertificateRequestResult result, IEnumerable <DeploymentTaskConfig> taskList, bool forceTaskExecute = false) { if (taskList == null || !taskList.Any()) { // nothing to do return(new List <ActionStep>()); } if (log == null) { log = ManagedCertificateLog.GetLogger(result.ManagedItem.Id, _loggingLevelSwitch); } // perform or preview each task var deploymentTasks = new List <DeploymentTask>(); var steps = new List <ActionStep>(); foreach (var taskConfig in taskList) { // add task to execution list unless the task is deferred/manual and we are currently skipping deferred tasks if (taskConfig.TaskTrigger != TaskTriggerType.MANUAL || (taskConfig.TaskTrigger == TaskTriggerType.MANUAL && !skipDeferredTasks)) { try { var provider = DeploymentTaskProviderFactory.Create(taskConfig.TaskTypeId.ToLower(), _pluginManager.DeploymentTaskProviders); Dictionary <string, string> credentials = null; if (!string.IsNullOrEmpty(taskConfig.ChallengeCredentialKey)) { credentials = await _credentialsManager.GetUnlockedCredentialsDictionary(taskConfig.ChallengeCredentialKey); } var deploymentTask = new DeploymentTask(provider, taskConfig, credentials); deploymentTasks.Add(deploymentTask); } catch (Exception exp) { steps.Add(new ActionStep { HasError = true, Title = "Task: " + taskConfig.TaskName, Description = "Cannot create task provider for deployment task: " + exp.ToString() }); } } } ActionStep previousActionStep = null; bool shouldRunCurrentTask = true; string taskTriggerReason = "Task will run for any status"; foreach (var task in deploymentTasks) { if (previousActionStep != null && (previousActionStep.HasError && !task.TaskConfig.RunIfLastStepFailed)) { shouldRunCurrentTask = false; taskTriggerReason = "Task will not run because previous task failed."; } else { if (task.TaskConfig.TaskTrigger == TaskTriggerType.ANY_STATUS) { shouldRunCurrentTask = true; taskTriggerReason = "Task will run for any status"; } else if (task.TaskConfig.TaskTrigger == TaskTriggerType.NOT_ENABLED) { shouldRunCurrentTask = false; taskTriggerReason = "Task is not enabled and will be skipped."; } else if (task.TaskConfig.TaskTrigger == TaskTriggerType.ON_SUCCESS) { if (result != null && (!result.Abort && result.IsSuccess)) { shouldRunCurrentTask = true; taskTriggerReason = "Task is enabled and primary request was successful."; } else { shouldRunCurrentTask = false; taskTriggerReason = "Task is enabled but will not run because primary request unsuccessful."; } } else if (task.TaskConfig.TaskTrigger == TaskTriggerType.ON_ERROR) { if (result != null && (!result.Abort && result.IsSuccess)) { shouldRunCurrentTask = false; taskTriggerReason = "Task is enabled but will not run because primary request was successful."; } else { shouldRunCurrentTask = true; taskTriggerReason = "Task is enabled and will run because primary request was unsuccessful."; } } else if (task.TaskConfig.TaskTrigger == TaskTriggerType.MANUAL) { if (skipDeferredTasks) { shouldRunCurrentTask = false; taskTriggerReason = "Task is enabled but will not run because execution is deferred/manual."; } else { shouldRunCurrentTask = true; taskTriggerReason = "Task is enabled and will run because deferred/manual tasks are not being skipped."; } } } if (forceTaskExecute == true) { if (!shouldRunCurrentTask) { shouldRunCurrentTask = true; taskTriggerReason = $"Task is being has been forced to run. Normal status would be [{taskTriggerReason}]"; } } var taskResults = new List <ActionResult>(); if (shouldRunCurrentTask) { log.Information($"Task [{task.TaskConfig.TaskName}] :: {taskTriggerReason}"); task.TaskConfig.DateLastExecuted = DateTime.Now; taskResults = await task.Execute(log, result, CancellationToken.None, isPreviewOnly : isPreviewOnly); if (!isPreviewOnly) { if (taskResults?.All(t => t.IsSuccess) == true) { _tc?.TrackEvent("TaskCompleted", new Dictionary <string, string> { { "TaskType", task.TaskConfig.TaskTypeId } }); } else { if (!forceTaskExecute) { _tc?.TrackEvent("TaskFailed", new Dictionary <string, string> { { "TaskType", task.TaskConfig.TaskTypeId } }); } } } } else { taskResults.Add(new ActionResult($"Task [{task.TaskConfig.TaskName}] :: {taskTriggerReason}", true)); } var subSteps = new List <ActionStep>(); var stepIndex = 1; foreach (var r in taskResults) { subSteps.Add(new ActionStep { HasError = !r.IsSuccess, Description = r.Message, Title = $"Task Step {stepIndex} of {task.TaskConfig.TaskName}", Key = task.TaskConfig.Id + "_" + stepIndex, Category = "Task Step" }); if (r.IsSuccess) { log?.Information(r.Message); } else { log?.Error(r.Message); } stepIndex++; } var overallTaskResult = "Unknown"; if (taskResults != null && taskResults.Any(t => t.IsSuccess == false)) { overallTaskResult = taskResults.First(t => t.IsSuccess == false).Message; } else { if (isPreviewOnly) { overallTaskResult = taskTriggerReason; } else { if (shouldRunCurrentTask) { overallTaskResult = "Task Completed OK"; } else { overallTaskResult = taskTriggerReason; } } } var hasError = (taskResults != null && taskResults.Any(t => t.IsSuccess == false) ? true : false); var currentStep = new ActionStep { Key = task.TaskConfig.Id, Title = task.TaskConfig.TaskName, Category = "Task", HasError = hasError, Description = overallTaskResult, HasWarning = !shouldRunCurrentTask, Substeps = subSteps }; task.TaskConfig.LastRunStatus = hasError ? RequestState.Error : RequestState.Success; task.TaskConfig.LastResult = overallTaskResult; steps.Add(currentStep); previousActionStep = currentStep; } return(steps); }
public async Task <List <ActionStep> > PerformDeploymentTask(ILog log, string managedCertificateId, string taskId, bool isPreviewOnly, bool skipDeferredTasks) { var steps = new List <ActionStep>(); var managedCert = await GetManagedCertificate(managedCertificateId); if (managedCert == null) { steps.Add(new ActionStep { HasError = true, Title = "Deployment", Description = "Managed certificate not found. Could not deploy." }); } if (log == null) { log = ManagedCertificateLog.GetLogger(managedCert.Id, _loggingLevelSwitch); } // perform or preview each task var credentialsManager = new CredentialsManager(); var deploymentTasks = new List <DeploymentTask>(); var taskList = managedCert.DeploymentTasks?.Where(t => string.IsNullOrEmpty(taskId) || taskId == t.Id); foreach (var taskConfig in taskList) { // add task to execution list unless the task is deferred and we are currently skipping deferred tasks if (!taskConfig.IsDeferred || (taskConfig.IsDeferred && !skipDeferredTasks)) { try { var provider = DeploymentTaskProviderFactory.Create(taskConfig.TaskTypeId.ToLower(), _pluginManager.DeploymentTaskProviders); Dictionary <string, string> credentials = null; if (!string.IsNullOrEmpty(taskConfig.ChallengeCredentialKey)) { credentials = await credentialsManager.GetUnlockedCredentialsDictionary(taskConfig.ChallengeCredentialKey); } var deploymentTask = new DeploymentTask(provider, taskConfig, credentials); deploymentTasks.Add(deploymentTask); } catch (Exception exp) { steps.Add(new ActionStep { HasError = true, Title = "Deployment Task: " + taskConfig.TaskName, Description = "Cannot create task provider for deployment task: " + exp.ToString() }); } } } foreach (var task in deploymentTasks) { var results = await task.Execute(log, managedCert, isPreviewOnly : isPreviewOnly); foreach (var r in results) { steps.Add(new ActionStep { HasError = !r.IsSuccess, Description = r.Message }); } } return(steps); }