public void Start_node()
        {
            using (var loggerFactory = CreateLoggerFactory())
            {
                var cfg  = new NodeOptions("Nodo 1", "1234", 1, 2000, "http://localhost:8000");
                var node = new Node(cfg, new BlockBuilder(), loggerFactory, new PeerChannelInProc());

                try
                {
                    node.Start();
                    int count = 20;
                    while (node.State != NodeState.Running && count-- > 0)
                    {
                        Thread.Sleep(500);
                    }
                    Assert.AreEqual(NodeState.Running, node.State);
                }
                finally
                {
                    node.Stop();
                    int count = 20;
                    while (node.State != NodeState.Stoped && count-- > 0)
                    {
                        Thread.Sleep(500);
                    }
                }
            }
        }
Example #2
0
            public Node SetOptions(NodeOptions remove = NodeOptions.None, NodeOptions add = NodeOptions.None)
            {
                Node node = this;

                node.Options = (node.Options & ~remove) | add;
                return(node);
            }
        /// <summary>
        /// Deserializes a JSON string on a previously existing object.
        /// Throws an exception if the string is null or not a valid JSON string.
        /// </summary>
        /// <param name="obj">Object to deserialize on.</param>
        /// <param name="jsonString">The JSON string to deserialize from.</param>
        /// <param name="options">Deserialization options (optional).</param>
        /// <param name="deserializer">Custom deserializer. If not given,
        /// the default deserializer is used.</param>
        public static void DeserializeOn(
            object obj,
            string jsonString,
            NodeOptions options       = NodeOptions.Default,
            Deserializer deserializer = null)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }
            if (jsonString == null)
            {
                throw new ArgumentNullException("jsonString");
            }
            if (deserializer == null)
            {
                deserializer = Deserializer.Default;
            }

            SimpleJSON.JSONNode node = SimpleJSON.JSON.Parse(jsonString);
            if (node == null)
            {
                throw new ArgumentException("Argument is not a valid JSON string: " + jsonString);
            }
            deserializer.DeserializeOn(obj, node, options);
        }
Example #4
0
 public NodeService(ILoggerFactory loggerFactory, Authenticator authenticator, NodeOptions options)
 {
     _cancellationTokenSource = new CancellationTokenSource();
     _logger        = loggerFactory.CreateLogger <NodeService>();
     _authenticator = authenticator;
     _options       = options;
 }
Example #5
0
        private string _SerializeCustomMember(MemberInfo keyMemberInfo, object value, bool useTupleFormat)
        {
            JSONNodeAttribute attribute = Util.GetAttribute <JSONNodeAttribute> (keyMemberInfo);
            NodeOptions       options   = attribute == null ? NodeOptions.Default : attribute.options;

            if (!options.IsSerialized())
            {
                return(null);
            }

            string valueString = Serialize(value, options);

            if (valueString != null || options.ShouldSerializeNull())
            {
                if (useTupleFormat)
                {
                    return(valueString == null ? _kUndefined : valueString);
                }
                string key = (attribute != null && attribute.key != null) ? attribute.key : keyMemberInfo.Name;
                return(_SerializeString(key) + ":" + (valueString == null ? _kUndefined : valueString));
            }
            else
            {
                return(null);
            }
        }
Example #6
0
 public Node(NodeOptions option)
 {
     this.option       = option;
     this.self         = null;
     this.lineToObject = null;
     this.altLine      = null;
 }
Example #7
0
    private void SelectionAndExpantion()
    {
        int option = ChooseRandomAction();

        if (!currentNode.checkChildren(option))
        {
            MonteCarloTree.Node nodeToAdd = new MonteCarloTree.Node();
            nodeToAdd.NodeOption = option;
            currentNode.AddChild(nodeToAdd);
        }

        float highestUCB = -1.0f;

        MonteCarloTree.Node testNode = currentNode;
        for (int i = 0; i < currentNode.GetNumberOfChildren(); i++)
        {
            float UCB = UpperConfidenceBound(currentNode.GetChild(i));
            if (highestUCB < UCB)
            {
                testNode   = currentNode.GetChild(i);
                highestUCB = UCB;
            }
        }
        currentNode = testNode;
        nodeOptions = (NodeOptions)currentNode.NodeOption;
    }
 /// <summary>
 /// Serializes the object into JSON string.
 /// </summary>
 /// <param name="obj">Object to be serialized.</param>
 /// <param name="options">Serialization options (optional).</param>
 /// <param name="serializer">Custom serializer. If not given,
 /// the default serializer is used.</param>
 public static string ToJSONString(
     this object obj,
     NodeOptions options   = NodeOptions.Default,
     Serializer serializer = null)
 {
     return(Serialize(obj, options, serializer));
 }
Example #9
0
 /// <summary>
 /// Tries to perform application-specific serialization. This is called
 /// first when the #Serialize method is called, and performs internal
 /// serialization if it returns <c>false</c>. This method is called before
 /// ISerializable.Serialize.
 /// </summary>
 /// <param name="obj">Object to serialize. Object is guaranteed to be non-null.</param>
 /// <param name="options">Serialization options.</param>
 /// <param name="serialized">The serialized JSON string.</param>
 protected virtual bool TrySerialize(
     object obj,
     NodeOptions options,
     out string serialized)
 {
     serialized = null;
     return(false);
 }
Example #10
0
 public BaseService(ILogger logger, ClusterOptions clusterOptions, NodeOptions nodeOptions, IStateMachine <State> stateMachine, NodeStateService nodeState)
 {
     _logger          = logger;
     ClusterOptions   = clusterOptions;
     NodeOptions      = nodeOptions;
     StateMachine     = stateMachine;
     NodeStateService = nodeState;
 }
 /// <summary>
 /// Deserializes a JSON string on the previously existing object.
 /// Throws an exception if the string is null or not a valid JSON string.
 /// </summary>
 /// <param name="obj">Object to deserialize on.</param>
 /// <param name="jsonString">The JSON string to deserialize from.</param>
 /// <param name="options">Deserialization options (optional).</param>
 /// <param name="deserializer">Custom deserializer. If not given,
 /// the default deserializer is used.</param>
 public static void FeedJSON(
     this object obj,
     string jsonString,
     NodeOptions options       = NodeOptions.Default,
     Deserializer deserializer = null)
 {
     DeserializeOn(obj, jsonString, options, deserializer);
 }
Example #12
0
        /// <summary>
        /// Gets connected instance list
        /// </summary>
        private async Task GetInstanceList(MqClient client, HorseMessage message)
        {
            foreach (IAdminAuthorization authorization in _server.AdminAuthorizations)
            {
                bool grant = await authorization.CanManageInstances(client, message);

                if (!grant)
                {
                    if (message.WaitResponse)
                    {
                        await client.SendAsync(message.CreateResponse(HorseResultCode.Unauthorized));
                    }

                    return;
                }
            }

            List <NodeInformation> list = new List <NodeInformation>();

            //slave instances
            List <MqClient> slaves = _server.NodeManager.Clients.GetAsClone();

            foreach (MqClient slave in slaves)
            {
                list.Add(new NodeInformation
                {
                    IsSlave     = true,
                    Host        = slave.RemoteHost,
                    IsConnected = slave.IsConnected,
                    Id          = slave.UniqueId,
                    Name        = slave.Name,
                    Lifetime    = slave.ConnectedDate.LifetimeMilliseconds()
                });
            }

            //master instances
            foreach (HmqStickyConnector connector in _server.NodeManager.Connectors)
            {
                NodeOptions options = connector.Tag as NodeOptions;
                HorseClient c       = connector.GetClient();

                list.Add(new NodeInformation
                {
                    IsSlave     = false,
                    Host        = options?.Host,
                    IsConnected = connector.IsConnected,
                    Id          = c.ClientId,
                    Name        = options?.Name,
                    Lifetime    = Convert.ToInt64(connector.Lifetime.TotalMilliseconds)
                });
            }

            HorseMessage response = message.CreateResponse(HorseResultCode.Ok);

            message.ContentType = KnownContentTypes.InstanceList;
            response.Serialize(list, _server.MessageContentSerializer);
            await client.SendAsync(response);
        }
Example #13
0
        public async Task <Node> EditNodeAsync(int id, NodeOptions options, CancellationToken token = default)
        {
            var request = new RestRequest($"/api/application/nodes/{id}", Method.PATCH)
                          .AddJsonBody(options);

            var response = await HandleRequest <Node>(request, token);

            return(response);
        }
Example #14
0
        /// <summary>
        /// Client creation action for server instances
        /// </summary>
        private static HorseClient CreateInstanceClient(NodeOptions options)
        {
            HorseClient client = new HorseClient();

            client.SetClientName(options.Name);
            client.SetClientToken(options.Token);
            client.SetClientType("server");
            return(client);
        }
Example #15
0
        public async Task <Node> CreateNodeAsync(NodeOptions options, CancellationToken token = default)
        {
            var request = new RestRequest($"/api/application/nodes", Method.POST)
                          .AddJsonBody(options);

            var response = await HandleRequest <Node>(request, token);

            return(response);
        }
Example #16
0
 public override Node CreateNode(string name, NodeSize size, NodeImage image, NodeLocation location, NodeAuth auth, NodeOptions options)
 {
     LinodeNodeOptions ops = options as LinodeNodeOptions;
     if (ops == null && options != null)
         throw new Exception ("Only LinodeNodeOptions can be used as NodeOptions for creating Linode Nodes.");
     else if (ops == null)
         ops = new LinodeNodeOptions ();
     return API.CreateNode (name, size, image, location, auth, ops);
 }
Example #17
0
 /// <summary>
 /// Serializes a string into JSON string with the optional
 /// node options.
 /// </summary>
 public string SerializeString(
     string stringValue,
     NodeOptions options = NodeOptions.Default)
 {
     if (stringValue == null)
     {
         return(SerializeNull(options));
     }
     return(_SerializeString(stringValue));
 }
Example #18
0
        private string _SerializeNullable(object nullable, NodeOptions options)
        {
            Type type = nullable.GetType();

            if (!(bool)(type.GetProperty("HasValue").GetValue(nullable, null)))
            {
                return(SerializeNull(options));
            }

            return(Serialize(type.GetProperty("Value").GetValue(nullable, null), options));
        }
Example #19
0
 private InstantiationData _HandleError(NodeOptions options, string message)
 {
     if (options.ShouldIgnoreUnknownType())
     {
         return(InstantiationData.Null);
     }
     else
     {
         throw new InstantiationException(message);
     }
 }
Example #20
0
 /// <summary>
 /// Deserializes an object of the generic type from
 /// the given JSON string. Throws an exception if the string
 /// is null or not a valid JSON string.
 /// </summary>
 /// <param name="jsonString">The JSON string to deserialize from.</param>
 /// <param name="options">Deserialization options (optional).</param>
 /// <param name="deserializer">Custom deserializer. If not given,
 /// the default deserializer is used.</param>
 /// <typeparam name="T">The type of object to deserialize.</typeparam>
 public static T Deserialize <T> (
     string jsonString,
     NodeOptions options       = NodeOptions.Default,
     Deserializer deserializer = null)
 {
     if (deserializer == null)
     {
         deserializer = Deserializer.Default;
     }
     return(deserializer.Deserialize <T> (jsonString, options));
 }
        private static void RunNodeWithSpecifiedId(NodeOptions options)
        {
            new Thread(() =>
            {
                var nodeWorker = IoC.Resolve <IDCCNodeWorker>();

                nodeWorker.Init(options.Id);

                nodeWorker.Start();
            }).Start();
        }
Example #22
0
        public Node(IWallet miner, IListener listener, IPeerFactory peerFactory, NodeOptions options = null)
        {
            this.Engine  = new Engine(miner);
            this.options = options ?? new NodeOptions();

            this.listener = listener;
            this.listener.Start();
            this.peerFactory = peerFactory;
            this.ConnPool    = new ConnectionPool(this, this.options.WellKnownNodes, this.peerFactory, this.listener);
            this.ConnPool.Start();
        }
Example #23
0
 /// <summary>
 /// Tries to instantiate an object of a specific type. This performs
 /// application specific instantiation and subclasses should override
 /// this method to perform their own logic. If the instantiated object is
 /// null, then InstantiationData.Null should be returned.
 /// </summary>
 /// <param name="node">JSON node to create the instance from. This
 /// might be used to decide the type of the object or for the arguments
 /// of a constructor.</param>
 /// <param name="targetType">Target type of the object.</param>
 /// <param name="referingType">Refering type that is only set if this
 /// is a substitute type for another type.</param>
 /// <param name="options">Instantiation options.</param>
 /// <param name="deserializer">Deserializer to use for the instantiation.</param>
 protected virtual bool TryInstantiate(
     JSONNode node,
     Type targetType,
     Type referingType,
     NodeOptions options,
     Deserializer deserializer,
     out InstantiationData instantiationData)
 {
     instantiationData = InstantiationData.Null;
     return(false);
 }
Example #24
0
 /// <summary>
 /// Deserializes a JSON string on a previously existing object.
 /// Throws an exception if the string is null or not a valid JSON string.
 /// </summary>
 /// <param name="obj">Object to deserialize on.</param>
 /// <param name="jsonString">The JSON string to deserialize from.</param>
 /// <param name="options">Deserialization options (optional).</param>
 /// <param name="deserializer">Custom deserializer. If not given,
 /// the default deserializer is used.</param>
 public static void DeserializeOn(
     object obj,
     string jsonString,
     NodeOptions options       = NodeOptions.Default,
     Deserializer deserializer = null)
 {
     if (deserializer == null)
     {
         deserializer = Deserializer.Default;
     }
     deserializer.DeserializeOn(obj, jsonString, options);
 }
Example #25
0
        /// <summary>
        /// Instantiates an object with a suitable constructor. If the
        /// class or the struct has a constructor with the attribute
        /// JSONConstructorAttribute, then that constructor is used, otherwise
        /// the default constructor is used.
        ///
        /// If the instantiated object is null, then InstantiationData.Null is
        /// returned.
        /// </summary>
        /// <param name="jsonString">JSON string to create the instance from. This
        /// might be used for the arguments of the constructor.</param>
        /// <param name="targetType">Target type.</param>
        /// <param name="options">Options.</param>
        /// <param name="deserializer">Deserializer.</param>
        public InstantiationData InstantiateWithConstructor(
            string jsonString,
            Type targetType,
            NodeOptions options       = NodeOptions.Default,
            Deserializer deserializer = null)
        {
            if (jsonString == null)
            {
                throw new ArgumentNullException("jsonString");
            }
            JSONNode node = SimpleJSON.JSON.Parse(jsonString);

            return(InstantiateWithConstructor(node, targetType, options, deserializer));
        }
Example #26
0
 /// <summary>
 /// Serializes a System.Nullable<T> object into JSON string.
 /// Throws an ArgumentException if the object is not of a
 /// nullable type.
 /// </summary>
 public string SerializeNullable(
     object nullable,
     NodeOptions options = NodeOptions.Default)
 {
     if (nullable == null)
     {
         return(SerializeNull(options));
     }
     if (Nullable.GetUnderlyingType(nullable.GetType()) == null)
     {
         throw new ArgumentException("Argument is not a nullable object.");
     }
     return(_SerializeNullable(nullable, options));
 }
Example #27
0
 public void Set(NodeOption opt, params string[] symbols)
 {
     if (!NodeOptions.ContainsKey(opt))
     {
         NodeOptions[opt] = new Dictionary <string, List <dynamic> >();
     }
     foreach (var smb in symbols)
     {
         if (!NodeOptions[opt].ContainsKey(smb))
         {
             NodeOptions[opt].Add(smb, null);
         }
     }
 }
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 48;
            RoleEnvironment.Changing += RoleEnvironmentChanging;

            try
            {
                Trace.WriteLine("OnStart:System is starting up", "Information");
                var    endpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Http"].IPEndpoint;
                string param;
                if (!AzureSettingsProvider.TryGetString("params", out param))
                {
                    param = "";
                }

                var options = new NodeOptions();
                if (!CommandLineParser.Default.ParseArguments(param.Split(' '), options))
                {
                    throw new Exception("Failed to parse: " + param);
                }

                options.HttpPort    = endpoint.Port;
                options.LocalHttpIp = endpoint.Address.ToString();

                // Uncomment these lines and class BlobTraceListener to write traces into blob.
                //var parts = options.StoreLocation.Split('|');
                //var account = CloudStorageAccount.Parse(parts[0]);
                //var client = account.CreateCloudBlobClient();
                //var container = client.GetContainerReference(parts[1]);
                //var blobListener = new BlobTraceListener(container.GetBlobReference("log.txt"));
                //Trace.Listeners.Add(blobListener);

                Trace.WriteLine("");
                Trace.WriteLine(string.Format("Listening endpoint http://{0}:{1}/", endpoint.Address, endpoint.Port), "Information");

                _entryPoint = NodeEntryPoint.StartWithOptions(options, i => RoleEnvironment.RequestRecycle());
            }
            catch (Exception ex)
            {
                Trace.WriteLine("OnStart:Failed " + ex, "Information");
                throw;
            }

            var result = base.OnStart();

            Trace.WriteLine("OnStart:Exit");
            return(result);
        }
 /// <summary>
 /// Serializes the given object into JSON string. Throws an
 /// error if the object is null.
 /// </summary>
 /// <param name="obj">Object to be serialized.</param>
 /// <param name="options">Serialization options (optional).</param>
 /// <param name="serializer">Custom serializer. If not given,
 /// the default serializer is used.</param>
 public static string Serialize(
     object obj,
     NodeOptions options   = NodeOptions.Default,
     Serializer serializer = null)
 {
     if (obj == null)
     {
         throw new ArgumentNullException("obj");
     }
     if (serializer == null)
     {
         serializer = Serializer.Default;
     }
     return(serializer.Serialize(obj, options));
 }
Example #30
0
        public bool Start(HostControl hostControl)
        {
            var nodeOptions = new NodeOptions();

            var config = ConfigurationManager.AppSettings["params"] ?? "";

            if (!CommandLineParser.Default.ParseArguments(config.Split(' '), nodeOptions))
            {
                return(false);
            }

            _entryPoint = NodeEntryPoint.StartWithOptions(nodeOptions, i => Environment.Exit(i));

            return(true);
        }
Example #31
0
        public bool Start(HostControl hostControl)
        {
            var nodeOptions = new NodeOptions();

            var config = ConfigurationManager.AppSettings["params"] ?? "";

            if (!CommandLineParser.Default.ParseArguments(config.Split(' '), nodeOptions))
            {
                return false;
            }

            _entryPoint = NodeEntryPoint.StartWithOptions(nodeOptions, i => Environment.Exit(i));

            return true;
        }
Example #32
0
        /// <summary>
        /// Serializes an object by its fields and properties. This will
        /// ignore custom serializations of the object (see Serializer.TrySerialize
        /// and ISerializable.Serialize). This will throw an argument exception if
        /// the object is a non-struct value type (primitives and enums).
        /// </summary>
        public string SerializeByParts(object obj, NodeOptions options = NodeOptions.Default)
        {
            if (obj == null)
            {
                return(SerializeNull(options));
            }
            Type type = obj.GetType();

            if (type.IsPrimitive || type.IsEnum)
            {
                throw new ArgumentException("Cannot serialize non-struct value types by parts.");
            }

            return(_SerializeCustom(obj, options));
        }
Example #33
0
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 48;
            RoleEnvironment.Changing += RoleEnvironmentChanging;

            try
            {
                Trace.WriteLine("OnStart:System is starting up", "Information");
                var endpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Http"].IPEndpoint;
                string param;
                if (!AzureSettingsProvider.TryGetString("params", out param))
                    param = "";

                var options = new NodeOptions();
                if (!CommandLineParser.Default.ParseArguments(param.Split(' '), options))
                    throw new Exception("Failed to parse: " + param);

                options.HttpPort = endpoint.Port;
                options.LocalHttpIp = endpoint.Address.ToString();

                // Uncomment these lines and class BlobTraceListener to write traces into blob.
                //var parts = options.StoreLocation.Split('|');
                //var account = CloudStorageAccount.Parse(parts[0]);
                //var client = account.CreateCloudBlobClient();
                //var container = client.GetContainerReference(parts[1]);
                //var blobListener = new BlobTraceListener(container.GetBlobReference("log.txt"));
                //Trace.Listeners.Add(blobListener);

                Trace.WriteLine("");
                Trace.WriteLine(string.Format("Listening endpoint http://{0}:{1}/", endpoint.Address, endpoint.Port), "Information");

                _entryPoint = NodeEntryPoint.StartWithOptions(options, i => RoleEnvironment.RequestRecycle());
            }
            catch (Exception ex)
            {
                Trace.WriteLine("OnStart:Failed " + ex, "Information");
                throw;
            }

            var result = base.OnStart();

            Trace.WriteLine("OnStart:Exit");
            return result;
        }
Example #34
0
        public override Node CreateNode(string name, NodeSize size, NodeImage image, NodeLocation location, NodeAuth auth, NodeOptions options)
        {
            EC2NodeOptions ops = options as EC2NodeOptions;
            if (ops == null && options != null)
                throw new Exception ("Only EC2NodeOptions can be used as NodeOptions for creating EC2 Nodes.");
            else if (ops == null)
                ops = new EC2NodeOptions ();

            RunInstancesRequest request = new RunInstancesRequest () {
                InstanceType = size.Id,
                ImageId = image.Id,
                MinCount = 1,
                MaxCount = 1,
                KeyName = auth.UserName,
            };
            RunInstancesResponse response = Client.RunInstances (request);

            foreach (var i in response.RunInstancesResult.Reservation.RunningInstance) {
                return EC2Node.FromRunningInstance (i, this);
            }

            return null;
        }
Example #35
0
        public void WriteStartNode(string id, NodeOptions options)
        {
            if (id == null)
            {
                throw new System.ArgumentNullException("id");
            }
            this.checkstate(WriterState.Graph);
            this.state = WriterState.Node;

            this.write(id);
            if (options != null)
            {
                this.write(" [ ");

                if (options.Label != null)
                {
                    this.WriteNodeOption("label", options.Label);
                }
                if (options.FontName != null)
                {
                    this.WriteNodeOption("fontname", options.FontName);
                }

                if (options.FillColor != null)
                {
                    this.WriteNodeOption("fillcolor", options.FillColor.Value.ToWebColorString());
                }


                if (options.FontColor != null)
                {
                    this.WriteNodeOption("fontcolor", options.FontColor.Value.ToWebColorString());
                }

                if (options.FontSize.HasValue)
                {
                    this.WriteNodeOption("fontsize", options.FontSize.Value);
                }

                if (options.Shape != null)
                {
                    this.WriteNodeOption("shape", options.Shape.Value.ToString().ToLower());
                }

                if (options.Style != null)
                {
                    this.WriteNodeOption("style", options.Style.Value.ToString().ToLower());
                }

                if (options.Width.HasValue)
                {
                    this.WriteNodeOption("width", options.Width.Value);
                }

                if (options.Height.HasValue)
                {
                    this.WriteNodeOption("height", options.Height.Value);
                }

                if (options.URL != null)
                {
                    this.WriteNodeOption("url", options.URL);
                }

                if (options.ToolTip != null)
                {
                    this.WriteNodeOption("tooltip", options.ToolTip);
                }

                if (options.Z != null)
                {
                    this.WriteNodeOption("z", options.Z.Value);
                }

                this.write(" ]");
            }

            this.writeline("");
        }