示例#1
0
        /// <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(PooledSocket 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;
        }
示例#2
0
		protected internal override IOperationResult ReadResponse(PooledSocket 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;
		}
示例#3
0
        public override void ReadFrom(PooledSocket socket)
        {
            var replies = new List<RedisValue>();
            if (Transactional)
            {
                _multi.ReadFrom(socket);  // OK

                for (int i = 0; i < _commands.Count; i++)
                {
                    // read "QUEUED"
                    var status = socket.ExpectSingleLineReply();
                }
                // The result is a multi-bulk, so
                // consume the count of returned items
                var count = socket.ExpectMultiBulkCount();
                if (count != _commands.Count)
                    throw new RedisClientException(
                        String.Format("Invalid number of bulk responses. Expected {0}, Got {1}", _commands.Count, count));
            }

            foreach (var command in _commands)
            {
                command.ReadFrom(socket);
                replies.Add(command.Value);
            }
            this.Value = new RedisValue(){Type = RedisValueType.MultiBulk, MultiBulkValues =replies.ToArray()};   
        }
		/// <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(PooledSocket 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);
		}
		/// <summary>
		/// Implements memcached's SASL auth sequence. (See the protocol docs for more details.)
		/// </summary>
		/// <param name="socket"></param>
		/// <returns></returns>
		private bool Auth(PooledSocket socket)
		{
			SaslStep currentStep = new SaslStart(this.authenticationProvider);

			socket.Write(currentStep.GetBuffer());

			while (!currentStep.ReadResponse(socket))
			{
				// 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;
		}
		protected internal override IOperationResult ReadResponse(PooledSocket socket)
		{
			return new TextOperationResult
			{
				Success = String.Compare(TextSocketHelper.ReadResponse(socket), "STORED", StringComparison.Ordinal) == 0
			};
		}
示例#7
0
        public unsafe bool Read(PooledSocket 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;
        }
示例#8
0
		protected internal override IOperationResult ReadResponse(PooledSocket 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 bool ReadResponse(PooledSocket socket)
        {
            this.result = new Dictionary<string, CacheItem>();
            this.Cas = new Dictionary<string, ulong>();

            var response = new BinaryResponse();

            while (response.Read(socket))
            {
                // found the noop, quit
                if (response.CorrelationId == this.noopId)
                    return true;

                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 false;
        }
示例#10
0
		public static void FinishCurrent(PooledSocket socket)
		{
			string response = TextSocketHelper.ReadResponse(socket);

			if (String.Compare(response, "END", StringComparison.Ordinal) != 0)
				throw new MemcachedClientException("No END was received.");
		}
        protected internal override bool ReadResponse(PooledSocket socket)
        {
            var response = new BinaryResponse();
            var retval = response.Read(socket);
            this.Cas = response.CAS;

            return retval & this.ProcessResponse(response);
        }
示例#12
0
        protected internal override bool ReadResponse(PooledSocket socket)
        {
            var response = new BinaryResponse();
            var retval = response.Read(socket);

            this.StatusCode = StatusCode;

            return retval;
        }
示例#13
0
        public override void WriteTo(PooledSocket socket)
        {
            new MultiCommand().WriteTo(socket);

            foreach (var command in _commands)
            {
                command.WriteTo(socket);
            }
            new ExecCommand().WriteTo(socket);                    
        }
示例#14
0
        protected internal override bool ReadResponse(PooledSocket socket)
        {
            string response = TextSocketHelper.ReadResponse(socket);

            //maybe we should throw an exception when the item is not found?
            if (String.Compare(response, "NOT_FOUND", StringComparison.Ordinal) == 0)
                return false;

            return UInt64.TryParse(response, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture, out this.result);
        }
		public unsafe bool Read(PooledSocket socket)
		{
			if (!socket.IsAlive)
			{
				this.StatusCode = -1;
				return false;
			}

			byte[] header = new byte[24];
			socket.Read(header, 0, 24);
#if DEBUG_PROTOCOL
			if (log.IsDebugEnabled)
			{
				log.Debug("Received binary response");

				StringBuilder sb = new StringBuilder(128).AppendLine();

				for (int i = 0; i < header.Length; i++)
				{
					byte value = header[i];
					sb.Append(value < 16 ? "0x0" : "0x").Append(value.ToString("X"));

					if (i % 4 == 3) sb.AppendLine(); else sb.Append(" ");
				}

				log.Debug(sb.ToString());
			}
#endif

			fixed (byte* buffer = header)
			{
				if (buffer[0] != MAGIC_VALUE)
					throw new InvalidOperationException("Expected magic value " + MAGIC_VALUE + ", received: " + buffer[0]);

				int remaining = BinaryConverter.DecodeInt32(buffer, HEADER_BODY);
				int extraLength = buffer[HEADER_EXTRA];

				byte[] data = new byte[remaining];
				socket.Read(data, 0, remaining);

				this.Extra = new ArraySegment<byte>(data, 0, extraLength);
				this.Data = new ArraySegment<byte>(data, extraLength, data.Length - extraLength);

				this.DataType = buffer[HEADER_DATATYPE];
				this.Opcode = buffer[HEADER_OPCODE];
				this.StatusCode = BinaryConverter.DecodeInt16(buffer, HEADER_STATUS);

				this.KeyLength = BinaryConverter.DecodeInt16(buffer, HEADER_KEY);
				this.CorrelationId = BinaryConverter.DecodeInt32(buffer, HEADER_OPAQUE);
				this.CAS = BinaryConverter.DecodeUInt64(buffer, HEADER_CAS);
			}

			return this.StatusCode == 0;
		}
        public override void Dispose()
        {
            GC.SuppressFinalize(this);

            if (socket != null)
            {
                ((IDisposable)socket).Dispose();
                socket = null;
            }

            base.Dispose();
        }
示例#17
0
        protected internal override bool ReadResponseAsync(PooledSocket 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 bool ReadResponseAsync(PooledSocket 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();
		}
示例#19
0
        /// <summary>
        /// Reads a line from the socket. A line is terninated by \r\n.
        /// </summary>
        /// <returns></returns>
        private static string ReadLine(PooledSocket socket)
        {
            const int    SANITY_CHECK_MAX_SIZE = 1024 * 1024 * 10;
            MemoryStream ms = new MemoryStream(50);

            bool gotR = false;
            //byte[] buffer = new byte[1];

            int data;
            int count = 0;

            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);

                if (++count > SANITY_CHECK_MAX_SIZE)
                {
                    LogSanityException(socket, ms.ToArray());
                    socket.IsAlive = false;
                    throw new Exception("KrudySanityCheckException, memcached value beyond expected size");
                }
            }

            string retval = Encoding.ASCII.GetString(ms.ToArray(), 0, (int)ms.Length);

            if (log.IsDebugEnabled)
            {
                log.Debug("ReadLine: " + retval);
            }

            return(retval);
        }
        protected override bool ReadResponse(PooledSocket socket)
        {
            var response = new BinaryResponse();

            if (response.Read(socket))
            {
                this.Result = DecodeResult(response.Data);

                return(true);
            }

            return(false);
        }
示例#21
0
        protected internal override bool ReadResponse(PooledSocket socket)
        {
            GetResponse r = GetHelper.ReadItem(socket);

            if (r == null) return false;

            this.result = r.Item;
            this.Cas = r.CasValue;

            GetHelper.FinishCurrent(socket);

            return true;
        }
示例#22
0
        public override void WriteTo(PooledSocket socket)
        {
            if (Transactional)
                _multi.WriteTo(socket);

            foreach (var command in _commands)
            {
                // todo: if transactional, ignore MULTI or EXEC, if any
                command.WriteTo(socket);
            }
            if (Transactional)
                _exec.WriteTo(socket);
        }
示例#23
0
		protected internal override IOperationResult ReadResponse(PooledSocket 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;
		}
示例#24
0
        public static GetResponse ReadItem(PooledSocket socket, ILogger log)
        {
            string description = TextSocketHelper.ReadResponse(socket, log);

            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 (!ulong.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  = ushort.Parse(parts[2], CultureInfo.InvariantCulture);
            int    length = int.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);

            log.LogDebug("Received value. Data type: {Type}, size: {Size}.", retval.Item.Flags, retval.Item.Data.Count);

            return(retval);
        }
		protected internal override IOperationResult ReadResponse(PooledSocket 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(PooledSocket 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);
        }
        protected internal override async Task <IOperationResult> ReadResponseAsync(PooledSocket socket, CancellationToken cancellationToken = default(CancellationToken))
        {
            var response = new BinaryResponse();
            var success  = await response.ReadAsync(socket, cancellationToken).ConfigureAwait(false);

            this.StatusCode = StatusCode;
            var result = new BinaryOperationResult()
            {
                Success    = success,
                StatusCode = this.StatusCode
            };

            result.PassOrFail(success, "Failed to read response");
            return(result);
        }
示例#28
0
		protected internal override IOperationResult ReadResponse(PooledSocket 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;
		}
示例#29
0
        protected internal override IOperationResult ReadResponse(PooledSocket 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);
        }
示例#30
0
        public Socket[] TakeRange(int count)
        {
            var socks = new Socket[count];
            int i     = _pool.TryPopRange(socks);

            if (i < count)
            {
                Array.Resize(ref socks, count);
                for (; i < count; i++)
                {
                    socks[i] = new PooledSocket(this);
                }
            }
            return(socks);
        }
        protected internal override async Task <IOperationResult> ReadResponseAsync(PooledSocket socket, CancellationToken cancellationToken = default(CancellationToken))
        {
            string response = await TextSocketHelper.ReadResponseAsync(socket, cancellationToken).ConfigureAwait(false);

            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);
        }
        protected override bool ExecuteAction()
        {
            foreach (MemcachedNode server in ServerPool.WorkingServers)
            {
                using (PooledSocket ps = server.Acquire())
                {
                    if (ps != null)
                    {
                        ps.SendCommand("flush_all");
                    }
                }
            }

            return(true);
        }
        /// <summary>
        /// Reads a line from the socket. A line is terninated by \r\n.
        /// </summary>
        /// <returns></returns>
        private static string ReadLine(PooledSocket socket)
        {
            var ms = new MemoryStream(50);

            bool gotR = false;
            //byte[] buffer = new byte[1];

            int data;

            while (true)
            {
                data = socket.ReadByte();

                if (data == -1)
                {
                    return(string.Empty);
                }

                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.ToArray(), 0, (int)ms.Length);

            if (log.IsDebugEnabled)
            {
                log.Debug("ReadLine: " + retval);
            }

            return(retval);
        }
示例#34
0
        protected override IOperationResult ReadResponse(PooledSocket 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);
        }
        protected internal override bool ReadResponse(PooledSocket socket)
        {
            GetResponse r = GetHelper.ReadItem(socket);

            if (r == null)
            {
                return(false);
            }

            this.result = r.Item;
            this.Cas    = r.CasValue;

            GetHelper.FinishCurrent(socket);

            return(true);
        }
示例#36
0
 public override void ReadFrom(PooledSocket socket)
 {
     var values = new List<RedisValue>();
     int subscriptionCount = 0;
     for (var k = 0; k < _channelCount; k++)
     {
         string action = "", channel = "";
         socket.ParseSubscriptionResponse(ref action, ref channel, ref subscriptionCount);
         values.Add( channel );
     }
     values.Add( subscriptionCount );
     Value = new RedisValue()
                  {
                      MultiBulkValues = values.ToArray()
                  };
 }
示例#37
0
        protected internal override IOperationResult ReadResponse(PooledSocket socket)
        {
            var response = new BinaryResponse();
            var success  = response.Read(socket);

            this.StatusCode = response.StatusCode;
            this.Data       = response.Data.Array;

            var result = new BinaryOperationResult
            {
                StatusCode = this.StatusCode
            };

            result.PassOrFail(success, "Failed to read response");
            return(result);
        }
示例#38
0
		public static GetResponse ReadItem(PooledSocket 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;
		}
示例#39
0
        protected internal override IOperationResult ReadResponse(PooledSocket 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());
        }
示例#40
0
        protected override IOperationResult ReadResponse(PooledSocket socket)
        {
            string description = TextSocketHelper.ReadResponse(socket, _log);

            if (string.Compare(description, "END", StringComparison.Ordinal) == 0)
            {
                return(null);
            }

            if (description.Length < 7 || string.Compare(description, 0, "CONFIG ", 0, 7, StringComparison.Ordinal) != 0)
            {
                throw new MemcachedClientException("No CONFIG response received.\r\n" + description);
            }

            string[] parts = description.Split(' ');

            /****** Format ********
             *
             * CONFIG <key> <flags> <bytes>
             * 0        1       2       3
             *
             */

            ushort flags  = ushort.Parse(parts[2], CultureInfo.InvariantCulture);
            int    length = int.Parse(parts[3], CultureInfo.InvariantCulture);

            byte[] allNodes = new byte[length];
            byte[] eod      = new byte[2];

            socket.Read(allNodes, 0, length);
            socket.Read(eod, 0, 2); // data is terminated by \r\n

            _result      = new CacheItem(flags, new ArraySegment <byte>(allNodes, 0, length));
            ConfigResult = _result;

            string response = TextSocketHelper.ReadResponse(socket, _log);

            if (string.Compare(response, "END", StringComparison.Ordinal) != 0)
            {
                throw new MemcachedClientException("No END was received.");
            }

            var result = new TextOperationResult();

            return(result.Pass());
        }
        protected internal override bool ReadResponse(PooledSocket 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(true);
        }
示例#42
0
        protected internal override async Task <IOperationResult> ReadResponseAsync(PooledSocket socket, CancellationToken cancellationToken = default(CancellationToken))
        {
            var serverData = new Dictionary <string, string>();

            while (true)
            {
                string line = await TextSocketHelper.ReadResponseAsync(socket, cancellationToken).ConfigureAwait(false);

                // 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 (this._logger.IsEnabled(LogLevel.Debug))
                    {
                        this._logger.LogWarning("Unknow response: " + line);
                    }

                    continue;
                }

                // get the key&value
                string[] parts = line.Remove(0, 5).Split(' ');
                if (parts.Length != 2)
                {
                    if (this._logger.IsEnabled(LogLevel.Debug))
                    {
                        this._logger.LogWarning("Unknow response: " + line);
                    }

                    continue;
                }

                // store the stat item
                serverData[parts[0]] = parts[1];
            }

            this._result = serverData;

            return(new TextOperationResult().Pass());
        }
示例#43
0
        protected internal override async Task <IOperationResult> ReadResponseAsync(PooledSocket socket, CancellationToken cancellationToken = default(CancellationToken))
        {
            var response = await GetHelper.ReadItemAsync(socket, cancellationToken).ConfigureAwait(false);

            var result = new TextOperationResult();

            if (response == null)
            {
                return(result.Fail("Failed to read response"));
            }

            this.result = response.Item;
            this.Cas    = response.CasValue;

            await GetHelper.FinishCurrentAsync(socket, cancellationToken).ConfigureAwait(false);

            return(result.Pass());
        }
示例#44
0
        /// <summary>
        /// Reads a line from the socket. A line is terninated by \r\n.
        /// </summary>
        /// <returns></returns>
        static string ReadLine(PooledSocket socket)
        {
            using (var stream = new MemoryStream(50))
            {
                var  gotR = false;
                byte data;

                while (true)
                {
                    data = socket.Receive();

                    if (data == 13)
                    {
                        gotR = true;
                        continue;
                    }

                    if (gotR)
                    {
                        if (data == 10)
                        {
                            break;
                        }

                        stream.WriteByte(13);

                        gotR = false;
                    }

                    stream.WriteByte(data);
                }

                var result = Encoding.ASCII.GetString(stream.ToArray(), 0, (int)stream.Length);

                Logger = Logger ?? Caching.Logger.CreateLogger(typeof(TextSocketHelper));
                if (Logger.IsEnabled(LogLevel.Debug))
                {
                    Logger.LogDebug("ReadLine: " + result);
                }

                return(result);
            }
        }
示例#45
0
        protected internal override IOperationResult ReadResponse(PooledSocket 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."));
        }
示例#46
0
        /// <summary>
        /// Reads a line from the socket. A line is terninated by \r\n.
        /// </summary>
        /// <returns></returns>
        static async Task <string> ReadLineAsync(PooledSocket socket, CancellationToken cancellationToken = default(CancellationToken))
        {
            using (var stream = new MemoryStream(50))
            {
                var  gotR = false;
                byte data;

                while (true)
                {
                    data = await socket.ReceiveAsync(cancellationToken).ConfigureAwait(false);

                    if (data == 13)
                    {
                        gotR = true;
                        continue;
                    }

                    if (gotR)
                    {
                        if (data == 10)
                        {
                            break;
                        }

                        stream.WriteByte(13);

                        gotR = false;
                    }

                    stream.WriteByte(data);
                }

                var result = Encoding.ASCII.GetString(stream.ToArray(), 0, (int)stream.Length);

                Logger = Logger ?? Caching.Logger.CreateLogger(typeof(TextSocketHelper));
                if (Logger.IsEnabled(LogLevel.Debug))
                {
                    Logger.LogDebug("ReadLine (async): " + result);
                }

                return(result);
            }
        }
        protected override bool ExecuteAction()
        {
            PooledSocket socket = Socket;

            if (socket == null)
            {
                return(false);
            }

            socket.SendCommand(String.Concat("incr ", HashedKey, " ", amount.ToString(CultureInfo.InvariantCulture)));

            string response = socket.ReadResponse();

            //maybe we should throw an exception when the item is not found?
            if (String.Compare(response, "NOT_FOUND", StringComparison.Ordinal) == 0)
            {
                return(false);
            }

            return(UInt32.TryParse(response, out result));
        }
示例#48
0
        public override void ReadFrom(PooledSocket socket)
        {
            socket.ExpectSingleLineReply(); // OK - matching Multi

            for (int i = 0; i < _commands.Count; i++)
            {
                // read "QUEUED"
                var status = socket.ExpectSingleLineReply();
            }
            // The result is a multi-bulk, so
            // consume the count of returned items
            var count = socket.ExpectMultiBulkCount();
            if (count != _commands.Count)
                throw new RedisClientException(
                    String.Format("Invalid number of bulk responses. Expected {0}, Got {1}", _commands.Count, count));

            foreach (var command in _commands)
            {
                command.ReadFrom(socket);
            }
        }
示例#49
0
        protected internal override bool ReadResponse(PooledSocket 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;

            return(retval);
        }
示例#50
0
        protected override bool ExecuteAction()
        {
            PooledSocket socket = Socket;

            if (socket == null)
            {
                return(false);
            }

            socket.SendCommand("get " + HashedKey);

            GetResponse r = GetHelper.ReadItem(Socket);

            if (r != null)
            {
                result = ServerPool.Transcoder.Deserialize(r.Item);
                GetHelper.FinishCurrent(Socket);
            }

            return(true);
        }
		protected internal override bool ReadResponse(PooledSocket 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;

			return retval;
		}
示例#52
0
        protected override bool ReadResponseAsync(PooledSocket 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);
        }
示例#53
0
        public unsafe bool Read(PooledSocket 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);
        }
示例#54
0
        /// <summary>
        /// Reads a line from the socket. A line is terninated by \r\n.
        /// </summary>
        /// <returns></returns>
        private static string ReadLine(PooledSocket socket, ILogger log)
        {
            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);

            log.LogDebug("ReadLine: " + retval);

            return(retval);
        }
示例#55
0
        protected internal override bool ReadResponse(PooledSocket 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 true;
        }
示例#56
0
        protected override IOperationResult ReadResponse(PooledSocket 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);
        }
		/// <summary>
		/// Reads a line from the socket. A line is terninated by \r\n.
		/// </summary>
		/// <returns></returns>
		private static string ReadLine(PooledSocket 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;
		}
        public async Task<bool> ReadAsync(PooledSocket socket)
        {
            this.StatusCode = -1;

            if (!socket.IsAlive) return false;

            var header = await socket.ReadBytesAsync(HeaderLength);

            int dataLength, extraLength;

            DeserializeHeader(header, out dataLength, out extraLength);

            if (dataLength > 0)
            {
                var data = await socket.ReadBytesAsync(dataLength);

                this.Extra = new ArraySegment<byte>(data, 0, extraLength);
                this.Data = new ArraySegment<byte>(data, extraLength, data.Length - extraLength);
            }

            return this.StatusCode == 0;
        }
        public override void WriteTo(PooledSocket socket)
        {
            var sb = new StringBuilder()
                .Append(" ")
                .Append(_keys.Count)
                .Append(" ")
                .Append(KeysToString(_keys));

            if (_weights != null && _weights.Count>0)
            {
                sb.Append(" ");
                sb.Append(KeysToString(_keys));    
            }
            if (_aggregate != AggregateType.None)
            {
                var aggr = "";
                switch (_aggregate)
                {
                    case AggregateType.Min:
                        aggr = "MIN"; 
                        break;
                    case AggregateType.Max:
                        aggr = "MAX";
                        break;
                    case AggregateType.Sum:
                        aggr = "SUM";
                        break;
                }
                if (!String.IsNullOrEmpty(aggr))
                {
                    sb.Append(" ")
                        .Append("AGGREGATE ")
                        .Append(aggr);
                }
            }
            //protocol.IssueSimpleCommand(Name, sb.ToString());
            throw new NotImplementedException();
        }
示例#60
0
        /// <summary>
        /// Reads the response from the socket
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        public async Task <bool> ReadAsync(PooledSocket socket, CancellationToken cancellationToken = default)
        {
            this.StatusCode = -1;

            if (!socket.IsAlive)
            {
                return(false);
            }

            try
            {
                var header = new byte[BinaryResponse.HeaderLength];
                await socket.ReceiveAsync(header, 0, header.Length, cancellationToken).ConfigureAwait(false);

                this.DeserializeHeader(header, out var dataLength, out var extraLength);

                if (dataLength > 0)
                {
                    var data = new byte[dataLength];
                    await socket.ReceiveAsync(data, 0, dataLength, cancellationToken).ConfigureAwait(false);

                    this.Extra = new ArraySegment <byte>(data, 0, extraLength);
                    this.Data  = new ArraySegment <byte>(data, extraLength, data.Length - extraLength);
                }

                return(this.StatusCode == 0);
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                this._logger.LogError(ex, "ReadAsync: Error occurred while reading socket");
                throw;
            }
        }