Beispiel #1
0
        private void ToMonik(TraceEventType eventType, string format, object[] args)
        {
            switch (eventType)
            {
            case TraceEventType.Critical:
                _monik.ApplicationFatal(format, args);
                break;

            case TraceEventType.Error:
                _monik.ApplicationError(format, args);
                break;

            case TraceEventType.Warning:
                _monik.ApplicationWarning(format, args);
                break;

            case TraceEventType.Information:
                _monik.ApplicationInfo(format, args);
                break;
            }
        }
        public Worker(IMonik monik, ILogic logic)
        {
            stringVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            Method = logic.CheckScheduleAndExecute;

            this.monik = monik;
            logic.Start();

            monik.ApplicationInfo("Worker.ctor");
            Console.WriteLine("HostHolder.ctor");
        }
Beispiel #3
0
        } //taskresolver

        public void CheckScheduleAndExecute()
        {
            monik.ApplicationInfo($"{DateTime.Now}");

            List <IReportTask> currentTasks;

            lock (tasks)
                currentTasks = tasks.ToList();

            CultureInfo.CurrentCulture = new CultureInfo("en-US");

            foreach (var task in currentTasks.Where(x => x.Schedule != null))
            {
                string[] cronStrings =
                    schedules.First(s => s.Id == task.Schedule.Id).Schedule.Split(';');

                foreach (var cronString in cronStrings)
                {
                    var cronSchedule = CrontabSchedule.TryParse(cronString);

                    if (cronSchedule == null)
                    {
                        continue;
                    }

                    var occurrences =
                        cronSchedule.GetNextOccurrences(task.LastTime, DateTime.Now);

                    if (!occurrences.Any() ||
                        contextsInWork.Select(cont => cont.Value)
                        .Where(rtask => rtask.TaskId == task.Id).Any())
                    {
                        continue;
                    }

                    ExecuteTask(task);
                    break;
                }
            }
        }
Beispiel #4
0
        public HostHolder()
        {
            nancyHost = new NancyHost(
                new Uri("http://localhost:12345"),
                new Bootstrapper(),
                HostConfigs);

            stringVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            monik = Bootstrapper.Global.Resolve <IMonik>();
            monik.ApplicationInfo("HostHolder.ctor");
            Console.WriteLine("HostHolder.ctor");
        }
Beispiel #5
0
        public IReportTaskRunContext GetCurrentContext(bool takeDefault)
        {
            var context = autofac.Resolve <IReportTaskRunContext>();

            context.OpersToExecute = takeDefault
                ? Operations.Where(oper => oper.Properties.IsDefault)
                                     .OrderBy(oper => oper.Properties.Number).ToList()
                : Operations.OrderBy(oper => oper.Properties.Number).ToList();

            if (!context.OpersToExecute.Any())
            {
                var msg = $"Task {Id} did not executed (no operations found)";
                monik.ApplicationInfo(msg);
                Console.WriteLine(msg);
                return(null);
            }

            context.DefaultExporter = autofac.Resolve <IDefaultTaskExporter>();
            context.TaskId          = Id;
            context.TaskName        = Name;
            context.DependsOn       = DependsOn;

            context.CancelSource = new CancellationTokenSource();


            var pairsTask = Task.Run(async() => await Task.WhenAll(Parameters.Select(async pair =>
                                                                                     new KeyValuePair <string, object>(pair.Key,
                                                                                                                       await repository.GetBaseQueryResult("select " + pair.Value,
                                                                                                                                                           context.CancelSource.Token)))));

            var pairs = pairsTask.Result;

            context.Parameters = pairs
                                 .ToDictionary(pair => pair.Key, pair => pair.Value);

            var dtoTaskInstance = new DtoTaskInstance
            {
                TaskId    = Id,
                StartTime = DateTime.Now,
                Duration  = 0,
                State     = (int)InstanceState.InProcess
            };

            dtoTaskInstance.Id =
                repository.CreateEntity(dtoTaskInstance);

            context.TaskInstance = dtoTaskInstance;

            return(context);
        }
Beispiel #6
0
        } //ctor

        public IReportTaskRunContext GetCurrentContext(bool isDefault)
        {
            var context = autofac.Resolve <IReportTaskRunContext>();

            context.OpersToExecute = isDefault
                ? Operations.Where(oper => oper.Properties.IsDefault)
                                     .OrderBy(oper => oper.Properties.Number).ToList()
                : Operations.OrderBy(oper => oper.Properties.Number).ToList();

            if (!context.OpersToExecute.Any())
            {
                var msg = $"Task {Id} did not executed (no operations found)";
                monik.ApplicationInfo(msg);
                Console.WriteLine(msg);
                return(null);
            }

            context.Exporter = autofac.Resolve <IDefaultTaskExporter>();
            context.TaskId   = Id;
            context.TaskName = Name; //can do it by NamedParameter+ctor,but..

            context.Parameters = Parameters
                                 .ToDictionary(pair => pair.Key,
                                               pair => repository.GetBaseQueryResult("select " + pair.Value.ToString()));

            context.CancelSource = new CancellationTokenSource();

            var dtoTaskInstance = new DtoTaskInstance
            {
                TaskId    = Id,
                StartTime = DateTime.Now,
                Duration  = 0,
                State     = (int)InstanceState.InProcess
            };

            dtoTaskInstance.Id =
                repository.CreateEntity(dtoTaskInstance);

            context.TaskInstance = dtoTaskInstance;

            return(context);
        }
Beispiel #7
0
 private void SendServiceInfo(string msg)
 {
     monik.ApplicationInfo(msg);
     Console.WriteLine(msg);
 }
Beispiel #8
0
        public SecureNancyModule(ICacheMetric cacheMetric, ICacheSourceInstance sourceInstanceCache, IMonik monik)
        {
            this.RequiresAuthentication();

            Delete("/instances/{id:int}", args =>
            {
                try
                {
                    monik.ApplicationInfo($"Delete /instances/{args.id} by {Context.CurrentUser.Identity.Name}");
                    sourceInstanceCache.RemoveInstance(args.id);
                    return(HttpStatusCode.OK);
                }
                catch (Exception ex)
                {
                    monik.ApplicationError($"Method DELETE /instances/id : {ex.Message}");
                    return(HttpStatusCode.InternalServerError);
                }
            });

            Delete("/metrics/{id:int}", args =>
            {
                try
                {
                    monik.ApplicationInfo($"Delete /metrics/{args.id} by {Context.CurrentUser.Identity.Name}");
                    cacheMetric.RemoveMetric(args.id);
                    return(HttpStatusCode.OK);
                }
                catch (Exception ex)
                {
                    monik.ApplicationError($"Method DELETE /metrics/id : {ex.Message}");
                    return(HttpStatusCode.InternalServerError);
                }
            });

            Delete("/sources/{id:int}", args =>
            {
                try
                {
                    monik.ApplicationInfo($"Delete /sources/{args.id} by {Context.CurrentUser.Identity.Name}");
                    sourceInstanceCache.RemoveSource((short)args.id);
                    return(HttpStatusCode.OK);
                }
                catch (Exception ex)
                {
                    monik.ApplicationError($"Method DELETE /sources/id : {ex.Message}");
                    return(HttpStatusCode.InternalServerError);
                }
            });

            Post("/groups", args =>
            {
                try
                {
                    var group = this.Bind <Group_>();
                    monik.ApplicationInfo($"Post /groups {group.Name} by {Context.CurrentUser.Identity.Name}");
                    var result = sourceInstanceCache.CreateGroup(group);
                    return(Response.AsJson(result, HttpStatusCode.Created)
                           .WithHeader("Location", $"/groups/{result.ID}"));
                }
                catch (Exception ex)
                {
                    monik.ApplicationError($"Method POST /groups : {ex.Message}");
                    return(HttpStatusCode.InternalServerError);
                }
            });
            Delete("/groups/{id:int}", args =>
            {
                try
                {
                    monik.ApplicationInfo($"Delete /groups/{args.id} by {Context.CurrentUser.Identity.Name}");
                    var result = sourceInstanceCache.RemoveGroup((short)args.id);
                    return(result ? HttpStatusCode.OK : HttpStatusCode.NotFound);
                }
                catch (Exception ex)
                {
                    monik.ApplicationError($"Method DELETE /groups/id : {ex.Message}");
                    return(HttpStatusCode.InternalServerError);
                }
            });
            Put("/groups/{groupId:int}/instances/{instanceId:int}", args =>
            {
                try
                {
                    monik.ApplicationInfo($"Put /groups/{args.groupId}/instances/{args.instanceId} by {Context.CurrentUser.Identity.Name}");
                    sourceInstanceCache.AddInstanceToGroup(args.instanceId, (short)args.groupId);
                    return(HttpStatusCode.OK);
                }
                catch (Exception ex)
                {
                    monik.ApplicationError($"Method PUT /groups/id/instances/id : {ex.Message}");
                    return(HttpStatusCode.InternalServerError);
                }
            });
            Delete("/groups/{groupId:int}/instances/{instanceId:int}", args =>
            {
                try
                {
                    monik.ApplicationInfo($"Delete /groups/{args.groupId}/instances/{args.instanceId} by {Context.CurrentUser.Identity.Name}");
                    var result = sourceInstanceCache.RemoveInstanceFromGroup(args.instanceId, (short)args.groupId);
                    return(result ? HttpStatusCode.OK : HttpStatusCode.NotFound);
                }
                catch (Exception ex)
                {
                    monik.ApplicationError($"Method DELETE /groups/id/instances/id : {ex.Message}");
                    return(HttpStatusCode.InternalServerError);
                }
            });
        }
Beispiel #9
0
        public void EndAndLog([CallerMemberName] string sourceName = "")
        {
            var delta = DateTime.Now - _from;

            _monik.ApplicationInfo("{0} execution time: {1}ms", sourceName, delta.TotalMilliseconds);
        }
Beispiel #10
0
        public void RunOperations(IReportTaskRunContext taskContext)
        {
            Stopwatch duration = new Stopwatch();

            duration.Start();

            bool deleteFolder = false;

            if (taskContext.OpersToExecute.Any(oper => oper is SshImporter))//todo:not sshimporter but needsfolder
            {
                deleteFolder = true;
                taskContext.CreateDataFolder();
            }

            taskContext.PackageStates = taskContext.OpersToExecute
                                        .Select(oper => oper.Properties.Name + " (Not started) ").ToList();

            var dtoTaskInstance = taskContext.TaskInstance;

            var success    = true;
            var exceptions = new List <Tuple <Exception, string> >();

            try
            {
                foreach (var oper in taskContext.OpersToExecute)
                {
                    if (taskContext.CancelSource.IsCancellationRequested)
                    {
                        taskContext.CancelSource.Dispose();
                        success = false;
                        break;
                    }

                    var dtoOperInstance = new DtoOperInstance
                    {
                        TaskInstanceId = dtoTaskInstance.Id,
                        OperationId    = oper.Properties.Id,
                        StartTime      = DateTime.Now,
                        Duration       = 0,
                        State          = (int)InstanceState.InProcess
                    };

                    dtoOperInstance.Id =
                        repository.CreateEntity(dtoOperInstance);

                    taskContext.PackageStates[oper.Properties.Number - 1] =
                        GetOperationStateFromInstance(oper.Properties.Name, dtoOperInstance);

                    Stopwatch operDuration = new Stopwatch();
                    operDuration.Start();

                    try
                    {
                        Task.Run(async() => await oper
                                 .ExecuteAsync(taskContext)).Wait(taskContext.CancelSource.Token);

                        if (oper.Properties.NeedSavePackage)
                        {
                            dtoOperInstance.DataSet =
                                taskContext.GetCompressedPackage(oper.Properties.PackageName);
                        }

                        dtoOperInstance.State = (int)InstanceState.Success;
                        operDuration.Stop();
                        dtoOperInstance.Duration =
                            Convert.ToInt32(operDuration.ElapsedMilliseconds);
                        repository.UpdateEntity(dtoOperInstance);
                    }

                    catch (Exception e)
                    {
                        if (e is OperationCanceledException)
                        {
                            dtoOperInstance.State = (int)InstanceState.Canceled;
                        }

                        else
                        {
                            if (e.InnerException == null)
                            {
                                exceptions.Add(new Tuple <Exception, string>(e, oper.Properties.Name));
                                dtoOperInstance.ErrorMessage = e.Message;
                            }

                            else
                            {
                                var allExceptions = e.FromHierarchy(ex => ex.InnerException).ToList();

                                exceptions.AddRange(allExceptions
                                                    .Select(exx => new Tuple <Exception, string>(exx, oper.Properties.Name)));

                                dtoOperInstance.ErrorMessage =
                                    string.Join("\n", allExceptions.Select(exx => exx.Message));
                            }

                            dtoOperInstance.State = (int)InstanceState.Failed;
                        }

                        operDuration.Stop();
                        dtoOperInstance.Duration =
                            Convert.ToInt32(operDuration.ElapsedMilliseconds);
                        repository.UpdateEntity(dtoOperInstance);
                    }

                    finally
                    {
                        taskContext.PackageStates[oper.Properties.Number - 1] =
                            GetOperationStateFromInstance(oper.Properties.Name, dtoOperInstance);
                    }
                }

                if (exceptions.Count == 0 || dtoTaskInstance.State == (int)InstanceState.Canceled)
                {
                    var msg = dtoTaskInstance.State == (int)InstanceState.Canceled
                        ? $"Task {taskContext.TaskId} stopped"
                        : $"Task {taskContext.TaskId} completed successfully";
                    monik.ApplicationInfo(msg);
                    Console.WriteLine(msg);
                }

                else
                {
                    success = false;
                    taskContext.Exporter.SendError(exceptions, taskContext.TaskName);
                    var msg = $"Task {taskContext.TaskId} completed with errors";
                    monik.ApplicationInfo(msg);
                    Console.WriteLine(msg);
                }
            }

            catch (Exception e)
            {
                success = false;
                taskContext.Exporter.SendError(exceptions, taskContext.TaskName);
                var msg = $"Task {taskContext.TaskId} is not completed. An error has occurred: {e.Message}";
                monik.ApplicationError(msg);
                Console.WriteLine(msg);
            }

            duration.Stop();

            if (deleteFolder)
            {
                taskContext.RemoveDataFolder();
            }

            dtoTaskInstance.Duration = Convert.ToInt32(duration.ElapsedMilliseconds);

            dtoTaskInstance.State =
                success ? (int)InstanceState.Success
                : dtoTaskInstance.State == (int)InstanceState.Canceled ? (int)InstanceState.Canceled
                : (int)InstanceState.Failed;

            repository.UpdateEntity(dtoTaskInstance);
        }