Beispiel #1
0
        protected override void OnStop()
        {
            lock (ServiceLock)
            {
                Stopping = true;

                // TODO If agent service is killed make sure AgentListener also is killed
                try
                {
                    if (AgentListener != null && !AgentListener.HasExited)
                    {
                        // Try to let the agent process know that we are stopping
                        // TODO: This is not working, fix it
                        AgentListener.StandardInput.WriteLine("\x03");

                        // Wait for the process to finish (give it up to 30 seconds)
                        AgentListener.WaitForExit(30000);
                        // if agent is still running, kill it
                        if (!AgentListener.HasExited)
                        {
                            AgentListener.Kill();
                        }
                    }
                }
                catch (Exception exception)
                {
                    // InvalidOperationException is thrown when there is no process associated to the process object.
                    // There is no process to kill, Log the exception and shutdown the service.
                    // If we don't handle this here, the service get into a state where it can neither be stoped nor restarted (Error 1061)
                    WriteException(exception);
                }
            }
        }
        public async Task TestAgentCloseConnectionWorksForOutgoing()
        {
            var endpoint = "127.0.0.1:9604";

            var myDid = await Signus.CreateAndStoreMyDidAsync(_wallet, "{}");

            var identityJson = string.Format("{{\"did\":\"{0}\", \"pk\":\"{1}\", \"verkey\":\"{2}\", \"endpoint\":\"{3}\"}}",
                                             myDid.Did, myDid.Pk, myDid.VerKey, endpoint);

            await Signus.StoreTheirDidAsync(_wallet, identityJson);

            var activeListener = await AgentListener.ListenAsync(endpoint);

            await activeListener.AddIdentityAsync(_pool, _wallet, myDid.Did);

            await AgentConnection.ConnectAsync(_pool, _wallet, myDid.Did, myDid.Did);

            var connectionEvent = await activeListener.WaitForConnection();

            var serverToClientConnection = connectionEvent.Connection;

            await activeListener.CloseAsync();

            var ex = await Assert.ThrowsExceptionAsync <IndyException>(() =>
                                                                       serverToClientConnection.SendAsync("msg")
                                                                       );

            Assert.AreEqual(ErrorCode.CommonInvalidStructure, ex.ErrorCode);
        }
Beispiel #3
0
        public async Task TestAgentCloseConnectionWorksForIncoming()
        {
            var endpoint = "127.0.0.1:9613";

            var myDid = await Signus.CreateAndStoreMyDidAsync(wallet, "{}");

            var identityJson = string.Format(AGENT_IDENTITY_JSON_TEMPLATE, myDid.Did, myDid.Pk, myDid.VerKey, endpoint);

            await Signus.StoreTheirDidAsync(wallet, identityJson);

            var activeListener = await AgentListener.ListenAsync(endpoint);

            await activeListener.AddIdentityAsync(pool, wallet, myDid.Did);

            var connection = await AgentConnection.ConnectAsync(pool, wallet, myDid.Did, myDid.Did);

            var connectionEvent = await activeListener.WaitForConnectionAsync();

            var serverToClientConnection = connectionEvent.Connection;

            await serverToClientConnection.CloseAsync();

            var ex = await Assert.ThrowsExceptionAsync <InvalidStructureException>(() =>
                                                                                   serverToClientConnection.SendAsync("msg")
                                                                                   );
        }
        public async Task DisposeCanBeCalledRepeatedly()
        {
            var listener = await AgentListener.ListenAsync(endpoint);

            listener.Dispose();
            listener.Dispose();
        }
 public async Task CanDisposeClosedListener()
 {
     using (var listener = await AgentListener.ListenAsync(endpoint))
     {
         await listener.CloseAsync();
     }
 }
Beispiel #6
0
 /// <summary>
 /// Initializes a new AgentConnectionEvent.
 /// </summary>
 /// <param name="listener">The listener the connection was established on.</param>
 /// <param name="result">The result of the opening the connection.</param>
 /// <param name="connection">The connection.</param>
 /// <param name="senderDid">The DID of the sender.</param>
 /// <param name="receiverDid">The DID of the receiver.</param>
 internal AgentConnectionEvent(AgentListener listener, ErrorCode result, AgentConnection connection, string senderDid, string receiverDid) :
     base(listener.Handle, result)
 {
     Connection  = connection;
     SenderDid   = senderDid;
     ReceiverDid = receiverDid;
     Listener    = listener;
 }
Beispiel #7
0
        protected override void OnStop()
        {
            lock (ServiceLock)
            {
                Stopping = true;

                // throw exception during OnStop() will make SCM think the service crash and trigger recovery option.
                // in this way we can self-update the service host.
                if (_restart)
                {
                    throw new Exception(Resource.CrashServiceHost);
                }

                // TODO If agent service is killed make sure AgentListener also is killed
                try
                {
                    if (AgentListener != null && !AgentListener.HasExited)
                    {
                        // Try to let the agent process know that we are stopping
                        //Attach service process to console of Agent.Listener process. This is needed,
                        //because windows service doesn't use its own console.
                        if (AttachConsole((uint)AgentListener.Id))
                        {
                            //Prevent main service process from stopping because of Ctrl + C event with SetConsoleCtrlHandler
                            SetConsoleCtrlHandler(null, true);
                            try
                            {
                                //Generate console event for current console with GenerateConsoleCtrlEvent (processGroupId should be zero)
                                GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
                                //Wait for the process to finish (give it up to 30 seconds)
                                AgentListener.WaitForExit(30000);
                            }
                            finally
                            {
                                //Disconnect from console and restore Ctrl+C handling by main process
                                FreeConsole();
                                SetConsoleCtrlHandler(null, false);
                            }
                        }

                        // if agent is still running, kill it
                        if (!AgentListener.HasExited)
                        {
                            AgentListener.Kill();
                        }
                    }
                }
                catch (Exception exception)
                {
                    // InvalidOperationException is thrown when there is no process associated to the process object.
                    // There is no process to kill, Log the exception and shutdown the service.
                    // If we don't handle this here, the service get into a state where it can neither be stoped nor restarted (Error 1061)
                    WriteException(exception);
                }
            }
        }
        public async Task EndpointCanBeReUsedAfterDispose()
        {
            var listener = await AgentListener.ListenAsync(endpoint);

            listener.Dispose();

            using (var newListener = await AgentListener.ListenAsync(endpoint))
            {
            }
        }
        public async Task TestAgentAddIdentityWorks()
        {
            var endpoint = "127.0.0.1:9601";

            var myDidResult = await Signus.CreateAndStoreMyDidAsync(_wallet, "{}");

            var activeListener = await AgentListener.ListenAsync(endpoint);

            await activeListener.AddIdentityAsync(_pool, _wallet, myDidResult.Did);
        }
Beispiel #10
0
        [Ignore] //Wait until proper error is implemented in SDK and handle.
        public async Task CanCloseAfterDispose()
        {
            var endpoint = "127.0.0.1:9617";

            await PrepareForListener(endpoint);

            var listener = await AgentListener.ListenAsync(endpoint);

            listener.Dispose();
            await listener.CloseAsync();
        }
Beispiel #11
0
        public async Task DisposeCanBeCalledRepeatedly()
        {
            var endpoint = "127.0.0.1:9615";

            await PrepareForListener(endpoint);

            var listener = await AgentListener.ListenAsync(endpoint);

            listener.Dispose();
            listener.Dispose();
        }
Beispiel #12
0
        public async Task CanDisposeClosedListener()
        {
            var endpoint = "127.0.0.1:9614";

            await PrepareForListener(endpoint);

            using (var listener = await AgentListener.ListenAsync(endpoint))
            {
                await listener.CloseAsync();
            }
        }
Beispiel #13
0
        private async Task SendSTTResultToUser(string text, IEnumerable <Participant> participants)
        {
            var to   = participants.Single(x => x.Originator);
            var from = participants.First(x => !x.Originator);

            var jsonSpeech = JsonConvert.DeserializeObject <BingSpeechResponse>(text);

            var g = await this.takeAction(jsonSpeech.DisplayText);

            await AgentListener.Resume(to.Identity, to.DisplayName, from.Identity, from.DisplayName, to.Identity, g);
        }
Beispiel #14
0
        public async Task TestAgentListenWorks()
        {
            var endpoint = "127.0.0.1:9607";

            var myDidResult = await Signus.CreateAndStoreMyDidAsync(wallet, "{}");

            var identityJson = string.Format(AGENT_IDENTITY_JSON_TEMPLATE, myDidResult.Did, myDidResult.Pk, myDidResult.VerKey, endpoint);
            await Signus.StoreTheirDidAsync(wallet, identityJson);

            await AgentListener.ListenAsync(endpoint);
        }
        public async Task CanCloseAfterDispose()
        {
            var listener = await AgentListener.ListenAsync(endpoint);

            listener.Dispose();

            var ex = await Assert.ThrowsExceptionAsync <IndyException>(() =>
                                                                       listener.CloseAsync()
                                                                       );

            Assert.AreEqual(ErrorCode.WalletAlreadyExistsError, ex.ErrorCode);
        }
Beispiel #16
0
        public async Task TestAgentConnectWorksForRemoteData()
        {
            var endpoint           = "127.0.0.1:9605";
            var listenerWalletName = "listenerWallet";
            var trusteeWalletName  = "trusteeWallet";

            await Wallet.CreateWalletAsync(_poolName, listenerWalletName, "default", null, null);

            var listenerWallet = await Wallet.OpenWalletAsync(listenerWalletName, null, null);

            await Wallet.CreateWalletAsync(_poolName, trusteeWalletName, "default", null, null);

            var trusteeWallet = await Wallet.OpenWalletAsync(trusteeWalletName, null, null);

            var senderWallet = trusteeWallet;

            var createMyDidResult = await Signus.CreateAndStoreMyDidAsync(listenerWallet, "{}");

            var listenerDid    = createMyDidResult.Did;
            var listenerVerkey = createMyDidResult.VerKey;
            var listenerPk     = createMyDidResult.Pk;

            var trusteeDidJson = "{\"seed\":\"000000000000000000000000Trustee1\"}";

            var trusteeDidResult = await Signus.CreateAndStoreMyDidAsync(trusteeWallet, trusteeDidJson);

            var trusteeDid = trusteeDidResult.Did;
            var senderDid  = trusteeDid;

            var nymRequest = await Ledger.BuildNymRequestAsync(trusteeDid, listenerDid, listenerVerkey, null, null);

            await Ledger.SignAndSubmitRequestAsync(_pool, trusteeWallet, trusteeDid, nymRequest);

            var attribRequest = await Ledger.BuildAttribRequestAsync(listenerDid, listenerDid, null,
                                                                     string.Format("{{\"endpoint\":{{\"ha\":\"{0}\",\"verkey\":\"{1}\"}}}}", endpoint, listenerPk), null);

            await Ledger.SignAndSubmitRequestAsync(_pool, listenerWallet, listenerDid, attribRequest);

            var activeListener = await AgentListener.ListenAsync(endpoint);

            await activeListener.AddIdentityAsync(_pool, listenerWallet, listenerDid);

            await AgentConnection.ConnectAsync(_pool, senderWallet, senderDid, listenerDid);

            await listenerWallet.CloseAsync();

            await Wallet.DeleteWalletAsync(listenerWalletName, null);

            await trusteeWallet.CloseAsync();

            await Wallet.DeleteWalletAsync(trusteeWalletName, null);
        }
Beispiel #17
0
        public async Task PrepareForConnection(string endpoint)
        {
            var myDidResult = await Signus.CreateAndStoreMyDidAsync(wallet, "{}");

            _myDid = myDidResult.Did;

            var identityJson = string.Format(AGENT_IDENTITY_JSON_TEMPLATE, _myDid, myDidResult.Pk, myDidResult.VerKey, endpoint);
            await Signus.StoreTheirDidAsync(wallet, identityJson);

            _activeListener = await AgentListener.ListenAsync(endpoint);

            await _activeListener.AddIdentityAsync(pool, wallet, _myDid);
        }
Beispiel #18
0
        public async Task TestAgentListenWorks()
        {
            var endpoint = "127.0.0.1:9607";

            var didJson = "{\"seed\":\"indy_agent_connect_works_for_aaa\"}";

            var myDidResult = await Signus.CreateAndStoreMyDidAsync(_wallet, didJson);

            var identityJson = string.Format("{{\"did\":\"{0}\", \"pk\":\"{1}\", \"verkey\":\"{2}\", \"endpoint\":\"{3}\"}}",
                                             myDidResult.Did, myDidResult.Pk, myDidResult.VerKey, endpoint);
            await Signus.StoreTheirDidAsync(_wallet, identityJson);

            await AgentListener.ListenAsync(endpoint);
        }
Beispiel #19
0
        [Ignore]//Appears endpoint cannot be re-connected to.  Requires further testing.
        public async Task EndpointCanBeReUsedAfterDispose()
        {
            var endpoint = "127.0.0.1:9616";

            await PrepareForListener(endpoint);

            var listener = await AgentListener.ListenAsync(endpoint);

            listener.Dispose();

            using (var newListener = await AgentListener.ListenAsync(endpoint))
            {
            }
        }
        public async Task PrepareForConnection()
        {
            var endpoint = "127.0.0.1:9603";

            myDid = await Signus.CreateAndStoreMyDidAsync(_wallet, "{}");

            var identityJson = string.Format("{{\"did\":\"{0}\", \"pk\":\"{1}\", \"verkey\":\"{2}\", \"endpoint\":\"{3}\"}}",
                                             myDid.Did, myDid.Pk, myDid.VerKey, endpoint);

            await Signus.StoreTheirDidAsync(_wallet, identityJson);

            activeListener = await AgentListener.ListenAsync(endpoint);

            await activeListener.AddIdentityAsync(_pool, _wallet, myDid.Did);
        }
Beispiel #21
0
        public async Task TestAgentConnectWorksForAllDataInWalletPresent()
        {
            var endpoint = "127.0.0.1:9606";

            var myDidResult = await Signus.CreateAndStoreMyDidAsync(wallet, "{}");

            var identityJson = string.Format(AGENT_IDENTITY_JSON_TEMPLATE, myDidResult.Did, myDidResult.Pk, myDidResult.VerKey, endpoint);
            await Signus.StoreTheirDidAsync(wallet, identityJson);

            var activeListener = await AgentListener.ListenAsync(endpoint);

            await activeListener.AddIdentityAsync(pool, wallet, myDidResult.Did);

            await AgentConnection.ConnectAsync(pool, wallet, myDidResult.Did, myDidResult.Did);
        }
Beispiel #22
0
        public async Task TestAgentConnectWorksForAllDataInWalletPresent()
        {
            var endpoint = "127.0.0.1:9606";

            var myDidResult = await Signus.CreateAndStoreMyDidAsync(_wallet, "{}");

            var identityJson = string.Format("{{\"did\":\"{0}\", \"pk\":\"{1}\", \"verkey\":\"{2}\", \"endpoint\":\"{3}\"}}",
                                             myDidResult.Did, myDidResult.Pk, myDidResult.VerKey, endpoint);
            await Signus.StoreTheirDidAsync(_wallet, identityJson);

            var activeListener = await AgentListener.ListenAsync(endpoint);

            await activeListener.AddIdentityAsync(_pool, _wallet, myDidResult.Did);

            await AgentConnection.ConnectAsync(_pool, _wallet, myDidResult.Did, myDidResult.Did);
        }
        public async Task TestAgentAddIdentityWorksForMultiplyKeys()
        {
            var endpoint = "127.0.0.1:9602";

            var myDid1 = await Signus.CreateAndStoreMyDidAsync(_wallet, "{}");

            var myDid2 = await Signus.CreateAndStoreMyDidAsync(_wallet, "{}");

            CreateAndStoreMyDidResult[] didResults = { myDid1, myDid2 };

            var activeListener = await AgentListener.ListenAsync(endpoint);

            foreach (var didResult in didResults)
            {
                await activeListener.AddIdentityAsync(_pool, _wallet, didResult.Did);
            }
        }
Beispiel #24
0
        public async Task TestAgentSendWorks()
        {
            var endpoint = "127.0.0.1:9609";

            var myDidResult = await Signus.CreateAndStoreMyDidAsync(_wallet, "{}");

            var identityJson = string.Format("{{\"did\":\"{0}\", \"pk\":\"{1}\", \"verkey\":\"{2}\", \"endpoint\":\"{3}\"}}",
                                             myDidResult.Did, myDidResult.Pk, myDidResult.VerKey, endpoint);
            await Signus.StoreTheirDidAsync(_wallet, identityJson);

            var listener = await AgentListener.ListenAsync(endpoint);

            await listener.AddIdentityAsync(_pool, _wallet, myDidResult.Did);

            var clientConnection = await AgentConnection.ConnectAsync(_pool, _wallet, myDidResult.Did, myDidResult.Did);

            var connectionEvent = await listener.WaitForConnection();

            var serverConnection = connectionEvent.Connection;

            var waitListenerConnectionTask = listener.WaitForConnection(); //Start waiting for additional connections - we'll never get one in this test, however.

            var clientToServerMessage = "msg_from_client";
            var serverToClientMessage = "msg_from_server";

            await clientConnection.SendAsync(clientToServerMessage);

            var waitServerMessageTask = serverConnection.WaitForMessage();

            var completedTask = await Task.WhenAny(waitListenerConnectionTask, waitServerMessageTask); //Wait for either an additional connection or message and proceed when one has arrived.

            Assert.AreEqual(completedTask, waitServerMessageTask);

            var serverMessageEvent = await waitServerMessageTask;

            Assert.AreEqual(clientToServerMessage, serverMessageEvent.Message);

            await serverConnection.SendAsync(serverToClientMessage);

            var clientMessageEvent = await clientConnection.WaitForMessage();

            Assert.AreEqual(serverToClientMessage, clientMessageEvent.Message);
        }
Beispiel #25
0
        // this will send either Ctrl-C or Ctrl-Break to agent.listener
        // Ctrl-C will be used for OnStop()
        // Ctrl-Break will be used for OnShutdown()
        private void SendCtrlSignalToAgentListener(uint signal)
        {
            try
            {
                if (AgentListener != null && !AgentListener.HasExited)
                {
                    // Try to let the agent process know that we are stopping
                    //Attach service process to console of Agent.Listener process. This is needed,
                    //because windows service doesn't use its own console.
                    if (AttachConsole((uint)AgentListener.Id))
                    {
                        //Prevent main service process from stopping because of Ctrl + C event with SetConsoleCtrlHandler
                        SetConsoleCtrlHandler(null, true);
                        try
                        {
                            //Generate console event for current console with GenerateConsoleCtrlEvent (processGroupId should be zero)
                            GenerateConsoleCtrlEvent(signal, 0);
                            //Wait for the process to finish (give it up to 30 seconds)
                            AgentListener.WaitForExit(30000);
                        }
                        finally
                        {
                            //Disconnect from console and restore Ctrl+C handling by main process
                            FreeConsole();
                            SetConsoleCtrlHandler(null, false);
                        }
                    }

                    // if agent is still running, kill it
                    if (!AgentListener.HasExited)
                    {
                        AgentListener.Kill();
                    }
                }
            }
            catch (Exception exception)
            {
                // InvalidOperationException is thrown when there is no process associated to the process object.
                // There is no process to kill, Log the exception and shutdown the service.
                // If we don't handle this here, the service get into a state where it can neither be stoped nor restarted (Error 1061)
                WriteException(exception);
            }
        }
Beispiel #26
0
        protected override void OnStart(string[] args)
        {
            RunningLoop = Task.Run(
                () =>
            {
                try
                {
                    bool stopping;
                    WriteInfo("Starting VSTS Agent Service");
                    TimeSpan timeBetweenRetries = TimeSpan.FromSeconds(5);

                    lock (ServiceLock)
                    {
                        stopping = Stopping;
                    }

                    while (!stopping)
                    {
                        WriteInfo("Starting VSTS Agent listener");
                        lock (ServiceLock)
                        {
                            AgentListener = CreateAgentListener();
                            AgentListener.Start();
                        }

                        AgentListener.WaitForExit();
                        int exitCode = AgentListener.ExitCode;

                        // Handle error code 1?
                        // If agent fails (because its not configured) also returns error code 1, in such case we dont want to run the service
                        // Killing a process also returns error code 1, but we want to restart the process here.
                        // TODO: change the error code for run method if agent is not configured?

                        if (exitCode == 2)
                        {
                            // Agent wants to stop the service as well
                            Stopping = true;
                            WriteInfo(Resource.ServiceRequestedToStop);
                            ExitCode = exitCode;
                            Stop();
                        }
                        else
                        {
                            // wait for few seconds before restarting the process
                            Thread.Sleep(timeBetweenRetries);
                        }
                    }

                    lock (ServiceLock)
                    {
                        AgentListener.Dispose();
                        AgentListener = null;
                    }
                }
                catch (Exception exception)
                {
                    WriteException(exception);
                    ExitCode = 1;
                    Stop();
                }
            });
        }
Beispiel #27
0
        public static async Task Execute()
        {
            Console.WriteLine("Agent sample -> started");

            var listenerWalletName = "listenerWallet";
            var trusteeWalletName  = "trusteeWallet";
            var endpoint           = "127.0.0.1:9801";
            var message            = "test";
            var trusteeSeed        = "000000000000000000000000Trustee1";

            try
            {
                //1. Create Pool
                await PoolUtils.CreatePoolLedgerConfig();

                //2. Create Listener Wallet
                await WalletUtils.CreateWalleatAsync(PoolUtils.DEFAULT_POOL_NAME, listenerWalletName, "default", null, null);

                //3. Create Trustee Wallet
                await WalletUtils.CreateWalleatAsync(PoolUtils.DEFAULT_POOL_NAME, trusteeWalletName, "default", null, null);

                //4. Open pool and wallets in using statements to ensure they are closed when finished.
                using (var pool = await Pool.OpenPoolLedgerAsync(PoolUtils.DEFAULT_POOL_NAME, "{}"))
                    using (var listenerWallet = await Wallet.OpenWalletAsync(listenerWalletName, null, null))
                        using (var trusteeWallet = await Wallet.OpenWalletAsync(trusteeWalletName, null, null))
                        {
                            var senderWallet = trusteeWallet;

                            //5. Create My Did
                            var createMyDidResult = await Signus.CreateAndStoreMyDidAsync(listenerWallet, "{}");

                            var listenerDid    = createMyDidResult.Did;
                            var listenerVerkey = createMyDidResult.VerKey;
                            var listenerPk     = createMyDidResult.Pk;

                            //6. Create Their Did from Trustee seed
                            var trusteeDidJson = string.Format("{{\"seed\":\"{0}\"}}", trusteeSeed);

                            var trusteeDidResult = await Signus.CreateAndStoreMyDidAsync(trusteeWallet, trusteeDidJson);

                            var trusteeDid = trusteeDidResult.Did;
                            var senderDid  = trusteeDid;

                            //7. Prepare and Send NYM request with signing
                            var nymRequest = await Ledger.BuildNymRequestAsync(trusteeDid, listenerDid, listenerVerkey, null, null);

                            await Ledger.SignAndSubmitRequestAsync(pool, trusteeWallet, trusteeDid, nymRequest);

                            //8. Prepare and Send Attrib for listener (will be requested from ledger and used by sender at start connection)
                            var rawAttribJson = string.Format("{{\"endpoint\":{{\"ha\":\"{0}\",\"verkey\":\"{1}\"}}}}", endpoint, listenerPk);
                            var attribRequest = await Ledger.BuildAttribRequestAsync(listenerDid, listenerDid, null, rawAttribJson, null);

                            await Ledger.SignAndSubmitRequestAsync(pool, listenerWallet, listenerDid, attribRequest);

                            //9. start listener on endpoint
                            var activeListener = await AgentListener.ListenAsync(endpoint);

                            //10. Allow listener accept incoming connection for specific DID (listener_did)
                            await activeListener.AddIdentityAsync(pool, listenerWallet, listenerDid);

                            //11. Initiate connection from sender to listener
                            var sendingConnection = await AgentConnection.ConnectAsync(pool, senderWallet, senderDid, listenerDid);

                            var connectionEvent = await activeListener.WaitForConnectionAsync();

                            var receivingConnection = connectionEvent.Connection;

                            //12. Send test message from sender to listener
                            await sendingConnection.SendAsync(message);

                            var messageEvent = await receivingConnection.WaitForMessageAsync();

                            Debug.Assert(string.Equals(message, messageEvent.Message));

                            //13. Close connection
                            await sendingConnection.CloseAsync();

                            //14. Close listener
                            await activeListener.CloseAsync();

                            //15. Close wallets and pool
                            await listenerWallet.CloseAsync();

                            await trusteeWallet.CloseAsync();

                            await pool.CloseAsync();
                        }
            }
            finally
            {
                // 16. Delete Pool ledger config and wallets
                await PoolUtils.DeletePoolLedgerConfigAsync(PoolUtils.DEFAULT_POOL_NAME);

                await WalletUtils.DeleteWalletAsync(listenerWalletName, null);

                await WalletUtils.DeleteWalletAsync(trusteeWalletName, null);
            }

            Console.WriteLine("Agent sample -> completed");
        }
Beispiel #28
0
        private void listener_ElementsReceived(AgentListener.MessageQueueElement[] elements)
        {
            if (InvokeRequired)
            {
                Invoke(receivedHandler, new object[] { elements });
                return;
            }

            object source = dataGridView.DataSource;
            dataGridView.DataSource = null;
            dataSet.Tables[0].BeginLoadData();

            foreach (AgentListener.MessageQueueElement msg in elements)
            {
                DataTable tbl = dataSet.Tables["messages"];

                DataRow row = tbl.NewRow();
                row.BeginEdit();

                /* Common stuff */
                row["Timestamp"] = new DateTime(msg.time.wYear, msg.time.wMonth,
                                                msg.time.wDay, msg.time.wHour,
                                                msg.time.wMinute, msg.time.wSecond,
                                                msg.time.wMilliseconds,
                                                DateTimeKind.Local);

                row["ProcessName"] = msg.process_name;
                row["ProcessId"] = msg.process_id;
                row["ThreadId"] = msg.thread_id;

                row["FunctionName"] = msg.function_name;
                row["Backtrace"] = msg.backtrace;

                UInt32 returnAddress = 0;
                string callerModName = "";

                if (msg.backtrace.Length > 0)
                {
                    string[] tokens = msg.backtrace.Split(new char[] { '\n' }, 2);
                    if (tokens.Length >= 1)
                    {
                        string line = tokens[0];
                        string[] lineTokens = line.Split(new string[] { "::" }, 2, StringSplitOptions.None);

                        if (lineTokens.Length == 2)
                        {
                            returnAddress = Convert.ToUInt32(lineTokens[1].Substring(2), 16);
                            callerModName = lineTokens[0];
                        }
                    }
                }

                row["ReturnAddress"] = returnAddress;
                row["CallerModuleName"] = callerModName;

                row["ResourceId"] = msg.resource_id;

                row["MsgType"] = msg.msg_type;

                row["MsgContext"] = msg.context;
                row["Domain"] = msg.domain;
                row["Severity"] = msg.severity;
                row["Message"] = msg.message;

                if (msg.context == MessageContext.MESSAGE_CTX_ACTIVESYNC_DEVICE)
                    deviceLabel = msg.message;
                else if (msg.context == MessageContext.MESSAGE_CTX_ACTIVESYNC_STATUS)
                    statusLabel = msg.message;
                else if (msg.context == MessageContext.MESSAGE_CTX_ACTIVESYNC_SUBSTATUS)
                    subStatusLabel = msg.message;
                else if (msg.context == MessageContext.MESSAGE_CTX_ACTIVESYNC_WZ_STATUS)
                    wizStatusLabel = msg.message;

                row["Direction"] = msg.direction;
                row["LocalAddress"] = msg.local_address;
                row["LocalPort"] = msg.local_port;
                row["PeerAddress"] = msg.peer_address;
                row["PeerPort"] = msg.peer_port;

                byte[] data = new byte[msg.len];
                Array.Copy(msg.buf, data, data.Length);
                row["Data"] = data;

                row["AS_Device"] = deviceLabel;
                row["AS_Status"] = statusLabel;
                row["AS_SubStatus"] = subStatusLabel;
                row["AS_WizStatus"] = wizStatusLabel;

                row.EndEdit();

                tbl.Rows.Add(row);
            }

            dataSet.Tables[0].EndLoadData();
            dataGridView.DataSource = source;
        }
Beispiel #29
0
        public async Task TestAgentDemo()
        {
            var endpoint           = "127.0.0.1:9801";
            var listenerWalletName = "listenerWallet";
            var trusteeWalletName  = "trusteeWallet";
            var message            = "test";

            //1. Create and Open Pool
            var poolName = PoolUtils.CreatePoolLedgerConfig();
            var pool     = await Pool.OpenPoolLedgerAsync(poolName, "{}");

            //2. Create and Open Listener Wallet
            await Wallet.CreateWalletAsync(poolName, listenerWalletName, "default", null, null);

            var listenerWallet = await Wallet.OpenWalletAsync(listenerWalletName, null, null);

            //3. Create and Open Trustee Wallet
            await Wallet.CreateWalletAsync(poolName, trusteeWalletName, "default", null, null);

            var trusteeWallet = await Wallet.OpenWalletAsync(trusteeWalletName, null, null);

            var senderWallet = trusteeWallet;

            //4. Create My Did
            var createMyDidResult = await Signus.CreateAndStoreMyDidAsync(listenerWallet, "{}");

            var listenerDid    = createMyDidResult.Did;
            var listenerVerkey = createMyDidResult.VerKey;
            var listenerPk     = createMyDidResult.Pk;

            //5. Create Their Did from Trustee seed
            var trusteeDidJson = "{\"seed\":\"000000000000000000000000Trustee1\"}";

            var trusteeDidResult = await Signus.CreateAndStoreMyDidAsync(trusteeWallet, trusteeDidJson);

            var trusteeDid = trusteeDidResult.Did;
            var senderDid  = trusteeDid;

            // 6. Prepare and Send NYM request with signing
            var nymRequest = await Ledger.BuildNymRequestAsync(trusteeDid, listenerDid, listenerVerkey, null, null);

            await Ledger.SignAndSubmitRequestAsync(pool, trusteeWallet, trusteeDid, nymRequest);

            // 7. Prepare and Send Attrib for listener (will be requested from ledger and used by sender at start connection)
            var rawJson       = string.Format("{{\"endpoint\":{{\"ha\":\"{0}\",\"verkey\":\"{1}\"}}}}", endpoint, listenerPk);
            var attribRequest = await Ledger.BuildAttribRequestAsync(listenerDid, listenerDid, null, rawJson, null);

            await Ledger.SignAndSubmitRequestAsync(pool, listenerWallet, listenerDid, attribRequest);

            // 8. start listener on endpoint
            var activeListener = await AgentListener.ListenAsync(endpoint);

            // 9. Allow listener accept incoming connection for specific DID (listener_did)
            await activeListener.AddIdentityAsync(pool, listenerWallet, listenerDid);

            // 10. Initiate connection from sender to listener
            var connection = await AgentConnection.ConnectAsync(pool, senderWallet, senderDid, listenerDid);

            // 11. Send test message from sender to listener
            await connection.SendAsync("test");

            var serverConnectionEvent = await activeListener.WaitForConnection();

            var serverConnection = serverConnectionEvent.Connection;
            var messageEvent     = await serverConnection.WaitForMessage();

            Assert.AreEqual(message, messageEvent.Message);

            // 12. Close connection
            await connection.CloseAsync();

            // 13. Close listener
            await activeListener.CloseAsync();

            // 14. Close and delete Issuer Wallet
            await listenerWallet.CloseAsync();

            await Wallet.DeleteWalletAsync(listenerWalletName, null);

            // 15. Close and delete Prover Wallet
            await trusteeWallet.CloseAsync();

            await Wallet.DeleteWalletAsync(trusteeWalletName, null);

            //16. Close Pool
            await pool.CloseAsync();
        }
Beispiel #30
0
        protected override void OnStart(string[] args)
        {
            RunningLoop = Task.Run(
                () =>
            {
                try
                {
                    bool stopping;
                    WriteInfo("Starting VSTS Agent Service");
                    TimeSpan timeBetweenRetries = TimeSpan.FromSeconds(5);

                    lock (ServiceLock)
                    {
                        stopping = Stopping;
                    }

                    while (!stopping)
                    {
                        WriteInfo("Starting VSTS Agent listener");
                        lock (ServiceLock)
                        {
                            AgentListener = CreateAgentListener();
                            AgentListener.OutputDataReceived += AgentListener_OutputDataReceived;
                            AgentListener.ErrorDataReceived  += AgentListener_ErrorDataReceived;
                            AgentListener.Start();
                            AgentListener.BeginOutputReadLine();
                            AgentListener.BeginErrorReadLine();
                        }

                        AgentListener.WaitForExit();
                        int exitCode = AgentListener.ExitCode;

                        // exit code 0 and 1 need stop service
                        // exit code 2 and 3 need restart agent
                        switch (exitCode)
                        {
                        case 0:
                            Stopping = true;
                            WriteInfo(Resource.AgentExitWithoutError);
                            break;

                        case 1:
                            Stopping = true;
                            WriteInfo(Resource.AgentExitWithTerminatedError);
                            break;

                        case 2:
                            WriteInfo(Resource.AgentExitWithError);
                            break;

                        case 3:
                            WriteInfo(Resource.AgentUpdateInProcess);
                            var updateResult = HandleAgentUpdate();
                            if (updateResult == AgentUpdateResult.Succeed)
                            {
                                WriteInfo(Resource.AgentUpdateSucceed);
                            }
                            else if (updateResult == AgentUpdateResult.Failed)
                            {
                                WriteInfo(Resource.AgentUpdateFailed);
                                Stopping = true;
                            }
                            else if (updateResult == AgentUpdateResult.SucceedNeedRestart)
                            {
                                WriteInfo(Resource.AgentUpdateRestartNeeded);
                                _restart = true;
                                ExitCode = int.MaxValue;
                                Stop();
                            }
                            break;

                        default:
                            WriteInfo(Resource.AgentExitWithUndefinedReturnCode);
                            break;
                        }

                        if (Stopping)
                        {
                            ExitCode = exitCode;
                            Stop();
                        }
                        else
                        {
                            // wait for few seconds before restarting the process
                            Thread.Sleep(timeBetweenRetries);
                        }

                        lock (ServiceLock)
                        {
                            AgentListener.OutputDataReceived -= AgentListener_OutputDataReceived;
                            AgentListener.ErrorDataReceived  -= AgentListener_ErrorDataReceived;
                            AgentListener.Dispose();
                            AgentListener = null;
                            stopping      = Stopping;
                        }
                    }
                }
                catch (Exception exception)
                {
                    WriteException(exception);
                    ExitCode = 99;
                    Stop();
                }
            });
        }