Пример #1
0
        public void ConnectToClient(HubInfo hubInfo)
        {
            Req req = new Req(LocalHubInfo.Id, hubInfo.Id);

            SendMessageTCP(req);

            log.LogInformation("Sent Connection Request To: " + hubInfo.ToString());

            Thread connect = new Thread(new ThreadStart(delegate
            {
                IPEndPoint responsiveEndpoint = FindReachableEndpoint(hubInfo);

                if (responsiveEndpoint != null)
                {
                    log.LogInformation("Connection Successfull to: " + responsiveEndpoint.ToString());

                    hub.Publish(new ConnectionStartedEvent()
                    {
                        Data = hubInfo, Endpoint = responsiveEndpoint
                    });
                }
            }))
            {
                IsBackground = true
            };

            connect.Start();
        }
        public void Process(BaseMessage message, ProtocolType Protocol, IPEndPoint EP = null, TcpClient Client = null)
        {
            ReqMessage msg     = (ReqMessage)message;
            HubInfo    hubInfo = connections.GetConnection(msg.RecipientId);

            if (hubInfo != null)
            {
                hub.Publish(new ConnectionStartingEvent()
                {
                    Data = hubInfo
                });

                IPEndPoint ResponsiveEP = manager.FindReachableEndpoint(hubInfo);

                if (ResponsiveEP != null)
                {
                    hub.Publish(new ConnectionStartedEvent()
                    {
                        Data = hubInfo, Endpoint = ResponsiveEP
                    });
                    hub.Publish(new ConnectionUpdatedEvent()
                    {
                        Data = hubInfo
                    });
                }
            }
        }
 public void RemoveConnection(HubInfo connection)
 {
     lock (Connections)
     {
         Connections.Remove(connection);
     }
 }
        public void Process(BaseMessage message, ProtocolType Protocol, IPEndPoint EP = null, TcpClient Client = null)
        {
            var msg = (HubInfoMessage)message;

            // We need this lock as we're checking for null and during an initial handshake messages will come almost simultaneously.
            //lock (manager.Connections)
            lock (connections)
            {
                HubInfo hubInfo = connections.GetConnection(msg.Id);

                if (hubInfo == null)
                {
                    hubInfo = new HubInfo(msg);
                    connections.AddConnection(hubInfo);

                    hub.Publish(new ConnectionAddedEvent()
                    {
                        Data = hubInfo
                    });
                }
                else
                {
                    hubInfo.Update(msg);

                    hub.Publish(new ConnectionUpdatedEvent()
                    {
                        Data = hubInfo
                    });
                }
            }
        }
 public void AddConnection(HubInfo hubInfo)
 {
     lock (Connections)
     {
         Connections.Add(hubInfo);
     }
 }
Пример #6
0
        public virtual HubInfo GetInfo()
        {
            LogIdentity(System.Reflection.MethodInfo.GetCurrentMethod());

            var info = new HubInfo();

            return(info);
        }
Пример #7
0
        public void Process(BaseMessage message, ProtocolType Protocol, IPEndPoint EP = null, TcpClient Client = null)
        {
            ReqMessage req = (ReqMessage)message;

            HubInfo hubInfo = manager.Connections.GetConnection(req.RecipientId);

            if (hubInfo != null)
            {
                manager.SendTCP(new Req(req), hubInfo.Client);
            }
        }
        private static Response HandleHubProperty(IHubController _, string notification)
        {
            var deviceInfo = new HubInfo(notification);

            return(deviceInfo.DeviceType switch
            {
                HubInfoType.HubName => new HubName(notification),
                HubInfoType.ButtonState => new ButtonStateMessage(notification),
                HubInfoType.FirmwareVersion => new FirmwareVersion(notification),
                HubInfoType.SystemType => new SystemType(notification),
                _ => deviceInfo,
            });
Пример #9
0
        public void Disconnect(TcpClient client)
        {
            HubInfo hubInfo = Connections.GetConnection(client);

            if (hubInfo != null)
            {
                Connections.RemoveConnection(hubInfo);

                log.LogInformation($"Client disconnected {client.Client.RemoteEndPoint}");

                client.Close();

                BroadcastTCP(new Notification(NotificationsTypes.Disconnected, hubInfo.Id));
            }
        }
Пример #10
0
        private async Task GolemHubQueryTask(System.Threading.CancellationToken token)
        {
            //first try to connect to the hub
            HubInfo = await golemApi.GetHubInfoAsync();

            Logger.LogMessage($"Connected to Golem Hub\n{HubInfo.ToJson()}");

            while (!token.IsCancellationRequested)
            {
                try
                {
                    //get all peers
                    var peers = await golemApi.ListPeersAsync();

                    //synchronize peers with the knownPeers
                    foreach (var p in peers)
                    {
                        if (!knownPeers.Contains(p))
                        {
                            //add new workers to workerPool
                            workerPool.Enqueue(new GolemWorker(this, p, await golemApi.GetPeerHardwareAsync(p.NodeId)));
                        }
                    }
                    //TODO: do we need to do sth with workers that are not in the hub anymore? or will they die automatically?

                    knownPeers = peers;

                    await Task.Delay(10 * 1000, token);//do this once per 10 seconds
                }
                catch (TaskCanceledException)
                {
                }
                catch (Exception ex)
                {
                    //probably timed out request
                    Logger.LogMessage(ex.Message);
                }
            }
        }
Пример #11
0
        public void Process(BaseMessage message, ProtocolType Protocol, IPEndPoint EP = null, TcpClient Client = null)
        {
            AckMessage msg = (AckMessage)message;

            if (msg.Response)
            {
                manager.AckResponces.Add(new Ack(msg));
            }
            else
            {
                HubInfo CI = connections.GetConnection(msg.Id);

                if (CI.ExternalEndpoint.Address.Equals(EP.Address) & CI.ExternalEndpoint.Port != EP.Port)
                {
                    log.LogInformation("Received Ack on Different Port (" + EP.Port + "). Updating ...");

                    CI.ExternalEndpoint.Port = EP.Port;

                    hub.Publish(new ConnectionUpdatedEvent()
                    {
                        Data = CI
                    });
                }

                List <string> IPs = new List <string>();
                CI.InternalAddresses.ForEach(new Action <IPAddress>(delegate(IPAddress IP) { IPs.Add(IP.ToString()); }));

                if (!CI.ExternalEndpoint.Address.Equals(EP.Address) & !IPs.Contains(EP.Address.ToString()))
                {
                    log.LogInformation("Received Ack on New Address (" + EP.Address + "). Updating ...");

                    CI.InternalAddresses.Add(EP.Address);
                }

                msg.Response    = true;
                msg.RecipientId = manager.LocalHubInfo.Id;
                manager.SendMessageUDP(new Ack(msg), EP);
            }
        }
Пример #12
0
        public void ConnectToClient(string id)
        {
            HubInfo hub = Connections.GetConnection(id);

            ConnectToClient(hub);
        }
Пример #13
0
 /// <inheritdoc />
 /// <summary>
 ///     Initializes a new instance of the <see cref="T:Harmony.HubFoundEventArgs" /> class.
 /// </summary>
 /// <param name="hubInfo">The Hub that was found</param>
 public HubFoundEventArgs(HubInfo hubInfo) => this.HubInfo = hubInfo;
Пример #14
0
        public void UploadToHub(Report report, HubSettings settings, Connection socketConnection)
        {
            var reportName = report?.Name ?? null;

            if (String.IsNullOrEmpty(reportName))
            {
                throw new Exception("The report filename is empty.");
            }

            if (String.IsNullOrEmpty(settings.Owner))
            {
                throw new Exception("No owner for shared content found.");
            }

            //Delete reports from hub before uploaded!
            if (settings.Mode == DistributeMode.DELETEALLFIRST)
            {
                DeleteReportsFromHub(report, settings, socketConnection);
            }

            foreach (var reportPath in report.Paths)
            {
                try
                {
                    var fileData    = report.Data.FirstOrDefault(f => f.Filename == Path.GetFileName(reportPath));
                    var contentName = GetContentName(reportName, fileData);

                    // Copy with report name - Important for other delivery options.
                    var uploadCopyReportPath = Path.Combine(Path.GetDirectoryName(reportPath), $"{reportName}{Path.GetExtension(reportPath)}");
                    File.Copy(reportPath, uploadCopyReportPath, true);

                    if (settings.Mode == DistributeMode.OVERRIDE ||
                        settings.Mode == DistributeMode.CREATEONLY)
                    {
                        var uploadResult = new HubResult()
                        {
                            ReportName = reportName,
                        };

                        HubInfo hubInfo   = null;
                        Guid?   hubUserId = null;

                        var qrsApi = GetQrsApiConnection(socketConnection);
                        logger.Debug($"Use the following Qlik user '{settings.Owner}'...");
                        var hubUser = new DomainUser(settings.Owner, true);
                        var filter  = $"userId eq '{hubUser.UserId}' and userDirectory eq '{hubUser.UserDirectory}'";
                        logger.Debug($"Use Filter '{filter}'...");
                        var result = qrsApi.SendRequestAsync("user", HttpMethod.Get, null, filter).Result;
                        logger.Debug($"QRS Result for user: '******'");
                        if (result == null || result == "[]")
                        {
                            throw new Exception($"Qlik user {settings.Owner} was not found or session not connected (QRS).");
                        }
                        var userObject = JArray.Parse(result);
                        if (userObject.Count > 1)
                        {
                            throw new Exception($"Too many User found. {result}");
                        }
                        else if (userObject.Count == 1)
                        {
                            hubUserId = new Guid(userObject.First()["id"].ToString());
                        }
                        logger.Debug($"hubUser id is '{hubUserId}'.");

                        var sharedContent = GetSharedContentFromUser(contentName, hubUser, qrsApi);
                        if (sharedContent == null)
                        {
                            var createRequest = new HubCreateRequest()
                            {
                                Name        = contentName,
                                ReportType  = settings.SharedContentType,
                                Description = "Created by Analytics Gate",
                                Tags        = new List <Tag>()
                                {
                                    new Tag()
                                    {
                                        Name         = "SER",
                                        CreatedDate  = DateTime.Now,
                                        ModifiedDate = DateTime.Now
                                    }
                                },
                                Data = new ContentData()
                                {
                                    ContentType  = $"application/{Path.GetExtension(fileData.Filename).Trim('.')}",
                                    ExternalPath = Path.GetFileName(uploadCopyReportPath),
                                    FileData     = fileData.DownloadData,
                                }
                            };

                            logger.Debug($"Create request '{JsonConvert.SerializeObject(createRequest)}'");
                            hubInfo = qrsApi.CreateSharedContentAsync(createRequest).Result;
                            logger.Debug($"Create response '{JsonConvert.SerializeObject(hubInfo)}'");
                        }
                        else
                        {
                            if (settings.Mode == DistributeMode.OVERRIDE)
                            {
                                var tag = sharedContent?.Tags?.FirstOrDefault(t => t.Name == "SER") ?? null;
                                if (tag != null)
                                {
                                    tag.CreatedDate  = DateTime.Now;
                                    tag.ModifiedDate = DateTime.Now;
                                }
                                var updateRequest = new HubUpdateRequest()
                                {
                                    Info = sharedContent,
                                    Data = new ContentData()
                                    {
                                        ContentType  = $"application/{Path.GetExtension(fileData.Filename).Trim('.')}",
                                        ExternalPath = Path.GetFileName(uploadCopyReportPath),
                                        FileData     = fileData.DownloadData,
                                    }
                                };

                                logger.Debug($"Update request '{JsonConvert.SerializeObject(updateRequest)}'");
                                hubInfo = qrsApi.UpdateSharedContentAsync(updateRequest).Result;
                                logger.Debug($"Update response '{JsonConvert.SerializeObject(hubInfo)}'");
                            }
                            else
                            {
                                throw new Exception($"The shared content '{contentName}' already exist.");
                            }
                        }

                        if (hubUserId != null)
                        {
                            //change shared content owner
                            logger.Debug($"Change shared content owner '{hubUserId}' (User: '******').");
                            var newHubInfo = new HubInfo()
                            {
                                Id    = hubInfo.Id,
                                Type  = settings.SharedContentType,
                                Owner = new Owner()
                                {
                                    Id            = hubUserId.ToString(),
                                    UserId        = hubUser.UserId,
                                    UserDirectory = hubUser.UserDirectory,
                                    Name          = hubUser.UserId,
                                }
                            };

                            var changeRequest = new HubUpdateRequest()
                            {
                                Info = newHubInfo,
                            };
                            logger.Debug($"Update Owner request '{JsonConvert.SerializeObject(changeRequest)}'");
                            var ownerResult = qrsApi.UpdateSharedContentAsync(changeRequest).Result;
                            logger.Debug($"Update Owner response '{JsonConvert.SerializeObject(ownerResult)}'");
                        }

                        // Get fresh shared content infos
                        var filename = Path.GetFileName(uploadCopyReportPath);
                        filename = filename.Replace("+", " ");
                        hubInfo  = GetSharedContentFromUser(contentName, hubUser, qrsApi);
                        logger.Debug("Get shared content link.");
                        var link = hubInfo?.References?.FirstOrDefault(r => r.LogicalPath.Contains($"/{filename}"))?.ExternalPath ?? null;
                        if (link == null)
                        {
                            throw new Exception($"The download link is empty. Please check the security rules. (Name: {filename} - References: {hubInfo?.References?.Count}) - User: {hubUser}.");
                        }

                        Results.Add(new HubResult()
                        {
                            Success     = true,
                            ReportState = GetFormatedState(),
                            TaskName    = JobResult.TaskName,
                            Message     = "Upload to the hub was successful.",
                            Link        = link,
                            ReportName  = contentName,
                            FullLink    = GetFullLink(qrsApi.ConnectUri, link)
                        });
                    }
                    else
                    {
                        throw new Exception($"Unknown hub mode {settings.Mode}");
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "The delivery via 'Hub' failed.");
                    JobResult.Exception = ReportException.GetException(ex);
                    JobResult.Status    = TaskStatusInfo.ERROR;
                    Results.Add(new HubResult()
                    {
                        Success     = false,
                        ReportState = "ERROR",
                        TaskName    = JobResult.TaskName,
                        Message     = ex.Message
                    });
                }
                finally
                {
                    socketConnection.IsFree = true;
                }
            }
        }
Пример #15
0
    private static void AddCachePortAndPortModeInformation(DeviceType type, Version hardwareRevision, Version softwareRevision, HubInfo hub, PortInfo port, ProtocolKnowledge knowledge, IDeviceFactory deviceFactory)
    {
        var device = deviceFactory.Create(type);

        if (device is not null)
        {
            foreach (var message in device.GetStaticPortInfoMessages(hardwareRevision, softwareRevision, hub.SystemType).Select(b => MessageEncoder.Decode(b, null)))
            {
                var messageToProcess = message;
                switch (messageToProcess)
                {
                case PortModeInformationMessage pmim:
                    messageToProcess = pmim with
                    {
                        HubId  = port.HubId,
                        PortId = port.PortId,
                    };
                    break;

                case PortInformationMessage pim:
                    messageToProcess = pim with
                    {
                        HubId  = port.HubId,
                        PortId = port.PortId,
                    };
                    break;
                }

                ApplyStaticProtocolKnowledge(messageToProcess, knowledge);

                if (messageToProcess is PortModeInformationMessage pmim2 && pmim2.InformationType == PortModeInformationType.Name)
                {
                    device.ExtendPortMode(knowledge.PortMode(pmim2.HubId, pmim2.PortId, pmim2.Mode));
                }
            }
        }
    }
        public void Process(BaseMessage message, ProtocolType protocol, IPEndPoint endpoint = null, TcpClient client = null)
        {
            HubInfo hubInfo = connections.GetConnection(message.Id);

            if (hubInfo == null)
            {
                hubInfo = new HubInfo((HubInfoMessage)message);
                connections.AddConnection(hubInfo);

                if (endpoint != null)
                {
                    log.LogInformation("Client Added: UDP EP: {0}:{1}, Name: {2}", endpoint.Address, endpoint.Port, hubInfo.Name);
                }
                else if (client != null)
                {
                    log.LogInformation("Client Added: TCP EP: {0}:{1}, Name: {2}", ((IPEndPoint)client.Client.RemoteEndPoint).Address, ((IPEndPoint)client.Client.RemoteEndPoint).Port, hubInfo.Name);
                }
            }
            else
            {
                hubInfo.Update((HubInfoMessage)message);

                if (endpoint != null)
                {
                    log.LogInformation("Client Updated: UDP EP: {0}:{1}, Name: {2}", endpoint.Address, endpoint.Port, hubInfo.Name);
                }
                else if (client != null)
                {
                    log.LogInformation("Client Updated: TCP EP: {0}:{1}, Name: {2}", ((IPEndPoint)client.Client.RemoteEndPoint).Address, ((IPEndPoint)client.Client.RemoteEndPoint).Port, hubInfo.Name);
                }
            }

            if (endpoint != null)
            {
                hubInfo.ExternalEndpoint = endpoint;
            }

            if (client != null)
            {
                hubInfo.Client = client;
            }

            manager.BroadcastTCP(hubInfo);

            if (!hubInfo.Initialized)
            {
                if (hubInfo.ExternalEndpoint != null & protocol == ProtocolType.Udp)
                {
                    manager.SendUDP(new Message("Server", hubInfo.Name, "UDP Communication Test"), hubInfo.ExternalEndpoint);
                }

                if (hubInfo.Client != null & protocol == ProtocolType.Tcp)
                {
                    manager.SendTCP(new Message("Server", hubInfo.Name, "TCP Communication Test"), hubInfo.Client);
                }

                if (hubInfo.Client != null & hubInfo.ExternalEndpoint != null)
                {
                    foreach (HubInfo ci in connections.GetBroadcastConnections(false))
                    {
                        manager.SendUDP(ci, hubInfo.ExternalEndpoint);
                    }

                    hubInfo.Initialized = true;
                }
            }
        }
Пример #17
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            log.LogInformation($"Start Hub Service for {chainSettings.Symbol}.");

            Protection    protection = new Protection();
            Mnemonic      recoveryPhrase;
            DirectoryInfo dataFolder = new DirectoryInfo(hubSettings.DataFolder);

            if (!dataFolder.Exists)
            {
                dataFolder.Create();
            }

            string path = Path.Combine(dataFolder.FullName, "recoveryphrase.txt");

            if (!File.Exists(path))
            {
                recoveryPhrase = new Mnemonic(Wordlist.English, WordCount.Twelve);
                string cipher = protection.Protect(recoveryPhrase.ToString());
                File.WriteAllText(path, cipher);
            }
            else
            {
                string cipher = File.ReadAllText(path);
                recoveryPhrase = new Mnemonic(protection.Unprotect(cipher));
            }

            if (recoveryPhrase.ToString() != "border indicate crater public wealth luxury derive media barely survey rule hen")
            {
                //throw new ApplicationException("RECOVERY PHRASE IS DIFFERENT!");
            }

            // Read the identity from the secure storage and provide it here.
            //host.Setup(new Identity(recoveryPhrase.ToString()), stoppingToken);


            IPAddress[] IPAddresses = Dns.GetHostAddresses(hubSettings.Server);

            if (IPAddresses.Length == 0)
            {
                throw new ApplicationException("Did not find any IP address for the hub server.");
            }

            //ServerEndpoint = new IPEndPoint(IPAddress.Parse(hubSettings.Server), hubSettings.Port);
            // TODO: #4
            ServerEndpoint = new IPEndPoint(IPAddresses[0], hubSettings.Port);
            LocalHubInfo   = new HubInfo();
            AckResponces   = new List <Ack>();

            UDPClientGateway.AllowNatTraversal(true);
            UDPClientGateway.Client.SetIPProtectionLevel(IPProtectionLevel.Unrestricted);
            UDPClientGateway.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            LocalHubInfo.Name           = Environment.MachineName;
            LocalHubInfo.ConnectionType = ConnectionTypes.Unknown;
            LocalHubInfo.Id             = Guid.NewGuid().ToString();
            //LocalHubInfo.Id = DateTime.Now.Ticks;

            IEnumerable <IPAddress> IPs = Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork);

            foreach (IPAddress IP in IPs)
            {
                log.LogInformation("Internal Address: {IP}", IP);
                LocalHubInfo.InternalAddresses.Add(IP);
            }

            // To avoid circular reference we must resolve these in the startup.
            messageProcessing = serviceProvider.GetService <IHubMessageProcessing>();
            messageSerializer = serviceProvider.GetService <MessageSerializer>();

            // Prepare the messaging processors for message handling.
            MessageMaps maps = messageProcessing.Build();

            messageSerializer.Maps = maps;

            hub.Subscribe <ConnectionAddedEvent>(this, e =>
            {
                StringBuilder entry = new StringBuilder();

                entry.AppendLine($"ConnectionAddedEvent: {e.Data.Id}");
                entry.AppendLine($"                    : ExternalIPAddress: {e.Data.ExternalEndpoint}");
                entry.AppendLine($"                    : InternalIPAddress: {e.Data.InternalEndpoint}");
                entry.AppendLine($"                    : Name: {e.Data.Name}");

                foreach (System.Net.IPAddress address in e.Data.InternalAddresses)
                {
                    entry.AppendLine($"                    : Address: {address}");
                }

                log.LogInformation(entry.ToString());

                //var msg = new MessageModel
                //{
                //   Type = "ConnectionAddedEvent",
                //   Date = DateTime.UtcNow,
                //   Message = entry.ToString(),
                //   Data = e
                //};

                hubContext.Clients.All.SendAsync("Event", e);
            });

            hub.Subscribe <ConnectionRemovedEvent>(this, e =>
            {
                log.LogInformation($"ConnectionRemovedEvent: {e.Data.Id}");

                log.LogInformation($"ConnectionRemovedEvent: {e.Data.Id}");

                if (ConnectedHubs.ContainsKey(e.Data.Id))
                {
                    ConnectedHubs.Remove(e.Data.Id);
                }


                //var msg = new MessageModel
                //{
                //   Type = "ConnectionRemovedEvent",
                //   Date = DateTime.UtcNow,
                //   Message = e.Data.ToString(),
                //   Data = e.Data
                //};



                hubContext.Clients.All.SendAsync("Event", e);
            });

            hub.Subscribe <ConnectionStartedEvent>(this, e =>
            {
                log.LogInformation($"ConnectionStartedEvent: {e.Endpoint}");

                //var msg = new MessageModel
                //{
                //   Type = "ConnectionStartedEvent",
                //   Date = DateTime.UtcNow,
                //   Message = e.Endpoint.ToString(),
                //   Data = e.Endpoint.ToString()
                //};

                hubContext.Clients.All.SendAsync("Event", e);
            });

            hub.Subscribe <ConnectionStartingEvent>(this, e =>
            {
                log.LogInformation($"ConnectionStartingEvent: {e.Data.Id}");

                //var msg = new MessageModel
                //{
                //   Type = "ConnectionStartingEvent",
                //   Date = DateTime.UtcNow,
                //   Message = e.Data.Id.ToString(),
                //   Data = e.Data.Id.ToString()
                //};

                hubContext.Clients.All.SendAsync("Event", e);
            });

            hub.Subscribe <ConnectionUpdatedEvent>(this, e =>
            {
                log.LogInformation($"ConnectionUpdatedEvent: {e.Data.Id}");

                //var msg = new MessageModel
                //{
                //   Type = "ConnectionUpdatedEvent",
                //   Date = DateTime.UtcNow,
                //   Message = e.Data.Id.ToString(),
                //   Data = e.Data.Id
                //};

                hubContext.Clients.All.SendAsync("Event", e);

                // Automatically connect to discovered hubs.
                if (LocalHubInfo.Id != e.Data.Id)
                {
                    ConnectToClient(e.Data);
                }
            });

            hub.Subscribe <GatewayConnectedEvent>(this, e =>
            {
                log.LogInformation("Connected to Gateway");

                //var msg = new MessageModel
                //{
                //   Type = "GatewayConnectedEvent",
                //   Date = DateTime.UtcNow,
                //   Message = "",
                //   Data = ""
                //};

                hubContext.Clients.All.SendAsync("Event", e);
            });

            hub.Subscribe <GatewayShutdownEvent>(this, e =>
            {
                log.LogInformation("Disconnected from Gateway");

                //var msg = new MessageModel
                //{
                //   Type = "GatewayShutdownEvent",
                //   Date = DateTime.UtcNow,
                //   Message = "",
                //   Data = ""
                //};

                hubContext.Clients.All.SendAsync("Event", e);
            });

            hub.Subscribe <HubInfoEvent>(this, e =>
            {
                //var msg = new MessageModel
                //{
                //   Type = "HubInfoEvent",
                //   Date = DateTime.UtcNow,
                //   Message = e.Data.ToString(),
                //   Data = e.Data
                //};

                //if (e.Data.Id == Identity.Id)
                //{
                //   return;
                //}

                AvailableHubs.Add(e.Data.Id, new HubInfo(e.Data));

                hubContext.Clients.All.SendAsync("Event", e);
            });

            hub.Subscribe <MessageReceivedEvent>(this, e =>
            {
                log.LogInformation($"MessageReceivedEvent: {e.Data.Content}");

                //var msg = new MessageModel
                //{
                //   Type = "MessageReceivedEvent",
                //   Date = DateTime.UtcNow,
                //   Message = e.Data.Content,
                //   Data = e.Data.Content
                //};

                hubContext.Clients.All.SendAsync("Event", e);
            });

            hub.Subscribe <GatewayErrorEvent>(this, e =>
            {
                log.LogInformation($"GatewayErrorEvent: {e.Message}");

                //var msg = new MessageModel
                //{
                //   Type = "GatewayErrorEvent",
                //   Date = DateTime.UtcNow,
                //   Message = e.Message,
                //   Data = e.Message
                //};

                hubContext.Clients.All.SendAsync("Event", e);
            });

            Task.Run(async() =>
            {
                try
                {
                    bool connectedToGateway = false;

                    while (!cancellationToken.IsCancellationRequested)
                    {
                        //Task tcpTask = Task.Run(() =>
                        //{
                        //   TcpWorker(cancellationToken);
                        //}, cancellationToken);

                        //Task udTask = Task.Run(() =>
                        //{
                        //   UdpWorker(cancellationToken);
                        //}, cancellationToken);

                        //Task.WaitAll(new Task[] { tcpTask, udTask }, cancellationToken);

                        if (!connectedToGateway)
                        {
                            connectedToGateway = ConnectGateway();
                        }

                        // TODO: This loop will just continue to run after connected to gateway. It should check status and attempt to recycle and reconnect when needed.
                        Task.Delay(TimeSpan.FromSeconds(retryInterval), cancellationToken).Wait(cancellationToken);

                        //Task.Delay(TimeSpan.FromSeconds(retryInterval), cancellationToken).Wait(cancellationToken);

                        //var tokenSource = new CancellationTokenSource();
                        //cancellationToken.Register(() => { tokenSource.Cancel(); });

                        //try
                        //{
                        //   using (IServiceScope scope = scopeFactory.CreateScope())
                        //   {
                        //      Runner runner = scope.ServiceProvider.GetService<Runner>();
                        //      System.Collections.Generic.IEnumerable<Task> runningTasks = runner.RunAll(tokenSource);

                        //      Task.WaitAll(runningTasks.ToArray(), cancellationToken);

                        //      if (cancellationToken.IsCancellationRequested)
                        //      {
                        //         tokenSource.Cancel();
                        //      }
                        //   }

                        //   break;
                        //}
                        //catch (OperationCanceledException)
                        //{
                        //   // do nothing the task was cancel.
                        //   throw;
                        //}
                        //catch (AggregateException ae)
                        //{
                        //   if (ae.Flatten().InnerExceptions.OfType<SyncRestartException>().Any())
                        //   {
                        //      log.LogInformation("Sync: ### - Restart requested - ###");
                        //      log.LogTrace("Sync: Signalling token cancelation");
                        //      tokenSource.Cancel();

                        //      continue;
                        //   }

                        //   foreach (Exception innerException in ae.Flatten().InnerExceptions)
                        //   {
                        //      log.LogError(innerException, "Sync");
                        //   }

                        //   tokenSource.Cancel();

                        //   int retryInterval = 10;

                        //   log.LogWarning($"Unexpected error retry in {retryInterval} seconds");
                        //   //this.tracer.ReadLine();

                        //   // Blokcore Indexer is designed to be idempotent, we want to continue running even if errors are found.
                        //   // so if an unepxected error happened we log it wait and start again

                        //   Task.Delay(TimeSpan.FromSeconds(retryInterval), cancellationToken).Wait(cancellationToken);

                        //   continue;
                        //}
                        //catch (Exception ex)
                        //{
                        //   log.LogError(ex, "Sync");
                        //   break;
                        //}
                    }
                }
                catch (OperationCanceledException)
                {
                    // do nothing the task was cancel.
                    throw;
                }
                catch (Exception ex)
                {
                    log.LogError(ex, "Gateway");
                    throw;
                }
            }, cancellationToken);

            return(Task.CompletedTask);
        }
Пример #18
0
        public void DisconnectToClient(string id)
        {
            HubInfo hub = Connections.GetConnection(id);

            // TODO: Figure out where hub.Client went? We need it to disconnect.
        }
Пример #19
0
        public IPEndPoint FindReachableEndpoint(HubInfo hubInfo)
        {
            log.LogInformation("Attempting to Connect via LAN");

            for (int ip = 0; ip < hubInfo.InternalAddresses.Count; ip++)
            {
                if (!TCPClientGateway.Connected)
                {
                    break;
                }

                IPAddress  IP       = hubInfo.InternalAddresses[ip];
                IPEndPoint endpoint = new IPEndPoint(IP, hubInfo.InternalEndpoint.Port);

                for (int i = 1; i < 4; i++)
                {
                    if (!TCPClientGateway.Connected)
                    {
                        break;
                    }

                    log.LogInformation("Sending Ack to " + endpoint.ToString() + ". Attempt " + i + " of 3");

                    SendMessageUDP(new Ack(LocalHubInfo.Id), endpoint);

                    Thread.Sleep(200);

                    Ack response = AckResponces.FirstOrDefault(a => a.RecipientId == hubInfo.Id);

                    if (response != null)
                    {
                        log.LogInformation("Received Ack Responce from " + endpoint.ToString());

                        hubInfo.ConnectionType = ConnectionTypes.LAN;

                        AckResponces.Remove(response);

                        return(endpoint);
                    }
                }
            }

            if (hubInfo.ExternalEndpoint != null)
            {
                log.LogInformation("Attempting to Connect via Internet");

                for (int i = 1; i < 100; i++)
                {
                    if (!TCPClientGateway.Connected)
                    {
                        break;
                    }

                    log.LogInformation("Sending Ack to " + hubInfo.ExternalEndpoint + ". Attempt " + i + " of 99");

                    SendMessageUDP(new Ack(LocalHubInfo.Id), hubInfo.ExternalEndpoint);

                    Thread.Sleep(300);

                    Ack response = AckResponces.FirstOrDefault(a => a.RecipientId == hubInfo.Id);

                    if (response != null)
                    {
                        log.LogInformation("Received Ack New from " + hubInfo.ExternalEndpoint.ToString());

                        hubInfo.ConnectionType = ConnectionTypes.WAN;

                        AckResponces.Remove(response);

                        return(hubInfo.ExternalEndpoint);
                    }
                }

                log.LogInformation("Connection to " + hubInfo.Name + " failed");
            }
            else
            {
                log.LogInformation("Client's External EndPoint is Unknown");
            }

            return(null);
        }