Free cookie consent management tool by TermsFeed Policy Generator

Changeset 13887


Ignore:
Timestamp:
06/08/16 17:02:06 (8 years ago)
Author:
thasling
Message:

prepared protoype for next meeting

Location:
branches/thasling/DistributedGA
Files:
5 deleted
25 edited

Legend:

Unmodified
Added
Removed
  • branches/thasling/DistributedGA/DistributedGA.ContactServer.Host/DistributedGA.ContactServer.Host.csproj

    r13524 r13887  
    4848  <ItemGroup>
    4949    <None Include="App.config" />
     50    <None Include="startServer.bat">
     51      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
     52    </None>
    5053  </ItemGroup>
    5154  <ItemGroup>
  • branches/thasling/DistributedGA/DistributedGA.ContactServer.Host/Program.cs

    r13557 r13887  
    22using System.ServiceModel;
    33
    4 namespace DistributedGA.ContactServer.Host {
    5   class Program {
    6     static void Main(string[] args) {
    7       string baseAddress = string.Empty;
    8       if (args.GetUpperBound(0) > -1) {
    9         baseAddress = args[0];
    10       }
    11       if (string.IsNullOrWhiteSpace(baseAddress)) {
    12         baseAddress = "net.tcp://localhost:9090/DistributedGA.ContactServer/ContactService";
    13       }
    14       using (ServiceHost host = new ServiceHost(typeof(ContactServiceImpl), new Uri[] { new Uri(baseAddress) })) {
    15         // Enable metadata publishing.
     4namespace DistributedGA.ContactServer.Host
     5{
     6    class Program
     7    {
     8        static void Main(string[] args)
     9        {
     10            string baseAddress = string.Empty;
     11            if (args.GetUpperBound(0) > -1)
     12            {
     13                baseAddress = args[0];
     14            }
     15            if (string.IsNullOrWhiteSpace(baseAddress))
     16            {
     17                baseAddress = "net.tcp://localhost:9090/DistributedGA.ContactServer/ContactService";
     18            }
     19            using (ServiceHost host = new ServiceHost(typeof(ContactServiceImpl), new Uri[] { new Uri(baseAddress) }))
     20            {
     21                // Enable metadata publishing.
    1622
    1723
    18         // Open the ServiceHost to start listening for messages. Since
    19         // no endpoints are explicitly configured, the runtime will create
    20         // one endpoint per base address for each service contract implemented
    21         // by the service.
     24                // Open the ServiceHost to start listening for messages. Since
     25                // no endpoints are explicitly configured, the runtime will create
     26                // one endpoint per base address for each service contract implemented
     27                // by the service.
    2228
    23         host.Open();
     29                host.Open();
    2430
    25         Console.WriteLine("The service is ready at {0}", baseAddress);
    26         Console.WriteLine("Press <Enter> to stop the service.");
    27         Console.ReadLine();
     31                Console.WriteLine("The service is ready at {0}", baseAddress);
     32                Console.WriteLine("Press <Enter> to stop the service.");
     33                Console.ReadLine();
    2834
    29         // Close the ServiceHost.
    30         host.Close();
    31       }
     35                // Close the ServiceHost.
     36                host.Close();
     37            }
     38        }
    3239    }
    33   }
    3440}
  • branches/thasling/DistributedGA/DistributedGA.ContactServer/ContactServiceImpl.cs

    r13557 r13887  
    88using DistributedGA.Core.Domain;
    99
    10 namespace DistributedGA.ContactServer {
     10namespace DistributedGA.ContactServer
     11{
    1112
    12   [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    13   public class ContactServiceImpl : IContactService {
     13    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
     14    public class ContactServiceImpl : IContactService
     15    {
    1416
    15     private ConcurrentDictionary<PeerInfo, DateTime> allPeers = null;
     17        private ConcurrentDictionary<PeerInfo, DateTime> allPeers = null;
    1618
    17     private Timer timer = null;
     19        private Timer timer = null;
    1820
    19     private Object logLock = new Object();
     21        private Object logLock = new Object();
    2022
    21     public ContactServiceImpl() {
    22       allPeers = new ConcurrentDictionary<PeerInfo, DateTime>();
     23        public ContactServiceImpl()
     24        {
     25            allPeers = new ConcurrentDictionary<PeerInfo, DateTime>();
    2326
    24       timer = new Timer(60 * 1000); //each hour
    25       timer.Elapsed += CleanUpContactTable;
    26       timer.Start();
     27            timer = new Timer(1000 * 60 * 60); //each hour
     28            timer.Elapsed += CleanUpContactTable;
     29            timer.Start();
     30        }
     31
     32        public void RegisterPeer(PeerInfo source)
     33        {
     34            try
     35            {
     36                UpdateHeartbeat(source);
     37            }
     38            catch (Exception ex)
     39            {
     40                AddError("ContactServiceImpl.RegisterPeer", ex);
     41            }
     42        }
     43
     44        public List<PeerInfo> GetPeerList(PeerInfo source)
     45        {
     46            try
     47            {
     48                UpdateHeartbeat(source);
     49                //only return peers of the same work group and not the sender itself
     50                return allPeers.Keys.Where(x =>
     51                {
     52                    if (source.ProblemInstance.Equals(x.ProblemInstance) &&
     53                        (!(x.IpAddress.Equals(source.IpAddress) && (x.Port.Equals(source.Port)))))
     54                        return true;
     55                    else
     56                        return false;
     57                }).ToList();
     58            }
     59            catch (Exception ex)
     60            {
     61                AddError("ContactServiceImpl.GetPeerList", ex);
     62                return null;
     63            }
     64        }
     65
     66        public void MakeLog(PeerInfo source, string msg)
     67        {
     68            try
     69            {
     70                // TODO
     71                lock (logLock)
     72                {
     73                    File.AppendAllText("Log.txt", string.Concat(source.IpAddress, ":", source.Port, ",", source.ProblemInstance, ",", msg, Environment.NewLine));
     74                }
     75            }
     76            catch (Exception ex)
     77            {
     78                //Nothing to do because maybe called from adderror
     79            }
     80        }
     81
     82        public void UpdateHeartbeat(PeerInfo source)
     83        {
     84            try
     85            {
     86                Console.WriteLine("hb from {0}:{1}", source.IpAddress, source.Port);
     87                DateTime now = DateTime.Now;
     88                allPeers.AddOrUpdate(source, now, (k, v) => v = now);
     89            }
     90            catch (Exception ex)
     91            {
     92                AddError("ContactServiceImpl.UpdateHeartbeat", ex);
     93            }
     94        }
     95
     96        private void CleanUpContactTable(object sender, ElapsedEventArgs e)
     97        {
     98            DateTime deadline = DateTime.Now;
     99            //collect items to remove
     100            List<PeerInfo> itemsToDelete = new List<PeerInfo>();
     101            foreach (PeerInfo pi in allPeers.Keys)
     102            {
     103                DateTime tmp;
     104                if (allPeers.TryGetValue(pi, out tmp))
     105                {
     106                    if (tmp.AddHours(1f) < deadline)
     107                    {
     108                        //if (tmp < deadline.AddHours(1f)) {
     109                        itemsToDelete.Add(pi);
     110                    }
     111                }
     112            }
     113            //remove items
     114            foreach (PeerInfo pi in itemsToDelete)
     115            {
     116                DateTime tmp;
     117                allPeers.TryRemove(pi, out tmp);
     118            }
     119        }
     120
     121        private void AddError(string source, Exception ex)
     122        {
     123            MakeLog(new PeerInfo() { ProblemInstance = "ContactServer  Error at " + source }, ex.Message);
     124        }
     125
    27126    }
    28 
    29     public void RegisterPeer(PeerInfo source) {
    30       try {
    31         UpdateHeartbeat(source);
    32       } catch (Exception ex) {
    33         AddError("ContactServiceImpl.RegisterPeer", ex);
    34       }
    35     }
    36 
    37     public List<PeerInfo> GetPeerList(PeerInfo source) {
    38       try {
    39         UpdateHeartbeat(source);
    40         //only return peers of the same work group and not the sender itself
    41         return allPeers.Keys.Where(x => {
    42           if (source.ProblemInstance.Equals(x.ProblemInstance) &&
    43               (!(x.IpAddress.Equals(source.IpAddress) && (x.Port.Equals(source.Port)))))
    44             return true;
    45           else
    46             return false;
    47         }).ToList();
    48       } catch (Exception ex) {
    49         AddError("ContactServiceImpl.GetPeerList", ex);
    50         return null;
    51       }
    52     }
    53 
    54     public void MakeLog(PeerInfo source, string msg) {
    55       try {
    56         // TODO
    57         lock (logLock) {
    58           File.AppendAllText("Log.txt", string.Concat(source.IpAddress, ":", source.Port, ",", source.ProblemInstance, ",", msg, Environment.NewLine));
    59         }
    60       } catch (Exception ex) {
    61         //Nothing to do because maybe called from adderror
    62       }
    63     }
    64 
    65     private void UpdateHeartbeat(PeerInfo source) {
    66       Console.WriteLine("hb from {0}:{1}", source.IpAddress, source.Port);
    67       DateTime now = DateTime.Now;
    68       allPeers.AddOrUpdate(source, now, (k, v) => v = now);
    69     }
    70 
    71     private void CleanUpContactTable(object sender, ElapsedEventArgs e) {
    72       DateTime deadline = DateTime.Now;
    73       //collect items to remove
    74       List<PeerInfo> itemsToDelete = new List<PeerInfo>();
    75       foreach (PeerInfo pi in allPeers.Keys) {
    76         DateTime tmp;
    77         if (allPeers.TryGetValue(pi, out tmp)) {
    78           if (tmp.AddHours(1f) < deadline) {
    79             //if (tmp < deadline.AddHours(1f)) {
    80             itemsToDelete.Add(pi);
    81           }
    82         }
    83       }
    84       //remove items
    85       foreach (PeerInfo pi in itemsToDelete) {
    86         DateTime tmp;
    87         allPeers.TryRemove(pi, out tmp);
    88       }
    89     }
    90 
    91     private void AddError(string source, Exception ex) {
    92       MakeLog(new PeerInfo() { ProblemInstance = "ContactServer  Error at " + source }, ex.Message);
    93     }
    94 
    95   }
    96127}
  • branches/thasling/DistributedGA/DistributedGA.ContactServer/IContactService.cs

    r13524 r13887  
    1919
    2020        [OperationContract]
    21         void MakeLog(PeerInfo source, string msg); //used to log all peers at a single location
    22  
     21        void UpdateHeartbeat(PeerInfo source); //Sends heartbeat to contact-server
     22
     23        [OperationContract]
     24        void MakeLog(PeerInfo source, string msg); //Used to log all peers at a single location
     25
    2326    }
    2427}
  • branches/thasling/DistributedGA/DistributedGA.Core

    • Property svn:global-ignores set to
      obj
  • branches/thasling/DistributedGA/DistributedGA.Core.Host/App.config

    r13557 r13887  
    66  <appSettings>
    77    <add key="ContactServerURL" value="net.tcp://localhost:9090/DistributedGA.ContactServer/ContactService"/>
    8     <add key="LanIpPrefix" value="10."/>
     8    <add key="LanIpPrefix" value="192."/>
     9    <!--<add key="LanIpPrefix" value="10."/>-->
    910  </appSettings>
    1011</configuration>
  • branches/thasling/DistributedGA/DistributedGA.Core.Host/Program.cs

    r13557 r13887  
    66using DistributedGA.Core.Interface;
    77
    8 namespace DistributedGA.Core.Host {
    9   class Program {
    10     static void Main(string[] args) {
    11       try {
    12         Console.WriteLine("Starting peer...");
    13         string ipPrefix = ConfigurationManager.AppSettings["LanIpPrefix"];
    14         string serverUrl = ConfigurationManager.AppSettings["ContactServerURL"];
     8namespace DistributedGA.Core.Host
     9{
     10    class Program
     11    {
     12        static void Main(string[] args)
     13        {
     14            try
     15            {
     16                Console.WriteLine("Starting peer...");
     17                string ipPrefix = ConfigurationManager.AppSettings["LanIpPrefix"];
     18                string serverUrl = ConfigurationManager.AppSettings["ContactServerURL"];
    1519
     20                IMessageHandler h = new PeerNetworkMessageHandler();
     21                h.Init(ipPrefix, serverUrl);
    1622
    17         IMessageHandler h = new PeerNetworkMessageHandler();
    18         h.Init(ipPrefix, serverUrl);
    19         PeerInfo pi = h.GetPeerInfo();
    20         Console.WriteLine(string.Format("Peer is hostet at IP: {0} and port: {1}", pi.IpAddress, pi.Port));
    21         Thread.Sleep(1000 * 20);
    22         Console.WriteLine("Current peers within network:");
    23         foreach (var item in h.GetCurrentNetwork()) {
    24           Console.WriteLine(string.Format("Peer at {0}:{1}", item.IpAddress, item.Port));
     23                PeerInfo pi = h.GetPeerInfo();
     24                Console.WriteLine(string.Format("Peer is hostet at IP: {0} and port: {1}", pi.IpAddress, pi.Port));
     25                Thread.Sleep(1000 * 20);
     26                Console.WriteLine("Current peers within network:");
     27                foreach (var item in h.GetCurrentNetwork())
     28                {
     29                    Console.WriteLine(string.Format("Peer at {0}:{1}", item.IpAddress, item.Port));
     30                }
     31
     32                int i = 0;
     33                while (i < 10)
     34                {
     35                    i++;
     36                    Thread.Sleep(1000 * 10);
     37                    var message = CreateMessage(pi, i);
     38                    Console.WriteLine("Publishing messages...");
     39                    h.PublishDataToNetwork(message);
     40                    Console.WriteLine("Messages published.");
     41                    Console.WriteLine("Recieved messages:");
     42                    foreach (var item in h.GetDataFromNetwork())
     43                    {
     44                        Console.WriteLine(string.Format("Message:{0}", GetString(item)));
     45                    }
     46                }
     47            }
     48            catch (Exception ex)
     49            {
     50                Console.WriteLine(ex.Message);
     51                Console.WriteLine("press any key to continue...");
     52                Console.ReadLine();
     53            }
     54
    2555        }
    26         int i = 1;
    27         while (i < 10) {
    28           i++;
    29           Thread.Sleep(1000 * 10);
    30           var pop1 = CreatePopulation();
    31           Console.WriteLine("Publish population into network...");
    32           h.PublishDataToNetwork(pop1);
    33           Console.WriteLine("Population published.");
    34           Console.WriteLine("Recieved populations:");
    35           foreach (var item in h.GetDataFromNetwork()) {
    36             Console.WriteLine(string.Format("Population with Quality: {0:2} in Iteration {1}", item.Quality, item.IterationNumber));
    37           }
     56
     57        private static byte[][] CreateMessage(PeerInfo pi, int iterationNumber)
     58        {
     59            string msg1 = string.Concat("Message 1 from Peer ", pi.IpAddress, ":", pi.Port, " at iteration ", iterationNumber);
     60            string msg2 = string.Concat("Message 2 from Peer ", pi.IpAddress, ":", pi.Port, " at iteration ", iterationNumber);
     61            return new byte[][] { GetBytes(msg1), GetBytes(msg2) };
    3862        }
    39       } catch (Exception ex) {
    40         Console.WriteLine(ex.Message);
    41         Console.WriteLine("press any key to continue...");
    42         Console.ReadLine();
    43       }
    4463
     64        static byte[] GetBytes(string str)
     65        {
     66            byte[] bytes = new byte[str.Length * sizeof(char)];
     67            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
     68            return bytes;
     69        }
     70
     71        static string GetString(byte[] bytes)
     72        {
     73            char[] chars = new char[bytes.Length / sizeof(char)];
     74            System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
     75            return new string(chars);
     76        }
    4577    }
    46 
    47     private static SolutionInfo[] CreatePopulation() {
    48       SolutionInfo si1 = new SolutionInfo() {
    49         IterationNumber = 1,
    50         Quality = 3.5f,
    51         Solution = new Solution() {
    52         }
    53       };
    54       SolutionInfo si2 = new SolutionInfo() {
    55         IterationNumber = 2,
    56         Quality = 3.5f,
    57         Solution = new Solution() {
    58         }
    59       };
    60       SolutionInfo si3 = new SolutionInfo() {
    61         IterationNumber = 3,
    62         Quality = 3.5f,
    63         Solution = new Solution() {
    64         }
    65       };
    66       return new SolutionInfo[] { si1, si2, si3 };
    67     }
    68   }
    6978}
  • branches/thasling/DistributedGA/DistributedGA.Core/DistributedGA.Core.csproj

    r13556 r13887  
    6464    <Compile Include="Interface\IPeerListManager.cs" />
    6565    <Compile Include="Properties\AssemblyInfo.cs" />
    66     <Compile Include="Solution.cs" />
    67     <Compile Include="SolutionInfo.cs" />
    6866  </ItemGroup>
    6967  <ItemGroup>
  • branches/thasling/DistributedGA/DistributedGA.Core/Domain/MessageRecieveEventArgs.cs

    r13553 r13887  
    11using System;
    22
    3 namespace DistributedGA.Core.Domain {
    4   public class MessageRecieveEventArgs : EventArgs {
    5     public int val;
    6     public SolutionInfo[] data { get; set; }
    7     public PeerInfo Sender { get; set; }
    8   }
     3namespace DistributedGA.Core.Domain
     4{
     5    public class MessageRecieveEventArgs : EventArgs
     6    {
     7        public int val;
     8        public byte[][] data { get; set; }
     9        public PeerInfo Sender { get; set; }
     10    }
    911}
  • branches/thasling/DistributedGA/DistributedGA.Core/Implementation/MessageContractImpl.cs

    r13553 r13887  
    44using DistributedGA.Core.Interface;
    55
    6 namespace DistributedGA.Core.Implementation {
    7   [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    8   public class MessageContractImpl : IMessageContract {
    9     public void SendData(PeerInfo sender, SolutionInfo[] data) {
    10       MessageRecieveEventArgs args = new MessageRecieveEventArgs() { Sender = sender, data = data };
     6namespace DistributedGA.Core.Implementation
     7{
     8    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
     9    public class MessageContractImpl : IMessageContract
     10    {
     11        public void SendData(PeerInfo sender, byte[][] data)
     12        {
     13            MessageRecieveEventArgs args = new MessageRecieveEventArgs() { Sender = sender, data = data };
    1114
    12       if (MessageRecieved != null) {
    13         MessageRecieved(this, args);
    14       }
     15            if (MessageRecieved != null)
     16            {
     17                MessageRecieved(this, args);
     18            }
     19        }
     20
     21        public event EventHandler<MessageRecieveEventArgs> MessageRecieved;
     22
    1523    }
    16 
    17     public event EventHandler<MessageRecieveEventArgs> MessageRecieved;
    18 
    19   }
    2024}
  • branches/thasling/DistributedGA/DistributedGA.Core/Implementation/PeerNetworkMessageHandler.cs

    r13556 r13887  
    77using DistributedGA.Core.Interface;
    88
    9 namespace DistributedGA.Core.Implementation {
    10   public class PeerNetworkMessageHandler : IMessageHandler {
    11     //own peer-instance Information
    12     private PeerInfo ownInstance = null;
     9namespace DistributedGA.Core.Implementation
     10{
     11    public class PeerNetworkMessageHandler : IMessageHandler
     12    {
     13        //own peer-instance Information
     14        private PeerInfo ownInstance = null;
    1315
    14     //uses peer-list from IPeerListManager to decide which peers to contact
    15     private IPeerListManager peerListManager;
     16        //uses peer-list from IPeerListManager to decide which peers to contact
     17        private IPeerListManager peerListManager;
    1618
    17     //uses IMessageSender to send populations to peers
    18     private IMessageSender sender = null;
     19        //uses IMessageSender to send populations to peers
     20        private IMessageSender sender = null;
    1921
    20     //provides current population for the higher layer IMigrationOperator
    21     //to queues are used to gather and and provide population more efficiently
    22     private object activeQueueLocker = new object();
    23     private ConcurrentQueue<SolutionInfo> writeQueue;
    24     private ConcurrentQueue<SolutionInfo> readQueue;
     22        //provides current population for the higher layer IMigrationOperator
     23        //to queues are used to gather and and provide population more efficiently
     24        private object activeQueueLocker = new object();
     25        private ConcurrentQueue<byte[]> writeQueue;
     26        private ConcurrentQueue<byte[]> readQueue;
    2527
    26     //uses IMessageService for recieving population from one peer at once
    27     private IMessageService host = null;
     28        //uses IMessageService for recieving population from one peer at once
     29        private IMessageService host = null;
    2830
    2931
    3032
    31     public void Init(string lanIpPrefix, string contactServerUrl) {
    32       try {
    33         ownInstance = new PeerInfo() {
    34           IpAddress = GetExternalIpAddress(lanIpPrefix),
    35           Port = 0,
    36           ProblemInstance = "TestProblem"
    37         }; // TODO: get own peerinfo
     33        public void Init(string lanIpPrefix, string contactServerUrl)
     34        {
     35            try
     36            {
     37                ownInstance = new PeerInfo()
     38                {
     39                    IpAddress = GetInternalIpAddress(lanIpPrefix),
     40                    Port = 0,
     41                    ProblemInstance = "TestProblem"
     42                }; // TODO: get own peerinfo
    3843
    39         writeQueue = new ConcurrentQueue<SolutionInfo>();
    40         readQueue = new ConcurrentQueue<SolutionInfo>();
     44                writeQueue = new ConcurrentQueue<byte[]>();
     45                readQueue = new ConcurrentQueue<byte[]>();
    4146
    42         host = new WcfMessageService();
    43         ownInstance.Port = host.Init(ownInstance.IpAddress); //getting port, on which service is hostet
    44         host.OnDataRecieved += new EventHandler<MessageRecieveEventArgs>(OnPopulationRecieved);
     47                host = new WcfMessageService();
     48                ownInstance.Port = host.Init(ownInstance.IpAddress); //getting port, on which service is hostet
     49                host.OnDataRecieved += new EventHandler<MessageRecieveEventArgs>(OnPopulationRecieved);
    4550
    46         peerListManager = new WcfPeerListManager();
    47         peerListManager.Init(ownInstance, contactServerUrl);
     51                peerListManager = new WcfPeerListManager();
     52                peerListManager.Init(ownInstance, contactServerUrl);
    4853
    49         sender = new WcfMessageSender();
    50         sender.Init(ownInstance);
     54                sender = new WcfMessageSender();
     55                sender.Init(ownInstance);
    5156
    52       } catch (Exception ex) {
    53         AddError("PeerNetworkMessageHandler.Init", ex);
    54       }
    55     }
    56 
    57     public void Dispose() {
    58       try {
    59         host.Dispose();
    60       } catch (Exception ex) {
    61         AddError("PeerNetworkMessageHandler.Dispose", ex);
    62       }
    63     }
    64 
    65     public void PublishDataToNetwork(SolutionInfo[] data) {
    66       try {
    67         foreach (PeerInfo peer in peerListManager.GetPeerList()) {
    68           //HACK: manipulate for monitoring in test
    69           foreach (SolutionInfo si in data) {
    70             si.IterationNumber = ownInstance.Port;
    71           }
    72           //maybe something will go wrong during network communication...
    73           try {
    74             sender.SendData(peer, data);
    75           } catch (Exception ex) {
    76             AddError("PeerNetworkMessageHandler.PublishMigrationInfo(during sending to one peer!)", ex);
    77           }
    78         }
    79       } catch (Exception ex) {
    80         AddError("PeerNetworkMessageHandler.PublishMigrationInfo", ex);
    81       }
    82     }
    83 
    84     public SolutionInfo[] GetDataFromNetwork() {
    85       try {
    86         List<SolutionInfo> res = new List<SolutionInfo>();
    87         SolutionInfo item = null;
    88         lock (activeQueueLocker) {
    89           var tmp = readQueue;
    90           readQueue = writeQueue;
    91           writeQueue = tmp;
     57            }
     58            catch (Exception ex)
     59            {
     60                AddError("PeerNetworkMessageHandler.Init", ex);
     61            }
    9262        }
    9363
    94         //creating resultset
    95         while (!readQueue.IsEmpty) {
    96           if (readQueue.TryDequeue(out item)) {
    97             res.Add(item);
    98           }
     64        public void Dispose()
     65        {
     66            try
     67            {
     68                host.Dispose();
     69            }
     70            catch (Exception ex)
     71            {
     72                AddError("PeerNetworkMessageHandler.Dispose", ex);
     73            }
    9974        }
    100         return res.ToArray();
    101       } catch (Exception ex) {
    102         AddError("PeerNetworkMessageHandler.GetMigrationInfo", ex);
    103         return null;
    104       }
     75
     76        public void PublishDataToNetwork(byte[][] data)
     77        {
     78            try
     79            {
     80                foreach (PeerInfo peer in peerListManager.GetPeerList())
     81                {
     82                    //maybe something will go wrong during network communication...
     83                    try
     84                    {
     85                        sender.SendData(peer, data);
     86                    }
     87                    catch (Exception ex)
     88                    {
     89                        AddError("PeerNetworkMessageHandler.PublishDataToNetwork(during sending to one peer!)", ex);
     90                    }
     91                }
     92            }
     93            catch (Exception ex)
     94            {
     95                AddError("PeerNetworkMessageHandler.PublishDataToNetwork", ex);
     96            }
     97        }
     98
     99        public byte[][] GetDataFromNetwork()
     100        {
     101            try
     102            {
     103                List<byte[]> res = new List<byte[]>();
     104                byte[] item = null;
     105                lock (activeQueueLocker)
     106                {
     107                    var tmp = readQueue;
     108                    readQueue = writeQueue;
     109                    writeQueue = tmp;
     110                }
     111
     112                //creating resultset
     113                while (!readQueue.IsEmpty)
     114                {
     115                    if (readQueue.TryDequeue(out item))
     116                    {
     117                        res.Add(item);
     118                    }
     119                }
     120                return res.ToArray();
     121            }
     122            catch (Exception ex)
     123            {
     124                AddError("PeerNetworkMessageHandler.GetDataFromNetwork", ex);
     125                return null;
     126            }
     127        }
     128
     129        public PeerInfo GetPeerInfo()
     130        {
     131            return ownInstance;
     132        }
     133
     134        public List<PeerInfo> GetCurrentNetwork()
     135        {
     136            return peerListManager.GetPeerList();
     137        }
     138
     139        private string GetInternalIpAddress(string ipPrefix)
     140        {
     141            try
     142            {
     143                var strHostName = Dns.GetHostName();
     144                // Then using host name, get the IP address list..
     145                IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
     146                IPAddress[] addr = ipEntry.AddressList;
     147
     148                return addr
     149                  .Select(ip => ip.ToString())
     150                  .First(str => str.StartsWith(ipPrefix));
     151            }
     152            catch { return null; }
     153        }
     154
     155        private void OnPopulationRecieved(object sender, MessageRecieveEventArgs e)
     156        {
     157            if (e != null)
     158            {
     159                lock (activeQueueLocker)
     160                {
     161                    foreach (byte[] item in e.data)
     162                    {
     163                        writeQueue.Enqueue(item);
     164                    }
     165                }
     166            }
     167        }
     168
     169        private void AddError(string source, Exception ex)
     170        {
     171            if (peerListManager != null)
     172            {
     173                try
     174                {
     175                    peerListManager.SendLogToServer(string.Concat("Source: ", source, ", Exception: ", ex.Message));
     176                }
     177                catch { }
     178            }
     179        }
     180
    105181    }
    106 
    107     public PeerInfo GetPeerInfo() {
    108       return ownInstance;
    109     }
    110 
    111     public List<PeerInfo> GetCurrentNetwork() {
    112       return peerListManager.GetPeerList();
    113     }
    114 
    115     private string GetExternalIpAddress(string ipPrefix) {
    116       try {
    117         var strHostName = Dns.GetHostName();
    118         // Then using host name, get the IP address list..
    119         IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
    120         IPAddress[] addr = ipEntry.AddressList;
    121 
    122         return addr
    123           .Select(ip => ip.ToString())
    124           .First(str => str.StartsWith(ipPrefix));
    125       } catch { return null; }
    126     }
    127 
    128     private void OnPopulationRecieved(object sender, MessageRecieveEventArgs e) {
    129       if (e != null) {
    130         lock (activeQueueLocker) {
    131           foreach (SolutionInfo si in e.data) {
    132             writeQueue.Enqueue(si);
    133           }
    134         }
    135       }
    136     }
    137 
    138     private void AddError(string source, Exception ex) {
    139       if (peerListManager != null) {
    140         try {
    141           peerListManager.SendLogToServer(string.Concat("Source: ", source, ", Exception: ", ex.Message));
    142         } catch { }
    143       }
    144     }
    145 
    146   }
    147182}
  • branches/thasling/DistributedGA/DistributedGA.Core/Implementation/TestPeerListManager.cs

    r13556 r13887  
    33using DistributedGA.Core.Interface;
    44
    5 namespace DistributedGA.Core.Implementation {
    6   public class TestPeerListManager : IPeerListManager {
     5namespace DistributedGA.Core.Implementation
     6{
     7    public class TestPeerListManager : IPeerListManager
     8    {
    79
    810
    9     public List<PeerInfo> GetPeerList() {
    10       PeerInfo pi1 = new PeerInfo() { IpAddress = "localhost", Port = 3030 };
    11       PeerInfo pi2 = new PeerInfo() { IpAddress = "localhost", Port = 3031 };
    12       PeerInfo pi3 = new PeerInfo() { IpAddress = "localhost", Port = 3032 };
    13       PeerInfo pi4 = new PeerInfo() { IpAddress = "localhost", Port = 3033 };
    14       PeerInfo pi5 = new PeerInfo() { IpAddress = "localhost", Port = 3034 };
    15       return new List<PeerInfo>() { pi1, pi2, pi3, pi4, pi5 };
     11        public List<PeerInfo> GetPeerList()
     12        {
     13            PeerInfo pi1 = new PeerInfo() { IpAddress = "localhost", Port = 3030 };
     14            PeerInfo pi2 = new PeerInfo() { IpAddress = "localhost", Port = 3031 };
     15            PeerInfo pi3 = new PeerInfo() { IpAddress = "localhost", Port = 3032 };
     16            PeerInfo pi4 = new PeerInfo() { IpAddress = "localhost", Port = 3033 };
     17            PeerInfo pi5 = new PeerInfo() { IpAddress = "localhost", Port = 3034 };
     18            return new List<PeerInfo>() { pi1, pi2, pi3, pi4, pi5 };
     19        }
     20
     21        public void SendLogToServer(string msg)
     22        {
     23
     24        }
     25
     26        public void Init(PeerInfo source, string contactServerUrl)
     27        {
     28
     29        }
    1630    }
    17 
    18     public void SendLogToServer(string msg) {
    19 
    20     }
    21 
    22     public void Init(PeerInfo source, string contactServerUrl) {
    23 
    24     }
    25   }
    2631}
  • branches/thasling/DistributedGA/DistributedGA.Core/Implementation/WcfMessageSender.cs

    r13557 r13887  
    44using DistributedGA.Core.Interface;
    55
    6 namespace DistributedGA.Core.Implementation {
    7   public class WcfMessageSender : IMessageSender {
    8     private PeerInfo myself;
     6namespace DistributedGA.Core.Implementation
     7{
     8    public class WcfMessageSender : IMessageSender
     9    {
     10        private PeerInfo myself;
    911
    10     public void Init(PeerInfo source) {
    11       myself = source;
     12        public void Init(PeerInfo source)
     13        {
     14            myself = source;
     15        }
     16
     17        public void SendData(PeerInfo destination, byte[][] data)
     18        {
     19            var client = CreateServerClient(destination.IpAddress, destination.Port);
     20            client.SendData(myself, data); //maybe timout exception...
     21        }
     22
     23        private IMessageContract CreateServerClient(string ip, int port)
     24        {
     25            var serviceUrl = "DistributedGA.svc";
     26            var baseUri = new Uri(string.Concat("net.tcp://", ip, ":", port, "/DistributedGA"));
     27            var serviceUri = new Uri(baseUri, serviceUrl);
     28
     29            var binding = new NetTcpBinding();
     30            var endpoint = new EndpointAddress(serviceUri);
     31            var myChannelFactory = new ChannelFactory<IMessageContract>(binding, endpoint);
     32
     33            IMessageContract client = null;
     34            client = myChannelFactory.CreateChannel();
     35            return client;
     36        }
     37
    1238    }
    13 
    14     public void SendData(PeerInfo destination, SolutionInfo[] data) {
    15       var client = CreateServerClient(destination.IpAddress, destination.Port);
    16       client.SendData(myself, data); //maybe timout exception...
    17     }
    18 
    19     private IMessageContract CreateServerClient(string ip, int port) {
    20       var serviceUrl = "DistributedGA.svc";
    21       var baseUri = new Uri(string.Concat("net.tcp://", ip, ":", port, "/DistributedGA"));
    22       var serviceUri = new Uri(baseUri, serviceUrl);
    23 
    24       var binding = new NetTcpBinding();
    25       var endpoint = new EndpointAddress(serviceUri);
    26       var myChannelFactory = new ChannelFactory<IMessageContract>(binding, endpoint);
    27 
    28       IMessageContract client = null;
    29       client = myChannelFactory.CreateChannel();
    30       return client;
    31     }
    32 
    33   }
    3439}
  • branches/thasling/DistributedGA/DistributedGA.Core/Implementation/WcfMessageService.cs

    r13557 r13887  
    77using DistributedGA.Core.Interface;
    88
    9 namespace DistributedGA.Core.Implementation {
    10   public class WcfMessageService : IMessageService {
    11     public event EventHandler<MessageRecieveEventArgs> OnDataRecieved;
     9namespace DistributedGA.Core.Implementation
     10{
     11    public class WcfMessageService : IMessageService
     12    {
     13        public event EventHandler<MessageRecieveEventArgs> OnDataRecieved;
    1214
    13     private static ManualResetEvent _ResetEvent = new ManualResetEvent(false);
     15        private static ManualResetEvent _ResetEvent = new ManualResetEvent(false);
    1416
    15     private IMessageContract messageContract = null;
     17        private IMessageContract messageContract = null;
    1618
    17     public int Init(string ip) {
    18       int port = 0;
    19       port = FreeTcpPort();
     19        public int Init(string ip)
     20        {
     21            int port = 0;
     22            port = FreeTcpPort();
    2023
    21       messageContract = new MessageContractImpl();
    22       messageContract.MessageRecieved += new EventHandler<MessageRecieveEventArgs>(OnMessageRecieved);
     24            messageContract = new MessageContractImpl();
     25            messageContract.MessageRecieved += new EventHandler<MessageRecieveEventArgs>(OnMessageRecieved);
    2326
    24       var serviceUrl = "DistributedGA.svc";
    25       new Thread(() => {
    26         var baseUri = new Uri(string.Concat("net.tcp://", ip, ":", port, "/DistributedGA"));
    27         var serviceUri = new Uri(baseUri, serviceUrl);
    28         NetTcpBinding binding = new NetTcpBinding();
    29         //using (var host = new ServiceHost(typeof(MessageContractImpl), serviceUri))
     27            var serviceUrl = "DistributedGA.svc";
     28            new Thread(() =>
     29            {
     30                var baseUri = new Uri(string.Concat("net.tcp://", ip, ":", port, "/DistributedGA"));
     31                var serviceUri = new Uri(baseUri, serviceUrl);
     32                NetTcpBinding binding = new NetTcpBinding();
     33                //using (var host = new ServiceHost(typeof(MessageContractImpl), serviceUri))
    3034
    31         using (var host = new ServiceHost(messageContract, serviceUri)) {
    32           host.AddServiceEndpoint(typeof(IMessageContract), binding, serviceUri);
     35                using (var host = new ServiceHost(messageContract, serviceUri))
     36                {
     37                    host.AddServiceEndpoint(typeof(IMessageContract), binding, serviceUri);
    3338
    34           host.Open();
     39                    host.Open();
    3540
    36           _ResetEvent.WaitOne();
     41                    _ResetEvent.WaitOne();
     42                }
     43            }).Start();
     44            //close service again:
     45            //  _ResetEvent.Set();
     46            return port;
    3747        }
    38       }).Start();
    39       //close service again:
    40       //  _ResetEvent.Set();
    41       return port;
     48
     49        public void Dispose()
     50        {
     51            _ResetEvent.Set();
     52        }
     53
     54        private int FreeTcpPort()
     55        {
     56            TcpListener l = new TcpListener(IPAddress.Loopback, 0);
     57            l.Start();
     58            int port = ((IPEndPoint)l.LocalEndpoint).Port;
     59            l.Stop();
     60            return port;
     61        }
     62
     63        private void OnMessageRecieved(object sender, MessageRecieveEventArgs e)
     64        {
     65            if (OnDataRecieved != null)
     66            {
     67                OnDataRecieved(this, e);
     68            }
     69        }
    4270    }
    43 
    44     public void Dispose() {
    45       _ResetEvent.Set();
    46     }
    47 
    48     private int FreeTcpPort() {
    49       TcpListener l = new TcpListener(IPAddress.Loopback, 0);
    50       l.Start();
    51       int port = ((IPEndPoint)l.LocalEndpoint).Port;
    52       l.Stop();
    53       return port;
    54     }
    55 
    56     private void OnMessageRecieved(object sender, MessageRecieveEventArgs e) {
    57       if (OnDataRecieved != null) {
    58         OnDataRecieved(this, e);
    59       }
    60     }
    61   }
    6271}
  • branches/thasling/DistributedGA/DistributedGA.Core/Implementation/WcfPeerListManager.cs

    r13557 r13887  
    55using DistributedGA.Core.Domain;
    66using DistributedGA.Core.Interface;
     7using System.Timers;
    78
    8 namespace DistributedGA.Core.Implementation {
    9   public class WcfPeerListManager : IPeerListManager {
    10     private string serverString = null;
     9namespace DistributedGA.Core.Implementation
     10{
     11    public class WcfPeerListManager : IPeerListManager
     12    {
     13        private string serverString = null;
    1114
    12     private IContactService client = null;
     15        private IContactService client = null;
    1316
    14     private PeerInfo myself = null;
     17        private IContactService heartbeatClient = null;
    1518
    16     public void Init(PeerInfo source, string contactServerUrl) {
    17       serverString = contactServerUrl;
    18       client = CreateClient();
    19       myself = source;
    20       client.RegisterPeer(source);
     19        private PeerInfo myself = null;
     20
     21        private Timer timer = null; //sends heartbeat to contact-server
     22
     23        public void Init(PeerInfo source, string contactServerUrl)
     24        {
     25            serverString = contactServerUrl;
     26            client = CreateClient();
     27            heartbeatClient = CreateClient();
     28            myself = source;
     29            client.RegisterPeer(source);
     30            timer = new Timer(1000 * 60 * 5); //each 5 minutes
     31            timer.Elapsed += SendHeartbeatToServer;
     32            timer.Start();
     33        }
     34
     35
     36
     37        public List<PeerInfo> GetPeerList()
     38        {
     39            var allPeers = client.GetPeerList(myself);
     40            var peersForMessaging = ChoosePeersForMessaging(allPeers);
     41            //return peersForMessaging;
     42            return allPeers; //TODO: Enable 10% list communication
     43        }
     44
     45        public void SendLogToServer(string msg)
     46        {
     47            client.MakeLog(myself, msg);
     48        }
     49
     50        private IContactService CreateClient()
     51        {
     52            var binding = new NetTcpBinding();
     53            var endpoint = new EndpointAddress(serverString);
     54            var myChannelFactory = new ChannelFactory<IContactService>(binding, endpoint);
     55
     56            IContactService client = null;
     57            client = myChannelFactory.CreateChannel();
     58            return client;
     59        }
     60
     61        private List<PeerInfo> ChoosePeersForMessaging(List<PeerInfo> allPeers)
     62        {
     63            //communicate with 10% of the network
     64            int noOfPeers = allPeers.Count / 10;
     65            List<int> indexList = GetRandomItemIndexes(noOfPeers, 0, allPeers.Count - 1);
     66            List<PeerInfo> res = new List<PeerInfo>();
     67            foreach (int index in indexList)
     68            {
     69                res.Add(allPeers.ElementAt(index));
     70            }
     71            return res;
     72        }
     73
     74        private List<int> GetRandomItemIndexes(int noOfItems, int minValue, int maxValue)
     75        {
     76            List<int> res = new List<int>();
     77            Random rnd = new Random();
     78            int tmp = -1;
     79            while (res.Count < noOfItems)
     80            {
     81                tmp = rnd.Next(minValue, maxValue);
     82                if (!res.Contains(tmp))
     83                {
     84                    res.Add(tmp);
     85                }
     86            }
     87            return res;
     88        }
     89
     90        private void SendHeartbeatToServer(object sender, ElapsedEventArgs e)
     91        {
     92            try
     93            {
     94                heartbeatClient.UpdateHeartbeat(myself);
     95            }
     96            catch { } //nothing to do, exception is raised when getting peer list
     97        }
     98
    2199    }
    22 
    23     public List<PeerInfo> GetPeerList() {
    24       var allPeers = client.GetPeerList(myself);
    25       var peersForMessaging = ChoosePeersForMessaging(allPeers);
    26       //return peersForMessaging;
    27       return allPeers; //TODO: Enable 10% list communication
    28     }
    29 
    30     public void SendLogToServer(string msg) {
    31       client.MakeLog(myself, msg);
    32     }
    33 
    34     private IContactService CreateClient() {
    35       var binding = new NetTcpBinding();
    36       var endpoint = new EndpointAddress(serverString);
    37       var myChannelFactory = new ChannelFactory<IContactService>(binding, endpoint);
    38 
    39       IContactService client = null;
    40       client = myChannelFactory.CreateChannel();
    41       return client;
    42     }
    43 
    44     private List<PeerInfo> ChoosePeersForMessaging(List<PeerInfo> allPeers) {
    45       //communicate with 10% of the network
    46       int noOfPeers = allPeers.Count / 10;
    47       List<int> indexList = GetRandomItemIndexes(noOfPeers, 0, allPeers.Count - 1);
    48       List<PeerInfo> res = new List<PeerInfo>();
    49       foreach (int index in indexList) {
    50         res.Add(allPeers.ElementAt(index));
    51       }
    52       return allPeers;
    53     }
    54 
    55     private List<int> GetRandomItemIndexes(int noOfItems, int minValue, int maxValue) {
    56       List<int> res = new List<int>();
    57       Random rnd = new Random();
    58       int tmp = -1;
    59       while (res.Count < noOfItems) {
    60         tmp = rnd.Next(minValue, maxValue);
    61         if (!res.Contains(tmp)) {
    62           res.Add(tmp);
    63         }
    64       }
    65       return res;
    66     }
    67 
    68   }
    69100}
  • branches/thasling/DistributedGA/DistributedGA.Core/Interface/IContactService.cs

    r13524 r13887  
    1919
    2020        [OperationContract]
    21         void MakeLog(PeerInfo source, string msg); //used to log all peers at a single location
    22  
     21        void UpdateHeartbeat(PeerInfo source); //Sends heartbeat to contact-server
     22
     23        [OperationContract]
     24        void MakeLog(PeerInfo source, string msg); //Used to log all peers at a single location
     25
    2326    }
    2427}
  • branches/thasling/DistributedGA/DistributedGA.Core/Interface/IMessageContract.cs

    r13553 r13887  
    33using DistributedGA.Core.Domain;
    44
    5 namespace DistributedGA.Core.Interface {
    6   [ServiceContract]
    7   public interface IMessageContract {
    8     [OperationContract]
    9     void SendData(PeerInfo sender, SolutionInfo[] data);
     5namespace DistributedGA.Core.Interface
     6{
    107
    11     event EventHandler<MessageRecieveEventArgs> MessageRecieved;
    12   }
     8    [ServiceContract]
     9    public interface IMessageContract
     10    {
     11
     12        [OperationContract]
     13        void SendData(PeerInfo sender, byte[][] data);
     14
     15        event EventHandler<MessageRecieveEventArgs> MessageRecieved;
     16    }
    1317}
  • branches/thasling/DistributedGA/DistributedGA.Core/Interface/IMessageHandler.cs

    r13556 r13887  
    22using DistributedGA.Core.Domain;
    33
    4 namespace DistributedGA.Core.Interface {
    5   public interface IMessageHandler {
    6     void Init(string lanIpPrefix, string contactServerUrl); //Registers at contract-server
     4namespace DistributedGA.Core.Interface
     5{
    76
    8     void PublishDataToNetwork(SolutionInfo[] data);
     7    public interface IMessageHandler
     8    {
    99
    10     SolutionInfo[] GetDataFromNetwork();
     10        void Init(string lanIpPrefix, string contactServerUrl); //Registers at contract-server
    1111
    12     PeerInfo GetPeerInfo();
     12        void PublishDataToNetwork(byte[][] data);
    1313
    14     List<PeerInfo> GetCurrentNetwork();
     14        byte[][] GetDataFromNetwork();
    1515
    16     void Dispose();
    17   }
     16        PeerInfo GetPeerInfo();
     17
     18        List<PeerInfo> GetCurrentNetwork();
     19
     20        void Dispose();
     21    }
    1822}
  • branches/thasling/DistributedGA/DistributedGA.Core/Interface/IMessageSender.cs

    r13553 r13887  
    11using DistributedGA.Core.Domain;
    22
    3 namespace DistributedGA.Core.Interface {
    4   public interface IMessageSender {
    5     void Init(PeerInfo source);
     3namespace DistributedGA.Core.Interface
     4{
    65
    7     void SendData(PeerInfo destination, SolutionInfo[] data);
    8   }
     6    public interface IMessageSender
     7    {
     8
     9        void Init(PeerInfo source);
     10
     11        void SendData(PeerInfo destination, byte[][] data);
     12    }
    913}
  • branches/thasling/DistributedGA/DistributedGA.Core/Interface/IMessageService.cs

    r13553 r13887  
    22using DistributedGA.Core.Domain;
    33
    4 namespace DistributedGA.Core.Interface {
    5   public interface IMessageService {
    6     /// <summary>
    7     /// Initializes a WCF service and host it with another thread
    8     /// </summary>
    9     /// <param name="ip">current external ip address</param>
    10     /// <returns>The port, on which the service was successfully hosted</returns>
    11     int Init(string ip);
     4namespace DistributedGA.Core.Interface
     5{
    126
    13     void Dispose();
     7    public interface IMessageService
     8    {
    149
    15     event EventHandler<MessageRecieveEventArgs> OnDataRecieved;
    16   }
     10        /// <summary>
     11        /// Initializes a WCF service and host it with another thread
     12        /// </summary>
     13        /// <param name="ip">current external ip address</param>
     14        /// <returns>The port, on which the service was successfully hosted</returns>
     15        int Init(string ip);
     16
     17        void Dispose();
     18
     19        event EventHandler<MessageRecieveEventArgs> OnDataRecieved;
     20    }
    1721}
  • branches/thasling/DistributedGA/DistributedGA.Core/Interface/IPeerListManager.cs

    r13556 r13887  
    22using DistributedGA.Core.Domain;
    33
    4 namespace DistributedGA.Core.Interface {
    5   public interface IPeerListManager {
    6     void Init(PeerInfo source, string contactServerUrl); //Registers own instance at the contact-server
     4namespace DistributedGA.Core.Interface
     5{
    76
    8     List<PeerInfo> GetPeerList(); //Recieves all peers in the network from contact-server
     7    public interface IPeerListManager
     8    {
    99
    10     void SendLogToServer(string msg);
    11   }
     10        void Init(PeerInfo source, string contactServerUrl); //Registers own instance at the contact-server
     11
     12        List<PeerInfo> GetPeerList(); //Recieves all peers in the network from contact-server
     13
     14        void SendLogToServer(string msg);
     15    }
    1216}
  • branches/thasling/DistributedGA/DistributedGA.Hive

    • Property svn:ignore
      •  

        old new  
         1DistributedGA.Hive.csproj
        12bin
        23obj
  • branches/thasling/DistributedGA/DistributedGA.Hive/P2PTask.cs

    r13557 r13887  
    1414using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    1515
    16 namespace DistributedGA.Hive {
    17   [StorableClass]
    18   [Creatable(Category = "Haslinger's Very Special XO", Priority = 1000)]
    19   public class P2PTask : ParameterizedNamedItem, IOptimizer {
    20 
    21 
    22     [Storable]
    23     private DateTime startTime;
    24     [Storable]
    25     private RunCollection runCollection;
    26 
    27     #region Constructors and Cloning
    28     [StorableConstructor]
    29     protected P2PTask(bool deserializing) { }
    30     protected P2PTask(P2PTask original, Cloner cloner)
    31       : base(original, cloner) {
    32       startTime = original.startTime;
    33       runCollection = cloner.Clone(original.runCollection);
     16namespace DistributedGA.Hive
     17{
     18    [StorableClass]
     19    [Creatable(Category = "Haslinger's Very Special XO", Priority = 1000)]
     20    public class P2PTask : ParameterizedNamedItem, IOptimizer
     21    {
     22
     23        [Storable]
     24        private DateTime startTime;
     25        [Storable]
     26        private RunCollection runCollection;
     27
     28        #region Constructors and Cloning
     29        [StorableConstructor]
     30        protected P2PTask(bool deserializing) { }
     31        protected P2PTask(P2PTask original, Cloner cloner)
     32            : base(original, cloner)
     33        {
     34            startTime = original.startTime;
     35            runCollection = cloner.Clone(original.runCollection);
     36        }
     37        public P2PTask()
     38        {
     39            Name = "P2PTask";
     40            Description = "P2PTask";
     41            runCollection = new RunCollection();
     42
     43            Parameters.Add(new ValueParameter<StringValue>("LanIpPrefix", "", new StringValue("10.")));
     44            Parameters.Add(new ValueParameter<StringValue>("ContactServerURL", "", new StringValue("net.tcp://10.42.1.150:9090/DistributedGA.ContactServer/ContactService")));
     45            Parameters.Add(new ValueParameter<Log>("Log", "", new Log()));
     46
     47        }
     48
     49        [StorableHook(HookType.AfterDeserialization)]
     50        protected virtual void AfterDeserialization()
     51        {
     52        }
     53
     54        public override IDeepCloneable Clone(Cloner cloner)
     55        {
     56            return new P2PTask(this, cloner);
     57        }
     58        #endregion
     59
     60        #region ITask Members
     61        public ExecutionState ExecutionState { get; private set; }
     62
     63        public TimeSpan ExecutionTime { get; private set; }
     64
     65        public void Prepare()
     66        {
     67            Prepare(true);
     68        }
     69        public void Prepare(bool clearRuns)
     70        {
     71            // ignore
     72            ExecutionState = HeuristicLab.Core.ExecutionState.Prepared;
     73            OnExecutionStateChanged();
     74            OnPrepared();
     75        }
     76
     77        private CancellationTokenSource cts;
     78        private ManualResetEvent stoppedEvent;
     79
     80        public void Start()
     81        {
     82            Task.Factory.StartNew(() =>
     83            {
     84                cts = new CancellationTokenSource();
     85                stoppedEvent = new ManualResetEvent(false);
     86                startTime = DateTime.Now;
     87
     88                ExecutionState = HeuristicLab.Core.ExecutionState.Started;
     89                OnExecutionStateChanged();
     90                OnStarted();
     91
     92                var log = ((Log)(Parameters["Log"].ActualValue));
     93
     94                try
     95                {
     96
     97                    log.LogMessage("Starting peer...");
     98                    IMessageHandler h = new PeerNetworkMessageHandler();
     99                    var lanIpPrefix = ((StringValue)(Parameters["LanIpPrefix"].ActualValue)).Value;
     100                    var contactServerUri = ((StringValue)(Parameters["ContactServerURL"].ActualValue)).Value;
     101                    h.Init(lanIpPrefix, contactServerUri);
     102                    PeerInfo pi = h.GetPeerInfo();
     103                    log.LogMessage(string.Format("Peer is hostet at IP: {0} and port: {1}", pi.IpAddress, pi.Port));
     104                    Thread.Sleep(1000 * 20);
     105                    log.LogMessage("Current peers within network:");
     106                    foreach (var item in h.GetCurrentNetwork())
     107                    {
     108                        log.LogMessage(string.Format("Peer at {0}:{1}", item.IpAddress, item.Port));
     109                    }
     110                    int i = 0;
     111                    while (i < 10 && !cts.Token.IsCancellationRequested)
     112                    {
     113                        i++;
     114                        Thread.Sleep(1000 * 10);
     115                        var message = CreateMessage(pi, i);
     116                        Console.WriteLine("Publishing messages...");
     117                        h.PublishDataToNetwork(message);
     118                        Console.WriteLine("Messages published.");
     119                        Console.WriteLine("Recieved messages:");
     120                        foreach (var item in h.GetDataFromNetwork())
     121                        {
     122                            log.LogMessage(string.Format("Message:{0}", GetString(item)));
     123                        }
     124                        ExecutionTime = DateTime.Now - startTime;
     125                        OnExecutionTimeChanged();
     126                    }
     127                }
     128                catch (Exception ex)
     129                {
     130                    log.LogMessage(ex.Message);
     131                    log.LogMessage("press any key to continue...");
     132                }
     133
     134                var run = new Run();
     135                var results = new ResultCollection();
     136
     137                run.Results.Add("Execution Time", new TimeSpanValue(ExecutionTime));
     138                run.Results.Add("Log", log);
     139
     140                runCollection.Add(run);
     141
     142                stoppedEvent.Set();
     143                ExecutionState = HeuristicLab.Core.ExecutionState.Stopped;
     144
     145                OnExecutionStateChanged();
     146                OnStopped();
     147            });
     148        }
     149
     150
     151        public void Pause()
     152        {
     153            if (cts != null) cts.Cancel();
     154            stoppedEvent.WaitOne();
     155
     156            ExecutionState = HeuristicLab.Core.ExecutionState.Paused;
     157            OnExecutionStateChanged();
     158
     159            OnPaused();
     160        }
     161
     162        public void Stop()
     163        {
     164            if (cts != null) cts.Cancel();
     165            stoppedEvent.WaitOne();
     166
     167            ExecutionState = HeuristicLab.Core.ExecutionState.Stopped;
     168            OnExecutionStateChanged();
     169
     170            OnStopped();
     171        }
     172
     173        public event EventHandler Started;
     174        protected virtual void OnStarted()
     175        {
     176            EventHandler handler = Started;
     177            if (handler != null) handler(this, EventArgs.Empty);
     178        }
     179
     180        public event EventHandler Stopped;
     181        protected virtual void OnStopped()
     182        {
     183            EventHandler handler = Stopped;
     184            if (handler != null) handler(this, EventArgs.Empty);
     185        }
     186
     187        public event EventHandler Paused;
     188        protected virtual void OnPaused()
     189        {
     190            EventHandler handler = Paused;
     191            if (handler != null) handler(this, EventArgs.Empty);
     192        }
     193
     194        public event EventHandler Prepared;
     195        protected virtual void OnPrepared()
     196        {
     197            EventHandler handler = Prepared;
     198            if (handler != null) handler(this, EventArgs.Empty);
     199        }
     200
     201
     202        public event EventHandler ComputeInParallelChanged;
     203        protected virtual void OnComputeInParallelChanged()
     204        {
     205            EventHandler handler = ComputeInParallelChanged;
     206            if (handler != null) handler(this, EventArgs.Empty);
     207        }
     208        #endregion
     209
     210        #region Events
     211        public event EventHandler ExecutionTimeChanged;
     212        protected virtual void OnExecutionTimeChanged()
     213        {
     214            EventHandler handler = ExecutionTimeChanged;
     215            if (handler != null) handler(this, EventArgs.Empty);
     216        }
     217        public event EventHandler ExecutionStateChanged;
     218        protected virtual void OnExecutionStateChanged()
     219        {
     220            EventHandler handler = ExecutionStateChanged;
     221            if (handler != null) handler(this, EventArgs.Empty);
     222        }
     223        #endregion
     224
     225        public override string ToString()
     226        {
     227            return Name;
     228        }
     229
     230
     231
     232        private static byte[][] CreateMessage(PeerInfo pi, int iterationNumber)
     233        {
     234            string msg1 = string.Concat("Message 1 from Peer ", pi.IpAddress, ":", pi.Port, " at iteration ", iterationNumber);
     235            string msg2 = string.Concat("Message 2 from Peer ", pi.IpAddress, ":", pi.Port, " at iteration ", iterationNumber);
     236            return new byte[][] { GetBytes(msg1), GetBytes(msg2) };
     237        }
     238
     239        static byte[] GetBytes(string str)
     240        {
     241            byte[] bytes = new byte[str.Length * sizeof(char)];
     242            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
     243            return bytes;
     244        }
     245
     246        static string GetString(byte[] bytes)
     247        {
     248            char[] chars = new char[bytes.Length / sizeof(char)];
     249            System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
     250            return new string(chars);
     251        }
     252
     253        public System.Collections.Generic.IEnumerable<IOptimizer> NestedOptimizers
     254        {
     255            get { return Enumerable.Empty<IOptimizer>(); }
     256        }
     257
     258        public RunCollection Runs
     259        {
     260            get { return runCollection; }
     261        }
     262
     263        public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
     264
    34265    }
    35     public P2PTask() {
    36       Name = "P2PTask";
    37       Description = "P2PTask";
    38       runCollection = new RunCollection();
    39 
    40       Parameters.Add(new ValueParameter<StringValue>("LanIpPrefix", "", new StringValue("10.")));
    41       Parameters.Add(new ValueParameter<StringValue>("ContactServerURL", "", new StringValue("net.tcp://10.42.1.150:9090/DistributedGA.ContactServer/ContactService")));
    42       Parameters.Add(new ValueParameter<Log>("Log", "", new Log()));
    43 
    44     }
    45 
    46     [StorableHook(HookType.AfterDeserialization)]
    47     protected virtual void AfterDeserialization() {
    48     }
    49 
    50     public override IDeepCloneable Clone(Cloner cloner) {
    51       return new P2PTask(this, cloner);
    52     }
    53     #endregion
    54 
    55     #region ITask Members
    56     public ExecutionState ExecutionState { get; private set; }
    57 
    58     public TimeSpan ExecutionTime { get; private set; }
    59 
    60     public void Prepare() {
    61       Prepare(true);
    62     }
    63     public void Prepare(bool clearRuns) {
    64       // ignore
    65       ExecutionState = HeuristicLab.Core.ExecutionState.Prepared;
    66       OnExecutionStateChanged();
    67       OnPrepared();
    68     }
    69 
    70     private CancellationTokenSource cts;
    71     private ManualResetEvent stoppedEvent;
    72 
    73     public void Start() {
    74       Task.Factory.StartNew(() => {
    75         cts = new CancellationTokenSource();
    76         stoppedEvent = new ManualResetEvent(false);
    77         startTime = DateTime.Now;
    78 
    79         ExecutionState = HeuristicLab.Core.ExecutionState.Started;
    80         OnExecutionStateChanged();
    81         OnStarted();
    82 
    83         var log = ((Log)(Parameters["Log"].ActualValue));
    84 
    85 
    86         try {
    87 
    88           log.LogMessage("Starting peer...");
    89           IMessageHandler h = new PeerNetworkMessageHandler();
    90           var lanIpPrefix = ((StringValue)(Parameters["LanIpPrefix"].ActualValue)).Value;
    91           var contactServerUri = ((StringValue)(Parameters["ContactServerURL"].ActualValue)).Value;
    92           h.Init(lanIpPrefix, contactServerUri);
    93           PeerInfo pi = h.GetPeerInfo();
    94           log.LogMessage(string.Format("Peer is hostet at IP: {0} and port: {1}", pi.IpAddress, pi.Port));
    95           Thread.Sleep(1000 * 20);
    96           log.LogMessage("Current peers within network:");
    97           foreach (var item in h.GetCurrentNetwork()) {
    98             log.LogMessage(string.Format("Peer at {0}:{1}", item.IpAddress, item.Port));
    99           }
    100           int i = 1;
    101           while (i < 10 && !cts.Token.IsCancellationRequested) {
    102             i++;
    103             Thread.Sleep(1000 * 10);
    104             var pop1 = CreatePopulation();
    105             log.LogMessage("Publish population into network...");
    106             h.PublishDataToNetwork(pop1);
    107             log.LogMessage("Population published.");
    108             log.LogMessage("Recieved populations:");
    109             foreach (var item in h.GetDataFromNetwork()) {
    110               log.LogMessage(string.Format("Population with Quality: {0:2} in Iteration {1}", item.Quality, item.IterationNumber));
    111             }
    112             ExecutionTime = DateTime.Now - startTime;
    113             OnExecutionTimeChanged();
    114           }
    115         } catch (Exception ex) {
    116           log.LogMessage(ex.Message);
    117           log.LogMessage("press any key to continue...");
    118         }
    119 
    120         var run = new Run();
    121         var results = new ResultCollection();
    122 
    123         run.Results.Add("Execution Time", new TimeSpanValue(ExecutionTime));
    124         run.Results.Add("Log", log);
    125 
    126         runCollection.Add(run);
    127 
    128         stoppedEvent.Set();
    129         ExecutionState = HeuristicLab.Core.ExecutionState.Stopped;
    130 
    131         OnExecutionStateChanged();
    132         OnStopped();
    133       });
    134     }
    135 
    136 
    137     public void Pause() {
    138       if (cts != null) cts.Cancel();
    139       stoppedEvent.WaitOne();
    140 
    141       ExecutionState = HeuristicLab.Core.ExecutionState.Paused;
    142       OnExecutionStateChanged();
    143 
    144       OnPaused();
    145     }
    146 
    147     public void Stop() {
    148       if (cts != null) cts.Cancel();
    149       stoppedEvent.WaitOne();
    150 
    151       ExecutionState = HeuristicLab.Core.ExecutionState.Stopped;
    152       OnExecutionStateChanged();
    153 
    154       OnStopped();
    155     }
    156 
    157     public event EventHandler Started;
    158     protected virtual void OnStarted() {
    159       EventHandler handler = Started;
    160       if (handler != null) handler(this, EventArgs.Empty);
    161     }
    162 
    163     public event EventHandler Stopped;
    164     protected virtual void OnStopped() {
    165       EventHandler handler = Stopped;
    166       if (handler != null) handler(this, EventArgs.Empty);
    167     }
    168 
    169     public event EventHandler Paused;
    170     protected virtual void OnPaused() {
    171       EventHandler handler = Paused;
    172       if (handler != null) handler(this, EventArgs.Empty);
    173     }
    174 
    175     public event EventHandler Prepared;
    176     protected virtual void OnPrepared() {
    177       EventHandler handler = Prepared;
    178       if (handler != null) handler(this, EventArgs.Empty);
    179     }
    180 
    181 
    182     public event EventHandler ComputeInParallelChanged;
    183     protected virtual void OnComputeInParallelChanged() {
    184       EventHandler handler = ComputeInParallelChanged;
    185       if (handler != null) handler(this, EventArgs.Empty);
    186     }
    187     #endregion
    188 
    189     #region Events
    190     public event EventHandler ExecutionTimeChanged;
    191     protected virtual void OnExecutionTimeChanged() {
    192       EventHandler handler = ExecutionTimeChanged;
    193       if (handler != null) handler(this, EventArgs.Empty);
    194     }
    195     public event EventHandler ExecutionStateChanged;
    196     protected virtual void OnExecutionStateChanged() {
    197       EventHandler handler = ExecutionStateChanged;
    198       if (handler != null) handler(this, EventArgs.Empty);
    199     }
    200     #endregion
    201 
    202     public override string ToString() {
    203       return Name;
    204     }
    205 
    206 
    207 
    208     private static SolutionInfo[] CreatePopulation() {
    209       SolutionInfo si1 = new SolutionInfo() {
    210         IterationNumber = 1,
    211         Quality = 3.5f,
    212         Solution = new Solution() {
    213         }
    214       };
    215       SolutionInfo si2 = new SolutionInfo() {
    216         IterationNumber = 2,
    217         Quality = 3.5f,
    218         Solution = new Solution() {
    219         }
    220       };
    221       SolutionInfo si3 = new SolutionInfo() {
    222         IterationNumber = 3,
    223         Quality = 3.5f,
    224         Solution = new Solution() {
    225         }
    226       };
    227       return new SolutionInfo[] { si1, si2, si3 };
    228     }
    229 
    230     public System.Collections.Generic.IEnumerable<IOptimizer> NestedOptimizers {
    231       get { return Enumerable.Empty<IOptimizer>(); }
    232     }
    233 
    234     public RunCollection Runs {
    235       get { return runCollection; }
    236     }
    237 
    238     public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
    239 
    240   }
    241266}
  • branches/thasling/DistributedGA/DistributedGA.Operator/DistributedGA.Operator.csproj

    r13524 r13887  
    4040  </ItemGroup>
    4141  <ItemGroup>
    42     <Compile Include="Implementation\DefaultMigrationOperator.cs" />
    43     <Compile Include="Interface\IMigrationOperator.cs" />
    4442    <Compile Include="Properties\AssemblyInfo.cs" />
    4543  </ItemGroup>
    46   <ItemGroup />
     44  <ItemGroup>
     45    <Folder Include="Implementation\" />
     46    <Folder Include="Interface\" />
     47  </ItemGroup>
    4748  <ItemGroup>
    4849    <ProjectReference Include="..\DistributedGA.Core\DistributedGA.Core.csproj">
  • branches/thasling/DistributedGA/DistributedGA.Test/Form1.cs

    r13556 r13887  
    3535      IMessageHandler h5 = new PeerNetworkMessageHandler();
    3636      h5.Init("", "");
    37       var pop1 = CreatePopulation();
    38       h1.PublishDataToNetwork(pop1);
    39       h1.PublishDataToNetwork(pop1);
    40       var res1 = h1.GetDataFromNetwork();
    41       var res2 = h2.GetDataFromNetwork();
    42       h1.PublishDataToNetwork(pop1);
    43       h1.PublishDataToNetwork(pop1);
    44       var res3 = h1.GetDataFromNetwork();
    45       var res4 = h2.GetDataFromNetwork();
    46       h1.PublishDataToNetwork(pop1);
    47       h1.PublishDataToNetwork(pop1);
     37      //byte[] message = CreateTestMessage();
     38      //h1.PublishDataToNetwork(pop1);
     39      //h1.PublishDataToNetwork(pop1);
     40      //var res1 = h1.GetDataFromNetwork();
     41      //var res2 = h2.GetDataFromNetwork();
     42      //h1.PublishDataToNetwork(pop1);
     43      //h1.PublishDataToNetwork(pop1);
     44      //var res3 = h1.GetDataFromNetwork();
     45      //var res4 = h2.GetDataFromNetwork();
     46      //h1.PublishDataToNetwork(pop1);
     47      //h1.PublishDataToNetwork(pop1);
    4848      var res5 = h1.GetDataFromNetwork();
    4949      var res6 = h2.GetDataFromNetwork();
     
    8181    }
    8282
    83     private SolutionInfo[] CreatePopulation() {
    84       SolutionInfo si1 = new SolutionInfo() {
    85         IterationNumber = 1,
    86         Quality = 3.5f,
    87         Solution = new Solution() {
    88         }
    89       };
    90       SolutionInfo si2 = new SolutionInfo() {
    91         IterationNumber = 2,
    92         Quality = 3.5f,
    93         Solution = new Solution() {
    94         }
    95       };
    96       SolutionInfo si3 = new SolutionInfo() {
    97         IterationNumber = 3,
    98         Quality = 3.5f,
    99         Solution = new Solution() {
    100         }
    101       };
    102       return new SolutionInfo[] { si1, si2, si3 };
    103     }
    10483  }
    10584}
Note: See TracChangeset for help on using the changeset viewer.