public void Connect(IWatcher watcher) { Monitor.Enter(this._zookeeperLock); try { if (this._zk != null) { throw new Exception("zk client has already been started"); } try { Logger.Debug("Creating new ZookKeeper instance to connect to " + this._servers + "."); this._zk = new ZooKeeper(this._servers, this._sessionTimeOut, watcher); } catch (Exception e) { throw new ZkException("Unable to connect to " + this._servers, e); } } finally { Monitor.Exit(this._zookeeperLock); } }
public HandleHolder(IZookeeperFactory zookeeperFactory, IWatcher watcher, IEnsembleProvider ensembleProvider, TimeSpan sessionTimeout, bool canBeReadOnly) { this.zookeeperFactory = zookeeperFactory; this.watcher = watcher; this.ensembleProvider = ensembleProvider; this.sessionTimeout = sessionTimeout; this.canBeReadOnly = canBeReadOnly; this.helper = null; }
protected WatcherCheck(IWatcher watcher) { if (watcher == null) throw new ArgumentNullException(nameof(watcher), "Watcher can not be null."); if (string.IsNullOrEmpty(watcher.Name)) throw new ArgumentException("Watcher name can not be empty."); WatcherName = watcher.Name; WatcherType = watcher.GetType(); }
public ConnectionState(IZookeeperFactory zookeeperFactory, IEnsembleProvider ensembleProvider, TimeSpan sessionTimeout, TimeSpan connectionTimeout, IWatcher parentWatcher, ITracerDriver tracer, bool canBeReadOnly) { this.ensembleProvider = ensembleProvider; this.sessionTimeout = sessionTimeout; this.connectionTimeout = connectionTimeout; this.tracer = tracer; if ( parentWatcher != null ) { parentWatchers.Enqueue (parentWatcher); } zooKeeper = new HandleHolder(zookeeperFactory, this, ensembleProvider, sessionTimeout, canBeReadOnly); }
public BlobWatchableDisposableValueProvider(IStorageBlob blob, object value, Type valueType, IWatcher watcher, IDisposable disposable) { if (value != null && !valueType.IsAssignableFrom(value.GetType())) { throw new InvalidOperationException("value is not of the correct type."); } _blob = blob; _value = value; _valueType = valueType; _watcher = watcher; _disposable = disposable; }
/** * @param zookeeperFactory factory for creating {@link ZooKeeper} instances * @param ensembleProvider the ensemble provider * @param sessionTimeoutMs session timeout * @param connectionTimeoutMs connection timeout * @param watcher default watcher or null * @param retryPolicy the retry policy to use * @param canBeReadOnly if true, allow ZooKeeper client to enter * read only mode in case of a network partition. See * {@link ZooKeeper#ZooKeeper(String, int, Watcher, long, byte[], bool)} * for details */ public CuratorZookeeperClient(IZookeeperFactory zookeeperFactory, IEnsembleProvider ensembleProvider, int sessionTimeoutMs, int connectionTimeoutMs, IWatcher watcher, IRetryPolicy retryPolicy, bool canBeReadOnly) { if ( sessionTimeoutMs < connectionTimeoutMs ) { log.Warn(String.Format("session timeout [{0}] is less than connection timeout [{1}]", sessionTimeoutMs, connectionTimeoutMs)); } // retryPolicy = Preconditions.checkNotNull(retryPolicy, "retryPolicy cannot be null"); // ensembleProvider = Preconditions.checkNotNull(ensembleProvider, "ensembleProvider cannot be null"); this.connectionTimeoutMs = connectionTimeoutMs; state = new ConnectionState(zookeeperFactory, ensembleProvider, TimeSpan.FromMilliseconds(sessionTimeoutMs), TimeSpan.FromMilliseconds(connectionTimeoutMs), watcher, tracer, canBeReadOnly); SetRetryPolicy(retryPolicy); }
/// <summary> /// register watcher /// </summary> /// <param name="container"></param> /// <param name="watcher"></param> /// <param name="clientPath"></param> /// <exception cref="ArgumentNullException">container is null</exception> private void RegisterWatcher(Dictionary<string, HashSet<IWatcher>> container, IWatcher watcher, string clientPath) { if (container == null) throw new ArgumentNullException("container"); lock (container) { HashSet<IWatcher> set = null; if (!container.TryGetValue(clientPath, out set)) { set = new HashSet<IWatcher>(); container[clientPath] = set; } set.Add(watcher); } }
public static void ReadKeywordFromFile(string filePath, bool listening) { ReadKeyword(ReadAllText(filePath)); if (_watcher != null) { _watcher.Dispose(); } if (listening) { _watcher = Watcher.WatcherFile(filePath); _watcher.Changed += _watcher_Changed; _watcher.Async = true; } }
public void SetUp() { _scheduler = new TestScheduler(); _source = new SourceCache<Person, string>(p => p.Key); _watcher = _source.Connect().AsWatcher(_scheduler); _results = new ChangeSetAggregator<SelfObservingPerson, string> ( _source.Connect() .Transform(p => new SelfObservingPerson(_watcher.Watch(p.Key).Select(w => w.Current))) .DisposeMany() ); _cleanUp = Disposable.Create(() => { _results.Dispose(); _source.Dispose(); _watcher.Dispose(); }); }
/// <summary> /// Connects to ZooKeeper server /// </summary> /// <param name="watcher"> /// The watcher to be installed in ZooKeeper. /// </param> public void Connect(IWatcher watcher) { this.EnsuresNotDisposed(); lock (this.syncLock) { if (this.Client != null) { throw new InvalidOperationException("ZooKeeper client has already been started"); } try { Logger.Debug("Starting ZK client"); this.Client = new ZooKeeper(this.Servers, new TimeSpan(0, 0, 0, 0, this.SessionTimeout), watcher); } catch (IOException exc) { throw new ZooKeeperException("Unable to connect to " + this.Servers, exc); } } }
private WatcherResultState GetPreviousWatcherState(IWatcher watcher) { return(_latestWatcherResultStates.ContainsKey(watcher) ? _latestWatcherResultStates[watcher] : WatcherResultState.NotSet); }
protected internal Builder(IWatcher watcher) { _configuration = new WatcherConfiguration(watcher); }
/// <summary> /// register child watcher /// </summary> /// <param name="watcher"></param> /// <param name="clientPath"></param> public void RegisterChildWatcher(IWatcher watcher, string clientPath) { this.RegisterWatcher(this._childWatches, watcher, clientPath); }
/// <summary> /// new /// </summary> /// <param name="defaultWatcher"></param> public ZookWatcherManager(IWatcher defaultWatcher) { this.DefaultWatcher = defaultWatcher; }
public WatcherExecutionResult(IWatcher watcher, WatcherResultState currentState, WatcherResultState previousState, IWardenCheckResult wardenCheckResult, Exception exception = null) { Watcher = watcher; CurrentState = currentState; PreviousState = previousState; WardenCheckResult = wardenCheckResult; Exception = exception; }
public ScanAsMessageViewModel(IMvxMessenger messenger, IWatcher watcher) { _watcher = watcher; _messageToken = messenger.SubscribeOnMainThread<MessageReceived>(MessageRecieved); }
/// <summary> /// register data watcher /// </summary> /// <param name="watcher"></param> /// <param name="clientPath"></param> public void RegisterDataWatcher(IWatcher watcher, string clientPath) { this.RegisterWatcher(this._dataWatches, watcher, clientPath); }
/// <summary> /// register watcher /// </summary> /// <param name="container"></param> /// <param name="watcher"></param> /// <param name="clientPath"></param> /// <exception cref="ArgumentNullException">container is null</exception> private void RegisterWatcher(Dictionary <string, HashSet <IWatcher> > container, IWatcher watcher, string clientPath) { if (container == null) { throw new ArgumentNullException("container"); } lock (container) { HashSet <IWatcher> set = null; if (!container.TryGetValue(clientPath, out set)) { set = new HashSet <IWatcher>(); container[clientPath] = set; } set.Add(watcher); } }
public void ReConnect(IWatcher watcher) { throw new NotImplementedException(); }
public T GetData <T>(string path, IWatcher watcher, Stat stat) where T : class { var data = GetData(path, watcher, stat); return(_binarySerializer.Deserialize <T>(data)); }
public CleanProcessor(ILog logger, IConfiguration configuration, IWatcher watcher) : base(logger, configuration, watcher) { }
/// <summary> /// The Jones client constructor /// </summary> /// <param name="service">Service Name</param> /// <param name="hostname">Hostname</param> /// <param name="zkclient">Zookeeper Client connection object</param> /// <param name="callback">Callback function for any changes to the config tree</param> public SimpleJonesClient(string service, string hostname = null, IZookClient zkclient = null, Action<Dictionary<string, string>> callback = null) { // initialize the hostname if (String.IsNullOrEmpty(hostname)) { // get FDQN // http://stackoverflow.com/questions/804700/how-to-find-fqdn-of-local-machine-in-c-net // http://support.microsoft.com/kb/303902 HostName = System.Net.Dns.GetHostEntry("LocalHost").HostName.ToLower(); int idx = HostName.IndexOf("."); if (idx > 0) { HostName = HostName.Substring(0, idx); } } if (zkclient != null) { _zkclient = zkclient; } // initialize the dictionary to hold the configurations Config = new Dictionary<string, string>(); // set the service name ServiceName = service; // this is our callback for Config View ZNode changes, to refresh our // this.Config ConfigViewNodeChangeWatcher = new WatcherWrapper(e => { _zkclient.GetData(e.Path, ConfigViewNodeChangeWatcher).ContinueWith(d => { string conf_data = Encoding.UTF8.GetString(d.Result.Data); Config = DeserializeNodeMap(conf_data); if (callback != null) { callback.Invoke(Config); } }); }); NodeMapPath = String.Format(@"/services/{0}/nodemaps", ServiceName); #region get the current Config from the view string current_conf_path = ""; var tnm = _zkclient.GetData(NodeMapPath, false).ContinueWith(c => { string conf_path_json = Encoding.UTF8.GetString(c.Result.Data); try { current_conf_path = DeserializeNodeMap(conf_path_json)[HostName]; } catch (Exception) { // fail-safe default configs when there's no machine-specific config is found current_conf_path = String.Format(@"/services/{0}/conf", ServiceName); } var td = _zkclient.GetData(current_conf_path, ConfigViewNodeChangeWatcher).ContinueWith(d => { // this part is important so this.Config will not be empty on constructor completion! string conf_data = Encoding.UTF8.GetString(d.Result.Data); Config = DeserializeNodeMap(conf_data); }); td.Wait(); // synchronous wait }); tnm.Wait(); // synchronous wait #endregion }
public IWatcher AddWatcher(IWatcher watcher) { throw new System.NotImplementedException(); }
/// <summary> /// register exist watcher /// </summary> /// <param name="watcher"></param> /// <param name="clientPath"></param> public void RegisterExistWatcher(IWatcher watcher, string clientPath) { this.RegisterWatcher(this._existWatches, watcher, clientPath); }
/// <summary> /// Establishes a connection to the ring master server that is being exercised /// by this test. /// </summary> /// <param name="watcher">the watcher</param> /// <returns>A <see cref="RingMasterClient"/> object that represents the connection.</returns> protected virtual RingMasterClient ConnectToRingMaster(IWatcher watcher) { RingMasterClient rm = new RingMasterClient(this.ringMasterAddress, this.clientCertificateThumbprints, this.serverCertificateThumbprints, 40000, watcher); return(rm); }
protected WatcherWrapper(IWatcher watcher) { InternalWatcher = watcher; }
private WatcherResultState GetPreviousWatcherState(IWatcher watcher) { return _latestWatcherResultStates.ContainsKey(watcher) ? _latestWatcherResultStates[watcher] : WatcherResultState.NotSet; }
public void SetWatcher(IWatcher watcher) { this.watcher = watcher; //watcher.setUpdateCallback(this::loadPolicy); }
/// <summary> /// Initializes a new instance of the <see cref="BulkWatcherSpec"/> class. /// </summary> /// <param name="specStr">The spec string.</param> /// <param name="id">The identifier.</param> /// <param name="watcher">The watcher.</param> /// <exception cref="NotImplementedException">If subpath is undefined</exception> public BulkWatcherSpec(string specStr, string id, IWatcher watcher) { this.id = id; this.bulkWatcher = watcher; this.ProcessSpec(specStr); }
public ScanAsMessageViewModel(IMvxMessenger messenger, IWatcher watcher) { _watcher = watcher; _messageToken = messenger.SubscribeOnMainThread <MessageReceived>(MessageRecieved); }
private void InitMaidStatus() { maidStatusWatcher = FieldWatcher.CreateWatcher <Status>(); maidStatusWatcher.OnValueChanged = OnStatusUpdate; bonusStatusField = typeof(Status).GetField("bonusStatus", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); bonusStatusFields = typeof(BonusStatus).GetFields(BindingFlags.Instance | BindingFlags.Public); maidSetters = new Dictionary <string, MethodInfo>(); maidGetters = new Dictionary <string, MethodInfo>(); maidFields = new Dictionary <string, FieldInfo>(); var props = typeof(Status).GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (PropertyInfo propertyInfo in props) { MethodInfo get = propertyInfo.GetGetMethod(); MethodInfo set = propertyInfo.GetSetMethod(); if (get != null && (get.ReturnType.IsPrimitive || get.ReturnType == typeof(string) || get.ReturnType.IsEnum)) { maidGetters.Add(propertyInfo.Name, get); } if (set != null) { maidSetters.Add(propertyInfo.Name, set); } } var fields = typeof(Status).GetFields(BindingFlags.Instance | BindingFlags.Public).Where(f => f.FieldType.IsValueType || f.FieldType.IsEnum || f.FieldType == typeof(string)); foreach (var field in fields) { maidFields[field.Name] = field; } MaidStatusHooks.PropertyChanged += OnPropertyChange; MaidStatusHooks.WorkDataChanged += OnMaidStatusHooksOnWorkDataChanged; MaidStatusHooks.PropFeatureChanged += OnPropFeatureChanged; MaidStatusHooks.OldMaidDeserialized += OnOldMaidDeserialized; MaidStatusHooks.ProprtyShouldChange += CheckPropertyShouldChange; YotogiSkillHooks.SkillInfoChanged += OnYotogiSkillHooksOnSkillInfoChanged; MaidStatusHooks.ThumbnailChanged += (sender, args) => { if (IsDeserializing) { return; } Emit("maid_thumbnail_changed", new Dict { ["guid"] = args.Maid.status.guid, ["thumb"] = args.Maid.GetThumIcon().EncodeToPNG() }); }; }
private async Task <IList <WatcherExecutionResult> > ExecuteWatcherCheckAsync(IWatcher watcher, IWatcherCheckResult watcherCheckResult, IWardenCheckResult wardenCheckResult, WatcherConfiguration watcherConfiguration) { var results = new List <WatcherExecutionResult>(); if (watcherCheckResult.IsValid) { var result = wardenCheckResult; results.Add(new WatcherExecutionResult(watcher, WatcherResultState.Success, GetPreviousWatcherState(watcher), result)); await UpdateWatcherResultStateAndExecuteHooksPossibleAsync(watcher, WatcherResultState.Success, () => InvokeOnFirstSuccessHooksAsync(watcherConfiguration, result), executeIfLatestStateIsNotSet : false); await InvokeOnSuccessHooksAsync(watcherConfiguration, wardenCheckResult); } else { var result = wardenCheckResult; results.Add(new WatcherExecutionResult(watcher, WatcherResultState.Failure, GetPreviousWatcherState(watcher), result)); await UpdateWatcherResultStateAndExecuteHooksPossibleAsync(watcher, WatcherResultState.Failure, () => InvokeOnFirstFailureHooksAsync(watcherConfiguration, result)); await InvokeOnFailureHooksAsync(watcherConfiguration, wardenCheckResult); } return(results); }
public TaskManager(IWatcher watcher) { _watcher = watcher; watcher.ThereIsFileToHandlingEvent += CreateTask; }
private SortedDictionary<long, string> OrderedChildren(IWatcher watcher) { var orderedChildren = new SortedDictionary<long, string>(); foreach (string childName in _zookeeper.GetChildren(_dir, watcher)) { try { bool matches = childName.Length > Prefix.Length && childName.Substring(0, Prefix.Length) == Prefix; if (!matches) { Log.WarnFormat("Found child node with improper name: {0}", childName); continue; } string suffix = childName.Substring(Prefix.Length); long childId = Convert.ToInt64(suffix); orderedChildren[childId] = childName; } catch (InvalidCastException e) { Log.WarnFormat("Found child node with improper format : {0} {1} {2}", childName, e, e.StackTrace); } } return orderedChildren; }
public IZooKeeper NewZooKeeper(String connectString, TimeSpan sessionTimeout, IWatcher watcher, bool canBeReadOnly) { return(new ZooKeeper(connectString, sessionTimeout, watcher)); }
private static void AddWatcherToPool(IWatcher watcher) { TailWatcherPool.Add(watcher); }
/// <summary> /// Factory method for creating a new instance of the IWatcherCheck. /// </summary> /// <param name="watcher"></param> /// <returns></returns> public static IWatcherCheck Create(IWatcher watcher) => new WatcherCheck(watcher);
public DataManager(IWatcher watcher) { Watcher = watcher; }
/// <summary> /// Factory method for creating a new instance of the IWatcherCheckResult. /// </summary> /// <param name="watcher">Instance of IWatcher.</param> /// <param name="isValid">Flag determining whether the performed check was valid.</param> /// <param name="description">Custom description of the performed check.</param> /// <returns>Instance of IWatcherCheckResult.</returns> public static IWatcherCheckResult Create(IWatcher watcher, bool isValid, string description = "") => new WatcherCheckResult(watcher, isValid, description);
/// <summary> /// Registers a bulk watcher for the given path prefix. /// </summary> /// <param name="ringMaster">Interface to ringmaster</param> /// <param name="pathPrefix">Path prefix to watch</param> /// <param name="watcher">The watcher that will be notified of changes that happen under the given path.</param> /// <returns>A <see cref="Task"/> that tracks execution of this method</returns> public static async Task RegisterBulkWatcher(this IRingMasterRequestHandler ringMaster, string pathPrefix, IWatcher watcher) { await ringMaster.Exists(string.Format("bulkwatcher:{0}", pathPrefix), watcher); }
private SortedDictionary<long, string> OrderedChildren(IWatcher watcher) { var orderedChildren = new SortedDictionary<long, string>(); foreach (string childName in zookeeper.GetChildren(dir, watcher)) { try { bool matches = childName.Length > prefix.Length && childName.Substring(0, prefix.Length) == prefix; if (!matches) { LOG.Warn("Found child node with improper name: " + childName); continue; } string suffix = childName.Substring(prefix.Length); long childId = Convert.ToInt64(suffix); orderedChildren[childId] = childName; } catch (InvalidCastException e) { LOG.Warn("Found child node with improper format : " + childName + " " + e, e); } } return orderedChildren; }
protected WatcherCheckResult(IWatcher watcher, bool isValid, string description) : base(watcher) { Description = description; IsValid = isValid; }
public AutoRefreshingWatcher(IWatcher watcher) : base(watcher) { InitBasicPolicies(); }
/// <summary> /// Connects to ZooKeeper server /// </summary> /// <param name="watcher"> /// The watcher to be installed in ZooKeeper. /// </param> public void Connect(IWatcher watcher) { if (this.disposed) { throw new ObjectDisposedException(this.GetType().Name); } lock (this.syncLock) { if (this._zkclient != null) { throw new InvalidOperationException("ZooKeeper client has already been started"); } try { Logger.InfoFormat("Starting ZK client .. with connect handler.. {0}...", watcher.ToString()); this._zkclient = new ZooKeeper(this.Servers, new TimeSpan(0, 0, 0, 0, this.SessionTimeout), watcher);//new ZkClientState(this.Servers, new TimeSpan(0, 0, 0, 0, this.SessionTimeout), watcher); Logger.InfoFormat("Finish start ZK client .. with connect handler.. {0}...", watcher.ToString()); } catch (IOException exc) { throw new ZooKeeperException("Unable to connect to " + this.Servers, exc); } } }
public BlobWatchableValueProvider(ICloudBlob blob, object value, Type valueType, IWatcher watcher) { if (value != null && !valueType.IsAssignableFrom(value.GetType())) { throw new InvalidOperationException("value is not of the correct type."); } _blob = blob; _value = value; _valueType = valueType; _watcher = watcher; }
private async Task<IList<WatcherExecutionResult>> ExecuteWatcherCheckAsync(IWatcher watcher, IWatcherCheckResult watcherCheckResult, IWardenCheckResult wardenCheckResult, WatcherConfiguration watcherConfiguration) { var results = new List<WatcherExecutionResult>(); if (watcherCheckResult.IsValid) { var result = wardenCheckResult; results.Add(new WatcherExecutionResult(watcher, WatcherResultState.Success, GetPreviousWatcherState(watcher), result)); await UpdateWatcherResultStateAndExecuteHooksPossibleAsync(watcher, WatcherResultState.Success, () => InvokeOnFirstSuccessHooksAsync(watcherConfiguration, result), executeIfLatestStateIsNotSet: false); await InvokeOnSuccessHooksAsync(watcherConfiguration, wardenCheckResult); } else { var result = wardenCheckResult; results.Add(new WatcherExecutionResult(watcher, WatcherResultState.Failure, GetPreviousWatcherState(watcher), result)); await UpdateWatcherResultStateAndExecuteHooksPossibleAsync(watcher, WatcherResultState.Failure, () => InvokeOnFirstFailureHooksAsync(watcherConfiguration, result)); await InvokeOnFailureHooksAsync(watcherConfiguration, wardenCheckResult); } return results; }
public static BlobWatchableValueProvider Create <T>(ICloudBlob blob, T value, IWatcher watcher) { return(new BlobWatchableValueProvider(blob, value: value, valueType: typeof(T), watcher: watcher)); }
private async Task UpdateWatcherResultStateAndExecuteHooksPossibleAsync(IWatcher watcher, WatcherResultState state, Func<Task> hooks, bool executeIfLatestStateIsNotSet = true) { var previousState = GetPreviousWatcherState(watcher); if (previousState == state) return; if (previousState == WatcherResultState.NotSet && !executeIfLatestStateIsNotSet) return; _latestWatcherResultStates[watcher] = state; await hooks(); }
protected ZooKeeper CreateClient(IWatcher watcher) { return(new ZooKeeper("127.0.0.1:2181", new TimeSpan(0, 0, 0, 10000), watcher)); }
public Person(IWatcher watcher) { Watcher = watcher; }
public MonitorController(ILogger logger, IWatcher watcher, RestClient restClient) { Logger = logger; Watcher = watcher; RestClient = restClient; }
/// <summary> /// Specify the default watcher for the connection (overrides the one /// specified during construction). /// </summary> /// <param name="watcher">The watcher.</param> public void Register(IWatcher watcher) // the defaultwatcher is already a full fenced so we don't need to mark the method synchronized { watchManager.DefaultWatcher = watcher; }
/// <summary> /// Initializes a new instance of the <see cref="WatchRegistration"/> class. /// </summary> /// <param name="watcher">The watcher.</param> /// <param name="clientPath">The client path.</param> protected WatchRegistration(IWatcher watcher, string clientPath) { this.watcher = watcher; this.clientPath = clientPath; }
/// <summary> /// Factory method for creating a new instance of fluent builder for the WatcherConfiguration. /// </summary> /// <returns>Instance of fluent builder for the WatcherConfiguration.</returns> public static Builder Create(IWatcher watcher) => new Builder(watcher);
public ChildWatchRegistration(ZKWatchManager watchManager, IWatcher watcher, string clientPath) : base(watcher, clientPath) { this.watchManager = watchManager; }
/// <summary> /// Initializes a new instance of the <see cref="RingMaster"/> class. /// To create a RingMaster client object, the application needs to pass a connection string containing a comma separated list of host:port pairs, each corresponding to a ZooKeeper server /// </summary> /// <param name="connectString">The connect string.</param> /// <param name="sessionTimeout">The session timeout.</param> /// <param name="watcher">The watcher.</param> /// <param name="sessionId">The session identifier.</param> /// <param name="sessionPasswd">The session passwd.</param> /// <param name="requestTimeout">Request timeout in millisecond</param> public RingMaster(string connectString, int sessionTimeout, IWatcher watcher, long sessionId = 0, byte[] sessionPasswd = null, int requestTimeout = 15000) : base(connectString, sessionTimeout, watcher, sessionId, sessionPasswd, requestTimeout) { this.transportConfiguration.UseSecureConnection = false; this.transportConfiguration.CommunicationProtocolVersion = RingMasterCommunicationProtocol.MaximumSupportedVersion; }