예제 #1
0
        public void ClientStateMachine()
        {
            string command = "";

            while (true)
            {
                switch (STATE_CLIENT)
                {
                case STATE_CLIENT_ROOT_DISCOVER:
                    if (SearchForRootServer() == true)
                    {
                        //new Thread(() => PingLoop()).Start(); SERA ***********************************
                        if (clientScript_path != null)
                        {
                            STATE_CLIENT = STATE_READ_CLIENT_SCRIPT;
                        }
                        else
                        {
                            STATE_CLIENT = STATE_CLIENT_COMMAND_INTERPRETATION;
                        }
                    }
                    break;

                case STATE_READ_CLIENT_SCRIPT:              //Está martelado, fica assim, caso tenhamos tempo otimizo depois
                    /*script_comands = ReadScriptFile(clientScript_path);
                     * foreach (string linha in script_comands)
                     * {
                     *  results = linha.Split(' ');
                     *  if (results[0].Equals("add") || results[0].Equals("read") || results[0].Equals("take"))
                     *  {
                     *      command = command.Replace(">", "");
                     *      command = command.Replace("<", "");
                     *
                     *      List<string> tupleArguments = FiltroInput(results[1]);
                     *
                     *      object[] tupleOBJ = new object[tupleArguments.Count];
                     *      for (int i = 0; i < tupleArguments.Count; ++i)
                     *      {
                     *          tupleOBJ[i] = GetObjectFromString(tupleArguments[i]);
                     *      }
                     *      tuple = new MyTuple(tupleOBJ);
                     *
                     *      switch (results[0])
                     *      {
                     *          case "add":
                     *              Execute("add", tuple);
                     *              if (START_CICLE == true)
                     *              {
                     *                  CommandsInCycle.Add(new Command("add", tuple, null));
                     *              }
                     *              break;
                     *          case "read":
                     *              Execute("read", tuple);
                     *              if (START_CICLE == true)
                     *              {
                     *                  CommandsInCycle.Add(new Command("read", tuple, null));
                     *              }
                     *              break;
                     *          case "take":
                     *              Execute("take", tuple);
                     *              if (START_CICLE == true)
                     *              {
                     *                  CommandsInCycle.Add(new Command("take", tuple, null));
                     *              }
                     *              break;
                     *          case "wait":
                     *              Thread.Sleep(Int32.Parse(results[1]));
                     *              if (START_CICLE == true)
                     *              {
                     *                  CommandsInCycle.Add(new Command("wait", results[1], null));
                     *              }
                     *              break;
                     *          case "begin-repeat":
                     *              START_CICLE = true;
                     *              NumberOfCycles = Int32.Parse(results[1]);
                     *              break;
                     *          case "end-repeat":
                     *              START_CICLE = false;
                     *              --NumberOfCycles;
                     *              STATE_CLIENT = STATE_CLIENT_COMMAND_CYCLE;
                     *              break;
                     *          default:
                     *              Console.WriteLine("Wrong type of command!");
                     *              break;
                     *      }
                     *  }
                     * }*/

                    STATE_CLIENT = STATE_CLIENT_COMMAND_INTERPRETATION;
                    break;

                case STATE_CLIENT_COMMAND_INTERPRETATION:
                    Console.Write("Command: ");
                    command = Console.ReadLine();
                    //string[] results;
                    //MyTuple tuple = null;
                    results = command.Split(' ');
                    if (results[0].Equals("add") || results[0].Equals("read") || results[0].Equals("take"))
                    {
                        command = command.Replace(">", "");
                        command = command.Replace("<", "");


                        List <string> tupleArguments = FiltroInput(results[1]);

                        object[] tupleOBJ = new object[tupleArguments.Count];
                        for (int i = 0; i < tupleArguments.Count; ++i)
                        {
                            tupleOBJ[i] = GetObjectFromString(tupleArguments[i]);
                        }
                        tuple = new MyTuple(tupleOBJ);
                    }
                    STATE_CLIENT = STATE_CLIENT_COMMAND_EXECUTION;
                    break;

                case STATE_CLIENT_COMMAND_EXECUTION:

                    switch (results[0])
                    {
                    case "add":
                        Execute("add", tuple);
                        if (START_CICLE == true)
                        {
                            CommandsInCycle.Add(new Command("add", tuple, null, -1));
                        }
                        STATE_CLIENT = STATE_CLIENT_COMMAND_INTERPRETATION;
                        break;

                    case "read":
                        Execute("read", tuple);
                        if (START_CICLE == true)
                        {
                            CommandsInCycle.Add(new Command("read", tuple, null, -1));
                        }
                        STATE_CLIENT = STATE_CLIENT_COMMAND_INTERPRETATION;
                        break;

                    case "take":
                        Execute("take", tuple);
                        if (START_CICLE == true)
                        {
                            CommandsInCycle.Add(new Command("take", tuple, null, -1));
                        }
                        STATE_CLIENT = STATE_CLIENT_COMMAND_INTERPRETATION;
                        break;

                    case "wait":
                        Thread.Sleep(Int32.Parse(results[1]));
                        if (START_CICLE == true)
                        {
                            CommandsInCycle.Add(new Command("wait", results[1], null, -1));
                        }
                        STATE_CLIENT = STATE_CLIENT_COMMAND_INTERPRETATION;
                        break;

                    case "begin-repeat":
                        START_CICLE    = true;
                        NumberOfCycles = Int32.Parse(results[1]);
                        STATE_CLIENT   = STATE_CLIENT_COMMAND_INTERPRETATION;
                        break;

                    case "end-repeat":
                        START_CICLE = false;
                        --NumberOfCycles;
                        STATE_CLIENT = STATE_CLIENT_COMMAND_CYCLE;
                        break;

                    default:
                        Console.WriteLine("Wrong type of command!");
                        STATE_CLIENT = STATE_CLIENT_COMMAND_INTERPRETATION;
                        break;
                    }
                    break;

                case STATE_CLIENT_COMMAND_CYCLE:
                    Console.WriteLine();
                    Console.WriteLine("Inicio da {0} iteração", NumberOfCycles);

                    if (NumberOfCycles-- == 0)
                    {
                        CommandsInCycle.Clear();
                        STATE_CLIENT = STATE_CLIENT_COMMAND_INTERPRETATION;
                    }
                    else
                    {
                        for (int i = 0; i < CommandsInCycle.Count; ++i)
                        {
                            switch (CommandsInCycle[i].GetCommand())
                            {
                            case "read":
                                Console.WriteLine("READ");

                                Execute("read", (MyTuple)CommandsInCycle[i].GetPayload());
                                break;

                            case "add":
                                Console.WriteLine("ADD");

                                Execute("add", (MyTuple)CommandsInCycle[i].GetPayload());
                                break;

                            case "take":
                                Console.WriteLine("TAKE");
                                Execute("take", (MyTuple)CommandsInCycle[i].GetPayload());
                                break;

                            case "wait":
                                Console.WriteLine("WAIT");

                                Thread.Sleep(Int32.Parse((string)CommandsInCycle[i].GetPayload()));
                                break;
                            }
                        }
                    }
                    break;
                }
            }
        }
예제 #2
0
        //==============================================================
        //==============================================================


        public static void CheckCommandsInQueue_thread()
        {
            while (true)
            {
                while (MustFreeze == true)
                {
                    ;                             //FREEZE ****************************
                }
                Thread.Sleep(50);                 //Min time to check commands
                if (commLayer.GetQueueSize() > 0) //if there is commands
                {
                    Command cmd     = commLayer.RemoveFromCommandQueue();
                    MyTuple payload = (MyTuple)cmd.GetPayload();
                    Object  tmp;

                    switch (cmd.GetCommand())
                    {
                    case "read":
                        Console.WriteLine("START ========= REGISTER");

                        tmp = ts.Read(payload);
                        MyTuple a = tmp as MyTuple;

                        if (CommandsAlreadyReceived.Contains(cmd) == false)     //Test If command is received by the first time
                        {
                            //First time received
                            for (int i = 0; i < CommandsAlreadyReceived.Count; ++i)
                            {
                                if (CommandsAlreadyReceived[i].GetUriFromSender().Equals(cmd.GetUriFromSender()) == true)     //Remove the last command sent by the client
                                {
                                    CommandsAlreadyReceived.RemoveAt(i);
                                    break;
                                }
                            }
                            CommandsAlreadyReceived.Add(cmd); //add

                            if (a == null)                    //object does not exist in the tuple space so we put in backlog
                            {
                                commLayer.InsertInBackLog(cmd);
                                Console.WriteLine("(ServerService) Comando no Backlog: " + cmd.GetCommand() + " " + cmd.GetPayload().ToString());
                            }
                            else
                            {
                                GiveBackResult(cmd.GetUriFromSender(), new Command("read", a, ServerProgram.GetMyAddress(), cmd.GetSequenceNumber()));
                            }
                        }
                        //Ignore command
                        break;

                    case "add":

                        Console.WriteLine("============ADD: " + cmd.GetUriFromSender());

                        ////
                        if (CommandsAlreadyReceived.Contains(cmd) == false)     //Test If command is received by the first time
                        {
                            //First time received
                            for (int i = 0; i < CommandsAlreadyReceived.Count; ++i)
                            {
                                if (CommandsAlreadyReceived[i].GetUriFromSender().Equals(cmd.GetUriFromSender()) == true)     //Remove the last command sent by the client
                                {
                                    CommandsAlreadyReceived.RemoveAt(i);
                                    break;
                                }
                            }
                            CommandsAlreadyReceived.Add(cmd); //add

                            ts.Add(payload);                  //Insert in the tuple space

                            Console.WriteLine("Imagem: ");
                            Console.WriteLine(ts.ToString());


                            GiveBackResult(cmd.GetUriFromSender(), new Command("add", null, ServerProgram.GetMyAddress(), cmd.GetSequenceNumber()));

                            MyTuple a1;
                            //serach in the backlog
                            for (int i = 0; i < commLayer.GetBackLogSize(); ++i)
                            {
                                Command Command_tmp = commLayer.GetBackLogCommand(i);
                                if (Command_tmp.GetCommand().Equals("read"))
                                {
                                    tmp = ts.Read((MyTuple)Command_tmp.GetPayload());
                                    a1  = tmp as MyTuple;
                                    if (a1 != null)
                                    {
                                        commLayer.RemoveFromBackLog(i);
                                        i = -1;
                                        Console.WriteLine("(ServerService) Comando Atendido e Removido do Backlog: " + cmd.GetCommand() + " " + cmd.GetPayload().ToString());
                                        //GiveBackResult(Command_tmp.GetUriFromSender(), a1);
                                        GiveBackResult(cmd.GetUriFromSender(), new Command("read", null, ServerProgram.GetMyAddress(), cmd.GetSequenceNumber()));
                                    }
                                }
                            }
                        }
                        ///
                        break;

                    case "take":
                        if (CommandsAlreadyReceived.Contains(cmd) == false)     //Test If command is received by the first time
                        {
                            //First time received
                            for (int i = 0; i < CommandsAlreadyReceived.Count; ++i)
                            {
                                if (CommandsAlreadyReceived[i].GetUriFromSender().Equals(cmd.GetUriFromSender()) == true)     //Remove the last command sent by the client
                                {
                                    CommandsAlreadyReceived.RemoveAt(i);
                                    break;
                                }
                            }
                            CommandsAlreadyReceived.Add(cmd);     //add


                            //========================================================
                            //============================= PHASE 1
                            //========================================================
                            bool res = ts.IsTupleIn(payload);

                            if (res == false)     //object does not exist in the tuple space so we must Send REFUSE
                            {
                                GiveBackResult(cmd.GetUriFromSender(), new Command("refuse", null, ServerProgram.GetMyAddress(), cmd.GetSequenceNumber()));
                                //Console.WriteLine("(ServerService) Comando no Backlog: " + cmd.GetCommand() + " " + cmd.GetPayload().ToString());
                            }
                            else
                            {
                                //Check if is in lock
                                if (LockedTuples.Count == 0)
                                {
                                    //I will acquire the lock for sure
                                    //Acquire Lock
                                    Lock LockTmp = new Lock(cmd.GetUriFromSender());

                                    MyTuple RoverTmp;
                                    int     Rover = 0;
                                    while (true)     //Check all that match
                                    {
                                        RoverTmp = ts.RoverOneByOne(Rover);
                                        if (RoverTmp == null)
                                        {
                                            break;
                                        }
                                        else
                                        {
                                            if (RoverTmp.Equals(payload) == true)
                                            {
                                                LockTmp.Insert(RoverTmp);
                                            }
                                        }
                                        ++Rover;
                                    }
                                    LockedTuples.Add(LockTmp);
                                    //Return to the caller the set of all tuples that match
                                    GiveBackResult(cmd.GetUriFromSender(), new Command("accept", LockTmp.GetSet(), ServerProgram.GetMyAddress(), cmd.GetSequenceNumber()));
                                }
                                else
                                {
                                    for (int i = 0; i < LockedTuples.Count; ++i)
                                    {
                                        if (LockedTuples[i].IsIn(payload) == true)
                                        {
                                            //Object already has lock. So I must send Refuse
                                            GiveBackResult(cmd.GetUriFromSender(), new Command("refuse", null, ServerProgram.GetMyAddress(), cmd.GetSequenceNumber()));
                                            break;
                                        }
                                        else
                                        {
                                            //Acquire Lock
                                            Lock LockTmp = new Lock(cmd.GetUriFromSender());

                                            MyTuple RoverTmp;
                                            int     Rover = 0;
                                            while (true)     //Check all that match
                                            {
                                                RoverTmp = ts.RoverOneByOne(Rover);
                                                if (RoverTmp == null)
                                                {
                                                    break;
                                                }
                                                else
                                                {
                                                    if (RoverTmp.Equals(payload) == true)
                                                    {
                                                        LockTmp.Insert(RoverTmp);
                                                    }
                                                }
                                                ++Rover;
                                            }
                                            LockedTuples.Add(LockTmp);
                                            //Return to the caller the set of all tuples that match
                                            GiveBackResult(cmd.GetUriFromSender(), new Command("accept", LockTmp.GetSet(), ServerProgram.GetMyAddress(), cmd.GetSequenceNumber()));
                                        }
                                    }
                                }
                            }



                            //Console.WriteLine("Imagem: ");
                            //Console.WriteLine(ts.ToString());
                        }
                        break;

                    case "remove":
                        //========================================================
                        //============================= PHASE 2
                        //========================================================
                        if (CommandsAlreadyReceived.Contains(cmd) == false)     //Test If command is received by the first time
                        {
                            //First time received
                            for (int i = 0; i < CommandsAlreadyReceived.Count; ++i)
                            {
                                if (CommandsAlreadyReceived[i].GetUriFromSender().Equals(cmd.GetUriFromSender()) == true)     //Remove the last command sent by the client
                                {
                                    CommandsAlreadyReceived.RemoveAt(i);
                                    break;
                                }
                            }
                            CommandsAlreadyReceived.Add(cmd);     //add
                            ts.Take((MyTuple)cmd.GetPayload());
                            //release do lock
                            Console.WriteLine("Imagem: ");
                            Console.WriteLine(ts.ToString());

                            LockedTuples.Remove(new Lock(cmd.GetUriFromSender()));
                            GiveBackResult(cmd.GetUriFromSender(), new Command("ack", cmd.GetPayload(), ServerProgram.GetMyAddress(), cmd.GetSequenceNumber()));
                        }
                        break;

                    case "free_lock":
                        if (CommandsAlreadyReceived.Contains(cmd) == false)     //Test If command is received by the first time
                        {
                            //First time received
                            for (int i = 0; i < CommandsAlreadyReceived.Count; ++i)
                            {
                                if (CommandsAlreadyReceived[i].GetUriFromSender().Equals(cmd.GetUriFromSender()) == true)     //Remove the last command sent by the client
                                {
                                    CommandsAlreadyReceived.RemoveAt(i);
                                    break;
                                }
                            }
                            CommandsAlreadyReceived.Add(cmd);     //add

                            //release do lock
                            LockedTuples.Remove(new Lock(cmd.GetUriFromSender()));
                            //GiveBackResult(cmd.GetUriFromSender(), new Command("ack", null, ServerProgram.GetMyAddress(), cmd.GetSequenceNumber()));
                        }
                        break;
                    }
                }
            }
        }
예제 #3
0
        /// <summary>
        /// Execute the command. Sends to Server
        /// </summary>
        /// <param name="command"></param>
        /// <param name="t"></param>
        public static void Execute(string command, MyTuple t)
        {
            Console.WriteLine("EXECUTAR");
            Command   c  = new Command(command, t, MyAddress, ++SequenceNumber);
            Stopwatch sw = new Stopwatch();

            while (true)
            {
                switch (STATE_EXECUTE)
                {
                case STATE_COMMAND:
                    switch (command)
                    {
                    case "read":
                        //Console.WriteLine("========================================");
                        for (int i = 0; i < AllServers.Count; i++)
                        {
                            ThreadWithState tws = new ThreadWithState(c, i);
                            Thread          td  = new Thread(new ThreadStart(tws.TX_Command_thread));

                            ThreadsInAction.Add(new SenderPool(tws, td, new Uri(AllServers[i]), c));
                            td.Start();
                        }
                        STATE_EXECUTE = STATE_WAIT_FOR_REPLY_READ;
                        break;

                    case "add":
                        Console.WriteLine("========================================");
                        for (int i = 0; i < AllServers.Count; i++)
                        {
                            ThreadWithState tws = new ThreadWithState(c, i);
                            Thread          td  = new Thread(new ThreadStart(tws.TX_Command_thread));

                            ThreadsInAction.Add(new SenderPool(tws, td, new Uri(AllServers[i]), c));
                            td.Start();
                        }
                        STATE_EXECUTE = STATE_WAIT_FOR_REPLY_ADD;
                        break;

                    case "take":          //FASE 1
                        Console.WriteLine("========================================");
                        for (int i = 0; i < AllServers.Count; i++)
                        {
                            ThreadWithState tws = new ThreadWithState(c, i);
                            Thread          td  = new Thread(new ThreadStart(tws.TX_Command_thread));

                            ThreadsInAction.Add(new SenderPool(tws, td, new Uri(AllServers[i]), c));
                            td.Start();
                        }
                        STATE_EXECUTE = STATE_WAIT_FOR_REPLY_TAKE;
                        break;

                    case "remove":          //FASE 2
                        Console.WriteLine("========================================");
                        for (int i = 0; i < AllServers.Count; i++)
                        {
                            ThreadWithState tws = new ThreadWithState(c, i);
                            Thread          td  = new Thread(new ThreadStart(tws.TX_Command_thread));

                            ThreadsInAction.Add(new SenderPool(tws, td, new Uri(AllServers[i]), c));
                            td.Start();
                        }
                        STATE_EXECUTE = STATE_WAIT_FOR_REPLY_TAKE;
                        break;
                    }
                    break;

                case STATE_WAIT_FOR_REPLY_READ:
                    Pending_SignalEvent.WaitOne();
                    Pending_SignalEvent.Reset();
                    STATE_EXECUTE = STATE_COMMAND;
                    return;

                case STATE_WAIT_FOR_REPLY_ADD:
                    Pending_SignalEvent.WaitOne();
                    Pending_SignalEvent.Reset();
                    STATE_EXECUTE = STATE_COMMAND;
                    return;

                case STATE_WAIT_FOR_REPLY_TAKE:
                    Console.WriteLine("============INICIO======================STATE_WAIT_FOR_REPLY_TAKE");

                    Pending_SignalEvent.WaitOne();
                    Pending_SignalEvent.Reset();

                    Console.WriteLine("============ENTREI======================STATE_WAIT_FOR_REPLY_TAKE: " + TerminateTakenActivity.ToString());
                    STATE_EXECUTE = STATE_COMMAND;
                    if (TerminateTakenActivity == true && command == "take")
                    {
                        //Console.WriteLine("============ACABEI======================STATE_WAIT_FOR_REPLY_TAKE");
                        TerminateTakenActivity = false;
                        command = "remove";
                        c       = new Command(command, t, MyAddress, ++SequenceNumber);
                        //Take_SignalEvent.Set();
                        //return;
                    }
                    else
                    {
                        if (TerminateTakenActivity == true && command == "remove")
                        {
                            TerminateTakenActivity = false;
                            return;
                        }
                    }
                    break;
                }



                /*try
                 * {
                 *  Command c = new Command(command, t, MyAddress);
                 *  ss.RX_Command(c);
                 *  while (BlockUntilAnswer == false) ;
                 *  BlockUntilAnswer = false;
                 *  break;
                 * }
                 * catch (System.Net.Sockets.SocketException e)
                 * {
                 *  Console.WriteLine("AQUI");
                 *  Stopwatch sw = new Stopwatch();
                 *  sw.Start();
                 *  while (SearchForRootServer() == false) //Search for ROOT
                 *  {
                 *      if (sw.ElapsedMilliseconds > Timeout)
                 *      {
                 *          Console.WriteLine("No Server available.");
                 *          Console.WriteLine("Retrying in {0} [s]", Timeout);
                 *          Thread.Sleep(Timeout);
                 *          //break;
                 *      }
                 *  }
                 * }*/
            }
        }
예제 #4
0
        public static void CheckCommandsInQueue_thread()
        {
            while (true)
            {
                while (MustFreeze == true)
                {
                    ;                             //FREEZE ****************************
                }
                Thread.Sleep(50);                 //Min time to check commands

                if (commLayer.GetQueueSize() > 0) //if there is commands
                {
                    Command cmd     = commLayer.RemoveFromCommandQueue();
                    MyTuple payload = (MyTuple)cmd.GetPayload();
                    Object  tmp;



                    switch (cmd.GetCommand())
                    {
                    case "read":
                        tmp = ts.Read(payload);
                        MyTuple a = tmp as MyTuple;

                        Console.WriteLine("Imagem: ");
                        Console.WriteLine(ServerService.GetTupleSpaceRepresentation());

                        if (a == null)     //object does not exist in the tuple space so we put in backlog
                        {
                            commLayer.InsertInBackLog(cmd);
                            Console.WriteLine("(ServerService) Comando no Backlog: " + cmd.GetCommand() + " " + cmd.GetPayload().ToString());
                        }
                        else
                        {
                            GiveBackResult(cmd.GetUriFromSender(), a);
                        }
                        break;

                    case "add":
                        ts.Add(payload);
                        //Console.WriteLine(" ================= UMA VEZ ================ ");

                        Console.WriteLine("Imagem: ");
                        Console.WriteLine(ServerService.GetTupleSpaceRepresentation());

                        GiveBackResult(cmd.GetUriFromSender(), null);
                        MyTuple a1;
                        //serach in the backlog
                        for (int i = 0; i < commLayer.GetBackLogSize(); ++i)
                        {
                            Command Command_tmp = commLayer.GetBackLogCommand(i);
                            if (Command_tmp.GetCommand().Equals("read"))
                            {
                                tmp = ts.Read((MyTuple)Command_tmp.GetPayload());
                                a1  = tmp as MyTuple;
                                if (a1 != null)
                                {
                                    commLayer.RemoveFromBackLog(i);
                                    i = -1;
                                    Console.WriteLine("(ServerService) Comando Atendido e Removido do Backlog: " + cmd.GetCommand() + " " + cmd.GetPayload().ToString());
                                    GiveBackResult(Command_tmp.GetUriFromSender(), a1);
                                }
                            }
                            else
                            {
                                if (Command_tmp.GetCommand().Equals("take"))
                                {
                                    tmp = ts.Take((MyTuple)Command_tmp.GetPayload());
                                    a1  = tmp as MyTuple;
                                    if (a1 != null)     //test if is a MyTuple
                                    {
                                        commLayer.RemoveFromBackLog(i);
                                        i = -1;
                                        GiveBackResult(Command_tmp.GetUriFromSender(), a1);
                                    }
                                }
                            }
                        }
                        break;

                    case "take":
                        tmp = ts.Take(payload);
                        MyTuple a2 = tmp as MyTuple;
                        if (a2 == null)     //object does not exist in the tuple space so we put in backlog
                        {
                            commLayer.InsertInBackLog(cmd);
                            Console.WriteLine("(ServerService) Comando no Backlog: " + cmd.GetCommand() + " " + cmd.GetPayload().ToString());
                        }
                        else
                        {
                            Console.WriteLine("Imagem: ");
                            Console.WriteLine(ServerService.GetTupleSpaceRepresentation());

                            GiveBackResult(cmd.GetUriFromSender(), a2);
                        }
                        break;
                    }
                }
            }
        }