示例#1
0
        public void SerializeSolveRequest()
        {
            SolveRequest d   = new SolveRequest();
            string       xml = d.SerializeToXML();

            Assert.IsNotNull(xml);
        }
        public void SendProblemGetResponseTest()
        {
            var mockcore     = new Mock <ClientNodeProcessingModule>();
            var mockcreator  = new Mock <IMessageArrayCreator>();
            var solveRequest = new SolveRequest()
            {
                ProblemType = "abc"
            };

            Message[] request = new[] { solveRequest };
            mockcreator.Setup(u => u.Create(solveRequest)).Returns(request);
            mockcore.Setup(u => u.GetRequest()).Returns(solveRequest);

            var mockclient   = new Mock <IClusterClient>();
            var shouldReturn = new SolveRequestResponse {
                Id = 222
            };
            var responses = new Message[] { new NoOperation(),
                                            shouldReturn };

            mockclient.Setup(u => u.SendRequests(request)).Returns(responses);

            var clientNode = new ClientNode(mockclient.Object, mockcore.Object, mockcreator.Object);

            var ret = clientNode.SendProblem();

            Assert.AreEqual(ret, shouldReturn);
        }
示例#3
0
        private void SendSolveRequest(SolveRequest solveRequest)
        {
            String message = solveRequest.SerializeToXML();

            CMSocket.Instance.SendMessage(this.Port, this.IP, message, this);

            //nowy comment
            //Object obj = response.DeserializeXML();
            //Debug.Assert(obj is SolveRequestResponse, "Wrong response object");
            //SolveRequestResponse requestResopnse = (SolveRequestResponse)obj;
            //Debug.Assert(requestResopnse.IdSpecified, "No ID in solve request response");
            //if (!requestResopnse.IdSpecified)
            //    return;
            //Console.WriteLine("ID of the problem" + requestResopnse.Id);


            //stary comment
            //string message = solveRequest.SerializeToXML();
            //string res = CMSocket.Instance.SendMessage(this.Port, this.IP, message, this);
            //Object obj = res.DeserializeXML();
            //if (!(obj is SolveRequestResponse))
            //    throw new Exception("Wrong type");

            //SolveRequestResponse response = (SolveRequestResponse)obj;
            //if (response.IdSpecified) {
            //    ulong id = response.Id;
            //}
        }
示例#4
0
        /// <summary>
        /// Executes the command.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The arguments.</param>
        /// <returns></returns>
        public override CommandResult Execute(IClient sender, string[] args)
        {
            if (args.Length != 2)
            {
                return(new CommandResult(false, Command.Solve, "Usage: solve <name> <algorithm>", true));
            }

            string name = args[0];
            byte   algorithm;

            if (!byte.TryParse(args[1], out algorithm))
            {
                return(new CommandResult(false, Command.Solve, "Bad <algorithm> field. Expected: 0 - for bfs, 1 - for dfs", true));
            }

            SolveRequest request = new SolveRequest(name, algorithm);

            try
            {
                MazeSolution sol = _model.SolveMaze(request);
                //serialize and send the object
                bool keepCom = _model.IsInGame(sender);
                return(new CommandResult(true, Command.Solve, sol.ToJSON(), keepCom));
            }
            catch (Exception e)
            {
                return(new CommandResult(false, Command.Solve, e.Message, true));
            }
        }
示例#5
0
        protected override string ReceivedSolvePartialProblems(SolvePartialProblems solvePartialProblems)
        {
            /* Partial problems message is sent by the TM after dividing the problem into smaller partial problems.
             * The data in it consists of two parts – common for all partial problems and specific for the given task.
             * The same Partial Problems schema is used for the messages sent to be computed by the CN and to relay
             * information for synchronizing info with Backup CS.
             */

            this.serverQueues.ProblemsToSolve.Enqueue(solvePartialProblems);
            //if (this.BackupMode == true)
            //    return null;

            if (this.serverQueues.SolveRequests.Count > 0)
            {
                SolveRequest  solveRequest  = this.serverQueues.SolveRequests.Dequeue();
                DivideProblem divideProblem = new DivideProblem();
                divideProblem.Data = solveRequest.Data;
                divideProblem.Id   = solveRequest.Id;
                Console.WriteLine("Sending DivideProblem as an ans to SolvePartiaProblems");
                return(divideProblem.SerializeToXML());
            }

            //TM is not going to join the solutions
            //if (this.serverQueues.Solutions.Count > 0) {
            //    Solutions solutions = this.serverQueues.Solutions.Dequeue();
            //    return solutions.SerializeToXML();
            //}

            Console.WriteLine("Sending NoOp as an ans to SolvePartialProblems");
            return(this.GenerateNoOperation().SerializeToXML());
        }
示例#6
0
        /// <summary>
        /// Method used to send request to solve a problem with data
        /// </summary>
        /// <returns>Method returns true, when Client succesfully send SolveRequest; Method return flase when send was failed</returns>
        public bool SolveRequest()
        {
            //GenerateData();
            byte[] bytesToSend;
            if (problemData == null)
            {
                bytesToSend = null;
            }
            bytesToSend = SerializeFromClass(problemData);

            SolveRequest solveRequest = new SolveRequest()
            {
                Data        = bytesToSend,
                ProblemType = "DVRP-02",

                SolvingTimeoutSpecified = cf.timeoutSpecified
            };

            if (cf.timeoutSpecified)
            {
                solveRequest.SolvingTimeout = (ulong)cf.timeout;
            }

            // bool result =
            Send(SerializeMessage <SolveRequest>(solveRequest));
            //if (result)
            ReceiveSolveRequest();
            //return result;
            return(true);
        }
示例#7
0
        /// <summary>
        /// Solves the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public MazeSolution SolveMaze(SolveRequest request)
        {
            // if there is a maze with this name
            if (!mazes.ContainsKey(request.MazeName))
            {
                throw new InvalidOperationException(string.Format("There is no maze with the name \"{0}\"", request.MazeName));
            }

            // if solution exists in the cache
            if (solutionCache.ContainsKey(request.MazeName))
            {
                return(solutionCache[request.MazeName]);
            }
            // initialize the search components
            MazeAdapter          adapter   = new MazeAdapter(mazes[request.MazeName]);
            ISearcher <Position> algorithm = GetAlgorithm(request.Algorithm);
            // search for the solution
            Solution <Position> sol = algorithm.Search(adapter);
            // create the mazeSolution object.
            MazeSolution path = new MazeSolution(algorithm.GetNumberOfNodesEvaluated(), request.MazeName, sol);

            // save the solution in the cache
            solutionCache[request.MazeName] = path;
            //return the solution
            return(path);
        }
        public void SendProblemMultipleResponsesExceptionTest()
        {
            var mockcore     = new Mock <ClientNodeProcessingModule>();
            var mockcreator  = new Mock <IMessageArrayCreator>();
            var solveRequest = new SolveRequest()
            {
                ProblemType = "abc"
            };

            Message[] request = new[] { solveRequest };
            mockcreator.Setup(u => u.Create(solveRequest)).Returns(request);
            mockcore.Setup(u => u.GetRequest()).Returns(solveRequest);

            var mockclient   = new Mock <IClusterClient>();
            var shouldReturn = new SolveRequestResponse {
                Id = 222
            };
            var duplicated = new SolveRequestResponse {
                Id = 222
            };
            var responses = new Message[] { shouldReturn, duplicated };

            mockclient.Setup(u => u.SendRequests(request)).Returns(responses);

            var clientNode = new ClientNode(mockclient.Object, mockcore.Object, mockcreator.Object);

            var ret = clientNode.SendProblem();
        }
示例#9
0
        public void DeserializeSolveRequest()
        {
            SolveRequest d   = new SolveRequest();
            string       xml = d.SerializeToXML();

            d = (SolveRequest)xml.DeserializeXML();
            Assert.IsNotNull(d);
        }
示例#10
0
 protected override void ProcessSolveRequestMessage(SolveRequest message,
                                                    IDictionary <int, ProblemDataSet> dataSets,
                                                    IDictionary <int, ActiveComponent> activeComponents)
 {
     WriteControlInformation(message);
     dataSets.Add((int)message.Id, new ProblemDataSet()
     {
         CommonData    = message.Data,
         PartialSets   = null,
         ProblemType   = message.ProblemType,
         TaskManagerId = 0
     });
 }
示例#11
0
        public void SolveRequestMessageSerializationTest()
        {
            SolveRequest request =
                MessagesFactory.CreateEmptyMessage(MessageType.SolveRequestMessage).Cast <SolveRequest>();

            request.Data                    = new byte[100];
            request.ProblemType             = "DVRP";
            request.SolvingTimeout          = 1500;
            request.SolvingTimeoutSpecified = true; //dziwne, że to trzeba podawać
            string       xml = _serializer.ToXmlString(request);
            SolveRequest requestDeserialized = _serializer.FromXmlString(xml).Cast <SolveRequest>();

            Assert.AreEqual(request.Data.Length, requestDeserialized.Data.Length);
            Assert.AreEqual(request.ProblemType, requestDeserialized.ProblemType);
            Assert.AreEqual(request.SolvingTimeout, requestDeserialized.SolvingTimeout);
        }
示例#12
0
        void ProblemsTimerCallback(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (this.problems.Count <= 0)
            {
                return;
            }
            String singleProblem = this.problems.Dequeue();

            if (singleProblem == null)
            {
                return;
            }
            var          base64       = singleProblem.Base64Encode();
            SolveRequest solveRequest = new SolveRequest();

            solveRequest.Data        = base64;
            solveRequest.ProblemType = Utilities.ProblemNameForType(ProblemType.DVRP);
            this.SendSolveRequest(solveRequest);
        }
示例#13
0
        public IHttpActionResult SolveMaze(SolveRequest solveRequest)
        {
            string searchAlgo = "1";

            if (solveRequest.SearchAlgo == "BFS")
            {
                searchAlgo = "0";
            }
            SolveInfo       solveInfo       = Model.SolveMaze(solveRequest.Name, searchAlgo);
            SolutionAdapter solutionAdapter = new SolutionAdapter(solveInfo.Solution);
            string          strSolution     = solutionAdapter.CreateString();

            JObject solutionObj = new JObject();

            solutionObj["Name"]     = solveRequest.Name;
            solutionObj["Solution"] = strSolution;

            return(Ok(solutionObj));
        }
        private ulong AddProblem(SolveRequest _solveRequestMessage)
        {
            Problem problem = new Problem()
            {
                Data             = _solveRequestMessage.Data,
                ProblemType      = _solveRequestMessage.ProblemType,
                manager          = null,
                timeoutOccured   = false,
                timeoutSpecified = _solveRequestMessage.SolvingTimeoutSpecified
            };

            if (_solveRequestMessage.SolvingTimeoutSpecified)
            {
                problem.solvingTimeout = _solveRequestMessage.SolvingTimeout;
            }
            m_memoryLock.WaitOne();
            problem.Id = m_problemId++;
            m_problems.Add(problem);
            m_memoryLock.Release();
            return(problem.Id);
        }
示例#15
0
        protected override string ReceivedSolveRequest(SolveRequest solveRequest)
        {
            this.serverQueues.SolveRequests.Enqueue(solveRequest);
            SolveRequestResponse response = new SolveRequestResponse();

            if (solveRequest.IdSpecified)
            {
                response.Id = solveRequest.Id; //TaskIDCounter++;
            }
            else
            {
                response.Id = TaskIDCounter++;
            }
            response.IdSpecified = true;

            if (!this.BackupMode)
            {
                Console.WriteLine("Sending SolveRequestResponse");
            }
            return(response.SerializeToXML());
        }
        public void ResponseIfProblemIsSolved()
        {
            DvrpProblem.Problems.Clear();
            DvrpProblem.ProblemSolutions.Clear();
            SolveRequest solveRequest = new SolveRequest() {Data = new byte[1]};
            DvrpProblem.Problems.Add(1, solveRequest);
            Solutions solution = new Solutions()
            {
                CommonData = new byte[1],
                Solutions1 = new SolutionsSolution[] {new SolutionsSolution() {Data = new byte[1]}}
            };
            SolutionRequest request = new SolutionRequest() {Id = 1};
            DvrpProblem.ProblemSolutions.Add(request.Id, solution);
            string msg = MessageSerialization.Serialize(request);
            SolutionRequestStrategy solutionRequestStrategy = new SolutionRequestStrategy();

            solutionRequestStrategy.HandleMessage(networkAdapterMock.Object, msg, MessageType.SolutionRequestMessage, new TimeSpan(0,1,0));

            networkAdapterMock.Verify(p => p.Send(It.IsAny<Solutions>()), Times.Once);
            //Assert.AreEqual(DvrpProblem.ProblemSolutions.Count, 0);
        }
示例#17
0
        /// <summary>
        /// sends problem to cluster, returns unique problem id
        /// </summary>
        /// <returns></returns>
        public virtual SolveRequestResponse SendProblem()
        {
            SolveRequest problemRequest = core.GetRequest();

            problemRequest.IdSpecified = false;

            Message[]            requests      = creator.Create(problemRequest);
            Message[]            responses     = this.SendMessages(clusterClient, requests);
            SolveRequestResponse solveResponse = null;

            foreach (var response in responses)
            {
                switch (response.MessageType)
                {
                case MessageType.SolveRequestResponseMessage:
                    log.Debug("SolveRequestResponse acquired: handling");
                    if (solveResponse != null)
                    {
                        throw new Exception("Multiple SolveRequestResponse messages in CC");
                    }
                    solveResponse = response.Cast <SolveRequestResponse>();
                    break;

                case MessageType.NoOperationMessage:
                    log.Debug("NoOperation acquired: updating backups");
                    UpdateBackups(response.Cast <NoOperation>());
                    break;

                default:
                    throw new Exception("Invalid message delivered in CC's sendProblem procedure "
                                        + response.ToString());
                }
            }
            if (solveResponse == null)
            {
                throw new Exception("No solveRequestResponse in CC");
            }

            return(solveResponse);
        }
        public void SendProblemNoResponseExceptionTest()
        {
            var mockcore     = new Mock <ClientNodeProcessingModule>();
            var mockcreator  = new Mock <IMessageArrayCreator>();
            var solveRequest = new SolveRequest()
            {
                ProblemType = "abc"
            };

            Message[] request = new[] { solveRequest };
            mockcreator.Setup(u => u.Create(solveRequest)).Returns(request);
            mockcore.Setup(u => u.GetRequest()).Returns(solveRequest);

            var mockclient = new Mock <IClusterClient>();
            var response   = new NoOperation();
            var responses  = new Message[] { response };

            mockclient.Setup(u => u.SendRequests(request)).Returns(responses);

            var clientNode = new ClientNode(mockclient.Object, mockcore.Object, mockcreator.Object);

            var ret = clientNode.SendProblem();
        }
        protected virtual Message[] RespondSolveRequestMessage(SolveRequest message,
                                                               IDictionary <int, ProblemDataSet> dataSets,
                                                               IDictionary <int, ActiveComponent> activeComponents, List <BackupServerInfo> backups)
        {
            //sent by client node. create new issue in dataset with unique problemId,
            //send back NoOp + SolveRequestResponse with proper problemId
            var maxProblemId = dataSets.Count == 0 ? 1 : dataSets.Keys.Max() + 1;
            var newSet       = new ProblemDataSet()
            {
                CommonData    = message.Data,
                PartialSets   = null,
                ProblemType   = message.ProblemType,
                TaskManagerId = 0
            };

            dataSets.Add(maxProblemId, newSet);
            Log.DebugFormat("New problem, ProblemType={0}. Assigned id: {1}",
                            message.ProblemType, maxProblemId);
            Log.DebugFormat("New problem, ProblemType={0}. Assigned id: {1}",
                            message.ProblemType, maxProblemId);

            message.Id          = (ulong)maxProblemId;
            message.IdSpecified = true;
            SynchronizationQueue.Enqueue(message);

            return(new Message[]
            {
                new NoOperation()
                {
                    BackupServersInfo = backups.ToArray()
                },
                new SolveRequestResponse()
                {
                    Id = (ulong)maxProblemId
                }
            });
        }
示例#20
0
 /// <summary>
 /// Solves the requested maze.
 /// </summary>
 /// <param name="request">The request.</param>
 /// <returns></returns>
 public MazeSolution SolveMaze(SolveRequest request)
 {
     return(mazeManager.SolveMaze(request));
 }
示例#21
0
        protected override string ReceivedStatus(Status status)
        {
            Debug.Assert(this.serverQueues != null, "null server queue");
            Node node = this.RegisteredComponents.NodeWithID(status.Id);

            NoOperation noOperationResponse = this.GenerateNoOperation();

            if (!this.ensureNode(node))
            {
                return(noOperationResponse.SerializeToXML());
            }

            switch (node.NodeType)
            {
            case NodeType.TaskManager:
                if (this.serverQueues.SolveRequests.Count > 0)
                {
                    SolveRequest  solveRequest  = this.serverQueues.SolveRequests.Dequeue();
                    DivideProblem divideProblem = new DivideProblem();
                    divideProblem.Data = solveRequest.Data;
                    divideProblem.Id   = solveRequest.Id;
                    Console.WriteLine("Sending DivideProblem to TM");
                    return(divideProblem.SerializeToXML());
                }
                //TM is not going to join the solutions
                //if (this.serverQueues.Solutions.Count > 0) {
                //    Solutions solutions = this.serverQueues.Solutions.Dequeue();
                //    return solutions.SerializeToXML();
                //}
                break;

            case NodeType.ComputationalNode:     //TODO: check!!
                bool busy = false;
                if (status.Threads != null)
                {
                    Console.WriteLine("Threads field not null");
                    foreach (StatusThreadsThread stt in status.Threads)
                    {
                        if (stt.ProblemInstanceIdSpecified || stt.TaskIdSpecified)
                        {
                            busy = true;
                            Console.WriteLine("Busy = true");
                        }
                    }
                }
                if (this.serverQueues.ProblemsToSolve.Count > 0 && !busy)
                {
                    Console.WriteLine("Busy = true");
                    SolvePartialProblems partialProblems = this.serverQueues.ProblemsToSolve.Dequeue();
                    Console.WriteLine("Sending PartialProblems to CN");
                    return(partialProblems.SerializeToXML());
                }
                break;

            case NodeType.Server: {
                foreach (BackupServerQueue bsq in this.backupServerQueues)
                {
                    if (bsq.backupServerId == status.Id)
                    {
                        Console.WriteLine("Sending queued message to BackupCS");
                        if (bsq.messages.Count > 0)
                        {
                            return(bsq.messages.Dequeue());
                        }
                    }
                }
            }
            break;

            default:
                break;
            }

            Debug.Assert(node != null, "Received unregistered node status");
            if (node == null)
            {
                Console.WriteLine("Received unregistered node status");
                return(noOperationResponse.SerializeToXML());
            }

            if (!this.BackupMode)
            {
                Console.WriteLine("Sending NoOp");
            }
            return(noOperationResponse.SerializeToXML());
        }
 protected virtual void ProcessSolveRequestMessage(SolveRequest message,
                                                   IDictionary <int, ProblemDataSet> dataSets,
                                                   IDictionary <int, ActiveComponent> activeComponents)
 {
 }
示例#23
0
 protected abstract string ReceivedSolveRequest(SolveRequest solveRequest);
示例#24
0
        private ulong RequestForSolvingProblem(string type, byte[] data)
        {
            try
            {
                var request = new SolveRequest
                    {
                        ProblemType = type,
                        Data = data
                    };
                var response = SendMessageSingleResponse(request);

                switch (MessageTypeResolver.GetMessageType(response.XmlMessage))
                {
                    case MessageTypeResolver.MessageType.Error:
                        HandleErrorMessage(response);
                        throw new Exception("Solve request failed");
                    case MessageTypeResolver.MessageType.SolveRequestResponse:
                        var message = (SolveRequestResponse)response.ClusterMessage;
                        return message.Id;
                    default:
                        throw new Exception("Solve request failed.");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#25
0
 protected override string ReceivedSolveRequest(SolveRequest solveRequest)
 {
     Debug.Assert(false, "Should not be here");
     return(null);
 }
示例#26
0
        private void SendSolveRequest()
        {
            var sr = new SolveRequest
            {
                Data = _data,
                ProblemType = _problemType,
                SolvingTimeout = _solvingTimeout,
                SolvingTimeoutSpecified = true
            };

            _networkAdapter.Send(sr, false);
        }