Ejemplo n.º 1
0
 public void Resume()
 {
     if (this.State == RunState.Paused)
     {
         this.State = RunState.Starting;
         this.logger.WriteEntry("Resume: Called", EventLogEntryType.Information);
         this.running = false; //tells the monitor to stop
         while (this.monitoring)
         {
             Thread.Sleep(1); //wait for the monitor to stop
         }
         HostCommunication comm     = this.comms;
         HostMessage       response = this.SendMessage(this.procs, comm, HostCommand.Resume, null);
         if (response != null && response.Command == HostCommand.Resume)
         {
             if (response.Message.StartsWith("success"))
             {
                 this.logger.WriteEntry("Resume: started", EventLogEntryType.Information);
             }
             else
             {
                 this.logger.WriteEntry("Resume: failed resuming", EventLogEntryType.Information);
             }
         }
         this.State = RunState.Running;
     }
 }
Ejemplo n.º 2
0
        public async Task <FunctionResult> ExecuteAsync(IStorageQueueMessage value, CancellationToken cancellationToken)
        {
            HostMessage model = JsonConvert.DeserializeObject <HostMessage>(value.AsString, JsonSerialization.Settings);

            if (model == null)
            {
                throw new InvalidOperationException("Invalid invocation message.");
            }

            CallAndOverrideMessage callAndOverrideModel = model as CallAndOverrideMessage;

            if (callAndOverrideModel != null)
            {
                await ProcessCallAndOverrideMessage(callAndOverrideModel, cancellationToken);

                return(new FunctionResult(true));
            }

            AbortHostInstanceMessage abortModel = model as AbortHostInstanceMessage;

            if (abortModel != null)
            {
                ProcessAbortHostInstanceMessage();
                return(new FunctionResult(true));
            }

            string error = String.Format(CultureInfo.InvariantCulture, "Unsupported invocation type '{0}'.", model.Type);

            throw new NotSupportedException(error);
        }
Ejemplo n.º 3
0
 public void Shutdown()
 {
     if (this.State == RunState.Running || this.State == RunState.Stopped)
     {
         this.logger.WriteEntry("Shutdown: Called");
         this.running = false; //tells the monitor to stop
         while (this.monitoring)
         {
             Thread.Sleep(1); //wait for the monitor to stop
         }
         HostCommunication comm     = comms;
         HostMessage       response = this.SendMessage(this.procs, comm, HostCommand.Shutdown, null);
         if (response != null && response.Command == HostCommand.Shutdown)
         {
             if (response.Message.StartsWith("success"))
             {
                 this.logger.WriteEntry("Shutdown: started", EventLogEntryType.Information);
             }
             else
             {
                 this.logger.WriteEntry("Shutdown: failed shutting down", EventLogEntryType.Warning);
             }
         }
         this.State = RunState.Shutdown;
     }
 }
Ejemplo n.º 4
0
        private bool RestartProcess(string fileName)
        {
            try
            {
                Process p = this.procs;
                if (p != null && !p.HasExited)
                {
                    p.Kill();
                }

                p = CreateProcess(fileName);
                if (p.Start())
                {
                    HostCommunication comm = new HostCommunication(p.StandardOutput, p.StandardInput);
                    //we need to also init this thing
                    HostMessage response = this.SendMessage(p, comm, HostCommand.Init, null);
                    if (response != null && response.Command == HostCommand.Init)
                    {
                        if (response.Message.StartsWith("success"))
                        {
                            response = this.SendMessage(p, comm, HostCommand.Start, null);
                            if (response != null && response.Command == HostCommand.Start)
                            {
                                if (response.Message.StartsWith("success"))
                                {
                                    this.comms = comm;
                                    this.procs = p;
                                    return(true);
                                }
                                else
                                {
                                    p.Kill();
                                }
                            }
                            else
                            {
                                p.Kill();
                            }
                        }
                        else
                        {
                            p.Kill();
                        }
                    }
                    else
                    {
                        p.Kill();
                    }
                }
            }
            catch
            { }
            return(false);
        }
Ejemplo n.º 5
0
        private void MonitorServices()
        {
            this.monitoring = true;
            this.running    = true;
            string success  = Osrs.Runtime.RunState.Running.ToString();
            string failed   = Osrs.Runtime.RunState.FailedRunning.ToString();
            string starting = Osrs.Runtime.RunState.Starting.ToString();
            string stopping = Osrs.Runtime.RunState.Stopping.ToString();

            while (this.running)
            {
                //make a copy of the list so we're sure we can mutate the lists for restart
                HostCommunication comm     = this.comms;
                HostMessage       response = this.SendMessage(this.procs, comm, HostCommand.HeartBeat, null);
                if (response != null && response.Command == HostCommand.HeartBeat)
                {
                    if (!response.Message.StartsWith(Osrs.Runtime.RunState.Running.ToString()))
                    {
                        if (response.Message.StartsWith(starting) || response.Message.StartsWith(stopping))
                        {
                            continue; //may need to deal with hangs later
                        }
                        if (response.Message.StartsWith(failed))
                        {
                            this.logger.WriteEntry("Monitor: problem " + response.Message, EventLogEntryType.Warning);
                            if (this.RestartProcess(this.fileName))
                            {
                                this.logger.WriteEntry("Monitor: successfully restarted", EventLogEntryType.Information);
                            }
                            else
                            {
                                this.logger.WriteEntry("Monitor: failed to restart", EventLogEntryType.Warning);
                            }
                        }
                        else
                        {
                            this.logger.WriteEntry("Monitor: problem (ignored)" + response.Message, EventLogEntryType.Warning);
                        }
                    }
                }
                if (!this.running) //get us out ASAP
                {
                    break;
                }
                for (int i = 0; i < 10; i++)
                {
                    if (this.running)      //get us out ASAP
                    {
                        Thread.Sleep(500); //5 seconds in total
                    }
                }
            }
            this.monitoring = false;
        }
        private async void SendScoreboard(Object state)
        {
            var message = new HostMessage
            {
                Type         = HostMessageType.Scoreboard,
                PlayerScores = Scorecards,
                TimeSent     = DateTime.Now
            };

            await DispatcherHelper.ExecuteOnUIThreadAsync(async() =>
                                                          await App.SessionManager.SendMessageToParticipantsAsync(message));
        }
Ejemplo n.º 7
0
        public void JsonConvert_Roundtrips()
        {
            // Arrange
            HostMessage roundtrip = new HostMessage();

            // Act
            HostMessage message = JsonConvert.DeserializeObject <HostMessage>(
                JsonConvert.SerializeObject(roundtrip));

            // Assert
            Assert.NotNull(message);
            Assert.Equal(typeof(HostMessage).Name, message.Type);
        }
        public void JsonConvert_Roundtrips()
        {
            // Arrange
            HostMessage roundtrip = new HostMessage();

            // Act
            HostMessage message = JsonConvert.DeserializeObject<HostMessage>(
                JsonConvert.SerializeObject(roundtrip));

            // Assert
            Assert.NotNull(message);
            Assert.Equal(typeof(HostMessage).Name, message.Type);
        }
Ejemplo n.º 9
0
        static void Shutdown()
        {
            lock (syncRoot)
            {
                HostMessage m = new HostMessage();
                m.Command = HostCommand.Shutdown;
                state     = RunState.Stopping;
                HostingManager.Instance.Shutdown();
                state     = RunState.Shutdown;
                m.Message = "success";

                comms.Send(m);
            }
        }
        /// <inheritdoc />
        public void Enqueue(string queueName, HostMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            CloudQueue queue = _client.GetQueueReference(queueName);
            Debug.Assert(queue != null);
            queue.CreateIfNotExists();
            string content = JsonConvert.SerializeObject(message, JsonSerialization.Settings);
            Debug.Assert(content != null);
            CloudQueueMessage queueMessage = new CloudQueueMessage(content);
            queue.AddMessage(queueMessage);
        }
Ejemplo n.º 11
0
        /// <inheritdoc />
        public async Task EnqueueAsync(string queueName, HostMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            CloudQueue queue = _client.GetQueueReference(queueName);

            Debug.Assert(queue != null);
            await queue.CreateIfNotExistsAsync();

            string content = JsonConvert.SerializeObject(message, JsonSerialization.Settings);

            Debug.Assert(content != null);
            CloudQueueMessage queueMessage = new CloudQueueMessage(content);
            await queue.AddMessageAsync(queueMessage);
        }
Ejemplo n.º 12
0
        public void JsonConvertDerivedType_Roundtrips()
        {
            // Arrange
            CallAndOverrideMessage expectedMessage = new CallAndOverrideMessage
            {
                Id = Guid.NewGuid()
            };

            // Act
            HostMessage message = JsonConvert.DeserializeObject <HostMessage>(
                JsonConvert.SerializeObject(expectedMessage));

            // Assert
            Assert.NotNull(message);
            Assert.IsType <CallAndOverrideMessage>(message);
            CallAndOverrideMessage typedMessage = (CallAndOverrideMessage)message;

            Assert.Equal(expectedMessage.Id, typedMessage.Id);
        }
Ejemplo n.º 13
0
 private HostMessage SendMessage(Process p, HostCommunication comm, HostCommand cmd, string msg)
 {
     try
     {
         if (!p.HasExited)
         {
             HostMessage mess = new HostMessage();
             mess.Command = cmd;
             if (msg != null)
             {
                 mess.Message = msg;
             }
             return(comm.SendReceive(mess));
         }
     }
     catch
     { }
     return(new HostMessage());
 }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            Environment.CurrentDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
            comms = new HostCommunication(Console.In, Console.Out);

            //basic REPL loop logic on main thread
            while (true)
            {
                HostMessage message = comms.Receive();
                if (message.Command == HostCommand.HeartBeat)
                {
                    message.Message = HostingManager.Instance.RealtimeState().ToString();
                    comms.Send(message); //just an echo back
                }
                else if (message.Command == HostCommand.Pause)
                {
                    Pause();
                }
                else if (message.Command == HostCommand.Resume)
                {
                    Resume();
                }
                else if (message.Command == HostCommand.Stop)
                {
                    Stop();
                }
                else if (message.Command == HostCommand.Start)
                {
                    Start();
                }
                else if (message.Command == HostCommand.Init)
                {
                    Init();
                }
                else if (message.Command == HostCommand.Shutdown)
                {
                    Shutdown();
                    Environment.Exit(0); //exits the app
                }
            }
        }
Ejemplo n.º 15
0
        static void Resume()
        {
            lock (syncRoot)
            {
                HostMessage m = new HostMessage();
                m.Command = HostCommand.Start;
                if (state == RunState.Paused)
                {
                    state = RunState.Starting;
                    HostingManager.Instance.Resume();
                    state     = RunState.Running;
                    m.Message = "success";
                }
                else
                {
                    m.Message = "ignored";
                }

                comms.Send(m);
            }
        }
Ejemplo n.º 16
0
 public void Pause()
 {
     if (this.State == RunState.Running)
     {
         this.State = RunState.Stopping;
         this.logger.WriteEntry("Pause: Called");
         HostCommunication comm     = this.comms;
         HostMessage       response = this.SendMessage(this.procs, comm, HostCommand.Pause, null);
         if (response != null && response.Command == HostCommand.Pause)
         {
             if (response.Message.StartsWith("success"))
             {
                 this.logger.WriteEntry("Pause: started", EventLogEntryType.Information);
             }
             else
             {
                 this.logger.WriteEntry("Pause: failed pausing", EventLogEntryType.Warning);
             }
         }
         this.State = RunState.Paused;
     }
 }
        public async Task <MessageWithReply> GetChanelMessages(string messageId)
        {
            Models.Message data = await _data.GetChannelMessages(messageId);

            ReplyMessage replyData = await _data.GetReplyMessages(messageId);

            var hostData = new HostMessage {
                CreatedDateTime = data.CreatedDateTime, HostUserId = data.From.User.Id
            };
            IEnumerable <ReplyMessageData> reply = replyData.Value.Select(s =>
            {
                return(new ReplyMessageData
                {
                    CreatedDateTime = s.CreatedDateTime,
                    Content = s.Body.Content,
                    UserId = s.From.User.Id
                });
            }).OrderBy(o => o.CreatedDateTime);

            return(new MessageWithReply {
                Message = hostData, ReplyMessage = reply
            });
        }
Ejemplo n.º 18
0
        public void Start(EventLog logger)
        {
            this.logger = logger;
            if (this.State == RunState.Created || this.State == RunState.FailedInitializing)
            {
                this.Init();
            }

            if (this.State == RunState.Initialized || this.State == RunState.Stopped)
            {
                this.State = RunState.Starting;
                this.logger.WriteEntry("Start: Called");
                if (File.Exists(this.fileName))
                {
                    if (this.procs == null) //new for this startup
                    {
                        try
                        {
                            Process p = this.CreateProcess(this.fileName);
                            if (p.Start())
                            {
                                HostCommunication comm = new HostCommunication(p.StandardOutput, p.StandardInput);
                                //we need to also init this thing
                                HostMessage response = this.SendMessage(p, comm, HostCommand.Init, null);
                                if (response != null && response.Command == HostCommand.Init)
                                {
                                    if (response.Message.StartsWith("success"))
                                    {
                                        this.logger.WriteEntry("Start: initialized");
                                        this.comms = comm;
                                        this.procs = p;
                                    }
                                }
                                else
                                {
                                    p.Kill();
                                }
                            }
                            else
                            {
                                p.Kill();
                            }
                        }
                        catch
                        { }
                    }

                    if (this.procs != null)
                    {
                        HostCommunication comm     = this.comms;
                        HostMessage       response = this.SendMessage(this.procs, comm, HostCommand.Start, null);
                        if (response != null && response.Command == HostCommand.Start)
                        {
                            if (response.Message.StartsWith("success"))
                            {
                                this.logger.WriteEntry("Start: started");
                            }
                            else
                            {
                                this.logger.WriteEntry("Start: failed starting", EventLogEntryType.Warning);
                            }
                        }
                    }
                    else
                    {
                        this.logger.WriteEntry("Start: no process", EventLogEntryType.Warning);
                        this.State = RunState.FailedStarting;
                        return;
                    }
                }
                else
                {
                    this.logger.WriteEntry("Start: failed to find", EventLogEntryType.Warning);
                    this.State = RunState.FailedStarting;
                    return;
                }

                //we've started
                this.logger.WriteEntry("Start: Succeeded, starting monitoring");
                Task t = new Task(this.MonitorServices);
                t.Start();
                this.State = RunState.Running;
            }
        }
Ejemplo n.º 19
0
        private void __OnRegistered(Network.Node player)
        {
            if (player == null)
            {
                return;
            }

            short index = player.index;

            player.RegisterHandler((short)HostMessageHandle.Ready, delegate(NetworkReader reader)
            {
                Ready(index);
            });

            player.RegisterHandler((short)HostMessageHandle.NotReady, delegate(NetworkReader reader)
            {
                NotReady(index);
            });

            Node node;

            if (GetNode(player.index, out node))
            {
                IEnumerable <KeyValuePair <int, Network.Node> > room = GetRoom(node.roomIndex);
                if (room != null)
                {
                    NetworkWriter writer = new NetworkWriter();
                    writer.Write((short)HostMessageHandle.Ready);
                    writer.Write(new ReadyMessage());
                    HostMessage hostMessage = new HostMessage(-1, writer.Position, writer.AsArray());
                    Lobby.Node  instance;
                    int         i;
                    foreach (KeyValuePair <int, Network.Node> pair in room)
                    {
                        instance = pair.Value as Lobby.Node;
                        if (instance != null)
                        {
                            hostMessage.index = instance.index;
                            for (i = 0; i < instance._count; ++i)
                            {
                                Send(node.connectionId, (short)Network.HostMessageType.Rpc, hostMessage);
                            }
                        }
                    }

                    IEnumerable <int> neighborRoomIndices = GetNeighborRoomIndices(node.roomIndex);
                    if (neighborRoomIndices != null)
                    {
                        foreach (int neighborRoomIndex in neighborRoomIndices)
                        {
                            room = GetRoom(neighborRoomIndex);
                            if (room == null)
                            {
                                continue;
                            }

                            foreach (KeyValuePair <int, Network.Node> pair in room)
                            {
                                instance = pair.Value as Lobby.Node;
                                if (instance != null)
                                {
                                    hostMessage.index = instance.index;
                                    for (i = 0; i < instance._count; ++i)
                                    {
                                        Send(node.connectionId, (short)Network.HostMessageType.Rpc, hostMessage);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 20
0
        protected override bool _Unregister(NetworkReader reader, int connectionId, short index)
        {
            int count = 0;

            while (__NotReady(index, connectionId >= 0))
            {
                ++count;
            }

            if (connectionId >= 0 && count > 0)
            {
                Node node;
                if (GetNode(index, out node))
                {
                    IEnumerable <KeyValuePair <int, Network.Node> > room = GetRoom(node.roomIndex);
                    if (room != null)
                    {
                        NetworkWriter writer = new NetworkWriter();
                        writer.Write((short)HostMessageHandle.NotReady);
                        writer.Write(new NotReadyMessage());
                        HostMessage hostMessage = new HostMessage(-1, writer.Position, writer.AsArray());
                        Lobby.Node  instance;
                        int         i;

                        foreach (KeyValuePair <int, Network.Node> pair in room)
                        {
                            instance = pair.Value as Lobby.Node;
                            if (instance != null)
                            {
                                hostMessage.index = instance.index;
                                for (i = 0; i < instance._count; ++i)
                                {
                                    Send(connectionId, (short)Network.HostMessageType.Rpc, hostMessage);
                                }
                            }
                        }

                        IEnumerable <int> neighborRoomIndices = GetNeighborRoomIndices(node.roomIndex);
                        if (neighborRoomIndices != null)
                        {
                            foreach (int neighborRoomIndex in neighborRoomIndices)
                            {
                                room = GetRoom(neighborRoomIndex);
                                if (room == null)
                                {
                                    continue;
                                }

                                foreach (KeyValuePair <int, Network.Node> pair in room)
                                {
                                    instance = pair.Value as Lobby.Node;
                                    if (instance != null)
                                    {
                                        hostMessage.index = instance.index;
                                        for (i = 0; i < instance._count; ++i)
                                        {
                                            Send(connectionId, (short)Network.HostMessageType.Rpc, hostMessage);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 21
0
        static void Init()
        {
            lock (syncRoot)
            {
                HostMessage m = new HostMessage();
                m.Command = HostCommand.Init;

                if (state == RunState.Created)
                {
                    IEnumerable <TypeNameReference> names = null;
                    m.Message = "";

                    LogProviderBase log = null;
                    try
                    {
                        ConfigurationManager.Instance.Bootstrap();
                        ConfigurationManager.Instance.Initialize();
                        ConfigurationManager.Instance.Start();
                        if (ConfigurationManager.Instance.State == RunState.Running)
                        {
                            LogManager.Instance.Bootstrap();
                            LogManager.Instance.Initialize();
                            LogManager.Instance.Start();
                            if (LogManager.Instance.State == RunState.Running)
                            {
                                log = LogManager.Instance.GetProvider(typeof(Program));
                            }
                            if (log == null)
                            {
                                log = new NullLogger(typeof(Program));
                            }

                            ConfigurationProviderBase prov = ConfigurationManager.Instance.GetProvider();
                            if (prov != null)
                            {
                                ConfigurationParameter param = prov.Get(typeof(Program), "hostList");
                                if (param != null)
                                {
                                    string[] values = param.Value as string[];
                                    if (values != null && values.Length > 0)
                                    {
                                        HashSet <TypeNameReference> tps = new HashSet <TypeNameReference>();
                                        foreach (string s in values)
                                        {
                                            TypeNameReference cur = TypeNameReference.Parse(s);
                                            if (cur != null)
                                            {
                                                tps.Add(cur);
                                            }
                                            else
                                            {
                                                log.Log(5, "Failed to parse TypeName for: " + s);
                                            }
                                        }
                                        if (tps.Count > 0)
                                        {
                                            names = tps;
                                        }
                                    }
                                    else
                                    {
                                        m.Message = "Failed to get configuration value";
                                        log.Log(1000, m.Message);
                                    }
                                }
                                else
                                {
                                    m.Message = "Failed to get configuration parameter: hostList";
                                    log.Log(1000, m.Message);
                                }
                            }
                            else
                            {
                                m.Message = "Failed to get configuration provider";
                                log.Log(1000, m.Message);
                            }
                        }
                        else
                        {
                            m.Message = "Failed to initialize using local file, quitting (" + AppContext.BaseDirectory + ")";
                            if (log != null)
                            {
                                log.Log(1000, m.Message);
                            }
                        }
                    }
                    catch
                    {
                        m.Message = "Failed to initialize using config, falling back to local file";
                        if (log != null)
                        {
                            log.Log(1000, m.Message);
                        }
                    }

                    if (names != null)
                    {
                        HostingManager.Instance.Initialize(names);
                        state = HostingManager.Instance.State;
                        if (state == RunState.Initialized)
                        {
                            m.Message = "success " + m.Message;
                            if (log != null)
                            {
                                log.Log(0, m.Message);
                            }
                        }
                        else
                        {
                            m.Message = "failed " + m.Message;
                            if (log != null)
                            {
                                log.Log(1000, m.Message);
                            }
                        }
                    }
                    else
                    {
                        state     = HostingManager.Instance.State;
                        m.Message = "failed " + m.Message;
                        if (log != null)
                        {
                            log.Log(1000, m.Message);
                        }
                    }
                }
                else
                {
                    state     = HostingManager.Instance.State;
                    m.Message = "ignored";
                }

                comms.Send(m);
            }
        }