Exemple #1
0
        public LogConfig GetLogConfig(Guid accountId, Guid componentId)
        {
            lock (LockObject.ForComponent(componentId))
            {
                var componentService = Context.ComponentService;
                var component        = componentService.GetComponentById(accountId, componentId);

                var accountDbContext = Context.GetAccountDbContext(accountId);
                var repository       = accountDbContext.GetLogConfigRepository();
                var config           = repository.GetByComponentId(componentId);

                if (config == null)
                {
                    config = new LogConfig()
                    {
                        Enabled          = true,
                        ComponentId      = component.Id,
                        LastUpdateDate   = DateTime.Now,
                        IsDebugEnabled   = true,
                        IsTraceEnabled   = true,
                        IsInfoEnabled    = true,
                        IsWarningEnabled = true,
                        IsErrorEnabled   = true,
                        IsFatalEnabled   = true
                    };
                    repository.Add(config);
                }

                return(config);
            }
        }
        public Component GetOrCreateComponentInternal(Guid accountId, GetOrCreateComponentRequestData data, bool createNew)
        {
            if (data == null)
            {
                throw new ParameterRequiredException("Request.Data");
            }
            if (data.TypeId == null)
            {
                throw new ParameterRequiredException("Request.Data.TypeId");
            }
            if (string.IsNullOrEmpty(data.SystemName))
            {
                throw new ParameterRequiredException("data.SystemName");
            }

            if (data.ParentComponentId == null)
            {
                data.ParentComponentId = GetRootId(accountId);
            }

            var componentId = data.NewId ?? Guid.NewGuid();
            var systemName  = data.SystemName;

            var properties = ApiConverter.GetComponentProperties(data.Properties);

            var accountDbContext    = Context.GetAccountDbContext(accountId);
            var componentRepository = accountDbContext.GetComponentRepository();
            var lockObj             = LockObject.ForComponent(systemName);

            lock (lockObj)
            {
                // ищем в детях
                var  component = componentRepository.GetChild(data.ParentComponentId.Value, systemName);
                bool isExists  = true;
                if (component == null)
                {
                    // ищем в папках
                    var parent = componentRepository.GetById(data.ParentComponentId.Value);
                    component = FindBySystemName(parent, systemName);
                    if (component == null)
                    {
                        // Проверим лимит
                        var checker          = AccountLimitsCheckerManager.GetCheckerForAccount(accountId);
                        var limitCheckResult = checker.CheckMaxComponents(accountDbContext);
                        if (!limitCheckResult.Success)
                        {
                            throw new OverLimitException(limitCheckResult.Message);
                        }

                        // создаем новый
                        component = Add(
                            accountId,
                            componentId,
                            data.ParentComponentId.Value,
                            data.DisplayName ?? systemName,
                            systemName,
                            data.TypeId.Value);

                        isExists = false;
                        checker.RefreshComponentsCount();
                    }
                }

                if (isExists && createNew)
                {
                    throw new ResponseCodeException(
                              ResponseCode.ParameterError,
                              "Компонент с таким системным именем уже существует");
                }

                // обновим версию
                if (string.IsNullOrEmpty(data.Version) == false)
                {
                    component.Version = data.Version;
                }

                // обновим свойства
                foreach (var property in properties)
                {
                    component.SetProperty(property);
                }
                accountDbContext.SaveChanges();
                return(component);
            }
        }
Exemple #3
0
        public IMetricCacheReadObject SaveMetric(Guid accountId, SendMetricRequestData data)
        {
            if (data.Value.HasValue && (double.IsNaN(data.Value.Value) || double.IsInfinity(data.Value.Value)))
            {
                throw new ParameterErrorException("Metric value can't be Nan or Infinity");
            }

            var processDate      = DateTime.Now;
            var accountDbContext = Context.GetAccountDbContext(accountId);

            // Проверим лимиты
            var limitChecker = AccountLimitsCheckerManager.GetCheckerForAccount(accountId);

            limitChecker.CheckMetricsRequestsPerDay(accountDbContext);

            // Проверим лимит размера хранилища
            var size = data.GetSize();

            limitChecker.CheckStorageSize(accountDbContext, size);

            // получим тип метрики
            var metricType = GetOrCreateType(accountId, data.Name);

            // получим метрику
            var componentId = data.ComponentId.Value;
            var metricInfo  = FindMetric(accountId, componentId, metricType.Id);

            if (metricInfo == null)
            {
                var createMetricLock = LockObject.ForComponent(componentId);
                lock (createMetricLock)
                {
                    metricInfo = FindMetric(accountId, componentId, metricType.Id);
                    if (metricInfo == null)
                    {
                        CreateMetric(accountId, componentId, metricType.Id);
                        metricInfo = FindMetric(accountId, componentId, metricType.Id);
                        if (metricInfo == null)
                        {
                            throw new Exception("Не удалось создать метрику");
                        }
                    }
                }
            }
            using (var metric = AllCaches.Metrics.Write(metricInfo))
            {
                GetActualMetricInternal(metric, processDate);

                // если метрика выключена
                if (metric.CanProcess == false)
                {
                    throw new ResponseCodeException(Zidium.Api.ResponseCode.ObjectDisabled, "Метрика выключена");
                }

                // Рассчитаем цвет
                ObjectColor color;
                string      errorMessage = null;
                try
                {
                    color = GetColor(metricType, metric, data.Value);
                }
                catch (Exception exception)
                {
                    color        = ObjectColor.Red;
                    errorMessage = "Ошибка вычисления цвета метрики:" + exception.Message;
                }

                // Запишем метрику в хранилище
                var status = MonitoringStatusHelper.Get(color);

                // Время актуальности
                var actualTime =
                    metric.ActualTime
                    ?? metricType.ActualTime
                    ?? TimeSpanHelper.FromSeconds(data.ActualIntervalSecs)
                    ?? TimeSpan.FromHours(1);

                var actualDate = processDate + actualTime;
                var statusData = SetMetricValue(metricType, metric, data.Value, processDate, actualDate, status, errorMessage, true);

                limitChecker.AddMetricsRequestsPerDay(accountDbContext);
                limitChecker.AddMetricsSizePerDay(accountDbContext, size);

                metric.BeginSave();
                return(metric);
            }
        }