public override void Load() { EtcdClientOpitions options = new EtcdClientOpitions() { Urls = source.Options.Urls, Username = source.Options.Username, Password = source.Options.Password, UseProxy = false, IgnoreCertificateError = true }; EtcdClient etcdClient = new EtcdClient(options); try { EtcdResponse resp = etcdClient.GetNodeAsync(source.Options.RootKey, recursive: true, sorted: true).Result; if (resp.Node.Nodes != null) { foreach (var node in resp.Node.Nodes) { // child node Data[node.Key] = node.Value; } } } catch (EtcdCommonException.KeyNotFound) { // key does not Console.WriteLine("key not found exception"); } }
public async Task <IEnumerable <string> > LookupServiceAsync(string serviceName) { EtcdResponse response = await _client.GetNodeAsync($"/killrvideo/services/{serviceName}", ignoreKeyNotFoundException : true).ConfigureAwait(false); if (response == null) { throw new ServiceNotFoundException(serviceName); } return(response.Node.Nodes.Select(n => n.Value)); }
/// <summary> /// 输出在线状态 /// </summary> /// <returns></returns> private static async Task OutputOnlineState() { try { if (m_client != null) { //var response = await m_client.GetNodeAsync("/Client"); try { EtcdResponse resp1 = await m_client.CreateNodeAsync("/Client", "valye"); EtcdResponse resp = await m_client.SetNodeAsync("/Client", "valye"); Console.WriteLine("Key `{0}` is changed, modifiedIndex={1}", "/Client", resp.Node.ModifiedIndex); var value = await m_client.GetNodeValueAsync("/Client", true); Console.WriteLine("The value of `{0}` is `{1}`", "/Client", value); } catch (EtcdCommonException.KeyNotFound) { Console.WriteLine("Key `{0}` does not exist", "/Client"); } var response = await m_client.GetNodeAsync("/", true); if (response != null && response.Node != null) { if (response.Node.Nodes != null) { foreach (var child in response.Node.Nodes) { var key = child.Key.Replace("/Client/", ""); var value = child.Value; string result = $"{key}状态是{value}"; Console.WriteLine(result); } } } } } catch (Exception e) { Console.WriteLine(e); } }
private async Task <bool> UpdateKeyAndCheckIsMaster(EtcdNode node) { //Update our key to ensure it doens't expire. //Only do this if it exists await etcdClient.CompareAndSwapNodeAsync(node.Key, InstanceId, InstanceId, electionTimeoutSec); //Todo: validate what happens here if the key's ttl has expired due to this node hanging. // Expect it to throw and crash the node, orchestrata would then restart and node would be bottom of the list for next master. await Task.Delay(TimeSpan.FromSeconds(electionTimeoutSec - 10)); //Get a sorted list of nodes for the election Key. //Oldest nodes will be a at the top. They're a good candidate for master as they're the most stable. var currentStatus = await etcdClient.GetNodeAsync(ElectionKey, false, false, true); //The first node is the oldest, if this is us - we're the master if (currentStatus.Node.Nodes.First().Value == InstanceId) { return(true); } return(false); }
static async Task DoSample() { EtcdClientOpitions options = new EtcdClientOpitions() { #if NET45 // TODO: This is optional, having HTTPS setup could make this work in .NET Core as well, but it's not tested for now Urls = new string[] { "https://etcd0.em", "https://etcd1.em", "https://etcd2.em" }, #else Urls = new string[] { "http://*****:*****@"client.p12"), // client cerificate JsonDeserializer = new NewtonsoftJsonDeserializer(), }; EtcdClient etcdClient = new EtcdClient(options); string key = "/my/key"; string value; // query the value of the node using GetNodeValueAsync try { value = await etcdClient.GetNodeValueAsync(key); Console.WriteLine("The value of `{0}` is `{1}`", key, value); } catch (EtcdCommonException.KeyNotFound) { Console.WriteLine("Key `{0}` does not exist", key); } // update the value using SetNodeAsync EtcdResponse resp = await etcdClient.SetNodeAsync(key, "some value"); Console.WriteLine("Key `{0}` is changed, modifiedIndex={1}", key, resp.Node.ModifiedIndex); // query the node using GetNodeAsync resp = await etcdClient.GetNodeAsync(key, ignoreKeyNotFoundException : true); if (resp == null || resp.Node == null) { Console.WriteLine("Key `{0}` does not exist", key); } else { Console.WriteLine("The value of `{0}` is `{1}`", key, resp.Node.Value); } ////////////////////////////////////////////////////////// List <Task <EtcdResponse> > tasks = new List <Task <EtcdResponse> >(); key = "/in-order-queue"; // start monitoring the expire event WatchChanges(etcdClient, key); // create 5 in-order nodes, TTL = 3 second for (int i = 0; i < 5; i++) { tasks.Add(etcdClient.CreateInOrderNodeAsync(key, i.ToString(), ttl: 3)); } await Task.WhenAll(tasks); // list the in-order nodes resp = await etcdClient.GetNodeAsync(key, false, recursive : true, sorted : true); if (resp.Node.Nodes != null) { foreach (var node in resp.Node.Nodes) { Console.WriteLine("`{0}` = {1}", node.Key, node.Value); } } ///////////////////////////////////////////////////////////// key = "/my/cas-test"; value = Guid.NewGuid().ToString(); try { resp = await etcdClient.CreateNodeAsync(key, value, null, dir : false); Console.WriteLine("Key `{0}` is created with value {1}", key, value); } catch (EtcdCommonException.NodeExist) { Console.WriteLine("Key `{0}` already exists", key); } long prevIndex = 1; try { resp = await etcdClient.CompareAndSwapNodeAsync(key, value, "new value"); Console.WriteLine("Key `{0}` is updated to `{1}`", key, resp.Node.Value); prevIndex = resp.Node.ModifiedIndex; } catch (EtcdCommonException.KeyNotFound) { Console.WriteLine("Key `{0}` does not exists", key); } catch (EtcdCommonException.TestFailed) { Console.WriteLine("Key `{0}` can not be updated because the supplied previous value is incorrect", key); } try { resp = await etcdClient.CompareAndSwapNodeAsync(key, prevIndex, "new value2"); Console.WriteLine("Key `{0}` is updated to `{1}`", key, resp.Node.Value); } catch (EtcdCommonException.KeyNotFound) { Console.WriteLine("Key `{0}` does not exists", key); } catch (EtcdCommonException.TestFailed) { Console.WriteLine("Key `{0}` can not be updated because the supplied previous index is incorrect", key); } try { resp = await etcdClient.CompareAndDeleteNodeAsync(key, prevIndex + 1); Console.WriteLine("Key `{0}` is deleted", key); } catch (EtcdCommonException.KeyNotFound) { Console.WriteLine("Key `{0}` does not exists", key); } catch (EtcdCommonException.TestFailed) { Console.WriteLine("Key `{0}` can not be deleted because the supplied previous index is incorrect", key); } if (prevIndex == 1) // the previous CAS failed { try { resp = await etcdClient.CompareAndDeleteNodeAsync(key, "new value2"); Console.WriteLine("Key `{0}` is deleted", key); } catch (EtcdCommonException.KeyNotFound) { Console.WriteLine("Key `{0}` does not exists", key); } catch (EtcdCommonException.TestFailed) { Console.WriteLine("Key `{0}` can not be deleted because the supplied previous value is incorrect", key); etcdClient.DeleteNodeAsync(key, ignoreKeyNotFoundException: true).Wait(); } } }
public IEnumerable <Change <T> > Watch(string id) { string key = CreateKey(id); long? waitIndex = null; EtcdResponse resp; Change <T> nextChange = null; while (true) // TODO: Cancellation token { // try // { // when waitIndex is null, get it from the ModifiedIndex if (!waitIndex.HasValue) { resp = etcdClient.GetNodeAsync(key, ignoreKeyNotFoundException: true, recursive: true).Result; if (resp != null && resp.Node != null) { waitIndex = resp.Node.ModifiedIndex + 1; // and also check the children if (resp.Node.Nodes != null) { foreach (var child in resp.Node.Nodes) { if (child.ModifiedIndex >= waitIndex.Value) { waitIndex = child.ModifiedIndex + 1; } // child node } } } } // watch the changes resp = etcdClient.WatchNodeAsync(key, recursive: true, waitIndex: waitIndex).Result; if (resp != null && resp.Node != null) { waitIndex = resp.Node.ModifiedIndex + 1; if (resp.Node.Key.StartsWith(key, StringComparison.InvariantCultureIgnoreCase)) { string nodeId = ParseKey(resp.Node.Key); T value = resp.Node.Value != null?FromDataRecord(resp.Node.Value) : default(T); switch (resp.Action.ToLowerInvariant()) { case EtcdResponse.ACTION_DELETE: nextChange = new Change <T>(ChangeType.Delete, nodeId, value); break; case EtcdResponse.ACTION_EXPIRE: nextChange = new Change <T>(ChangeType.Delete, nodeId, value); break; case EtcdResponse.ACTION_COMPARE_AND_DELETE: nextChange = new Change <T>(ChangeType.Delete, nodeId, default(T)); break; case EtcdResponse.ACTION_SET: nextChange = new Change <T>(ChangeType.Update, nodeId, value); break; case EtcdResponse.ACTION_CREATE: nextChange = new Change <T>(ChangeType.Create, nodeId, value); break; case EtcdResponse.ACTION_COMPARE_AND_SWAP: nextChange = new Change <T>(ChangeType.Update, nodeId, value); break; default: break; } } } // } // catch(TaskCanceledException) // { // // time out, try again // } // catch(EtcdException ee) // { // // reset the waitIndex // waitIndex = null; // } // catch (EtcdGenericException ege) // { // // etcd returns an error // } // catch (Exception ex) // { // // generic error // } if (nextChange != null) { yield return(nextChange); nextChange = null; } } }