예제 #1
0
 public BridgeService(IrcService ircLink, DiscordService discordLink, BridgeConfig config)
 {
     this.Config      = config;
     this.IrcLink     = ircLink;
     this.DiscordLink = discordLink;
     this.UserLinks   = new Dictionary <string, UserLink>();
 }
예제 #2
0
        public void GetEdgeHubConfig_BridgeValidatorReturnsError_ExpectedException()
        {
            var validator = new Mock <BrokerPropertiesValidator>();

            validator
            .Setup(v => v.ValidateAuthorizationConfig(It.IsAny <AuthorizationProperties>()))
            .Returns(new List <string>());
            validator
            .Setup(v => v.ValidateBridgeConfig(It.IsAny <BridgeConfig>()))
            .Returns(new List <string> {
                "Validation error has occurred"
            });

            var routeFactory = new EdgeRouteFactory(new Mock <IEndpointFactory>().Object);
            var configParser = new EdgeHubConfigParser(routeFactory, validator.Object);

            var bridgeConfig = new BridgeConfig
            {
                new Bridge("floor2", new List <Settings> {
                })
            };

            var brokerProperties = new BrokerProperties(bridgeConfig, new AuthorizationProperties());
            var properties       = new EdgeHubDesiredProperties_1_2(
                "1.2.0",
                new Dictionary <string, RouteSpec>(),
                new StoreAndForwardConfiguration(100),
                brokerProperties);

            // assert
            Assert.Throws <InvalidOperationException>(() => configParser.GetEdgeHubConfig(properties));
        }
예제 #3
0
        /// <summary>
        /// Asynchronously gets the whitelist with the bridge.
        /// </summary>
        /// <returns>An enumerable of <see cref="WhiteList"/>s registered with the bridge.</returns>
        public async Task <IEnumerable <WhiteList> > GetWhiteListAsync()
        {
            //Not needed to check if initialized, can be used without API key

            BridgeConfig config = await GetConfigAsync().ConfigureAwait(false);

            return(config.WhiteList.Select(l => l.Value).ToList());
        }
예제 #4
0
            protected override IAssemblyInfo ReadConfig()
            {
                BridgeConfig bridgeJson = new BridgeConfig()
                {
                    output = output_
                };
                string json = JsonConvert.SerializeObject(bridgeJson);

                return(JsonConvert.DeserializeObject <AssemblyInfo>(json));
            }
예제 #5
0
 public HueDriver(Microsoft.Extensions.Logging.ILogger logger)
 {
     Instance              = this;
     BridgeConfig          = new BridgeConfig();
     BridgeConfig.Gateway  = NetworkHelper.GetActiveIp();
     BridgeConfig.Netmask  = NetworkHelper.GetActiveIpNetmask();
     BridgeConfig.BridgeId = BridgeId.ToString();
     BridgeConfig.Mac      = NetworkHelper.GetActiveMacAddress();
     Logger = logger;
 }
예제 #6
0
        /// <summary>
        /// Create textual multiline information with most of a bridge's properties.
        /// </summary>
        /// <param name="bridge">The bridge for which to return information.</param>
        /// <param name="nrTabs">The initial number of tabs to use for indentation.</param>
        /// <returns></returns>
        public static string CreateBridgeInfo(Bridge bridge, int nrTabs)
        {
            string        tabs = new String(' ', nrTabs * tabSize);
            StringBuilder sb   = new StringBuilder();

            if (bridge != null)
            {
                sb.AppendLine(String.Format("{0}Bridge:", tabs));
                BridgeConfig config = bridge.Config;
                if (config != null)
                {
                    tabs = new String(' ', (nrTabs + 1) * tabSize);
                    sb.AppendLine(String.Format("{0}ID              : {1}", tabs, config.BridgeId));
                    sb.AppendLine(String.Format("{0}Name            : {1}", tabs, config.Name));
                    sb.AppendLine();
                    sb.AppendLine(String.Format("{0}IP address      : {1}", tabs, config.IpAddress));
                    sb.AppendLine(String.Format("{0}Gateway         : {1}", tabs, config.Gateway));
                    sb.AppendLine(String.Format("{0}DHCP            : {1}", tabs, config.Dhcp));
                    sb.AppendLine(String.Format("{0}NetMask         : {1}", tabs, config.NetMask));
                    sb.AppendLine(String.Format("{0}Portal connect  : {1}", tabs, config.PortalConnection));
                    sb.AppendLine(String.Format("{0}Zigbee channel  : {1}", tabs, config.ZigbeeChannel));
                    sb.AppendLine();
                    sb.AppendLine(String.Format("{0}Api version     : {1}", tabs, config.ApiVersion));
                    sb.AppendLine(String.Format("{0}SoftwareVersion : {1}", tabs, config.SoftwareVersion));
                    sb.AppendLine(String.Format("{0}DS version      : {1}", tabs, config.DataStoreVersion));
                    sb.AppendLine(String.Format("{0}Model           : {1}", tabs, config.ModelId));
                    sb.AppendLine(String.Format("{0}FactoryNew      : {1}", tabs, config.FactoryNew));
                    sb.AppendLine(String.Format("{0}Time zone       : {1}", tabs, config.TimeZone));
                    if (config.Utc.HasValue)
                    {
                        sb.AppendLine(String.Format("{0}Date/time UTC   : {1}", tabs, ((DateTime)(config.Utc.Value)).ToString("yyyy-MM-dd HH:mm:ss")));
                    }
                    sb.AppendLine();
                }
                if (bridge.WhiteList != null)
                {
                    sb.AppendLine(String.Format("{0}White list", tabs));
                    List <WhiteList> whiteLst = (List <WhiteList>)bridge.WhiteList;
                    foreach (WhiteList w in whiteLst)
                    {
                        sb.AppendLine(String.Format("{0}  ID              : {1}", tabs, w.Id));
                        sb.AppendLine(String.Format("{0}  Name            : {1}", tabs, w.Name));
                    }
                    sb.AppendLine();
                }
            }
            return(sb.ToString());
        }
예제 #7
0
        public async Task CreateNewClientLinkFailTest()
        {
            const string invalidID  = "NewAutomatedTestDeveloper";
            const string deviceType = "AutomatedTestDevice";

            Bridge bridge = await GetLoggedInBridge();

            var bridgeConfig = new BridgeConfig {
                LinkButton = false
            };

            Assert.IsInstanceOfType(await bridge.SetBridgeConfigurationAsync(bridgeConfig),
                                    typeof(HueObjectCollectionBase <Success>));
            Assert.IsFalse(((BridgeConfig)await bridge.GetBridgeConfigurationAsync()).LinkButton == true);
            Assert.IsInstanceOfType(await bridge.CreateNewClientAsync(deviceType, invalidID),
                                    typeof(HueObjectCollectionBase <Error>));
        }
예제 #8
0
 /// <summary>
 /// Create a new information object.
 /// </summary>
 /// <param name="infoObject">Either a <see cref="Q42.HueApi.Light"/> or a <see cref="Q42.HueApi.Models.Groups.Group"/></param>
 public HueObject(object infoObject)
 {
     if (infoObject.GetType() == typeof(Q42.HueApi.Bridge))
     {
         Bridge       bridge = (Q42.HueApi.Bridge)infoObject;
         BridgeConfig config = bridge.Config;
         if (config == null)
         {
             id   = "-1";
             name = "Bridge";
         }
         else
         {
             id   = config.BridgeId;
             name = config.Name;
         }
         isBridge = true;
         lightIDs = new List <string>();
         value    = infoObject;
     }
     else if (infoObject.GetType() == typeof(Q42.HueApi.Light))
     {
         Q42.HueApi.Light light = (Q42.HueApi.Light)infoObject;
         id       = light.Id;
         name     = light.Name;
         isLight  = true;
         lightIDs = new List <string> {
             id
         };
         value = infoObject;
     }
     else if (infoObject.GetType() == typeof(Q42.HueApi.Models.Groups.Group))
     {
         Q42.HueApi.Models.Groups.Group grp = (Q42.HueApi.Models.Groups.Group)infoObject;
         id       = grp.Id;
         name     = grp.Name;
         isGroup  = true;
         lightIDs = grp.Lights;
         value    = infoObject;
     }
     else
     {
         throw new ArgumentException("Argument should be either Bridge, Group or Light.", "infoObject");
     }
 }
예제 #9
0
        public void ValidateBridgeConfig_InvalidTopicOrPrefix()
        {
            var validator = new BrokerPropertiesValidator();

            var bridgeConfig = new BridgeConfig
            {
                new Bridge("$upstream", new List <Settings>
                {
                    new Settings(Direction.In, "topic/#/a", "local/#", "remote/+/")
                })
            };

            IList <string> errors = validator.ValidateBridgeConfig(bridgeConfig);

            Assert.Equal(3, errors.Count);
            Assert.Equal("Bridge 0: Topic is invalid: topic/#/a", errors[0]);
            Assert.Equal("Bridge 0: InPrefix must not contain wildcards (+, #)", errors[1]);
            Assert.Equal("Bridge 0: OutPrefix must not contain wildcards (+, #)", errors[2]);
        }
예제 #10
0
        public void ValidateBridgeConfig_EmptyElements()
        {
            var validator = new BrokerPropertiesValidator();

            var bridgeConfig = new BridgeConfig
            {
                new Bridge(string.Empty, new List <Settings>
                {
                    new Settings(Direction.In, string.Empty, string.Empty, string.Empty)
                }),
                new Bridge("floor2", new List <Settings> {
                })
            };

            IList <string> errors = validator.ValidateBridgeConfig(bridgeConfig);

            Assert.Equal(2, errors.Count);
            Assert.Equal("Bridge 0: Endpoint must not be empty", errors[0]);
            Assert.Equal("Bridge 1: Settings must not be empty", errors[1]);
        }
예제 #11
0
        async Task ConfigUpdateHandler(EdgeHubConfig config)
        {
            try
            {
                PolicyUpdate policyUpdate = ConfigToPolicyUpdate(config);
                BridgeConfig bridgeUpdate = ConfigToBridgeUpdate(config);

                Events.PublishPolicyUpdate(policyUpdate);

                var policyPayload = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(policyUpdate));
                await this.connector.SendAsync(PolicyUpdateTopic, policyPayload);

                var bridgePayload = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bridgeUpdate));
                await this.connector.SendAsync(BridgeUpdateTopic, bridgePayload);
            }
            catch (Exception ex)
            {
                Events.ErrorUpdatingPolicy(ex);
            }
        }
예제 #12
0
        public async Task InitializeBridge(bool initIrc = true, bool initDiscord = true)
        {
            config = ConfigHelper.LoadConfig();
            if (initIrc)
            {
                IrcLink = new IrcService(Logger, config.IRCServer);
            }
            if (initDiscord)
            {
                DiscordLink = new DiscordService(Logger, config.DiscordServer);
            }
            glue = new BridgeService(IrcLink, DiscordLink, config);

            if (initDiscord)
            {
                DiscordLink.OnChannelMessage += glue.DiscordChannelMessage;
                DiscordLink.OnGuildConnected += glue.DiscordGuildConnected;
                DiscordLink.OnUserUpdated    += glue.DiscordUserUpdated;
                DiscordLink.OnUserJoin       += glue.DiscordUserJoined;
                DiscordLink.OnUserLeave      += glue.DiscordUserLeave;
            }

            if (initIrc)
            {
                IrcLink.OnChannelMessage   += glue.IrcChannelMessage;
                IrcLink.OnPrivateMessage   += glue.IrcPrivateMessage;
                IrcLink.OnServerDisconnect += glue.IrcServerDisconnect;
                IrcLink.OnServerConnect    += glue.IrcServerConnect;
            }

            // Start the Async Processing
            if (initDiscord)
            {
                DiscordLink.MainAsync().GetAwaiter();
            }
            if (initIrc)
            {
                IrcLink.StartBridge(); // Sort of Async.. Fix this later
            }
        }
예제 #13
0
        /// <summary>
        /// Get bridge config
        /// </summary>
        /// <returns>BridgeConfig object</returns>
        public async Task <BridgeConfig> GetConfigAsync()
        {
            //Not needed to check if initialized, can be used without API key

            HttpClient client = await GetHttpClient().ConfigureAwait(false);

            string stringResult = await client.GetStringAsync(new Uri(String.Format("{0}config", ApiBase))).ConfigureAwait(false);

            JToken       token  = JToken.Parse(stringResult);
            BridgeConfig config = null;

            if (token.Type == JTokenType.Object)
            {
                var jsonResult = (JObject)token;
                config = JsonConvert.DeserializeObject <BridgeConfig>(jsonResult.ToString());

                //Fix whitelist IDs
                foreach (var whitelist in config.WhiteList)
                {
                    whitelist.Value.Id = whitelist.Key;
                }
            }
            return(config);
        }
예제 #14
0
        /// <summary>
        /// The main entry point for the tool.
        /// </summary>
        public void RemoveBridgeCache()
        {
            try
            {
                _bridgeService = new NCBridgeRPCService(BridgeServer);
                _bridgeServer  = _bridgeService.GetBridgeServer(TimeSpan.FromSeconds(30));

                NCacheRPCService nService = new NCacheRPCService(CacheServer);
                cacheServer = nService.GetCacheServer(new TimeSpan(0, 0, 0, 30));

                if (!ValidateParameters())
                {
                    return;
                }

                //**********************************
                config = cacheServer.GetCacheConfiguration(CacheName);
                if (config == null)
                {
                    OutputProvider.WriteErrorLine("Error : The cache'{0}' does not exist on server {1}:{2} .", CacheName, NCache.ServerName, NCache.Port);
                    return;
                }
                {
                    //OutputProvider.WriteErrorLine("Error : The Bidge {0} is running on {1} , please stop Bridge and try again .", BridgeId, NCache.ServerName);
                    //return;
                }
                if (config.CacheType.ToLower().Equals("local-cache"))
                {
                    OutputProvider.WriteLine("Local Cache cannot be added as a bridge cache");
                    return;
                }
                //cacheServer = GetCacheServers(config.Cluster.GetAllConfiguredNodes());

                if (_bridgeServer != null)
                {
                    try
                    {
                        OutputProvider.WriteLine("Removing Cache To Bridge '{0}' on {1}:{2}.", BridgeId, _bridgeService.ServerName, _bridgeService.Port);
                        Alachisoft.NCache.Bridging.Configuration.BridgeConfiguration bridgeConfig = _bridgeServer.GetBridgeConfiguration(BridgeId);

                        ToolsUtil.VerifyBridgeConfigurations(bridgeConfig, BridgeId);
                        if (bridgeConfig == null)
                        {
                            OutputProvider.WriteErrorLine("No Bridge with Bridge ID '{0} exists' on Server {1}:{2}.", BridgeId, _bridgeService.ServerName, _bridgeService.Port);
                            return;
                        }

                        TargetCacheCofiguration targtCacheConfig = new TargetCacheCofiguration();
                        targtCacheConfig.CacheID     = CacheName;
                        targtCacheConfig.Servers     = cacheServer.GetHostName();
                        targtCacheConfig.IsConnected = true;
                        {
                            if (!VerifyBridgeMasterCache(BridgeId, false, bridgeConfig))
                            {
                                targtCacheConfig.IsMaster = true;
                            }
                            targtCacheConfig.Status = BridgeCacheStateParam.Active.ToString();
                        }

                        List <TargetCacheCofiguration> previouslyAddedCaches = bridgeConfig.TargetCacheConfigList;
                        int removedCacheIndex = -1;
                        if (previouslyAddedCaches.Count >= 1)
                        {
                            int iteration = 0;
                            //checking validations regarding bridge
                            foreach (TargetCacheCofiguration pCache in previouslyAddedCaches)
                            {
                                //if exists than remove
                                if (pCache.CacheID.ToLower().Equals(CacheName.ToLower()))
                                {
                                    if (pCache.CacheAlias.ToLower().Equals(Alias.ToLower()) || string.IsNullOrEmpty(Alias))
                                    {
                                        removedCacheIndex = iteration;
                                        if (pCache.IsMaster)
                                        {
                                            OutputProvider.WriteErrorLine("Failed to Remove Cache to bridge '{0}'. Error: Master cache cannot be removed ", BridgeId);
                                            return;
                                        }
                                    }
                                }
                                if (pCache.Status.Equals("passive"))
                                {
                                    OutputProvider.WriteErrorLine("Failed to Remove Cache to bridge '{0}'. Error: No both bridge caches can be passive ", BridgeId);
                                    return;
                                }
                                iteration++;
                            }
                        }
                        else
                        {
                            OutputProvider.WriteErrorLine("Failed to Remove Cache There is currently no Cache Added in Bridge {0} ", BridgeId);
                            return;
                        }
                        //
                        if (removedCacheIndex >= 0)
                        {
                            bridgeConfig.TargetCacheConfigList.RemoveAt(removedCacheIndex);
                        }
                        else
                        {
                            OutputProvider.WriteErrorLine("Bridge Cache Does not exists with name{0} in Bridge '{1}'", CacheName, BridgeId);
                            return;
                        }
                        //Adding Bridge to config.ncconf

                        BridgeConfig bridgeConf = config.Bridge;

                        config.Bridge = null;

                        byte[] userId = null;
                        byte[] paswd  = null;
                        if (UserId != string.Empty && Password != string.Empty)
                        {
                            userId = EncryptionUtil.Encrypt(UserId);
                            paswd  = EncryptionUtil.Encrypt(Password);
                        }

                        //writing to config.ncconf
                        config.ConfigVersion++;
                        cacheServer.ConfigureBridgeToCache(config, userId, paswd, true);
                        cacheServer.HotApplyBridgeReplicator(CacheName, false);

                        ConveyToRegisteredNodes();


                        char[] separater = { ',' };
                        // write in all bridge nodes bridge.nconnf file
                        bool write = false;
                        foreach (string bridgeIp in bridgeConfig.BridgeNodes.Split(separater).ToList())
                        {
                            try{
                                _bridgeService = new NCBridgeRPCService(bridgeIp);
                                _bridgeServer  = _bridgeService.GetBridgeServer(TimeSpan.FromSeconds(30));


                                _bridgeServer.RegisterBridge(bridgeConfig, true, true);
                                write = true;
                                OutputProvider.WriteLine("Removed Bridge Cache {0} From Bridge {1}", CacheName, BridgeId);
                            }
                            catch (Exception e)
                            {
                                OutputProvider.WriteErrorLine("Removing Bridge Cache {0} From Bridge Server{1} Gives Error: {2}", bridgeConf, bridgeIp, e.Message);
                            }
                        }
                    }
                    catch (SecurityException e)
                    {
                        OutputProvider.WriteErrorLine("Failed to Remove Cache to bridge '{0}'. Error: {1} ", BridgeId, e.Message);
                    }
                    catch (Exception e)
                    {
                        OutputProvider.WriteErrorLine("Failed to Remove Cache to bridge '{0}'. Error: {1} ", BridgeId, e.Message);
                    }
                }
            }
            catch (Exception e)
            {
                OutputProvider.WriteErrorLine("Error: {0}", e.Message);
            }
            finally
            {
                if (_bridgeService != null)
                {
                    _bridgeService.Dispose();
                }
                if (NCache != null)
                {
                    NCache.Dispose();
                }
            }
        }
예제 #15
0
        public static EdgeHubDesiredProperties_1_2 GetTestData()
        {
            var statement1 = new AuthorizationProperties.Statement(
                identities: new List <string>
            {
                "device_1",
                "device_3"
            },
                allow: new List <AuthorizationProperties.Rule>
            {
                new AuthorizationProperties.Rule(
                    operations: new List <string>
                {
                    "mqtt:publish",
                    "mqtt:subscribe"
                },
                    resources: new List <string>
                {
                    "topic/a",
                    "topic/b"
                })
            },
                deny: new List <AuthorizationProperties.Rule>
            {
                new AuthorizationProperties.Rule(
                    operations: new List <string>
                {
                    "mqtt:publish"
                },
                    resources: new List <string>
                {
                    "system/alerts/+",
                    "core/#"
                })
            });

            var statement2 = new AuthorizationProperties.Statement(
                identities: new List <string>
            {
                "device_2"
            },
                allow: new List <AuthorizationProperties.Rule>
            {
                new AuthorizationProperties.Rule(
                    operations: new List <string>
                {
                    "mqtt:publish",
                    "mqtt:subscribe"
                },
                    resources: new List <string>
                {
                    "topic1",
                    "topic2"
                })
            },
                deny: new List <AuthorizationProperties.Rule>());

            var authzProperties = new AuthorizationProperties {
                statement1, statement2
            };
            var bridgeConfig = new BridgeConfig
            {
                new Bridge("$upstream", new List <Settings>
                {
                    new Settings(Direction.In, "topic/a", "local/", "remote/")
                }),
                new Bridge("floor2", new List <Settings>
                {
                    new Settings(Direction.Out, "/topic/b", "local", "remote")
                })
            };

            var brokerProperties = new BrokerProperties(bridgeConfig, authzProperties);
            var properties       = new EdgeHubDesiredProperties_1_2(
                "1.2.0",
                new Dictionary <string, RouteSpec>(),
                new StoreAndForwardConfiguration(100),
                brokerProperties);

            return(properties);
        }
 public SmartthingsController(Synchronizer mqtt, BridgeConfig config)
 {
     _mqtt       = mqtt;
     _authHeader = "Bearer " + config.StToBridgeAuthToken;
 }
예제 #17
0
 protected override IAssemblyInfo ReadConfig() {
     BridgeConfig bridgeJson = new BridgeConfig() { output = output_ };
     string json = JsonConvert.SerializeObject(bridgeJson);
     return JsonConvert.DeserializeObject<AssemblyInfo>(json);
 }
예제 #18
0
        /// <summary>
        /// The main entry point for the tool.
        /// </summary>
        public void SetBridgeCacheMode()
        {
            try
            {
                _bridgeService = new NCBridgeRPCService(BridgeServer);
                _bridgeServer  = _bridgeService.GetBridgeServer(TimeSpan.FromSeconds(30));

                NCacheRPCService nService = new NCacheRPCService(CacheServer);
                cacheServer = nService.GetCacheServer(new TimeSpan(0, 0, 0, 30));

                if (!ValidateParameters())
                {
                    return;
                }

                //**********************************
                config = cacheServer.GetCacheConfiguration(CacheName);

                if (config == null)
                {
                    OutputProvider.WriteErrorLine("Error : The cache'{0}' does not exist on server {1}:{2} .", CacheName, NCache.ServerName, NCache.Port);
                    return;
                }

                if (config.CacheType.ToLower().Equals("local-cache"))
                {
                    OutputProvider.WriteLine("Local Cache cannot be Set as a bridge cache");
                    return;
                }
                //cacheServer = GetCacheServers(config.Cluster.GetAllConfiguredNodes());
                bool isNotMaster  = false;
                int  passiveCount = 0;

                TargetCacheCofiguration targtCacheConfig = null;
                if (_bridgeServer != null)
                {
                    try
                    {
                        OutputProvider.WriteLine("Setting Cache Mode To Bridge '{0}' on {1}:{2}.", BridgeId, _bridgeService.ServerName, _bridgeService.Port);
                        Alachisoft.NCache.Bridging.Configuration.BridgeConfiguration bridgeConfig = _bridgeServer.GetBridgeConfiguration(BridgeId);

                        ToolsUtil.VerifyBridgeConfigurations(bridgeConfig, BridgeId);

                        List <TargetCacheCofiguration> previouslyAddedCaches = bridgeConfig.TargetCacheConfigList;
                        if (previouslyAddedCaches.Count >= 1)
                        {
                            //checking validations regarding bridge
                            foreach (TargetCacheCofiguration pCache in previouslyAddedCaches)
                            {
                                if (pCache.CacheID.ToLower().Equals(CacheName.ToLower()))
                                {
                                    isNotMaster      = !pCache.IsMaster;
                                    targtCacheConfig = pCache;
                                }
                                if (pCache.Status.Equals("passive"))
                                {
                                    passiveCount++;
                                }
                            }
                        }
                        else
                        {
                            OutputProvider.WriteErrorLine("No Cache Exists in Bridge {0}", BridgeId);
                        }

                        if (passiveCount >= 1 && State.Equals(BridgeCacheStateParam.Passive))
                        {
                            OutputProvider.WriteErrorLine("There is already a Passive cache in Bridge", BridgeId);
                            return;
                        }
                        if (!isNotMaster)
                        {
                            OutputProvider.WriteErrorLine("Bridge Cache '{0}' is a master Node,please change masterNode first", CacheName);
                            return;
                        }
                        if (targtCacheConfig.Status.Equals(State.ToString()))
                        {
                            OutputProvider.WriteErrorLine("Bridge Cache '{0}' is already {1}", CacheName, State.ToString());
                            return;
                        }

                        //

                        //Adding Bridge to config.ncconf
                        BridgeConfig bridgeConf = config.Bridge;
                        bridgeConf.Status = State.ToString();

                        config.Bridge = bridgeConf;
                        WriteToClientConf();

                        WriteToBridgeConf(bridgeConfig, targtCacheConfig);

                        OutputProvider.WriteLine("Cache '{0}' mode set to {1}", BridgeId, State.ToString());
                    }
                    catch (SecurityException e)
                    {
                        OutputProvider.WriteErrorLine("Failed to Add Cache to bridge '{0}'. Error: {1} ", BridgeId, e.Message);
                    }
                    catch (Exception e)
                    {
                        OutputProvider.WriteErrorLine("Failed to Add Cache to bridge '{0}'. Error: {1} ", BridgeId, e.Message);
                    }
                }
            }
            catch (Exception e)
            {
                OutputProvider.WriteErrorLine("Error: {0}", e.Message);
            }
            finally
            {
                if (_bridgeService != null)
                {
                    _bridgeService.Dispose();
                }
                if (NCache != null)
                {
                    NCache.Dispose();
                }
            }
        }
예제 #19
0
        public static IEnumerable <object[]> GetEdgeHubConfigData()
        {
            var r1 = new Route("id", string.Empty, "iotHub", Mock.Of <IMessageSource>(), new Mock <Endpoint>("endpoint1").Object, 0, 3600);
            var r2 = new Route("id", string.Empty, "iotHub", Mock.Of <IMessageSource>(), new Mock <Endpoint>("endpoint2").Object, 0, 3600);

            var routeConfig1 = new RouteConfig("r1", "FROM /* INTO $upstream", r1);
            var routeConfig2 = new RouteConfig("r2", "FROM /messages/* INTO $upstream", r2);

            var routes1 = new Dictionary <string, RouteConfig>
            {
                [routeConfig1.Name] = routeConfig1,
                [routeConfig2.Name] = routeConfig2
            };

            var routes2 = new Dictionary <string, RouteConfig>
            {
                [routeConfig1.Name] = routeConfig1
            };

            var routes3 = new Dictionary <string, RouteConfig>
            {
                [routeConfig2.Name] = routeConfig2
            };

            var storeAndForwardConfig1 = new StoreAndForwardConfiguration(-1);
            var storeAndForwardConfig2 = new StoreAndForwardConfiguration(7200);
            var storeAndForwardConfig3 = new StoreAndForwardConfiguration(3600);

            StoreLimits s1 = new StoreLimits(100L);
            StoreLimits s2 = new StoreLimits(200L);
            var         storeAndForwardConfig4 = new StoreAndForwardConfiguration(3600, s1);
            var         storeAndForwardConfig5 = new StoreAndForwardConfiguration(3600, s2);
            var         storeAndForwardConfig6 = new StoreAndForwardConfiguration(3600);

            var bridge1 = new BridgeConfig
            {
                new Bridge("endpoint1", new List <Settings>
                {
                    new Settings(Direction.In, "topic/a", "local/", "remote/")
                })
            };

            var bridge2 = new BridgeConfig
            {
                new Bridge("endpoint1", new List <Settings>
                {
                    new Settings(Direction.Out, "/topic/b", "local", "remote")
                })
            };

            var bridge3 = new BridgeConfig
            {
                new Bridge("endpoint1", new List <Settings>
                {
                    new Settings(Direction.In, "topic/a", "local/", "remote/")
                })
            };

            var statement1 = new Statement(
                effect: Effect.Allow,
                identities: new List <string>
            {
                "device_1"
            },
                operations: new List <string>
            {
                "read",
                "write"
            },
                resources: new List <string>
            {
                "file1",
                "file2"
            });

            var statement2 = new Statement(
                effect: Effect.Deny,
                identities: new List <string>
            {
                "device_1"
            },
                operations: new List <string>
            {
                "read"
            },
                resources: new List <string>
            {
                "root1",
                "root2"
            });

            var statement3 = new Statement(
                effect: Effect.Allow,
                identities: new List <string>
            {
                "device_1"
            },
                operations: new List <string>
            {
                "read",
                "write"
            },
                resources: new List <string>
            {
                "file1",
                "file2"
            });

            var brokerConfig1 = new BrokerConfig(
                Option.Some(bridge1),
                Option.Some(new AuthorizationConfig(new List <Statement> {
                statement1
            })));
            var brokerConfig2 = new BrokerConfig(
                Option.Some(bridge2),
                Option.Some(new AuthorizationConfig(new List <Statement> {
                statement2
            })));
            var brokerConfig3 = new BrokerConfig(
                Option.Some(bridge3),
                Option.Some(new AuthorizationConfig(new List <Statement> {
                statement3
            })));

            string version = "1.0";

            var edgeHubConfig1  = new EdgeHubConfig(version, routes1, storeAndForwardConfig1, Option.Some(brokerConfig1));
            var edgeHubConfig2  = new EdgeHubConfig(version, routes2, storeAndForwardConfig1, Option.Some(brokerConfig1));
            var edgeHubConfig3  = new EdgeHubConfig(version, routes3, storeAndForwardConfig1, Option.Some(brokerConfig1));
            var edgeHubConfig4  = new EdgeHubConfig(version, routes1, storeAndForwardConfig1, Option.Some(brokerConfig1));
            var edgeHubConfig5  = new EdgeHubConfig(version, routes1, storeAndForwardConfig2, Option.Some(brokerConfig1));
            var edgeHubConfig6  = new EdgeHubConfig(version, routes1, storeAndForwardConfig3, Option.Some(brokerConfig1));
            var edgeHubConfig7  = new EdgeHubConfig(version, routes2, storeAndForwardConfig2, Option.Some(brokerConfig1));
            var edgeHubConfig8  = new EdgeHubConfig(version, routes2, storeAndForwardConfig3, Option.Some(brokerConfig1));
            var edgeHubConfig9  = new EdgeHubConfig(version, routes3, storeAndForwardConfig3, Option.Some(brokerConfig1));
            var edgeHubConfig10 = new EdgeHubConfig(version, routes3, storeAndForwardConfig3, Option.Some(brokerConfig1));
            var edgeHubConfig11 = new EdgeHubConfig(version, routes3, storeAndForwardConfig4, Option.Some(brokerConfig1));
            var edgeHubConfig12 = new EdgeHubConfig(version, routes3, storeAndForwardConfig5, Option.Some(brokerConfig1));
            var edgeHubConfig13 = new EdgeHubConfig(version, routes3, storeAndForwardConfig6, Option.Some(brokerConfig1));

            yield return(new object[] { edgeHubConfig1, edgeHubConfig2, false });

            yield return(new object[] { edgeHubConfig2, edgeHubConfig3, false });

            yield return(new object[] { edgeHubConfig3, edgeHubConfig4, false });

            yield return(new object[] { edgeHubConfig4, edgeHubConfig5, false });

            yield return(new object[] { edgeHubConfig5, edgeHubConfig6, false });

            yield return(new object[] { edgeHubConfig6, edgeHubConfig7, false });

            yield return(new object[] { edgeHubConfig7, edgeHubConfig8, false });

            yield return(new object[] { edgeHubConfig8, edgeHubConfig9, false });

            yield return(new object[] { edgeHubConfig9, edgeHubConfig10, true });

            yield return(new object[] { edgeHubConfig10, edgeHubConfig11, false });

            yield return(new object[] { edgeHubConfig11, edgeHubConfig12, false });

            yield return(new object[] { edgeHubConfig10, edgeHubConfig13, true });

            yield return(new object[] { edgeHubConfig12, edgeHubConfig13, false });

            // authorization config equality check
            var edgeHubConfig14 = new EdgeHubConfig(version, routes1, storeAndForwardConfig1, Option.Some(brokerConfig2));
            var edgeHubConfig15 = new EdgeHubConfig(version, routes1, storeAndForwardConfig1, Option.Some(brokerConfig3));

            yield return(new object[] { edgeHubConfig1, edgeHubConfig14, false });

            yield return(new object[] { edgeHubConfig1, edgeHubConfig15, true });
        }
예제 #20
0
 public ILightsManager Construct(BridgeConfig config)
 {
     return(new LightsManager(config));
 }
예제 #21
0
        /// <summary>
        /// The main entry point for the tool.
        /// </summary>
        public void AddBridgeCache()
        {
            try
            {
                if (!ValidateParameters())
                {
                    return;
                }

                _bridgeService = new NCBridgeRPCService(BridgeServer);

                if (Port == -1)
                {
                    _bridgeService.Port = _bridgeService.UseTcp ? BridgeConfigurationManager.NCacheTcpPort : BridgeConfigurationManager.NCacheHttpPort;
                }
                else
                {
                    _bridgeService.Port = Port;
                }

                if (!string.IsNullOrEmpty(BridgeServer))
                {
                    _bridgeService.ServerName = BridgeServer;
                }

                _bridgeServer = _bridgeService.GetBridgeServer(TimeSpan.FromSeconds(30));

                NCacheRPCService nService = new NCacheRPCService(CacheServer);

                cacheServer = nService.GetCacheServer(new TimeSpan(0, 0, 0, 30));



                //**********************************
                config = cacheServer.GetCacheConfiguration(CacheName);

                if (config == null)
                {
                    OutputProvider.WriteErrorLine("Error : The cache'{0}' does not exist on server {1}:{2} .", CacheName, NCache.ServerName, NCache.Port);
                    return;
                }

                if (config.CacheType.ToLower().Equals("local-cache"))
                {
                    OutputProvider.WriteLine("Local Cache cannot be added as a bridge cache");
                    return;
                }
                //cacheServer = GetCacheServers(config.Cluster.GetAllConfiguredNodes());

                if (_bridgeServer != null)
                {
                    try
                    {
                        OutputProvider.WriteLine("Adding Cache To Bridge '{0}' on {1}:{2}.", BridgeId, _bridgeService.ServerName, _bridgeService.Port);
                        Alachisoft.NCache.Bridging.Configuration.BridgeConfiguration bridgeConfig = _bridgeServer.GetBridgeConfiguration(BridgeId);

                        if (bridgeConfig == null)
                        {
                            OutputProvider.WriteErrorLine("No Bridge with Bridge ID '{0} exists' on Server {1}:{2}.", BridgeId, _bridgeService.ServerName, _bridgeService.Port);
                            return;
                        }
                        TargetCacheCofiguration targtCacheConfig = new TargetCacheCofiguration();
                        targtCacheConfig.CacheID    = CacheName;
                        targtCacheConfig.CacheAlias = Alias; // set the Alias, null if name is different.
                        Alachisoft.NCache.Config.NewDom.CacheServerConfig serverConfig = cacheServer.GetNewConfiguration(CacheName);
                        string servers = String.Empty;
                        foreach (Address node in serverConfig.CacheDeployment.Servers.GetAllConfiguredNodes())
                        {
                            servers += node.IpAddress + ",";
                        }

                        servers = servers.Remove(servers.Length - 1);
                        targtCacheConfig.Servers = servers;

                        targtCacheConfig.IsConnected = true;
                        if (State.Equals(BridgeCacheStateParam.Active))
                        {
                            if (!VerifyBridgeMasterCache(BridgeId, false, bridgeConfig))
                            {
                                targtCacheConfig.IsMaster = true;
                            }
                            targtCacheConfig.Status = BridgeCacheStateParam.Active.ToString();
                        }
                        else
                        {
                            targtCacheConfig.Status = BridgeCacheStateParam.Passive.ToString();
                        }

                        ToolsUtil.VerifyBridgeConfigurations(bridgeConfig, BridgeId);
                        List <TargetCacheCofiguration> previouslyAddedCaches = bridgeConfig.TargetCacheConfigList;

                        if (previouslyAddedCaches.Count <= 1)
                        {
                            //checking validations regarding bridge
                            foreach (TargetCacheCofiguration pCache in previouslyAddedCaches)
                            {
                                if (pCache.CacheID.ToLower().Equals(targtCacheConfig.CacheID.ToLower()))
                                {
                                    OutputProvider.WriteErrorLine("Failed to Add Cache to bridge '{0}'. Error:No Same Cache Can be Added Twice ", BridgeId);
                                    return;
                                }

                                if (pCache.Status.Equals("passive"))
                                {
                                    OutputProvider.WriteErrorLine("Failed to Add Cache to bridge '{0}'. Error:No both bridge caches can be passive ", BridgeId);
                                    return;
                                }
                            }
                        }
                        else
                        {
                            OutputProvider.WriteErrorLine("Failed to Add Cache to bridge '{0}'. Error:No More than 2 caches can be add at a time ", BridgeId);
                            return;
                        }
                        //

                        //Adding Bridge to config.ncconf
                        BridgeConfig bridgeConf = new BridgeConfig();
                        bridgeConf.CacheAlias = Alias;
                        bridgeConf.Id         = BridgeId;
                        if (config != null)
                        {
                            bridgeConf.Servers = bridgeConfig.BridgeNodes;
                            bridgeConf.Port    = bridgeConfig.BridgePort;
                            bridgeConf.Status  = State.ToString();
                        }

                        config.Bridge = bridgeConf;


                        byte[] userId = null;
                        byte[] paswd  = null;
                        if (UserId != string.Empty && Password != string.Empty)
                        {
                            userId = EncryptionUtil.Encrypt(UserId);
                            paswd  = EncryptionUtil.Encrypt(Password);
                        }

                        //writing to config.ncconf
                        config.ConfigVersion++;

                        cacheServer.ConfigureBridgeToCache(config, userId, paswd, true);
                        cacheServer.HotApplyBridgeReplicator(CacheName, false);


                        Alachisoft.NCache.Config.NewDom.CacheServerConfig nConfig = cacheServer.GetNewConfiguration(CacheName);

                        foreach (Address node in nConfig.CacheDeployment.Servers.GetAllConfiguredNodes())
                        {
                            NCache.ServerName = node.IpAddress.ToString();
                            ICacheServer server = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                            server.ConfigureBridgeToCache(config, userId, paswd, true);
                            server.HotApplyBridgeReplicator(CacheName, false);
                        }

                        ConveyToRegisteredNodes();



                        char [] separater = { ',' };
                        bridgeConfig.TargetCacheConfigList.Add(targtCacheConfig);
                        // write in all bridge nodes bridge.nconnf file
                        bridgeConfig.DeploymentVersion++;
                        foreach (string bridgeIp in bridgeConfig.BridgeNodes.Split(separater).ToList())
                        {
                            _bridgeService = new NCBridgeRPCService(bridgeIp);
                            _bridgeServer  = _bridgeService.GetBridgeServer(TimeSpan.FromSeconds(30));


                            _bridgeServer.RegisterBridge(bridgeConfig, true, true);
                        }

                        OutputProvider.WriteLine("{0} successfully added to BridgeID {1}", CacheName, BridgeId);
                    }
                    catch (SecurityException e)
                    {
                        OutputProvider.WriteErrorLine("Failed to Add Cache to bridge '{0}'. Error: {1} ", BridgeId, e.Message);
                    }
                    catch (Exception e)
                    {
                        OutputProvider.WriteErrorLine("Failed to Add Cache to bridge '{0}'. Error: {1} ", BridgeId, e.Message);
                    }
                }
            }
            catch (Exception e)
            {
                OutputProvider.WriteErrorLine("Error: {0}", e.Message);
            }
            finally
            {
                if (_bridgeService != null)
                {
                    _bridgeService.Dispose();
                }
                if (NCache != null)
                {
                    NCache.Dispose();
                }
            }
        }
예제 #22
0
        private void ServiceBridge()
        {
            if (useNominalSyncHoldoffTimer)
            {
                nominalSyncHoldoffTimer.Reset();
            }

            // service IVI table additions:
            if (lastIVINamesArrayLength != IVI.ValueNamesArrayLength)
            {
                string[] iviValueNamesArray = IVI.ValueNamesArray ?? emptyStringArray;
                lastIVINamesArrayLength = iviValueNamesArray.Length;

                // check for new IVI additions
                foreach (string ivaNativeName in iviValueNamesArray)
                {
                    if (ivaNameToSyncItemDictionary.ContainsKey(ivaNativeName) || lookAtLaterDictionary.ContainsKey(ivaNativeName))
                    {
                        continue;
                    }

                    bool propagateIVAName = BridgeConfig.IVAPropagateNameMatchRuleSet.MatchesAny(ivaNativeName);

                    string mappedFromIVAName = ivaNativeName;

                    propagateIVAName &= (BridgeConfig.IVAMapNameFromTo == null || BridgeConfig.IVAMapNameFromTo.Map(ivaNativeName, ref mappedFromIVAName));

                    string mappedToCKAKeyName = mappedFromIVAName;
                    propagateIVAName &= (BridgeConfig.CKAMapNameFromTo == null || BridgeConfig.CKAMapNameFromTo.MapInverse(mappedFromIVAName, ref mappedToCKAKeyName));

                    // check if we should add a sync item for this key or if we should indicate that we have seen it and that it will not be synced
                    if (propagateIVAName)
                    {
                        var attemptToAddSyncItemInfo = new AttemptToAddSyncItemForIVAInfo()
                        {
                            ivaNativeName      = ivaNativeName,
                            mappedFromIVAName  = mappedFromIVAName,
                            mappedToCKAKeyName = mappedToCKAKeyName,
                            iva = IVI.GetValueAccessor(ivaNativeName),
                        };

                        if (!AttemptToAddSyncItemForIVA(attemptToAddSyncItemInfo, requireUpdateNeeded: false))
                        {
                            lookAtLaterDictionary[ivaNativeName] = attemptToAddSyncItemInfo;

                            Log.Debug.Emit("IVA [{0}] has been added to look at later list", attemptToAddSyncItemInfo.iva);

                            useLookAtLaterTimer = !BridgeConfig.MinLookAtLaterInterval.IsZero();
                            if (useLookAtLaterTimer)
                            {
                                lookAtLaterTimer.StartIfNeeded(BridgeConfig.MinLookAtLaterInterval);
                            }
                        }
                    }
                    else
                    {
                        ivaNameToSyncItemDictionary[ivaNativeName] = null;
                    }
                }
            }

            // if we have lookAtLater items and the corresponding timer has triggered then
            if (lookAtLaterDictionary.Count > 0 && (!useLookAtLaterTimer || lookAtLaterTimer.IsTriggered))
            {
                foreach (var item in lookAtLaterDictionary.Values.ToArray())
                {
                    if (AttemptToAddSyncItemForIVA(item, requireUpdateNeeded: true))
                    {
                        Log.Debug.Emit("IVA [{0}] has been removed from the look at later list", item.iva);

                        lookAtLaterDictionary.Remove(item.ivaNativeName);
                    }
                }

                if (lookAtLaterDictionary.Count == 0)
                {
                    lookAtLaterTimer.Stop();
                }
            }

            // service CKA table addition:
            ConfigSubscriptionSeqNums configSeqNum = Config.SeqNums;

            if (lastConfigSeqNums.KeyAddedSeqNum != configSeqNum.KeyAddedSeqNum || lastConfigSeqNums.EnsureExistsSeqNum != configSeqNum.EnsureExistsSeqNum)
            {
                string[] configKeyNamesArray = Config.SearchForKeys();   // find all of the current keys

                foreach (string configKeyName in (configKeyNamesArray ?? emptyStringArray))
                {
                    if (configKeyNameToSyncItemDictionary.ContainsKey(configKeyName))
                    {
                        continue;
                    }

                    bool propagateConfigKeyName = BridgeConfig.CKAPropagateKeyMatchRuleSet.MatchesAny(configKeyName);

                    IConfigKeyAccess cka = (propagateConfigKeyName ? Config.GetConfigKeyAccess(new ConfigKeyAccessSpec()
                    {
                        Key = configKeyName, Flags = new ConfigKeyAccessFlags()
                        {
                            MayBeChanged = true
                        }
                    }) : null);

                    propagateConfigKeyName &= (BridgeConfig.CKAPropagateFilterPredicate == null || (cka != null && BridgeConfig.CKAPropagateFilterPredicate(cka.Key, cka.MetaData, cka.VC)));

                    string mappedFromConfigKeyName = configKeyName;
                    propagateConfigKeyName &= (BridgeConfig.CKAMapNameFromTo == null || BridgeConfig.CKAMapNameFromTo.MapInverse(configKeyName, ref mappedFromConfigKeyName));

                    string mappedToIVAName = mappedFromConfigKeyName;
                    propagateConfigKeyName &= (BridgeConfig.IVAMapNameFromTo == null || BridgeConfig.IVAMapNameFromTo.Map(mappedFromConfigKeyName, ref mappedToIVAName));

                    if (propagateConfigKeyName)
                    {
                        IValueAccessor iva = IVI.GetValueAccessor(mappedToIVAName);

                        AddSyncItemAndPerformInitialPropagation(iva, cka, mappedToIVAName, mappedFromConfigKeyName, null, configKeyName);
                    }
                    else
                    {
                        configKeyNameToSyncItemDictionary[configKeyName] = null;
                    }
                }
            }

            bool syncItemArrayUpdated = false;

            if (syncItemArray == null)
            {
                syncItemArray = syncItemList.ToArray();
                ivaArray      = syncItemArray.Select(syncItem => syncItem.iva).ToArray();
            }

            // service existing IVA -> CKA items
            if (syncItemArrayUpdated || ivaArray.IsUpdateNeeded())
            {
                foreach (SyncItem syncItem in syncItemArray)
                {
                    if (syncItem.iva.IsUpdateNeeded)
                    {
                        ValueContainer vc = syncItem.iva.Update().VC;

                        if (!vc.IsEqualTo(syncItem.icka.VC))
                        {
                            ValueTraceEmitter.Emit("Propagating iva change '{0}' to cka '{1}'", syncItem.iva, syncItem.icka);
                            syncItem.icka.SetValue(vc, "{0}: Propagating value change from iva '{1}'".CheckedFormat(PartID, syncItem.iva), autoUpdate: false);
                            syncItem.UpdateCopyInSet(ReferenceSet);
                        }
                        else
                        {
                            ValueTraceEmitter.Emit("iva '{0}' updated, value matches cka '{1}'", syncItem.iva, syncItem.icka);
                        }
                    }
                }
            }

            // service existing CKA -> IVA items
            if (lastConfigSeqNums.ChangeSeqNum != configSeqNum.ChangeSeqNum)
            {
                foreach (SyncItem syncItem in syncItemArray)
                {
                    if (syncItem.icka.UpdateValue())
                    {
                        ValueContainer vc = syncItem.icka.VC;

                        if (!vc.IsEqualTo(syncItem.iva.VC))
                        {
                            ValueTraceEmitter.Emit("Propagating cka change '{0}' to iva '{1}'", syncItem.icka, syncItem.iva);
                            syncItem.iva.Set(vc);
                            syncItem.UpdateCopyInSet(ReferenceSet);
                        }
                        else
                        {
                            ValueTraceEmitter.Emit("cka '{0}' updated, value matches iva '{1}'", syncItem.icka, syncItem.iva);
                        }
                    }
                }
            }

            // update lastConfigSeqNum as a whole
            if (!lastConfigSeqNums.Equals(configSeqNum))
            {
                lastConfigSeqNums = configSeqNum;
            }
        }