Beispiel #1
0
        public IActionResult GetMetricsAgentFromAgent([FromRoute] int agentId, [FromRoute] DateTimeOffset fromTime, [FromRoute] DateTimeOffset toTime)
        {
            _logger.LogInformation($"starting new request to metrics agent");
            var metrics = _metricsAgentClient.GetAllNetworkMetrics(new GetAllNetworkMetricsApiRequest
            {
                ClientBaseAddress = _uriAdress.GetUri(agentId),
                FromTime          = fromTime,
                ToTime            = toTime
            });

            if (metrics != null)
            {
                foreach (var item in metrics.Metrics)
                {
                    _repository.Create(new NetworkMetrics
                    {
                        AgentId = agentId,
                        Time    = item.Time,
                        Value   = item.Value
                    });
                }
                ;
            }
            return(Ok(metrics));
        }
Beispiel #2
0
        public Task Execute(IJobExecutionContext context)
        {
            DateTimeOffset     toTime   = DateTimeOffset.UtcNow;
            DateTimeOffset     fromTime = _repositoryNetwork.LastTime();
            IList <AgentModel> agents   = _repositoryAgent.GetAll();


            foreach (var agent in agents)
            {
                if (agent.Status == true)
                {
                    AllNetworkMetricsApiResponse allNetworkMetrics = _client.GetAllNetworkMetrics(new GetAllNetworkMetricsApiRequest
                    {
                        FromTime = fromTime,
                        ToTime   = toTime,
                        Addres   = agent.Ipaddress
                    });

                    if (allNetworkMetrics != null)
                    {
                        foreach (var metric in allNetworkMetrics.Metrics)
                        {
                            _repositoryNetwork.Create(new NetworkMetricModel
                            {
                                IdAgent = agent.Id,
                                Time    = metric.Time,
                                Value   = metric.Value
                            });
                        }
                    }
                }
            }

            return(Task.CompletedTask);
        }
Beispiel #3
0
        public Task Execute(IJobExecutionContext context)
        {
            IList <Agents> _agents = _agentsRepository.GetAgents();

            foreach (var agent in _agents)
            {
                var fromTime = _repository.GetLastDate(agent.AgentId);
                var toTime   = DateTimeOffset.Now;

                var metrics = _metricsAgentClient.GetNetworkMetrics(new GetAllNetworkMetricsApiRequest
                {
                    FromTime          = fromTime,
                    ToTime            = toTime,
                    ClientBaseAddress = agent.AgentUrl
                });

                if (metrics != null)
                {
                    foreach (var metric in metrics)
                    {
                        _repository.Create(new NetworkMetric {
                            Time = metric.time.ToUnixTimeSeconds(), Value = metric.value, AgentId = agent.AgentId
                        });
                    }
                }
            }
            return(Task.CompletedTask);
        }
Beispiel #4
0
      public async Task Execute(IJobExecutionContext context)
      {
          var agents = _agentsRepository.GetActiveAgents();

          // асинхронно собираем метрики
          var listMetrics = await Task.WhenAll(agents.Select(async agent =>
            {
                var toTime   = DateTimeOffset.UtcNow;
                var fromTime = _metricsRepository.GetDateUpdate(agent.Id);
                var response = await GetMetricsByPeriod(agent, fromTime, toTime);
                return(response.Select(metric => new NetworkMetric()
                {
                    AgentId = agent.Id,
                    Time = metric.Time,
                    Value = metric.Value
                }));
            }));

          // сохраняем метрики
          foreach (var metrics in listMetrics)
          {
              foreach (var metric in metrics)
              {
                  _metricsRepository.Create(metric);
              }
          }
      }
Beispiel #5
0
        public Task Execute(IJobExecutionContext context)
        {
            var agentList = _repositoryAgent.GetAllAgents();

            foreach (var agent in agentList)
            {
                string agentAddress = _repositoryAgent.GetAddressForId(agent.AgentId);

                var fromTime = _repositoryNetwork.GetDateTimeOfLastRecord(agent.AgentId);
                var toTime   = DateTimeOffset.UtcNow;

                var metrics = _metricsAgentClient.GetNetworkMetrics(new GetAllNetworkMetricsApiRequest()
                {
                    FromTime          = fromTime,
                    ToTime            = toTime,
                    ClientBaseAddress = agentAddress
                });

                if (metrics != null)
                {
                    foreach (var metricFromAgent in metrics.Metrics)
                    {
                        _repositoryNetwork.Create(agent.AgentId, metricFromAgent);
                    }
                }
            }
            return(Task.CompletedTask);
        }
Beispiel #6
0
        private async Task SyncronizeMetricsFromAgent(AgentInfo agentInfo)
        {
            try
            {
                var lastTime = _metricsRepository.GetMetricsLastDateFormAgent(agentInfo.AgentId).AddSeconds(1);
                var response = await _agentClient.GetMetrics(new NetworkMetricClientRequest
                {
                    BaseUrl  = agentInfo.AgentUrl,
                    FromTime = lastTime,
                    ToTime   = DateTimeOffset.Now
                });

                if (response == null)
                {
                    return;
                }

                foreach (var clientMetric in response.Metrics)
                {
                    var NetworkMetric = _mapper.Map <NetworkMetric>(clientMetric);
                    NetworkMetric.AgentId = agentInfo.AgentId;
                    _metricsRepository.Create(NetworkMetric);
                }

                _logger.LogDebug($"Sincronized {response.Metrics.Count} Network Metrics from Agent ({agentInfo})");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }
        }
Beispiel #7
0
        public Task Execute(IJobExecutionContext context)
        {
            var allAgentsInfo = _agentsRepository.GetAllAgentsInfo();

            foreach (var agentInfo in allAgentsInfo)
            {
                var last    = _repository.GetLast(agentInfo.AgentId);
                var request = new GetAllNetWorkMetricsApiRequest()
                {
                    AgentUrl = agentInfo.AgentUrl,
                    FromTime = last,
                    ToTime   = DateTimeOffset.UtcNow,
                };

                var response = _client.GetAllNetworkMetrics(request);

                if (response != null)
                {
                    if (response.Metrics[0].Time == last)
                    {
                        response.Metrics.RemoveAt(0);
                    }

                    foreach (var metric in response.Metrics)
                    {
                        var formatedMetric = _mapper.Map <NetworkMetric>(metric);
                        formatedMetric.AgentId = agentInfo.AgentId;
                        _repository.Create(formatedMetric);
                    }
                }
            }

            return(Task.CompletedTask);
        }
Beispiel #8
0
 public IActionResult Create([FromBody] NetworkMetricCreateRequest request)
 {
     _repository.Create(new NetworkMetric
     {
         Time  = request.Time,
         Value = request.Value
     });
     return(Ok());
 }
Beispiel #9
0
        public IActionResult Create([FromBody] NetworkMetricCreateRequest request)
        {
            repository.Create(new NetworkMetric
            {
                FromTime = request.FromTime,
                ToTime   = request.ToTime,
            });

            return(Ok());
        }
Beispiel #10
0
        public IActionResult Create([FromBody] NetworkMetricsCreateRequest request)
        {
            _logger.LogInformation($"Метод Create {request}");
            _repository.Create(new NetworkMetrics
            {
                Time = request.Time,
                Value = request.Value
            });

            return Ok();
        }
        public Task Execute(IJobExecutionContext context)
        {
            var networkUsage = Convert.ToInt32(_networkCounter.NextValue());
            var time         = DateTimeOffset.UtcNow.ToUnixTimeSeconds();

            _repository.Create(new DAL.Models.NetworkMetric {
                Time = time, Value = networkUsage
            });

            return(Task.CompletedTask);
        }
Beispiel #12
0
        public Task Execute(IJobExecutionContext context)
        {
            var NetWorkUsageInPercents = Convert.ToInt32(_netWorkCounter.NextValue());
            var time = DateTimeOffset.UtcNow;

            _repository.Create(new NetworkMetric {
                Time = time, Value = NetWorkUsageInPercents
            });

            return(Task.CompletedTask);
        }
        public IActionResult Create([FromBody] NetworkMetricCreateRequest request)
        {
            _repository.Create(new NetworkMetric
            {
                Time  = request.Time,
                Value = request.Value
            });

            _logger.LogInformation($"Create - Value: {request.Value}, Time: {request.Time} - Entry added successfully");

            return(Ok());
        }
Beispiel #14
0
        public Task Execute(IJobExecutionContext context)
        {
            int bytesRecived = Convert.ToInt32(_networkCounter.NextValue());
            var time         = DateTimeOffset.UtcNow;

            _repository.Create(new NetworkMetricModel()
            {
                Time  = time,
                Value = bytesRecived
            });
            return(Task.CompletedTask);
        }
        public IActionResult Create([FromBody] NetworkMetricCreateRequest request)
        {
            _repository.Create(new NetworkMetric
            {
                Time  = request.Time,
                Value = request.Value
            });

            _logger.LogInformation(string.Concat("Create_Network: ", " Time: ", request.Time.ToString(), " Value: ", request.Value.ToString()));

            return(Ok());
        }
Beispiel #16
0
        public IActionResult Create([FromBody] NetworkMetricCreateRequest request)
        {
            _logger.LogInformation($"Создается запись с данными Time:{request.Time}; Value:{request.Value}");

            _repository.Create(new NetworkMetric
            {
                Time  = request.Time,
                Value = request.Value
            });

            return(Ok());
        }
        public Task Execute(IJobExecutionContext context)
        {
            var value = Convert.ToInt32(_counter.NextValue());

            var time = DateTimeOffset.UtcNow;

            _repository.Create(new NetworkMetric {
                Time = time, Value = value
            });

            return(Task.CompletedTask);
        }
Beispiel #18
0
        public Task Execute(IJobExecutionContext context)
        {
            _logger.LogDebug("== NetworkMetricJob START - " +
                             $"Time {DateTimeOffset.UtcNow}");
            //Получаем из репозитория агентов список всех агентов
            var allAgentsInfo = _agentsRepository.GetAllAgentsInfo();

            //Обрабатываем каждого агента в списке
            foreach (var agentInfo in allAgentsInfo.Agents)
            {
                //Временная метка, когда для текущего агента была снята последняя метрика
                var lastTime = _repository.GetLast(agentInfo.AgentId);

                // Создаем запрос для получения от текущего агента метрик за период времени
                // от последней проверки до текущего момента
                var request = new NetworkMetricGetByIntervalRequestByClient()
                {
                    AgentUri = agentInfo.AgentUri,
                    FromTime = lastTime,
                    ToTime   = DateTimeOffset.UtcNow,
                };

                // Делаем запрос к Агенту метрик и получаем список метрик
                var response = _client.GetMetrics <NetworkMetricFromAgentDto>(request, ApiNames.Network);

                if (response != null)
                {
                    // Убираем из выборки первую метрику если она совпадает с последней сохраненной в базе
                    // для исключения дублирования данных в базе
                    if (response.Metrics[0].Time == lastTime)
                    {
                        response.Metrics.RemoveAt(0);
                    }

                    // Перекладываем данные из Response в модели метрик
                    var recievedMetrics = new AllMetrics <NetworkMetric>();
                    foreach (var metricDto in response.Metrics)
                    {
                        recievedMetrics.Metrics.Add(new NetworkMetric
                        {
                            AgentId = agentInfo.AgentId,
                            Time    = metricDto.Time,
                            Value   = metricDto.Value
                        });
                    }
                    _repository.Create(recievedMetrics);
                }
            }
            _logger.LogDebug("!= NetworkMetricJob END - " +
                             $"Time {DateTimeOffset.UtcNow}");
            return(Task.CompletedTask);
        }
Beispiel #19
0
        public Task Execute(IJobExecutionContext context)
        {
            var allBytesPerSecond = Convert.ToInt32(_networkCounter.NextValue());

            // узнаем когда мы сняли значение метрики.
            var time = DateTimeOffset.UtcNow;

            // теперь можно записать что-то при помощи репозитория

            _repository.Create(new Models.NetworkMetric {
                Time = time, Value = allBytesPerSecond
            });

            return(Task.CompletedTask);
        }
Beispiel #20
0
        public Task Execute(IJobExecutionContext context)
        {
            int networkUsageInPercents = 0;

            foreach (var item in _allnetworkInterface)
            {
                networkUsageInPercents = networkUsageInPercents + Convert.ToInt32(item.NextValue());
            }
            DateTimeOffset time = DateTimeOffset.UtcNow;

            _repository.Create(new Models.NetworkMetrics {
                Time = time, Value = networkUsageInPercents
            });
            return(Task.CompletedTask);
        }
Beispiel #21
0
 public IActionResult Create([FromBody] NetworkMetricCreateRequest metric)
 {
     try
     {
         _logger.Debug($"Route(api/metrics/network): Running the Create method");
         _repository.Create(_mapper.Map <NetworkMetric>(metric));
         _logger.Debug($"Route(api/metrics/network): Create method completed successfully");
         return(Ok());
     }
     catch (Exception e)
     {
         _logger.Error(e);
         return(BadRequest(e.Message));
     }
 }
Beispiel #22
0
 public Task Execute(IJobExecutionContext context)
 {
     try
     {
         var cpuUsageInPercent = Convert.ToInt32(_networkCounter.NextValue());
         var time = DateTimeOffset.Now.ToUnixTimeSeconds();
         _repository.Create(new NetworkMetric()
         {
             Time = time, Value = cpuUsageInPercent
         });
     }
     catch (Exception ex)
     {
         _logger.LogError(ex.Message);
     }
     return(Task.CompletedTask);
 }
        public Task Execute(IJobExecutionContext context)
        {
            var value = 0;

            foreach (var counter in _counters)
            {
                value += Convert.ToInt32(counter.NextValue());
            }

            var time = DateTimeOffset.UtcNow.ToUnixTimeSeconds();

            _repository.Create(new NetworkMetric {
                Time = time, Value = value
            });

            return(Task.CompletedTask);
        }
Beispiel #24
0
        public Task Execute(IJobExecutionContext context)
        {
            var networkUsageRx = 0;

            foreach (var item in _networkCounter)
            {
                networkUsageRx += (int)item.NextValue();
            }

            //var time = TimeSpan.FromSeconds(DateTimeOffset.UtcNow.ToUnixTimeSeconds());
            var time = DateTimeOffset.UtcNow;

            _repository.Create(new NetworkMetrics {
                Time = time, Value = networkUsageRx
            });

            return(Task.CompletedTask);
        }
Beispiel #25
0
        public Task Execute(IJobExecutionContext context)
        {
            int sendByAllCards = 0;

            foreach (var counter in _networkCounters)
            {
                sendByAllCards += Convert.ToInt32(counter.NextValue());
            }

            _repository.Create(new NetworkMetric
            {
                Time  = DateTimeOffset.Now,
                Value = sendByAllCards
            });

            _logger.LogDebug("Bytes sent in second {0}b/s % by {1}", sendByAllCards, DateTimeOffset.Now);

            return(Task.CompletedTask);
        }
Beispiel #26
0
        public Task Execute(IJobExecutionContext context)
        {
            // Складываем характеристики всех экземпляров счетчиков
            int value = 0;

            foreach (var counter in _counters)
            {
                value += Convert.ToInt32(counter.NextValue());
            }

            // Время когда была собрана метрика
            var time = DateTimeOffset.UtcNow;

            // Запись метрики в репозиторий
            _repository.Create(new NetworkMetric {
                Time = time, Value = value
            });

            return(Task.CompletedTask);
        }
Beispiel #27
0
        public Task Execute(IJobExecutionContext context)
        {
            var adress = new AdressAgentFormTable();
            List <AgentInfo> uriAdress = adress.GetAllAdress();

            foreach (var adressAgent in uriAdress)
            {
                var fromTimeTable     = new LastDate();
                var fromTimeFromTable = fromTimeTable.GetTimeFromTable("networkmetrics", adressAgent.AgentId);
                AllNetworkMetricsApiResponse networkMetrics = null;

                if (fromTimeFromTable == null)
                {
                    DateTimeOffset fromTime = DateTimeOffset.UnixEpoch;
                    DateTimeOffset toTime   = DateTimeOffset.UtcNow;
                    networkMetrics = _metricsAgent.GetAllNetworkMetrics(new Requests.GetAllNetworkMetricsApiRequest {
                        ClientBaseAddress = new Uri(adressAgent.AgentAddress), ToTime = toTime, FromTime = fromTime
                    });
                }
                else
                {
                    DateTimeOffset toTime = DateTimeOffset.UtcNow;
                    networkMetrics = _metricsAgent.GetAllNetworkMetrics(new Requests.GetAllNetworkMetricsApiRequest {
                        ClientBaseAddress = new Uri(adressAgent.AgentAddress), ToTime = toTime, FromTime = fromTimeFromTable
                    });
                }
                if (networkMetrics != null)
                {
                    foreach (var item in networkMetrics.Metrics)
                    {
                        _repository.Create(new NetworkMetrics
                        {
                            AgentId = adressAgent.AgentId,
                            Time    = item.Time,
                            Value   = item.Value
                        });
                    }
                }
            }
            return(Task.CompletedTask);
        }
Beispiel #28
0
 public Task Execute(IJobExecutionContext context)
 {
     try
     {
         var agents = _agentsRepository.GetAgentsList();
         for (int i = 0; i < agents.Count(); i++)
         {
             if (agents[i].Enabled)
             {
                 long           lastTime = _repository.GetLastTime(i);
                 DateTimeOffset fromTime = DateTimeOffset.FromUnixTimeSeconds(lastTime);
                 var            metrics  = _client.GetNetworkMetrics(new GetAllNetworkMetrisApiRequest()
                 {
                     AgentAddress = agents[i].AgentAddress,
                     FromTime     = fromTime,
                     ToTime       = DateTimeOffset.Now
                 });
                 if (metrics != null)
                 {
                     foreach (var metric in metrics.Metrics)
                     {
                         _repository.Create(new NetworkMetric()
                         {
                             AgentId = metric.AgentId,
                             Time    = metric.Time.ToUnixTimeSeconds(),
                             Value   = metric.Value
                         });
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         _logger.LogError(ex.Message);
     }
     return(Task.CompletedTask);
 }
Beispiel #29
0
        public Task Execute(IJobExecutionContext context)
        {
            var agentsList = _repositoryAgents.GetAll();

            foreach (var agent in agentsList)
            {
                var metricsList = _metricsAgentClient.GetAllNetworkMetrics(new GetAllNetworkMetricsApiRequest
                {
                    FromTime          = _repository.GetMaxDate(agent.AgentId),
                    ToTime            = DateTimeOffset.UtcNow,
                    ClientBaseAddress = agent.AgentURL
                });

                if (!object.ReferenceEquals(metricsList, null))
                {
                    foreach (var metric in metricsList.Metrics)
                    {
                        _repository.Create(metric, agent.AgentId);
                    }
                }
            }

            return(Task.CompletedTask);
        }
Beispiel #30
0
        public IActionResult Create([FromBody] NetworkMetricCreateRequest request)
        {
            _repository.Create(_mapper.Map <NetworkMetric>(request));

            return(Ok());
        }