public static SolveRequestMessage loadDataFromDisc(String filePath) { SolveRequestMessage solveRequestMessage; StreamReader streamReader = new StreamReader(filePath); string text = streamReader.ReadToEnd(); VRPParser benchmark = new VRPParser(text); string problemType = ""; byte[] data; streamReader.Close(); String extension = Path.GetExtension(filePath); if (extension == ".vrp") { problemType = "DVRP"; } else { Console.WriteLine(">> Unsupported problem type. Please load a problem with one of the following problem types: \n *DVRP"); return(null); } data = DataSerialization.ObjectToByteArray(benchmark); // data = GetBytes(filePath); solveRequestMessage = new SolveRequestMessage(problemType, data); Console.WriteLine(" >> Success"); return(solveRequestMessage); }
public string SendSolveRequest(SolveRequestMessage solveRequestMessage) { try { clientSocket = communicationModule.SetupClient(); communicationModule.Connect(clientSocket); var serializer = new ComputationSerializer <SolveRequestMessage>(); var message = serializer.Serialize(solveRequestMessage); communicationModule.SendData(message, clientSocket); var response = communicationModule.ReceiveData(clientSocket); communicationModule.CloseSocket(clientSocket); return(response); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); //TODO logowanie } return(String.Empty); }
public void SolveRequestMessageSerializationTest() { byte[] byteArray = Encoding.UTF8.GetBytes("Test Byte Array"); var solveRequestMessage = new SolveRequestMessage("Problem Type", 122L, byteArray); var result = solveRequestMessage.SerializeToXml(); Assert.IsNotNull(result); Assert.AreNotEqual(0, result.Length); var xmlValidator = new XmlValidator(); var xsdSchemaFile = "SolveRequestMessage.xsd"; var xsdSchemaPath = Path.Combine(_xsdSchemasPath, xsdSchemaFile); var validationResult = xmlValidator.Validate(result, xsdSchemaPath, true); var errorsCount = validationResult.Errors.Count + validationResult.Warnings.Count; Assert.AreEqual(0, errorsCount); #region ExampleResult //<?xml version="1.0" encoding="utf-16"?> //<SolveRequest xmlns="http://www.mini.pw.edu.pl/ucc/"> // <ProblemType>Problem Type</ProblemType> // <SolvingTimeout>122</SolvingTimeout> // <Data>VGVzdCBCeXRlIEFycmF5</Data> //</SolveRequest> #endregion }
/// <summary> /// SolveRequest is sent by Computational Client /// </summary> /// <param name="messagePackage"></param> private void handleSolveRequestMessage(MessagePackage messagePackage) { SolveRequestMessage message = (SolveRequestMessage)messagePackage.Message; InformBackup(message); // if the cluster can solve this problem if (clientTracker.CanSolveProblem(message.ProblemType)) { Task task = new Task((int)systemTracker.GetNextTaskID(), message.ProblemType, message.Data); taskTracker.AddTask(task); if (Server.primaryMode) { NoOperationMessage responseNoOp = new NoOperationMessage(clientTracker.BackupServers); SolveRequestResponseMessage response = new SolveRequestResponseMessage((ulong)task.ID); List <Message> messages = new List <Message>(); messages.Add(responseNoOp); messages.Add(response); server.Send(messagePackage.Socket, messages); SmartConsole.PrintLine("Sent a SolveRequestResponse Message", SmartConsole.DebugLevel.Basic); } } else { //TODO RESPONSE MESSAGE Console.Write(" >> TM ERROR\n"); } }
/// <summary> /// Sends request for solving the problem. /// </summary> /// <param name="problemType">The name of the type as given by TaskSolver.</param> /// <param name="data">The serialized problem data.</param> /// <param name="solvingTimeout">The optional time restriction for solving the problem (in ms).</param> /// <returns>The ID of the problem instance assigned by the server or null if server is not responding.</returns> public ulong?SendSolveRequest(string problemType, byte[] data, ulong?solvingTimeout) { var solveRequestMessage = new SolveRequestMessage { ProblemType = problemType, ProblemData = data, SolvingTimeout = solvingTimeout }; var receivedMessages = SendMessage(solveRequestMessage); if (receivedMessages == null) { return(null); } ulong?problemId = null; foreach (var receivedMessage in receivedMessages) { SolveRequestResponseMessage solveRequestResponseMessage; if ((solveRequestResponseMessage = receivedMessage as SolveRequestResponseMessage) != null) { problemId = solveRequestResponseMessage.AssignedId; } else { RaiseEvent(MessageHandlingException, receivedMessage, new InvalidOperationException("SolveRequestResponseMessage expected.")); } } return(problemId); }
public void Parse_XMLString_SolveRequestMessage() { /*********** Actual message ***********/ string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"xml_samples\SolveRequest.xml"); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(path); string xmlStr = xmlDoc.OuterXml; string name = Message.GetMessageName(xmlStr); SolveRequestMessage actualMessage = null; if (name == SolveRequestMessage.ELEMENT_NAME) { actualMessage = SolveRequestMessage.Construct(xmlStr); } /*********** Expected message ***********/ string problemType = "TSP"; ulong id = 12; byte[] data = { 1, 23, 25, 2, 5, 5, 5, 5, 2, 26, 87 }; ulong solvingTimeout = 1000; SolveRequestMessage expectedMessage = new SolveRequestMessage(problemType, data, solvingTimeout, id); Assert.AreEqual(expectedMessage, actualMessage); }
public void SolveRequestMessageIsAcceptedAndSolveRequestResponseMessageIsPassedBack() { var waitHandle = new AutoResetEvent(false); var msg = new SolveRequestMessage { ProblemData = new byte[0], ProblemType = "dvrp" }; var rawMsg = _marshaller.Marshall(new Message[] { msg }); Message outputMessage = null; ProcessedDataCallback c = response => { outputMessage = _marshaller.Unmarshall(response)[0]; waitHandle.Set(); }; _processor.StartProcessing(); _processor.EnqueueDataToProcess(rawMsg, null, c); waitHandle.WaitOne(5000); _processor.StopProcessing(); Assert.IsInstanceOfType(outputMessage, typeof(SolveRequestResponseMessage)); }
private void Browse_Click(object sender, RoutedEventArgs e) { // Create OpenFileDialog Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); // Display OpenFileDialog by calling ShowDialog method Nullable <bool> result = dlg.ShowDialog(); // Get the selected file name and display in a TextBox if (result == true) { // Open document string filename = dlg.FileName; string content = File.ReadAllText(filename); wiadomosc.Text = content; //CommunicationModule cm = new CommunicationModule("127.0.0.1", 5555, 5000); //var socket = cm.SetupClient(); //cm.Connect(socket); this.solveRequestMessage = new SolveRequestMessage() { Data = CommunicationModule.ConvertStringToData(content), ProblemType = "DVRP", SolvingTimeout = long.Parse(this.timeoutTextBox.Text) }; this.computationalClient = new ComputationClient("127.0.0.1", 5555, 2000); //BaseNode bn = new BaseNode(); //cm.SendData(bn.SerializeMessage(solveRequestMessage), socket); //cm.CloseSocket(socket); } }
/// <summary> /// Constructs message by given xml string /// </summary> /// <param name="xmlString"> /// xml in string /// </param> /// <returns> /// Message constructed by the xml /// </returns> public static Message Construct(string xmlString) { xmlString = concCompabilityIssuesStringWojtekIsGay(xmlString); if (GetMessageName(xmlString) == RegisterMessage.ELEMENT_NAME) { return(RegisterMessage.Construct(xmlString)); } if (GetMessageName(xmlString) == DivideProblemMessage.ELEMENT_NAME) { return(DivideProblemMessage.Construct(xmlString)); } if (GetMessageName(xmlString) == NoOperationMessage.ELEMENT_NAME) { return(NoOperationMessage.Construct(xmlString)); } if (GetMessageName(xmlString) == RegisterResponseMessage.ELEMENT_NAME) { return(RegisterResponseMessage.Construct(xmlString)); } if (GetMessageName(xmlString) == SolutionRequestMessage.ELEMENT_NAME) { return(SolutionRequestMessage.Construct(xmlString)); } if (GetMessageName(xmlString) == SolutionsMessage.ELEMENT_NAME) { return(SolutionsMessage.Construct(xmlString)); } if (GetMessageName(xmlString) == SolvePartialProblemsMessage.ELEMENT_NAME) { try { //return SolvePartialProblemsMessage.Construct(xmlString); } catch (InvalidOperationException e) { return(null); } Console.WriteLine("******** SOLVE PARTIAL PROBLEM MESSAGE **************"); return(SolvePartialProblemsMessage.Construct(xmlString)); } if (GetMessageName(xmlString) == SolveRequestMessage.ELEMENT_NAME) { return(SolveRequestMessage.Construct(xmlString)); } if (GetMessageName(xmlString) == SolveRequestResponseMessage.ELEMENT_NAME) { return(SolveRequestResponseMessage.Construct(xmlString)); } if (GetMessageName(xmlString) == StatusMessage.ELEMENT_NAME) { return(StatusMessage.Construct(xmlString)); } return(null); }
public static SolveRequestMessage CreateSolveRequestMessage() { string problemType = "TSP"; ulong id = 12; byte[] data = { 1, 23, 25, 2, 5, 5, 5, 5, 2, 26, 87 }; ulong solvingTimeout = 1000; SolveRequestMessage expectedMessage = new SolveRequestMessage(problemType, data, solvingTimeout, id); return(expectedMessage); }
/// <summary> /// Handle solve request message. /// </summary> /// <param name="msg">Solve request message.</param> /// <param name="metadata">Information about data and the TCP connection it came from.</param> /// <returns>List of response messages.</returns> private List <Message> HandleMessage(SolveRequestMessage msg, TcpDataProviderMetadata metadata) { var solvingTimeout = msg.SolvingTimeout ?? ulong.MaxValue; var id = _workManager.AddProblem(msg.ProblemType, msg.ProblemData, solvingTimeout); var response = new SolveRequestResponseMessage { AssignedId = id }; return(new List <Message> { response }); }
public void SolveRequestMessageSerialization() { string testData = System.IO.File.ReadAllText(@"XMLTestData\SolveRequestMessage.xml"); var serializer = new ComputationSerializer <SolveRequestMessage>(); var solveRequestMessage = new SolveRequestMessage() { Data = new byte[] { 0, 0, 25 }, ProblemType = "TSP", SolvingTimeout = 15 }; var result = serializer.Serialize(solveRequestMessage); Assert.AreEqual(result, testData); }
public void SolveRequestMessageXmlIsProperlySerializedAndDeserialized() { var message = new SolveRequestMessage { ProblemData = new byte[] { 1, 2, 3 }, ProblemInstanceId = 5, ProblemType = "Dvrp", SolvingTimeout = 50 }; var serializedMessage = _serializer.Serialize(message); var deserializedMessage = _serializer.Deserialize(serializedMessage); Assert.IsInstanceOfType(deserializedMessage, typeof(SolveRequestMessage)); }
/// <summary> /// Dequeues first solveReqest of given type and returns appropiate DivideProblemMessage for SolveRequest /// </summary> /// <param name="type"></param> /// <returns></returns> private DivideProblemMessage GetDivideProblemMessageForType(List <string> solvingTypes) { DivideProblemMessage divideProblemMessage = null; ulong solveRequestId = 0; SolveRequestMessage solveRequest = new SolveRequestMessage(); lock (solveRequests) { solveRequestId = solveRequests.FirstOrDefault(x => solvingTypes.Contains(x.Value.ProblemType)).Key; solveRequests.TryRemove(solveRequestId, out solveRequest); } if (solveRequest != null) { int activeNodeCount = 0; lock (activeNodes) { foreach (var activeNode in this.activeNodes) { if (activeNode.Value.Type == RegisterType.ComputationalNode) { activeNodeCount++; } } } divideProblemMessage = new DivideProblemMessage() { ComputationalNodes = (ulong)activeNodeCount, Data = solveRequest.Data, ProblemType = solveRequest.ProblemType, Id = solveRequestId }; } return(divideProblemMessage); }
private void ProcessSolveRequestMessage(SolveRequestMessage msg, TcpClient client) { var data = msg.Data; var problemType = msg.ProblemType; var timeout = msg.SolvingTimeout; var taskManagerInfo = GetTaskManagerByProblemType(problemType); if (taskManagerInfo == null) { EventLogger.GetLog().ErrorFormat("Brak task managera dla problemu {0}", msg.ProblemType); return; } var problemInstance = new ProblemInstanceInfo(++_maxProblemId, msg.ProblemType) { Data = data, TaskManager = taskManagerInfo, ComputationalClient = GetComponentsInfoByTcpClient(client), SolvingTimeout = timeout, ProblemType = msg.ProblemType }; _problemInstances.Add(problemInstance); //Wyslij odpowiedz var responseMsg = new SolveRequestResponseMessage(problemInstance.Id); SendMessage(responseMsg.Serialize(), client); EventLogger.GetLog().InfoFormat("Otrzymano żądanie rozwiązania problemu {0} o id {1}", problemInstance.ProblemType, problemInstance.Id); //Wyslij prosbe o podzielenie var availableComputationalNodes = _computationalNodes.Count(c => c.SolvableProblems.Contains(problemInstance.ProblemType)); var divideProblemMsg = new DivideProblemMessage(problemInstance.ProblemType, problemInstance.Id, problemInstance.Data, (ulong)availableComputationalNodes); SendMessage(divideProblemMsg.Serialize(), taskManagerInfo.Client); EventLogger.GetLog().InfoFormat("Wysłano żądanie podzielenia problemu {0} o id {1} do TM {2}", problemInstance.ProblemType, problemInstance.Id, taskManagerInfo.Id); }
public void Parse_SolveRequestMessage_XMLString() { string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"xml_samples\SolveRequest.xml"); string problemType = "TSP"; ulong id = 12; byte[] data = { 1, 23, 25, 2, 5, 5, 5, 5, 2, 26, 87 }; ulong solvingTimeout = 1000; SolveRequestMessage message = new SolveRequestMessage(problemType, data, solvingTimeout, id); message.ToXmlFile(path); string actualXmlStr = message.ToXmlString(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(path); string expectedXmlStr = xmlDoc.OuterXml; Assert.AreEqual(expectedXmlStr, actualXmlStr); }
static void Main(string[] args) { RegisterType type = RegisterType.ComputationalClient; byte parallelThreads = 5; string[] problems = { "DVRP" }; SolveRequestMessage solveRequestMessage = new SolveRequestMessage(); string inputLine = ""; foreach (string arg in args) { inputLine += arg + " "; } InputParser inputParser = new InputParser(inputLine); inputParser.ParseInput(); IPAddress address = inputParser.Address; int port = inputParser.Port; NetworkNode node = new NetworkNode(type, parallelThreads, problems) { Timeout = CLIENT_REQUEST_FREQUENCY }; SmartConsole.PrintLine("ComputationalClient starting work", SmartConsole.DebugLevel.Advanced); NetworkClient client = new NetworkClient(address, port); for (; ;) { /*************** Register *****************/ doWork = true; SmartConsole.PrintLine("Type in a file path", SmartConsole.DebugLevel.Advanced); String filePath = Console.ReadLine(); solveRequestMessage = loadDataFromDisc(filePath); /****** setup logic modules *****************/ SystemTracker systemTracker = new SystemTracker(node); MessageHandler messageHandler = new MessageHandler(systemTracker, client); MessageProcessor messageProcessor = new MessageProcessor(messageHandler, client, node); KeepAliveTimer keepAliveTimer = new KeepAliveTimer(messageProcessor, systemTracker); messageHandler.keepAliveTimer = keepAliveTimer; node.MessageProcessor = messageProcessor; /************ send solve request *****************/ client.Connect(); messageProcessor.Communicate(solveRequestMessage); COMP_TIME = DateTime.Now; while (doWork) { Thread.Sleep(1000); } /*Object mutex = new Object(); * * lock (mutex) * { * Monitor.Wait(mutex); * }*/ } }
static void Main(string[] args) { EventLogger.AddAppender(new Log4NetAppender()); var ipAddress = "127.0.0.1"; var port = 8123; IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port); Console.WriteLine("Choose component: \n" + "1 ComputationalClient\n" + "2 TaskManager\n" + "3 ComputationalNode\n"); Console.WriteLine("Select: "); int componentType; int.TryParse(Console.ReadLine(), out componentType); Component component = new ComputationalClient(); switch (componentType) { case 1: component = new ComputationalClient(); break; case 2: component = new TaskManager(); break; case 3: component = new ComputationalNode(); break; } component.SolvableProblems = new List <string>() { "MultiplyProblem", "DVRP" }; component.Register(endPoint); var filePath = @"DvrpData\okulD.vrp"; var problem = new DvrpProblem(new DvrpProblemData(filePath)); //var problem = new MultiplyProblem(10, 3, 1000000); while (true) { Common.Abstractions.Message msg = null; int result; Console.WriteLine("RegisterMessage was sent\n" + "Choose another message: \n" + "1 RegisterMessage\n" + "2 RegisterResponseMessage\n" + "3 StatusMessage\n" + "4 SolveRequestMessage\n" + "5 SolveRequestResponseMessage\n" + "6 DivideProblemMessage\n" + "7 SolutionRequestMessage\n" + "8 PartialProblemsMessage\n" + "9 Solutions message\n" + "10 Exit" ); Console.WriteLine("Choose message to send: "); if (int.TryParse(Console.ReadLine(), out result) == false || result < 1 || result > 10) { Console.WriteLine("\nWrong input\n\n"); continue; } switch (result) { case 1: msg = new RegisterMessage(component.Type, 0, component.SolvableProblems); break; case 2: msg = new RegisterResponseMessage(123L, DateTime.Now); break; case 3: msg = new StatusMessage(123L, null); break; case 4: msg = new SolveRequestMessage(problem.ProblemType, problem.SolvingTimeout, problem.Data); break; case 5: msg = new SolveRequestResponseMessage(123L); break; case 6: msg = new DivideProblemMessage("Problem type", 123L, Encoding.UTF8.GetBytes("test1"), 321L); break; case 7: msg = new SolutionRequestMessage(123L); break; case 8: msg = new SolvePartialProblemsMessage("problem type", 123L, Encoding.UTF8.GetBytes("test1"), 333L, null); break; case 9: msg = new SolutionsMessage("problemy type", 123L, Encoding.UTF8.GetBytes("test1"), null); break; case 10: Environment.Exit(0); break; } component.SendMessage(msg.Serialize()); } //component.SendMessage(Encoding.UTF8.GetBytes("dupa")); }
protected virtual void ProcessSolveRequestMessage(SolveRequestMessage message) { }