コード例 #1
0
        protected override string ReceivedDivideProblem(DivideProblem divideProblem)
        {
            /* Divide Problem is sent to TM to start the action of dividing the problem instance to smaller tasks.
             * TM is provided with information about the computational power of the cluster in terms of total number
             * of available threads. The same message is used to relay information for synchronizing info with Backup CS.
             */

            //Debug.Assert(false, "Unimplemented");

            //!!!!!!!!!!!!!!!!!!!
            ////we are not dividing yet - inserting everything into CommonData
            ////the same should be done in the ComputationalNode
            SolvePartialProblems solvePartialProblems = new SolvePartialProblems();

            solvePartialProblems.CommonData = divideProblem.Data;

            solvePartialProblems.Id = divideProblem.Id;
            solvePartialProblems.SolvingTimeoutSpecified = false;
            if (divideProblem.ProblemType != null)
            {
                solvePartialProblems.ProblemType = divideProblem.ProblemType;
            }

            CMSocket.Instance.SendMessage(this.Port, this.IP, solvePartialProblems.SerializeToXML(), this);

            return(null);
        }
コード例 #2
0
        public void SerializeDivideProblem()
        {
            DivideProblem d   = new DivideProblem();
            string        xml = d.SerializeToXML();

            Assert.IsNotNull(xml);
        }
コード例 #3
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());
        }
コード例 #4
0
 protected override void ProcessDivideProblemMessage(DivideProblem message,
                                                     IDictionary <int, ProblemDataSet> dataSets,
                                                     IDictionary <int, ActiveComponent> activeComponents)
 {
     WriteControlInformation(message);
     DataSetOps.HandleDivideProblem(message, dataSets);
 }
コード例 #5
0
        public void DeserializeDivideProblem()
        {
            DivideProblem d   = new DivideProblem();
            string        xml = d.SerializeToXML();

            d = (DivideProblem)xml.DeserializeXML();
            Assert.IsNotNull(d);
        }
コード例 #6
0
        public Message DivideProblem(DivideProblem divideProblem)
        {
            log.DebugFormat("Division of problem has started. ({0})", divideProblem.Id);

            if (!SolvableProblems.Contains(divideProblem.ProblemType))
            {
                log.Debug("Not supported problem type.");
                return(new Error()
                {
                    ErrorMessage = "not supported problem type",
                    ErrorType = ErrorErrorType.InvalidOperation
                });
            }

            var commonData = divideProblem.Data;
            var taskSolver = _resolver.GetInstanceByBaseTypeName(divideProblem.ProblemType, commonData);
            var bytes      = taskSolver.DivideProblem(0);

            log.DebugFormat("Length of divide problem message: {0}", bytes?.Sum(x => x.Length));
            //adding info about partial problems, their task ids, and partialProblem
            //some things can be temporary (partialProblems?)
            storage.AddIssue(divideProblem.Id, new ProblemInfo()
            {
                ProblemsCount  = bytes?.GetLength(0) ?? 0,
                ProblemType    = divideProblem.ProblemType,
                SolutionsCount = 0,
                CommonData     = commonData
            });

            var problemsList = new List <SolvePartialProblemsPartialProblem>();

            //iterate through all partial problems and create proper messages
            for (var i = 0; i < (bytes?.GetLength(0) ?? 0); i++)
            {
                var partialProblem = new SolvePartialProblemsPartialProblem()
                {
                    TaskId = (ulong)i,
                    Data   = bytes[i],
                    NodeID = componentId
                };

                problemsList.Add(partialProblem);
                //adding info about subtask to task manager memory
                storage.AddTaskToIssue(divideProblem.Id, partialProblem);
            }

            log.DebugFormat("Division finished. ({0})", divideProblem.Id);
            //creating msg
            var partialProblems = new SolvePartialProblems()
            {
                ProblemType     = divideProblem.ProblemType,
                Id              = divideProblem.Id,
                CommonData      = divideProblem.Data,
                PartialProblems = problemsList.ToArray()
            };

            return(partialProblems);
        }
コード例 #7
0
        public void DivideProblemConstructorTest()
        {
            //Arrange
            byte[] data = new byte[0];

            //Act
            DivideProblem divideProblem = new DivideProblem("name", 1, data, 1);

            //Assert
            Assert.IsNotNull(divideProblem);
        }
コード例 #8
0
        protected override string ReceivedDivideProblem(DivideProblem divideProblem)
        {
            /* Divide Problem is sent to TM to start the action of dividing the problem instance to smaller tasks.
             * TM is provided with information about the computational power of the cluster in terms of total number
             * of available threads. The same message is used to relay information for synchronizing info with Backup CS.
             */
            Debug.Assert(this.BackupMode == true, "ReceivedDivideProblem received to primary Server");

            //NoOperation noOperationResponse = this.GenerateNoOperation();
            return(null); //noOperationResponse.SerializeToXML();
        }
コード例 #9
0
ファイル: TMNode.cs プロジェクト: kuzawskak/14-pl-05
        /// <summary>
        /// metoda na potzreby symulacji to TEST-weeku
        /// dlatego korzystamy w sumie tylko z liczby CN
        /// </summary>
        /// <param name="msg">DivideProblem message object</param>
        public void DivideProblemSimulation(DivideProblem msg, ComputationalThread thread)
        {
            if (msg == null)
            {
                Console.WriteLine("TM: DivideProblemSimulation failure - msg is null");
                return;
            }
            ulong? timeout_in_miliseconds = timeout != null ? (ulong?)timeout.Millisecond : null;
            ulong computational_nodes = msg.ComputationalNodes;

            var asm = Assembly.Load(AssemblyName.GetAssemblyName(Path.GetFullPath("DVRP.dll")));
            Type t = asm.GetType("DVRP.DVRP");

            var methodInfo = t.GetMethod("DivideProblem");
            object[] constructor_params = new object[1];
            constructor_params[0] = msg.Data;
            var o = Activator.CreateInstance(t, constructor_params);

            object[] param = new object[1];
            param[0] = (int)msg.ComputationalNodes;
            byte[][] result = (byte[][])methodInfo.Invoke(o, param);

            // start_time = DateTime.Now;

            List<PartialProblem> divided_problems = new List<PartialProblem>();
            //tworzymy tyle podproblemow ile dostepnych nodów

            for (int i = 0; i < (int)computational_nodes; i++)
            {
                Console.WriteLine("adding partial problem to divided problems");
                PartialProblem pp = new PartialProblem((ulong)i, result[i]);
                divided_problems.Add(pp);
            }

            if (divided_problems.Count == 0)
            {
                Console.WriteLine("TM: Cannot send msg with no partial problems set");
                return;
            }

            SolverRegisteredProblem srp = new SolverRegisteredProblem(msg.Id, divided_problems);
            ongoing_problems.Add(srp);
            SolvePartialProblems solve_partial_problems_msg = new SolvePartialProblems(msg.ProblemType, msg.Id, msg.Data, timeout_in_miliseconds, divided_problems);

            byte[] response = client.Work(solve_partial_problems_msg.GetXmlData());
            //in this case it's expected value
            if (response == null)
            {
                Console.WriteLine("TM: DivideProblems message sent successfully");
            }
            SetComputationalThreadIdle((ulong)thread.ProblemInstanceId, (ulong)thread.TaskId);
        }
コード例 #10
0
        public void DivideProblemToXmlTest()
        {
            //Arrange
            DivideProblem dp = new DivideProblem("abc", 100, new byte[] { 1, 2, 3, 4 }, 100);
            byte[] data;

            //Act
            data = dp.GetXmlData();

            //Assert
            Assert.IsNotNull(data);

            Debug.WriteLine(System.Text.Encoding.UTF8.GetString(data));
        }
コード例 #11
0
        /// <summary>
        /// handler of respones, sends proper requests
        /// </summary>
        ///
        public override void HandleResponses()
        {
            while (true)
            {
                Message message;
                if (!messageQueue.TryDequeue(out message))
                {
                    Thread.Sleep(100);
                    continue;
                }
                switch (message.MessageType)
                {
                case MessageType.NoOperationMessage:
                    log.Debug("NoOperation acquired: updating backups");
                    UpdateBackups(message.Cast <NoOperation>());
                    break;

                case MessageType.DivideProblemMessage:
                    //should be done in another thread not to
                    //overload message handler thread
                    log.Debug("DivideProblem acquired: dividing problem processing...");
                    DivideProblem msg        = message.Cast <DivideProblem>();
                    Thread        compThread = new Thread
                                                   (o => this.StartLongComputation(() => core.DivideProblem
                                                                                       (msg)));
                    compThread.Start();
                    break;

                case MessageType.SolutionsMessage:
                    //first, in this thread, if solution needs to be linked,
                    //create new thread
                    log.Debug("Solutions acquired: solutions msg processing");
                    Solutions smsg      = message.Cast <Solutions>();
                    Thread    solThread = new Thread(o => this.StartLongComputation
                                                         (() => core.HandleSolutions(smsg)));
                    solThread.Start();
                    break;

                case MessageType.ErrorMessage:
                    log.DebugFormat("Error message acquired:{0}", message.Cast <Error>().ErrorMessage);
                    break;

                default:
                    throw new Exception("Wrong message delivered to TM: " + message.ToString());
                }
            }
        }
コード例 #12
0
 private void ReceiveProblem(DivideProblem _problem)
 {
     Console.WriteLine("Trying to divide Problem ID = {0}", _problem.Id);
     m_lockStatus.WaitOne();
     m_lastChangeTime    = DateTime.Now;
     m_status.Threads[0] = new StatusThread()
     {
         State   = StatusThreadState.Busy,
         HowLong = 0,
         ProblemInstanceIdSpecified = true,
         ProblemInstanceId          = _problem.Id,
         ProblemType     = _problem.ProblemType,
         TaskIdSpecified = false
     };
     m_lockStatus.Release();
     DivideProblem(_problem);
 }
コード例 #13
0
ファイル: XmlParserTests.cs プロジェクト: kuzawskak/14-pl-05
        public void DivideProblemParseTest()
        {
            //Arrange
            DivideProblem dp = new DivideProblem("name", 123, new byte[] { 1, 2, 3 }, 123);
            byte[] data = dp.GetXmlData();

            //Act
            XMLParser parser = new XMLParser(data);

            //Assert
            Assert.IsNotNull(parser);
            Assert.AreEqual(MessageTypes.DivideProblem, parser.MessageType);
            DivideProblem result = (DivideProblem)parser.Message;
            Assert.AreEqual(dp.Id, result.Id);
            Assert.AreEqual(dp.ProblemType, result.ProblemType);
            Assert.AreEqual(dp.ComputationalNodes, result.ComputationalNodes);
            Assert.AreEqual(dp.Data.Length, result.Data.Length);
        }
コード例 #14
0
        public void CheckComputationsWrongMessageExceptionTest()
        {
            var mockcore        = new Mock <ClientNodeProcessingModule>();
            var mockcreator     = new Mock <IMessageArrayCreator>();
            var solutionRequest = new SolutionRequest();

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

            var mockclient = new Mock <IClusterClient>();
            var response   = new DivideProblem();
            var response2  = new Solutions();
            var responses  = new Message[] { response, response2 };

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

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

            var ret = clientNode.CheckComputations(solutionRequest);
        }
コード例 #15
0
        private void SendPartialProblem(DivideProblem _problem, byte[][] partitions)
        {
            SolvePartialProblems solvePartialProblems = new SolvePartialProblems()
            {
                Id              = _problem.Id,
                CommonData      = _problem.Data,
                ProblemType     = taskSolver.Name,
                PartialProblems = new SolvePartialProblemsPartialProblem[partitions.Length]
            };

            for (int i = 0; i < solvePartialProblems.PartialProblems.Length; i++)
            {
                solvePartialProblems.PartialProblems[i] = new SolvePartialProblemsPartialProblem()
                {
                    TaskId = (ulong)i,
                    Data   = partitions[i]
                };
            }
            Send(SerializeMessage <SolvePartialProblems>(solvePartialProblems));
            Console.WriteLine("Sending Partial Problem from Problem ID={0} to server.", _problem.Id);
        }
コード例 #16
0
        private bool SendProblemToTaskManager(ulong _problemId)
        {
            ComponentObject state       = new ComponentObject();
            ulong           freeThreads = 0;
            //  bool flag = false;
            Problem problem = m_problems.Find(e => e.Id == _problemId);

            /* foreach (var computationalNode in m_nodes)
             *   if (computationalNode.solvableProblems.Contains(problem.ProblemType))
             *       foreach (var thread in computationalNode.statusThreads)
             *           if (thread.State == StatusThreadState.Idle)
             *               freeThreads++;*/
            freeThreads = (ulong)m_nodes.Count(node => node.solvableProblems.Contains(problem.ProblemType) && node.statusThreads[0].State == StatusThreadState.Idle);

            foreach (var taskManager in m_managers)
            {
                if (taskManager.solvableProblems.Contains(problem.ProblemType) && taskManager.statusThreads[0].State == StatusThreadState.Idle)
                {
                    problem.manager = taskManager;
                    state           = taskManager.state;
                    break;
                }
            }
            if (state.m_socket == null || freeThreads == 0)
            {
                problem.manager = null;
                return(false);
            }
            DivideProblem divideProblem = new DivideProblem()
            {
                ComputationalNodes = freeThreads,
                Data        = problem.Data,
                Id          = _problemId,
                ProblemType = problem.ProblemType
            };

            return(Send(SerializeMessage(divideProblem), state.m_socket));
        }
コード例 #17
0
        /// <summary>
        /// Sends problem to task (if any is available)
        /// </summary>
        public static void Work(ulong taskId, ServerNetworkAdapter networkAdapter)
        {
            if (DvrpProblem.ProblemsDividing[taskId].Count > 0 || DvrpProblem.SolutionsMerging[taskId].Count > 0)
                return;

            ulong problemId = 0;

            var problems = new List<ulong>(DvrpProblem.ProblemsID);

            foreach (var list in DvrpProblem.ProblemsDividing.Values)
                foreach (var el in list)
                    problems.Remove(el);

            foreach (var list in DvrpProblem.SolutionsMerging.Values)
                foreach (var el in list)
                    problems.Remove(el);

            foreach (var id in problems)
                if (!DvrpProblem.PartialProblems.ContainsKey(id) && !DvrpProblem.PartialSolutions.ContainsKey(id) && !DvrpProblem.ProblemSolutions.ContainsKey(id))
                {
                    problemId = id;
                    break;
                }

            if (problemId == 0)
                return;

            var pr = DvrpProblem.Problems[problemId];
            DivideProblem div = new DivideProblem();
            div.Id = problemId;
            div.ProblemType = pr.ProblemType;
            div.Data = pr.Data;
            div.ComputationalNodes = (ulong)DvrpProblem.Nodes.Count;

            if (networkAdapter.Send(div))
                DvrpProblem.ProblemsDividing[taskId].Add(problemId);
        }
コード例 #18
0
        public void SendProblemInvalidResponseExceptionTest()
        {
            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 invalidResponse = new DivideProblem();
            var properResponse  = new SolveRequestResponse();
            var responses       = new Message[] { invalidResponse, properResponse };

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

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

            var ret = clientNode.SendProblem();
        }
コード例 #19
0
ファイル: Server.cs プロジェクト: kuzawskak/14-pl-05
        /// <summary>
        /// Aktualizuje informację o TM i CN. Sprawdza czy jest dla nich nowe zadanie i jeśli znajdzie, odsyła.
        /// </summary>
        /// <param name="obj">Status TM/CN</param>
        /// <returns></returns>
        private MessageObject UpdateAndGiveData(MessageObject obj)
        {
            MessageObject response = null;
            Status status = obj as Status;

            lock (lockObj)
            {
                Node node = taskManagers.Find(item => item.Id == status.Id);
                if (node == null)
                    node = computationalNodes.Find(item => item.Id == status.Id);

                if (node != null)
                {
                    node.Update(status.Threads);
                    UpdateTemporaryProblems(node.TemporaryProblems);

                    if (node.GetAvailableThreads() > 0)
                    {
                        if (node.GetType() == typeof(TaskManager))
                        {
                            Problem partialP = problems.Find(t => t.Status == ProblemStatus.PartiallySolved
                                && node.SolvableProblems.Contains(t.ProblemType));

                            if (partialP != null)
                            {
                                partialP.Status = ProblemStatus.WaitingForSolutions;

                                List<Solution> solutions = new List<Solution>();
                                node.TemporaryProblems.Add(new TempProblem(partialP.Id, ProblemStatus.WaitingForSolutions, null));

                                foreach (var pp in partialP.PartialProblems)
                                {
                                    solutions.Add(new Solution(pp.TaskId, pp.TimeoutOccured, SolutionType.Partial, pp.ComputationsTime, pp.Data));
                                }

                                response = new Solutions(partialP.ProblemType, partialP.Id, partialP.CommonData, solutions);
                                return response;
                            }

                            Problem newP = problems.Find(t => t.Status == ProblemStatus.New
                                && node.SolvableProblems.Contains(t.ProblemType));

                            if (newP != null)
                            {
                                newP.Status = ProblemStatus.WaitingForDivision;
                                node.TemporaryProblems.Add(new TempProblem(newP.Id, ProblemStatus.WaitingForDivision, null));
                                ulong computationalNodesCount = (ulong)computationalNodes.Sum(t => t.GetAvailableThreads());
                                response = new DivideProblem(newP.ProblemType, newP.Id, newP.Data, computationalNodesCount);
                                return response;
                            }
                        }
                        else    // ComputationalNode
                        {
                            Problem dividedP = problems.Find(t => t.Status == ProblemStatus.Divided
                                && node.SolvableProblems.Contains(t.ProblemType));

                            if (dividedP != null)
                            {
                                List<CommunicationXML.PartialProblem> pp =
                                    dividedP.GetPartialProblemListToSolve(node.GetAvailableThreads());

                                response =
                                    new SolvePartialProblems(dividedP.ProblemType, dividedP.Id,
                                        dividedP.CommonData, dividedP.SolvingTimeout, pp);

                                List<TempPartial> ppnums = new List<TempPartial>();

                                foreach(var x in pp)
                                {
                                    ppnums.Add(new TempPartial(x.TaskId, PartialProblemStatus.Sended));
                                }

                                node.TemporaryProblems.Add(new TempProblem(dividedP.Id, dividedP.Status, ppnums));

                                return response;
                            }
                        }
                    }
                }
            }

            return response;
        }
コード例 #20
0
ファイル: Node.cs プロジェクト: blathursby/15-en-03
 protected abstract string ReceivedDivideProblem(DivideProblem divideProblem);
コード例 #21
0
 protected virtual void ProcessDivideProblemMessage(DivideProblem message,
                                                    IDictionary <int, ProblemDataSet> dataSets,
                                                    IDictionary <int, ActiveComponent> activeComponents)
 {
 }
コード例 #22
0
ファイル: TMNode.cs プロジェクト: kuzawskak/14-pl-05
 //podziel problem
 public void DivideProblem(DivideProblem msg)
 {
     //extract data from message
     //start appropriate method implementing TaskSolver
     ///after dividing problem send PartialProblems message
 }
コード例 #23
0
ファイル: TMNode.cs プロジェクト: kuzawskak/14-pl-05
        public void DivideThreadFunc(DivideProblem msg, ComputationalThread thread)
        {
            if (msg == null)
            {
                Console.WriteLine("TM: DivideProblemSimulation failure - msg is null");
                return;
            }
            ulong? timeout_in_miliseconds = timeout != null ? (ulong?)timeout.Millisecond : null;
            ulong computational_nodes = msg.ComputationalNodes;

            var asm = Assembly.Load(AssemblyName.GetAssemblyName(Path.GetFullPath(msg.ProblemType + ".dll")));
            if (asm == null)
                throw new ArgumentException("Nie mozna znalezc modulu " + msg.ProblemType + ".dll");
            //Type t = asm.GetType("DVRP.DVRP");
            Type t = asm.GetTypes().Where(x => x.IsSubclassOf(typeof(UCCTaskSolver.TaskSolver))).FirstOrDefault();
            if (t == null)
                throw new ArgumentException("Brak odpowiedniej klasy w module.");

            var methodInfo = t.GetMethod("DivideProblem");
            object[] constructor_params = new object[1];
            constructor_params[0] = msg.Data;
            var o = Activator.CreateInstance(t, constructor_params);
            /*********event handler*/

            //var eventInfo = t.GetEvent("ProblemDividingFinished");
            //Type tDelegate = eventInfo.EventHandlerType;

            //MethodInfo addHandler = eventInfo.GetAddMethod();

            //Type returnType = GetDelegateReturnType(tDelegate);
            //Console.WriteLine(returnType.ToString());

            //DynamicMethod handler = new DynamicMethod("", null,
            //                      GetDelegateParameterTypes(tDelegate), t);

            //ILGenerator ilgen = handler.GetILGenerator();

            //Type[] showParameters = { typeof(String) };
            //MethodInfo simpleShow = typeof(CNNode).GetMethod("SetComputationalThreadIdle");
            //Console.WriteLine(simpleShow.ToString());

            //ilgen.Emit(OpCodes.Ldstr, "string");//ct.ProblemInstanceId.Value);//Ldstr,"This event handler was constructed at run time.");
            //ilgen.Emit(OpCodes.Call, simpleShow);
            ////   ilgen.Emit(OpCodes.Pop);
            //ilgen.Emit(OpCodes.Ret);

            //// Complete the dynamic method by calling its CreateDelegate
            //// method. Use the "add" accessor to add the delegate to
            //// the invocation list for the event.
            ////
            //Delegate dEmitted = handler.CreateDelegate(tDelegate);
            //addHandler.Invoke(o, new Object[] { dEmitted });

            object[] param = new object[1];
            param[0] = (int)msg.ComputationalNodes;
            byte[][] result = null;

            try
            {
                result = (byte[][])methodInfo.Invoke(o, param);
            }
            catch (Exception e)
            {
                MessageBox.Show("Moduł '" + msg.ProblemType + ".dll' zakończył działanie z błędem:\n\n" + e.InnerException.Message, "Błąd modułu", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }

            //start_time = DateTime.Now;

            List<PartialProblem> divided_problems = new List<PartialProblem>();
            //tworzymy tyle podproblemow ile dostepnych nodów

            for (int i = 0; i < (int)computational_nodes; i++)
            {
                Console.WriteLine("adding partial problem to divided problems");
                PartialProblem pp = new PartialProblem((ulong)i, result[i]);
                divided_problems.Add(pp);
            }

            if (divided_problems.Count == 0)
            {
                Console.WriteLine("TM: Cannot send msg with no partial problems set");
                return;
            }

            SolverRegisteredProblem srp = new SolverRegisteredProblem(msg.Id, divided_problems);
            ongoing_problems.Add(srp);
            SolvePartialProblems solve_partial_problems_msg = new SolvePartialProblems(msg.ProblemType, msg.Id, msg.Data, timeout_in_miliseconds, divided_problems);

            byte[] response = client.Work(solve_partial_problems_msg.GetXmlData());
            //in this case it's expected value
            if (response == null)
            {
                Console.WriteLine("TM: DivideProblems message sent successfully");
            }
            SetComputationalThreadIdle((ulong)thread.ProblemInstanceId, (ulong)thread.TaskId);
        }
コード例 #24
0
 private void ReceiveDivide(DivideProblem divideProblem)
 {
     problem = divideProblem;
 }
コード例 #25
0
        private void DivideProblem(DivideProblem _problem)
        {
            bool isEnd = false;

            /*   var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
             * List<string> loadedP=new List<string>();
             * foreach (var asembly in loadedAssemblies)
             * {
             *     try
             *     {
             *         string s = asembly.Location;
             *         loadedP.Add(s);
             *     }
             *     catch (Exception) { }
             * }
             *
             *
             * var loadedPaths = loadedP.ToArray();
             * var referencedPaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
             * var toLoad = referencedPaths.Where(r => !loadedPaths.Contains(r, StringComparer.InvariantCultureIgnoreCase)).ToList();
             * toLoad.ForEach(path => loadedAssemblies.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(path))));*/
            List <Assembly> list   = AppDomain.CurrentDomain.GetAssemblies().ToList();
            Type            myType = null;

            foreach (var asem in list)
            {
                foreach (var type in asem.GetTypes())
                {
                    if (type.BaseType == typeof(TaskSolver))
                    {
                        TaskSolver solv = (TaskSolver)Activator.CreateInstance(type, new byte[0]);
                        if (solv.Name == _problem.ProblemType)
                        {
                            myType = type; isEnd = true; break;
                        }
                    }
                }
                if (isEnd)
                {
                    break;
                }
            }

            taskSolver = (UCCTaskSolver.TaskSolver)Activator.CreateInstance(myType, _problem.Data);
            byte[][] partials = taskSolver.DivideProblem((int)_problem.ComputationalNodes);

            SendPartialProblem(_problem, partials);
            m_lockStatus.WaitOne();
            m_lastChangeTime    = DateTime.Now;
            m_status.Threads[0] = new StatusThread()
            {
                State   = StatusThreadState.Idle,
                HowLong = 0,
                ProblemInstanceIdSpecified = false,
                ProblemType     = "",
                TaskIdSpecified = false
            };
            m_lockStatus.Release();

            //List<List<List<List<int>>>> permutationForNodes = new List<List<List<List<int>>>>();
            //for (int i = 0; i < (int)_problem.ComputationalNodes; i++)
            //    permutationForNodes.Add(new List<List<List<int>>>());
            //int ind = 0;
            //foreach (var set in allDevisions)
            // {
            //     permutationForNodes[ind].Add(set);
            //     ind = (ind + 1) % (int)_problem.ComputationalNodes;
            // }
            // SendPartialProblem(_problem, permutationForNodes);
        }
コード例 #26
0
ファイル: TaskManager.cs プロジェクト: pkupidura/NETCluster
        private void DivideAndSendPartialProblems(DivideProblem message)
        {
            var partialProblems = CreatePartialProblems(message);
            if (partialProblems == null) return;

            SendMessageNoResponse(partialProblems);
        }
コード例 #27
0
ファイル: TaskManager.cs プロジェクト: pkupidura/NETCluster
        private SolvePartialProblems CreatePartialProblems(DivideProblem message)
        {
            var taskSolver = CreateSolverOrSendError(message.ProblemType, message.Data);
            if (taskSolver == null) return null;

            var problemsData = taskSolver.DivideProblem(0);

            var partialProblemsMessage = new SolvePartialProblems
            {
                Id = message.Id,
                ProblemType = "DVRP",
                CommonData = message.Data,
                PartialProblems = problemsData.Select((t, i) => new SolvePartialProblemsPartialProblem
                {
                    TaskId = (ulong) i, NodeID = Id, Data = t
                }).ToArray()
            };

            return partialProblemsMessage;
        }
コード例 #28
0
 protected override string ReceivedDivideProblem(DivideProblem divideProblem)
 {
     Debug.Assert(false, "Should not be here");
     return(null);
 }
コード例 #29
0
 public static void HandleDivideProblem(DivideProblem message, IDictionary <int, ProblemDataSet> dataSets)
 {
     dataSets[(int)message.Id].TaskManagerId = (int)message.NodeID;
 }
コード例 #30
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());
        }
コード例 #31
0
        /// <summary>
        /// gets proper problem to solve as response for status msg request from TM
        /// </summary>
        /// <param name="components">active components list</param>
        /// <param name="componentId">the id of TM that send status</param>
        /// <param name="dataSets">current server problem memory</param>
        /// <returns>message for TM</returns>
        public static Message GetMessageForTaskManager
            (IDictionary <int, ActiveComponent> components, int componentId,
            IDictionary <int, ProblemDataSet> dataSets)
        {
            //TODO: get message for TM - implementation
            Message response = null;

            //checking divide problem posibilities
            foreach (var dataSet in dataSets.Where(dataSet => components[componentId].SolvableProblems.Contains(dataSet.Value.ProblemType) && dataSet.Value.TaskManagerId == 0))
            {
                response = new DivideProblem()
                {
                    ComputationalNodes = 1, //we'll worry about this later
                    Data        = dataSet.Value.CommonData,
                    Id          = (ulong)dataSet.Key,
                    NodeID      = (ulong)componentId,
                    ProblemType = dataSet.Value.ProblemType
                };
                dataSet.Value.TaskManagerId = componentId;
                break;
            }
            //if divide problem is here, we can send it:
            if (response != null)
            {
                return(response);
            }

            //checking linking solutions posibilites
            foreach (var dataSet in dataSets)
            {
                //check only in your own problem assignments
                if (dataSet.Value.TaskManagerId != componentId)
                {
                    continue;
                }
                //problem is not divided yet, so nothing
                if (dataSet.Value.PartialSets == null || dataSet.Value.PartialSets.Length == 0)
                {
                    break;
                }
                //check potential solutions-to-link
                var solutionsToSend = new List <SolutionsSolution>();
                foreach (var partialSet in dataSet.Value.PartialSets.Where(partialSet => partialSet.Status == PartialSetStatus.Ongoing &&
                                                                           partialSet.PartialSolution != null))
                {
                    solutionsToSend.Add(partialSet.PartialSolution);
                    partialSet.Status = PartialSetStatus.Sent;
                }
                //if can be linked, then make a message and break
                if (solutionsToSend.Count > 0)
                {
                    return(new Solutions()
                    {
                        CommonData = dataSet.Value.CommonData,
                        Id = (ulong)dataSet.Key,
                        ProblemType = dataSet.Value.ProblemType,
                        SolutionsList = solutionsToSend.ToArray()
                    });
                }
            }
            return(null);
        }
コード例 #32
0
 protected virtual Message[] RespondDivideProblemMessage(DivideProblem message,
                                                         IDictionary <int, ProblemDataSet> dataSets,
                                                         IDictionary <int, ActiveComponent> activeComponents)
 {
     return(null);
 }