internal static Exception AdminModeNotEnabled(bool includeDetail, RedisCommand command, Message message, ServerEndPoint server) { string s = GetLabel(includeDetail, command, message); var ex = new RedisCommandException("This operation is not available unless admin mode is enabled: " + s); if (includeDetail) AddDetail(ex, message, server, s); return ex; }
public int Write(RedisCommand command, Stream stream) { string prepared = Prepare(command); byte[] data = _io.Encoding.GetBytes(prepared); stream.Write(data, 0, data.Length); return data.Length; }
internal static Exception NotSupported(bool includeDetail, RedisCommand command) { string s = GetLabel(includeDetail, command, null); var ex = new RedisCommandException("Command is not available on your server: " + s); if (includeDetail) AddDetail(ex, null, null, s); return ex; }
internal static Exception DatabaseRequired(bool includeDetail, RedisCommand command) { string s = command.ToString(); var ex = new RedisCommandException("A target database is required for " + s); if (includeDetail) AddDetail(ex, null, null, s); return ex; }
internal static Exception CommandDisabled(bool includeDetail, RedisCommand command, Message message, ServerEndPoint server) { string s = GetLabel(includeDetail, command, message); var ex = new RedisCommandException("This operation has been disabled in the command-map and cannot be used: " + s); if (includeDetail) AddDetail(ex, message, server, s); return ex; }
public string SendCommand(RedisCommand command,params string[] args) { const string headstr = "*{0}\r\n"; const string bulkstr = "${0}\r\n{1}\r\n"; var sb = new StringBuilder(); sb.AppendFormat(headstr, args.Length + 1); var cmd = command.ToString(); sb.AppendFormat(bulkstr, cmd.Length, cmd); foreach (var arg in args) { sb.AppendFormat(bulkstr, arg.Length, arg); } byte[] c = Encoding.UTF8.GetBytes(sb.ToString()); try { Connect(); socket.Send(c); socket.Receive(ReceiveBuffer); Close(); return ReadData(); } catch (SocketException e) { Close(); } return null; }
internal static Exception MasterOnly(bool includeDetail, RedisCommand command, Message message, ServerEndPoint server) { string s = GetLabel(includeDetail, command, message); var ex = new RedisCommandException("Command cannot be issued to a slave: " + s); if (includeDetail) AddDetail(ex, message, server, s); return ex; }
/// <summary> /// Executes all Redis command handlers, running behaviors that must run before some given command is about to get executed. /// </summary> /// <param name="handlers">The sequence of Redis command handlers</param> /// <param name="command">The Redis command</param> /// <param name="involvedKeys">An array of involved Redis keys in the command</param> /// <param name="involvedValues">An array of involved Redis values in the command</param> /// <returns>True if handlers could be executed. Otherwise, false.</returns> public static bool ExecuteBeforeHandlers(this IEnumerable<IRedisCommandHandler> handlers, RedisCommand command, RedisKey[] involvedKeys = null, RedisValue[] involvedValues = null) { bool canExecute = CanExecuteHandlers(handlers, command); if (canExecute) foreach (IRedisCommandHandler handler in handlers) handler.OnExecuting(command, involvedKeys, involvedValues); return canExecute; }
/// <summary> /// Determines if a given sequence of handlers are executable for a given Redis command. /// </summary> /// <param name="handlers"></param> /// <param name="command"></param> /// <returns>True if given handlers can be executed for the given handlers. Otherwise, returns false.</returns> private static bool CanExecuteHandlers(IEnumerable<IRedisCommandHandler> handlers, RedisCommand command) { return handlers != null && ( RedisCommandHandlerConfiguration.ActivatedCommands.Count == 0 || (RedisCommandHandlerConfiguration.ActivatedCommands.Count > 0 && RedisCommandHandlerConfiguration.ActivatedCommands.Contains(command)) ); }
/// <summary> /// Executes all Redis command handlers, running behaviors that must run after some given command has been already executed. /// </summary> /// <typeparam name="TResult">The type of Redis command result</typeparam> /// <param name="handlers">The sequence of Redis command handlers</param> /// <param name="command">The Redis command</param> /// <param name="involvedKeys">An array of involved Redis keys in the command</param> /// <param name="result">The result of the Redis command execution</param> /// <returns>True if handlers could be executed. Otherwise, false.</returns> public static bool ExecuteAfterHandlers(this IEnumerable<IRedisCommandHandler> handlers, RedisCommand command, RedisKey[] involvedKeys, ref object result) { bool canExecute = CanExecuteHandlers(handlers, command); if (canExecute) foreach (IRedisCommandHandler handler in handlers) handler.OnExecuted(command, ref result, involvedKeys); return canExecute; }
internal static Exception NoConnectionAvailable(bool includeDetail, RedisCommand command, Message message, ServerEndPoint server, ServerEndPoint[] serverSnapshot) { string s = GetLabel(includeDetail, command, message); if (server != null) { //if we already have the serverEndpoint for connection failure use that //otherwise it would output state of all the endpoints serverSnapshot = new ServerEndPoint[] { server }; } string exceptionmessage = "No connection is available to service this operation: " + s ; var ex = new RedisConnectionException(ConnectionFailureType.UnableToResolvePhysicalConnection, exceptionmessage, GetServerSnapshotInnerExceptions(serverSnapshot)); if (includeDetail) { AddDetail(ex, message, server, s); } return ex; }
string Prepare(RedisCommand command) { var parts = command.Command.Split(' '); int length = parts.Length + command.Arguments.Length; StringBuilder sb = new StringBuilder(); sb.Append(MultiBulk).Append(length).Append(EOL); foreach (var part in parts) sb.Append(Bulk).Append(_io.Encoding.GetByteCount(part)).Append(EOL).Append(part).Append(EOL); foreach (var arg in command.Arguments) { string str = String.Format(CultureInfo.InvariantCulture, "{0}", arg); sb.Append(Bulk).Append(_io.Encoding.GetByteCount(str)).Append(EOL).Append(str).Append(EOL); } return sb.ToString(); }
public void OnExecuting(RedisCommand command, RedisKey[] involvedKeys = null, RedisValue[] involvedValues = null) { if (involvedValues != null && involvedValues.Length > 0 && CanBeExecuted(involvedKeys)) { switch (command) { case RedisCommand.SET: CompressSET(involvedValues); break; case RedisCommand.HSET: case RedisCommand.HMSET: case RedisCommand.ZADD: CompressValuesWithArgs(involvedValues); break; case RedisCommand.SADD: case RedisCommand.LPUSH: case RedisCommand.LPUSHX: CompressAdd(involvedValues); break; } } }
public IndexOf(RedisCommand <T> command, int index) : base(command.Command, command.Arguments) { _command = command; _index = index; }
internal object Send(RedisCommand command,params string[] args) { SendN(command.ToString(), args); return ReadData(); }
internal void WriteHeader(RedisCommand command, int arguments) { var commandBytes = multiplexer.CommandMap.GetBytes(command); if (commandBytes == null) { throw ExceptionFactory.CommandDisabled(multiplexer.IncludeDetailInExceptions, command, null, bridge.ServerEndPoint); } outStream.WriteByte((byte)'*'); WriteRaw(outStream, arguments + 1); WriteUnified(outStream, commandBytes); }
#pragma warning disable RCS1231 // Make parameter ref read-only. public static Message CreateMessage(Condition condition, int db, CommandFlags flags, RedisCommand command, in RedisKey key, RedisValue value = default(RedisValue))
public CommandKeyKeyMessage(int db, CommandFlags flags, RedisCommand command, RedisKey key0, RedisKey key1) : base(db, flags, command, key0) { key1.AssertNotNull(); this.key1 = key1; }
public T Write <T>(RedisCommand <T> command) { _writer.Write(command, _buffer); _parsers.Enqueue(() => command.Parse(_reader)); return(default(T)); }
/// <summary> /// /// </summary> /// <param name="command"></param> /// <param name="args"></param> /// <param name="keepConnect"></param> /// <returns></returns> public string SendCommand(RedisCommand command, string[] args, bool keepConnect = false) { try { //请求头部格式, *<number of arguments>\r\n const string headstr = "*{0}\r\n"; //参数信息 $<number of bytes of argument N>\r\n<argument data>\r\n const string bulkstr = "${0}\r\n{1}\r\n"; var sb = new StringBuilder(); sb.AppendFormat(headstr, args.Length + 1); var cmd = command.ToString(); sb.AppendFormat(bulkstr, cmd.Length, cmd); foreach (var arg in args) { sb.AppendFormat(bulkstr, arg.Length, arg); } socket.Send(Encoding.UTF8.GetBytes(sb.ToString())); ReceiveBuffer = new byte[65536]; if (command == RedisCommand.Get) { var total = 0; var length = 0; while (true) { try { var rev = new byte[65536]; var temp = socket.Receive(rev, rev.Length, SocketFlags.None); Buffer.BlockCopy(rev, 0, ReceiveBuffer, total, temp); total += temp; if (length == 0) { var line = ReadData().Split(new[] { '$', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)[0]; length = cvt.ToInt(line); if (length > 60000) { ReceiveBuffer = new byte[length + 1000]; Buffer.BlockCopy(rev, 0, ReceiveBuffer, 0, temp); } } if (total >= length) { break; } } catch { break; } } } else { socket.Receive(ReceiveBuffer); } var data = ReadData(); if (!keepConnect) { Using = false; } return(data); } catch { } Using = false; return(null); }
/// <summary> /// 发送命令 /// </summary> /// <param name="command"></param> /// <param name="args"></param> /// <returns></returns> public string SendCommand(RedisCommand command, params string[] args) { return(SendCommand(command, args, false)); }
/// <summary> /// 添加命令 /// </summary> /// <param name="command"></param> /// <param name="args"></param> /// <returns></returns> public string AddCommand(RedisCommand command, params string[] args) { return(SendCommand(command, args, true)); }
internal bool IsSelectable(RedisCommand command, bool allowDisconnected = false) { var bridge = unselectableReasons == 0 ? GetBridge(command, false) : null; return(bridge != null && (allowDisconnected || bridge.IsConnected)); }
internal string GetStormLog(RedisCommand command) { var bridge = GetBridge(command); return(bridge?.GetStormLog()); }
internal static Exception NoConnectionAvailable( ConnectionMultiplexer multiplexer, Message message, ServerEndPoint server, ReadOnlySpan <ServerEndPoint> serverSnapshot = default, RedisCommand command = default) { string commandLabel = GetLabel(multiplexer.IncludeDetailInExceptions, message?.Command ?? command, message); if (server != null) { //if we already have the serverEndpoint for connection failure use that //otherwise it would output state of all the endpoints serverSnapshot = new ServerEndPoint[] { server }; } var innerException = PopulateInnerExceptions(serverSnapshot == default ? multiplexer.GetServerSnapshot() : serverSnapshot); // Try to get a useful error message for the user. long attempts = multiplexer._connectAttemptCount, completions = multiplexer._connectCompletedCount; string initialMessage; // We only need to customize the connection if we're aborting on connect fail // The "never" case would have thrown, if this was true if (!multiplexer.RawConfig.AbortOnConnectFail && attempts <= multiplexer.RawConfig.ConnectRetry && completions == 0) { // Initial attempt, attempted use before an async connection completes initialMessage = $"Connection to Redis never succeeded (attempts: {attempts} - connection likely in-progress), unable to service operation: "; } else if (!multiplexer.RawConfig.AbortOnConnectFail && attempts > multiplexer.RawConfig.ConnectRetry && completions == 0) { // Attempted use after a full initial retry connect count # of failures // This can happen in Azure often, where user disables abort and has the wrong config initialMessage = $"Connection to Redis never succeeded (attempts: {attempts} - check your config), unable to service operation: "; } else { // Default if we don't have a more useful error message here based on circumstances initialMessage = "No connection is active/available to service this operation: "; } StringBuilder sb = new StringBuilder(initialMessage); sb.Append(commandLabel); string innermostExceptionstring = GetInnerMostExceptionMessage(innerException); if (!string.IsNullOrEmpty(innermostExceptionstring)) { sb.Append("; ").Append(innermostExceptionstring); } // Add counters and exception data if we have it List <Tuple <string, string> > data = null; if (multiplexer.IncludeDetailInExceptions) { data = new List <Tuple <string, string> >(); AddCommonDetail(data, sb, message, multiplexer, server); } var ex = new RedisConnectionException(ConnectionFailureType.UnableToResolvePhysicalConnection, sb.ToString(), innerException, message?.Status ?? CommandStatus.Unknown); if (multiplexer.IncludeDetailInExceptions) { CopyDataToException(data, ex); sb.Append("; ").Append(PerfCounterHelper.GetThreadPoolAndCPUSummary(multiplexer.IncludePerformanceCountersInExceptions)); AddExceptionDetail(ex, message, server, commandLabel); } return(ex); }
public CommandInfo(RedisCommand command, string[] args) { this.command = command; this.args = args; }
public int SendCommand(RedisCommand command, IDictionary <string, byte[]> datas, params string[] args) { // http://redis.io/topics/protocol // new redis communication protocol specifications StringBuilder sb = new StringBuilder(); int acount = args != null ? args.Length + 1 : 1; acount += datas != null && datas.Count > 0 ? datas.Count * 2 : 0; sb.AppendFormat("*{0}\r\n", acount); var cmd = command.ToString(); sb.AppendFormat("${0}\r\n{1}\r\n", cmd.Length, cmd); if (args != null) { foreach (var arg in args) { sb.AppendFormat("${0}\r\n{1}\r\n", arg.Length, arg); } } MemoryStream ms = new MemoryStream(); byte[] r = Encoding.UTF8.GetBytes(sb.ToString()); ms.Write(r, 0, r.Length); if (datas != null && datas.Count > 0) { foreach (var data in datas) { r = Encoding.UTF8.GetBytes(string.Format("${0}\r\n{1}\r\n", data.Key.Length, data.Key)); ms.Write(r, 0, r.Length); r = Encoding.UTF8.GetBytes(string.Format("${0}\r\n", data.Value.Length)); ms.Write(r, 0, r.Length); ms.Write(data.Value, 0, data.Value.Length); ms.Write(_end_data, 0, 2); } } var socket = this.Connect(); try { Log("S: " + sb.ToString(), datas); socket.Send(ms.ToArray()); } catch (SocketException e) { Log("Exception: " + e.Message); // timeout; socket.Shutdown(SocketShutdown.Both); RemoveSocket(); throw; } if (Configuration.LogUnbalancedCommands) { return(_tracer.TraceCommand(command)); } return(0); }
internal static Exception NoConnectionAvailable(bool includeDetail, bool includePerformanceCounters, RedisCommand command, Message message, ServerEndPoint server, ReadOnlySpan <ServerEndPoint> serverSnapshot) { string commandLabel = GetLabel(includeDetail, command, message); if (server != null) { //if we already have the serverEndpoint for connection failure use that //otherwise it would output state of all the endpoints serverSnapshot = new ServerEndPoint[] { server }; } var innerException = PopulateInnerExceptions(serverSnapshot); StringBuilder exceptionmessage = new StringBuilder("No connection is available to service this operation: ").Append(commandLabel); string innermostExceptionstring = GetInnerMostExceptionMessage(innerException); if (!string.IsNullOrEmpty(innermostExceptionstring)) { exceptionmessage.Append("; ").Append(innermostExceptionstring); } if (includeDetail) { exceptionmessage.Append("; ").Append(PerfCounterHelper.GetThreadPoolAndCPUSummary(includePerformanceCounters)); } var ex = new RedisConnectionException(ConnectionFailureType.UnableToResolvePhysicalConnection, exceptionmessage.ToString(), innerException, message?.Status ?? CommandStatus.Unknown); if (includeDetail) { AddDetail(ex, message, server, commandLabel); } return(ex); }
public Task <T> CallAsync <T>(RedisCommand <T> command) { return(Async.CallAsync(command)); }
internal static Exception NoCursor(RedisCommand command) { string s = GetLabel(false, command, null); return(new RedisCommandException("Command cannot be used with a cursor: " + s)); }
internal static Exception CommandDisabled(RedisCommand command) => CommandDisabled(command.ToString());
private static string GetLabel(bool includeDetail, RedisCommand command, Message message) { return(message == null?command.ToString() : (includeDetail ? message.CommandAndKey : message.Command.ToString())); }
public dynamic Send(RedisCommand command) => Send(command.ToString());
public void OnExecuted(RedisCommand command, ref object result, RedisKey[] involvedKeys = null) { if (CanBeExecuted(involvedKeys)) { if (result != null && result.GetType() != typeof(bool) && result.GetType() != typeof(int) && result.GetType() != typeof(long)) { bool isScanResult = command == RedisCommand.SCAN || command == RedisCommand.HSCAN || command == RedisCommand.SSCAN || command == RedisCommand.ZSCAN; object scanValues = null; if (isScanResult) scanValues = result.GetType() .GetField("Values", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance) .GetValue(result); if (result.GetType() == typeof(RedisValue)) { byte[] valueBlob = (RedisValue)result; RedisValueCompressor.Compressor.Decompress(ref valueBlob); if (valueBlob != null && valueBlob.Length > 0) result = (RedisValue)Encoding.UTF8.GetString(valueBlob); } else if (result.GetType() == typeof(RedisValue[]) || (command == RedisCommand.SCAN || command == RedisCommand.SSCAN)) { RedisValue[] values; if (!isScanResult) values = (RedisValue[])result; else values = (RedisValue[])scanValues; for (int i = 0; i < values.Length; i++) { byte[] valueBlob = values[i]; RedisValueCompressor.Compressor.Decompress(ref valueBlob); values[i] = (RedisValue)valueBlob; } } else if (result.GetType() == typeof(SortedSetEntry)) { SortedSetEntry source = (SortedSetEntry)result; byte[] valueBlob = source.Element; RedisValueCompressor.Compressor.Decompress(ref valueBlob); result = new SortedSetEntry((RedisValue)valueBlob, source.Score); } else if (result.GetType() == typeof(SortedSetEntry[]) || command == RedisCommand.ZSCAN) { SortedSetEntry[] entries; if (!isScanResult) entries = (SortedSetEntry[])result; else entries = (SortedSetEntry[])scanValues; for (int i = 0; i < entries.Length; i += 2) { SortedSetEntry source = (SortedSetEntry)entries[i]; byte[] valueBlob = source.Element; RedisValueCompressor.Compressor.Decompress(ref valueBlob); entries[i] = new SortedSetEntry((RedisValue)valueBlob, source.Score); } } else if (result.GetType() == typeof(HashEntry)) { HashEntry source = (HashEntry)result; byte[] valueBlob = source.Value; RedisValueCompressor.Compressor.Decompress(ref valueBlob); result = new HashEntry(source.Name, (RedisValue)valueBlob); } else if (result.GetType() == typeof(HashEntry[]) || command == RedisCommand.HSCAN) { HashEntry[] entries; if (!isScanResult) entries = (HashEntry[])result; else // TODO: Not the best solution... But I need to investigate further how to improve StackExchange.Redis // to get these values directly... entries = (HashEntry[])scanValues; for (int i = 0; i < entries.Length; i++) { HashEntry source = entries[i]; byte[] valueBlob = source.Value; RedisValueCompressor.Compressor.Decompress(ref valueBlob); entries[i] = new HashEntry(source.Name, (RedisValue)valueBlob); } } } } }
internal static Exception NoCursor(RedisCommand command) { string s = GetLabel(false, command, null); var ex = new RedisCommandException("Command cannot be used with a cursor: " + s); return ex; }
public object Execute(RedisCommand rc,params string[] args) { var reply = Execute(() => Send(rc, args), Continuation); return reply; }
public StrongPairs(RedisCommand <T1> command1, RedisCommand <T2> command2, string command, params object[] args) : base(new RedisTuple.Generic <T1, T2> .Repeating(command1, command2, command, args)) { }
public ConditionMessage(Condition condition, int db, CommandFlags flags, RedisCommand command, in RedisKey key, in RedisValue value)
public Generic(RedisCommand <T> memberCommand) : base(memberCommand.Command, memberCommand.Arguments) { _memberCommand = memberCommand; }
internal void WriteHeader(RedisCommand command, int arguments) { var commandBytes = multiplexer.CommandMap.GetBytes(command); if (commandBytes == null) { throw ExceptionFactory.CommandDisabled(multiplexer.IncludeDetailInExceptions, command, null, bridge.ServerEndPoint); } outStream.WriteByte((byte)'*'); // remember the time of the first write that still not followed by read Interlocked.CompareExchange(ref firstUnansweredWriteTickCount, Environment.TickCount, 0); WriteRaw(outStream, arguments + 1); WriteUnified(outStream, commandBytes); }
internal bool IsSelectable(RedisCommand command) { var bridge = unselectableReasons == 0 ? GetBridge(command, false) : null; return(bridge != null && bridge.IsConnected); }
public dynamic Send(RedisCommand command, params byte[][] arguments) => Send(command.ToString(), arguments);
public MiningController(RedisCommand redisCommand) { _redisCommand = redisCommand; }
static string GetLabel(bool includeDetail, RedisCommand command, Message message) { return message == null ? command.ToString() : (includeDetail ? message.CommandAndKey : message.Command.ToString()); }
public CommandKeyValueMessage(int db, CommandFlags flags, RedisCommand command, RedisKey key, RedisValue value) : base(db, flags, command, key) { value.AssertNotNull(); this.value = value; }
public Single(RedisCommand <T1> command1, RedisCommand <T2> command2, string command, params object[] args) : base(command1, command2, command, args) { }
public T Execute <T>(RedisCommand <T> command) { return(this.Write(command).Parse(this)); }
protected Generic(RedisCommand <T1> command1, RedisCommand <T2> command2, string command, params object[] args) : base(command, args) { _command1 = command1; _command2 = command2; }
public CommandKeyMessage(int db, CommandFlags flags, RedisCommand command, RedisKey key) : base(db, flags, command, key) { }
private ServerEndPoint Select(int slot, RedisCommand command, CommandFlags flags) { flags = Message.GetMasterSlaveFlags(flags); // only intersted in master/slave preferences ServerEndPoint[] arr; if (slot == NoSlot || (arr = map) == null) return Any(command, flags); ServerEndPoint endpoint = arr[slot], testing; // but: ^^^ is the MASTER slots; if we want a slave, we need to do some thinking if (endpoint != null) { switch (flags) { case CommandFlags.DemandSlave: return FindSlave(endpoint, command) ?? Any(command, flags); case CommandFlags.PreferSlave: testing = FindSlave(endpoint, command); if (testing != null) return testing; break; case CommandFlags.DemandMaster: return FindMaster(endpoint, command) ?? Any(command, flags); case CommandFlags.PreferMaster: testing = FindMaster(endpoint, command); if (testing != null) return testing; break; } if (endpoint.IsSelectable(command)) return endpoint; } return Any(command, flags); }
private ServerEndPoint FindSlave(ServerEndPoint endpoint, RedisCommand command) { if (endpoint.IsSlave && endpoint.IsSelectable(command)) return endpoint; var slaves = endpoint.Slaves; for (int i = 0; i < slaves.Length; i++) { endpoint = slaves[i]; if (endpoint.IsSlave && endpoint.IsSelectable(command)) return endpoint; } return null; }
public CommandChannelValueMessage(int db, CommandFlags flags, RedisCommand command, RedisChannel channel, RedisValue value) : base(db, flags, command, channel) { value.AssertNotNull(); this.value = value; }
private ServerEndPoint Any(RedisCommand command, CommandFlags flags) { return multiplexer.AnyConnected(serverType, (uint)Interlocked.Increment(ref anyStartOffset), command, flags); }
private ServerEndPoint FindMaster(ServerEndPoint endpoint, RedisCommand command) { int max = 5; do { if (!endpoint.IsSlave && endpoint.IsSelectable(command)) return endpoint; endpoint = endpoint.Master; } while (endpoint != null && --max != 0); return null; }
public ServerEndPoint Select(int db, RedisCommand command, RedisKey key, CommandFlags flags) { int slot = serverType == ServerType.Cluster ? HashSlot(key) : NoSlot; return Select(slot, command, flags); }
internal bool IsAvailable(RedisCommand command) { return map[(int)command] != null; }
internal byte[] GetBytes(RedisCommand command) { return map[(int)command]; }
internal void AssertAvailable(RedisCommand command) { if (map[(int)command] == null) throw ExceptionFactory.CommandDisabled(false, command, null, null); }
internal static Exception NoConnectionAvailable(bool includeDetail, RedisCommand command, Message message, ServerEndPoint server) { string s = GetLabel(includeDetail, command, message); var ex = new RedisConnectionException(ConnectionFailureType.UnableToResolvePhysicalConnection, "No connection is available to service this operation: " + s); if (includeDetail) AddDetail(ex, message, server, s); return ex; }