예제 #1
0
        public void SolvePartialProblemsWithTimeoutTest()
        {
            //Arrange
            SolvePartialProblems spp = new SolvePartialProblems("name", 123, new byte[] { 1, 2, 3 }, null, new List<PartialProblem>() {
                new PartialProblem(123, new byte[]{ 1, 2, 3, 4}),
                new PartialProblem(321, new byte[]{ 4, 3, 2, 1})
            });

            //Act
            byte[] data = spp.GetXmlData();

            //Assert
            Assert.IsNotNull(data);

            Debug.WriteLine(System.Text.Encoding.UTF8.GetString(data));
        }
예제 #2
0
        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);
        }
예제 #3
0
        /// <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);
        }
예제 #4
0
        public void SolvePartialProblemsConstructorTest()
        {
            //Arrange
            byte[] data = new byte[0];
            PartialProblem[] partialProblems = new PartialProblem[]{ new PartialProblem(0, (byte[])data.Clone()),
                new PartialProblem(1, (byte[])data.Clone()) };

            //Act
            SolvePartialProblems solvePartialProblems = new SolvePartialProblems("name",
                0, data, null, partialProblems);

            //Assert
            Assert.IsNotNull(solvePartialProblems);
        }
예제 #5
0
        public void SolvePartialProblemsParseTest()
        {
            //Arrange
            SolvePartialProblems spp = new SolvePartialProblems("name", 123, new byte[] { 1, 2, 3 }, null, new List<PartialProblem>() {
                new PartialProblem(123, new byte[]{ 1, 2, 3, 4}),
                new PartialProblem(321, new byte[]{ 4, 3, 2, 1})
            });

            byte[] data = spp.GetXmlData();

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

            //Assert
            Assert.IsNotNull(parser);
            Assert.AreEqual(MessageTypes.SolvePartialProblems, parser.MessageType);
            SolvePartialProblems result = (SolvePartialProblems)parser.Message;
            Assert.AreEqual(spp.CommonData.Length, result.CommonData.Length);
            Assert.AreEqual(spp.Id, result.Id);
            Assert.AreEqual(spp.PartialProblems.Count, result.PartialProblems.Count);
            Assert.AreEqual(spp.ProblemType, result.ProblemType);
            Assert.IsNull(result.SolvingTimeout);
            PartialProblem p = spp.PartialProblems[0];
            PartialProblem rp = spp.PartialProblems[0];
            Assert.AreEqual(p.TaskId, rp.TaskId);
            Assert.AreEqual(p.Data.Length, rp.Data.Length);
        }
예제 #6
0
        public void NodeThreadFunc(/*object o, MethodInfo methodInfo,*/ SolvePartialProblems msg, PartialProblem pp, ComputationalThread ct)
        {
            DateTime start_time = DateTime.Now;

            var asm = Assembly.Load(AssemblyName.GetAssemblyName(Path.GetFullPath(msg.ProblemType + ".dll")));
            //Type t = asm.GetType("DVRP.DVRP");
            Type t = asm.GetTypes().Where(x => x.IsSubclassOf(typeof(UCCTaskSolver.TaskSolver))).FirstOrDefault();

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

            var eventInfo = t.GetEvent("SolutionsMergingFinished");
            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 });

            if (methodInfo != null)
            {
                object[] param = new object[2];

                param[0] = pp.Data;
                if (msg.SolvingTimeout == null)
                    param[1] = null;
                else param[1] = new TimeSpan((long)msg.SolvingTimeout * 10000000);

                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();
                }

                TimeSpan ts = DateTime.Now - start_time;
                Solution s = new Solution(pp.TaskId, false, SolutionType.Partial, (ulong)ts.TotalSeconds, result);

                solution.Add(s);
                Console.WriteLine("sending partial solutions");
                Solutions solutions = new Solutions(msg.ProblemType, msg.Id, msg.CommonData, solution);

                client.Work(solutions.GetXmlData());

                SetComputationalThreadIdle(msg.Id, pp.TaskId);
            }
            else Console.WriteLine("Method equal to null");
        }
예제 #7
0
        /// <summary>
        /// Rozwiazuje nadeslany problem czesciowy
        /// </summary>
        public void SolveProblem(SolvePartialProblems msg)
        {
            //get the problem with your id
            solution = new List<Solution>();
            List<PartialProblem> problems_list = msg.PartialProblems;
            //i dla kazdego z listy tworz nowy watek
            // Thread[] threadss = new Thread[problems_list.Capacity];

            int i = 0;
            if (problems_list != null)
            {
                foreach (PartialProblem pp in problems_list)
                {
                    ComputationalThread ct = threads.Find(x => x.State == ComputationalThreadState.Idle);
                    threads.Remove(ct);
                    ComputationalThread new_thread = new ComputationalThread(ComputationalThreadState.Busy, 0, msg.Id, pp.TaskId, msg.ProblemType);
                    threads.Add(new_thread);

                    threadss[i] = new Thread(() => NodeThreadFunc(/*o,methodInfo*,*/msg, pp, new_thread));
                    threadss[i].Start();
                    i++;

                }

            }
            else
            {
                Console.WriteLine("PartialProblems list is null");
            }
        }
예제 #8
0
        /// <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;
        }