Пример #1
0
 DataService()
 {
     roadInformation     = new RoadInformation();
     boothInformation    = new BoothInformation();
     agentInformation    = new AgentInformation();
     contactsInformation = new ContactsInformation();
 }
Пример #2
0
 public void RunChildDecision(AgentInformation agentInformation, bool value)
 {
     if (value)
     {
         if (TrueNode != null)
         {
             TrueNode.MakeDecision(agentInformation);
             return;
         }
         else if (TrueAction != null)
         {
             TrueAction.TakeAction(agentInformation);
             return;
         }
     }
     else
     {
         if (FalseNode != null)
         {
             FalseNode.MakeDecision(agentInformation);
             return;
         }
         else if (FalseAction != null)
         {
             FalseAction.TakeAction(agentInformation);
             return;
         }
     }
     Debug.Log("No Further Decisions Or Actions!");
 }
        private void AddProviderAgent(AgentInformation agentInfo, ProviderState state)
        {
            string name            = agentInfo.DisplayData.ShortName;
            var    indexAndTooltip = _providerStatesIconIndexAndTooltip[state];

            var item = new ListViewItem(name);

            item.Name      = name;
            item.ForeColor = Color.Yellow;
            item.UseItemStyleForSubItems = true;

            item.ToolTipText = string.Format("{0} - {1} ({2})", agentInfo.PeerNode.Description, agentInfo.DisplayData.Name, indexAndTooltip.ToolTipText);

            if (!agentInfo.Contracts.Contains(typeof(IProviderAgent).AssemblyQualifiedName))
            {
                item.ImageIndex = indexAndTooltip.OperationalIconIndex;
            }
            else
            {
                item.ImageIndex = indexAndTooltip.ProviderIconIndex;
            }

            lvwProviderAgents.Items.Add(item);
            lvwProviderAgents.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
        }
Пример #4
0
        public async Task AgentOfflineShouldCheckStatusAndReImage()
        {
            //Arrange
            var log = new Mock <ILogger>();

            var mockHttp   = new MockHttpMessageHandler();
            var getRequest = mockHttp.When(HttpMethod.Get, "https://management.azure.com/subscriptions/f13f81f8-7578-4ca8-83f3-0a845fad3cb5/resourceGroups/*/providers/Microsoft.Compute/virtualMachineScaleSets/agents/virtualmachines/*/instanceView?api-version=2018-06-01")
                             .Respond("application/json", "{ \"placementGroupId\": \"f79e82f0-3480-4eb3-a893-5cf9bd74daad\", \"platformUpdateDomain\": 0, \"platformFaultDomain\": 0, \"computerName\": \"agents2q3000000\", \"osName\": \"ubuntu\", \"osVersion\": \"18.04\", \"vmAgent\": { \"vmAgentVersion\": \"2.2.36\", \"statuses\": [ { \"code\": \"ProvisioningState/succeeded\", \"level\": \"Info\", \"displayStatus\": \"Ready\", \"message\": \"Guest Agent is running\", \"time\": \"2019-02-22T08:15:48+00:00\" } ], \"extensionHandlers\": [] }, \"disks\": [ { \"name\": \"agents_agents_0_OsDisk_1_3009fa8e43e144029be77cd72065f6df\", \"statuses\": [ { \"code\": \"ProvisioningState/succeeded\", \"level\": \"Info\", \"displayStatus\": \"Provisioning succeeded\", \"time\": \"2019-02-06T11:45:35.5975265+00:00\" } ] } ], \"statuses\": [ { \"code\": \"ProvisioningState/succeeded\", \"level\": \"Info\", \"displayStatus\": \"Provisioning succeeded\", \"time\": \"2019-02-06T11:46:58.0511995+00:00\" }, { \"code\": \"PowerState/running\", \"level\": \"Info\", \"displayStatus\": \"VM running\" } ] } ");

            var postRequest = mockHttp.When(HttpMethod.Post, "https://management.azure.com/subscriptions/f13f81f8-7578-4ca8-83f3-0a845fad3cb5/resourceGroups/*/providers/Microsoft.Compute/virtualMachineScaleSets/agents/virtualmachines/*/reimage?api-version=2018-06-01")
                              .Respond(HttpStatusCode.OK);

            var agentInfo = new AgentInformation("rg", 0);


            var tokenProvider = new Intercept <AzureServiceTokenProvider>();

            tokenProvider
            .Setup(x => x.GetAccessTokenAsync(Arg.Ignore <string>(), null))
            .Returns(string.Empty);

            //Act
            await AgentPoolScanFunction.ReImageAgent(log.Object, agentInfo, mockHttp.ToHttpClient(), tokenProvider);

            //Assert

            //check if queried status
            mockHttp.GetMatchCount(getRequest).Should().Be(1);

            //check if reimage called
            mockHttp.GetMatchCount(postRequest).Should().Be(1);
        }
Пример #5
0
        /// <summary>
        /// Метод взаимодействия агента с диспетчером заданий.
        /// </summary>
        /// <param name="address">
        /// Адресс узла диспетчера заданий.
        /// </param>
        /// <param name="port">
        /// Порт указанного узла диспетчера заданий.
        /// </param>
        public static void Interworking(string address, int port)
        {
            TcpClient tcpClient = null;
            Agent     agent     = new Agent();

            bool isConcted = false;

            Console.WriteLine("Попытка подключиться к {0}:{1}", address, port);
            // Цикл бесконечных попыток подключения к диспетчеру заданий.
            while (true)
            {
                try
                {
                    tcpClient = new TcpClient(address, port);
                    NetworkStream networkStream = tcpClient.GetStream();    // Базовый поток данных для доступа к сети.
                    byte[]        data          = new byte[128];            // Буфер для получаемых/отправляемых данных.

                    isConcted = true;
                    Console.WriteLine("Установлено соединение {0}:{1}", address, port);

                    // Отправляем диспетчеру задач информацию об агенте.
                    AgentInformation agentInfo = new AgentInformation(agent.GetCores(), agent.GetProductivity());
                    data = Encoding.Unicode.GetBytes(agentInfo.Serealize());
                    networkStream.Write(data, 0, data.Length);

                    while (true)
                    {
                        // Получаем задание от диспетчера заданий.
                        string taskStr = GetStrFromStream(networkStream);
                        Task   task    = Task.Deserealize(taskStr);

                        // Обрабатываем задание.
                        string initialString = ParallelComputing(task);

                        // Отправляем результаты обработки задания диспетчеру заданий.
                        data = Encoding.Unicode.GetBytes(initialString);
                        networkStream.Write(data, 0, data.Length);
                    }
                }
                catch (Exception)
                {
                    if (isConcted)
                    {
                        Console.WriteLine("Попытка подключиться к {0}:{1}", address, port);
                    }

                    isConcted = false;
                }
                finally
                {
                    if (tcpClient != null)
                    {
                        tcpClient.Close();
                    }
                }

                // Задержка перед очередной попыткой подключения к серверу.
                Thread.Sleep(5000);
            }
        }
Пример #6
0
 public override void MakeDecision(AgentInformation agentInformation)
 {
     if (agentInformation.mAgentEnergy > 15)
     {
         RunChildDecision(agentInformation, true);
     }
     else
     {
         RunChildDecision(agentInformation, false);
     }
 }
Пример #7
0
    private IEnumerator Die(GameObject dyingAgent)
    {
        AgentInformation agentInfo = dyingAgent.GetComponent <AgentInformation>();

        WeaponInventory weaponScript = dyingAgent.GetComponent <WeaponInventory>();
        int             lostWeapon   = weaponScript.LoseWeapon(); //lose one weapon at random

        if (lostWeapon > -1)
        {
            GetComponent <WeaponDropManager>().CreateDrop(dyingAgent.transform, lostWeapon);        //create weapon drop close to player transform
        }

        weaponScript.SetDead(true);
        setComponents(dyingAgent, false);

        Animator animator = dyingAgent.GetComponentInChildren <Animator>();
        int      dieHash  = Animator.StringToHash("DeathFromFront");

        // Play
        animator.ResetTrigger("Respawn");
        animator.SetTrigger("Die");
        // Wait until animation starts
        while (animator.GetCurrentAnimatorStateInfo(0).shortNameHash != dieHash)
        {
            yield return(null);
        }

        //Now wait until the current state is done playing
        float waitTime = animator.GetCurrentAnimatorStateInfo(0).length;

        yield return(new WaitForSeconds(waitTime));

        yield return(new WaitForSeconds(agentInfo.TimeToRespawn));


        //respawn

        //reset position, animator, health
        animator.ResetTrigger("Die");
        animator.SetTrigger("Respawn");
        dyingAgent.transform.position = agentInfo.SpawnLocation;

        yield return(new WaitForSeconds(RespawnCooldownTime));

        setComponents(dyingAgent, true);

        weaponScript.InstantiateActiveWeapon();
        weaponScript.SetDead(false);

        dyingAgent.GetComponent <Health>().ResetHealth();

        yield break;
    }
Пример #8
0
        /// <summary>
        /// Метод обработки конкретного клиента в отдельном потоке.
        /// </summary>
        public void Process()
        {
            NetworkStream networkStream = null; // Базовый поток данных для доступа к сети.
            Task          task          = null; // Отправляемое задание.

            try
            {
                networkStream = _client.GetStream();

                // Получаем информацию о подключённом агенте.
                string           agentInfoStr = GetStrFromStream(networkStream);
                AgentInformation agentInfo    = AgentInformation.Deserealize(agentInfoStr);

                // ???????
                long taskSize = agentInfo.CoresCount * agentInfo.PasswordPerSecond * 5;

                while (_taskManager.GetTask(taskSize, ref task))
                {
                    // Отправляем задание агенту.
                    byte[] data = Encoding.Unicode.GetBytes(task.Serealize());
                    networkStream.Write(data, 0, data.Length);

                    // Получаем результат работы агента.
                    string password = GetStrFromStream(networkStream);

                    // Обрабатываем результат работы агента.
                    if (password != "----------")
                    {
                        _taskManager.PasswordFound(password);
                    }
                }
            }
            catch (Exception)
            {
                // Отправляем диспетчеру задач задание, во время
                // выполнения которого агент завершил свою работу.
                _taskManager.PushTask(task);
            }
            finally
            {
                if (networkStream != null)
                {
                    networkStream.Close();
                }

                if (_client != null)
                {
                    _client.Close();
                }
            }
        }
Пример #9
0
    public string GetAgentMoveInfo(string agentTag)
    {
        var agentInfo = new AgentInformation();

        agentInfo.agentName = agentTag;
        var agentGO = Array.Find(agents, x => x.tag == agentTag);

        agentInfo.agPosV3         = agentGO.transform.position.ToString("f3");
        agentInfo.agRotV3         = agentGO.transform.eulerAngles.ToString("f3");
        agentInfo.currentCardInfo = GetCardInformation();
        agentInfo.eyesightInfo    = GetEyesightObjs(agentTag);

        return(JsonUtility.ToJson(agentInfo));
    }
Пример #10
0
    private void setComponents(GameObject agent, bool enabled)
    {
        AgentInformation agentInfo = agent.GetComponent <AgentInformation>();

        if (agentInfo.IsPlayer)
        {
            agent.GetComponent <Attack>().enabled   = enabled;
            agent.GetComponent <Movement>().enabled = enabled;
            agent.GetComponent <FallDown>().enabled = enabled;
        }
        else
        {
            // Disable NavMesh, AISimpleAttack, stateMachine
            agent.GetComponent <AISimpleAttack>().enabled = enabled;
            //agent.GetComponent<NavMeshAgent>().enabled = enabled;
        }
        //agent.GetComponent<WeaponInventory>().enabled = enabled;      //weaponInventory needs to be enable so to handle the drops and the deselection of the lost wpn
    }
Пример #11
0
    private void Start()
    {
        mAgentDecisionTree = new BasicEnemyDecisionTree("Basic Enemy Decision Tree");
        mAgentDecisionTree.SetUpDecisionTree();

        AgentInformation agentInformation = new AgentInformation();

        agentInformation.mAgentHealth = 5;
        agentInformation.mAgentEnergy = 20;

        Debug.Log("Agent Health: " + agentInformation.mAgentHealth + "        Agent Energy: " + agentInformation.mAgentEnergy);

        mAgentDecisionTree.mRoot.MakeDecision(agentInformation);

        Debug.Log("Agent Health: " + agentInformation.mAgentHealth + "        Agent Energy: " + agentInformation.mAgentEnergy);

        mAgentDecisionTree.mRoot.MakeDecision(agentInformation);

        Debug.Log("Agent Health: " + agentInformation.mAgentHealth + "        Agent Energy: " + agentInformation.mAgentEnergy);
    }
        private void UpdateProviderAgent(AgentInformation agentInfo, ProviderState state)
        {
            string name = agentInfo.DisplayData.ShortName;

            var item = lvwProviderAgents.Items.Find(name, true).FirstOrDefault();

            if (item != null)
            {
                var indexAndTooltip = _providerStatesIconIndexAndTooltip[state];

                item.ToolTipText = string.Format("{0} - {1} ({2})", agentInfo.PeerNode.Description, agentInfo.DisplayData.Name, indexAndTooltip.ToolTipText);

                if (!agentInfo.Contracts.Contains(typeof(IProviderAgent).AssemblyQualifiedName))
                {
                    item.ImageIndex = indexAndTooltip.OperationalIconIndex;
                }
                else
                {
                    item.ImageIndex = indexAndTooltip.ProviderIconIndex;
                }
            }
        }
        public static async System.Threading.Tasks.Task ReImageAgent(ILogger log, AgentInformation agentInfo, HttpClient client, IUnmockable <AzureServiceTokenProvider> tokenProvider)
        {
            var accessToken = await tokenProvider.Execute(x => x.GetAccessTokenAsync("https://management.azure.com/", null)).ConfigureAwait(false);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            var agentStatusJson = await client.GetStringAsync($"https://management.azure.com/subscriptions/f13f81f8-7578-4ca8-83f3-0a845fad3cb5/resourceGroups/{agentInfo.ResourceGroup}/providers/Microsoft.Compute/virtualMachineScaleSets/agents/virtualmachines/{agentInfo.InstanceId}/instanceView?api-version=2018-06-01");

            dynamic status = JObject.Parse(agentStatusJson);

            if (status.statuses[0].code == "ProvisioningState/updating")
            {
                log.LogInformation($"Agent already being re-imaged: {agentInfo.ResourceGroup} - {agentInfo.InstanceId}");
                return;
            }

            log.LogInformation($"Re-image agent: {agentInfo.ResourceGroup} - {agentInfo.InstanceId}");
            var result = await client.PostAsync($"https://management.azure.com/subscriptions/f13f81f8-7578-4ca8-83f3-0a845fad3cb5/resourceGroups/{agentInfo.ResourceGroup}/providers/Microsoft.Compute/virtualMachineScaleSets/agents/virtualmachines/{agentInfo.InstanceId}/reimage?api-version=2018-06-01", new StringContent(""));

            if (!result.IsSuccessStatusCode)
            {
                throw new Exception($"Error Re-imaging agent: {agentInfo.ResourceGroup} - {agentInfo.InstanceId}");
            }
        }
Пример #14
0
 public abstract void TakeAction(AgentInformation agentInformation);
Пример #15
0
 public override void TakeAction(AgentInformation agentInformation)
 {
     Debug.Log("Trading Energy For Health!");
     agentInformation.mAgentEnergy -= 10;
     agentInformation.mAgentHealth += 10;
 }
Пример #16
0
        public AgentInformation AgentInformations()
        {
            if (Request.Headers["User-Agent"] != null)
            {
                string DeviceType = string.Empty;
                string DeviceName = string.Empty;
                //Session.Add("Mobile",false);

                if (Request.Browser["IsMobileDevice"] != null && Request.Browser["IsMobileDevice"] == "true")
                {
                    Session.Add("Device", "iPhone");
                    // MOBILE DEVICE DETECTED --------------------------------------
                    DeviceType = "Mobile Device";

                    // CHECK USER AGENTS STRINGS FIRST --------------------------------

                    if (Request.UserAgent.ToLower().Contains("windows"))
                    {
                        DeviceName = "Windows Mobile";
                    }
                    else if (Request.UserAgent.ToUpper().Contains("MIDP") || Request.UserAgent.ToUpper().Contains("CLDC"))
                    {
                        DeviceName = "Other";
                    }
                    else if (Request.UserAgent.ToLower().Contains("psp") || Request.UserAgent.ToLower().Contains("playstation portable"))
                    {
                        DeviceName = "Sony PSP";
                    }
                }
                else if (Request.UserAgent.ToLower().Contains("blackberry"))
                {
                    // DOES NOT IDENTIFY ITSELF AS A MOBILE DEVICE
                    // RIM DEVICES (BlackBerry) -------------
                    DeviceType = "Mobile Device";
                    DeviceName = "BlackBerry";
                    Session.Add("Device", "iPhone");
                }
                else if (Request.UserAgent.Contains("Android"))
                {
                    // DOES NOT IDENTIFY ITSELF AS A MOBILE DEVICE
                    // RIM DEVICES (BlackBerry) -------------
                    DeviceType = "Mobile Device";
                    DeviceName = "Android";
                    Session.Add("Device", "iPhone");
                }
                else if (Request.UserAgent.Contains("iPhone"))
                {
                    // DOES NOT IDENTIFY ITSELF AS A MOBILE DEVICE

                    // IPHONE/IPOD DEVICES ------------------
                    DeviceType = "Mobile Device";
                    DeviceName = "iPhone";
                    Session.Add("Device", "iPhone");
                }
                else
                {
                    // NOT A MOBILE DEVICE
                    DeviceType = "NOT a Mobile Device";
                    Session.Add("Device", "No");
                }
            }



            // SPIT OUT A BUNCH OF STUFF -----------------------------------------
            System.Web.HttpBrowserCapabilitiesBase browser = Request.Browser;

            AgentInformation aInformation = new AgentInformation();

            aInformation._Type               = browser.Type;
            aInformation._Name               = browser.Browser;
            aInformation._Majorversion       = browser.MajorVersion.ToString();
            aInformation._MinorVersion       = browser.MinorVersion.ToString();
            aInformation._Platform           = browser.Platform;
            aInformation._IsBeta             = browser.Beta.ToString();
            aInformation._IsCrawler          = browser.Crawler.ToString();
            aInformation._IsAol              = browser.AOL.ToString();
            aInformation._IsWin16            = browser.Win16.ToString();
            aInformation._IsWin32            = browser.Win32.ToString();
            aInformation._SupportFrames      = browser.Frames.ToString();
            aInformation._SupportTables      = browser.Tables.ToString();
            aInformation._SupportCookies     = browser.Cookies.ToString();
            aInformation._SupportVBScrpt     = browser.VBScript.ToString();
            aInformation._SupportJS          = browser.EcmaScriptVersion.ToString();
            aInformation._SupportJavaApplets = browser.JavaApplets.ToString();
            aInformation._SupportActiveX     = browser.ActiveXControls.ToString();

            // SPIT OUT THE WHOLE USER AGENT --------------------------------------------
            var DeviceAgent = Session["Device"];

            ViewData["DeviceAgent"] = DeviceAgent;

            ViewData["AgentInformation"] = aInformation;
            return(aInformation);
        }
Пример #17
0
 public abstract void MakeDecision(AgentInformation agentInformation);
Пример #18
0
 public AgentService(AgentInformation agentEndPoint)
 {
     _agentInformations = agentEndPoint;
 }
        public void AddAgent(AgentInformation agentInformation)
        {
            var client = new AgentClient(agentInformation.Url, loggerFactory.CreateLogger <AgentClient>());

            Agents.Add(client);
        }