예제 #1
0
        protected static void UpdateCounters()
        {
            if (RequestsDuration == 0)
            {
                return;
            }
            lock (CounterLockObject)
            {
                RequestsCount++;
                if (CounterTimer.Elapsed.TotalMinutes >= 1)
                {
                    var avgRequestDuration = RequestsDuration / (RequestsCount > 0 ? RequestsCount : 1);
                    var selfPercent        = (RequestsDuration - InvokeDuration) * 100 / RequestsDuration;

                    if (ComponentControl != null)
                    {
                        var actualInterval = TimeSpan.FromHours(1);
                        ComponentControl.SendMetric("Запросов в минуту", RequestsCount, actualInterval);
                        ComponentControl.SendMetric("Мс на запрос", avgRequestDuration, actualInterval);
                        ComponentControl.SendMetric("Процент собственных действий", selfPercent, actualInterval);
                    }

                    RequestsCount    = 0;
                    RequestsDuration = 0;
                    Interlocked.Exchange(ref InvokeDuration, 0);

                    CounterTimer.Restart();
                }
            }
        }
예제 #2
0
    //Array list of components for observer


    // Start is called before the first frame update
    void Start()
    {
        for (int i = 0; i < -1; i++)
        {
            //Randomise position
            GameObject new_piece = new GameObject("Component");

            new_piece.transform.position = new Vector3(Random.Range(-100.0f, 100.0f), 0f, Random.Range(-100.0f, 100.0f));

            ComponentControl new_component = new_piece.AddComponent <ComponentControl>();

            //Load an object (1-3 Thrusters, Hull, Wings) + a subset of the object (1-5 hull1, hull2, hull3...)
            new_component.you_are_a((ComponentControl.Slot)UnityEngine.Random.Range(0, 3), UnityEngine.Random.Range(1, 4));
            Rigidbody r = new_piece.AddComponent <Rigidbody>();
            r.isKinematic = true;
            Collider c = new_piece.AddComponent <BoxCollider>();
            c.isTrigger = true;
        }

        for (int i = 0; i < 20; i++)
        {
            GameObject cargo = new GameObject();
            cargo.transform.position = new Vector3(Random.Range(-100.0f, 100.0f), 0f, Random.Range(-100.0f, 100.0f));
        }//End for
    }
예제 #3
0
 private static void CheckComponentControl()
 {
     if (ComponentControl.IsFake())
     {
         throw new Exception("Component control is fake");
     }
 }
예제 #4
0
    // Start is called before the first frame update
    void Start()
    {
        GameObject new_piece = new GameObject("Dummy Hull");

        new_piece.transform.parent        = transform;
        new_piece.transform.localPosition = new Vector3(1, 0, 1);
        basic_hull = new_piece.AddComponent <ComponentControl>();
        //Load an object (1-3 Thrusters, Hull, Wings) + a subset of the object (1-5 hull1, hull2, hull3...)
        basic_hull.you_are_a(ComponentControl.Slot.Hull, 1);
        basic_hull.transform.localScale = new Vector3(.1f, 0.1f, 0.1f);
        basic_hull.you_are_a_dummy();

        /*
         * GameObject new_piece1 = new GameObject("Dummy Thruster");
         * new_piece1.transform.parent = transform;
         * //new_piece1.transform.localPosition = new Vector3(1, 0, 1);
         * basic_thruster = new_piece.AddComponent<ComponentControl>();
         * basic_thruster.you_are_a(ComponentControl.Slot.Thrusters, 1);
         * basic_thruster.transform.localScale = new Vector3(.1f, 0.1f, 0.1f);
         * basic_thruster.you_are_a_dummy();
         */

        GameObject new_piece2 = new GameObject("Dummy Wing");

        new_piece2.transform.parent        = transform;
        new_piece2.transform.localPosition = new Vector3(1, 0, 1);
        basic_wing = new_piece.AddComponent <ComponentControl>();
        basic_wing.you_are_a(ComponentControl.Slot.Wings, 1);
        basic_wing.transform.localScale = new Vector3(.1f, 0.1f, 0.1f);
        basic_wing.you_are_a_dummy();

        basic_wing.transform.SetParent(basic_hull.transform);
        basic_thruster.transform.SetParent(basic_hull.transform);
    }//End Start
        protected override string GetDebugInfo()
        {
            var output = new StringBuilder();

            output.AppendLine("DispatcherWrapper.Uptime = " + DispatcherWrapper.UptimeTimer.Elapsed);
            output.AppendLine("------------");

            if (ComponentControl.IsFake() == false)
            {
                output.AppendLine("Api.EventManager.GetQueueSize(): " + DataSizeHelper.GetSizeText(ComponentControl.Client.EventManager.GetQueueSize()));
                output.AppendLine("Api.WebLogManager.GetQueueSize(): " + DataSizeHelper.GetSizeText(ComponentControl.Client.WebLogManager.GetQueueSize()));
            }
            output.AppendLine("------------");

            output.AppendLine("");
            foreach (var cache in AllCaches.All)
            {
                output.AppendLine("--- " + cache.GetType() + " ---");
                output.AppendLine("Count: " + cache.Count);
                output.AppendLine("Size: " + DataSizeHelper.GetSizeText(cache.GetSize()));
                output.AppendLine("Changed: " + cache.GetChangedCount());
                output.AppendLine("LastSaveChangesDate: " + cache.GetLastSaveChangesDate());
                output.AppendLine("AddCacheCount: " + cache.AddCacheCount);
                output.AppendLine("AddDataBaseCount: " + cache.AddDataBaseCount);
                output.AppendLine("UpdateCacheCount: " + cache.UpdateCacheCount);
                output.AppendLine("UpdateDataBaseCount: " + cache.UpdateDataBaseCount);
                output.AppendLine("Generation: " + cache.Generation);
                output.AppendLine("LastSaveException: " + GetExceptionTempString(cache.LastSaveException));

                output.AppendLine("");
            }

            return(output.ToString());
        }
        private static void SaveCounters(object obj)
        {
            var threadId = DispatcherService.Wrapper.DeadLockHunter.Add("_SaveCounters_");

            try
            {
                SendCacheMetrics();
                SendMemoryMetrics();

                var avgRequestDuration = RequestsDuration / (RequestsCount > 0 ? RequestsCount : 1);
                var selfPercent        = (RequestsDuration - InvokeDuration) * 100 / (RequestsDuration > 0 ? RequestsDuration : 1);

                var actualInterval = TimeSpan.FromDays(365);
                ComponentControl.SendMetric("Запросов в минуту", RequestsCount, actualInterval);
                ComponentControl.SendMetric("Мс на запрос", avgRequestDuration, actualInterval);
                ComponentControl.SendMetric("Процент собственных действий", selfPercent, actualInterval);

                var stats = ActionsStats.Values.ToArray();
                foreach (var stat in stats)
                {
                    if (stat.Component == null)
                    {
                        stat.Component = ActionStatsFolder.GetOrCreateChildComponentControl("ActionStats", stat.Action);
                        stat.Component.IsFake();
                    }

                    var avgActionDuration = stat.Duration / (stat.Count > 0 ? stat.Count : 1);
                    stat.Component.SendMetric("Мс на запрос", avgActionDuration, actualInterval);
                    stat.Component.SendMetric("Запросов в минуту", stat.Count, actualInterval);
                }

                ComponentControl.SendMetric("Contexts.Account.Active", AccountDbContext.ActiveCount, actualInterval);
                ComponentControl.SendMetric("Contexts.Account.Max", AccountDbContext.MaxActiveCount, actualInterval);

                lock (CounterLockObject)
                {
                    RequestsCount    = 0;
                    RequestsDuration = 0;

                    foreach (var stat in stats)
                    {
                        stat.Count    = 0;
                        stat.Duration = 0;
                    }
                }

                Interlocked.Exchange(ref InvokeDuration, 0);
            }
            catch (Exception exception)
            {
                LogManager.GetCurrentClassLogger().Fatal(exception);
            }
            finally
            {
                DispatcherService.Wrapper.DeadLockHunter.Remove(threadId);
                _saveCountersTimer = new Timer(SaveCounters, _saveCountersTimer, TimeSpan.FromMinutes(1), TimeSpan.FromMilliseconds(-1));
            }
        }
예제 #7
0
    // Update is called once per frame
    void Update()
    {
        //This script acts as a basic animation, droping a ship component onto a ship
        if (Input.GetKey(KeyCode.Space))
        {
            ComponentControl x = FindObjectOfType <ComponentControl>();

            x.lock_in_place_to(transform);
        }
    }
예제 #8
0
        public SendEventResponse Send()
        {
            if (ComponentControl.IsFake())
            {
                return(ResponseHelper.GetOfflineResponse <SendEventResponse>());
            }

            var client = (Client)ComponentControl.Client;

            return(client.SendEventWrapper(this));
        }
예제 #9
0
 public void Add(MyDefinitionId id, double val1, double val2, MyFontEnum font)
 {
     var control = new ComponentControl(id);
     control.Size            = new Vector2(Size.X - m_padding.HorizontalSum, control.Size.Y);
     m_currentOffsetFromTop += control.Size.Y;
     control.Position        = -0.5f * Size + new Vector2(m_padding.Left, m_currentOffsetFromTop);
     control.OriginAlign     = MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_BOTTOM;
     control.ValuesFont      = font;
     control.SetValues(val1, val2);
     Elements.Add(control);
 }
 public void Add(MyDefinitionId id, double val1, double val2, MyFontEnum font)
 {
     var control = new ComponentControl(id);
     control.Size            = new Vector2(Size.X - m_padding.HorizontalSum, control.Size.Y);
     m_currentOffsetFromTop += control.Size.Y;
     control.Position        = -0.5f * Size + new Vector2(m_padding.Left, m_currentOffsetFromTop);
     control.OriginAlign     = MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_BOTTOM;
     control.ValuesFont      = font;
     control.SetValues(val1, val2);
     Elements.Add(control);
 }
        private static void SendMemoryMetrics()
        {
            var actualInterval = TimeSpan.FromDays(365);

            var workingSetSize = Environment.WorkingSet / 1024 / 1024;

            ComponentControl.SendMetric("Memory Working Set, Mb", workingSetSize, actualInterval);

            var managedSize = GC.GetTotalMemory(false) / 1024 / 1024;

            ComponentControl.SendMetric("Memory Managed, Mb", managedSize, actualInterval);
        }
        // "Add component" button click event
        private void ComponentButtonClick(object sender, RoutedEventArgs e)
        {
            ComponentControl userControl = new ComponentControl();

            Window window = new Window
            {
                Title   = "Select Component",
                Content = userControl,
                Height  = 450,
                Width   = 330,
                //SizeToContent = SizeToContent.WidthAndHeight
            };

            window.ShowDialog();
        }
예제 #13
0
        protected void UnloadDataLoop()
        {
            try
            {
                // выгружаем только если превышен порог
                if (Count < BeginUnloadCount)
                {
                    return;
                }

                // удаляем лишние
                bool hasUnloaded = false;
                int  doCount     = 0;
                int  count       = Count;
                while (count > StopUnloadCount)
                {
                    doCount++;
                    int tryUnloadCount = count - StopUnloadCount;
                    int unloaded       = UnloadOldData(tryUnloadCount);
                    if (unloaded > 0)
                    {
                        hasUnloaded = true;
                    }
                    count = Count;
                }

                // обновим статистику
                if (hasUnloaded)
                {
                    _generation++;
                }
            }
            catch (ThreadAbortException)
            {
            }
            catch (Exception exception)
            {
                ComponentControl.Log.Error("Ошибка UnloadDataLoop", exception);
                ComponentControl.AddApplicationError("Ошибка UnloadDataLoop", exception);
            }
        }
예제 #14
0
 /// <summary>
 /// Сохраняет изменения в бесконечном цикле пока есть хоть 1 изменение
 /// </summary>
 protected void SaveChangesLoop()
 {
     try
     {
         while (true)
         {
             int count = SaveChanges();
             if (count == 0)
             {
                 return;
             }
         }
     }
     catch (ThreadAbortException)
     {
     }
     catch (Exception exception)
     {
         _lastSaveException = new ExceptionTempInfo(exception);
         ComponentControl.Log.Error("Ошибка SaveChangesLoop", exception);
         ComponentControl.AddApplicationError(exception);
     }
 }
예제 #15
0
        protected override string GetDebugInfo()
        {
            var output = new StringBuilder();

            if (ComponentControl == null)
            {
                output.AppendLine("ComponentControl is NULL");
            }
            else
            {
                output.AppendLine("ComponentControl.IsFake()=" + ComponentControl.IsFake());
            }
            output.AppendLine("DispatcherService.Wrapper.RunTime = " + RunTime);
            output.AppendLine("DispatcherService.Wrapper.RunException = " + GetExceptionTempString(RunException));

            // проверка связи с диспетчером
            var adapter  = CreateAdapter("127.0.0.1", "system");
            var response = adapter.GetServerTime();

            output.AppendLine("GetServerTime = " + (response.Success ? response.Data.Date.ToString() : response.ErrorMessage));

            return(output.ToString());
        }
예제 #16
0
 internal void you_are_now_carrying(ComponentControl componentControl)
 {
     I_am_carrying = componentControl;
 }
        protected override void AddList(List <TWriteObject> writeObjects)
        {
            var accountGroups = writeObjects.GroupBy(x => x.AccountId);

            foreach (var accountGroup in accountGroups)
            {
                var accountId = accountGroup.Key;

                int batchCount = 100;

                // получим пачки
                var batchGroups = accountGroup
                                  .OrderBy(x => x.SaveOrder)
                                  .Select((x, index) => new
                {
                    Batch       = index / batchCount,
                    WriteObject = x
                })
                                  .GroupBy(x => x.Batch);

                foreach (var batchGroup in batchGroups)
                {
                    var batchItems = batchGroup.ToList();

                    var batch = batchItems
                                .Select(x => x.WriteObject)
                                .ToList();

                    // делаем N попыток
                    int  attemps  = 0;
                    bool chackAdd = false; // не проверять сущществование объектов перед вставкой
                    while (true)
                    {
                        attemps++;
                        try
                        {
                            AddBatch(accountId, batch, chackAdd);
                            _addDataBaseCount += batch.Count;

                            // отправим событие
                            var saveEvent = ComponentControl.CreateComponentEvent("AddBatch");
                            saveEvent.SetImportance(EventImportance.Success);
                            saveEvent.SetJoinInterval(TimeSpan.FromMinutes(1));
                            saveEvent.Add();

                            break;
                        }
                        catch (Exception exception)
                        {
                            // отправим событие
                            var errorEvent = ComponentControl.CreateApplicationError("AddBatchError", exception);
                            errorEvent.SetImportance(EventImportance.Alarm);
                            errorEvent.SetJoinInterval(TimeSpan.FromMinutes(1));
                            errorEvent.Add();

                            if (attemps >= 100)
                            {
                                throw;
                            }
                            chackAdd = true;
                            ComponentControl.Log.Error("Ошибка AddBatch. Попытка " + attemps, exception);
                            Thread.Sleep(TimeSpan.FromSeconds(10));
                        }
                    }

                    Interlocked.Increment(ref AddBatchCount);

                    // обновим статистику
                    foreach (var batchItem in batch)
                    {
                        SetResponseSaved(batchItem);
                    }
                }
            }
        }
예제 #18
0
        protected override void UpdateList(List <TWriteObject> writeObjects)
        {
            const int batchCount = 100; //todo

            var accountGroups = writeObjects.GroupBy(x => x.AccountId);

            foreach (var accountGroup in accountGroups)
            {
                var accountId = accountGroup.Key;

                // получим пачки
                var batchGroups = accountGroup
                                  .OrderBy(x => x.SaveOrder)
                                  .Select((x, index) => new
                {
                    Batch       = index / batchCount,
                    WriteObject = x
                })
                                  .GroupBy(x => x.Batch);

                foreach (var batchGroup in batchGroups)
                {
                    var batchItems = batchGroup.ToList();

                    // сохраним пачку
                    var batch = batchItems
                                .Select(x => x.WriteObject)
                                .ToList();

                    // делаем N попыток
                    int  attemps  = 0;
                    bool useCheck = false;
                    while (true)
                    {
                        attemps++;
                        try
                        {
                            UpdateBatch(accountId, batch, useCheck);
                            _updateDataBaseCount += batch.Count;

                            // отправим событие
                            var saveEvent = ComponentControl.CreateComponentEvent("UpdateBatch");
                            saveEvent.SetImportance(Zidium.Api.EventImportance.Success);
                            saveEvent.SetJoinInterval(TimeSpan.FromMinutes(1));
                            saveEvent.Add();

                            break;
                        }
                        catch (Exception exception)
                        {
                            // отправим событие
                            var errorEvent = ComponentControl.CreateApplicationError("UpdateBatchError", exception);
                            errorEvent.SetImportance(Zidium.Api.EventImportance.Alarm);
                            errorEvent.SetJoinInterval(TimeSpan.FromMinutes(1));
                            errorEvent.Add();

                            useCheck = true;
                            if (attemps >= 50)
                            {
                                throw;
                            }
                            ComponentControl.Log.Error("Ошибка UpdateBatch. Попытка " + attemps, exception);
                            Thread.Sleep(TimeSpan.FromSeconds(10));
                        }
                    }

                    Interlocked.Increment(ref UpdateBatchCount);

                    // обновим статистику
                    foreach (var batchItem in batch)
                    {
                        SetResponseSaved(batchItem);
                    }
                }
            }
        }