Ejemplo n.º 1
0
 /// <summary>
 /// Evaluate whether there is an entity with the specified genome at the specified location that has been revealed to the specified players
 /// </summary>
 /// <param name="node"></param>
 /// <param name="genome">Genome bit flags. 0: Any genome</param>
 /// <param name="revealedTo">Visibility bit flags. 0: Any player (or none)</param>
 public GenomeRevealedAtLocation(NodeConfig node, int genome = 0, int revealedTo = 0x7fffffff)
 {
     _genome     = genome;
     _revealedTo = revealedTo
     ;
     _node = node;
 }
Ejemplo n.º 2
0
        public ReturnStatus Execute()
        {
            ReturnStatus returnStatus = new ReturnStatus();

            try
            {
                NodeConfig config = new NodeConfig();

                string distrinctHome = Path.Combine(config.Get("GEAR_BASE_DIR"), ".settings");

                if (!Directory.Exists(distrinctHome))
                {
                    Directory.CreateDirectory(distrinctHome);
                }

                File.WriteAllText(Path.Combine(distrinctHome, "district.info"),
                                  string.Format("#Do not  modify manually!\nuuid='{0}'\nactive='{1}'\nfirst_uid={2}\nmax_uid={3}", Uuid, Active, FirstUid, MaxUid));

                //TODO handle profiling

                returnStatus.Output   = string.Format("created/updated district {0} with active = {1}, first_uid = {2}, max_uid = {3}", Uuid, Active, FirstUid, MaxUid);
                returnStatus.ExitCode = 0;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                returnStatus.Output   = ex.ToString();
                returnStatus.ExitCode = 255;
            }
            return(returnStatus);
        }
Ejemplo n.º 3
0
        private void StartServers(int serverCount = 0)
        {
            _clientConfig = new ClientConfig();
            _servers      = new List <ServerInfo>();

            serverCount = serverCount == 0 ? ServerCount : serverCount;

            for (var i = 0; i < serverCount; i++)
            {
                var serverInfo = new ServerInfo {
                    Channel = new TcpServerChannel()
                };
                var nodeConfig = new NodeConfig {
                    IsPersistent = true, DataPath = $"server{i:D2}"
                };
                serverInfo.Server =
                    new Server.Server(nodeConfig)
                {
                    Channel = serverInfo.Channel
                };
                serverInfo.Port = serverInfo.Channel.Init();
                serverInfo.Channel.Start();
                serverInfo.Server.Start();

                _servers.Add(serverInfo);

                _clientConfig.Servers.Add(
                    new ServerConfig {
                    Host = "localhost", Port = serverInfo.Port
                });
            }


            Thread.Sleep(500); //be sure the server nodes are started
        }
Ejemplo n.º 4
0
        private ListViewItem ToListViewItem(NodeConfig node)
        {
            ListViewItem item = new ListViewItem(node.server);

            item.SubItems.Add(node.server_port.ToString());
            item.SubItems.Add(node.server_udp_port.ToString());
            item.SubItems.Add(node.password);
            item.SubItems.Add(node.method);
            item.SubItems.Add(node.obfs);
            item.SubItems.Add(node.obfsparam);
            item.SubItems.Add(node.remarks);
            item.SubItems.Add(node.protocol);
            item.SubItems.Add(node.protocolparam);

            var ping = new ListViewItem.ListViewSubItem();

            ping.Name = "PingItem";
            ping.Text = "未测试";
            ping.Tag  = false;

            var geoip = new ListViewItem.ListViewSubItem();

            geoip.Name = "GeoIPItem";
            geoip.Text = "未测试";
            geoip.Tag  = false;

            item.SubItems.Add(ping);
            item.SubItems.Add(geoip);

            item.Tag = node;
            return(item);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Helper function to build a NodePool object.
        /// InitialNodeCount will default to 1.
        /// MaximumNodesToScaleTo have to be greater than MinimumNodesToScaleTo, which defaults to 1.
        /// </summary>
        /// <param name="name">The name of the node pool.</param>
        /// <param name="config">The config of the node pool.</param>
        /// <param name="initialNodeCount">The number of nodes created in the pool initially.</param>
        /// <param name="autoUpgrade">If true, nodes will have auto-upgrade enabled.</param>
        /// <param name="minimumNodesToScaleTo">The maximum number of nodes to scale to.</param>
        /// <param name="maximumNodesToScaleTo">
        /// The minimum number of nodes to scale to. Defaults to 1.
        /// </param>
        /// <returns></returns>
        protected NodePool BuildNodePool(string name, NodeConfig config, int?initialNodeCount, bool autoUpgrade,
                                         int?minimumNodesToScaleTo, int?maximumNodesToScaleTo)
        {
            var nodePool = new NodePool()
            {
                Name             = name,
                InitialNodeCount = initialNodeCount ?? 1,
                Config           = config
            };

            if (maximumNodesToScaleTo != null)
            {
                nodePool.Autoscaling = BuildAutoscaling(maximumNodesToScaleTo, minimumNodesToScaleTo);
            }

            if (autoUpgrade)
            {
                var nodeManagement = new NodeManagement()
                {
                    AutoUpgrade = true
                };
                nodePool.Management = nodeManagement;
            }

            return(nodePool);
        }
Ejemplo n.º 6
0
        //------------------------------------------------------------------------------------------------------------------------
        private void InitYodiwoConnection()
        {
            //create node configuration
            NodeConfig conf = new NodeConfig()
            {
                Name           = "Azure Clone of " + ActiveCfg.AzureInfo.AzureDeviceName,
                YpServer       = ActiveCfg.YodiwoInfo.YodiwoApiServer,
                YpchannelPort  = Convert.ToInt32(ActiveCfg.YodiwoInfo.YPChannelPort),
                FrontendServer = ActiveCfg.YodiwoInfo.YodiwoRestUrl,
                CanSolveGraphs = false,
                SecureYpc      = ActiveCfg.YodiwoInfo.SecureYPC,
            };

            //create the proxy node
            proxyNode = new Yodiwo.NodeLibrary.Node(conf, Things, null, null, null);

            //set transport
            proxyNode.Transport = Transport.YPCHANNEL;

            //register cbs
            proxyNode.OnChangedState          += OnChangedStateCb;
            proxyNode.OnTransportConnected    += OnTransportConnectedCb;
            proxyNode.OnTransportDisconnected += OnTransportDisconnectedCb;
            proxyNode.OnTransportError        += OnTransportErrorCb;
            proxyNode.OnUnexpectedMessage      = OnUnexpectedMessageCb;
            proxyNode.OnThingActivated        += OnThingActivatedCb;

            //use nodekey to setup things
            proxyNode.SetupNodeKeys(ActiveCfg.YodiwoInfo.YodiwoNodeKey, ActiveCfg.YodiwoInfo.YodiwoSecretKey);

            //connect
            proxyNode.Connect();
            RegisterThings();
        }
Ejemplo n.º 7
0
        private void DrawTimer_Tick(object sender, EventArgs e)
        {
            if (ShapeListBox.SelectedItem == null)
            {
                return;
            }
            Converter c;

            using (Graphics g = Graphics.FromImage(exampleBitmap))
            {
                c = new Converter(DrawPictureBox.Width, DrawPictureBox.Height, -1, 1, -5, 5);
                NodeConfig nc = new NodeConfig(
                    (INodeShape)ShapeListBox.SelectedItem,
                    c,
                    nodePen,
                    selectedNodePen,
                    FillNodeColorBTN.BackColor,
                    SelectedFillNodeBTN.BackColor,
                    c.ToRealFont(font),
                    FontColorBTN.BackColor
                    );
                Node testNode = new Node(NameTB.Text, c.IJtoXY(new Point(DrawPictureBox.Width / 2, DrawPictureBox.Height / 2)), nc);
                testNode.NodeConfig.Selected = selected;
                g.Clear(Color.White);
                Drawing.DrawNode(g, testNode);
                DrawPictureBox.Image = exampleBitmap;
            }
        }
Ejemplo n.º 8
0
        public int SpinDelay = 1000; //in miliseconds

        public bool StartPair(string frontendUrl, string redirectUri, NodeConfig conf, string selfUrl, NodePairingBackend.OnPairedDelegate OnPairedcb, NodePairingBackend.OnPairingFailedDelegate OnPairingFailedCB)
        {
            this.conf = conf;

            //pairing backend
            var backend = new NodePairingBackend(frontendUrl, conf, OnPairedcb, OnPairingFailedCB);
            string token2 = backend.pairGetTokens(redirectUri);
            pairingURI = backend.pairingPostUrl + "/" + API.Plegma.NodePairing.NodePairingConstants.UserConfirmPageURI + "?token2=" + token2;

            if (UriCustomLauncher != null)
                UriCustomLauncher(pairingURI);
            else
            {
#if NETFX
                Process.Start(pairingURI);
#else
                Windows.System.Launcher.LaunchUriAsync(new Uri(pairingURI)).AsTask();
#endif
            }

            //wait for finish
            Task.Delay(1000).Wait();
            Task.Run(() =>
            {
                while (true)
                {
                    var keys = backend.pairGetKeys();
                    if (keys != null)
                        break;
                    Task.Delay(SpinDelay).Wait();
                }
            });
            return true;
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Build this controller.
 /// </summary>
 /// <param name="config"> Higher level API configuration. </param>
 /// <param name="executor"> Node executor from bitprim-cs library. </param>
 /// <param name="logger">  Abstract logger. </param>
 public AddressController(IOptions <NodeConfig> config, Executor executor, ILogger <AddressController> logger)
 {
     nodeExecutor_ = executor;
     chain_        = nodeExecutor_.Chain;
     config_       = config.Value;
     logger_       = logger;
 }
Ejemplo n.º 10
0
 public ApplicationContainer(string applicationUuid, string containerUuid, EtcUser userId, string applicationName,
                             string containerName, string namespaceName, object quotaBlocks, object quotaFiles, Hourglass hourglass, int applicationUid = 0)
 {
     this.config          = NodeConfig.Values;
     this.Uuid            = containerUuid;
     this.ApplicationUuid = applicationUuid;
     this.ApplicationName = applicationName;
     this.ContainerName   = containerName;
     this.Namespace       = namespaceName;
     this.QuotaBlocks     = quotaBlocks;
     this.QuotaFiles      = quotaFiles;
     this.State           = new ApplicationState(this);
     this.hourglass       = hourglass ?? new Hourglass(3600);
     this.BaseDir         = this.config["GEAR_BASE_DIR"];
     this.containerPlugin = new ContainerPlugin(this);
     this.Cartridge       = new CartridgeModel(this, this.State, this.hourglass);
     if (userId != null)
     {
         this.uid   = userId.Uid;
         this.gid   = userId.Gid;
         this.gecos = userId.Gecos;
     }
     if (applicationUid > 0)
     {
         this.uid = applicationUid;
     }
 }
Ejemplo n.º 11
0
        public void Run()
        {
            List <string> usersNotInPrison = new List <string>();
            List <string> usersWithNoGears = new List <string>();

            Output.WriteDebug("Checking cygwing passwd file consistency");
            NodeConfig nodeConfig = new NodeConfig();
            Etc        etc        = new Etc(nodeConfig);

            EtcUser[] etcUsers = etc.GetAllUsers();
            Output.WriteDebug(string.Format("Found {0} Etc Users", etcUsers));

            Prison.Prison[] prisons = Prison.Prison.Load();
            Output.WriteDebug(string.Format("Found {0} Prison Users", prisons.Count()));

            List <ApplicationContainer> gears = ApplicationContainer.All(null, false).ToList <ApplicationContainer>();

            Output.WriteDebug(string.Format("Found {0} gears", gears.Count()));

            foreach (EtcUser etcUser in etcUsers)
            {
                Output.WriteDebug(string.Format("Checking user {0}", etcUser.Name));

                if (etcUser.Name == "administrator")
                {
                    //skipping administrator user
                    continue;
                }

                if (prisons.Where(p => p.ID.ToString().TrimStart('0').Replace("-", "") == etcUser.Name).Count() == 0)
                {
                    usersNotInPrison.Add(etcUser.Name);
                }

                if (gears.Where(g => g.Uuid == etcUser.Name).Count() == 0)
                {
                    usersWithNoGears.Add(etcUser.Name);
                }
            }

            if (usersNotInPrison.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("The following users exist in /etc/passwd");
                sb.AppendLine(String.Join(", ", usersNotInPrison.ToArray()));
                sb.AppendLine("but have no prison user associated to them");
                Output.WriteWarn(sb.ToString());
                exitCode = ExitCode.WARNING;
            }

            if (usersWithNoGears.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("The following users exist in /etc/passwd");
                sb.AppendLine(String.Join(", ", usersWithNoGears.ToArray()));
                sb.AppendLine("but have no gears associated to them");
                Output.WriteWarn(sb.ToString());
                exitCode = ExitCode.WARNING;
            }
        }
Ejemplo n.º 12
0
        private async void GeoIPTest_Click(object sender, EventArgs e)
        {
            StartBtn.Enabled = false;
            //GeoIPBtn.Enabled = false;
            foreach (ListViewItem item in NodeList.Items)
            {
                NodeConfig node      = (NodeConfig)item.Tag;
                var        geoipItem = item.SubItems["GeoIPItem"];
                // 跳过已ping
                if ((bool)geoipItem.Tag == true)
                {
                    continue;
                }
                geoipItem.Text = "测试中";
                IPSBObject GeoIPResult = await GetGeoIPAsync(node.server); // Request country

                if (GeoIPResult == null || GeoIPResult.country == string.Empty)
                {
                    geoipItem.Text = "失败";
                }
                else
                {
                    geoipItem.Text = GeoIPResult.country; // update node
                }
                geoipItem.Tag = true;
            }
            StartBtn.Enabled = true;
            //GeoIPBtn.Enabled = true;
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Build this controller.
 /// </summary>
 /// <param name="config"> Higher level API configuration. </param>
 /// <param name="chain"> Executor's chain instance from bitprim-cs library. </param>
 /// <param name="memoryCache"> Abstract. </param>
 /// <param name="poolsInfo"> For recognizing blocks which come from mining pools. </param>
 public BlockController(IOptions <NodeConfig> config, IChain chain, IMemoryCache memoryCache, IPoolsInfo poolsInfo)
 {
     config_      = config.Value;
     chain_       = chain;
     memoryCache_ = memoryCache;
     poolsInfo_   = poolsInfo;
 }
Ejemplo n.º 14
0
        public void SetupScenario(string name, out SimulationLifecycleManager lifecycleManager, out NodeConfig[] nodeConfigs)
        {
            // Arrange
            var nodeLeft = new NodeConfig
            {
                Name      = "00",
                X         = 0,
                Y         = 0,
                Archetype = SubsystemNode.Archetype,
            };

            var nodeRight = new NodeConfig()
            {
                Name      = "10",
                X         = 1,
                Y         = 0,
                Archetype = SubsystemNode.Archetype,
            };

            nodeConfigs = new []
            {
                nodeLeft,
                nodeRight
            };

            SetupScenario(name, out lifecycleManager, nodeConfigs);
        }
Ejemplo n.º 15
0
        public NodeMasterViewModel(NodeConfig config)
        {
            m_Config       = config;
            Name           = m_Config.Name;
            ConnectCommand = new DelegateCommand(ExecuteConnectCommand);

            try
            {
                m_WebSocket = new AgentWebSocket(config.Uri);
            }
            catch (Exception e)
            {
                ErrorMessage = e.Message;
                return;
            }

#if !SILVERLIGHT
            m_WebSocket.AllowUnstrustedCertificate = true;
            m_WebSocket.Closed += new EventHandler(WebSocket_Closed);
            m_WebSocket.Error  += new EventHandler <ClientEngine.ErrorEventArgs>(WebSocket_Error);
            m_WebSocket.Opened += new EventHandler(WebSocket_Opened);
            m_WebSocket.On <string>(CommandName.UPDATE, OnServerUpdated);
#else
            m_WebSocket.ClientAccessPolicyProtocol = System.Net.Sockets.SocketClientAccessPolicyProtocol.Tcp;
            m_WebSocket.Closed += new EventHandler(CreateAsyncOperation <object, EventArgs>(WebSocket_Closed));
            m_WebSocket.Error  += new EventHandler <ClientEngine.ErrorEventArgs>(CreateAsyncOperation <object, ClientEngine.ErrorEventArgs>(WebSocket_Error));
            m_WebSocket.Opened += new EventHandler(CreateAsyncOperation <object, EventArgs>(WebSocket_Opened));
            m_WebSocket.On <string>(CommandName.UPDATE, OnServerUpdatedAsync);
#endif
            StartConnect();
        }
 public NodeMasterViewModel(NodeConfig config)
 {
     m_Config       = config;
     Name           = m_Config.Name;
     ConnectCommand = new DelegateCommand(ExecuteConnectCommand);
     ThreadPool.QueueUserWorkItem((c) => InitializeWebSocket((NodeConfig)c), config);
 }
        void InitializeWebSocket(NodeConfig config)
        {
            try
            {
                m_WebSocket = new AgentWebSocket(config.Uri);
            }
            catch (Exception)
            {
                ErrorMessage = "Invalid server URI!";
                State        = NodeState.Offline;
                return;
            }

#if !SILVERLIGHT
            m_WebSocket.AllowUnstrustedCertificate = true;
            m_WebSocket.Closed += new EventHandler(WebSocket_Closed);
            m_WebSocket.Error  += new EventHandler <ClientEngine.ErrorEventArgs>(WebSocket_Error);
            m_WebSocket.Opened += new EventHandler(WebSocket_Opened);
            m_WebSocket.On <string>(CommandName.UPDATE, OnServerUpdated);
#else
            m_WebSocket.ClientAccessPolicyProtocol = System.Net.Sockets.SocketClientAccessPolicyProtocol.Tcp;
            m_WebSocket.Closed += new EventHandler(WebSocket_Closed);
            m_WebSocket.Error  += new EventHandler <ClientEngine.ErrorEventArgs>(WebSocket_Error);
            m_WebSocket.Opened += new EventHandler(WebSocket_Opened);
            m_WebSocket.On <string>(CommandName.UPDATE, OnServerUpdatedAsync);
#endif
            StartConnect();
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Build this controller.
 /// </summary>
 /// <param name="config"> Higher level API configuration. </param>
 /// <param name="executor"> Node executor from bitprim-cs library. </param>
 /// <param name="logger"> Abstract logger. </param>
 public TransactionController(IOptions <NodeConfig> config, Executor executor, ILogger <TransactionController> logger)
 {
     config_       = config.Value;
     nodeExecutor_ = executor;
     chain_        = executor.Chain;
     logger_       = logger;
 }
Ejemplo n.º 19
0
 private NodeConfig loadConfig()
 {
     if (File.Exists(_configFileName))
     {
         BinaryFormatter bf = new BinaryFormatter();
         FileStream      fs = new FileStream(_configFileName, FileMode.Open);
         try
         {
             NodeConfig setting = (NodeConfig)(bf.Deserialize(fs));
             //setting.OnCoordSettingChangedEvent += new OnCoordSettingChanged(settingChangeEvent);
             //setting.RaiseCoordChangedEvent();
             return(setting);
         }
         finally
         {
             fs.Close();
         }
     }
     else
     {
         NodeConfig setting = new NodeConfig();
         //setting.OnCoordSettingChangedEvent += new OnCoordSettingChanged(settingChangeEvent);
         //setting.RaiseCoordChangedEvent();
         return(setting);
     }
 }
Ejemplo n.º 20
0
 protected ProxyReactorBase(NodeConfig nodeConfig,
                            IMessageEncoder encoder, IMessageDecoder decoder, IByteBufAllocator allocator,
                            int bufferSize = NetworkConstants.DEFAULT_BUFFER_SIZE)
     : base(nodeConfig, encoder, decoder, allocator, bufferSize)
 {
     BufferSize = bufferSize;
 }
Ejemplo n.º 21
0
 public BaseTree(string name, Vector3 position, Transform transform, NodeConfig nodeConfig)
 {
     _name = name;
     _position = position;
     _nodeConfig = nodeConfig;
     AttachToTransform(transform);
 }
Ejemplo n.º 22
0
        public static string GetSSRLinkForServer(NodeConfig nodeConfig)
        {
            string main_part = nodeConfig.server + ":" + nodeConfig.server_port + ":" + nodeConfig.protocol + ":" + nodeConfig.method + ":" + nodeConfig.obfs + ":" + Base64.EncodeUrlSafeBase64(nodeConfig.password);
            string param_str = "obfsparam=" + Base64.EncodeUrlSafeBase64(nodeConfig.obfsparam ?? "");

            if (!string.IsNullOrEmpty(nodeConfig.protocolparam))
            {
                param_str += "&protoparam=" + Base64.EncodeUrlSafeBase64(nodeConfig.protocolparam);
            }
            if (!string.IsNullOrEmpty(nodeConfig.remarks))
            {
                param_str += "&remarks=" + Base64.EncodeUrlSafeBase64(nodeConfig.remarks);
            }
            if (!string.IsNullOrEmpty(nodeConfig.group))
            {
                param_str += "&group=" + Base64.EncodeUrlSafeBase64(nodeConfig.group);
            }
            if (nodeConfig.udp_over_tcp)
            {
                param_str += "&uot=" + "1";
            }
            if (nodeConfig.server_udp_port > 0)
            {
                param_str += "&udpport=" + nodeConfig.server_udp_port.ToString();
            }
            string base64 = Base64.EncodeUrlSafeBase64(main_part + "/?" + param_str);

            return("ssr://" + base64);
        }
Ejemplo n.º 23
0
        public ReturnStatus Execute()
        {
            ReturnStatus returnStatus = new ReturnStatus();

            try
            {
                NodeConfig config = new NodeConfig();

                string distrinctInfoPath = Path.Combine(config.Get("GEAR_BASE_DIR"), ".settings", "district.info");

                string districtInfo = File.ReadAllText(distrinctInfoPath);

                districtInfo = Regex.Replace(districtInfo, "first_uid=\\d+",
                                             string.Format("first_uid={0}", FirstUid), RegexOptions.Multiline);

                districtInfo = Regex.Replace(districtInfo, "max_uid=\\d+",
                                             string.Format("max_uid={0}", MaxUid), RegexOptions.Multiline);

                File.WriteAllText(distrinctInfoPath, districtInfo);

                //TODO handle profiling

                returnStatus.Output   = string.Format("updated district uid limits with first_uid = {0}, max_uid = {1}", FirstUid, MaxUid);
                returnStatus.ExitCode = 0;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                returnStatus.Output   = ex.ToString();
                returnStatus.ExitCode = 255;
            }

            return(returnStatus);
        }
Ejemplo n.º 24
0
 public Node(string Concept, PointF position, NodeConfig nodeConfig)
 {
     this.Concept = Concept;
     this.X       = position.X;
     this.Y       = position.Y;
     Neighbours   = new List <Edge>();
     NodeConfig   = nodeConfig;
 }
Ejemplo n.º 25
0
 public SerialPortReactor(NodeConfig nodeConfig,
                          IMessageEncoder encoder, IMessageDecoder decoder, IByteBufAllocator allocator,
                          int bufferSize = NetworkConstants.DEFAULT_BUFFER_SIZE)
     : base(nodeConfig, encoder, decoder, allocator,
            bufferSize)
 {
     networkState = CreateNetworkState(Listener, this.LocalEndpoint, allocator.Buffer(bufferSize), bufferSize);
 }
Ejemplo n.º 26
0
        static void RunOptionsAndReturnExitCode(Options opts)
        {
            if (opts.GenerateConfig)
            {
                const string cTemplate = ".\\config_template.xml";
                new AkkaNodeConfig().ToFile <AkkaNodeConfig>(cTemplate);
                Console.WriteLine(@"Template config file ""{0}"" created.", cTemplate);
                System.Environment.Exit(0);
            }

            try
            {
                var config = NodeConfig.FromFile <AkkaNodeConfig>(opts.ConfigPath);
                using (var system = AkkaXmlMessageSystem.Create(config))
                {
                    system.Start(config);
                    var exitHandler = new WinExitSignal(opts.NotInteractive, system);
                    if (opts.NotInteractive)
                    {
                        exitHandler.Exit += (sender, args) => System.Environment.Exit(0);
                        // Waits forever
                        _quitEvent.WaitOne();
                    }
                    else
                    {
                        Console.CancelKeyPress += (sender, e) =>
                        {
                            _quitEvent.Set();
                            e.Cancel = true;
                        };
                        Console.Title = config.NodeId;
                        Console.WriteLine("Press Control-C to exit, Enter to clear screen.");
                        bool exit = false;
                        do
                        {
                            if (Console.KeyAvailable)
                            {
                                var key = Console.ReadKey(true);
                                if (key.Key == ConsoleKey.Enter)
                                {
                                    Console.Clear();
                                }
                            }
                            exit = _quitEvent.WaitOne(100);
                        } while (!exit);
                    }
                }
                System.Environment.Exit(0);
            }
            catch (Exception ex)
            {
                if (!opts.NotInteractive)
                {
                    Console.WriteLine("Error : {0}", ex.Message);
                }
                System.Environment.Exit(1);
            }
        }
 /// <summary>
 /// Build this controller.
 /// </summary>
 /// <param name="config"> Higher level API configuration. </param>
 /// <param name="executor"> Node executor from bitprim-cs library. </param>
 /// <param name="logger"> Abstract logger. </param>
 /// <param name="memoryCache">Memory cache</param>
 public TransactionController(IOptions <NodeConfig> config, Executor executor, ILogger <TransactionController> logger, IMemoryCache memoryCache)
 {
     config_       = config.Value;
     nodeExecutor_ = executor;
     chain_        = executor.Chain;
     logger_       = logger;
     memoryCache_  = memoryCache;
     asmFormatter_ = new AsmFormatter();
 }
Ejemplo n.º 28
0
        //--------------------------------------------------------------------------------------------------------------------
        #endregion

        #region Constructor
        //--------------------------------------------------------------------------------------------------------------------
        public NodePairingBackend(string frontendUrl, NodeConfig conf, OnPairedDelegate callback, OnPairingFailedDelegate onPairingFailedCB)
        {
            this.frontendUrl      = frontendUrl;
            this.pairingPostUrl   = frontendUrl + "/" + NodePairingConstants.PairingRootURI + "/" + PlegmaAPI.APIVersion;
            this.conf             = conf;
            pairingState          = PairingStates.Initial;
            this.onPaired        += callback;
            this.onPairingFailed += onPairingFailedCB;
        }
Ejemplo n.º 29
0
        public void Json_FromStream_Deserializes()
        {
            var tag = new NodeConfig { Tables = new[] { new TableConfig("test string") } };
             var ms = tag.ToJsonString().ToMemoryStream();
             ms.Position = 0;

             var tag2 = ms.ReadAsJsonObject<NodeConfig>(Encoding.UTF8);
             Assert.Equal(tag.Tables[0].TableName, tag2.Tables[0].TableName);
        }
Ejemplo n.º 30
0
        //--------------------------------------------------------------------------------------------------------------------
        #endregion

        #region Constructor
        //--------------------------------------------------------------------------------------------------------------------
        public NodePairingBackend(string frontendUrl, NodeConfig conf, OnPairedDelegate callback, OnPairingFailedDelegate onPairingFailedCB)
        {
            this.frontendUrl = frontendUrl;
            this.pairingPostUrl = frontendUrl + "/" + NodePairingConstants.PairingRootURI + "/" + PlegmaAPI.APIVersion;
            this.conf = conf;
            pairingState = PairingStates.Initial;
            this.onPaired += callback;
            this.onPairingFailed += onPairingFailedCB;
        }
Ejemplo n.º 31
0
 public static Node ToNode(this NodeConfig node, Collection collection)
 {
     return(new Node
     {
         Buttons = node.Buttons.ToList(button => button.ToButton(collection.SubEntityVariants, collection.EntityVariant)),
         BaseType = node.BaseType,
         Panes = node.Panes.ToList(config => config.ToPane())
     });
 }
Ejemplo n.º 32
0
 /// <summary>
 /// Build this controller.
 /// </summary>
 /// <param name="config"> Higher level API configuration. </param>
 /// <param name="executor"> Node executor from bitprim-cs library. </param>
 /// <param name="logger"> Abstract logger. </param>
 /// <param name="memoryCache"> Abstract memory cache. </param>
 public ChainController(IOptions <NodeConfig> config, Executor executor, ILogger <ChainController> logger, IMemoryCache memoryCache)
 {
     config_       = config.Value;
     nodeExecutor_ = executor;
     chain_        = executor.Chain;
     memoryCache_  = memoryCache;
     execPolicy_   = Policy.WrapAsync(retryPolicy_, breakerPolicy_);
     logger_       = logger;
 }
Ejemplo n.º 33
0
        public virtual void SetAttrsDefaultValues()
        {
            NodeConfig cfg = DatabaseManager.NodeDatabase.GetNodeCfgByNodeType(_nodeType);

            if (cfg.defaultAttrValues == null)
            {
                return;
            }
            SetAttrsValues(cfg.defaultAttrValues);
        }
Ejemplo n.º 34
0
 public NodeConfigViewModel(NodeConfig node)
 {
     IsNew         = node is NewNodeConfig;
     Name          = IsNew ? string.Empty : node.Name;
     Uri           = node.Uri;
     UserName      = node.UserName;
     Password      = node.Password;
     SaveCommand   = new DelegateCommand(ExecuteSaveCommand, CanExecuteSaveCommand);
     RemoveCommand = new DelegateCommand(ExecuteRemoveCommand, CanExecuteRemoveCommand);
 }
Ejemplo n.º 35
0
 public BaseTree(string name, Vector3 position, BaseTree parent, NodeConfig nodeConfig)
     : this(name, position, parent.Node.transform, nodeConfig)
 {
     Parent = parent;
     parent._children.Add(this);
 }
Ejemplo n.º 36
0
        // TODO: Where to document? Thows FileNotFound; DirectoryNotFound
        public NodeController()
        {
            if (Properties.Settings.Default.CustomLocation.Length != 0)
            {
                _config = new NodeConfig(Properties.Settings.Default.CustomLocation);
            }
            else
            {
                Exception configException = null;
                foreach (var path in new[]
                {
                    Directory.GetCurrentDirectory(),
                    Environment.ExpandEnvironmentVariables(@"%LocalAppData%\Freenet"),
                })
                {
                    // TODO: If the wrapper has problems with arguments with non-ASCII characters should
                    // this the wrapper invocation change the working directory? Won't work in the general
                    // case because the pidfile location could contain non-ASCII characters, but it
                    // works for the default configuration.
                    // http://sourceforge.net/p/wrapper/bugs/290/
                    try
                    {
                        _config = new NodeConfig(path);
                        configException = null;
                        break;
                    }
                    catch (Exception e)
                    {
                        configException = e;
                    }
                }

                if (configException != null)
                {
                    Log.Error("Failed to detect Freenet installation.", configException);
                    throw configException;
                }
            }

            // Search for an existing wrapper process.
            try
            {
                using (var reader = new StreamReader(_config.PidFilename))
                {
                    var line = reader.ReadLine();

                    if (line != null)
                    {
                        var pid = int.Parse(line);
                        _wrapper = Process.GetProcessById(pid);
                        _wrapper.EnableRaisingEvents = true;
                        _wrapper.Exited += Wrapper_Exited;
                    }
                }
            }
            catch (ArgumentException)
            {
                Log.Debug("No process has the PID in the PID file.");
                // The wrapper can refuse to start if there is a stale PID file - "strict".
                try
                {
                    File.Delete(_config.PidFilename);
                }
                catch (IOException)
                {
                    // TODO: Be louder about this? Or will the wrapper fail to start and exit nonzero?
                    Log.Debug("Stale PID file is still held.");
                }
            }
            catch (FormatException)
            {
                Log.Debug("PID file does not contain an integer.");
            }
            catch (OverflowException)
            {
                Log.Debug("PID file does not contain an integer.");
            }
            catch (FileNotFoundException)
            {
                Log.Debug("PID file not found.");
            }

            /*
             * Hide the wrapper window when launching it. This prevents (or at least heavily complicates)
             * stopping it with Process.CloseMainWindow() or by sending ctrl + C.
             */
            _wrapperInfo.FileName = Path.Combine(_config.RelativeTo, WrapperFilename);
            // TODO: Is it worthwhile to omit the pidfile here when it's in the config file?
            _wrapperInfo.Arguments = "-c " + WrapperConfFilename + " wrapper.pidfile=" + _config.PidFilename;
            _wrapperInfo.UseShellExecute = false;
            _wrapperInfo.CreateNoWindow = true;
        }