コード例 #1
0
        public CloudManagerLocal(List <CloudMakefile> leaderCloudMakefiles, CloudMakefile localCloudMakefile,
                                 string name, List <List <string> > leaders, List <string> reserveLeaders, int nreplicas,
                                 int timeout, Vsync.Group vsyncGroup, string debugFilename,
                                 string monitorDebugFilename)
        {
            _vsyncAddress         = VsyncSystem.GetMyAddress().ToStringVerboseFormat();
            _name                 = name;
            _curDirectory         = Directory.GetCurrentDirectory();
            _procs                = new Dictionary <string, ProcessInfo> ();
            _procsLock            = new object();
            _leaders              = leaders;
            _reserveLeaders       = reserveLeaders;
            _nreplicas            = nreplicas;
            _leaderCloudMakefiles = leaderCloudMakefiles;
            _localCloudMakefile   = localCloudMakefile;
            _queue                = new List <Tuple <MessageType, List <string> > > ();
            _queueLock            = new object();
            _debugFilename        = debugFilename;
            _cloudMakeMonitor     = new CloudMakeMonitor(this, monitorDebugFilename, timeout);
            Thread cloudMakeMonitorThread = new Thread(delegate() {
                _cloudMakeMonitor.Run(vsyncGroup);
            });

            cloudMakeMonitorThread.Start();
        }
コード例 #2
0
 public CloudManagerLeader(List <CloudMakefile> leaderCloudMakefiles,
                           Dictionary <string, CloudMakefile> localCloudMakefiles,
                           Dictionary <string, string> nameToAddress, Dictionary <string, string> addressToName,
                           List <List <string> > leaders, List <string> reserveLeaders, int nreplicas,
                           string workingDir, string debugFilename)
 {
     _vsyncAddress         = VsyncSystem.GetMyAddress().ToStringVerboseFormat();
     _leaders              = leaders;
     _reserveLeaders       = reserveLeaders;
     _nreplicas            = nreplicas;
     _leaderCloudMakefiles = leaderCloudMakefiles;
     _localCloudMakefiles  = localCloudMakefiles;
     _partition            = CloudManager.FindPartition(_leaders, _reserveLeaders, _vsyncAddress);
     if (_partition >= 0)
     {
         _rank  = _leaders [_partition].IndexOf(_vsyncAddress);
         _state = _rank == 0 ? State.ACTIVE : State.WAITFORSTATE;
     }
     else if (_partition == -1)
     {
         _rank  = _reserveLeaders.IndexOf(_vsyncAddress);
         _state = State.INITIAL;
     }
     else
     {
         throw new Exception("CloudMakeLeader: I cannot find myself.\n");
     }
     _nameToAddress    = nameToAddress;
     _addressToName    = addressToName;
     _queue            = new List <Tuple <MessageType, List <string> > > ();
     _queueLock        = new object();
     _pending          = new List <Tuple <MessageType, List <string> > > ();
     _updatesDelivered = 0;
     _debugFilename    = debugFilename;
     _workingDir       = workingDir;
     if (!Directory.Exists(_workingDir))
     {
         throw new Exception("CloudMakeLeader: CloudMakeLeader directory " + _workingDir + " does not exist.");
     }
     Directory.SetCurrentDirectory(_workingDir);
 }
コード例 #3
0
        public static void Main(string[] args)
        {
            String roomname = "no roomname given";

            Console.WriteLine("THE SIZE OF ARGS IS " + args.Length);
            if (args.Length < 2)
            {
                Console.WriteLine("There are less than 2 args given.  This is fine for now, but in the future we need to give the room name.");
            }
            else
            {
                roomname = args [1];
                int max_port  = 65000;
                int min_port  = 15000;
                int port_diff = max_port - min_port;
                int room_hash = roomname.GetHashCode();
                room_hash = room_hash % port_diff;
                room_hash = room_hash + port_diff;
                room_hash = room_hash % port_diff;
                Console.WriteLine("Mod is " + room_hash);
                room_hash += min_port;
                Vsync.Vsync.VSYNC_GROUPPORT = room_hash;
                Console.WriteLine("VSYNC PORT NO IS " + room_hash);
            }

            currentRoom = new Room(roomname);
            ID          = Path.GetRandomFileName().Replace(".", "");
            Console.WriteLine("User ID IS " + ID);

            //Set up TCP Listener
            Console.WriteLine(args [0]);
            int         port   = Int32.Parse(args [0]);
            TcpListener server = new TcpListener(port);

            server.Start();
            Console.WriteLine("Server has started on 127.0.0.1:{0}.\nWaiting for a connection...", port);
            client = server.AcceptTcpClient();
            stream = client.GetStream();
            Console.WriteLine("Matched with a client! Now Starting VSYNC");

            VsyncSystem.Start();
            Console.WriteLine("VSYNC STARTED");
            String groupName = "TEST ROOM";

            roomGroup = new Vsync.Group(groupName);
            roomGroup.ViewHandlers += (ViewHandler) delegate(View v) {
                VsyncSystem.WriteLine("New View: " + v);
                Console.Title = "View " + v.viewid + ", my rank=" + v.GetMyRank();
            };
            roomGroup.Handlers [UPDATE] += (Action <string, string>) delegate(string username, string val) {
                lock (currentRoom) {
                    currentRoom.playerLocs [username] = val;
                }
                lock (updateLock) {
                    updateCount++;
                }
            };
            roomGroup.Handlers [LOOKUP] += (Action <string>) delegate(string s) {
                //VsyncSystem.WriteLine("IN LOOKUP");
                lock (currentRoom) {
                    roomGroup.Reply(currentRoom.playerLocs [s]);
                }
            };
            roomGroup.Handlers [REFRESH] += (Action) delegate() {
                lock (currentRoom) {
                    string reply = Extensions.FromDictionaryToJson(currentRoom.playerLocs);
                    roomGroup.Reply(reply);
                }
            };
            roomGroup.Handlers [JOIN_ROOM] += (Action <string>) delegate(string username) {
                lock (currentRoom) {
                    if (currentRoom.players.Count >= MAX_IN_ROOM)
                    {
                        roomGroup.Reply("FULL");
                    }
                    else
                    {
                        currentRoom.players.Add(username);
                        roomGroup.Reply("JOINED");
                    }
                }
            };
            roomGroup.Handlers [LEAVE_ROOM] += (Action <string>) delegate(string s) {
                Console.WriteLine("IN LEAVE ROOM");
                lock (currentRoom) {
                    currentRoom.playerLocs.Remove(s);
                    currentRoom.players.Remove(s);
                }
            };
            roomGroup.Join();
            Console.WriteLine("Room Group Joined");
            Console.WriteLine(groupName);

            List <String> results = new List <String> ();

            roomGroup.OrderedQuery(Vsync.Group.ALL, JOIN_ROOM, ID, new Vsync.EOLMarker(), results);
            Boolean full = false;

            for (int j = 0; j < results.Count; j++)
            {
                if (results [j].Equals("FULL"))
                {
                    Console.WriteLine("FULL");
                    full = true;
                }
            }
            if (full)
            {
                roomGroup.OrderedSend(LEAVE_ROOM, ID);
                Byte[] r    = Encoding.UTF8.GetBytes("ROOM FULL");
                Byte[] resp = Helpers.Connections.encode(r);
                stream.Write(resp, 0, resp.Length);
                client.Close();
                Console.WriteLine("LEAVING ROOM");
                roomGroup.Leave();
                return;
            }

            send_timer          = new System.Timers.Timer();
            send_timer.Elapsed += send_info;
            send_timer.Interval = UPDATE_RATE;
            send_timer.Start();

            test_timer          = new System.Timers.Timer();
            test_timer.Elapsed += test_print;
            test_timer.Interval = 10000;
            test_timer.Start();


            Byte[] bytes = new Byte[4096];
            String data  = null;

            int i = Helpers.Connections.checkRead(stream, bytes);

            //Continuously read from the buffer while the connection is open
            while (i != 0)
            {
                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                //First request -> Respond with HTTP Change Protocol Handshake
                if (new Regex("^GET").IsMatch(data))
                {
                    Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
                                                             + "Connection: Upgrade" + Environment.NewLine
                                                             + "Upgrade: websocket" + Environment.NewLine
                                                             + "Sec-WebSocket-Accept: " + Convert.ToBase64String(
                                                                 SHA1.Create().ComputeHash(
                                                                     Encoding.UTF8.GetBytes(
                                                                         new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups [1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
                                                                         )
                                                                     )
                                                                 ) + Environment.NewLine
                                                             + Environment.NewLine);

                    stream.Write(response, 0, response.Length);

                    //Generate and send user ID
                    Byte[] q = Encoding.UTF8.GetBytes(ID);
                    //Byte[] resp = Helpers.Connections.encode(q);
                    Byte[] resp = Helpers.Connections.encode(q);
                    stream.Write(resp, 0, resp.Length);

                    //Start the timer and send dictionary
                    i = Helpers.Connections.checkRead(stream, bytes);
                }
                else
                {
                    //decode input and put into dictionary if valid location data
                    Byte[] decoded = Helpers.Connections.decode(bytes);
                    //string s = System.Text.Encoding.UTF8.GetString(decoded, 0, decoded.Length);
                    //Console.WriteLine ("RECEIVED MESSAGE " + s);
                    String response = Helpers.Connections.parseAndPut(decoded);
                    //Console.WriteLine ("Received these coordinates" + response);
                    if (response == null)
                    {
                        Console.WriteLine("NULL STUFF RECEIVED");
                    }
                    else
                    {
                        still_alive = true;
                        roomGroup.OrderedSend(UPDATE, ID, response);
                    }
                    i = Helpers.Connections.checkRead(stream, bytes);
                    //Console.WriteLine ("Decoded: {0}", System.Text.Encoding.UTF8.GetString (decoded, 0, decoded.Length));
                }
            }

            Console.WriteLine("Reached end of input");
            Console.WriteLine("NEW");
            try {
                roomGroup.OrderedSend(LEAVE_ROOM, ID);
            }
            catch (Exception) {
                Console.WriteLine("WE HAVE AN ERROR BUT WE ARE IGNORING IT NOW");
            }
            send_timer.Stop();
            //is_alive_timer.Stop ();
            Console.WriteLine("ROOM GROUP LEAVE");
            //roomGroup.Leave();
            client.Close();
        }
コード例 #4
0
        public static void Main(string[] args)
        {
            //Set up vsync dictionary and handlers
            Dictionary <string, string> valueStore = new Dictionary <string, string> ();

            valueStore ["user1"] = "0,1,0,1,1,2";
            valueStore ["user2"] = "1,1,1,1,1,1";
            const int UPDATE  = 0;
            const int LOOKUP  = 1;
            const int REFRESH = 2;
            const int REMOVE  = 3;

            Console.WriteLine("Hello World!");
            VsyncSystem.Start();
            Console.WriteLine("VSYNC STARTED");

            Vsync.Group g = new Vsync.Group("dataHolder");
            g.ViewHandlers += (ViewHandler) delegate(View v) {
                VsyncSystem.WriteLine("New View: " + v);
                Console.Title = "View " + v.viewid + ", my rank=" + v.GetMyRank();
            };
            g.Handlers[UPDATE] += (Action <string, string>) delegate(string username, string val) {
                VsyncSystem.WriteLine("IN UPDATE");
                valueStore[username] = val;
            };
            g.Handlers[LOOKUP] += (Action <string>) delegate(string s) {
                VsyncSystem.WriteLine("IN LOOKUP");
                g.Reply(valueStore[s]);
            };
            g.Handlers [REFRESH] += (Action) delegate() {
                string reply = Extensions.FromDictionaryToJson(valueStore);
                g.Reply(reply);
            };
            g.Handlers [REMOVE] += (Action <string>) delegate(string s) {
                VsyncSystem.WriteLine("DELETING USER " + s);
                valueStore.Remove(s);
            };

            /*g.MakeChkpt += (Vsync.ChkptMaker)delegate(View nv) {
             *      g.SendChkpt(valueStore);
             *      g.EndOfChkpt();
             * };
             * g.LoadChkpt += (loadVSchkpt)delegate(Dictionary<string, position> vs) {
             * valueStore = vs;
             * }; */
            g.Join();

            //Quick visual check to make sure initialization goes smoothely
            //UNNECESSARY -> TAKE OUT LATER
            List <string> valuesDic = new List <string> ();

            g.Query(1, REFRESH, new EOLMarker(), valuesDic);
            Console.WriteLine(valuesDic [0]);

            //Set up TCP Listener
            TcpListener server = new TcpListener(7569);

            server.Start();
            Console.WriteLine("Server has started on 127.0.0.1:7569.{0}Waiting for a connection...", Environment.NewLine);
            //Listen for connections
            while (true)
            {
                TcpClient client = server.AcceptTcpClient();
                handler   h      = new handler(client, g);
                //Spin off new thread to handle clients as they arrive
                Thread handler = new Thread(new ThreadStart(h.handle));
                handler.Start();
                Console.WriteLine("A Client Connected!");
            }
        }
コード例 #5
0
        public static void Main(String[] Args)
        {
            Dictionary <string, List <int> > rooms = new Dictionary <string, List <int> > ();

            VsyncSystem.Start();
            Console.WriteLine("vsync started");
            Vsync.Group lGroup = new Vsync.Group("Load Balancers");
            lGroup.Handlers [UPDATE] += (Action <String, List <int> >) delegate(string id, List <int> r) {
                foreach (KeyValuePair <string, List <int> > entry in rooms)
                {
                    try
                    {
                        if (Int32.Parse(id) == Int32.Parse(entry.Key))
                        {
                            rooms[entry.Key] = r;
                            return;
                        }
                    }
                    catch (Exception e) {
                        //pass through
                    }
                }
                rooms[id] = r;
                Console.WriteLine("Adding {0} to dict", id);
            };
            lGroup.Handlers [LOOKUP] += (Action <String>) delegate(string id) {
                //Console.WriteLine("Looking in dict for {0}:end", id);
                //bool contains = false;
                foreach (KeyValuePair <string, List <int> > entry in rooms)
                {
                    //Console.WriteLine("s:{0}:f", entry.Key);
                    try
                    {
                        if (Int32.Parse(id) == Int32.Parse(entry.Key))
                        {
                            lGroup.Reply(entry.Value);
                            return;
                        }
                    }
                    catch (Exception e) {
                        //pass through
                    }
                }

                /*Console.WriteLine(rooms.ContainsKey(id));
                 * if (contains){
                 *      lGroup.Reply (rooms [id]);
                 *      Console.WriteLine("Found room in dictionary!");
                 * }
                 * else{ */
                lGroup.Reply(new List <int>());
                Console.WriteLine("Creating room in dictionary!");
            };
            lGroup.MakeChkpt += (Vsync.ChkptMaker) delegate(View nv){
                lGroup.SendChkpt(Extensions.FromDictionaryToJson(rooms));
                lGroup.EndOfChkpt();
            };
            lGroup.LoadChkpt += (loaddckpt) delegate(string rs) {
                rooms = Extensions.FromJsonToDictionary(rs);
            };

            //loadGroup.DHTEnable (1, 1, 1, 86400000);
            lGroup.Join();
            Console.WriteLine("Server Group Joined");
            int         port   = Int32.Parse(Args [0]);
            TcpListener server = new TcpListener(port);

            server.Start();
            Console.WriteLine("Server has started on 127.0.0.1:7000.{0}Waiting for a connection...", Environment.NewLine);
            int    counter = 7568;
            String room    = null;

            while (true)
            {
                TcpClient client = server.AcceptTcpClient();
                counter++;
                NetworkStream stream  = client.GetStream();
                bool          connect = true;
                //String room = null;
                while (connect)
                {
                    Byte[] bytes = new Byte[4096];
                    String data  = null;
                    int    i     = Helpers.Connections.checkRead(stream, bytes);
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                    //First request -> Respond with HTTP Change Protocol Handshake
                    if (new Regex("^GET").IsMatch(data))
                    {
                        Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
                                                                 + "Connection: Upgrade" + Environment.NewLine
                                                                 + "Upgrade: websocket" + Environment.NewLine
                                                                 + "Sec-WebSocket-Accept: " + Convert.ToBase64String(
                                                                     SHA1.Create().ComputeHash(
                                                                         Encoding.UTF8.GetBytes(
                                                                             new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups [1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
                                                                             )
                                                                         )
                                                                     ) + Environment.NewLine
                                                                 + Environment.NewLine);

                        stream.Write(response, 0, response.Length);
                    }
                    else
                    {
                        Byte[] response = Helpers.Connections.decode(bytes);
                        string r        = System.Text.Encoding.ASCII.GetString(response);
                        //r = r.Substring(0, 10);
                        room = r;
                        bool isValid = true;
                        //Console.WriteLine ("{0}", r);
                        //Console.WriteLine ("Length: {1}, Last Char: {0}!", room.Substring ((r.Length - 1)), room.Length);
                        if (room.Contains("j"))
                        {
                            Console.WriteLine("here");
                            try
                            {
                                List <List <int> > rez = new List <List <int> >();
                                room = room.Remove(room.IndexOf("j"), 1);
                                Console.WriteLine(room);
                                lGroup.OrderedQuery(1, LOOKUP, room, new Vsync.EOLMarker(), rez);
                                List <int> ports = rez[0];
                                if (ports.Count == 0)
                                {
                                    isValid = false;
                                    Console.WriteLine("BAD ID");
                                    byte[] f = Encoding.UTF8.GetBytes("BAD ID");
                                    f = Helpers.Connections.encode(f);
                                    stream.Write(f, 0, f.Length);
                                }
                                Console.WriteLine(room);
                                //r = room;
                            }
                            catch (Exception e) {
                                Console.WriteLine("Error: {0}", e);
                            }
                        }

                        if (isValid)
                        {
                            Console.WriteLine("The room name is " + room);
                            break;
                        }
                    }
                }


                List <List <int> > result = new List <List <int> > ();
                try
                {
                    lGroup.OrderedQuery(1, LOOKUP, room, new Vsync.EOLMarker(), result);
                    List <int> ports = result[0];
                    ports.Add(counter);
                    lGroup.OrderedSend(UPDATE, room, ports);
                }
                catch (Exception e) {
                    Console.WriteLine("DICTIONARY ADD Error: {0}", e);
                }



                /*Console.WriteLine ("good here...");
                 * List<int> portlst = loadGroup.DHTGet<String, List<int>>((string) room);
                 * Console.WriteLine ("good after this ish");
                 * if (portlst == null) {
                 *      portlst = new List<int> ();
                 * }
                 * portlst.Add (counter);
                 * Console.WriteLine ("putting");
                 * loadGroup.DHTPut (room, portlst);
                 * Console.WriteLine ("put"); */

                Byte[] q    = Encoding.UTF8.GetBytes(counter.ToString());
                Byte[] resp = Helpers.Connections.encode(q);
                Console.WriteLine("HEY " + "../launchServer.sh " + counter.ToString() + " " + room);
                Process proc = new Process {
                    StartInfo = new ProcessStartInfo {
                        FileName               = "/bin/bash",
                        Arguments              = "../launchServer.sh " + counter.ToString() + " " + room,
                        UseShellExecute        = true,
                        RedirectStandardOutput = false
                    }
                };

                proc.Start();
                Console.WriteLine("A Client Connected!Handler server started.");
                System.Threading.Thread.Sleep(1000);
                stream.Write(resp, 0, resp.Length);
                Console.WriteLine("Port Number Sent");
            }
        }