Example #1
0
        static void Main(string[] args)
        {
            var etcdClient = new EtcdClient("http://localhost:2379");

            etcdClient.DeleteRange("/foo");
            //Console.WriteLine(etcdClient.GetVal("/foo"));
            //Console.WriteLine(etcdClient.Get("foo").Kvs.FirstOrDefault().Value.ToStringUtf8());
            etcdClient.Put($"/foo/{Guid.NewGuid()}", Guid.NewGuid().ToString());
            etcdClient.Put(new PutRequest
            {
                Key   = ByteString.CopyFromUtf8("/time"),
                Value = ByteString.CopyFromUtf8(Guid.NewGuid().ToString()),
                Lease = etcdClient.LeaseGrant(new LeaseGrantRequest
                {
                    TTL = 20
                }).ID
            });
            var response = etcdClient.GetRange("/");

            foreach (var keyValue in response.Kvs)
            {
                Console.WriteLine($"{keyValue.Key.ToStringUtf8()}:{keyValue.Value.ToStringUtf8()}");
            }
            Console.ReadKey();
        }
Example #2
0
        public ModelVersion?incrementAndPublishNewModelVersion()
        {
            try
            {
                var lockResponse = client.Lock(name: MODEL_VERSION_LOCK, deadline: DateTime.UtcNow.AddMilliseconds(500));
                var modelVersion = getModelVersion();
                if (modelVersion.Version <= _modelVersion.Version)
                {
                    _modelVersion.Version++;
                    _modelVersion.TimeStamp = millis();
                    var json = serializeJson(_modelVersion);
                    client.Put(MODEL_VERSION, json);
                }

                client.Unlock(MODEL_VERSION_LOCK);
                filterOutModelVersions();
                return(_modelVersion);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return(null);
        }
Example #3
0
        public PutResponse Put(string key, string value)
        {
            var rsp = client.Put(new Etcdserverpb.PutRequest()
            {
                Key = key.ToProto(), Value = value.ToProto()
            });

            return(rsp.FromProto());
        }
Example #4
0
        public bool SetNodes(string key, string value)
        {
            if (key.IndexOf('/') != 0)
            {
                key = "/" + key;
            }
            var rep = etcdClient.Put(key, value).Result;

            return(true);
        }
Example #5
0
        public async Task ShouldReturnOneItem()
        {
            var resp = Enumerable.Range(0, 11).Select(async x => await etcdClient.Put("test" + x, "value" + x));
            await Task.WhenAll(resp);

            var res1 = await etcdClient.Get("test3");

            var res2 = await etcdClient.Get("test10");

            Assert.AreEqual("value3", res1);
            Assert.AreEqual("value10", res2);
        }
        public async Task ShouldNotOverwriteKeys()
        {
            var resp = Enumerable.Range(0, 100).Select(async x => await etcdClient.Put("test" + x, "value" + x))
                       .Concat(Enumerable.Range(0, 105).Select(async x => await etcdClient.Put("test" + x, "value" + x)))
                       .Concat(Enumerable.Range(0, 115).Select(async x => await etcdClient.Put("test" + x, "value" + x)));

            await Task.WhenAll(resp);

            var res = await etcdClient.GetRange("test");

            Assert.AreEqual(115, res.Count);
        }
Example #7
0
        public IActionResult Index(string key)
        {
            EtcdClient client = new EtcdClient("etcd", 2379);

            Etcdserverpb.RangeResponse response;
            if (key == null)
            {
                response = client.Get("/foo/foo");
            }
            else
            {
                response = client.Get(key);
            }

            try
            {
                RepeatedField <Mvccpb.KeyValue> kvs        = response.Kvs;
                IEnumerator <Mvccpb.KeyValue>   enumerator = kvs.GetEnumerator();
                enumerator.MoveNext();
                string value = enumerator.Current.Value.ToStringUtf8();

                ViewData["Message"] = "etcd says: " + value;
            }catch (Exception e) {
                ViewData["Message"] = e.ToString();
            }
            IHttpConnectionFeature feature = HttpContext.Features.Get <IHttpConnectionFeature>();

            ViewData["IP"]     = feature.LocalIpAddress.ToString();
            ViewData["Config"] = _configuration["somewhere"];

            client.Put("visited", feature.LocalIpAddress.ToString());

            return(View());
        }
        public async Task ShouldDeleteAllKeys()
        {
            var r = new Random();
            await etcdClient.Put("test1", r.Next().ToString());

            await etcdClient.Put("test2", r.Next().ToString());

            await etcdClient.Put("test3", r.Next().ToString());

            var deletedCount = await etcdClient.DeleteRange("test");

            var get = await etcdClient.GetRange("test");

            Assert.AreEqual(3, deletedCount);
            Assert.AreEqual(0, get.Values.Count);
        }
        public void PutGetDelete()
        {
            _client.Put("foo/bar", "barfoo");
            var getResult = _client.GetVal("foo/bar");

            Assert.AreEqual(getResult, "barfoo");
            _client.Delete("foo/bar");
        }
Example #10
0
 /// <summary>
 /// 创建
 /// </summary>
 /// <param name="host"></param>
 /// <param name="port"></param>
 /// <returns></returns>
 private EtcdClient CreateClient(string host, int port)
 {
     try
     {
         var c = new EtcdClient(host, port, username, password, caCert, clientCert, clientKey, publicRootCa);
         c.Put("TestCon", "EtcdCluster");
         return(c);
     }
     catch
     { return(null); }
 }
 WatchValues(ConcurrentDictionary <string, List <string> > cd)
 {
     try
     {
         var dk = etcdClient.GetRange(conf).Result;
         foreach (var item in dk)
         {
             cd.AddOrUpdate(item.Key.Replace(conf, ""), new List <string> {
                 item.Value
             }, (key, value) =>
             {
                 value[0] = item.Value;
                 return(value);
             });
         }
     }
     catch
     {
         foreach (var item in cd)
         {
             etcdClient.Put(conf + item.Key, item.Value[0]).Wait();
         }
     }
     watcher = etcdClient.WatchRange(conf).Result;
     watcher.Subscribe(s =>
     {
         foreach (var item in s)
         {
             cd.AddOrUpdate(item.Key.Replace(conf, ""), new List <string> {
                 item.Value
             }, (key, value) =>
             {
                 value[0] = item.Value;
                 return(value);
             });
         }
     });
 }
        public void CreateRequest()
        {
            string s = client.GetVal("req");

            if (s == null)
            {
                //ogranicenje, redom okidaj inicijalizaciju na cvorovima da ne dobijes 2 lidera
                client.Put("req", "");
                client.Put("leader", myId);
                IsLeader = true;
            }
            else
            {
                IsLeader = false;
            }
            ReqExists = true;
            client.Watch("leader", EtcdElected);
        }
Example #13
0
        /// <summary>
        /// 获取
        /// </summary>
        /// <returns></returns>
        public EtcdClient GetClient()
        {
            if (ClusterUseType == ClusterUse.Master_Slave)
            {
                try
                {
                    _client.Put("TestCon", "EtcdCluster");
                }
                catch
                {
                    _client.Dispose();
                    _client = null;
                    var c = GetEtcdClients(1);
                    if (c != null && c[0] != null)
                    {
                        _client.Dispose();
                        _client = c[0];
                    }
                }

                return(_client);
            }
            else
            {
                if (readerWriter.TryEnterReadLock(100))
                {
                    try
                    {
                        var c = dic.Values.Skip(_Lindex++ / dic.Count).First();
                        if (c != null)
                        {
                            c.lastUse = DateTime.Now.Ticks;
                            c.UseNum++;
                            return(c.Client);
                        }
                        return(null);
                    }
                    finally
                    {
                        readerWriter.ExitReadLock();
                    }
                }
                return(null);
            }
        }
Example #14
0
 public EtcdClient GetEtcdClient()
 {
     try
     {
         etcdClient.Put("testclient", "client");
         return(etcdClient);
     }
     catch (Exception ex)
     {
         //
         var client = GetClient();
         if (client != null)
         {
             etcdClient = client;
         }
         return(etcdClient);
     }
 }
        public void Put(string key, string value)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException(nameof(key));
            }

            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            DateTime?deadline = GetTimeOut();

            _etcdClient.Put(key, value, null, deadline);
        }
Example #16
0
        public async Task ShouldWatchSingleItem()
        {
            var resp = Enumerable.Range(0, 10).Select(async x => await etcdClient.Put("test" + x, "value" + x));
            await Task.WhenAll(resp);

            var resultList = new List <EtcdWatchEvent[]>();
            var watcher    = await etcdClient.Watch("test3");

            watcher.Subscribe(e => resultList.Add(e));

            await etcdClient.Put("test3", "value3");

            await etcdClient.Put("test2", "value2");

            await Task.Delay(500);

            watcher.Dispose();

            Assert.AreEqual(1, resultList.Count);
            Assert.AreEqual(1, resultList[0].Length);
        }
Example #17
0
        static void Main(string[] args)
        {
            Console.WriteLine("开始分库计算");
            int i = 1;

            //var db = (9527 % 20);
            //while (true)
            //{
            //    if (i == 0) continue;
            //    if ((9527 % i) == db)
            //    {
            //        Console.WriteLine("数据库(" + i + "):" + (9527 % i));
            //    }
            //    i++;
            //    //if (i % 10 == 0)
            //    //{
            //    //    Console.WriteLine("按任意键继续");
            //    //    Console.ReadLine();
            //    //}
            //}


            //var db = (9527 / 20) % 1;
            //while (true)
            //{
            //    var s = (9527 / 20) % i;
            //    if (s==db)
            //    {
            //        Console.WriteLine("数据库(" + i + "):" + s);
            //    }
            //    i++;
            //    //if (i % 10 == 0)
            //    //{
            //    //    Console.WriteLine("按任意键继续");
            //    //    Console.ReadLine();
            //    //}
            //}


            //dic.Add("1",new List<string> { "a"});
            //dic.Add("2", new List<string> { "b" });



            //List<string> list = dic["1"];

            //Console.WriteLine(list[0]);

            //dic["1"][0] = "C";

            //Console.WriteLine(list[0]);



            //dic["1"][0] = "C";

            //Console.WriteLine(list[0]);

            //dic["1"][0] = "K";

            //Console.WriteLine(list[0]);



            //Console.WriteLine("除数:" + (9527 / 10));

            //Console.WriteLine("数据库:" + (9527 / 10) % 8 + 1);
            //Console.WriteLine("表编号:" + (9527 % 10));

            //Console.WriteLine("数据库:" + (((9527 / 10) % 16 + 1) -1)% 2 +1);
            //Console.WriteLine("表编号:" + (9527 % 80));

            //int isTaked = 0;
            //if (Interlocked.Exchange(ref isTaked, 1) != 0)
            //{

            //    Console.Write("cc");
            //};
            //Interlocked.Exchange(ref isTaked, 0);

            EtcdClient etcdClient = new EtcdClient(new Uri("http://127.0.0.1:2379"));
            var        s          = etcdClient.Get("/111ddd").Result;

            Console.WriteLine(s);



            var sk = etcdClient.GetRange("/111").Result;
            var k  = etcdClient.Put("/conf/order/99999", "999").Result;

            var b     = etcdClient.Put("/conf/order/redis:add", "66666").Result;
            var etcdw = etcdClient.WatchRange("/111").Result;

            etcdw.Subscribe(x =>
            {
                Console.WriteLine("触发啦");
            });
            //etcdClient.Put("/111", "999");
            //etcdClient.Put("/111", "444");
            //etcdClient.Put("/111", "333");

            Console.Read();
        }
        public async Task ShouldDeleteAllKeys()
        {
            await etcdClient.Put("test1", string.Empty);

            await etcdClient.Put("test2", string.Empty);

            await etcdClient.Put("test3", string.Empty);

            var deletedCount = await EtcdTestHelper.DeleteAllRecords();

            var get = await etcdClient.GetRange("test");

            Assert.AreEqual(3, deletedCount);
            Assert.AreEqual(0, get.Values.Count);
        }
Example #19
0
        public static void ImportToEtcd(KeyValueData data)
        {
            string etcdUrl = $"http://{data.EtcdHost}:{data.EtcdPort}";

            $"Import to etcd {etcdUrl}".OutUnderline();

            using (var client = new EtcdClient(etcdUrl))
            {
                "Replace key-value tree".OutUnderline();
                client.DeleteRange("cfg/");

                foreach (var kv in data.Tree)
                {
                    kv.Key.Out();
                    client.Put(kv.Key, kv.Value);
                }

                "Delete users & roles".OutUnderline();
                var users = client
                            .UserList(new Etcdserverpb.AuthUserListRequest())
                            .Users
                            .ToList();

                foreach (var name in users)
                {
                    if (name != "root")
                    {
                        var reqDelUsr = new Etcdserverpb.AuthUserDeleteRequest()
                        {
                            Name = name
                        };
                        client.UserDelete(reqDelUsr);
                        $"User {name} deleted".Out();
                    }
                }

                var roles = client
                            .RoleList(new Etcdserverpb.AuthRoleListRequest())
                            .Roles
                            .ToList();

                foreach (var name in roles)
                {
                    if (name != "root")
                    {
                        var reqDelRole = new Etcdserverpb.AuthRoleDeleteRequest()
                        {
                            Role = name
                        };
                        client.RoleDelete(reqDelRole);
                        $"Role {name} deleted".Out();
                    }
                }

                "Create roles".OutUnderline();

                int i        = 0;
                var rolesDic = new Dictionary <string, string>(); // access vs role_name

                data.Users
                .Select(x => x.Access)
                .Distinct()
                .ToList()
                .ForEach(x =>
                {
                    string roleName = $"role{++i}";

                    var reqRoleAdd = new Etcdserverpb.AuthRoleAddRequest()
                    {
                        Name = roleName
                    };
                    client.RoleAdd(reqRoleAdd);
                    $"Role {roleName} created".Out();

                    var reqAddPerm = new Etcdserverpb.AuthRoleGrantPermissionRequest()
                    {
                        Name = roleName,
                        Perm = new Authpb.Permission()
                        {
                            Key      = Google.Protobuf.ByteString.CopyFromUtf8($"cfg/{x}"),
                            RangeEnd = Google.Protobuf.ByteString.CopyFromUtf8($"cfg/{x}"),
                            PermType = Authpb.Permission.Types.Type.Read
                        }
                    };
                    client.RoleGrantPermission(reqAddPerm);
                    $"Readonly access to cfg/{x} granted".Out();

                    reqAddPerm = new Etcdserverpb.AuthRoleGrantPermissionRequest()
                    {
                        Name = roleName,
                        Perm = new Authpb.Permission()
                        {
                            Key      = Google.Protobuf.ByteString.CopyFromUtf8($"app/{x}"),
                            RangeEnd = Google.Protobuf.ByteString.CopyFromUtf8($"app/{x}"),
                            PermType = Authpb.Permission.Types.Type.Readwrite
                        }
                    };
                    client.RoleGrantPermission(reqAddPerm);
                    $"Readwrite access to app/{x} granted".Out();

                    rolesDic[x] = roleName;
                });

                "Create users and grant roles".OutUnderline();

                foreach (var user in data.Users)
                {
                    var reqAddUsr = new Etcdserverpb.AuthUserAddRequest()
                    {
                        Name     = user.Name,
                        Password = user.Password
                    };

                    client.UserAdd(reqAddUsr);
                    $"User {user.Name} created".Out();

                    var reqGrantRole = new Etcdserverpb.AuthUserGrantRoleRequest()
                    {
                        User = user.Name,
                        Role = rolesDic[user.Access]
                    };
                    client.UserGrantRole(reqGrantRole);
                    $"Access to {user.Access} granted ({rolesDic[user.Access]})".Out();
                }
            }
        }