예제 #1
0
        public object GetUpdateBackupEntryList(string id)
        {
            UpdateInstruction instruction = _UpdateService.GetUpdateInstructionByID(new Guid(id));

            this.DoAnalytics("GetUpdateBackupEntryList", $"Getting backup list for '{instruction.Name}'");
            return(_UpdateService.GetUpdateBackupEntryList(instruction));
        }
        public static async Task <string> updateInstruction(bool updateVal, Instruction currInstruction)
        {
            CheckTimeZone();

            string url = AppConstants.BaseUrl + AppConstants.updateInstruction;

            currInstruction.updateIsComplete(updateVal);

            UpdateInstruction updateInstruction = new UpdateInstruction()
            {
                id             = currInstruction.unique_id,
                is_complete    = currInstruction.IsComplete,
                is_in_progress = currInstruction.IsInProgress
            };

            string toSend  = updateInstruction.updateInstruction();
            var    content = new StringContent(toSend);
            var    res     = await client.PostAsync(url, content);

            if (res.IsSuccessStatusCode)
            {
                Debug.WriteLine("Wrote to the datebase");
                return("SUCCESS");
            }
            else
            {
                Debug.WriteLine("Some error");
                Debug.WriteLine(toSend);
                Debug.WriteLine(res.ToString());
            }
            return("FAILURE");
        }
예제 #3
0
        public object DoRollback([FromBody] RollbackPayload rollbackPayload)
        {
            UpdateInstruction instructionData = _UpdateService.GetUpdateInstructionByID(rollbackPayload.UpdateInstructionID);
            string            ReturnData      = _UpdateService.DoScheduledRollback(rollbackPayload.UpdateInstructionID, rollbackPayload.RollbackUpdateID);

            this.DoAnalytics("DoRollback", $"Rolling back version of '{instructionData.Name}'. Schedule number is '{ReturnData}'");
            return(ReturnData);
            //return _backgroundJobs.Enqueue(() => _UpdateService.DoRollback(instruction, new UpdateBackupEntry("","")));
        }
예제 #4
0
        public object DoUpdate([FromBody] UpdatePayload updatePayload)
        {
            UpdateInstruction instruction = _UpdateService.GetUpdateInstructionByID(updatePayload.UpdateInstructionID);

            string ReturnData = _UpdateService.DoScheduledUpdate(instruction); //_backgroundJobs.Enqueue(() => _UpdateService.DoUpdate(instruction));

            this.DoAnalytics("DoUpdate", $"Rolling update for '{instruction.Name}'. Schedule number is '{ReturnData}'");

            return(ReturnData);
        }
예제 #5
0
        public List <UpdateBackupEntry> GetUpdateBackupEntryList(UpdateInstruction UpdateInstruction)
        {
            List <UpdateBackupEntry> returnData = new List <UpdateBackupEntry>();
            string RootDirectoryName            = new DirectoryInfo(System.IO.Path.GetDirectoryName(UpdateInstruction.WorkingDirectory + "\\")).Name;
            var    Directories = Directory.GetDirectories(System.IO.Directory.GetParent(UpdateInstruction.WorkingDirectory).FullName, $"{RootDirectoryName}*")
                                 .Where(x => UpdateInstruction.WorkingDirectory.ToUpper() != x.ToUpper()).ToList();

            foreach (var directoryPath in Directories)
            {
                string folderSufix = directoryPath.Replace($"{UpdateInstruction.WorkingDirectory}_", string.Empty);;
                returnData.Add(new UpdateBackupEntry(directoryPath, folderSufix));
            }
            return(returnData.OrderByDescending(x => x.BackupDate).ToList());
        }
예제 #6
0
        public UpdateResult DoUpdate(UpdateInstruction UpdateInstruction)
        {
            string AnalyticsMessageResult = "";

            var updateResultReturn = new UpdateResult()
            {
                ID        = UpdateInstruction.ID,
                IsSuccess = false,
                //Message = "No update found. Nothing to update!",
                UpdateInstructionID = UpdateInstruction.ID
            };


            try
            {
                UpdateEntry updateEntry = this.HasUpdate(UpdateInstruction);
                JobStatus   JobStatus   = _JobService.GetQueuePosition(new JobStatus()
                {
                    ID = UpdateInstruction.ID
                });

                if (updateEntry.HasUpdate)
                {
                    updateResultReturn = ExecuteUpdate(updateEntry);

                    AnalyticsMessageResult   = !updateResultReturn.IsSuccess ? $"Job '{JobStatus.QueuePosition}' failed to update '{updateEntry.ProductName}' from '{updateEntry.CurrentVersion}' to '{updateEntry.CurrentVersion}'. Alepsed time is: {this.ConvertMillisecondsToTimeString(updateResultReturn.TimeSpentMilliseconds)}.\r\nSee details:\r\n\r\n{ JsonConvert.SerializeObject(updateResultReturn.Messages, Formatting.Indented)}"
                    : AnalyticsMessageResult = $"Job '{JobStatus.QueuePosition}' updated '{updateEntry.ProductName}' from '{updateEntry.CurrentVersion}' to '{updateEntry.NewVersion}'. Alepsed time is: {this.ConvertMillisecondsToTimeString(updateResultReturn.TimeSpentMilliseconds)}.";
                }
                else
                {
                    AnalyticsMessageResult = $"Job '{JobStatus.QueuePosition}' did not found update for '{updateEntry.ProductName}' with version '{updateEntry.CurrentVersion}'. You have the latest version avaliable.";
                    updateResultReturn.AddMessage(AnalyticsMessageResult, UpdateResultMessage.eMessageType.INFORMATION);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                _JobService.CreateUpdateJobStatus(new JobStatus()
                {
                    ID = UpdateInstruction.ID, CurrentStatus = JobStatusTyes.Completed
                });
            }

            this._UpdateRepository.WriteUpdateInstructionResult(updateResultReturn);
            this.SendAnalyticsData("UpdateService.DoUpdate.Results", AnalyticsMessageResult);
            return(updateResultReturn);
        }
예제 #7
0
        public List <UpdateResult> GetUpdateHistory(UpdateInstruction instruction)
        {
            if (!Directory.Exists(_JobResultPath))
            {
                return(new List <UpdateResult>());
            }

            List <UpdateResult> returnResults = new List <UpdateResult>();

            foreach (var file in Directory.GetFiles(_JobResultPath, $"*{instruction.ID}*"))
            {
                returnResults.Add(JsonConvert.DeserializeObject <UpdateResult>(File.ReadAllText(file)));
            }

            return(returnResults);
        }
예제 #8
0
        public string DoScheduledUpdate(UpdateInstruction UpdateInstruction)
        {
            JobStatus CurrentJobStatus = this._JobService.GetQueuePosition(new Domain.Models.Job.JobStatus()
            {
                ID = UpdateInstruction.ID
            });

            if (!string.IsNullOrEmpty(CurrentJobStatus.QueuePosition))
            {
                return(CurrentJobStatus.QueuePosition);
            }

            CurrentJobStatus.ID            = UpdateInstruction.ID;
            CurrentJobStatus.QueuePosition = BackgroundJob.Enqueue(() => this.DoUpdate(UpdateInstruction));

            this._JobService.CreateUpdateJobStatus(CurrentJobStatus);
            return(CurrentJobStatus.QueuePosition);
        }
예제 #9
0
        public UpdateResult DoRollback(Guid UpdateInstructionID, Guid RollbackUpdateBackupID)
        {
            UpdateInstruction UpdateInstruction = _UpdateRepository.GetUpdateInstructionByID(UpdateInstructionID);
            UpdateBackupEntry UpdateBackupEntry = _UpdateRepository.GetUpdateBackupEntryFromUpdateID(UpdateInstruction, RollbackUpdateBackupID);

            string AnalyticsMessageResult = "";
            var    updateResultReturn     = new UpdateResult()
            {
                ID        = UpdateInstruction.ID,
                IsSuccess = false,
                //Message = "No update found. Nothing to update!",
                UpdateInstructionID = UpdateInstruction.ID
            };

            try
            {
                Version   CurrentVersionBeforeRollback = this.GetCurrentAssemblyVersion(UpdateInstruction);
                JobStatus JobStatus = _JobService.GetQueuePosition(new JobStatus()
                {
                    ID = UpdateInstruction.ID
                });

                updateResultReturn = ExecuteRollback(UpdateInstruction, UpdateBackupEntry);

                AnalyticsMessageResult = !updateResultReturn.IsSuccess ? $"Job '{JobStatus.QueuePosition}' Failed to rollback '{UpdateInstruction.Name}' from '{CurrentVersionBeforeRollback}' to '{UpdateBackupEntry.BackupVersion}'. Alepsed time is: {this.ConvertMillisecondsToTimeString(updateResultReturn.TimeSpentMilliseconds)}.\r\nSee details:\r\n\r\n{ JsonConvert.SerializeObject(updateResultReturn.Messages, Formatting.Indented)}"
                        : $"Job '{JobStatus.QueuePosition}' rollback success for product '{UpdateInstruction.Name}' from '{CurrentVersionBeforeRollback}' to '{UpdateBackupEntry.BackupVersion}'. Alepsed time is: {this.ConvertMillisecondsToTimeString(updateResultReturn.TimeSpentMilliseconds)}.";
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                _JobService.CreateUpdateJobStatus(new JobStatus()
                {
                    ID = UpdateInstruction.ID, CurrentStatus = JobStatusTyes.Completed
                });
            }

            this.SendAnalyticsData("UpdateService.DoRollback.Results", AnalyticsMessageResult);
            return(updateResultReturn);
        }
예제 #10
0
        public UpdateEntry HasUpdate(UpdateInstruction UpdateInstruction)
        {
            //Verifica se existe atualização para o sistema informado
            //Caso exista atualizar o retorno com dados necessários para atualizaçõ
            //Caso não exista, retornar que não existe atualização
            string UpdateEntryString = DownloadManager.DownloadString(UpdateInstruction.UrlOrPathToUpdateDefinition);

            UpdateFile updateFile = JsonConvert.DeserializeObject <UpdateFile>(UpdateEntryString);

            System.Version CurrentVersion = AssemblyManager.GetAssemblyVersion(UpdateInstruction.MainAssembly);
            bool           IsNewerVersion = AssemblyManager.IsNewerVersion(CurrentVersion, updateFile.Version);

            return(new UpdateEntry()
            {
                PathOrURLToFileUpdate = updateFile.PathOrURLToFileUpdate,
                CurrentVersion = CurrentVersion,
                NewVersion = updateFile.Version,
                FilesAndPathToKeep = updateFile.FilesAndPathToKeep,
                HasUpdate = IsNewerVersion,
                IsMandatory = false,
                ProductName = UpdateInstruction.Name,
                UpdateInstruction = UpdateInstruction
            });
        }
예제 #11
0
 public UpdateBackupEntry GetUpdateBackupEntryFromUpdateID(UpdateInstruction UpdateInstruction, Guid rollbackUpdateID)
 {
     return(this.GetUpdateBackupEntryList(UpdateInstruction).Where(x => x.UpdateID == rollbackUpdateID).FirstOrDefault());
 }
예제 #12
0
 public Version GetCurrentAssemblyVersion(UpdateInstruction UpdateInstruction)
 {
     return(AssemblyManager.GetAssemblyVersion(UpdateInstruction.MainAssembly));
 }
예제 #13
0
 public List <UpdateBackupEntry> GetUpdateBackupEntryList(UpdateInstruction UpdateInstruction)
 {
     return(_UpdateRepository.GetUpdateBackupEntryList(UpdateInstruction));
 }
예제 #14
0
 public List <UpdateResult> GetUpdateHistory(UpdateInstruction instruction)
 {
     return(_UpdateRepository.GetUpdateHistory(instruction));
 }
예제 #15
0
        public UpdateResult ExecuteRollback(UpdateInstruction UpdateInstruction, UpdateBackupEntry UpdateBackupEntry)
        {
            //1 - Rodar linha de comando antes do rollback
            //2 - Fazer backup do diretório antigo com prefixo da versão
            //3 - Renomear Diretório do backup para o diretório atual
            //4 - Rodar linha de comano pós rollback

            var updateResultReturn = new UpdateResult()
            {
                ID = Guid.NewGuid(),
                UpdateInstructionID = UpdateInstruction.ID
            };

            Stopwatch stopWatchTimer = Stopwatch.StartNew();

            System.Version CurrentVersion  = new Version("0.0.0");
            System.Version RollbackVersion = new Version("0.0.0");
            try
            {
                updateResultReturn.AddMessage("Starting the update process", UpdateResultMessage.eMessageType.INFORMATION);
                CurrentVersion  = AssemblyManager.GetAssemblyVersion(UpdateInstruction.MainAssembly);
                RollbackVersion = AssemblyManager.GetAssemblyVersion(UpdateBackupEntry.FullPath);

                updateResultReturn.AddMessage($"Trying to rollback version {CurrentVersion} to {RollbackVersion}", UpdateResultMessage.eMessageType.INFORMATION);

                var comandLineBeforeResult = Shell.ExecuteTerminalCommand(UpdateInstruction.GetCommandLineBeforeUpdateWithReplacedParams());
                if (comandLineBeforeResult.code > 0)
                {
                    throw new Exception($"Cannot run Commandline before update, see details.\r\nStdOut: {comandLineBeforeResult.stdout}\r\nStdErr: {comandLineBeforeResult.stderr}");
                }

                updateResultReturn.AddMessage($"Command line 'CommandLineBeforeUpdate' executed.\r\nOutput code: {comandLineBeforeResult.code}\r\nStdOut: {comandLineBeforeResult.stdout}\r\nStdErr: {comandLineBeforeResult.stderr}", UpdateResultMessage.eMessageType.SUCCESS);


                //Execuando Backup
                string workingFolderBackup = this.GenerateBackupFolderFullPathName(UpdateBackupEntry.UpdateID, updateResultReturn.ID, UpdateInstruction.WorkingDirectory, CurrentVersion);
                DirectoryManager.RenameDirectory(UpdateInstruction.WorkingDirectory, workingFolderBackup);

                updateResultReturn.AddMessage($"Renamed current version folder from {UpdateInstruction.WorkingDirectory} to {workingFolderBackup}.", UpdateResultMessage.eMessageType.SUCCESS);
                //Fazendo Rollback da versão anterior para versão atual de trabalho.
                //string BackupFolder = GetBackupFolderFromUpdateID()
                DirectoryManager.RenameDirectory(UpdateBackupEntry.FullPath, UpdateInstruction.WorkingDirectory);
                updateResultReturn.AddMessage($"Rollback diretory {UpdateBackupEntry.FullPath} to {UpdateInstruction.WorkingDirectory}.", UpdateResultMessage.eMessageType.SUCCESS);


                var comandLineAfterResult = Shell.ExecuteTerminalCommand(UpdateInstruction.GetCommandLineAfterUpdateWithReplacedParams());
                if (comandLineAfterResult.code > 0)
                {
                    throw new Exception($"Cannot run Commandline after update, see details.r\nStdOut: {comandLineAfterResult.stdout}\r\nStdErr: {comandLineAfterResult.stderr}");
                }

                updateResultReturn.AddMessage($"Command line 'CommandLineBeforeUpdate' executed.\r\nOutput code: {comandLineAfterResult.code}\r\nStdOut: {comandLineAfterResult.stdout}\r\nStdErr: {comandLineAfterResult.stderr}", UpdateResultMessage.eMessageType.SUCCESS);

                stopWatchTimer.Stop();
                updateResultReturn.TimeSpentMilliseconds = stopWatchTimer.ElapsedMilliseconds;
                updateResultReturn.IsSuccess             = true;

                /*string alepsedTime = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms",
                 *          stopWatchTimer.Elapsed.Hours,
                 *          stopWatchTimer.Elapsed.Minutes,
                 *          stopWatchTimer.Elapsed.Seconds,
                 *          stopWatchTimer.Elapsed.Milliseconds);*/

                updateResultReturn
                .AddMessage($"Rollback '{UpdateInstruction.Name}' from '{CurrentVersion}' to '{RollbackVersion}'. Alepsed time: {this.ConvertMillisecondsToTimeString(updateResultReturn.TimeSpentMilliseconds)}",
                            updateResultReturn.IsSuccess ?
                            (updateResultReturn.Messages.Where(x => x.Type == UpdateResultMessage.eMessageType.ERROR).Count() <= 0 ? UpdateResultMessage.eMessageType.SUCCESS : UpdateResultMessage.eMessageType.WARNING) : UpdateResultMessage.eMessageType.ERROR);
            }
            catch (Exception ex)
            {
                stopWatchTimer.Stop();
                updateResultReturn.TimeSpentMilliseconds = stopWatchTimer.ElapsedMilliseconds;

                updateResultReturn
                .AddMessage($"Error updating '{UpdateInstruction.Name}' from '{CurrentVersion}' to '{RollbackVersion}' see details.\r\nDetails: " + ex.ToString(), UpdateResultMessage.eMessageType.ERROR);
                updateResultReturn.IsSuccess = false;
            }
            finally
            {
                this._UpdateRepository.WriteUpdateInstructionResult(updateResultReturn);
            }


            return(updateResultReturn);
        }
예제 #16
0
 public UpdateBackupEntry GetUpdateBackupEntryFromUpdateID(UpdateInstruction UpdateInstruction, Guid rollbackUpdateID)
 {
     return(this._UpdateRepository.GetUpdateBackupEntryFromUpdateID(UpdateInstruction, rollbackUpdateID));
 }