Example #1
0
        public async Task Register(AgentRecord agentRecord, CancellationToken token = default)
        {
            agentRecord.VerifyNotNull(nameof(agentRecord));
            _logger.LogTrace($"{nameof(Register)}: agentId={agentRecord.Id}, state={agentRecord.State}");

            await _agentContainer.Set(agentRecord, token : token);
        }
Example #2
0
        public async Task GiveOneAgentsAddingTargets_WhenGetAssignments_CorrectTargetsShouldBeReturned()
        {
            // Arrange
            IWatcherRepository watcherRepository = new CosmosWatcherRepository(_watcherOption, _loggerFactory);
            await watcherRepository.Database.Delete(_databaseName, CancellationToken.None);

            await watcherRepository.InitializeContainers();

            IRecordContainer <TargetRecord> targetContainer = await watcherRepository.Container.Create <TargetRecord>();

            targetContainer.Should().NotBeNull();

            IAgentController agentController = new AgentController(_watcherOption, watcherRepository, _loggerFactory.CreateLogger <AgentController>());

            // Act
            const int   max         = 10;
            AgentRecord agentRecord = await agentController.CreateTestAgent(1);

            foreach (int targetCount in Enumerable.Range(1, max))
            {
                await targetContainer.CreateTestTarget(targetCount);

                await agentController.LoadBalanceAssignments();

                IReadOnlyList <TargetRecord> assignments = await targetContainer.GetAssignments(agentRecord.Id, _loggerFactory.CreateLogger <TargetRecord>());

                assignments.Count.Should().BeGreaterThan(targetCount);
            }

            // Clean up
            await watcherRepository.Database.Delete(_databaseName, CancellationToken.None);
        }
Example #3
0
        public async Task GivenOneAgentswithNoTargets_WhenGetAssignments_NoTargetsReturn()
        {
            // Arrange
            IWatcherRepository watcherRepository = new CosmosWatcherRepository(_watcherOption, _loggerFactory);
            await watcherRepository.Database.Delete(_databaseName);

            await watcherRepository.InitializeContainers();

            IAgentController agentController = new AgentController(_watcherOption, watcherRepository, _loggerFactory.CreateLogger <AgentController>());

            agentController.Should().NotBeNull();
            AgentRecord agentRecord = await agentController.CreateTestAgent(1);

            IRecordContainer <TargetRecord> targetContainer = await watcherRepository.Container.Create <TargetRecord>();

            targetContainer.Should().NotBeNull();


            // Act
            await agentController.LoadBalanceAssignments();

            IReadOnlyList <TargetRecord> targetRecords = await targetContainer.GetAssignments(agentRecord.Id, _loggerFactory.CreateLogger <TargetRecord>());

            // Assert
            targetRecords.Should().NotBeNull();
            targetRecords.Count.Should().Be(0);

            // Clean up
            await watcherRepository.Database.Delete(_databaseName);
        }
Example #4
0
        public static bool IsAgentRunning(this AgentRecord agentRecord, TimeSpan offlineTolerance)
        {
            agentRecord.VerifyNotNull(nameof(agentRecord));

            return(agentRecord.State == AgentState.Running &&
                   DateTime.UtcNow - agentRecord.UtcHeartbeat <= offlineTolerance);
        }
        public void Register(RemoteTestAgent agent, int pid)
        {
            AgentRecord r = agentData[pid];

            if (r == null)
            {
                throw new ArgumentException("Specified process is not in the agency database", "pid");
            }
            r.Agent = agent;
        }
        public void ReportStatus(int pid, AgentStatus status)
        {
            AgentRecord r = agentData[pid];

            if (r == null)
            {
                throw new ArgumentException("Specified process is not in the agency database", "pid");
            }

            r.Status = status;
        }
Example #7
0
        public void AddAgent(Guid agentId, Process process)
        {
            lock (_agentsById)
            {
                if (_agentsById.ContainsKey(agentId))
                {
                    throw new ArgumentException($"An agent has already been started with the ID '{agentId}'.", nameof(agentId));
                }

                _agentsById.Add(agentId, AgentRecord.Starting(process));
            }
        }
Example #8
0
        public void Register(TestAgent agent)
        {
            AgentRecord r = agentData[agent.Id];

            if (r == null)
            {
                throw new ArgumentException(
                          string.Format("Agent {0} is not in the agency database", agent.Id),
                          "agentId");
            }
            r.Agent = agent;
        }
Example #9
0
        public static async Task <AgentRecord> CreateTestAgent(this IAgentController container, int index)
        {
            var agentRecord = new AgentRecord
            {
                Id    = $"Agent.{index}",
                State = AgentState.Running,
            };

            await container.Register(agentRecord, CancellationToken.None);

            return(agentRecord);
        }
Example #10
0
        public void AddAgent(Guid agentId, Process process)
        {
            lock (LOCK)
            {
                if (_agentIndex.ContainsKey(agentId))
                {
                    throw new ArgumentException($"An agent has already been started with the ID '{agentId}'.", nameof(agentId));
                }

                _agentIndex[agentId] = _processIndex[process] = AgentRecord.Starting(agentId, process);
            }
        }
Example #11
0
        private void CreateAgentTemplate(int index, string file)
        {
            var record = new AgentRecord
            {
                Id           = $"Agent_{index}",
                State        = AgentState.Running,
                UtcHeartbeat = DateTime.UtcNow,
            };

            File.WriteAllText(file, _json.SerializeFormat(record));
            _logger.LogInformation($"Create json template {file} for Agent");
        }
        public void DestroyAgent(TestAgent agent)
        {
            AgentRecord r = agentData[agent.Id];

            if (r != null)
            {
                if (!r.Process.HasExited)
                {
                    r.Agent.Stop();
                }
                agentData[r.Process.Id] = null;
            }
        }
Example #13
0
        public void ReportStatus(Guid agentId, AgentStatus status)
        {
            AgentRecord r = agentData[agentId];

            if (r == null)
            {
                throw new ArgumentException(
                          string.Format("Agent {0} is not in the agency database", agentId),
                          "agentId");
            }

            r.Status = status;
        }
        public async Task GivenAgent_WhenRegistgeredAndStateIsChange_ShouldSucceed()
        {
            // Arrange
            IWatcherRepository watcherRepository = new CosmosWatcherRepository(_watcherOption, _loggerFactory);
            await watcherRepository.Database.Delete(_databaseName);

            await watcherRepository.InitializeContainers();

            IRecordContainer <AgentRecord> container = await watcherRepository.Container.Create <AgentRecord>();

            container.Should().NotBeNull();

            IAgentController agentController = new AgentController(_watcherOption, watcherRepository, _loggerFactory.CreateLogger <AgentController>());

            // Act - verify agent is not register
            const string agentName = "Agent.1";

            // Act - register agent and verify
            var agentRecord = new AgentRecord
            {
                Id    = agentName,
                State = AgentState.Running,
            };

            await agentController.Register(agentRecord);

            (await container.Exist(agentName)).Should().BeTrue();

            Record <AgentRecord>?record = await container.Get(agentName, token : CancellationToken.None);

            record.Should().NotBeNull();
            (record !.Value == agentRecord).Should().BeTrue();

            await agentController.SetState(agentName, AgentState.Stopped);

            agentRecord.State = AgentState.Stopped;

            record = await container.Get(agentName, token : CancellationToken.None);

            record.Should().NotBeNull();
            (record !.Value == agentRecord).Should().BeTrue();

            // Act - Un-register agent
            await agentController.UnRegister(agentName);

            (await container.Exist(agentName)).Should().BeFalse();

            // Clean up
            await watcherRepository.Database.Delete(_databaseName);
        }
        public void ReleaseAgent(TestAgent agent)
        {
            AgentRecord r = agentData[agent.Id];

            if (r == null)
            {
                NTrace.Error(string.Format("Unable to release agent {0} - not in database", agent.Id));
            }
            else
            {
                r.Status = AgentStatus.Ready;
                NTrace.Debug("Releasing agent " + agent.Id.ToString());
            }
        }
            public AgentRecord this[RemoteTestAgent agent]
            {
                get
                {
                    foreach (System.Collections.DictionaryEntry entry in agentData)
                    {
                        AgentRecord r = (AgentRecord)entry.Value;
                        if (r.Agent == agent)
                        {
                            return(r);
                        }
                    }

                    return(null);
                }
            }
Example #17
0
        public async Task GivenAgent_WhenRoundTrip_ShouldSucceed()
        {
            // Arrange
            IWatcherRepository watcherRepository = new CosmosWatcherRepository(_watcherOption, _loggerFactory);
            await watcherRepository.Database.Delete(_databaseName, CancellationToken.None);

            IRecordContainer <AgentRecord> container = await watcherRepository.Container.Create <AgentRecord>(_databaseName);

            container.Should().NotBeNull();

            // Act - Write
            var record = new AgentRecord
            {
                Id           = "Agent1",
                State        = AgentState.Running,
                UtcHeartbeat = DateTime.UtcNow,
            };

            ETag etag = await container.Set(record);

            etag.Should().NotBeNull();
            etag.Value.Should().NotBeEmpty();

            IReadOnlyList <AgentRecord> activeList = await container.Search("select * from ROOT");

            activeList.Should().NotBeNull();
            activeList.Count.Should().Be(1);

            // Act - Read
            Record <AgentRecord>?read = await container.Get(record.Id);

            read.Should().NotBeNull();
            (read !.Value == record).Should().BeTrue();

            // Act - Delete
            (await container.Delete(record.Id, etag)).Should().BeTrue();

            IReadOnlyList <AgentRecord> deleteList = await container.Search("select * from ROOT");

            deleteList.Should().NotBeNull();
            deleteList.Count.Should().Be(0);

            // Clean up
            (await watcherRepository.Database.Delete(_databaseName, CancellationToken.None)).Should().BeTrue();
        }
Example #18
0
        private async Task WriteRecord(string recordType, string json, CancellationToken token)
        {
            switch (recordType)
            {
            case nameof(AgentRecord):
                AgentRecord agentRecord = _json.Deserialize <AgentRecord>(json);
                await _agentContainer.Set(agentRecord, token);

                break;

            case nameof(TargetRecord):
                TargetRecord targetRecord = _json.Deserialize <TargetRecord>(json);
                await _targetContainer.Set(targetRecord, token);

                break;

            default:
                throw new ArgumentException($"Unknown record type for importing, recordType={recordType}");
            }
        }
Example #19
0
        private void AssignTargetsToAgents(IReadOnlyList <TargetRecord> activeTargets, IReadOnlyList <AgentRecord> activeAgents)
        {
            _logger.LogTrace($"{nameof(AssignTargetsToAgents)}: Assign un-assigned targets to agents");

            var newTargets = activeTargets
                             .Where(x => x.AssignedAgentId == null)
                             .ToArray();

            var newTargetsQueue = new Queue <TargetRecord>(newTargets);

            while (newTargetsQueue.TryDequeue(out TargetRecord targetRecord))
            {
                AgentRecord agent = activeAgents
                                    .Select(x => (Agent: x, Count: AgentAssignmentCount(x, activeTargets)))
                                    .OrderBy(x => x.Count)
                                    .Select(x => x.Agent)
                                    .First();

                targetRecord.AssignedAgentId = agent.Id;
            }
        }
        public TestAgent GetAgent(AgentType type, int waitTime)
        {
            if (type == AgentType.Default)
            {
                type = defaultAgentType;
            }

            if ((type & supportedAgentTypes) == 0)
            {
                throw new ArgumentException(
                          string.Format("AgentType {0} is not supported by this agency", type),
                          "type");
            }

            AgentRecord r = FindAvailableRemoteAgent(type);

            if (r == null)
            {
                r = CreateRemoteAgent(type, waitTime);
            }

            return(new TestAgent(this, r.Process.Id, r.Agent));
        }
Example #21
0
			public void Add( AgentRecord r )
			{
				agentData[r.Id] = r;
			}
 public void Add(AgentRecord r)
 {
     agentData[r.Id] = r;
 }
Example #23
0
 private int AgentAssignmentCount(AgentRecord agentRecord, IReadOnlyList <TargetRecord> activeAssignment) => activeAssignment.Count(x => x.AssignedAgentId == agentRecord.Id);
Example #24
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            AgentRecord ar = new AgentRecord();

            if (String.IsNullOrEmpty(txtCustomerName.Text.Trim()))
            {
                MessageBox.Show("代理商名称不许为空!", "软件提示");
                txtCustomerName.Focus();
                return;
            }
            if (String.IsNullOrEmpty(txtJuridicalPerson.Text.Trim()))
            {
                MessageBox.Show("法人不许为空!", "软件提示");
                txtJuridicalPerson.Focus();
                return;
            }
            if (String.IsNullOrEmpty(txtPhoneNumber.Text.Trim()))
            {
                MessageBox.Show("联系电话不许为空!", "软件提示");
                txtPhoneNumber.Focus();
                return;
            }
            if (cbxProvinceCode.SelectedValue == null)
            {
                MessageBox.Show("所在省市不许为空!", "软件提示");
                cbxProvinceCode.Focus();
                return;
            }
            if (String.IsNullOrEmpty(txtAddress.Text.Trim()))
            {
                MessageBox.Show("地址不许为空!", "软件提示");
                txtAddress.Focus();
                return;
            }

            if (this.Tag.ToString() == "Add")
            {
                DataGridViewRow dgvr = ar.AddDataGridViewRow(formAgentRecord.dgvAgentRecord, formAgentRecord.bsAgentRecord);
                dgvr.Cells["CustomerName"].Value      = txtCustomerName.Text.Trim();
                dgvr.Cells["JuridicalPerson"].Value   = txtJuridicalPerson.Text.Trim();
                dgvr.Cells["PhoneNumber"].Value       = txtPhoneNumber.Text.Trim();
                dgvr.Cells["ProvinceCode"].Value      = cbxProvinceCode.SelectedValue;
                dgvr.Cells["Address"].Value           = txtAddress.Text.Trim();
                dgvr.Cells["PostalCode"].Value        = txtPostalCode.Text.Trim();
                dgvr.Cells["URL"].Value               = txtURL.Text.Trim();
                dgvr.Cells["OpenAccBankName"].Value   = txtOpenAccBankName.Text.Trim();
                dgvr.Cells["AccountNumber"].Value     = txtAccountNumber.Text.Trim();
                dgvr.Cells["CertificateNumber"].Value = txtCertificateNumber.Text.Trim();
                dgvr.Cells["IsCancel"].Value          = useful.GetFlagValue(cbIsCancel);
                dgvr.Cells["CustomerType"].Value      = "1";//代理商类型为1,默认值,不许修改的
                dgvr.Cells["Remark"].Value            = txtRemark.Text.Trim();
                dgvr.Cells["OperatorCode"].Value      = GlobalProperty.OperatorCode;
                if (ar.Insert(formAgentRecord.dgvAgentRecord, formAgentRecord.bsAgentRecord))
                {
                    formAgentRecord.bsAgentRecord.DataSource  = ar.GetDataTable("Customer", " Where CustomerType = '1'");
                    formAgentRecord.dgvAgentRecord.DataSource = formAgentRecord.bsAgentRecord;
                    //formAgentRecord.bsAgentRecord.CancelEdit();//取消当前的编辑操作。
                    if (MessageBox.Show("保存成功,是否继续添加?", "软件提示", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                    {
                        txtCustomerName.Text          = "";
                        txtJuridicalPerson.Text       = "";
                        txtPhoneNumber.Text           = "";
                        cbxProvinceCode.SelectedIndex = -1;
                        txtAddress.Text           = "";
                        txtPostalCode.Text        = "";
                        txtURL.Text               = "";
                        txtOpenAccBankName.Text   = "";
                        txtAccountNumber.Text     = "";
                        txtCertificateNumber.Text = "";
                        cbIsCancel.Checked        = false; //表示不取消代理
                        txtRemark.Text            = "";
                        txtCustomerName.Focus();
                    }
                    else
                    {
                        this.Close();
                    }
                }
                else
                {
                    MessageBox.Show("保存失败!", "软件提示");
                }
            }
            if (this.Tag.ToString() == "Edit")
            {
                DataGridViewRow dgvr = formAgentRecord.dgvAgentRecord.CurrentRow;
                dgvr.Cells["CustomerName"].Value      = txtCustomerName.Text.Trim();
                dgvr.Cells["JuridicalPerson"].Value   = txtJuridicalPerson.Text.Trim();
                dgvr.Cells["PhoneNumber"].Value       = txtPhoneNumber.Text.Trim();
                dgvr.Cells["ProvinceCode"].Value      = cbxProvinceCode.SelectedValue;
                dgvr.Cells["Address"].Value           = txtAddress.Text.Trim();
                dgvr.Cells["PostalCode"].Value        = txtPostalCode.Text.Trim();
                dgvr.Cells["URL"].Value               = txtURL.Text.Trim();
                dgvr.Cells["OpenAccBankName"].Value   = txtOpenAccBankName.Text.Trim();
                dgvr.Cells["AccountNumber"].Value     = txtAccountNumber.Text.Trim();
                dgvr.Cells["CertificateNumber"].Value = txtCertificateNumber.Text.Trim();
                dgvr.Cells["IsCancel"].Value          = useful.GetFlagValue(cbIsCancel);
                //dgvr.Cells["CustomerType"].Value = "1";//代理商类型为1,默认值,不许修改
                dgvr.Cells["Remark"].Value = txtRemark.Text.Trim();
                //dgvr.Cells["OperatorCode"].Value = GlobalProperty.OperatorCode;
                if (ar.Update(formAgentRecord.bsAgentRecord))
                {
                    MessageBox.Show("保存成功!", "软件提示");
                    this.Close();
                }
                else
                {
                    MessageBox.Show("保存失败!", "软件提示");
                }
            }
        }