Ejemplo n.º 1
0
        public async Task testACLs()
        {
            ZooKeeper zk = await createClient();

            try {
                await zk.createAsync("/acltest", new byte[0], ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);

                Assert.fail("Should have received an invalid acl error");
            }
            catch (KeeperException.InvalidACLException e) {
                LOG.info("Test successful, invalid acl received : " + e.Message);
            }
            try {
                List <ACL> testACL = new List <ACL>();
                testACL.Add(new ACL((int)(ZooDefs.Perms.ALL | ZooDefs.Perms.ADMIN), ZooDefs.Ids.AUTH_IDS));
                testACL.Add(new ACL((int)(ZooDefs.Perms.ALL | ZooDefs.Perms.ADMIN), new Id("ip", "127.0.0.1/8")));
                await zk.createAsync("/acltest", new byte[0], testACL, CreateMode.PERSISTENT);

                Assert.fail("Should have received an invalid acl error");
            }
            catch (KeeperException.InvalidACLException e) {
                LOG.info("Test successful, invalid acl received : " + e.Message);
            }
            zk.addAuthInfo("digest", "ben:passwd".UTF8getBytes());
            await zk.createAsync("/acltest", new byte[0], ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);

            await zk.closeAsync();

            zk = await createClient();

            zk.addAuthInfo("digest", "ben:passwd2".UTF8getBytes());
            try {
                await zk.getDataAsync("/acltest", false);

                Assert.fail("Should have received a permission error");
            }
            catch (KeeperException e) {
                Assert.assertEquals(KeeperException.Code.NOAUTH, e.getCode());
            }
            zk.addAuthInfo("digest", "ben:passwd".UTF8getBytes());
            await zk.getDataAsync("/acltest", false);

            await zk.setACLAsync("/acltest", ZooDefs.Ids.OPEN_ACL_UNSAFE, -1);

            await zk.closeAsync();

            zk = await createClient();

            await zk.getDataAsync("/acltest", false);

            IList <ACL> acls = (await zk.getACLAsync("/acltest")).Acls;

            Assert.assertEquals(1, acls.Count);
            Assert.assertEquals(ZooDefs.Ids.OPEN_ACL_UNSAFE, acls);

            // The stat parameter should be optional.
            acls = (await zk.getACLAsync("/acltest")).Acls;
            Assert.assertEquals(1, acls.Count);
            Assert.assertEquals(ZooDefs.Ids.OPEN_ACL_UNSAFE, acls);
        }
Ejemplo n.º 2
0
        public void testACLs()
        {
            ZooKeeper zk = null;

            try {
                zk = createClient();
                try {
                    zk.create("/acltest", new byte[0], ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
                    Assert.fail("Should have received an invalid acl error");
                }
                catch (KeeperException.InvalidACLException e) {
                    LOG.info("Test successful, invalid acl received : " + e.Message);
                }
                try {
                    List <ACL> testACL = new List <ACL>();
                    testACL.Add(new ACL((int)(ZooDefs.Perms.ALL | ZooDefs.Perms.ADMIN), ZooDefs.Ids.AUTH_IDS));
                    testACL.Add(new ACL((int)(ZooDefs.Perms.ALL | ZooDefs.Perms.ADMIN), new Id("ip", "127.0.0.1/8")));
                    zk.create("/acltest", new byte[0], testACL, CreateMode.PERSISTENT);
                    Assert.fail("Should have received an invalid acl error");
                }
                catch (KeeperException.InvalidACLException e) {
                    LOG.info("Test successful, invalid acl received : " + e.Message);
                }
                zk.addAuthInfo("digest", "ben:passwd".getBytes());
                zk.create("/acltest", new byte[0], ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
                zk.close();
                zk = createClient();
                zk.addAuthInfo("digest", "ben:passwd2".getBytes());
                try {
                    zk.getData("/acltest", false, new Stat());
                    Assert.fail("Should have received a permission error");
                }
                catch (KeeperException e) {
                    Assert.assertEquals(KeeperException.Code.NOAUTH, e.getCode());
                }
                zk.addAuthInfo("digest", "ben:passwd".getBytes());
                zk.getData("/acltest", false, new Stat());
                zk.setACL("/acltest", ZooDefs.Ids.OPEN_ACL_UNSAFE, -1);
                zk.close();
                zk = createClient();
                zk.getData("/acltest", false, new Stat());
                IList <ACL> acls = zk.getACL("/acltest", new Stat());
                Assert.assertEquals(1, acls.Count);
                Assert.assertEquals(ZooDefs.Ids.OPEN_ACL_UNSAFE, acls);
                zk.close();
            }
            finally {
                if (zk != null)
                {
                    zk.close();
                }
            }
        }
Ejemplo n.º 3
0
 private void buttonAddAuth_Click(object sender, EventArgs e)
 {
     lock (m_zooKeeperClientLocker)
     {
         if (m_zooKeeperClient == null)
         {
             MessageBox.Show("No Connection.", "Info");
         }
         else
         {
             AuthInfoForm authInfoForm = new AuthInfoForm();
             var          dialogResult = authInfoForm.ShowDialog();
             if (dialogResult == DialogResult.OK)
             {
                 try
                 {
                     m_zooKeeperClient.addAuthInfo(authInfoForm.Scheme, authInfoForm.Auth);
                     Log("Auth added.");
                 }
                 catch (KeeperException ex)
                 {
                     Log(ex.Message);
                 }
             }
         }
     }
 }
Ejemplo n.º 4
0
        public void Get_Value_From_Node_With_ACL()
        {
            string usd = "110";

            byte[] auth = Encoding.UTF8.GetBytes("user1:pass1");
            var    zk   = new ZooKeeper("localhost:2181", 3000, null);

            zk.addAuthInfo("digest", auth);
            zk.createAsync("/AccountAppAuth", null, ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT).GetAwaiter().GetResult();
            zk.createAsync("/AccountAppAuth/Rate", null, ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT).GetAwaiter().GetResult();
            zk.createAsync("/AccountAppAuth/Rate/USD", Encoding.UTF8.GetBytes(usd), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT).GetAwaiter().GetResult();
            zk.closeAsync().GetAwaiter().GetResult();

            IConfigurationBuilder builder = new ConfigurationBuilder();

            builder.AddZookeeper(option =>
            {
                option.ConnectionString  = "localhost:2181";
                option.ConnectionTimeout = 10000;
                option.RootPath          = "/AccountAppAuth";
                option.SessionTimeout    = 30000;
                option.AddAuthInfo("digest", auth);
            });
            var configuration = builder.Build();

            Assert.Equal(usd, configuration["Rate:USD"]);
        }
Ejemplo n.º 5
0
        public void Dispose()
        {
            var zk = new ZooKeeper("localhost:2181", 3000, null);

            if (zk.existsAsync("/AccountApp").GetAwaiter().GetResult() != null)
            {
                zk.deleteAsync("/AccountApp/Rate/USD").GetAwaiter().GetResult();
                zk.deleteAsync("/AccountApp/Rate").GetAwaiter().GetResult();
                zk.deleteAsync("/AccountApp").GetAwaiter().GetResult();
            }
            byte[] auth = Encoding.UTF8.GetBytes("user1:pass1");

            zk.addAuthInfo("digest", auth);

            if (zk.existsAsync("/AccountAppAuth").GetAwaiter().GetResult() != null)
            {
                zk.deleteAsync("/AccountAppAuth/Rate/USD").GetAwaiter().GetResult();
                zk.deleteAsync("/AccountAppAuth/Rate").GetAwaiter().GetResult();
                zk.deleteAsync("/AccountAppAuth").GetAwaiter().GetResult();
            }

            if (zk.existsAsync("/AccountAppAuth2").GetAwaiter().GetResult() != null)
            {
                zk.deleteAsync("/AccountAppAuth2/Rate/USD").GetAwaiter().GetResult();
                zk.deleteAsync("/AccountAppAuth2/Rate").GetAwaiter().GetResult();
                zk.deleteAsync("/AccountAppAuth2").GetAwaiter().GetResult();
            }
            zk.closeAsync().GetAwaiter().GetResult();
        }
        /// <summary>
        /// 返回null表示连接不成功
        /// </summary>
        /// <param name="authEnum"></param>
        /// <param name="authInfo"></param>
        /// <returns></returns>
        public ZooKeeper Connect(AuthEnum authEnum, string authInfo)
        {
            foreach (string address in _address)
            {
                _zooKeeper = new ZooKeeper(address, _sessiontTimeout, new DefaultWatcher());
                if (authEnum != AuthEnum.world)
                {
                    _zooKeeper.addAuthInfo(authEnum.ToString(), System.Text.Encoding.UTF8.GetBytes(authInfo));
                }
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                while (stopwatch.ElapsedMilliseconds < _connectTimeout / _address.Count)
                {
                    ZooKeeper.States states = _zooKeeper.getState();
                    if (states == ZooKeeper.States.CONNECTED || states == ZooKeeper.States.CONNECTEDREADONLY)
                    {
                        break;
                    }
                }
                stopwatch.Stop();
                if (_zooKeeper.getState().ToString().ToUpper().Contains("CONNECTED"))
                {
                    break;
                }
            }

            return(_zooKeeper);
        }
Ejemplo n.º 7
0
            private async Task <InternalConnection> InternalConnectAsync(ZooKeeperConnectionInfo connectionInfo)
            {
                var watcher   = new ConnectionWatcher(connectionInfo.SessionTimeout);
                var zooKeeper = new ZooKeeper(
                    connectstring: connectionInfo.ConnectionString,
                    sessionTimeout: connectionInfo.SessionTimeout.InMilliseconds,
                    watcher: watcher
                    );

                using var timeoutSource       = new CancellationTokenSource(connectionInfo.ConnectTimeout.TimeSpan);
                using var timeoutRegistration = timeoutSource.Token.Register(
                          () => watcher.TaskCompletionSource.TrySetException(new TimeoutException($"Timed out connecting to ZooKeeper after {connectionInfo.ConnectTimeout.InMilliseconds}ms"))
                          );

                foreach (var authInfo in connectionInfo.AuthInfo)
                {
                    zooKeeper.addAuthInfo(authInfo.Scheme, authInfo.Auth.ToArray());
                }

                try
                {
                    await watcher.TaskCompletionSource.Task.ConfigureAwait(false);

                    return(new InternalConnection(zooKeeper, watcher));
                }
                catch
                {
                    // on failure, clean up the instance we created
                    try { await zooKeeper.closeAsync().ConfigureAwait(false); }
                    finally { watcher.Dispose(); }
                    throw;
                }
            }
Ejemplo n.º 8
0
            public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, bool canBeReadOnly)
            {
                ZooKeeper zooKeeper = _actualZookeeperFactory.newZooKeeper(connectString, sessionTimeout, watcher, canBeReadOnly);

                foreach (AuthInfo auth in _factory.authInfos)
                {
                    zooKeeper.addAuthInfo(auth.getScheme(), auth.getAuth());
                }
                return(zooKeeper);
            }
Ejemplo n.º 9
0
        /// <summary>
        /// create zooKeeper instance.
        /// </summary>
        public ZooKeeper CreateZooKeeper(string connectionString, int sessionTimeout, IEnumerable <AuthData> authData,
                                         out NodeWatcher watcher)
        {
            watcher = new NodeWatcher();
            var zk = new ZooKeeper(connectionString, sessionTimeout, watcher);

            if (authData != null && authData.Any())
            {
                foreach (var auth in authData)
                {
                    if (auth != null)
                    {
                        zk.addAuthInfo(auth.Scheme, auth.Data);
                    }
                }
            }

            return(zk);
        }
Ejemplo n.º 10
0
        public void Authenticate_With_Invalid_Credentials_Throws_Exception()
        {
            string usd = "110";

            byte[] auth = Encoding.UTF8.GetBytes("user1:pass1");
            var    zk   = new ZooKeeper("localhost:2181", 3000, null);

            zk.addAuthInfo("digest", auth);
            zk.createAsync("/AccountAppAuth2", null, ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT).GetAwaiter().GetResult();
            zk.createAsync("/AccountAppAuth2/Rate", null, ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT).GetAwaiter().GetResult();
            zk.createAsync("/AccountAppAuth2/Rate/USD", Encoding.UTF8.GetBytes(usd), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT).GetAwaiter().GetResult();
            zk.closeAsync().GetAwaiter().GetResult();

            IConfigurationBuilder builder1 = new ConfigurationBuilder();

            builder1.AddZookeeper(option =>
            {
                option.ConnectionString  = "localhost:2181";
                option.ConnectionTimeout = 10000;
                option.RootPath          = "/AccountAppAuth2";
                option.SessionTimeout    = 30000;
                option.AddAuthInfo("digest", Encoding.UTF8.GetBytes("user1:pass1"));
            });

            var configurationForUser1 = builder1.Build();

            Assert.Equal(usd, configurationForUser1["Rate:USD"]);

            IConfigurationBuilder builder2 = new ConfigurationBuilder();

            builder2.AddZookeeper(option =>
            {
                option.ConnectionString  = "localhost:2181";
                option.ConnectionTimeout = 10000;
                option.RootPath          = "/AccountAppAuth2";
                option.SessionTimeout    = 30000;
                option.AddAuthInfo("digest", Encoding.UTF8.GetBytes("user2:pass1"));
            });

            var configurationForUser2 = builder2.Build();

            Assert.Null(configurationForUser2["Rate:USD"]);
        }
Ejemplo n.º 11
0
                /// <summary>
                /// 建立ZK连接 返回null表示连接不成功
                /// </summary>
                /// <param name="authEnum"></param>
                /// <param name="authInfo"></param>
                /// <returns></returns>
                public ZooKeeper Connect(AuthEnum authEnum, string authInfo)
        {
            try
            {
                foreach (string address in _address)
                {
                    _zooKeeper = new ZooKeeper(address, _sessiontTimeout, new NodeWatcher(_log));
                    if (authEnum != AuthEnum.world)
                    {
                        _zooKeeper.addAuthInfo(authEnum.ToString(), System.Text.Encoding.UTF8.GetBytes(authInfo));
                    }
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    while (stopwatch.ElapsedMilliseconds < _connectTimeout / _address.Count)
                    {
                        ZooKeeper.States states = _zooKeeper.getState();
                        if (states == ZooKeeper.States.CONNECTED || states == ZooKeeper.States.CONNECTEDREADONLY)
                        {
                            break;
                        }
                    }
                    stopwatch.Stop();
                    if (_zooKeeper.getState().ToString().ToUpper().Contains("CONNECTED"))
                    {
                        break;
                    }
                }

                return(_zooKeeper);
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("连接zookeeper发生异常:{0}", ex.Message + ex.StackTrace);
            }
            return(null);
        }
Ejemplo n.º 12
0
 public void AddAuthInfo(string scheme, byte[] auth)
 {
     _zookeeper.addAuthInfo(scheme, auth);
 }
Ejemplo n.º 13
0
 public void AddAuthInfo(AclScheme scheme, byte[] auth)
 {
     ValidateState();
     _zk.addAuthInfo(scheme.ToString().ToLower(), auth);
 }
Ejemplo n.º 14
0
        public void testRootAcl()
        {
            ZooKeeper zk = createClient();

            try
            {
                // set auth using digest
                zk.addAuthInfo("digest", "pat:test".getBytes());
                zk.setACL("/", ZooDefs.Ids.CREATOR_ALL_ACL, -1);
                zk.getData("/", false, null);
                zk.close();
                // verify no access
                zk = createClient();
                try
                {
                    zk.getData("/", false, null);
                    Assert.fail("validate auth");
                }
                catch (KeeperException.NoAuthException)
                {
                    // expected
                }
                try
                {
                    zk.create("/apps", null, ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
                    Assert.fail("validate auth");
                }
                catch (KeeperException.InvalidACLException)
                {
                    // expected
                }
                zk.addAuthInfo("digest", "world:anyone".getBytes());
                try
                {
                    zk.create("/apps", null, ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
                    Assert.fail("validate auth");
                }
                catch (KeeperException.NoAuthException)
                {
                    // expected
                }
                zk.close();
                // verify access using original auth
                zk = createClient();
                zk.addAuthInfo("digest", "pat:test".getBytes());
                zk.getData("/", false, null);
                zk.create("/apps", null, ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
                zk.delete("/apps", -1);
                // reset acl (back to open) and verify accessible again
                zk.setACL("/", ZooDefs.Ids.OPEN_ACL_UNSAFE, -1);
                zk.close();
                zk = createClient();
                zk.getData("/", false, null);
                zk.create("/apps", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                try
                {
                    zk.create("/apps", null, ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
                    Assert.fail("validate auth");
                }
                catch (KeeperException.InvalidACLException)
                {
                    // expected
                }
                zk.delete("/apps", -1);
                zk.addAuthInfo("digest", "world:anyone".getBytes());
                zk.create("/apps", null, ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
                zk.close();
                zk = createClient();
                zk.delete("/apps", -1);
            }
            finally
            {
                zk.close();
            }
        }