protected internal override IOperationResult ReadResponse(IPooledSocket socket) { var response = new BinaryResponse(); var retval = response.Read(socket); this.Cas = response.CAS; this.StatusCode = response.StatusCode; var result = new BinaryOperationResult() { Success = retval, Cas = this.Cas, StatusCode = this.StatusCode }; IOperationResult responseResult; if (!(responseResult = this.ProcessResponse(response)).Success) { result.InnerResult = responseResult; responseResult.Combine(result); } return(result); }
var key = BinaryConverter.DecodeKey(data.Array, data.Offset, response.KeyLength); var value = BinaryConverter.DecodeKey(data.Array, data.Offset + response.KeyLength, data.Count - response.KeyLength); serverData[key] = value; } this.result = serverData; this.StatusCode = response.StatusCode; var result = new BinaryOperationResult() { StatusCode = StatusCode }; result.PassOrFail(retval, "Failed to read response"); return result; } Dictionary<string, string> IStatsOperation.Result { get { return this.result; } } } } #region [ License information ] /* ************************************************************ *
public unsafe bool Read(IPooledSocket socket) { this.StatusCode = -1; if (!socket.IsAlive) return false; var header = new byte[HeaderLength]; socket.Read(header, 0, header.Length); int dataLength, extraLength; DeserializeHeader(header, out dataLength, out extraLength); if (dataLength > 0) { var data = new byte[dataLength]; socket.Read(data, 0, dataLength); this.Extra = new ArraySegment<byte>(data, 0, extraLength); this.Data = new ArraySegment<byte>(data, extraLength, data.Length - extraLength); } return this.StatusCode == 0; }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { var retval = new Dictionary <string, CacheItem>(); var cas = new Dictionary <string, ulong>(); try { GetResponse r; while ((r = GetHelper.ReadItem(socket)) != null) { var key = r.Key; retval[key] = r.Item; cas[key] = r.CasValue; } } catch (NotSupportedException) { throw; } catch (Exception e) { log.Error(e); } this.result = retval; this.Cas = cas; return(new TextOperationResult().Pass()); }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { var response = new BinaryResponse(); var serverData = new Dictionary <string, string>(); var retval = false; while (response.Read(socket) && response.KeyLength > 0) { retval = true; var data = response.Data; var key = BinaryConverter.DecodeKey(data.Array, data.Offset, response.KeyLength); var value = BinaryConverter.DecodeKey(data.Array, data.Offset + response.KeyLength, data.Count - response.KeyLength); serverData[key] = value; } this.result = serverData; this.StatusCode = response.StatusCode; var result = new BinaryOperationResult() { StatusCode = StatusCode }; result.PassOrFail(retval, "Failed to read response"); return(result); }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { return(new TextOperationResult { Success = String.Compare(TextSocketHelper.ReadResponse(socket), "DELETED", StringComparison.Ordinal) == 0 }); }
public bool ExecuteAsync(IOperation op, Action <bool> next) { IPooledSocket socket = null; var result = false; try { socket = _pool.Acquire(); var buffers = op.GetBuffer(); socket.Write(buffers); result = op.ReadResponseAsync(socket, readSuccess => { socket.Dispose(); next(readSuccess); }); } catch (IOException e) { Log.Error(e); } finally { if (socket != null) { _pool.Release(socket); } } return(result); }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { var retval = new Dictionary<string, CacheItem>(); var cas = new Dictionary<string, ulong>(); try { GetResponse r; while ((r = GetHelper.ReadItem(socket)) != null) { var key = r.Key; retval[key] = r.Item; cas[key] = r.CasValue; } } catch (NotSupportedException) { throw; } catch (Exception e) { log.Error(e); } this.result = retval; this.Cas = cas; return new TextOperationResult().Pass(); }
/// <summary> /// Implements memcached's SASL auth sequence. (See the protocol docs for more details.) /// </summary> /// <param name="socket"></param> /// <returns></returns> private bool Auth(IPooledSocket socket) { SaslStep currentStep = new SaslStart(this.authenticationProvider); socket.Write(currentStep.GetBuffer()); while (!currentStep.ReadResponse(socket).Success) { // challenge-response authentication if (currentStep.StatusCode == 0x21) { currentStep = new SaslContinue(this.authenticationProvider, currentStep.Data); socket.Write(currentStep.GetBuffer()); } else { if (log.IsWarnEnabled) log.WarnFormat("Authentication failed, return code: 0x{0:x}", currentStep.StatusCode); // invalid credentials or other error return false; } } return true; }
/// <summary> /// Reads the response from the socket asynchronously. /// </summary> /// <param name="socket">The socket to read from.</param> /// <param name="next">The delegate whihc will continue processing the response. This is only called if the read completes asynchronoulsy.</param> /// <param name="ioPending">Set totrue if the read is still pending when ReadASync returns. In this case 'next' will be called when the read is finished.</param> /// <returns> /// If the socket is already dead, ReadAsync returns false, next is not called, ioPending = false /// If the read completes synchronously (e.g. data is received from the buffer), it returns true/false depending on the StatusCode, and ioPending is set to true, 'next' will not be called. /// It returns true if it has to read from the socket, so the operation will complate asynchronously at a later time. ioPending will be true, and 'next' will be called to handle the data /// </returns> public bool ReadAsync(IPooledSocket socket, Action <bool> next, out bool ioPending) { this.StatusCode = -1; this.currentSocket = socket; this.next = next; var asyncEvent = new AsyncIOArgs(); asyncEvent.Count = HeaderLength; asyncEvent.Next = this.DoDecodeHeaderAsync; this.shouldCallNext = true; if (socket.ReceiveAsync(asyncEvent)) { ioPending = true; return(true); } ioPending = false; this.shouldCallNext = false; return(asyncEvent.Fail ? false : this.DoDecodeHeader(asyncEvent, out ioPending)); }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { return new TextOperationResult { Success = String.Compare(TextSocketHelper.ReadResponse(socket), "DELETED", StringComparison.Ordinal) == 0 }; }
public unsafe bool Read(IPooledSocket socket) { this.StatusCode = -1; if (!socket.IsAlive) { return(false); } var header = new byte[HeaderLength]; socket.Read(header, 0, header.Length); int dataLength, extraLength; DeserializeHeader(header, out dataLength, out extraLength); if (dataLength > 0) { var data = new byte[dataLength]; socket.Read(data, 0, dataLength); this.Extra = new ArraySegment <byte>(data, 0, extraLength); this.Data = new ArraySegment <byte>(data, extraLength, data.Length - extraLength); } return(this.StatusCode == 0); }
/// <summary> /// Implements memcached's SASL auth sequence. (See the protocol docs for more details.) /// </summary> /// <param name="socket"></param> /// <returns></returns> private bool Auth(IPooledSocket socket) { SaslStep currentStep = new SaslStart(this.authenticationProvider); socket.Write(currentStep.GetBuffer()); while (!currentStep.ReadResponse(socket).Success) { // challenge-response authentication if (currentStep.StatusCode == 0x21) { currentStep = new SaslContinue(this.authenticationProvider, currentStep.Data); socket.Write(currentStep.GetBuffer()); } else { if (log.IsWarnEnabled) { log.WarnFormat("Authentication failed, return code: 0x{0:x}", currentStep.StatusCode); } // invalid credentials or other error return(false); } } return(true); }
public static void FinishCurrent(IPooledSocket socket) { string response = TextSocketHelper.ReadResponse(socket); if (String.Compare(response, "END", StringComparison.Ordinal) != 0) throw new MemcachedClientException("No END was received."); }
/// <summary> /// Reads the response of the server. /// </summary> /// <returns>The data sent by the memcached server.</returns> /// <exception cref="T:System.InvalidOperationException">The server did not sent a response or an empty line was returned.</exception> /// <exception cref="T:Enyim.Caching.Memcached.MemcachedException">The server did not specified any reason just returned the string ERROR. - or - The server returned a SERVER_ERROR, in this case the Message of the exception is the message returned by the server.</exception> /// <exception cref="T:Enyim.Caching.Memcached.MemcachedClientException">The server did not recognize the request sent by the client. The Message of the exception is the message returned by the server.</exception> public static string ReadResponse(IPooledSocket socket) { string response = TextSocketHelper.ReadLine(socket); if (log.IsDebugEnabled) log.Debug("Received response: " + response); if (String.IsNullOrEmpty(response)) throw new MemcachedClientException("Empty response received."); if (String.Compare(response, GenericErrorResponse, StringComparison.Ordinal) == 0) throw new NotSupportedException("Operation is not supported by the server or the request was malformed. If the latter please report the bug to the developers."); if (response.Length >= ErrorResponseLength) { if (String.Compare(response, 0, ClientErrorResponse, 0, ErrorResponseLength, StringComparison.Ordinal) == 0) { throw new MemcachedClientException(response.Remove(0, ErrorResponseLength)); } else if (String.Compare(response, 0, ServerErrorResponse, 0, ErrorResponseLength, StringComparison.Ordinal) == 0) { throw new MemcachedException(response.Remove(0, ErrorResponseLength)); } } return response; }
/// <summary> /// Reads the response of the server. /// </summary> /// <returns>The data sent by the memcached server.</returns> /// <exception cref="T:System.InvalidOperationException">The server did not sent a response or an empty line was returned.</exception> /// <exception cref="T:Enyim.Caching.Memcached.MemcachedException">The server did not specified any reason just returned the string ERROR. - or - The server returned a SERVER_ERROR, in this case the Message of the exception is the message returned by the server.</exception> /// <exception cref="T:Enyim.Caching.Memcached.MemcachedClientException">The server did not recognize the request sent by the client. The Message of the exception is the message returned by the server.</exception> public static string ReadResponse(IPooledSocket socket) { string response = TextSocketHelper.ReadLine(socket); if (log.IsDebugEnabled) { log.Debug("Received response: " + response); } if (String.IsNullOrEmpty(response)) { throw new MemcachedClientException("Empty response received."); } if (String.Compare(response, GenericErrorResponse, StringComparison.Ordinal) == 0) { throw new NotSupportedException("Operation is not supported by the server or the request was malformed. If the latter please report the bug to the developers."); } if (response.Length >= ErrorResponseLength) { if (String.Compare(response, 0, ClientErrorResponse, 0, ErrorResponseLength, StringComparison.Ordinal) == 0) { throw new MemcachedClientException(response.Remove(0, ErrorResponseLength)); } else if (String.Compare(response, 0, ServerErrorResponse, 0, ErrorResponseLength, StringComparison.Ordinal) == 0) { throw new MemcachedException(response.Remove(0, ErrorResponseLength)); } } return(response); }
public static void FinishCurrent(IPooledSocket socket) { string response = TextSocketHelper.ReadResponse(socket); if (String.Compare(response, "END", StringComparison.Ordinal) != 0) { throw new MemcachedClientException("No END was received."); } }
public IPooledSocket Acquire() { IPooledSocket socket = null; lock (_syncObj) { while (_queue.Count == 0) { if (_refs.Count() < _config.MaxPoolSize) { _queue.Enqueue(Create()); break; } if (!Monitor.Wait(_syncObj, _config.QueueTimeout)) { break; } } try { socket = _queue.Dequeue(); socket.IsInUse = true; } catch (InvalidOperationException e) { var sb = new StringBuilder(); sb.AppendFormat("Timeout occured while waiting for a socket on {0}.", _node.EndPoint); sb.AppendFormat("Your current configuration for queueTmeout is {0}{1}", _config.QueueTimeout, Environment.NewLine); sb.AppendFormat("Your current configuration for maxPoolSize is {0}{1}", _config.MaxPoolSize, Environment.NewLine); sb.AppendLine("Try increasing queueTimeout or increasing using maxPoolSize in your configuration."); throw new QueueTimeoutException(sb.ToString(), e); } try { if (!socket.IsAlive && (!_shutDownMode || _disposed)) { socket.Close(); socket = Create(); socket.IsInUse = true; } } catch (Exception) { Release(socket); throw; } if (_shutDownMode) { var msg = String.Format("SocketPool for node {0} has shutdown.", _node.EndPoint); throw new NodeShutdownException(msg); } Interlocked.Increment(ref _outCount); return(socket); } }
public void Close(IPooledSocket socket) { if (Log.IsDebugEnabled) { Log.DebugFormat("Closing socket Id={0} on {1}", socket.InstanceId, _node.EndPoint); } socket.Close(); }
public static GetResponse ReadItem(IPooledSocket socket) { string description = TextSocketHelper.ReadResponse(socket); if (String.Compare(description, "END", StringComparison.Ordinal) == 0) { return(null); } if (description.Length < 6 || String.Compare(description, 0, "VALUE ", 0, 6, StringComparison.Ordinal) != 0) { throw new MemcachedClientException("No VALUE response received.\r\n" + description); } ulong cas = 0; string[] parts = description.Split(' '); // response is: // VALUE <key> <flags> <bytes> [<cas unique>] // 0 1 2 3 4 // // cas only exists in 1.2.4+ // if (parts.Length == 5) { if (!UInt64.TryParse(parts[4], out cas)) { throw new MemcachedClientException("Invalid CAS VALUE received."); } } else if (parts.Length < 4) { throw new MemcachedClientException("Invalid VALUE response received: " + description); } ushort flags = UInt16.Parse(parts[2], CultureInfo.InvariantCulture); int length = Int32.Parse(parts[3], CultureInfo.InvariantCulture); byte[] allData = new byte[length]; byte[] eod = new byte[2]; socket.Read(allData, 0, length); socket.Read(eod, 0, 2); // data is terminated by \r\n GetResponse retval = new GetResponse(parts[1], flags, cas, allData); if (log.IsDebugEnabled) { log.DebugFormat("Received value. Data type: {0}, size: {1}.", retval.Item.Flags, retval.Item.Data.Count); } return(retval); }
protected internal override bool ReadResponseAsync(IPooledSocket socket, Action <bool> next) { this.result = new Dictionary <string, CacheItem>(); this.Cas = new Dictionary <string, ulong>(); this.currentSocket = socket; this.asyncReader = new BinaryResponse(); this.asyncLoopState = null; this.afterAsyncRead = next; return(this.DoReadAsync()); }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { string response = TextSocketHelper.ReadResponse(socket); var result = new TextOperationResult(); //maybe we should throw an exception when the item is not found? if (String.Compare(response, "NOT_FOUND", StringComparison.Ordinal) == 0) return result.Fail("Failed to read response. Item not found"); result.Success = UInt64.TryParse(response, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture, out this.result); return result; }
public void Release(IPooledSocket socket) { lock (_syncObj) { Interlocked.Decrement(ref _outCount); socket.IsInUse = false; if ((_disposed || _shutDownMode) && socket.IsAlive) { socket.Close(); } _queue.Enqueue(socket); Monitor.PulseAll(_syncObj); } }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { GetResponse r = GetHelper.ReadItem(socket); var result = new TextOperationResult(); if (r == null) return result.Fail("Failed to read response"); this.result = r.Item; this.Cas = r.CasValue; GetHelper.FinishCurrent(socket); return result.Pass(); }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { var response = new BinaryResponse(); var retval = response.Read(socket); this.StatusCode = StatusCode; var result = new BinaryOperationResult() { Success = retval, StatusCode = this.StatusCode }; result.PassOrFail(retval, "Failed to read response"); return(result); }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { var response = new BinaryResponse(); var retval = response.Read(socket); this.StatusCode = StatusCode; var result = new BinaryOperationResult() { Success = retval, StatusCode = this.StatusCode }; result.PassOrFail(retval, "Failed to read response"); return result; }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { string response = TextSocketHelper.ReadResponse(socket); var result = new TextOperationResult(); //maybe we should throw an exception when the item is not found? if (String.Compare(response, "NOT_FOUND", StringComparison.Ordinal) == 0) { return(result.Fail("Failed to read response. Item not found")); } result.Success = UInt64.TryParse(response, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture, out this.result); return(result); }
/// <summary> /// Releases an item back into the pool /// </summary> /// <param name="socket"></param> private void ReleaseSocket(IPooledSocket socket) { if (log.IsDebugEnabled) { log.Debug("Releasing socket " + socket.InstanceId); log.Debug("Are we alive? " + this.isAlive); } if (this.isAlive) { // is it still working (i.e. the server is still connected) if (socket.IsAlive) { // mark the item as free this.freeItems.Push(socket); } else { // kill this item //socket.Destroy(); socket.Dispose(); // mark ourselves as not working for a while this.MarkAsDead(); } } else { // one of our previous sockets has died, so probably all of them // are dead. so, kill the socket (this will eventually clear the pool as well) //socket.Destroy(); socket.Dispose(); } // In any event, we want to let any waiters know that we can create a new // socket: if (semaphore != null) { try { semaphore.Release(); } catch (ObjectDisposedException e) { log.Error(e); } } }
protected override IOperationResult ReadResponse(IPooledSocket socket) { var response = new BinaryResponse(); var result = new BinaryOperationResult(); if (response.Read(socket)) { this.Result = DecodeResult(response.Data); result.Pass(); return(result); } result.Fail("Processing of response failed"); return(result); }
public static GetResponse ReadItem(IPooledSocket socket) { string description = TextSocketHelper.ReadResponse(socket); if (String.Compare(description, "END", StringComparison.Ordinal) == 0) return null; if (description.Length < 6 || String.Compare(description, 0, "VALUE ", 0, 6, StringComparison.Ordinal) != 0) throw new MemcachedClientException("No VALUE response received.\r\n" + description); ulong cas = 0; string[] parts = description.Split(' '); // response is: // VALUE <key> <flags> <bytes> [<cas unique>] // 0 1 2 3 4 // // cas only exists in 1.2.4+ // if (parts.Length == 5) { if (!UInt64.TryParse(parts[4], out cas)) throw new MemcachedClientException("Invalid CAS VALUE received."); } else if (parts.Length < 4) { throw new MemcachedClientException("Invalid VALUE response received: " + description); } ushort flags = UInt16.Parse(parts[2], CultureInfo.InvariantCulture); int length = Int32.Parse(parts[3], CultureInfo.InvariantCulture); byte[] allData = new byte[length]; byte[] eod = new byte[2]; socket.Read(allData, 0, length); socket.Read(eod, 0, 2); // data is terminated by \r\n GetResponse retval = new GetResponse(parts[1], flags, cas, allData); if (log.IsDebugEnabled) log.DebugFormat("Received value. Data type: {0}, size: {1}.", retval.Item.Flags, retval.Item.Data.Count); return retval; }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { GetResponse r = GetHelper.ReadItem(socket); var result = new TextOperationResult(); if (r == null) { return(result.Fail("Failed to read response")); } this.result = r.Item; this.Cas = r.CasValue; GetHelper.FinishCurrent(socket); return(result.Pass()); }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { var serverData = new Dictionary <string, string>(); while (true) { string line = TextSocketHelper.ReadResponse(socket); // stat values are terminated by END if (String.Compare(line, "END", StringComparison.Ordinal) == 0) { break; } // expected response is STAT item_name item_value if (line.Length < 6 || String.Compare(line, 0, "STAT ", 0, 5, StringComparison.Ordinal) != 0) { if (log.IsWarnEnabled) { log.Warn("Unknow response: " + line); } continue; } // get the key&value string[] parts = line.Remove(0, 5).Split(' '); if (parts.Length != 2) { if (log.IsWarnEnabled) { log.Warn("Unknow response: " + line); } continue; } // store the stat item serverData[parts[0]] = parts[1]; } this.result = serverData; return(new TextOperationResult().Pass()); }
/// <summary> /// Reads a line from the socket. A line is terninated by \r\n. /// </summary> /// <returns></returns> private static string ReadLine(IPooledSocket socket) { MemoryStream ms = new MemoryStream(50); bool gotR = false; //byte[] buffer = new byte[1]; int data; while (true) { data = socket.ReadByte(); if (data == 13) { gotR = true; continue; } if (gotR) { if (data == 10) { break; } ms.WriteByte(13); gotR = false; } ms.WriteByte((byte)data); } string retval = Encoding.ASCII.GetString(ms.GetBuffer(), 0, (int)ms.Length); if (log.IsDebugEnabled) { log.Debug("ReadLine: " + retval); } return(retval); }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { this.result = new Dictionary <string, CacheItem>(); this.Cas = new Dictionary <string, ulong>(); var result = new TextOperationResult(); var response = new BinaryResponse(); while (response.Read(socket)) { this.StatusCode = response.StatusCode; // found the noop, quit if (response.CorrelationId == this.noopId) { return(result.Pass()); } string key; // find the key to the response if (!this.idToKey.TryGetValue(response.CorrelationId, out key)) { // we're not supposed to get here tho log.WarnFormat("Found response with CorrelationId {0}, but no key is matching it.", response.CorrelationId); continue; } if (log.IsDebugEnabled) { log.DebugFormat("Reading item {0}", key); } // deserialize the response int flags = BinaryConverter.DecodeInt32(response.Extra, 0); this.result[key] = new CacheItem((ushort)flags, response.Data); this.Cas[key] = response.CAS; } // finished reading but we did not find the NOOP return(result.Fail("Found response with CorrelationId {0}, but no key is matching it.")); }
protected override bool ReadResponseAsync(IPooledSocket socket, Action <bool> next) { var response = new BinaryResponse(); bool ioPending; var retval = response.ReadAsync(socket, (readSuccess) => { if (readSuccess) { this.DecodeResult(response.Data); } next(readSuccess); }, out ioPending); if (!ioPending && retval) { this.Result = this.DecodeResult(response.Data); } return(retval); }
public unsafe bool Read(IPooledSocket socket) { this.StatusCode = -1; if (!socket.IsAlive) { return(false); } var header = new byte[HeaderLength]; socket.Read(header, 0, header.Length); int dataLength, extraLength; DeserializeHeader(header, out dataLength, out extraLength); var keyHeader = new byte[4]; socket.Read(keyHeader, 0, 4); var vbucket = BinaryConverter.DecodeUInt16(keyHeader, 0); var keylen = BinaryConverter.DecodeUInt16(keyHeader, 2); var keyData = new byte[keylen]; socket.Read(keyData, 0, keylen); Key = BinaryConverter.DecodeKey(keyData); var keyStateData = new byte[1]; socket.Read(keyStateData, 0, keyStateData.Length); KeyState = (ObserveKeyState)keyStateData[0]; var casData = new byte[8]; socket.Read(casData, 0, casData.Length); Cas = BinaryConverter.DecodeUInt64(casData, 0); return(this.StatusCode == 0); }
protected override IOperationResult ReadResponse(IPooledSocket socket) { var response = new ObserveResponse(); var result = new ObserveOperationResult(); var retval = false; if (response.Read(socket)) { retval = true; result.Cas = response.Cas; result.StatusCode = StatusCode; result.Key = response.Key; result.KeyState = response.KeyState; result.PersistenceStats = response.PersistenceStats; result.ReplicationStats = response.ReplicationStats; } this.StatusCode = response.StatusCode; result.PassOrFail(retval, ResultHelper.ProcessResponseData(response.Data, "Failed: ")); return(result); }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { var serverData = new Dictionary<string, string>(); while (true) { string line = TextSocketHelper.ReadResponse(socket); // stat values are terminated by END if (String.Compare(line, "END", StringComparison.Ordinal) == 0) break; // expected response is STAT item_name item_value if (line.Length < 6 || String.Compare(line, 0, "STAT ", 0, 5, StringComparison.Ordinal) != 0) { if (log.IsWarnEnabled) log.Warn("Unknow response: " + line); continue; } // get the key&value string[] parts = line.Remove(0, 5).Split(' '); if (parts.Length != 2) { if (log.IsWarnEnabled) log.Warn("Unknow response: " + line); continue; } // store the stat item serverData[parts[0]] = parts[1]; } this.result = serverData; return new TextOperationResult().Pass(); }
protected override IOperationResult ReadResponse(IPooledSocket socket) { var response = new ObserveResponse(); var result = new ObserveOperationResult(); var retval = false; if (response.Read(socket)) { retval = true; result.Cas = response.Cas; result.StatusCode = StatusCode; result.Key = response.Key; result.KeyState = response.KeyState; result.PersistenceStats = response.PersistenceStats; result.ReplicationStats = response.ReplicationStats; } this.StatusCode = response.StatusCode; result.PassOrFail(retval, ResultHelper.ProcessResponseData(response.Data, "Failed: ")); return result; }
bool Authenticate(IPooledSocket socket) { var isAuthenticated = true; const int authContinue = 0x21; SaslStep step = new SaslStart(_provider); socket.Write(step.GetBuffer()); while (!step.ReadResponse(socket).Success) { if (step.StatusCode == authContinue) { step = new SaslContinue(_provider, step.Data); socket.Write(step.GetBuffer()); } else { isAuthenticated = false; break; } } return(isAuthenticated); }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { var response = new BinaryResponse(); var retval = response.Read(socket); this.Cas = response.CAS; this.StatusCode = response.StatusCode; var result = new BinaryOperationResult() { Success = retval, Cas = this.Cas, StatusCode = this.StatusCode }; IOperationResult responseResult; if (! (responseResult = this.ProcessResponse(response)).Success) { result.InnerResult = responseResult; responseResult.Combine(result); } return result; }
/// <summary> /// Reads a line from the socket. A line is terninated by \r\n. /// </summary> /// <returns></returns> private static string ReadLine(IPooledSocket socket) { MemoryStream ms = new MemoryStream(50); bool gotR = false; //byte[] buffer = new byte[1]; int data; while (true) { data = socket.ReadByte(); if (data == 13) { gotR = true; continue; } if (gotR) { if (data == 10) break; ms.WriteByte(13); gotR = false; } ms.WriteByte((byte)data); } string retval = Encoding.ASCII.GetString(ms.GetBuffer(), 0, (int)ms.Length); if (log.IsDebugEnabled) log.Debug("ReadLine: " + retval); return retval; }
IOperationResult IOperation.ReadResponse(IPooledSocket socket) { return this.ReadResponse(socket); }
/// <summary> /// Acquires a new item from the pool /// </summary> /// <returns>An <see cref="T:PooledSocket"/> instance which is connected to the memcached server, or <value>null</value> if the pool is dead.</returns> public IPooledSocketResult Acquire() { var result = new PooledSocketResult(); var message = string.Empty; bool hasDebug = log.IsDebugEnabled; if (hasDebug) { log.Debug("Acquiring stream from pool. " + this.endPoint); } if (!this.isAlive || this.isDisposed) { message = "Pool is dead or disposed, returning null. " + this.endPoint; result.Fail(message); if (hasDebug) { log.Debug(message); } return(result); } IPooledSocket retval = null; if (!this.semaphore.WaitOne(this.queueTimeout)) { message = "Pool is full, timeouting. " + this.endPoint; if (hasDebug) { log.Debug(message); } result.Fail(message, new TimeoutException()); result.StatusCode = (int)StatusCode.SocketPoolTimeout; // everyone is so busy return(result); } // maybe we died while waiting if (!this.isAlive) { message = "Pool is dead, returning null. " + this.endPoint; if (hasDebug) { log.Debug(message); } result.Fail(message); return(result); } // do we have free items? if (this.freeItems.TryPop(out retval)) { #region [ get it from the pool ] try { retval.Reset(); message = "Socket was reset. " + retval.InstanceId; if (hasDebug) { log.Debug(message); } result.Pass(message); result.Value = retval; return(result); } catch (Exception e) { message = "Failed to reset an acquired socket."; log.Error(message, e); this.MarkAsDead(); result.Fail(message, e); return(result); } #endregion } // free item pool is empty message = "Could not get a socket from the pool, Creating a new item. " + this.endPoint; if (hasDebug) { log.Debug(message); } try { // okay, create the new item retval = this.CreateSocket(); result.Value = retval; result.Pass(); } catch (Exception e) { message = "Failed to create socket. " + this.endPoint; log.Error(message, e); // eventhough this item failed the failure policy may keep the pool alive // so we need to make sure to release the semaphore, so new connections can be // acquired or created (otherwise dead conenctions would "fill up" the pool // while the FP pretends that the pool is healthy) semaphore.Release(); this.MarkAsDead(); result.Fail(message); return(result); } if (hasDebug) { log.Debug("Done."); } return(result); }
bool IOperation.ReadResponseAsync(IPooledSocket socket, Action<bool> next) { return this.ReadResponseAsync(socket, next); }
protected internal abstract IOperationResult ReadResponse(IPooledSocket socket);
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { this.result = new Dictionary<string, CacheItem>(); this.Cas = new Dictionary<string, ulong>(); var result = new TextOperationResult(); var response = new BinaryResponse(); while (response.Read(socket)) { this.StatusCode = response.StatusCode; // found the noop, quit if (response.CorrelationId == this.noopId) return result.Pass(); string key; // find the key to the response if (!this.idToKey.TryGetValue(response.CorrelationId, out key)) { // we're not supposed to get here tho log.WarnFormat("Found response with CorrelationId {0}, but no key is matching it.", response.CorrelationId); continue; } if (log.IsDebugEnabled) log.DebugFormat("Reading item {0}", key); // deserialize the response int flags = BinaryConverter.DecodeInt32(response.Extra, 0); this.result[key] = new CacheItem((ushort)flags, response.Data); this.Cas[key] = response.CAS; } // finished reading but we did not find the NOOP return result.Fail("Found response with CorrelationId {0}, but no key is matching it."); }
bool Authenticate(IPooledSocket socket) { var isAuthenticated = true; const int authContinue = 0x21; SaslStep step = new SaslStart(_provider); socket.Write(step.GetBuffer()); while (!step.ReadResponse(socket).Success) { if (step.StatusCode == authContinue) { step = new SaslContinue(_provider, step.Data); socket.Write(step.GetBuffer()); } else { isAuthenticated = false; break; } } return isAuthenticated; }
public void Close(IPooledSocket socket) { if (Log.IsDebugEnabled) { Log.DebugFormat("Closing socket Id={0} on {1}", socket.InstanceId, _node.EndPoint); } socket.Close(); }
protected override bool ReadResponseAsync(IPooledSocket socket, Action<bool> next) { var response = new BinaryResponse(); bool ioPending; var retval = response.ReadAsync(socket, (readSuccess) => { if (readSuccess) this.DecodeResult(response.Data); next(readSuccess); }, out ioPending); if (!ioPending && retval) this.Result = this.DecodeResult(response.Data); return retval; }
protected internal override bool ReadResponseAsync(IPooledSocket socket, System.Action <bool> next) { throw new System.NotSupportedException(); }
protected override IOperationResult ReadResponse(IPooledSocket socket) { var response = new BinaryResponse(); var result = new BinaryOperationResult(); if (response.Read(socket)) { this.Result = DecodeResult(response.Data); result.Pass(); return result; } result.Fail("Processing of response failed"); return result; }
public unsafe bool Read(IPooledSocket socket) { this.StatusCode = -1; if (!socket.IsAlive) return false; var header = new byte[HeaderLength]; socket.Read(header, 0, header.Length); int dataLength, extraLength; DeserializeHeader(header, out dataLength, out extraLength); var keyHeader = new byte[4]; socket.Read(keyHeader, 0, 4); var vbucket = BinaryConverter.DecodeUInt16(keyHeader, 0); var keylen = BinaryConverter.DecodeUInt16(keyHeader, 2); var keyData = new byte[keylen]; socket.Read(keyData, 0, keylen); Key = BinaryConverter.DecodeKey(keyData); var keyStateData = new byte[1]; socket.Read(keyStateData, 0, keyStateData.Length); KeyState = (ObserveKeyState)keyStateData[0]; var casData = new byte[8]; socket.Read(casData, 0, casData.Length); Cas = BinaryConverter.DecodeUInt64(casData, 0); return this.StatusCode == 0; }
protected internal override bool ReadResponseAsync(IPooledSocket socket, Action<bool> next) { throw new NotImplementedException(); }
public void Release(IPooledSocket socket) { lock (_syncObj) { Interlocked.Decrement(ref _outCount); socket.IsInUse = false; if ((_disposed || _shutDownMode) && socket.IsAlive) { socket.Close(); } _queue.Enqueue(socket); Monitor.PulseAll(_syncObj); } }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { TextSocketHelper.ReadResponse(socket); return new TextOperationResult().Pass(); }
protected internal override bool ReadResponseAsync(IPooledSocket socket, System.Action<bool> next) { throw new System.NotSupportedException(); }
protected internal override bool ReadResponseAsync(IPooledSocket socket, Action<bool> next) { this.result = new Dictionary<string, CacheItem>(); this.Cas = new Dictionary<string, ulong>(); this.currentSocket = socket; this.asyncReader = new BinaryResponse(); this.asyncLoopState = null; this.afterAsyncRead = next; return this.DoReadAsync(); }
protected internal abstract bool ReadResponseAsync(IPooledSocket socket, Action<bool> next);
/// <summary> /// Reads the response. /// </summary> /// <param name="step">The current SaslStep.</param> /// <param name="socket">The socket.to read from.</param> /// <returns></returns> public static IOperationResult ReadResponse(this SaslStep step, IPooledSocket socket) { return(step.ReadResponse(socket)); }