index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/util/Closeables.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.util; import java.io.Closeable; import java.io.IOException; import static com.google.common.io.Closeables.close; /** * Utility class that handles {@link java.io.Closeable} objects */ public class Closeables { public static void closeQuietly(Closeable closeable) { try{ close(closeable, true); }catch(IOException e){ // No need to do anything here as any IOException should // have been suppressed here. } } }
1,400
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/input/SuroInputPlugin.java
package com.netflix.suro.input; import com.netflix.suro.SuroPlugin; import com.netflix.suro.input.kafka.KafkaConsumer; import com.netflix.suro.input.remotefile.CloudTrail; import com.netflix.suro.input.remotefile.JsonLine; import com.netflix.suro.input.remotefile.S3Consumer; import com.netflix.suro.input.thrift.ThriftServer; public class SuroInputPlugin extends SuroPlugin { @Override protected void configure() { this.addInputType(ThriftServer.TYPE, ThriftServer.class); this.addInputType(KafkaConsumer.TYPE, KafkaConsumer.class); this.addInputType(S3Consumer.TYPE, S3Consumer.class); this.addRecordParserType(JsonLine.TYPE, JsonLine.class); this.addRecordParserType(CloudTrail.TYPE, CloudTrail.class); } }
1,401
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/input/DynamicPropertyInputConfigurator.java
package com.netflix.suro.input; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.Inject; import com.netflix.config.DynamicStringProperty; import com.netflix.governator.annotations.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import java.util.List; public class DynamicPropertyInputConfigurator { public static final String INPUT_CONFIG_PROPERTY = "SuroServer.inputConfig"; private static Logger LOG = LoggerFactory.getLogger(DynamicPropertyInputConfigurator.class); private final InputManager inputManager; private final ObjectMapper jsonMapper; @Configuration(INPUT_CONFIG_PROPERTY) private String initialInputConfig; @Inject public DynamicPropertyInputConfigurator( InputManager inputManager, ObjectMapper jsonMapper) { this.inputManager = inputManager; this.jsonMapper = jsonMapper; } @PostConstruct public void init() { DynamicStringProperty inputFP = new DynamicStringProperty(INPUT_CONFIG_PROPERTY, initialInputConfig) { @Override protected void propertyChanged() { buildInput(get(), false); } }; buildInput(inputFP.get(), true); } private void buildInput(String inputListStr, boolean initialSet) { try { List<SuroInput> inputList = jsonMapper.readValue( inputListStr, new TypeReference<List<SuroInput>>() {}); if (initialSet) { inputManager.initialSet(inputList); } else { inputManager.set(inputList); } } catch (Exception e) { LOG.info("Error reading input config from fast property: "+e.getMessage(), e); } } }
1,402
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/input/InputManager.java
package com.netflix.suro.input; import com.google.common.collect.Sets; import com.google.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @Singleton public class InputManager { private static final Logger log = LoggerFactory.getLogger(InputManager.class); private ConcurrentMap<String, SuroInput> inputMap = new ConcurrentHashMap<String, SuroInput>(); public void initialStart() throws Exception { for (SuroInput suroInput : inputMap.values()) { suroInput.start(); } } public void initialSet(List<SuroInput> inputList) { if (!inputMap.isEmpty()) { throw new RuntimeException("inputMap is not empty"); } for (SuroInput suroInput : inputList) { inputMap.put(suroInput.getId(), suroInput); } } public void set(List<SuroInput> inputList) { for (SuroInput suroInput : inputList) { if (!inputMap.containsKey(suroInput.getId())) { try { suroInput.start(); inputMap.put(suroInput.getId(), suroInput); } catch (Exception e) { log.error("Exception on starting the input", e); } } } HashSet<SuroInput> suroInputIdSet = Sets.newHashSet(inputList); for (Map.Entry<String, SuroInput> e : inputMap.entrySet()) { if (!suroInputIdSet.contains(e.getValue())) { SuroInput input = inputMap.remove(e.getKey()); input.shutdown(); } } } public SuroInput getInput(String id) { return inputMap.get(id); } public void shutdown() { for (SuroInput input : inputMap.values()) { input.shutdown(); } } }
1,403
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/input
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/input/thrift/MessageSetSerDe.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.input.thrift; import com.netflix.suro.message.SerDe; import com.netflix.suro.thrift.TMessageSet; import com.netflix.suro.util.Closeables; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.DataOutputBuffer; import java.nio.ByteBuffer; /** * {@link SerDe} implementation that serializes and de-serializes {@link TMessageSet}. This is serde is used to persist * {@link TMessageSet} objects to a disk-based queue. Messages in {@link TMessageSet} objects that are not consumed would be lost when the server fails, * if only in-memory queue is used to store {@link TMessageSet} objects. * * @author jbae */ public class MessageSetSerDe implements SerDe<TMessageSet> { @Override public TMessageSet deserialize(byte[] payload) { DataInputBuffer inBuffer = new DataInputBuffer(); inBuffer.reset(payload, payload.length); try { String app = inBuffer.readUTF(); int numMessages = inBuffer.readInt(); byte compression = inBuffer.readByte(); long crc = inBuffer.readLong(); byte[] messages = new byte[inBuffer.readInt()]; inBuffer.read(messages); return new TMessageSet( app, numMessages, compression, crc, ByteBuffer.wrap(messages) ); } catch (Exception e) { throw new RuntimeException("Failed to de-serialize payload into TMessageSet: "+e.getMessage(), e); } finally { Closeables.closeQuietly(inBuffer); } } @Override public byte[] serialize(TMessageSet payload) { DataOutputBuffer outBuffer = new DataOutputBuffer(); try { outBuffer.reset(); outBuffer.writeUTF(payload.getApp()); outBuffer.writeInt(payload.getNumMessages()); outBuffer.writeByte(payload.getCompression()); outBuffer.writeLong(payload.getCrc()); outBuffer.writeInt(payload.getMessages().length); outBuffer.write(payload.getMessages()); return ByteBuffer.wrap(outBuffer.getData(), 0, outBuffer.getLength()).array(); } catch (Exception e) { throw new RuntimeException("Failed to serialize TMessageSet: "+e.getMessage(), e); } finally { Closeables.closeQuietly(outBuffer); } } @Override public String toString(byte[] payload) { return deserialize(payload).toString(); } }
1,404
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/input
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/input/thrift/ThriftServer.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.input.thrift; import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.google.common.base.Throwables; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.governator.guice.lazy.LazySingleton; import com.netflix.suro.input.SuroInput; import com.netflix.suro.thrift.SuroServer; import org.apache.thrift.server.THsHaServer; import org.apache.thrift.transport.TTransportException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.*; @LazySingleton public class ThriftServer implements SuroInput { public static final String TYPE = "thrift"; private static final Logger logger = LoggerFactory.getLogger(ThriftServer.class); private THsHaServer server = null; private final ServerConfig config; private final MessageSetProcessor msgProcessor; private ExecutorService executor; private int port; @JsonCreator public ThriftServer( @JacksonInject ServerConfig config, @JacksonInject MessageSetProcessor msgProcessor) throws Exception { this.config = config; this.msgProcessor = msgProcessor; this.msgProcessor.setInput(this); } @Override public String getId() { return TYPE; } @Override public void start() throws TTransportException { msgProcessor.start(); logger.info("Starting ThriftServer with config " + config); CustomServerSocket transport = new CustomServerSocket(config); port = transport.getPort(); SuroServer.Processor processor = new SuroServer.Processor<MessageSetProcessor>(msgProcessor); THsHaServer.Args serverArgs = new THsHaServer.Args(transport); serverArgs.workerThreads(config.getThriftWorkerThreadNum()); serverArgs.processor(processor); serverArgs.maxReadBufferBytes = config.getThriftMaxReadBufferBytes(); executor = Executors.newSingleThreadExecutor(); server = new THsHaServer(serverArgs); Future<?> serverStarted = executor.submit(new Runnable() { @Override public void run() { server.serve(); } }); try { serverStarted.get(config.getStartupTimeout(), TimeUnit.MILLISECONDS); if (server.isServing()) { logger.info("Server started on port:" + config.getPort()); } else { throw new RuntimeException("ThriftServer didn't start up within: " + config.getStartupTimeout()); } } catch (InterruptedException e) { // ignore this type of exception } catch (TimeoutException e) { if (server.isServing()) { logger.info("Server started on port:" + config.getPort()); } else { logger.error("ThriftServer didn't start up within: " + config.getStartupTimeout()); Throwables.propagate(e); } } catch (ExecutionException e) { logger.error("Exception on starting ThriftServer: " + e.getMessage(), e); Throwables.propagate(e); } } @Override public void shutdown() { logger.info("Shutting down thrift server"); try { msgProcessor.stopTakingTraffic(); Thread.sleep(1000); server.stop(); executor.shutdownNow(); msgProcessor.shutdown(); } catch (Exception e) { // ignore any exception when shutdown logger.error("Exception while shutting down: " + e.getMessage(), e); } } @Override public boolean equals(Object o) { if (o instanceof ThriftServer) { return true; // thrift server is singleton } else { return false; } } @Override public int hashCode() { return TYPE.hashCode(); } private ExecutorService pauseExecutor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("ThriftServer-PauseExec-%d").build()); @Override public void setPause(final long ms) { if (ms > 0) { pauseExecutor.execute(new Runnable() { @Override public void run() { msgProcessor.stopTakingTraffic(); try { Thread.sleep(ms); } catch (InterruptedException e) { // do nothing } msgProcessor.startTakingTraffic(); } }); } } // for testing purpose public int getPort() { return port; } }
1,405
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/input
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/input/thrift/CustomServerSocket.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.input.thrift; import org.apache.thrift.transport.TNonblockingServerTransport; import org.apache.thrift.transport.TNonblockingSocket; import org.apache.thrift.transport.TTransportException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.SocketException; import java.nio.channels.*; /** * {@link ServerSocket} used by {@link TNonblockingServerTransport} in thrift 0.7.0 does not support KEEP_ALIVE. This * class enables KEEP_ALIVE in {@link TNonblockingServerTransport}. * @author jbae */ public class CustomServerSocket extends TNonblockingServerTransport { private static final Logger LOGGER = LoggerFactory.getLogger(TNonblockingServerTransport.class.getName()); /** * This channel is where all the nonblocking magic happens. */ private ServerSocketChannel serverSocketChannel = null; /** * Underlying ServerSocket object */ private ServerSocket serverSocket_ = null; private final ServerConfig config; public CustomServerSocket(ServerConfig config) throws TTransportException { this.config = config; InetSocketAddress bindAddr = new InetSocketAddress(config.getPort()); try { serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); // Make server socket serverSocket_ = serverSocketChannel.socket(); // Prevent 2MSL delay problem on server restarts serverSocket_.setReuseAddress(true); // Bind to listening port serverSocket_.bind(new InetSocketAddress(config.getPort())); } catch (IOException ioe) { serverSocket_ = null; throw new TTransportException("Could not create ServerSocket on address " + bindAddr.toString() + "."); } } public void listen() throws TTransportException { // Make sure not to block on accept if (serverSocket_ != null) { try { serverSocket_.setSoTimeout(0); } catch (SocketException sx) { sx.printStackTrace(); } } } protected TNonblockingSocket acceptImpl() throws TTransportException { if (serverSocket_ == null) { throw new TTransportException(TTransportException.NOT_OPEN, "No underlying server socket."); } try { SocketChannel socketChannel = serverSocketChannel.accept(); if (socketChannel == null) { return null; } TNonblockingSocket tsocket = new TNonblockingSocket(socketChannel); tsocket.setTimeout(0); // disabling client timeout tsocket.getSocketChannel().socket().setKeepAlive(true); tsocket.getSocketChannel().socket().setSendBufferSize(config.getSocketSendBufferBytes()); tsocket.getSocketChannel().socket().setReceiveBufferSize(config.getSocketRecvBufferBytes()); return tsocket; } catch (IOException iox) { throw new TTransportException(iox); } } public void registerSelector(Selector selector) { try { // Register the server socket channel, indicating an interest in // accepting new connections serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); } catch (ClosedChannelException e) { LOGGER.error("This shouldn't happen, ideally...: " + e.getMessage(), e); } } public void close() { if (serverSocket_ != null) { try { serverSocket_.close(); } catch (IOException iox) { LOGGER.warn("WARNING: Could not close server socket: " + iox.getMessage()); } serverSocket_ = null; } } public void interrupt() { // The thread-safeness of this is dubious, but Java documentation suggests // that it is safe to do this from a different thread context close(); } // for testing purpose public int getPort() { return serverSocket_.getLocalPort(); } }
1,406
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/input
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/input/thrift/MessageSetProcessor.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.input.thrift; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.Inject; import com.netflix.governator.guice.lazy.LazySingleton; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import com.netflix.servo.monitor.DynamicCounter; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.monitor.Monitors; import com.netflix.suro.ClientConfig; import com.netflix.suro.TagKey; import com.netflix.suro.input.SuroInput; import com.netflix.suro.message.DefaultMessageContainer; import com.netflix.suro.message.Message; import com.netflix.suro.message.MessageSetBuilder; import com.netflix.suro.message.MessageSetReader; import com.netflix.suro.queue.Queue4Server; import com.netflix.suro.routing.MessageRouter; import com.netflix.suro.thrift.*; import org.apache.thrift.TException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * The {@link TMessageSet} processor used by {@link com.netflix.suro.input.thrift.ThriftServer}. It takes incoming {@link TMessageSet} * sent by Suro client, validates each message set's CRC32 code, and then hands off validated message set to an internal queue. * A {@link MessageRouter} instance will asynchronously route the messages in the queue into configured sinks based on routing rules, * represented by {@link com.amazonaws.services.s3.model.RoutingRule}. * * Since this is the frontend of Thrift Server, it is implementing service status * and controlling to take the traffic or not. * * @author jbae */ @LazySingleton public class MessageSetProcessor implements SuroServer.Iface { private static final Logger log = LoggerFactory.getLogger(MessageSetProcessor.class); private SuroInput input; private boolean isTakingTraffic = true; public void stopTakingTraffic(){ this.isTakingTraffic = false; } public void startTakingTraffic(){ this.isTakingTraffic = true; } @Override public ServiceStatus getStatus() { if (isTakingTraffic){ return ServiceStatus.ALIVE; } else { return ServiceStatus.WARNING; } } private volatile boolean isRunning = false; private final Queue4Server queue; private final MessageRouter router; private final ServerConfig config; private ExecutorService executors; private final ObjectMapper jsonMapper; @Inject public MessageSetProcessor( Queue4Server queue, MessageRouter router, ServerConfig config, ObjectMapper jsonMapper) throws Exception { this.queue = queue; this.router = router; this.config = config; this.jsonMapper = jsonMapper; isRunning = true; Monitors.registerObject(this); } private static final String messageCountMetrics = "messageCount"; private static final String retryCountMetrics = "retryCount"; private static final String dataCorruptionCountMetrics = "corruptedMessageCount"; private static final String rejectedMessageCountMetrics = "rejectedMessageCount"; private static final String messageProcessErrorMetrics = "processErrorCount"; @Monitor(name ="QueueSize", type= DataSourceType.GAUGE) public int getQueueSize() { return queue.size(); } @Override public String getName() throws TException { return "Suro-MessageQueue"; } @Override public String getVersion() throws TException { return "V0.1.0"; } @Override public Result process(TMessageSet messageSet) throws TException { Result result = new Result(); try { // Stop adding chunks if it's no running if ( !isRunning) { DynamicCounter.increment(rejectedMessageCountMetrics, TagKey.APP, messageSet.getApp(), TagKey.REJECTED_REASON, "SURO_STOPPED"); log.warn("Message processor is not running. Message rejected"); result.setMessage("Suro server stopped"); result.setResultCode(ResultCode.STOPPED); return result; } if ( !isTakingTraffic ) { DynamicCounter.increment(rejectedMessageCountMetrics, TagKey.APP, messageSet.getApp(), TagKey.REJECTED_REASON, "SURO_THROTTLING"); log.warn("Suro is not taking traffic. Message rejected. "); result.setMessage("Suro server is not taking traffic"); result.setResultCode(ResultCode.OTHER_ERROR); return result; } MessageSetReader reader = new MessageSetReader(messageSet); if (!reader.checkCRC()) { DynamicCounter.increment(dataCorruptionCountMetrics, TagKey.APP, messageSet.getApp()); result.setMessage("data corrupted"); result.setResultCode(ResultCode.CRC_CORRUPTED); return result; } if (queue.offer(messageSet)) { DynamicCounter.increment( MonitorConfig.builder(messageCountMetrics) .withTag(TagKey.APP, messageSet.getApp()) .build(), messageSet.getNumMessages()); result.setMessage(Long.toString(messageSet.getCrc())); result.setResultCode(ResultCode.OK); } else { DynamicCounter.increment(retryCountMetrics, TagKey.APP, messageSet.getApp()); result.setMessage(Long.toString(messageSet.getCrc())); result.setResultCode(ResultCode.QUEUE_FULL); } return result; } catch (Exception e) { log.error("Exception when processing message set " + e.getMessage(), e); } return result; } public void start() { log.info("Starting processing message queue."); isRunning = true; executors = Executors.newFixedThreadPool(config.getMessageRouterThreads()); for (int i = 0; i < config.getMessageRouterThreads(); ++i) { executors.execute(new Runnable() { @Override public void run() { TMessageSet tMessageSet; long waitTime = config.messageRouterDefaultPollTimeout; while (isRunning) { try { tMessageSet = queue.poll(waitTime, TimeUnit.MILLISECONDS); if (tMessageSet == null) { if (waitTime < config.messageRouterMaxPollTimeout) { waitTime += config.messageRouterDefaultPollTimeout; } continue; } waitTime = config.messageRouterDefaultPollTimeout; processMessageSet(tMessageSet); } catch (Exception e) { log.error("Exception while handling TMessageSet: " + e.getMessage(), e); } } // drain remain when shutting down while ( !queue.isEmpty() ) { try { tMessageSet = queue.poll(0, TimeUnit.MILLISECONDS); processMessageSet(tMessageSet); } catch (Exception e) { log.error("Exception while processing drained message set: "+e.getMessage(), e); } } } }); } } @SuppressWarnings("unchecked") private void processMessageSet(TMessageSet tMessageSet) { MessageSetReader reader = new MessageSetReader(tMessageSet); for (final Message message : reader) { try { router.process(input, new DefaultMessageContainer(message, jsonMapper)); } catch (Exception e) { DynamicCounter.increment(messageProcessErrorMetrics, TagKey.APP, tMessageSet.getApp(), TagKey.DATA_SOURCE, message.getRoutingKey()); log.error(String.format("Failed to process message %s: %s", message, e.getMessage()), e); } } } @Override public long shutdown() throws TException { shutdown(config.messageRouterMaxPollTimeout * 2); return 0; } public void shutdown(long timeout) { log.info("MessageQueue is shutting down"); isRunning = false; try { executors.shutdown(); executors.awaitTermination(timeout, TimeUnit.MILLISECONDS); if ( !executors.isTerminated() ) { log.error("MessageDispatcher was not shut down gracefully"); } executors.shutdownNow(); } catch (InterruptedException e) { Thread.interrupted(); } } public TMessageSet poll(long timeout, TimeUnit unit) { try { return queue.poll(timeout, unit); } catch (InterruptedException e) { Thread.interrupted(); return new MessageSetBuilder(new ClientConfig()).build(); } } public void setInput(SuroInput input) { this.input = input; } }
1,407
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/input
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/input/thrift/ServerConfig.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.input.thrift; import com.netflix.governator.annotations.Configuration; /** * Configuration values for Suro server. Actual configuration values are assigned by * wired {@link com.netflix.governator.configuration.ConfigurationProvider} */ public class ServerConfig { public static final String SERVER_PORT = "SuroServer.port"; @Configuration(SERVER_PORT) private int port = 7101; public int getPort() { return port; } public static final String SERVER_STARTUP_TIMEOUT = "SuroServer.startupTimeout"; @Configuration(SERVER_STARTUP_TIMEOUT) private int startupTimeout = 5000; public int getStartupTimeout() { return startupTimeout; } public static final String THRIFT_WORKER_THREAD_NUM = "SuroServer.thriftWorkerThreadNum"; @Configuration(THRIFT_WORKER_THREAD_NUM) private int thriftWorkerThreadNum = -1; public int getThriftWorkerThreadNum() { if(thriftWorkerThreadNum < 0) { return Runtime.getRuntime().availableProcessors(); } return thriftWorkerThreadNum; } public static final String THRIFT_MAX_READ_BUFFER_BYTES = "SuroServer.thriftMaxReadBufferBytes"; @Configuration(THRIFT_MAX_READ_BUFFER_BYTES) private int thriftMaxReadBufferBytes = 1024 * 1024 * 400; public int getThriftMaxReadBufferBytes() { return thriftMaxReadBufferBytes; } public static final String SOCKET_SEND_BUFFER_BYTES = "SuroServer.socketSendBufferBytes"; @Configuration(SOCKET_SEND_BUFFER_BYTES) private int socketSendBufferBytes = 1024 * 1024 * 2; public int getSocketSendBufferBytes() { return socketSendBufferBytes; } public static final String SOCKET_RECV_BUFFER_BYTES = "SuroServer.socketRecvBufferBytes"; @Configuration(SOCKET_RECV_BUFFER_BYTES) private int socketRecvBufferBytes = 1024 * 1024 * 2; public int getSocketRecvBufferBytes() { return socketRecvBufferBytes; } public static final String QUEUE_TYPE = "SuroServer.queueType"; @Configuration(QUEUE_TYPE) private String queueType = "memory"; public String getQueueType() { return queueType; } public static final String MEMORY_QUEUE_CAPACITY = "SuroServer.memoryQueueCapacity"; @Configuration(MEMORY_QUEUE_CAPACITY) private int memoryQueueCapacity = 100; public int getQueueSize() { return memoryQueueCapacity; } public static final String MESSAGE_ROUTER_THREADS = "SuroServer.messageRouterThreads"; @Configuration(MESSAGE_ROUTER_THREADS) private int messageRouterThreads = 2; public int getMessageRouterThreads() { return messageRouterThreads; } @Configuration("SuroServer.statusServerPort") private int statusServerPort = 7103; public int getStatusServerPort() { return statusServerPort; } public static final String FILEQUEUE_PATH = "SuroServer.fileQueuePath"; @Configuration(FILEQUEUE_PATH) private String fileQueuePath = "/logs/suroserver"; public String getFileQueuePath() { return fileQueuePath; } public static final String FILEQUEUE_NAME = "SuroServer.fileQueueName"; @Configuration(FILEQUEUE_NAME) private String fileQueueName = "messageset"; public String getFileQueueName() { return fileQueueName; } public static final String FILEQUEUE_GC_PERIOD = "SuroServer.fileQueueGCPeriod"; @Configuration(FILEQUEUE_GC_PERIOD) private String fileQueueGCPeriod = "PT1m"; public String getFileQueueGCPeriod() { return fileQueueGCPeriod; } public static final String FILEQUEUE_SIZELIMIT = "SuroServer.fileQueueSizeLimit"; @Configuration(FILEQUEUE_SIZELIMIT) private long fileQueueSizeLimit = 10L * 1024L * 1024L * 1024L; // 10 GB public long getFileQueueSizeLimit() { return fileQueueSizeLimit; } public int messageRouterDefaultPollTimeout = 500; public int messageRouterMaxPollTimeout = 2500; @Override public String toString() { return "ServerConfig [port=" + port + ", startupTimeout=" + startupTimeout + ", thriftWorkerThreadNum=" + thriftWorkerThreadNum + ", thriftMaxReadBufferBytes=" + thriftMaxReadBufferBytes + ", socketSendBufferBytes=" + socketSendBufferBytes + ", socketRecvBufferBytes=" + socketRecvBufferBytes + ", queueType=" + queueType + ", memoryQueueCapacity=" + memoryQueueCapacity + ", messageRouterThreads=" + messageRouterThreads + ", statusServerPort=" + statusServerPort + ", messageRouterDefaultPollTimeout=" + messageRouterDefaultPollTimeout + ", messageRouterMaxPollTimeout=" + messageRouterMaxPollTimeout + "]"; } }
1,408
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/sink/ServerSinkPlugin.java
package com.netflix.suro.sink; import com.netflix.suro.SuroPlugin; import com.netflix.suro.message.Message; import com.netflix.suro.sink.elasticsearch.ElasticSearchSink; import com.netflix.suro.sink.kafka.KafkaSink; import com.netflix.suro.sink.kafka.KafkaSinkV2; import com.netflix.suro.sink.kafka.SuroKeyedMessage; import com.netflix.suro.sink.localfile.LocalFileSink; import com.netflix.suro.sink.notice.LogNotice; import com.netflix.suro.sink.notice.NoNotice; import com.netflix.suro.sink.notice.QueueNotice; import com.netflix.suro.sink.notice.SQSNotice; import com.netflix.suro.sink.remotefile.HdfsFileSink; import com.netflix.suro.sink.remotefile.S3FileSink; import com.netflix.suro.sink.remotefile.formatter.DateRegionStackFormatter; import com.netflix.suro.sink.remotefile.formatter.DynamicRemotePrefixFormatter; /** * * @author jbae */ public class ServerSinkPlugin extends SuroPlugin { @Override protected void configure() { this.addSinkType(LocalFileSink.TYPE, LocalFileSink.class); this.addSinkType(ElasticSearchSink.TYPE, ElasticSearchSink.class); this.addSinkType(KafkaSink.TYPE, KafkaSink.class); this.addSinkType(KafkaSinkV2.TYPE, KafkaSinkV2.class); Message.classMap.put((byte) 1, SuroKeyedMessage.class); this.addSinkType(S3FileSink.TYPE, S3FileSink.class); this.addSinkType(HdfsFileSink.TYPE, HdfsFileSink.class); this.addRemotePrefixFormatterType(DateRegionStackFormatter.TYPE, DateRegionStackFormatter.class); this.addRemotePrefixFormatterType(DynamicRemotePrefixFormatter.TYPE, DynamicRemotePrefixFormatter.class); this.addSinkType(SuroSink.TYPE, SuroSink.class); this.addNoticeType(NoNotice.TYPE, NoNotice.class); this.addNoticeType(QueueNotice.TYPE, QueueNotice.class); this.addNoticeType(SQSNotice.TYPE, SQSNotice.class); this.addNoticeType(LogNotice.TYPE, LogNotice.class); } }
1,409
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/sink
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/sink/notice/LogNotice.java
package com.netflix.suro.sink.notice; import com.netflix.util.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LogNotice implements Notice<String> { public static final String TYPE = "log"; private static Logger log = LoggerFactory.getLogger(LogNotice.class); @Override public void init() { } @Override public boolean send(String message) { log.info(message); return true; } @Override public String recv() { return null; } @Override public Pair<String, String> peek() { return null; } @Override public void remove(String key) { } @Override public String getStat() { return null; } }
1,410
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/sink
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/sink/notice/SQSNotice.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.sink.notice; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.services.sqs.AmazonSQSClient; import com.amazonaws.services.sqs.model.*; import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import com.netflix.servo.monitor.Monitors; import com.netflix.suro.TagKey; import com.netflix.util.Pair; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicLong; /** * SQS {@link com.netflix.suro.sink.notice.Notice} implementation * * @author jbae */ public class SQSNotice implements Notice<String> { static Logger log = LoggerFactory.getLogger(SQSNotice.class); public static final String TYPE = "sqs"; private final List<String> queues; private final List<String> queueUrls = new ArrayList<String>(); private final boolean enableBase64Encoding; private AmazonSQSClient sqsClient; private final AWSCredentialsProvider credentialsProvider; private ClientConfiguration clientConfig; private final String region; @Monitor(name = TagKey.SENT_COUNT, type = DataSourceType.COUNTER) private AtomicLong sentMessageCount = new AtomicLong(0); @Monitor(name = TagKey.LOST_COUNT, type = DataSourceType.COUNTER) private AtomicLong lostMessageCount = new AtomicLong(0); @Monitor(name = TagKey.RECV_COUNT, type = DataSourceType.COUNTER) private AtomicLong recvMessageCount = new AtomicLong(0); @JsonCreator public SQSNotice( @JsonProperty("queues") List<String> queues, @JsonProperty("region") @JacksonInject("region") String region, @JsonProperty("connectionTimeout") int connectionTimeout, @JsonProperty("maxConnections") int maxConnections, @JsonProperty("socketTimeout") int socketTimeout, @JsonProperty("maxRetries") int maxRetries, @JsonProperty("enableBase64Encoding") boolean enableBase64Encoding, @JacksonInject AmazonSQSClient sqsClient, @JacksonInject AWSCredentialsProvider credentialsProvider) { this.queues = queues; this.region = region; this.enableBase64Encoding = enableBase64Encoding; this.sqsClient = sqsClient; this.credentialsProvider = credentialsProvider; Preconditions.checkArgument(queues.size() > 0); Preconditions.checkNotNull(region); clientConfig = new ClientConfiguration(); if (connectionTimeout > 0) { clientConfig = clientConfig.withConnectionTimeout(connectionTimeout); } if (maxConnections > 0) { clientConfig = clientConfig.withMaxConnections(maxConnections); } if (socketTimeout > 0) { clientConfig = clientConfig.withSocketTimeout(socketTimeout); } if (maxRetries > 0) { clientConfig = clientConfig.withMaxErrorRetry(maxRetries); } Monitors.registerObject(Joiner.on('_').join(queues), this); } @Override public void init() { if (sqsClient == null) { // not injected sqsClient = new AmazonSQSClient(credentialsProvider, clientConfig); } String endpoint = "sqs." + this.region + ".amazonaws.com"; sqsClient.setEndpoint(endpoint); for (String queueName : queues) { GetQueueUrlRequest request = new GetQueueUrlRequest(); request.setQueueName(queueName); queueUrls.add(sqsClient.getQueueUrl(request).getQueueUrl()); } log.info(String.format("SQSNotice initialized with the endpoint: %s, queue: %s", endpoint, queues)); } @Override public boolean send(String message) { boolean sent = false; try { for (String queueUrl : queueUrls) { SendMessageRequest request = new SendMessageRequest() .withQueueUrl(queueUrl); if(enableBase64Encoding) { request = request.withMessageBody( new String( Base64.encodeBase64( message.getBytes(Charsets.UTF_8)))); } else { request = request.withMessageBody(message); } sqsClient.sendMessage(request); log.info("SQSNotice: " + message + " sent to " + queueUrl); if (!sent) { sentMessageCount.incrementAndGet(); sent = true; } } } catch (Exception e) { log.error("Exception while sending SQS notice: " + e.getMessage(), e); } if (!sent) { lostMessageCount.incrementAndGet(); } return sent; } @Override public String recv() { ReceiveMessageRequest request = new ReceiveMessageRequest() .withQueueUrl(queueUrls.get(0)) .withMaxNumberOfMessages(1); try { ReceiveMessageResult result = sqsClient.receiveMessage(request); if (!result.getMessages().isEmpty()) { Message msg = result.getMessages().get(0); recvMessageCount.incrementAndGet(); DeleteMessageRequest deleteReq = new DeleteMessageRequest() .withQueueUrl(queueUrls.get(0)) .withReceiptHandle(msg.getReceiptHandle()); sqsClient.deleteMessage(deleteReq); if (enableBase64Encoding) { return new String( Base64.decodeBase64(msg.getBody().getBytes()), Charsets.UTF_8); } else { return msg.getBody(); } } else { return ""; } } catch (Exception e) { log.error("Exception while recving SQS notice: " + e.getMessage(), e); return ""; } } @Override public Pair<String, String> peek() { ReceiveMessageRequest request = new ReceiveMessageRequest() .withQueueUrl(queueUrls.get(0)) .withMaxNumberOfMessages(1); try { ReceiveMessageResult result = sqsClient.receiveMessage(request); if (!result.getMessages().isEmpty()) { Message msg = result.getMessages().get(0); recvMessageCount.incrementAndGet(); if (enableBase64Encoding) { return new Pair<String, String>( msg.getReceiptHandle(), new String( Base64.decodeBase64(msg.getBody().getBytes()), Charsets.UTF_8)); } else { return new Pair<String, String>( msg.getReceiptHandle(), msg.getBody()); } } else { return null; } } catch (Exception e) { log.error("Exception while recving SQS notice: " + e.getMessage(), e); return null; } } @Override public void remove(String key) { DeleteMessageRequest deleteReq = new DeleteMessageRequest() .withQueueUrl(queueUrls.get(0)) .withReceiptHandle(key); sqsClient.deleteMessage(deleteReq); } @Override public String getStat() { return String.format("SQSNotice with the queues: %s, sent : %d, received: %d, dropped: %d", queues, sentMessageCount.get(), recvMessageCount.get(), lostMessageCount.get()); } }
1,411
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/server/SinkStat.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.server; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.suro.sink.SinkManager; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; @Singleton @Path("/surosinkstat") public class SinkStat { private final SinkManager sinkManager; @Inject public SinkStat(SinkManager sinkManager) { this.sinkManager = sinkManager; } @GET @Produces("text/plain") public String get() { return sinkManager.reportSinkStat(); } }
1,412
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/server/HealthCheck.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.server; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.suro.input.InputManager; import com.netflix.suro.input.thrift.ServerConfig; import com.netflix.suro.thrift.ServiceStatus; import com.netflix.suro.thrift.SuroServer; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import java.net.SocketException; /** * Healthcheck page for suro server * It is checking whether connecting to the suro server itself is available * * @author jbae */ @Path("/surohealthcheck") @Singleton public class HealthCheck { private static final Logger log = LoggerFactory.getLogger(HealthCheck.class); private final ServerConfig config; private final InputManager inputManager; private SuroServer.Client client; @Inject public HealthCheck(ServerConfig config, InputManager inputManager) throws SocketException, TTransportException { this.config = config; this.inputManager = inputManager; } @GET @Produces("text/plain") public synchronized String get() { try { if (inputManager.getInput("thrift") != null) { if (client == null) { client = getClient("localhost", config.getPort(), 5000); } ServiceStatus status = client.getStatus(); if (status != ServiceStatus.ALIVE) { throw new RuntimeException("NOT ALIVE!!!"); } } return "SuroServer - OK"; } catch (Exception e) { throw new RuntimeException("NOT ALIVE!!!"); } } private SuroServer.Client getClient(String host, int port, int timeout) throws SocketException, TTransportException { TSocket socket = new TSocket(host, port, timeout); socket.getSocket().setTcpNoDelay(true); socket.getSocket().setKeepAlive(true); socket.getSocket().setSoLinger(true, 0); TTransport transport = new TFramedTransport(socket); transport.open(); TProtocol protocol = new TBinaryProtocol(transport); return new SuroServer.Client(protocol); } }
1,413
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/server/StatusServer.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.server; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import com.google.inject.servlet.GuiceFilter; import com.google.inject.servlet.GuiceServletContextListener; import com.google.inject.servlet.ServletModule; import com.netflix.suro.input.thrift.ServerConfig; import com.sun.jersey.guice.spi.container.servlet.GuiceContainer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.ServletContextHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Embedded Jetty for status page * * @author jbae */ @Singleton public class StatusServer { static Logger log = LoggerFactory.getLogger(StatusServer.class); public static ServletModule createJerseyServletModule() { return new ServletModule() { @Override protected void configureServlets() { bind(HealthCheck.class); bind(SinkStat.class); bind(GuiceContainer.class).asEagerSingleton(); serve("/*").with(GuiceContainer.class); } }; } private final ExecutorService executor = Executors.newSingleThreadExecutor(); private final ServerConfig config; private final Injector injector; private final CountDownLatch startLatch = new CountDownLatch(1); @Inject public StatusServer(ServerConfig config, Injector injector) { this.injector = injector; this.config = config; } public void waitUntilStarted() throws InterruptedException { startLatch.await(); } public void start() { log.info("StatusServer starting"); executor.submit(new Runnable() { @Override public void run() { Server server = new Server(config.getStatusServerPort()); log.info("Starting status server on " + config.getStatusServerPort()); // Create a servlet context and add the jersey servlet. ServletContextHandler sch = new ServletContextHandler(server, "/"); // Add our Guice listener that includes our bindings sch.addEventListener(new GuiceServletContextListener() { @Override protected Injector getInjector() { return injector; } }); // Then add GuiceFilter and configure the server to // reroute all requests through this filter. sch.addFilter(GuiceFilter.class, "/*", null); // Must add DefaultServlet for embedded Jetty. // Failing to do this will cause 404 errors. // This is not needed if web.xml is used instead. sch.addServlet(DefaultServlet.class, "/"); // Start the server try { server.start(); startLatch.countDown(); server.join(); } catch (InterruptedException ie) { log.info("Interrupted to shutdown status server:"); } catch (Exception e) { log.error("Failed to start status server", e); } finally { try { server.stop(); log.info("StatusServer was shutdown"); } catch (Exception e) { log.error("Failed to join status server", e); } } } }); } public void shutdown() { try { log.info("StatusServer shutting down"); executor.shutdownNow(); } catch (Exception e) { //ignore exceptions while shutdown log.error("Exception while shutting down: " + e.getMessage(), e); } } }
1,414
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/queue/Queue4Server.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.queue; import com.google.inject.Inject; import com.netflix.suro.input.thrift.MessageSetSerDe; import com.netflix.suro.input.thrift.ServerConfig; import com.netflix.suro.thrift.TMessageSet; import org.joda.time.Period; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; /** * {@link BlockingQueue} wrapper that decides whether delegate queue operations to an in-memory bounded queue, or * to a disk-backed queue. An in-memory bounded blocking queue will be used if the configuration {@link com.netflix.suro.input.thrift.ServerConfig#getQueueType()} * returns "memory". Otherwise, a disk-backed queue will be used. * * @author jbae */ public class Queue4Server { private static final Logger logger = LoggerFactory.getLogger(Queue4Server.class); private BlockingQueue<TMessageSet> queue; private boolean isFile; @Inject public Queue4Server(ServerConfig config) { if (config.getQueueType().equals("memory")) { queue = new ArrayBlockingQueue<TMessageSet>(config.getQueueSize()); } else { isFile = true; try { queue = new FileBlockingQueue<TMessageSet>( config.getFileQueuePath(), config.getFileQueueName(), new Period(config.getFileQueueGCPeriod()).toStandardSeconds().getSeconds(), new MessageSetSerDe(), config.getFileQueueSizeLimit()); } catch (IOException e) { logger.error("Exception on initializing Queue4Server: " + e.getMessage(), e); } } } public boolean offer(TMessageSet msg) { return queue.offer(msg); } public TMessageSet poll(long timeout, TimeUnit timeUnit) throws InterruptedException { return queue.poll(timeout, timeUnit); } public void close() { if (isFile) { ((FileBlockingQueue<TMessageSet>) queue).close(); } } public boolean isEmpty() { return queue.isEmpty(); } public int size() { return queue.size(); } }
1,415
0
Create_ds/suro/suro-server/src/main/java/com/netflix/suro
Create_ds/suro/suro-server/src/main/java/com/netflix/suro/aws/PropertyAWSCredentialsProvider.java
package com.netflix.suro.aws; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.netflix.governator.annotations.Configuration; /** * An {@link AWSCredentialsProvider} implementation that is backed by Java properties. It is up to wired * {@link com.netflix.governator.configuration.ConfigurationProvider} to set the property values * for access key and secret key. If we use {@link com.netflix.suro.SuroServer}, then such properties can * be passed in using {@link com.netflix.suro.SuroServer}'s command line parameters. The properties are * set at server initialization time, and does not get refreshed. * * If you want to integrate with the profile-based credential provider, use Amazon's <a href="http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/auth/InstanceProfileCredentialsProvider.html">InstanceProfileCredentialsProvider</a> * * @author jbae * @author elandau */ public class PropertyAWSCredentialsProvider implements AWSCredentialsProvider { @Configuration("SuroServer.AWSAccessKey") private String accessKey; @Configuration("SuroServer.AWSSecretKey") private String secretKey; @Override public AWSCredentials getCredentials() { if (accessKey != null && secretKey != null) { return new AWSCredentials() { @Override public String getAWSAccessKeyId() { return accessKey; } @Override public String getAWSSecretKey() { return secretKey; } }; } else { return null; } } @Override public void refresh() { } }
1,416
0
Create_ds/suro/suro-integration-test/src/test/java/com/netflix
Create_ds/suro/suro-integration-test/src/test/java/com/netflix/suro/TestSuroClient.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro; import com.netflix.suro.client.SuroClient; import com.netflix.suro.message.Message; import com.netflix.suro.routing.TestMessageRouter; import com.netflix.suro.server.SuroServerExternalResource; import com.netflix.suro.sink.SinkManager; import org.apache.thrift.transport.TTransportException; import org.junit.Rule; import org.junit.Test; import java.util.Properties; import static org.junit.Assert.assertEquals; public class TestSuroClient { @Rule public SuroServerExternalResource suroServer = new SuroServerExternalResource(); @Test public void testSyncClient() throws TTransportException { // create the client final Properties clientProperties = new Properties(); clientProperties.setProperty(ClientConfig.LB_TYPE, "static"); clientProperties.setProperty(ClientConfig.LB_SERVER, "localhost:" + suroServer.getServerPort()); clientProperties.setProperty(ClientConfig.CLIENT_TYPE, "sync"); SuroClient client = new SuroClient(clientProperties); // send the message client.send(new Message("routingKey", "testMessage".getBytes())); // check the test server whether it got received TestMessageRouter.TestMessageRouterSink testSink = (TestMessageRouter.TestMessageRouterSink) suroServer.getInjector().getInstance(SinkManager.class).getSink("default"); assertEquals(testSink.getMessageList().size(), 1); assertEquals(testSink.getMessageList().get(0), "testMessage"); client.shutdown(); } @Test public void testAsyncClient() throws InterruptedException { // create the client final Properties clientProperties = new Properties(); clientProperties.setProperty(ClientConfig.LB_TYPE, "static"); clientProperties.setProperty(ClientConfig.LB_SERVER, "localhost:" + suroServer.getServerPort()); clientProperties.setProperty(ClientConfig.ASYNC_TIMEOUT, "0"); SuroClient client = new SuroClient(clientProperties); final int numMessages = 2; final int waitTime = 10; for (int i = 0; i < numMessages; ++i) { client.send(new Message("routingKey", "testMessage".getBytes())); } // check the test server whether it got received TestMessageRouter.TestMessageRouterSink testSink = (TestMessageRouter.TestMessageRouterSink) suroServer.getInjector().getInstance(SinkManager.class).getSink("default"); int count = 0; while (client.getSentMessageCount() < numMessages && count < waitTime) { Thread.sleep(1000); ++count; } assertEquals(client.getSentMessageCount(), numMessages); count = 0; while (testSink.getMessageList().size() < numMessages && count < waitTime) { Thread.sleep(1000); ++count; } assertEquals(testSink.getMessageList().size(), numMessages); for (int i = 0; i < numMessages; ++i) { assertEquals(testSink.getMessageList().get(0), "testMessage"); } } }
1,417
0
Create_ds/suro/suro-integration-test/src/test/java/com/netflix
Create_ds/suro/suro-integration-test/src/test/java/com/netflix/suro/TestSuroServer.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.netflix.suro.client.SuroClient; import com.netflix.suro.jackson.DefaultObjectMapper; import com.netflix.suro.message.Message; import com.netflix.suro.routing.TestMessageRouter; import com.netflix.suro.server.SuroServerExternalResource; import org.junit.Rule; import org.junit.Test; import java.util.List; import java.util.Map; import java.util.Properties; import static org.junit.Assert.assertTrue; public class TestSuroServer { private static final String inputConfig = "[\n" + " {\n" + " \"type\": \"thrift\"\n" + " }\n" + "]"; private static final String sinkDesc = "{\n" + " \"default\": {\n" + " \"type\": \"TestSink\",\n" + " \"message\": \"default\"\n" + " },\n" + " \"sink1\": {\n" + " \"type\": \"TestSink\",\n" + " \"message\": \"sink1\"\n" + " }\n" + "}"; private final String mapDesc = "{\n" + " \"topic1\": {\n" + " \"where\": [\n" + " {\"sink\" : \"sink1\"},\n" + " {\"sink\" : \"default\"}\n" + " ]\n" + " },\n" + " \"topic2\": {\n" + " \"where\": [\n" + " {\"sink\" : \"sink1\"}\n" + " ]\n" + " },\n" + " \"topic4\": {\n" + " \"where\": [{\n" + " \"sink\" : \"sink1\",\n" + " \"filter\" : {\n" + " \"type\" : \"xpath\",\n" + " \"filter\" : \"xpath(\\\"//foo/bar\\\") =~ \\\"^value[02468]$\\\"\",\n" + " \"converter\" : {\n" + " \"type\" : \"jsonmap\"\n" + " }\n" + " }\n" + " }]\n" + " }\n" + "}"; @Rule public SuroServerExternalResource suroServer = new SuroServerExternalResource(inputConfig, sinkDesc, mapDesc); @Test public void test() throws Exception { ObjectMapper jsonMapper = new DefaultObjectMapper(); try { // create the client final Properties clientProperties = new Properties(); clientProperties.setProperty(ClientConfig.LB_TYPE, "static"); clientProperties.setProperty(ClientConfig.LB_SERVER, "localhost:" + suroServer.getServerPort()); clientProperties.setProperty(ClientConfig.CLIENT_TYPE, "sync"); SuroClient client = new SuroClient(clientProperties); for (int i = 0; i < 10; ++i) { client.send(new Message("topic1", Integer.toString(i).getBytes())); } for (int i = 0; i < 5; ++i) { client.send(new Message("topic2", Integer.toString(i).getBytes())); } for (int i = 0; i < 20; ++i) { client.send(new Message("topic3", Integer.toString(i).getBytes())); } for(int i = 0; i < 30; ++i) { Map<String, Object> message = makeMessage("foo/bar", "value"+i); client.send(new Message("topic4", jsonMapper.writeValueAsBytes(message))); } int count = 10; while (!answer() && count > 0) { Thread.sleep(1000); --count; } assertTrue(answer()); client.shutdown(); } catch (Exception e) { System.err.println("SuroServer startup failed: " + e.getMessage()); System.exit(-1); } } private boolean answer() { Integer sink1 = TestMessageRouter.messageCount.get("sink1"); Integer defaultV = TestMessageRouter.messageCount.get("default"); System.out.println(sink1); return sink1 != null && sink1 == 20 && defaultV != null && defaultV == 30; } private Map<String, Object> makeMessage(String path, Object value) { Splitter splitter = Splitter.on("/").omitEmptyStrings().trimResults(); List<String> keys = Lists.newArrayList(splitter.split(path)); Map<String, Object> result = Maps.newHashMap(); Map<String, Object> current = result; for(int i = 0; i < keys.size() - 1; ++i) { Map<String, Object> map = Maps.newHashMap(); current.put(keys.get(i), map); current = map; } current.put(keys.get(keys.size() - 1), value); return result; } }
1,418
0
Create_ds/suro/suro-integration-test/src/test/java/com/netflix
Create_ds/suro/suro-integration-test/src/test/java/com/netflix/suro/TestPauseOnLongQueueKafkaConsumer.java
package com.netflix.suro; import com.amazonaws.util.StringInputStream; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.BeanProperty; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.InjectableValues; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.NamedType; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.util.concurrent.RateLimiter; import com.netflix.client.http.HttpRequest; import com.netflix.client.http.HttpResponse; import com.netflix.niws.client.http.RestClient; import com.netflix.suro.input.kafka.KafkaConsumer; import com.netflix.suro.jackson.DefaultObjectMapper; import com.netflix.suro.message.DefaultMessageContainer; import com.netflix.suro.message.Message; import com.netflix.suro.routing.MessageRouter; import com.netflix.suro.routing.RoutingMap; import com.netflix.suro.sink.QueuedSink; import com.netflix.suro.sink.Sink; import com.netflix.suro.sink.SinkManager; import com.netflix.suro.sink.elasticsearch.ElasticSearchSink; import com.netflix.suro.sink.kafka.KafkaRetentionPartitioner; import com.netflix.suro.sink.kafka.KafkaServerExternalResource; import com.netflix.suro.sink.kafka.KafkaSink; import com.netflix.suro.sink.kafka.ZkExternalResource; import kafka.admin.TopicCommand; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.RuleChain; import org.junit.rules.TestRule; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; public class TestPauseOnLongQueueKafkaConsumer { public static ZkExternalResource zk = new ZkExternalResource(); public static KafkaServerExternalResource kafkaServer = new KafkaServerExternalResource(zk); @ClassRule public static TestRule chain = RuleChain .outerRule(zk) .around(kafkaServer); private static final String TOPIC_NAME = "tpolq_kafka"; private final CountDownLatch latch = new CountDownLatch(1); @Test public void test() throws Exception { TopicCommand.createTopic(zk.getZkClient(), new TopicCommand.TopicCommandOptions(new String[]{ "--zookeeper", "dummy", "--create", "--topic", TOPIC_NAME, "--replication-factor", "2", "--partitions", "1"})); final ObjectMapper jsonMapper = new DefaultObjectMapper(); jsonMapper.setInjectableValues(new InjectableValues() { @Override public Object findInjectableValue(Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance) { if (valueId.equals(KafkaRetentionPartitioner.class.getName())) { return new KafkaRetentionPartitioner(); } else { return null; } } }); final KafkaSink kafkaSink = createKafkaProducer(jsonMapper, kafkaServer.getBrokerListStr()); RestClient client = mock(RestClient.class); final ElasticSearchSink sink = new ElasticSearchSink( "tpolq", null, 10, 1000, Lists.newArrayList("localhost:9200"), null, 0,0,0,0,0, null, false, jsonMapper, client ); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { final HttpRequest bulk = (HttpRequest) invocation.getArguments()[0]; int numRecords = bulk.getEntity().toString().split("\n").length / 2; latch.await(); HttpResponse result = mock(HttpResponse.class); doReturn(200).when(result).getStatus(); List list = new ArrayList(); for (int i = 0; i < numRecords; ++i) { list.add(new ImmutableMap.Builder<>().put("create", new ImmutableMap.Builder<>().put("status", 200).build()).build()); } doReturn(new StringInputStream( jsonMapper.writeValueAsString( new ImmutableMap.Builder<>() .put("took", 1000) .put("items", list) .build()))).when(result).getInputStream(); return result; } }).when(client).executeWithLoadBalancer(any(HttpRequest.class)); sink.open(); RoutingMap map = new RoutingMap(); map.set(new ImmutableMap.Builder<String, RoutingMap.RoutingInfo>() .put(TOPIC_NAME, new RoutingMap.RoutingInfo(Lists.newArrayList(new RoutingMap.Route("es", null, null)), null)) .build()); SinkManager sinks = new SinkManager(); sinks.initialSet(new ImmutableMap.Builder<String, Sink>() .put("es", sink).build()); MessageRouter router = new MessageRouter(map, sinks, jsonMapper); Properties properties = new Properties(); properties.setProperty("group.id", "testkafkaconsumer"); properties.setProperty("zookeeper.connect", zk.getConnectionString()); properties.setProperty("auto.offset.reset", "smallest"); properties.setProperty("consumer.timeout.ms", "1000"); KafkaConsumer consumer = new KafkaConsumer(properties, TOPIC_NAME, 1, router, jsonMapper); consumer.start(); // set the pause threshold to 100 QueuedSink.MAX_PENDING_MESSAGES_TO_PAUSE = 10; Thread t = createProducerThread(jsonMapper, kafkaSink, TOPIC_NAME); // wait until queue's is full over the threshold int count = 0; while (count < 3) { System.out.println("pending messages:" + sink.getNumOfPendingMessages()); if (sink.getNumOfPendingMessages() >= QueuedSink.MAX_PENDING_MESSAGES_TO_PAUSE) { ++count; } Thread.sleep(1000); } // get the number of pending messages for 10 seconds ArrayList<Integer> countList = new ArrayList<>(); for (int i = 0; i < 10; ++i) { countList.add((int) sink.getNumOfPendingMessages()); Thread.sleep(1000); } for (int i = 6; i < 9; ++i) { assertEquals(countList.get(i), countList.get(i + 1), 5); } latch.countDown(); run.set(false); t.join(); consumer.shutdown(); sink.close(); assertEquals(sink.getNumOfPendingMessages(), 0); } private KafkaSink createKafkaProducer(ObjectMapper jsonMapper, String brokerListStr) throws java.io.IOException { String description = "{\n" + " \"type\": \"kafka\",\n" + " \"client.id\": \"kafkasink\",\n" + " \"bootstrap.servers\": \"" + brokerListStr + "\",\n" + " \"acks\": 1\n" + "}"; jsonMapper.registerSubtypes(new NamedType(KafkaSink.class, "kafka")); final KafkaSink kafkaSink = jsonMapper.readValue(description, new TypeReference<Sink>(){}); kafkaSink.open(); return kafkaSink; } private final AtomicBoolean run = new AtomicBoolean(true); private Thread createProducerThread(final ObjectMapper jsonMapper, final KafkaSink kafkaSink, final String topicName) { Thread t = new Thread(new Runnable() { private final RateLimiter rateLimiter = RateLimiter.create(10); @Override public void run() { while (run.get()) { rateLimiter.acquire(); try { kafkaSink.writeTo(new DefaultMessageContainer( new Message( topicName, jsonMapper.writeValueAsBytes( new ImmutableMap.Builder<String, Object>() .put("f1", "v1") .put("f2", "v2") .build())), jsonMapper)); } catch (Exception e) { fail(); } } kafkaSink.close(); } }); t.start(); return t; } }
1,419
0
Create_ds/suro/suro-integration-test/src/test/java/com/netflix
Create_ds/suro/suro-integration-test/src/test/java/com/netflix/suro/TestPauseOnInsufficientDiskSpaceThriftServer.java
package com.netflix.suro; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.util.concurrent.RateLimiter; import com.netflix.suro.client.SuroClient; import com.netflix.suro.input.thrift.MessageSetProcessor; import com.netflix.suro.input.thrift.ServerConfig; import com.netflix.suro.input.thrift.ThriftServer; import com.netflix.suro.jackson.DefaultObjectMapper; import com.netflix.suro.message.Message; import com.netflix.suro.queue.MemoryQueue4Sink; import com.netflix.suro.queue.Queue4Server; import com.netflix.suro.routing.MessageRouter; import com.netflix.suro.routing.RoutingMap; import com.netflix.suro.sink.Sink; import com.netflix.suro.sink.SinkManager; import com.netflix.suro.sink.localfile.LocalFileSink; import com.netflix.suro.thrift.ServiceStatus; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; public class TestPauseOnInsufficientDiskSpaceThriftServer { @Rule public TemporaryFolder tempDir = new TemporaryFolder(); private static final String TOPIC_NAME = "tpolq_thrift"; private volatile boolean hasEnoughSpace = true; private LocalFileSink.SpaceChecker createMockedSpaceChecker() { LocalFileSink.SpaceChecker spaceChecker = mock(LocalFileSink.SpaceChecker.class); doReturn(hasEnoughSpace).when(spaceChecker).hasEnoughSpace(); return spaceChecker; } @Test public void test() throws Exception { ServerConfig config = new ServerConfig(); final ObjectMapper jsonMapper = new DefaultObjectMapper(); LocalFileSink.SpaceChecker spaceChecker = mock(LocalFileSink.SpaceChecker.class); LocalFileSink sink = new LocalFileSink( tempDir.newFolder().getAbsolutePath(), null, null, 0, "PT1s", 10, new MemoryQueue4Sink(10000), 100, 1000, true, spaceChecker ); sink.open(); SinkManager sinks = new SinkManager(); sinks.initialSet(new ImmutableMap.Builder<String, Sink>() .put("local", sink).build()); RoutingMap map = new RoutingMap(); map.set(new ImmutableMap.Builder<String, RoutingMap.RoutingInfo>() .put(TOPIC_NAME, new RoutingMap.RoutingInfo(Lists.newArrayList(new RoutingMap.Route("local", null, null)), null)) .build()); MessageSetProcessor msgProcessor = new MessageSetProcessor( new Queue4Server(config), new MessageRouter(map, sinks, jsonMapper), config, jsonMapper ); ThriftServer server = new ThriftServer(config, msgProcessor); server.start(); SuroClient client = createSuroClient(server.getPort()); Thread t = createClientThread(jsonMapper, client, TOPIC_NAME); // checking the traffic goes for (int i = 0; i < 10; ++i) { if (client.getSentMessageCount() > 0) { break; } Thread.sleep(1000); } assertTrue(client.getSentMessageCount() > 0); // shutting down the traffic hasEnoughSpace = false; int count = 0; while (count < 3) { if (msgProcessor.getStatus() == ServiceStatus.WARNING) { ++count; } } assertEquals(count, 3); client.shutdown(); run.set(false); t.join(); // resuming the traffic hasEnoughSpace = true; run.set(true); SuroClient newClient = createSuroClient(server.getPort()); t = createClientThread(jsonMapper, newClient, TOPIC_NAME); for (int i = 0; i < 10; ++i) { if (client.getSentMessageCount() > 0) { break; } Thread.sleep(1000); } assertTrue(client.getSentMessageCount() > 0); run.set(false); t.join(); client.shutdown(); server.shutdown(); sink.close(); assertEquals(sink.getNumOfPendingMessages(), 0); } private SuroClient createSuroClient(int port) throws java.io.IOException { final Properties clientProperties = new Properties(); clientProperties.setProperty(ClientConfig.CLIENT_TYPE, "sync"); clientProperties.setProperty(ClientConfig.LB_TYPE, "static"); clientProperties.setProperty(ClientConfig.LB_SERVER, "localhost:" + port); clientProperties.setProperty(ClientConfig.ASYNC_TIMEOUT, "0"); clientProperties.setProperty(ClientConfig.ENABLE_OUTPOOL, "true"); return new SuroClient(clientProperties); } private final AtomicBoolean run = new AtomicBoolean(true); private Thread createClientThread(final ObjectMapper jsonMapper, final SuroClient client, final String topicName) { Thread t = new Thread(new Runnable() { private final RateLimiter rateLimiter = RateLimiter.create(100); // 100 per seconds @Override public void run() { while (run.get()) { rateLimiter.acquire(); try { client.send( new Message( topicName, jsonMapper.writeValueAsBytes( new ImmutableMap.Builder<String, Object>() .put("f1", "v1") .put("f2", "v2") .build()))); } catch (JsonProcessingException e) { fail(); } } client.shutdown(); } }); t.start(); return t; } }
1,420
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/sink/TestQueuedSink.java
package com.netflix.suro.sink; import com.netflix.suro.message.Message; import com.netflix.suro.queue.FileQueue4Sink; import com.netflix.suro.queue.MemoryQueue4Sink; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class TestQueuedSink { @Rule public TemporaryFolder folder= new TemporaryFolder(); @Test public void testDrainOnce() throws IOException { FileQueue4Sink queue = new FileQueue4Sink(folder.newFolder().getAbsolutePath(), "testDrainOnce", "PT1m", 1024 * 1024 * 1024); final List<Message> sentMessageList = new LinkedList<Message>(); QueuedSink sink = new QueuedSink() { @Override protected void beforePolling() throws IOException { } @Override protected void write(List<Message> msgList) throws IOException { sentMessageList.addAll(msgList); msgList.clear(); } @Override protected void innerClose() throws IOException { } }; sink.initialize(queue, 100, 1000); sink.start(); int msgCount = 1000; for (int i = 0; i < msgCount; ++i) { queue.offer(new Message("routingKey", ("message" + i).getBytes())); } sink.close(); assertEquals(sentMessageList.size(), msgCount); } @Test public void shouldIncrementDroppedCounter() throws InterruptedException { final int queueCapacity = 200; final MemoryQueue4Sink queue = new MemoryQueue4Sink(queueCapacity); QueuedSink sink = new QueuedSink() { @Override protected void beforePolling() throws IOException { } @Override protected void write(List<Message> msgList) throws IOException { throw new RuntimeException("prevent to drain the queue"); } @Override protected void innerClose() throws IOException { } }; sink.initialize(queue, 100, 1000); sink.start(); int msgCount = 1000; for (int i = 0; i < msgCount; ++i) { sink.enqueue(new Message("routingKey", ("message" + i).getBytes())); } for (int i = 0; i < 10; ++i) { if (sink.droppedMessagesCount.get() < msgCount) { Thread.sleep(1000); } } sink.close(); assertEquals(sink.droppedMessagesCount.get(), msgCount); } @Test public void synchronizedQueue() throws InterruptedException { final int queueCapacity = 0; final MemoryQueue4Sink queue = new MemoryQueue4Sink(queueCapacity); final AtomicInteger sentCount = new AtomicInteger(); QueuedSink sink = new QueuedSink() { @Override protected void beforePolling() throws IOException { } @Override protected void write(List<Message> msgList) throws IOException { sentCount.addAndGet(msgList.size()); } @Override protected void innerClose() throws IOException { } }; sink.initialize(queue, 100, 1000); sink.start(); int msgCount = 1000; int offered = 0; for (int i = 0; i < msgCount; ++i) { if (queue.offer(new Message("routingKey", ("message" + i).getBytes()))) { offered++; } } assertEquals(msgCount, offered); for (int i = 0; i < 20; ++i) { if (sentCount.get() < offered) { Thread.sleep(500); } } assertEquals(sentCount.get(), offered); } @Test public void shouldNotPauseOnShortQueue() { QueuedSink sink = new QueuedSink() { @Override protected void beforePolling() throws IOException { } @Override protected void write(List<Message> msgList) throws IOException { } @Override protected void innerClose() throws IOException { } }; int queueCapacity = 10000; final MemoryQueue4Sink queue = new MemoryQueue4Sink(queueCapacity); final int initialCount = queueCapacity / 2 - 10; for (int i = 0; i < initialCount; ++i) { queue.offer(new Message("routingKey", ("testMessage" + i).getBytes())); } sink.initialize(queue, 100, 1000); assertEquals(sink.checkPause(), 0); } @Test public void shouldPauseOnLongQueue() throws InterruptedException { QueuedSink sink = new QueuedSink() { @Override protected void beforePolling() throws IOException { } @Override protected void write(List<Message> msgList) throws IOException { } @Override protected void innerClose() throws IOException { } }; int queueCapacity = 10000; final MemoryQueue4Sink queue = new MemoryQueue4Sink(queueCapacity); final int initialCount = queueCapacity / 2 + 10; for (int i = 0; i < initialCount; ++i) { queue.offer(new Message("routingKey", ("testMessage" + i).getBytes())); } sink.initialize(null, queue, 100, 1000, true); assertEquals(sink.checkPause(), queue.size()); queue.drain(Integer.MAX_VALUE, new LinkedList<Message>()); /////////////////////////// sink = new QueuedSink() { @Override protected void beforePolling() throws IOException { } @Override protected void write(List<Message> msgList) throws IOException { } @Override protected void innerClose() throws IOException { } }; QueuedSink.MAX_PENDING_MESSAGES_TO_PAUSE = 100; for (int i = 0; i < QueuedSink.MAX_PENDING_MESSAGES_TO_PAUSE + 1; ++i) { queue.offer(new Message("routingKey", ("testMessage" + i).getBytes())); } sink.initialize(null, queue, 100, 1000, true); assertEquals(sink.checkPause(), queue.size()); QueuedSink.MAX_PENDING_MESSAGES_TO_PAUSE = 1000000; queue.drain(Integer.MAX_VALUE, new LinkedList<Message>()); //////////////////////////// sink = new QueuedSink() { @Override protected void beforePolling() throws IOException { } @Override protected void write(List<Message> msgList) throws IOException { } @Override protected void innerClose() throws IOException { } }; sink.initialize(null, queue, 100, 1000, true); sink.throughput.increment(initialCount); for (int i = 0; i < initialCount; ++i) { queue.offer(new Message("routingKey", ("testMessage" + i).getBytes())); } assertTrue(sink.checkPause() < queue.size() && sink.checkPause() > 0); } }
1,421
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/queue/TestFileBlockingQueue.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.queue; import com.netflix.suro.message.Message; import com.netflix.suro.message.MessageSerDe; import com.netflix.suro.message.StringSerDe; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.util.Iterator; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import static org.junit.Assert.*; public class TestFileBlockingQueue { @Rule public TemporaryFolder tempDir = new TemporaryFolder(); @Test public void testOpenAndReadFromStart() throws IOException { final FileBlockingQueue<String> queue = getFileBlockingQueue(); createFile(queue, 3000); int count = 0; for (String m : new Iterable<String>() { @Override public Iterator<String> iterator() { return queue.iterator(); } }) { assertEquals(m, "testString" + count); ++count; } assertEquals(count, 3000); } private FileBlockingQueue<String> getFileBlockingQueue() throws IOException { return new FileBlockingQueue<String>( tempDir.newFolder().getAbsolutePath(), "default", 3600, new StringSerDe()); } @Test public void testOpenAndReadFromMark() throws IOException { final FileBlockingQueue<String> queue = getFileBlockingQueue(); createFile(queue, 3000); int count = 0; for (String m : new Iterable<String>() { @Override public Iterator<String> iterator() { return queue.iterator(); } }) { assertEquals(m, "testString" + count); ++count; } assertEquals(count, 3000); count = 0; createFile(queue, 3000); for (String m : new Iterable<String>() { @Override public Iterator<String> iterator() { return queue.iterator(); } }) { assertEquals(m, "testString" + count); ++count; } assertEquals(count, 3000); } @Test public void testPollWait() throws InterruptedException, IOException { final FileBlockingQueue<String> queue = getFileBlockingQueue(); final AtomicLong start = new AtomicLong(System.currentTimeMillis()); String m = queue.poll(1000, TimeUnit.MILLISECONDS); final AtomicLong duration = new AtomicLong(System.currentTimeMillis() - start.get()); assertTrue(duration.get() >= 1000 && duration.get() <= 2000); assertNull(m); ExecutorService e = Executors.newFixedThreadPool(1); e.execute(new Runnable() { @Override public void run() { start.set(System.currentTimeMillis()); String m = null; try { m = queue.poll(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException e1) { throw new RuntimeException(e1); } assertNotNull(m); duration.set(System.currentTimeMillis() - start.get()); } }); Thread.sleep(1000); queue.offer("testString"); assertTrue(duration.get() < 4000); } private void createFile(FileBlockingQueue<String> queue, int count) throws IOException { for (int i = 0; i < count; ++i) { assertTrue(queue.offer("testString" + i)); } } @Test public void testMultithreaded() throws IOException, InterruptedException { final FileBlockingQueue<Message> queue = new FileBlockingQueue<Message>( tempDir.newFolder().getAbsolutePath(), "default", 3600, new MessageSerDe()); final int messagecount = 100; final int threadCount = 10; ExecutorService executors = Executors.newFixedThreadPool(threadCount); final CountDownLatch latch = new CountDownLatch(threadCount + 1); final CountDownLatch producerStartLatch = new CountDownLatch(1); final CountDownLatch consumerStartLatch = new CountDownLatch(1); for (int i = 0; i < threadCount; ++i) { executors.execute(new Runnable() { @Override public void run() { try { producerStartLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } for (int j = 0; j < messagecount; ++j) { String str = generateRandomString(); Message msg = new Message("testRoutingKey", str.getBytes()); queue.offer(msg); } latch.countDown(); consumerStartLatch.countDown(); } }); } executors.execute(new Runnable() { @Override public void run() { try { consumerStartLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 0; i < threadCount * messagecount; ++i) { Message msg = queue.poll(); assertEquals(msg.getRoutingKey(), "testRoutingKey"); assertEquals(new String(msg.getPayload()).length(), 4096); } latch.countDown(); } }); producerStartLatch.countDown(); latch.await(); } public String generateRandomString() { Random rand = new Random(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4096; ++i) { sb.append((char) (rand.nextInt(95) + 32)); } return sb.toString(); } }
1,422
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/queue/FileQueueLoadTest.java
package com.netflix.suro.queue; import com.netflix.suro.message.Message; import com.netflix.suro.message.MessageSerDe; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.util.Collections; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.*; @Ignore public class FileQueueLoadTest { @Rule public TemporaryFolder tempDir = new TemporaryFolder(); private static FileBlockingQueue<Message> bigQueue; // configurable parameters ////////////////////////////////////////////////////////////////// private static int loop = 5; private static int totalItemCount = 100000; private static int producerNum = 4; private static int consumerNum = 1; private static int messageLength = 1024; ////////////////////////////////////////////////////////////////// private static enum Status { ERROR, SUCCESS } private static class Result { Status status; } private static final AtomicInteger producingItemCount = new AtomicInteger(0); private static final AtomicInteger consumingItemCount = new AtomicInteger(0); private static final Set<String> itemSet = Collections.newSetFromMap(new ConcurrentHashMap<String,Boolean>()); static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; static Random rnd = new Random(); public static String randomString(int len ) { StringBuilder sb = new StringBuilder( len ); for( int i = 0; i < len; i++ ) sb.append( AB.charAt( rnd.nextInt(AB.length()) ) ); return sb.toString(); } private static class Producer extends Thread { private final CountDownLatch latch; private final Queue<Result> resultQueue; public Producer(CountDownLatch latch, Queue<Result> resultQueue) { this.latch = latch; this.resultQueue = resultQueue; } public void run() { Result result = new Result(); String rndString = randomString(messageLength); try { latch.countDown(); latch.await(); while(true) { int count = producingItemCount.incrementAndGet(); if(count > totalItemCount) break; String item = rndString + count; itemSet.add(item); bigQueue.put(new Message("routing", item.getBytes())); } result.status = Status.SUCCESS; } catch (Exception e) { e.printStackTrace(); result.status = Status.ERROR; } resultQueue.offer(result); } } private static class Consumer extends Thread { private final CountDownLatch latch; private final Queue<Result> resultQueue; public Consumer(CountDownLatch latch, Queue<Result> resultQueue) { this.latch = latch; this.resultQueue = resultQueue; } public void run() { Result result = new Result(); try { latch.countDown(); latch.await(); while(true) { int index = consumingItemCount.getAndIncrement(); if (index >= totalItemCount) break; Message item = bigQueue.take(); assertNotNull(item); assertTrue(itemSet.remove(new String(item.getPayload()))); } result.status = Status.SUCCESS; } catch (Exception e) { e.printStackTrace(); result.status = Status.ERROR; } resultQueue.offer(result); } } @Test public void runTest() throws Exception { createQueue(); System.out.println("Load test begin ..."); for(int i = 0; i < loop; i++) { System.out.println("[doRunProduceThenConsume] round " + (i + 1) + " of " + loop); this.doRunProduceThenConsume(); // reset producingItemCount.set(0); consumingItemCount.set(0); } bigQueue.close(); createQueue(); for(int i = 0; i < loop; i++) { System.out.println("[doRunMixed] round " + (i + 1) + " of " + loop); this.doRunMixed(); // reset producingItemCount.set(0); consumingItemCount.set(0); } System.out.println("Load test finished successfully."); } private void createQueue() throws IOException { bigQueue = new FileBlockingQueue<Message>(tempDir.newFolder().getAbsolutePath(), "load_test", 1, new MessageSerDe()); } public void doRunProduceThenConsume() throws Exception { //prepare CountDownLatch platch = new CountDownLatch(producerNum); CountDownLatch clatch = new CountDownLatch(consumerNum); BlockingQueue<Result> producerResults = new LinkedBlockingQueue<Result>(); BlockingQueue<Result> consumerResults = new LinkedBlockingQueue<Result>(); //run testing for(int i = 0; i < producerNum; i++) { Producer p = new Producer(platch, producerResults); p.start(); } for(int i = 0; i < producerNum; i++) { Result result = producerResults.take(); assertEquals(result.status, Status.SUCCESS); } assertTrue(!bigQueue.isEmpty()); assertEquals(bigQueue.size(), totalItemCount); assertEquals(itemSet.size(), totalItemCount); for(int i = 0; i < consumerNum; i++) { Consumer c = new Consumer(clatch, consumerResults); c.start(); } for(int i = 0; i < consumerNum; i++) { Result result = consumerResults.take(); assertEquals(result.status, Status.SUCCESS); } assertTrue(itemSet.isEmpty()); assertTrue(bigQueue.isEmpty()); assertTrue(bigQueue.size() == 0); } public void doRunMixed() throws Exception { //prepare CountDownLatch allLatch = new CountDownLatch(producerNum + consumerNum); BlockingQueue<Result> producerResults = new LinkedBlockingQueue<Result>(); BlockingQueue<Result> consumerResults = new LinkedBlockingQueue<Result>(); //run testing for(int i = 0; i < producerNum; i++) { Producer p = new Producer(allLatch, producerResults); p.start(); } for(int i = 0; i < consumerNum; i++) { Consumer c = new Consumer(allLatch, consumerResults); c.start(); } //verify for(int i = 0; i < producerNum; i++) { Result result = producerResults.take(); assertEquals(result.status, Status.SUCCESS); } for(int i = 0; i < consumerNum; i++) { Result result = consumerResults.take(); assertEquals(result.status, Status.SUCCESS); } assertTrue(itemSet.isEmpty()); assertTrue(bigQueue.isEmpty()); assertTrue(bigQueue.size() == 0); } }
1,423
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/RoutingKeyFilterTest.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.routing; import com.netflix.suro.message.MessageContainer; import org.junit.Test; import static com.netflix.suro.routing.FilterTestUtil.makeMessageContainer; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * */ public class RoutingKeyFilterTest { @Test public void testDoFilter() throws Exception { RoutingKeyFilter filter = new RoutingKeyFilter("(?i)key"); MessageContainer container = makeMessageContainer("routingkEYname", null, null); assertTrue(filter.doFilter(container)); } @Test public void negativeTest() throws Exception { RoutingKeyFilter filter = new RoutingKeyFilter("nomatch"); MessageContainer container = makeMessageContainer("routingkey", null, null); assertFalse(filter.doFilter(container)); } }
1,424
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/XpathFilterTest.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.routing; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import com.netflix.suro.message.DefaultMessageContainer; import com.netflix.suro.message.Message; import org.junit.Test; import static com.netflix.suro.routing.FilterTestUtil.makeMessageContainer; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * */ public class XpathFilterTest { private ObjectMapper jsonMapper = new ObjectMapper(); @Test public void testXPathFilterWorksWithMap() throws Exception { String path = "//foo/bar/value"; Integer value = 6; XPathFilter filter = new XPathFilter(String.format("xpath(\"%s\") > 5", path), new JsonMapConverter()); assertTrue(filter.doFilter(makeMessageContainer("key", path, value))); } @Test public void testExistFilter() throws Exception { XPathFilter filter = new XPathFilter("xpath(\"data.fit.sessionId\") exists", new JsonMapConverter()); assertTrue(filter.doFilter(new DefaultMessageContainer(new Message( "routingKey", jsonMapper.writeValueAsBytes( new ImmutableMap.Builder<String, Object>() .put("data.fit.sessionId", "abc") .put("f1", "v1") .build())), jsonMapper))); assertFalse(filter.doFilter(new DefaultMessageContainer(new Message( "routingKey", jsonMapper.writeValueAsBytes( new ImmutableMap.Builder<String, Object>() .put("data.fit.sessionIdABC", "abc") .put("f1", "v1") .build())), jsonMapper))); } }
1,425
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/FilterTestUtil.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.routing; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.netflix.suro.message.MessageContainer; import java.util.List; import java.util.Map; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * */ public class FilterTestUtil { private static final Splitter PATH_SPLITTER = Splitter.on("/").omitEmptyStrings().trimResults(); // Returns a message container that has the given routing key , and payload that has the given path and given value public static MessageContainer makeMessageContainer(String routingKey, String path, Object value) throws Exception { MessageContainer container = mock(MessageContainer.class); when(container.getRoutingKey()).thenReturn(routingKey); if(path == null) { return container; } List<String> steps = Lists.newArrayList(PATH_SPLITTER.split(path)); Map<String, Object> map = Maps.newHashMap(); Map<String, Object> current = map; for(int i = 0; i < steps.size() - 1; i++) { String step = steps.get(i); Map<String, Object> obj = Maps.newHashMap(); current.put(step, obj); current = obj; } current.put(steps.get(steps.size() - 1), value); when(container.getEntity(Map.class)).thenReturn(map); return container; } }
1,426
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/ExistsMessageFilterTest.java
package com.netflix.suro.routing.filter; import com.google.common.collect.ImmutableMap; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ExistsMessageFilterTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testValueComparison() throws Exception { Object[][] inputs = { {new ImmutableMap.Builder<String, Object>().put("abc", "v1").put("f1", "v2").build(), "abc", true}, {new ImmutableMap.Builder<String, Object>().put("def", "v1").put("f1", "v2").build(), "abc", false} }; for(Object[] input : inputs){ String value = input[0].toString(); String field = (String)input[1]; boolean expected = ((Boolean)input[2]).booleanValue(); PathExistsMessageFilter pred = new PathExistsMessageFilter(field); assertEquals(String.format("Given value = %s, and field = %s", value, field), expected, pred.apply(input)); } } }
1,427
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/AlwaysTrueMessageFilterTest.java
package com.netflix.suro.routing.filter; import org.junit.After; import org.junit.Before; import org.junit.Test; import static com.netflix.suro.routing.filter.VerificationUtil.DUMMY_INPUT; import static org.junit.Assert.assertTrue; public class AlwaysTrueMessageFilterTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void test() { assertTrue(AlwaysTrueMessageFilter.INSTANCE.apply(DUMMY_INPUT)); } }
1,428
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/MessageFiltersTest.java
package com.netflix.suro.routing.filter; import com.netflix.suro.routing.filter.RegexValuePredicate.MatchPolicy; import org.junit.Test; import java.io.IOException; import static com.netflix.suro.routing.filter.MessageFilters.*; import static com.netflix.suro.routing.filter.VerificationUtil.*; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class MessageFiltersTest { @Test public void testAlwaysFalseReturnsFalse() { assertFalse(alwaysFalse().apply(DUMMY_INPUT)); } @Test public void testAlwaysTrueReturnsTrue() { assertTrue(alwaysTrue().apply(DUMMY_INPUT)); } @Test public void testNotAlwaysNegates(){ assertTrue(not(getFalseFilter()).apply(DUMMY_INPUT)); assertFalse(not(getTrueFilter()).apply(DUMMY_INPUT)); } @Test public void testOr() { assertTrue(or(getFalseFilter(), getFalseFilter(), getTrueFilter()).apply(DUMMY_INPUT)); assertFalse(or(getFalseFilter(), getFalseFilter()).apply(DUMMY_INPUT)); } @Test public void testAnd(){ assertTrue(and(getTrueFilter(), getTrueFilter()).apply(DUMMY_INPUT)); assertFalse(and(getTrueFilter(), getFalseFilter()).apply(DUMMY_INPUT)); } @Test public void showQuery() throws Exception { MessageFilter filter = MessageFilters.or( MessageFilters.and( new PathValueMessageFilter("//path/to/property", new StringValuePredicate("foo")), new PathValueMessageFilter("//path/to/property", new NumericValuePredicate(123, ">")), new PathValueMessageFilter("//path/to/property", new PathValuePredicate("//path/to/property", "//another/path")) ), MessageFilters.not( new PathValueMessageFilter("//path/to/time", new TimeMillisValuePredicate("yyyy-MM-dd", "1997-08-29", "!=")) ), new PathValueMessageFilter("//path/to/stringProp", new RegexValuePredicate(".*", MatchPolicy.PARTIAL)), new PathValueMessageFilter("//path/to/stringProp", new RegexValuePredicate(".*", MatchPolicy.FULL)) ); print(filter); } private void print(MessageFilter filter) throws IOException { System.out.println(filter.toString()); } }
1,429
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/NumericValuePredicateTest.java
package com.netflix.suro.routing.filter; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class NumericValuePredicateTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testEachOperatorWorks() throws Exception { Object[][] inputs = { {1, "=", 1L, true}, {.3, "=", .3, true}, {3, ">", 2.1, true}, {2, ">=", 2, true}, {3, ">=", 2.2f, true}, {4, "<", 5, true}, {4, "<=", 4, true}, {4, "<=", 5, true}, // Negative cases {4, "=", 3L, false}, {3.3, "=", 3.4f, false}, {3, ">", 4, false}, {3, ">=", 4, false}, {4, "<", 3, false}, {4.2, "<", 3.5f, false}, {4L, "<=", 3.2, false}, }; for(Object[] input : inputs){ Number inputValue = (Number)input[0]; String fn = (String)input[1]; Number value = (Number)input[2]; boolean expected = (Boolean) input[3]; verifyValuesOfDifferentFormatsCanBeCompared(inputValue, fn, value, expected); } } @Test(expected=IllegalArgumentException.class) public void testInvalidFunctionNameShouldBeRejected() { new NumericValuePredicate(4, "~~"); } public void verifyValuesOfDifferentFormatsCanBeCompared ( Number input, String fnName, Number value, boolean expectedValue) throws Exception { NumericValuePredicate pred = new NumericValuePredicate(value, fnName); boolean result = pred.apply(input); assertEquals( String.format( "Expected: %s %s %s", input, fnName, value), expectedValue, result); } }
1,430
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/VerificationUtil.java
package com.netflix.suro.routing.filter; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class VerificationUtil { public static final Object DUMMY_INPUT = new Object(); private VerificationUtil(){} /** * Creating mocked filter instead of using AwaysTrueFilter so this test case * is independent of other test target. */ public static MessageFilter getTrueFilter() { MessageFilter trueFilter = mock(MessageFilter.class); when(trueFilter.apply(VerificationUtil.DUMMY_INPUT)).thenReturn(true); return trueFilter; } public static MessageFilter getFalseFilter() { MessageFilter falseFilter = mock(MessageFilter.class); when(falseFilter.apply(VerificationUtil.DUMMY_INPUT)).thenReturn(false); return falseFilter; } }
1,431
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/AndMessageFilterTest.java
package com.netflix.suro.routing.filter; import com.google.common.collect.ImmutableList; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; public class AndMessageFilterTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testAllAcceptancesLeadToAcceptance() { List<? extends MessageFilter> filters = ImmutableList.of( VerificationUtil.getTrueFilter(), VerificationUtil.getTrueFilter(), VerificationUtil.getTrueFilter()); AndMessageFilter filter = new AndMessageFilter(filters); assertTrue(filter.apply(VerificationUtil.DUMMY_INPUT)); } @Test public void testOneRejectionLeadsToRejection() { List<? extends MessageFilter> filters = ImmutableList.of( VerificationUtil.getTrueFilter(), VerificationUtil.getTrueFilter(), VerificationUtil.getFalseFilter() ); AndMessageFilter filter = new AndMessageFilter(filters); assertFalse(filter.apply(VerificationUtil.DUMMY_INPUT)); } @Test public void testAndMessageFilterShortcuts() { MessageFilter falseFilter = VerificationUtil.getFalseFilter(); MessageFilter trueFilter = VerificationUtil.getTrueFilter(); List<? extends MessageFilter> filters = ImmutableList.of( falseFilter, trueFilter ); assertFalse(new AndMessageFilter(filters).apply(VerificationUtil.DUMMY_INPUT)); verify(trueFilter, never()).apply(VerificationUtil.DUMMY_INPUT); } }
1,432
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/PathValueMessageFilterTest.java
package com.netflix.suro.routing.filter; import com.google.common.collect.Maps; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.util.Map; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; public class PathValueMessageFilterTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testPositiveSelection() { MockRequestTrace requestTrace = Mockito.mock(MockRequestTrace.class); when(requestTrace.getClientInfoHostName()).thenReturn("localhost"); Map<String, Object> clientInfoMap = Maps.newHashMap(); clientInfoMap.put("clientName", "client"); clientInfoMap.put("clientId", (long) 10); when(requestTrace.getClientInfoMap()).thenReturn(clientInfoMap); // Test numerical values can be filtered MessageFilter filter = new PathValueMessageFilter("//clientInfoMap/clientId", new NumericValuePredicate(5, ">")); assertTrue("Filter should return true as the client ID is 10, greater than 5", filter.apply(requestTrace)); // Test string value can be filtered filter = new PathValueMessageFilter("//clientInfoMap/clientName", new StringValuePredicate("client")); assertTrue("Filter should return true as client name is 'client'", filter.apply(requestTrace)); // Test attribute is supported filter = new PathValueMessageFilter("//@clientInfoHostName", new StringValuePredicate("localhost")); assertTrue("Filter should return tre as clientInfoHostName is localhost", filter.apply(requestTrace)); } @Test public void testNonExistentValueShouldBeFiltered(){ MockRequestTrace requestTrace = Mockito.mock(MockRequestTrace.class); MessageFilter filter = new PathValueMessageFilter("//whatever", new StringValuePredicate("whatever")); assertFalse(filter.apply(requestTrace)); } @Test public void testNullValueCanBeAccepted(){ MockRequestTrace requestTrace = Mockito.mock(MockRequestTrace.class); MessageFilter filter = new PathValueMessageFilter("//whatever", NullValuePredicate.INSTANCE); assertTrue(filter.apply(requestTrace)); } }
1,433
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/OrMessageFilterTest.java
package com.netflix.suro.routing.filter; import com.google.common.collect.ImmutableList; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.List; import static com.netflix.suro.routing.filter.VerificationUtil.*; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; public class OrMessageFilterTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testAllRejectionsLeadToRejection() { List<? extends MessageFilter> filters = ImmutableList.of(getFalseFilter(), getFalseFilter(), getFalseFilter()); OrMessageFilter filter = new OrMessageFilter(filters); assertFalse(filter.apply(DUMMY_INPUT)); } @Test public void testOneAcceptanceLeadsToAcceptance() { List<? extends MessageFilter> filters = ImmutableList.of(getFalseFilter(), getTrueFilter(), getFalseFilter()); OrMessageFilter filter = new OrMessageFilter(filters); assertTrue(filter.apply(DUMMY_INPUT)); } @Test public void testOrMessageFilterShortcuts() { MessageFilter falseFilter = getFalseFilter(); MessageFilter trueFilter = getTrueFilter(); List<? extends MessageFilter> filters = ImmutableList.of(trueFilter, falseFilter); assertTrue(new OrMessageFilter(filters).apply(DUMMY_INPUT)); verify(falseFilter, never()).apply(DUMMY_INPUT); } }
1,434
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/AlwaysFalseMessageFilterTest.java
package com.netflix.suro.routing.filter; import org.junit.After; import org.junit.Before; import org.junit.Test; import static com.netflix.suro.routing.filter.VerificationUtil.DUMMY_INPUT; import static org.junit.Assert.assertFalse; public class AlwaysFalseMessageFilterTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testAlwaysFalse() { assertFalse(AlwaysFalseMessageFilter.INSTANCE.apply(DUMMY_INPUT)); } }
1,435
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/NotMessageFilterTest.java
package com.netflix.suro.routing.filter; import org.junit.After; import org.junit.Before; import org.junit.Test; import static com.netflix.suro.routing.filter.VerificationUtil.*; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class NotMessageFilterTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testNotTrueIsFalse() { assertFalse(new NotMessageFilter(getTrueFilter()).apply(DUMMY_INPUT)); } @Test public void testNotFalseIsTrue() { assertTrue(new NotMessageFilter(getFalseFilter()).apply(DUMMY_INPUT)); } }
1,436
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/TimeStringValuePredicateTest.java
package com.netflix.suro.routing.filter; import org.joda.time.format.DateTimeFormat; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.Date; import static org.junit.Assert.assertEquals; public class TimeStringValuePredicateTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testEachOperatorWorks() throws Exception { String valueFormat = "YYYY-MM-dd HH:mm:ss:SSS"; long now = new Date().getTime(); String inputFormat = "yyyyMMdd'T'HHmmss.SSSZ"; Object[][] inputs = { { now, "=", now, true}, {now+1, ">", now, true}, { now, ">=", now, true}, {now+2, ">=", now, true}, {now-1, "<", now, true}, { now, "<=", now, true}, {now-1, "<=", now, true}, // Negative cases {now+1, "=", now, false}, {now-1, "=", now, false}, {now-1, ">", now, false}, {now-1, ">=", now, false}, { now, "<", now, false}, {now+1, "<", now, false}, {now+1, "<=", now, false}, }; for(Object[] input : inputs){ long inputValue = (Long) input[0]; String fn = (String)input[1]; long value = (Long) input[2]; boolean expected = (Boolean) input[3]; verifyValuesOfDifferentFormatsCanBeCompared(valueFormat, value, inputFormat, inputValue, fn, expected); } } @Test(expected=IllegalArgumentException.class) public void testInvalidFunctionNameShouldBeRejected() { String valueFormat = "YYYY-MM-dd HH:mm:ss:SSS"; long now = new Date().getTime(); String inputFormat = "yyyyMMdd'T'HHmmss.SSSZ"; new TimeStringValuePredicate(valueFormat, inputFormat, toString(now, valueFormat), "~~"); } public void verifyValuesOfDifferentFormatsCanBeCompared ( String valueFormat, long value, String inputFormat, long input, String fnName, boolean expectedValue) throws Exception { String stringValue = toString(value, valueFormat); String stringInput = toString(input, inputFormat); TimeStringValuePredicate pred = new TimeStringValuePredicate(valueFormat, inputFormat, stringValue, fnName); boolean result = pred.apply(stringInput); assertEquals( String.format( "Expected: %s %s %s where input format = %s, and value format = %s. Expected string value: %s %s %s ", input, fnName, value, inputFormat, valueFormat, stringInput, fnName, stringValue), expectedValue, result); } private String toString(long millis, String format){ return DateTimeFormat.forPattern(format).print(millis); } }
1,437
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/MockRequestTrace.java
package com.netflix.suro.routing.filter; /** * Just for testing. Copy of platform's request trace. * */ import java.util.HashMap; import java.util.Map; public class MockRequestTrace { boolean bIsToplevelRequest = false; public static final String CLIENTINFO_SERVICE_NAME = "service_name"; public static final String CLIENTINFO_HOST_NAME = "host_name"; public static final String CLIENTINFO_SERVER_IP = "IP"; public static final String CLIENTINFO_VERSION = "version"; public static final String CLIENTINFO_AVAILABILITY_ZONE = "availability_zone"; public static final String CLIENTINFO_INSTANCE_ID = "instance_id"; public static final String SERVICEINFO_SERVICE_NAME = "service_name"; public static final String SERVICEINFO_HOST_NAME = "host_name"; public static final String SERVICEINFO_SERVER_IP = "IP"; public static final String SERVICEINFO_VERSION = "version"; public static final String SERVICEINFO_AVAILABILITY_ZONE = "availability_zone"; public static final String SERVICEINFO_INSTANCE_ID = "instance_id"; public static String TOPLEVEL_UUID = "uuid"; public static String TOPLEVEL_ECCUST_ID = "eccust_id"; public static String TOPLEVEL_CLIENT_IP = "client_ip"; public static String TOPLEVEL_USER_AGENT = "user_agent"; public static String TOPLEVEL_REFERRER_URL = "referrer_url"; public static String TOPLEVEL_COUNTRY = "country"; public static String TOPLEVEL_LANGUAGE = "language"; public static String TOPLEVEL_APP_ID = "app_id"; public static String TOPLEVEL_APP_VERSION = "app_version"; public static String TOPLEVEL_DEVICE_TYPE = "device_type"; public static String TOPLEVEL_ESN = "esn"; public static final String REQUEST_ECCUST_ID = "eccust_id"; public static final String REQUEST_CUST_ID_GUID = "cust_id_guid"; public static final String REQUEST_URL = "url"; public static final String REQUEST_PROTOCOL = "protocol"; public static final String REQUEST_PATH = "path"; public static final String REQUEST_ALIASED_PATH = "aliased_path"; public static final String REQUEST_METHOD = "method"; public static final String REQUEST_PARAMS = "params"; public static final String REQUEST_BODY = "body"; public static final String REQUEST_UUID = "uuid"; public static final String REQUEST_VERSION = "version"; public static final String REQUEST_CLIENT_IP = "client_ip"; public static final String REQUEST_USER_AGENT = "user_agent"; public static final String REQUEST_COUNTRY = "country"; public static final String REQUEST_REQUEST_LANGUAGE = "language"; public static final String REQUEST_REFERRER_URL = "referrer_url"; public static final String REQUEST_TRACE_PARENT_FLAG = "trace_parent_flag"; public static final String REQUEST_TRACE_CALLGRAPH_PERCENT = "trace_callgraph_percent"; public static final String REQUEST_TRACE_CALLGRAPH_FLAG = "trace_callgraph_flag"; public static final String REQUEST_TRACE_LOCAL_PERCENT = "trace_local_percent"; public static final String REQUEST_TRACE_LOCAL_FLAG = "trace_local_flag"; public static final String REQUEST_REQUEST_DIRECTION = "request_direction"; public static final String REQUEST_THROTTLED = "throttled"; public static final String RESULTS_STATUSCODE = "statuscode"; public static final String RESULTS_SUBCODE = "subcode"; public static final String RESULTS_EXCEPTION = "exception"; public static final String RESULTS_INFO_ID = "info_id"; public static final String RESULTS_INFO_MESSAGE = "info_message"; public static final String RESULTS_STACKTRACE = "stacktrace"; public static final String PERF_CLIENT_OUT_SERIAL_TIME_NS = "client_out_serial_time_ns"; public static final String PERF_CLIENT_IN_DESERIAL_TIME_NS = "client_in_deserial_time_ns"; public static final String PERF_SERVICE_OUT_SERIAL_TIME_NS = "service_out_serial_time_ns"; public static final String PERF_SERVICE_IN_DESERIAL_TIME_NS = "service_in_deserial_time_ns"; public static final String PERF_REQUEST_START_TIMESTAMP_MS = "request_start_timestamp_ms"; public static final String PERF_ROUNDTRIP_LATENCY_MS = "roundtrip_latency_ms"; public static final String PERF_RESPONSE_TIME_MS = "response_time_ms"; /** * The Maps that hold the logging data * We use different maps to provide the possibility of callers * passing in or setting specific sub categories of Logging data * e.g. Request, Response etc. * This also gels in with how Annotatable sends "bag of key value pairs" */ private static final long serialVersionUID = -4183164478625476329L; private Map<String,Object> clientInfoMap = new HashMap<String,Object>(); private Map<String,Object> serviceInfoMap = new HashMap<String,Object>(); private Map<String,Object> requestMap = new HashMap<String,Object>(); private Map<String,Object> toplevelMap = new HashMap<String,Object>(); private Map<String,Object> resultsMap = new HashMap<String,Object>(); private Map<String,Object> perfMap = new HashMap<String,Object>(); private Map<String,Object> extraDataMap = new HashMap<String,Object>(); /** * Methods that help set "bag of key value pairs" * Also helps define how LogManager.logEvent(Annotatable) names the "bag" * using the * @return */ public Map<String,Object> getClientInfoMap() { return clientInfoMap; } public void setClientInfoMap(Map<String,Object> clientInfoMap) { this.clientInfoMap = clientInfoMap; } public Map<String,Object> getServiceInfoMap() { return serviceInfoMap; } public void setServiceInfoMap(Map<String,Object> serviceInfoMap) { this.serviceInfoMap = serviceInfoMap; } public Map<String,Object> getRequestMap() { return requestMap; } public void setRequestMap(Map<String,Object> requestMap) { this.requestMap = requestMap; } public Map<String,Object> getToplevelMap() { return toplevelMap; } public void setToplevelMap(Map<String,Object> toplevelMap) { this.toplevelMap = toplevelMap; } public Map<String,Object> getResultsMap() { return resultsMap; } public void setResultsMap(Map<String,Object> resultsMap) { this.resultsMap = resultsMap; } public Map<String,Object> getPerfMap() { return perfMap; } public Map<String,Object> getExtraDataMap() { return extraDataMap; } public void setExtraDataMap(Map<String,Object> extraDataMap) { this.extraDataMap = extraDataMap; } /** * Methods to get/set various Request Tracing Data fields * --------------------------------------------------- */ public boolean isToplevelRequest() { return bIsToplevelRequest; } public void setIsToplevelRequest(boolean isToplevelRequest) { bIsToplevelRequest = isToplevelRequest; } /** * Set a "non-standard" (as in not captured in the "logging spec" data) * Typically you will call this when there are no available setter API for * the data that you (caller) are trying to set. */ public void setData(String key, Object value) { extraDataMap.put(key, value); } public void setPerfMap(Map<String,Object> perfMap) { this.perfMap = perfMap; } public static long getSerialVersionUID() { return serialVersionUID; } public void setRequestUUID(String uuid) { this.requestMap.put("uuid", uuid); } public String getClientInfoServiceName() { return (String) clientInfoMap.get(CLIENTINFO_SERVICE_NAME); } public String getClientInfoHostName() { return (String) clientInfoMap.get(CLIENTINFO_HOST_NAME); } public String getClientInfoServerIP() { return (String) clientInfoMap.get(CLIENTINFO_SERVER_IP); } public String getClientInfoVersion() { return (String) clientInfoMap.get(CLIENTINFO_VERSION); } public String getClientInfoAvailabilityZone() { return (String) clientInfoMap.get(CLIENTINFO_AVAILABILITY_ZONE); } public String getClientInfoInstanceID() { return (String) clientInfoMap.get(CLIENTINFO_INSTANCE_ID); } public String getServiceInfoInstanceID() { return (String) serviceInfoMap.get(SERVICEINFO_INSTANCE_ID); } public String getServiceInfoServiceName() { return (String) serviceInfoMap.get(SERVICEINFO_SERVICE_NAME); } public String getServiceInfoHostName() { return (String) serviceInfoMap.get(SERVICEINFO_HOST_NAME); } public String getServiceInfoServerIP() { return (String) serviceInfoMap.get(SERVICEINFO_SERVER_IP); } public String getServiceInfoVersion() { return (String) serviceInfoMap.get(SERVICEINFO_VERSION); } public String getServiceInfoAvailabilityZone() { return (String) serviceInfoMap.get(SERVICEINFO_AVAILABILITY_ZONE); } public String getRequestECCustID() { return (String) requestMap.get(REQUEST_ECCUST_ID); } public String getRequestCustIDGuid() { return (String) requestMap.get(REQUEST_CUST_ID_GUID); } public String getRequestUrl() { return (String) requestMap.get(REQUEST_URL); } public String getRequestProtocol() { return (String) requestMap.get(REQUEST_PROTOCOL); } public String getRequestPath() { return (String) requestMap.get(REQUEST_PATH); } public String getRequestAliasedPath() { return (String) requestMap.get(REQUEST_ALIASED_PATH); } public String getRequestMethod() { return (String) requestMap.get(REQUEST_METHOD); } public String getRequestParams() { return (String) requestMap.get(REQUEST_PARAMS); } public String getRequestBody() { return (String) requestMap.get(REQUEST_BODY); } public String getRequestUUID() { return (String) requestMap.get(REQUEST_UUID); } public String getRequestVersion() { return (String) requestMap.get(REQUEST_VERSION); } public String getRequestClientIP() { return (String) requestMap.get(REQUEST_CLIENT_IP); } public String getRequestUserAgent() { return (String) requestMap.get(REQUEST_USER_AGENT); } public String getRequestCountry() { return (String) requestMap.get(REQUEST_COUNTRY); } public String getRequestLanguage() { return (String) requestMap.get(REQUEST_REQUEST_LANGUAGE); } public String getRequestReferrerUrl() { return (String) requestMap.get(REQUEST_REFERRER_URL); } public String getRequestDirection() { return (String) requestMap.get(REQUEST_REQUEST_DIRECTION); } public boolean isRequestThrottled() { return getBoolean(requestMap, REQUEST_THROTTLED); } public boolean getRequestTraceParentFlag() { return getBoolean(requestMap, REQUEST_TRACE_PARENT_FLAG); } public int getRequestTraceCallGraphPercent() { return getInt(requestMap, REQUEST_TRACE_CALLGRAPH_PERCENT); } public boolean getRequestTraceCallGraphFlag() { return getBoolean(requestMap, REQUEST_TRACE_CALLGRAPH_FLAG); } public int getRequestTraceLocalPercent() { return getInt(requestMap, REQUEST_TRACE_LOCAL_PERCENT); } public boolean getRequestTraceLocalFlag() { return getBoolean(requestMap, REQUEST_TRACE_LOCAL_FLAG); } public int getResultsStatusCode() { int c = 200; try { c = ((Integer)resultsMap.get(RESULTS_STATUSCODE)); } catch (Exception e) { } return c; } public int getResultsSubCode() { int c = 0; try { c = ((Integer)resultsMap.get(RESULTS_SUBCODE)); } catch (Exception e) { } return c; } public String getResultsException() { return (String) resultsMap.get(RESULTS_EXCEPTION); } public String getResultsInfoID() { return (String) resultsMap.get(RESULTS_INFO_ID); } public String getResultsInfoMessage() { return (String) resultsMap.get(RESULTS_INFO_MESSAGE); } public String getResultsStackTrace() { return (String) resultsMap.get(RESULTS_STACKTRACE); } public long getPerfClientOutSerialTimeNS() { long l = 0; try { Object o = perfMap.get(PERF_CLIENT_OUT_SERIAL_TIME_NS); if (o!=null){ l = (Long) o; } } catch (Exception e) { } return l; } public long getPerfClientInDeserialTimeNS() { long l = 0; try { Object o = perfMap.get(PERF_CLIENT_IN_DESERIAL_TIME_NS); if (o!=null){ l = (Long) o; } } catch (NumberFormatException e) { } return l; } public long getPerfServiceOutSerialTimeNS() { long l = 0; try { Object o = perfMap.get(PERF_SERVICE_OUT_SERIAL_TIME_NS); if (o!=null){ l = (Long) o; } } catch (Exception e) { } return l; } public long getPerfServiceInDeserialTimeNS() { long l = 0; try { Object o = perfMap.get(PERF_SERVICE_IN_DESERIAL_TIME_NS); if (o!=null){ l = (Long) o; } } catch (Exception e) { } return l; } public long getPerfRequestStartTimestampMS() { long l = 0; try { Object o = perfMap.get(PERF_REQUEST_START_TIMESTAMP_MS); if (o!=null){ l = (Long) o; } } catch (Exception e) { } return l; } public long getPerfRoundtripLatencyMS() { long l = 0; try { Object o = perfMap.get(PERF_ROUNDTRIP_LATENCY_MS); if (o!=null){ l = (Long) o; } } catch (Exception e) { } return l; } public long getPerfResponseTimeMS() { long l = 0; try { Object o = perfMap.get(PERF_RESPONSE_TIME_MS); if (o!=null){ l = (Long) o; } } catch (Exception e) { } return l; } public void setClientInfoServiceName(String clientInfoServiceName) { clientInfoMap.put(CLIENTINFO_SERVICE_NAME, clientInfoServiceName); } public void setClientInfoHostName(String clientInfoHostName) { clientInfoMap.put(CLIENTINFO_HOST_NAME, clientInfoHostName); } public void setClientInfoServerIP(String clientInfoServerIP) { clientInfoMap.put(CLIENTINFO_SERVER_IP, clientInfoServerIP); } public void setClientInfoVersion(String clientInfoVersion) { clientInfoMap.put(CLIENTINFO_VERSION, clientInfoVersion); } public void setClientInfoAvailabilityZone(String clientInfoAvailabilityZone) { clientInfoMap.put(CLIENTINFO_AVAILABILITY_ZONE, clientInfoAvailabilityZone); } public void setClientInfoInstanceID(String clientInfoInstanceID) { clientInfoMap.put(CLIENTINFO_INSTANCE_ID, clientInfoInstanceID); } public void setServiceInfoInstanceID(String serviceInfoInstanceID) { serviceInfoMap.put(SERVICEINFO_INSTANCE_ID, serviceInfoInstanceID); } public void setServiceInfoServiceName(String serviceInfoServiceName) { serviceInfoMap.put(SERVICEINFO_SERVICE_NAME, serviceInfoServiceName); } public void setServiceInfoHostName(String serviceInfoHostName) { serviceInfoMap.put(SERVICEINFO_HOST_NAME, serviceInfoHostName); } public void setServiceInfoServerIP(String serviceInfoServerIP) { serviceInfoMap.put(SERVICEINFO_SERVER_IP, serviceInfoServerIP); } public void setServiceInfoVersion(String serviceInfoVersion) { serviceInfoMap.put(SERVICEINFO_VERSION, serviceInfoVersion); } public void setServiceInfoAvailabilityZone( String serviceInfoAvailabilityZone) { serviceInfoMap.put(SERVICEINFO_AVAILABILITY_ZONE, serviceInfoAvailabilityZone); } public void setRequestECCustID(String requestECCustID) { requestMap.put(REQUEST_ECCUST_ID, requestECCustID); } public void setRequestCustIDGUID(String requestCustIDGUID) { requestMap.put(REQUEST_CUST_ID_GUID, requestCustIDGUID); } public void setRequestURL(String requestUrl) { requestMap.put(REQUEST_URL, requestUrl); } public void setRequestProtocol(String requestProtocol) { requestMap.put(REQUEST_PROTOCOL, requestProtocol); } public void setRequestPath(String requestPath) { requestMap.put(REQUEST_PATH, requestPath); } public void setRequestAliasedPath(String requestAliasedPath) { requestMap.put(REQUEST_ALIASED_PATH, requestAliasedPath); } public void setRequestMethod(String requestMethod) { requestMap.put(REQUEST_METHOD, requestMethod); } public void setRequestParams(String requestParams) { requestMap.put(REQUEST_PARAMS, requestParams); } public void setRequestBody(String requestBody) { requestMap.put(REQUEST_BODY, requestBody); } public void setRequestVersion(String requestVersion) { requestMap.put(REQUEST_VERSION, requestVersion); } public void setRequestClientIP(String requestClientIP) { requestMap.put(REQUEST_CLIENT_IP, requestClientIP); } public void setRequestUserAgent(String requestUserAgent) { requestMap.put(REQUEST_USER_AGENT, requestUserAgent); } public void setRequestCountry(String requestCountry) { requestMap.put(REQUEST_COUNTRY, requestCountry); } public void setRequestRequestLanguage(String requestRequestLanguage) { requestMap.put(REQUEST_REQUEST_LANGUAGE, requestRequestLanguage); } public void setRequestReferrerURL(String requestReferrerUrl) { requestMap.put(REQUEST_REFERRER_URL, requestReferrerUrl); } public void setRequestDirection(String requestRequestDirection) { requestMap.put(REQUEST_REQUEST_DIRECTION, requestRequestDirection); } public String getRequestToplevelUUID() { return (String) requestMap.get(TOPLEVEL_UUID); } /** * @Deprecated Use {{@link #setToplevelUUID(String)} * @param requestMainUUID */ public void setRequestToplevelUUID(String requestMainUUID) { setToplevelUUID(requestMainUUID); } public void setRequestThrottled(boolean isThrottled) { requestMap.put(REQUEST_THROTTLED, Boolean.valueOf(isThrottled)); } public void setRequestTraceParentFlag(boolean flag) { requestMap.put(REQUEST_TRACE_PARENT_FLAG, Boolean.valueOf(flag)); } public void setRequestTraceCallGraphPercent(int percent) { requestMap.put(REQUEST_TRACE_CALLGRAPH_PERCENT, Integer.valueOf(percent)); } public void setRequestTraceCallGraphFlag(boolean flag) { requestMap.put(REQUEST_TRACE_CALLGRAPH_FLAG, Boolean.valueOf(flag)); } public void setRequestTraceLocalPercent(int percent) { requestMap.put(REQUEST_TRACE_LOCAL_PERCENT, Integer.valueOf(percent)); } public void setRequestTraceLocalFlag(boolean flag) { requestMap.put(REQUEST_TRACE_LOCAL_FLAG, Boolean.valueOf(flag)); } public void setResultsStatusCode(int resultsStatusCode) { resultsMap.put(RESULTS_STATUSCODE, Integer.valueOf(resultsStatusCode)); } public void setResultsSubCode(String resultsSubCode) { resultsMap.put(RESULTS_SUBCODE, resultsSubCode); } public void setResultsException(String resultsException) { resultsMap.put(RESULTS_EXCEPTION, resultsException); } public void setResultsInfoID(String resultsInfoID) { resultsMap.put(RESULTS_INFO_ID, resultsInfoID); } public void setResultsInfoMessage(String resultsInfoMessage) { resultsMap.put(RESULTS_INFO_MESSAGE, resultsInfoMessage); } public void setResultsStacktrace(String resultsStacktrace) { resultsMap.put(RESULTS_STACKTRACE, resultsStacktrace); } public void setPerfClientOutSerialTimeNS(long perfClientOutSerialTimeNS) { perfMap.put(PERF_CLIENT_OUT_SERIAL_TIME_NS, Long .valueOf(perfClientOutSerialTimeNS)); } public void setPerfClientInDeserialTimeNS(long perfClientInDeserialTimeNS) { perfMap.put(PERF_CLIENT_IN_DESERIAL_TIME_NS, Long .valueOf(perfClientInDeserialTimeNS)); } public void setPerfServiceOutSerialTimeNS(long perfServiceOutSerialTimeNS) { perfMap.put(PERF_SERVICE_OUT_SERIAL_TIME_NS, Long .valueOf(perfServiceOutSerialTimeNS)); } public void setPerfServiceInDeserialTimeNS(long perfServiceInDeserialTimeNS) { perfMap.put(PERF_SERVICE_IN_DESERIAL_TIME_NS, Long .valueOf(perfServiceInDeserialTimeNS)); } /** * @deprecated * Use {#link setPerfRequestStartTimestampMS()} * @param perfRequestStartTimestampNS */ public void setPerfRequestStartTimestampNS(long perfRequestStartTimestampNS) { setPerfRequestStartTimestampMS(perfRequestStartTimestampNS); } public void setPerfRequestStartTimestampMS(long perfRequestStartTimestampNS) { perfMap.put(PERF_REQUEST_START_TIMESTAMP_MS, Long .valueOf(perfRequestStartTimestampNS)); } public void setPerfRoundtripLatencyMS(long perfRoundtripLatencyMS) { perfMap.put(PERF_ROUNDTRIP_LATENCY_MS, Long .valueOf(perfRoundtripLatencyMS)); } public void setPerfResponseTimeMS(long perfResponseTimeMS) { perfMap.put(PERF_RESPONSE_TIME_MS, Long.valueOf(perfResponseTimeMS)); } //-------- Top Level Getters ------------------------- public String getToplevelUUID() { return (String) toplevelMap.get(TOPLEVEL_UUID); } public String getToplevelECCustID() { return (String) toplevelMap.get(TOPLEVEL_ECCUST_ID); } public String getToplevelClientIP() { return (String) toplevelMap.get(TOPLEVEL_CLIENT_IP); } public String getToplevelUserAgent() { return (String) toplevelMap.get(TOPLEVEL_USER_AGENT); } public String getToplevelReferrerURL() { return (String) toplevelMap.get(TOPLEVEL_REFERRER_URL); } public String getToplevelCountry() { return (String) toplevelMap.get(TOPLEVEL_COUNTRY); } public String getToplevelLanguage() { return (String) toplevelMap.get(TOPLEVEL_LANGUAGE); } public String getToplevelAppID() { return (String) toplevelMap.get(TOPLEVEL_APP_ID); } public String getToplevelAppVersion() { return (String) toplevelMap.get(TOPLEVEL_APP_VERSION); } public String getToplevelDeviceType() { return (String) toplevelMap.get(TOPLEVEL_DEVICE_TYPE); } public String getToplevelESN() { return (String) toplevelMap.get(TOPLEVEL_ESN); } // Top level Setters public void setToplevelUUID(String toplevelUuid) { toplevelMap.put(TOPLEVEL_UUID, toplevelUuid); } public void setToplevelECCustID(String toplevelECCustId) { toplevelMap.put(TOPLEVEL_ECCUST_ID , toplevelECCustId); } public void setToplevelClientIP(String toplevelClientIP) { toplevelMap.put(TOPLEVEL_CLIENT_IP , toplevelClientIP); } public void setToplevelUserAgent(String toplevelUserAgent) { toplevelMap.put(TOPLEVEL_USER_AGENT , toplevelUserAgent); } public void setToplevelReferrerURL(String toplevelReferrerURL) { toplevelMap.put(TOPLEVEL_REFERRER_URL , toplevelReferrerURL); } public void setToplevelCountry(String toplevelCountry) { toplevelMap.put(TOPLEVEL_COUNTRY , toplevelCountry); } public void setToplevelLanguage(String toplevelLanguage) { toplevelMap.put(TOPLEVEL_LANGUAGE , toplevelLanguage); } public void setToplevelAppID(String toplevelAppID) { toplevelMap.put(TOPLEVEL_APP_ID , toplevelAppID); } public void setToplevelAppVersion(String toplevelAppVersion) { toplevelMap.put(TOPLEVEL_APP_VERSION , toplevelAppVersion); } public void setToplevelDeviceType(String toplevelDeviceType) { toplevelMap.put(TOPLEVEL_DEVICE_TYPE , toplevelDeviceType); } public void setToplevelESN(String toplevelEsn) { toplevelMap.put(TOPLEVEL_ESN , toplevelEsn); } // ---------- "Helper" methods that help set common data /** * Set the Request Direction. * To be called/set by services */ public void setRequestDirectionIn(){ setRequestDirection("in"); } /** * Set the Request Direction. * To be called/set by clients making outbound calls */ public void setRequestDirectionOut(){ setRequestDirection("out"); } /** * Send this logEvent object to Chukwa (or Messagebus in DC) * This is a helper method that helps a caller "log" this object to Chukwa */ public void logMe() { // Callers that want to override this should call LogManager.logEvent(..) themselves long startTime = getPerfRequestStartTimestampMS(); long endTime = System.currentTimeMillis() - startTime; setPerfResponseTimeMS(endTime); } private int getInt(Map<String, Object> map, String keyName){ int i = 0; try { Object o = map.get(keyName); if (o!=null){ i = ((Integer) o).intValue(); } } catch (Exception e) { } return i; } private boolean getBoolean(Map<String, Object> map, String keyName){ boolean b = false; Object o = map.get(keyName); try { if(o != null) { b = ((Boolean)o).booleanValue(); } } catch (Exception e) { } return b; } }
1,438
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/RegexValuePredicateTest.java
package com.netflix.suro.routing.filter; import com.netflix.suro.routing.filter.RegexValuePredicate.MatchPolicy; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class RegexValuePredicateTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testNormalMatch() throws Exception { Object[][] inputs = { {"a123cd", "a[0-9]+cd", MatchPolicy.FULL, true}, {"", "", MatchPolicy.FULL, true}, {"", "^$", MatchPolicy.FULL, true}, {"32abde23", "[a-z]+", MatchPolicy.FULL, false}, {"32abde23", "[a-z]+", MatchPolicy.PARTIAL, true}, {null, ".*", MatchPolicy.PARTIAL, false}, {null, ".*", MatchPolicy.FULL, false}, {null, "", MatchPolicy.PARTIAL, false} }; for(Object[] input : inputs){ String value = (String)input[0]; String regex = (String)input[1]; MatchPolicy policy = (MatchPolicy)input[2]; boolean expected = (Boolean) input[3]; RegexValuePredicate pred = new RegexValuePredicate(regex, policy); assertEquals( String.format("Given regex = %s, isPartial = %s, and input = %s", regex, policy, value), expected, pred.apply(value)); } } @Test(expected = IllegalArgumentException.class) public void testNullPatternIsNotAllowed(){ new RegexValuePredicate(null, MatchPolicy.FULL); } }
1,439
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/NullValuePredicateTest.java
package com.netflix.suro.routing.filter; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class NullValuePredicateTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testNullIsAccepted() { assertTrue(NullValuePredicate.INSTANCE.apply(null)); } @Test public void testNonNullIsRejected() { assertFalse(NullValuePredicate.INSTANCE.apply(new Object())); } }
1,440
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/TimeMillisValuePredicateTest.java
package com.netflix.suro.routing.filter; import org.joda.time.format.DateTimeFormat; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.Date; import static org.junit.Assert.assertEquals; public class TimeMillisValuePredicateTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testEachOperatorWorks() throws Exception { String valueFormat = "YYYY-MM-dd HH:mm:ss:SSS"; long now = new Date().getTime(); Object[][] inputs = { { now, "=", now, true}, {now+1, ">", now, true}, { now, ">=", now, true}, {now+2, ">=", now, true}, {now-1, "<", now, true}, { now, "<=", now, true}, {now-1, "<=", now, true}, // Negative cases {now+1, "=", now, false}, {now-1, "=", now, false}, {now-1, ">", now, false}, {now-1, ">=", now, false}, { now, "<", now, false}, {now+1, "<", now, false}, {now+1, "<=", now, false}, }; for(Object[] input : inputs){ long inputValue = (Long) input[0]; String fn = (String)input[1]; long value = (Long) input[2]; boolean expected = (Boolean) input[3]; verifyValuesOfDifferentFormatsCanBeCompared(valueFormat, value, inputValue, fn, expected); } } @Test(expected=IllegalArgumentException.class) public void testInvalidFunctionNameShouldBeRejected() { String valueFormat = "YYYY-MM-dd HH:mm:ss:SSS"; long now = new Date().getTime(); new TimeMillisValuePredicate(valueFormat, toString(now, valueFormat), "~~"); } public void verifyValuesOfDifferentFormatsCanBeCompared ( String valueFormat, long value, long input, String fnName, boolean expectedValue) throws Exception { String stringValue = toString(value, valueFormat); TimeMillisValuePredicate pred = new TimeMillisValuePredicate(valueFormat, stringValue, fnName); boolean result = pred.apply(input); assertEquals( String.format( "Expected: %s %s %s where value format = %s. Expected string value: %s %s %s ", input, fnName, value, valueFormat, input, fnName, stringValue), expectedValue, result); } private String toString(long millis, String format){ return DateTimeFormat.forPattern(format).print(millis); } }
1,441
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/StringValuePredicateTest.java
package com.netflix.suro.routing.filter; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class StringValuePredicateTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testValueComparison() throws Exception { Object[][] inputs = { {"abc", "abc", true}, {"", "", true}, {"AB", "A", false}, {null, null, true}, {null, "", false}, {"", null, false} }; for(Object[] input : inputs){ String value = (String)input[0]; String inputValue = (String)input[1]; boolean expected = ((Boolean)input[2]).booleanValue(); StringValuePredicate pred = new StringValuePredicate(value); assertEquals(String.format("Given value = %s, and input = %s", value, inputValue), expected, pred.apply(inputValue)); } } }
1,442
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/TimeRangeValuePredicateTest.java
package com.netflix.suro.routing.filter; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.Date; import static org.junit.Assert.assertEquals; public class TimeRangeValuePredicateTest { private static final String DEFAULT_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss:SSS"; @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test(expected=IllegalArgumentException.class) public void testNegativeRangeShouldBeRejected() { verifyTimeRangeIsCalculatedCorrectly(DEFAULT_TIME_FORMAT, 10, 9, 20, false); } @Test public void testRangeChecks(){ long time = new Date().getTime(); // [start, end, input, expected] Object[][] inputs = { {time, time, time, false}, {time, time, time + 1, false}, {time, time, time - 1, false}, {time, time + 10, time, true}, {time, time + 10, time + 1, true}, {time, time + 10, time + 3, true}, {time, time + 10, time + 9, true}, {time, time + 10, time + 10, false}, {time, time + 10, time + 12, false}, {time, time + 10, time - 1, false}, {time, time + 10, time - 10, false} }; for(Object[] input: inputs){ long start = (Long) input[0]; long end = (Long) input[1]; long inputValue = (Long) input[2]; boolean expected = (Boolean) input[3]; verifyTimeRangeIsCalculatedCorrectly(DEFAULT_TIME_FORMAT, start, end, inputValue, expected); } } public void verifyTimeRangeIsCalculatedCorrectly(String timeFormat, long startInstant, long endInstant, long inputValue, boolean expected) { String start = TimeUtil.toString(startInstant, timeFormat); String end = TimeUtil.toString(endInstant, timeFormat); String input = TimeUtil.toString(inputValue, timeFormat); TimeRangeValuePredicate pred = new TimeRangeValuePredicate(DEFAULT_TIME_FORMAT, start, end); boolean result = pred.apply(inputValue); String originalValue = String.format("{input = %s, start = %s, end = %s}", inputValue, startInstant, endInstant); if(result){ assertEquals(String.format("The input value %s is in the given range [%s, %s). Original Values: %s", input, start, end, originalValue), expected, result); }else{ assertEquals(String.format("The input value %s is not in the given range [%s, %s). Original Value: %s", input, start, end, originalValue), expected, result); } } }
1,443
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/parser/CompositeMessageFilterParsingTest.java
package com.netflix.suro.routing.filter.parser; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.netflix.suro.routing.filter.MessageFilter; import com.netflix.suro.routing.filter.MessageFilterCompiler; import com.netflix.suro.routing.filter.lang.InvalidFilterException; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import static com.netflix.suro.routing.filter.parser.FilterPredicate.*; import static org.junit.Assert.assertEquals; @RunWith(Parameterized.class) public class CompositeMessageFilterParsingTest { private static final String TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss:SSS"; private final static DateTime now = DateTime.now(); // An example composite filter string: // (xpath("//a/b/c") = "foo" or xpath("//a/b/d") > 5 or xpath("//a/f") is null) and not xpath("timestamp") > time-millis("yyyy-MM-dd'T'HH:mm:ss:SSS", "2012-08-22T08:45:56:086") and xpath("//a/b/e") between (5, 10) and xpath("//a/b/f") =~ "null" and xpath("//a/g") <= time-string("yyyy-MM-dd'T'HH:mm:ss:SSS", "yyyy-MM-dd'T'HH:mm:ss:SSS", "2012-08-22T16:45:56:086") and xpath("//a/h") in (a,b,c,d) or xpath("//a/b/g/f") in (1,2,3,4) or not xpath("//no/no") exists @Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { { // (xpath("//a/b/c") = "foo" or xpath("//a/b/d") > 5 or xpath("//a/f") is null) // and not xpath("timestamp") > time-millis(TIME_FORMAT, 3 hours ago) // and xpath("//a/b/e") between (5, 10) // and xpath("//a/b/f") =~ "[0-9a-zA-Z]+" // and xpath("//a/g") <= time-string(TIME_FORMAT, TIME_FORMAT, 5 hours later) // and xpath("//a/h") in ("a", "b", "c", "d") // or xpath("//a/b/g/f") in (1, 2, 3, 4) // or not xpath("//no/no") exists and( bracket( or( stringComp.create("//a/b/c", "=", "foo"), numberComp.create("//a/b/d", ">", 5), isNull.create("//a/f") ) ), not( timeComp.create("timestamp", ">", timeMillisNHoursAway(-3, TIME_FORMAT)) ), and( between.create("//a/b/e", null, new Object[]{5, 10}), regex.create("//a/b/f", "[0-9a-zA-Z]+"), timeComp.create("//a/g", "<=", timeStringNHoursAway(5, TIME_FORMAT)) ), or( inPred.create("//a/h", null, wrap(new Object[]{"a", "b", "c", "d"})), inPred.create("//a/b/g/f", null, new Object[]{1, 2, 3, 4}), not ( existsRight.create("//no/no") ) ) ), new Object[][]{ // This event matches the filter above new Object[]{ createEvent( new Object[]{"//a/b/c", "bar"}, // It's OK. There's a number of "or" clauses. new Object[]{"//a/b/d", 10}, new Object[]{"//a/f", "not null"}, // It's OK. The previous one is true new Object[]{"timestamp", nHoursAway(-4)}, // note this is not > new Object[]{"//a/b/e", 7}, new Object[]{"//a/b/f", "123a43bsdfA"}, new Object[]{"//a/g", nHoursAway(0, TIME_FORMAT)}, new Object[]{"//a/h", "c"}, new Object[]{"//a/b/g/f", 3}, new Object[]{"//no/no", "something"} // this will fail the last clause ), true, }, new Object[]{ createEvent( new Object[]{"//a/b/c", "bar"}, // not match new Object[]{"//a/b/d", 0}, // not match new Object[]{"//a/f", "not null"}, // not match new Object[]{"timestamp", nHoursAway(-4)}, // match new Object[]{"//a/b/e", 7}, new Object[]{"//a/b/f", "123a43bsdfA"}, new Object[]{"//a/g", nHoursAway(0, TIME_FORMAT)}, new Object[]{"//a/h", "c"}, new Object[]{"//a/b/g/f", 10}, // match new Object[]{"//no/no", "something"} // match ), false } } } }); } private static String wrap(String value){ return String.format("\"%s\"", value); } private static String[] wrap(Object[] strings) { String[] result = new String[strings.length]; for(int i = 0; i < strings.length; ++i) { result[i] = wrap(strings[i].toString()); } return result; } private static long nHoursAway(int n) { return now.plusHours(n).getMillis(); } private static String nHoursAway(int n, String format) { return DateTimeFormat.forPattern(format).print(nHoursAway(n)); } // Creates a time-millis that is n hours away from now private static String timeMillisNHoursAway(int n, String format) { return String.format( "time-millis(\"%s\", \"%s\")", format, nHoursAway(n, format)); } private static String timeStringNHoursAway(int n, String format) { return String.format( "time-string(\"%s\", \"%s\", \"%s\")", format, format, nHoursAway(n, format)); } private String filterString; private MessageFilter filter; private Object[][] eventResultPairs; public CompositeMessageFilterParsingTest(String filterString, Object[][]eventResultPairs) throws InvalidFilterException { this.filterString = filterString; this.filter = MessageFilterCompiler.compile(this.filterString); this.eventResultPairs = eventResultPairs; } @Test public void trans() { String input = and( stringComp.create("//a/b/c", "=", "foo"), numberComp.create("//a/b/d", ">", 5), between.create("//a/b/e", null, new Object[]{5, 10}), regex.create("//a/b/f", "[0-9a-zA-Z]+"), timeComp.create("//a/g", "<=", timeStringNHoursAway(5, TIME_FORMAT)), inPred.create("//a/h", null, wrap(new Object[]{"a", "b", "c", "d"})) ); System.out.println("Generated filter string: "+input); MessageFilter ef = null; try { ef = MessageFilterCompiler.compile(input); } catch (InvalidFilterException e) { throw new AssertionError("Invalid filter string generated. Error: " + e.getMessage()); } } @Test public void test() throws Exception { for(Object[] pair : eventResultPairs){ Object event = pair[0]; boolean result = (Boolean) pair[1]; assertEquals(String.format("Event object: %s\nFilter string: %s\n", event, this.filterString), result, filter.apply(event)); } } private static String or(String firstTerm, String secondTerm, Object...rest) { return Joiner.on(" or ").join(firstTerm, secondTerm, rest); } private static String and(String first, String second, Object...rest) { return Joiner.on(" and ").join(first, second, rest); } private static String not(String term) { return "not "+term; } private static String bracket(String term) { return String.format("(%s)", term); } private static Object createEvent(Object[]... pairs) { Map<String, ? super Object> object = Maps.newHashMap(); for(Object[] pair: pairs) { String path = (String)pair[0]; List<String> steps = toSteps(path); Object value = pair[1]; updateObjectWithPathAndValue(object, steps, value); } return object; } private static List<String> toSteps(String xpath) { List<String> steps = ImmutableList .copyOf(Splitter.on('/') .trimResults() .omitEmptyStrings() .split(xpath)); return steps; } // Bypass JXPathContext#createPathAndValue() because it doesn't support context-dependent predicates private static void updateObjectWithPathAndValue(Map<String, ? super Object> object, List<String> path, Object value) { if(path.isEmpty()) { throw new IllegalArgumentException("There should be at least one step in the given path"); } if(path.size() == 1) { object.put(path.get(0), value); return; } String key = path.get(0); @SuppressWarnings("unchecked") Map<String, ? super Object> next = (Map)object.get(key); if(next == null){ next = Maps.newHashMap(); object.put(key,next); } updateObjectWithPathAndValue(next, path.subList(1, path.size()), value); } }
1,444
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/parser/FilterPredicate.java
package com.netflix.suro.routing.filter.parser; import com.google.common.base.Joiner; public enum FilterPredicate { stringComp("xpath(\"%s\") %s \"%s\""), numberComp("xpath(\"%s\") %s %s"), between("xpath(\"%s\") between (%s, %s)") { public String create(String path, String operator, Object value) { Object[] values = (Object[])value; return String.format(getTemplate(), path, values[0], values[1]); } }, isNull("xpath(\"%s\") is null") { public String create(String path, String operator, Object value) { return String.format(getTemplate(), path); } }, regex("xpath(\"%s\") =~ \"%s\"") { public String create(String path, String operator, Object value) { return String.format(getTemplate(), path, value); } }, existsRight("xpath(\"%s\") exists") { public String create(String path, String operator, Object value) { return String.format(getTemplate(), path); } }, existsLeft("exists xpath(\"%s\")") { public String create(String path, String operator, Object value) { return String.format(getTemplate(), path); } }, trueValue("true") { public String create(String path, String operator, Object value) { return getTemplate(); } }, falseValue("false") { public String create(String path, String operator, Object value) { return getTemplate(); } }, timeComp("xpath(\"%s\") %s %s"), inPred("xpath(\"%s\") in (%s)") { public String create(String path, String operator, Object value) { Object[] values = (Object[])value; return String.format(getTemplate(), path, Joiner.on(',').join(values)); } } ; final private String template; private FilterPredicate(String template) { this.template = template; } public String create(String path, String operator, Object value) { return String.format(template, path, operator, value); } public String getTemplate() { return template; } public String create(String path) { return create(path, null); } public String create(String path, Object value) { return create(path, null, value); } public String create(String path, String operator){ return create(path, operator, null); } public String create() { return create(null, null); } }
1,445
0
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter
Create_ds/suro/suro-core/src/test/java/com/netflix/suro/routing/filter/parser/SimpleMessageFilterParsingTest.java
package com.netflix.suro.routing.filter.parser; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.netflix.suro.routing.filter.MessageFilter; import com.netflix.suro.routing.filter.MessageFilterCompiler; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import static com.netflix.suro.routing.filter.parser.FilterPredicate.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @RunWith(Parameterized.class) public class SimpleMessageFilterParsingTest { private static final String TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss:SSS"; private final static DateTime now = DateTime.now(); @Parameters public static Collection<Object[]> data() { return Arrays.asList( new Object[][] { {0, stringComp, "root", "!=", "value", "!value", "value"}, {1, stringComp, "//a/b/c", "!=", "value", "!value", "value"}, {2, stringComp, "root", "=", "value", "value", "!value"}, {3, stringComp, "//a/b/c", "=", "value", "value", "!value"}, {4, numberComp, "root", "=", -5, -5, 4}, {5, numberComp, "//a/b/c/f", "!=", 10.11, 10.12, 10.11}, {6, numberComp, "root", ">", 5, 9, 5}, {7, numberComp, "root", ">", 5, 9, 4}, {8, numberComp, "//a/b/c/f", ">=", 134.12, 134.12, 133}, {9, numberComp, "root", ">", 134.12, 150, -100}, {10, numberComp, "//a/b/c/f", ">=", 134.12, 140, 100}, {11, numberComp, "root", "<", 5, 4, 5}, {12, numberComp, "root", "<", 5, 4, 9}, {13, numberComp, "//a/b/c/f", "<=", 134.12, 134.12, 190}, {14, numberComp, "//a/b/c/f", "<=", 134.12, 100, 190}, {15, between, "//a/b/cd", null, new Object[]{6, 10}, 6, 15}, {16, between, "//a/b/cd", null, new Object[]{6, 10}, 8, 15}, {17, between, "//a/b/cd", null, new Object[]{6, 10}, 8, 10}, {18, between, "//a/b/cd", null, new Object[]{6, 10}, 8, 15}, {19, between, "//a/b/cd", null, new Object[]{6, 10}, 8, 5}, {20, between, "//a/b/ef", null, new Object[]{ timeMillisNHoursAway(-3, TIME_FORMAT), timeMillisNHoursAway(3, TIME_FORMAT) }, nHoursAway(0), nHoursAway(-4) }, {21, between, "//a/b/ef", null, new Object[]{ timeMillisNHoursAway(-3, TIME_FORMAT), timeMillisNHoursAway(3, TIME_FORMAT) }, nHoursAway(-3), nHoursAway(3) }, {22, between, "//a/b/ef", null, new Object[]{ timeMillisNHoursAway(-3, TIME_FORMAT), timeMillisNHoursAway(3, TIME_FORMAT) }, nHoursAway(2), nHoursAway(4) }, {23, between, "//a/b/ef", null, new Object[]{ timeStringNHoursAway(-3, TIME_FORMAT), timeStringNHoursAway(3, TIME_FORMAT) }, nHoursAway(0, TIME_FORMAT), nHoursAway(-4, TIME_FORMAT) }, {24, between, "//a/b/ef", null, new Object[]{ timeStringNHoursAway(-3, TIME_FORMAT), timeStringNHoursAway(3, TIME_FORMAT) }, nHoursAway(-3, TIME_FORMAT), nHoursAway(3, TIME_FORMAT) }, {25, between, "//a/b/ef", null, new Object[]{ timeStringNHoursAway(-3, TIME_FORMAT), timeStringNHoursAway(3, TIME_FORMAT) }, nHoursAway(2, TIME_FORMAT), nHoursAway(4, TIME_FORMAT) }, {26, timeComp, "//a/b/ef", ">", timeStringNHoursAway(-3, TIME_FORMAT), nHoursAway(0, TIME_FORMAT), nHoursAway(-4, TIME_FORMAT) }, {27, timeComp, "//a/b/ef", "<", timeStringNHoursAway(3, TIME_FORMAT), nHoursAway(0, TIME_FORMAT), nHoursAway(4, TIME_FORMAT) }, {28, timeComp, "//a/b/ef", "=", timeStringNHoursAway(3, TIME_FORMAT), nHoursAway(3, TIME_FORMAT), nHoursAway(4, TIME_FORMAT) }, {29, timeComp, "//a/b/ef", "!=", timeStringNHoursAway(3, TIME_FORMAT), nHoursAway(4, TIME_FORMAT), nHoursAway(3, TIME_FORMAT) }, {30, timeComp, "//a/b/ef", "<", timeMillisNHoursAway(3, TIME_FORMAT), nHoursAway(0), nHoursAway(4) }, {31, timeComp, "//a/b/ef", ">", timeMillisNHoursAway(-3, TIME_FORMAT), nHoursAway(0), nHoursAway(-4) }, {32, timeComp, "//a/b/ef", "<", timeMillisNHoursAway(3, TIME_FORMAT), nHoursAway(0), nHoursAway(4) }, {33, timeComp, "//a/b/ef", "=", timeMillisNHoursAway(3, TIME_FORMAT), nHoursAway(3), nHoursAway(4) }, {34, timeComp, "//a/b/ef", "!=", timeMillisNHoursAway(3, TIME_FORMAT), nHoursAway(0), nHoursAway(3) }, {35, isNull, "//a/b/c", null, null, null, "not null value"}, {36, regex, "//a/b/c", null, "[0-9]+", "1234234", "aaaaaaaaaa"}, {37, existsRight, "//a/b/c", "some value", null, "value", "whaever"}, {38, existsLeft, "//a/b/c", "some value", null, "value", "whaever"}, {39, trueValue, "//a/b/c", null, null, null, null}, {40, falseValue, "//a/b", null, null, null, null}, {41, inPred, "//a/b/c", null, new Object[]{ wrap("abc"), wrap("def"), wrap("foo"), wrap("123"), wrap("end") }, "foo", "bar" }, {41, inPred, "//a/b/c", null, new Object[]{ 123, 455, 1234.23, -1324, 23.0 }, 23.0, 100 } } ); } private static String wrap(String value){ return String.format("\"%s\"", value); } private static long nHoursAway(int n) { return now.plusHours(n).getMillis(); } private static String nHoursAway(int n, String format) { return DateTimeFormat.forPattern(format).print(nHoursAway(n)); } // Creates a time-millis that is n hours away from now private static String timeMillisNHoursAway(int n, String format) { return String.format( "time-millis(\"%s\", \"%s\")", format, nHoursAway(n, format)); } private static String timeStringNHoursAway(int n, String format) { return String.format( "time-string(\"%s\", \"%s\", \"%s\")", format, format, nHoursAway(n, format)); } @Before public void setUp() throws Exception { } private int index; private FilterPredicate predicate; private String predicateString; private Object expectedValue; private Object unexpectedValue; private String xpath; public SimpleMessageFilterParsingTest( int index, FilterPredicate targetPredicate, String xpath, String operator, Object value, Object expected, Object unexpected ) { this.index = index; this.predicate = targetPredicate; this.xpath = xpath; this.predicateString = targetPredicate.create(xpath, operator, value); System.out.println(String.format("[%d] filter = %s", index, predicateString)); this.expectedValue = expected; this.unexpectedValue = unexpected; } @After public void tearDown() throws Exception { } @Test public void testPredicate() throws Exception { try{ MessageFilter filter = MessageFilterCompiler.compile(predicateString); assertNotNull(filter); if(predicate != falseValue){ testPositiveMatch(filter); } if(predicate == trueValue){ return; } if(predicate == existsLeft || predicate == existsRight) { testNegativeExistsPredicate(filter); } else { testNegativeMatch(filter); } }catch(Exception e) { System.err.println(String.format("Failed input for test data [%d]: %s", index, predicateString)); throw e; } } private void testNegativeExistsPredicate(MessageFilter filter) { Object unexpectedEvent = createEvent("nonpath", unexpectedValue); assertEquals( String.format("The object is %s, should not match the filter %s for data set [%d]. Translated filter: %s", unexpectedEvent, predicateString, index, filter), false, filter.apply(unexpectedEvent)); } private void testNegativeMatch(MessageFilter filter) { Object unexpectedEvent = createEvent(xpath, unexpectedValue); assertEquals( String.format("The object is %s, should not match the filter %s for data set [%d]. Translated filter: %s", unexpectedEvent, predicateString, index, filter), false, filter.apply(unexpectedEvent)); } private void testPositiveMatch(MessageFilter filter) { Object expectedEvent = createEvent(xpath, expectedValue); assertEquals( String.format("The object is %s, should match the filter %s for data set [%d]. Translated filter: %s ", expectedEvent, predicateString, index, filter), true, filter.apply(expectedEvent)); } private static Object createEvent(String path, Object value) { List<String> steps = ImmutableList .copyOf(Splitter.on('/') .trimResults() .omitEmptyStrings() .split(path)); return createObjectWithPathAndValue(steps, value); } // Bypass JXPathContext#createPathAndValue() because it doesn't support context-dependent predicates private static Map<String, ? extends Object> createObjectWithPathAndValue(List<String> path, Object value) { if(path.isEmpty()) { throw new IllegalArgumentException("There should be at least one step in the given path"); } if(path.size() == 1) { // We want to allow null values, so we don't use ImmutableMap.of() here. Map<String, ? super Object> map = Maps.newHashMap(); map.put(path.get(0), value); return map; } Map<String, ? extends Object> child = createObjectWithPathAndValue(path.subList(1, path.size()), value); return ImmutableMap.of(path.get(0), child); } }
1,446
0
Create_ds/suro/suro-core/src/main/java/com/netflix
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/SuroPlugin.java
package com.netflix.suro; import com.google.inject.AbstractModule; import com.google.inject.multibindings.Multibinder; import com.netflix.suro.input.RecordParser; import com.netflix.suro.input.SuroInput; import com.netflix.suro.routing.Filter; import com.netflix.suro.sink.Sink; import com.netflix.suro.sink.notice.Notice; import com.netflix.suro.sink.remotefile.RemotePrefixFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Guice based suro plugin with convenience methods for adding pluggable components * using Guice's MapBinder. * * @author elandau * */ public abstract class SuroPlugin extends AbstractModule { protected static final Logger LOG = LoggerFactory.getLogger(SuroPlugin.class); /** * Add a sink implementation to Suro. typeName is the expected value of the * 'type' field of a JSON configuration. * * @param typeName * @param sinkClass */ public <T extends Sink> void addSinkType(String typeName, Class<T> sinkClass) { LOG.info("Adding sinkType: " + typeName + " -> " + sinkClass.getCanonicalName()); Multibinder<TypeHolder> bindings = Multibinder.newSetBinder(binder(), TypeHolder.class); bindings.addBinding().toInstance(new TypeHolder(typeName, sinkClass)); } public <T extends SuroInput> void addInputType(String typeName, Class<T> inputClass) { LOG.info("Adding inputType: " + typeName + " -> " + inputClass.getCanonicalName()); Multibinder<TypeHolder> bindings = Multibinder.newSetBinder(binder(), TypeHolder.class); bindings.addBinding().toInstance(new TypeHolder(typeName, inputClass)); } public <T extends RecordParser> void addRecordParserType(String typeName, Class<T> recordParserClass) { LOG.info("Adding recordParser: " + typeName + " -> " + recordParserClass.getCanonicalName()); Multibinder<TypeHolder> bindings = Multibinder.newSetBinder(binder(), TypeHolder.class); bindings.addBinding().toInstance(new TypeHolder(typeName, recordParserClass)); } public <T extends RemotePrefixFormatter> void addRemotePrefixFormatterType(String typeName, Class<T> remotePrefixFormatterClass) { LOG.info("Adding remotePrefixFormatterType: " + typeName + " -> " + remotePrefixFormatterClass.getCanonicalName()); Multibinder<TypeHolder> bindings = Multibinder.newSetBinder(binder(), TypeHolder.class); bindings.addBinding().toInstance(new TypeHolder(typeName, remotePrefixFormatterClass)); } public <T extends Notice> void addNoticeType(String typeName, Class<T> noticeClass) { LOG.info("Adding notice: " + typeName + "->" + noticeClass.getCanonicalName()); Multibinder<TypeHolder> bindings = Multibinder.newSetBinder(binder(), TypeHolder.class); bindings.addBinding().toInstance(new TypeHolder(typeName, noticeClass)); } public <T extends Filter> void addFilterType(String typeName, Class<T> filterClass) { LOG.info("Adding filterType: " + typeName + "->" + filterClass.getCanonicalName()); Multibinder<TypeHolder> bindings = Multibinder.newSetBinder(binder(), TypeHolder.class); bindings.addBinding().toInstance(new TypeHolder(typeName, filterClass)); } }
1,447
0
Create_ds/suro/suro-core/src/main/java/com/netflix
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/TypeHolder.java
package com.netflix.suro; /** * Holder for a generic subtype to be registered with guice as a Map<String, TypeWrapper> * so that we can cross link Guice injection with Jackson injection. * * Tried to use TypeLiteral but guice doesn't seem to like mixing TypeLiteral with * MapBinder * * @author elandau * */ public class TypeHolder { private final Class<?> type; private final String name; public TypeHolder(String name, Class<?> type) { this.type = type; this.name = name; } public Class<?> getRawType() { return type; } public String getName() { return this.name; } @Override public String toString() { return "TypeHolder [type=" + type + ", name=" + name + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TypeHolder other = (TypeHolder) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1,448
0
Create_ds/suro/suro-core/src/main/java/com/netflix
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/TagKey.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro; public class TagKey { public static final String APP = "suro.app"; public static final String DATA_SOURCE = "suro.datasource"; public static final String SENT_COUNT = "sentMessageCount"; public static final String RECV_COUNT = "receivedMessageCount"; public static final String LOST_COUNT = "lostMessageCount"; public static final String DROPPED_COUNT = "droppedMessageCount"; public static final String RESTORED_COUNT = "restoredMessageCount"; public static final String RETRIED_COUNT = "retriedCount"; public static final String ROUTING_KEY = "routingKey"; public static final String REJECTED_REASON = "rejectedReason"; public static final String ATTEMPTED_COUNT = "attemptedMessageCount"; public static final String DROPPED_REASON = "droppedReason"; }
1,449
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/input/RecordParser.java
package com.netflix.suro.input; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.netflix.suro.message.MessageContainer; import java.util.List; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") public interface RecordParser { List<MessageContainer> parse(String data); }
1,450
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/input/SuroInput.java
package com.netflix.suro.input; import com.fasterxml.jackson.annotation.JsonTypeInfo; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") public interface SuroInput { String getId(); void start() throws Exception; void shutdown(); void setPause(long ms); }
1,451
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/servo/Servo.java
package com.netflix.suro.servo; import com.netflix.servo.DefaultMonitorRegistry; import com.netflix.servo.monitor.*; import com.netflix.servo.tag.BasicTagList; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; public class Servo { private static final ConcurrentMap<MonitorConfig, Counter> counters = new ConcurrentHashMap<>(); private static final ConcurrentMap<MonitorConfig, Timer> timers = new ConcurrentHashMap<>(); private static final ConcurrentMap<MonitorConfig, LongGauge> longGauges = new ConcurrentHashMap<>(); private static final ConcurrentMap<MonitorConfig, DoubleGauge> doubleGauges = new ConcurrentHashMap<>(); private Servo() { } public static Counter getCounter(MonitorConfig config) { Counter v = counters.get(config); if (v != null) return v; else { Counter counter = new BasicCounter(config); Counter prevCounter = counters.putIfAbsent(config, counter); if (prevCounter != null) return prevCounter; else { DefaultMonitorRegistry.getInstance().register(counter); return counter; } } } public static Counter getCounter(String name, String... tags) { MonitorConfig.Builder cfgBuilder = MonitorConfig.builder(name); if (tags.length > 0) { cfgBuilder.withTags(BasicTagList.of(tags)); } return getCounter(cfgBuilder.build()); } public static Timer getTimer(MonitorConfig config) { Timer v = timers.get(config); if (v != null) return v; else { Timer timer = new BasicTimer(config, TimeUnit.SECONDS); Timer prevTimer = timers.putIfAbsent(config, timer); if (prevTimer != null) return prevTimer; else { DefaultMonitorRegistry.getInstance().register(timer); return timer; } } } public static Timer getTimer(String name, String... tags) { MonitorConfig.Builder cfgBuilder = MonitorConfig.builder(name); if (tags.length > 0) { cfgBuilder.withTags(BasicTagList.of(tags)); } return getTimer(cfgBuilder.build()); } public static LongGauge getLongGauge(MonitorConfig config) { LongGauge v = longGauges.get(config); if (v != null) return v; else { LongGauge gauge = new LongGauge(config); LongGauge prev = longGauges.putIfAbsent(config, gauge); if (prev != null) return prev; else { DefaultMonitorRegistry.getInstance().register(gauge); return gauge; } } } public static DoubleGauge getDoubleGauge(MonitorConfig config) { DoubleGauge v = doubleGauges.get(config); if (v != null) return v; else { DoubleGauge gauge = new DoubleGauge(config); DoubleGauge prev = doubleGauges.putIfAbsent(config, gauge); if (prev != null) return prev; else { DefaultMonitorRegistry.getInstance().register(gauge); return gauge; } } } }
1,452
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/servo/Meter.java
package com.netflix.suro.servo; import com.netflix.servo.monitor.BasicCounter; import com.netflix.servo.monitor.MonitorConfig; public class Meter { private BasicCounter counter; private long startTime; public Meter(MonitorConfig config) { counter = new BasicCounter(config); startTime = System.currentTimeMillis() - 1; // to prevent divided by 0 } public void increment() { counter.increment(); } public void increment(long delta) { counter.increment(delta); } public double meanRate() { return counter.getValue().longValue() / (double) (System.currentTimeMillis() - startTime); } }
1,453
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/sink/SinkManager.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.sink; import com.google.common.collect.Maps; import com.google.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PreDestroy; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentMap; /** * SinkManager contains map of sink name and its sink object. * * @author jbae */ @Singleton public class SinkManager { private static final Logger log = LoggerFactory.getLogger(SinkManager.class); private final ConcurrentMap<String, Sink> sinkMap = Maps.newConcurrentMap(); public void initialStart() { for (Sink sink : sinkMap.values()) { sink.open(); } } public void initialSet(Map<String, Sink> newSinkMap) { if (!sinkMap.isEmpty()) { throw new RuntimeException("sinkMap is not empty"); } for (Map.Entry<String, Sink> sink : newSinkMap.entrySet()) { log.info(String.format("Adding sink '%s'", sink.getKey())); sinkMap.put(sink.getKey(), sink.getValue()); } } public void set(Map<String, Sink> newSinkMap) { try { for (Map.Entry<String, Sink> sink : sinkMap.entrySet()) { if ( !newSinkMap.containsKey( sink.getKey() ) ) { // removed Sink removedSink = sinkMap.remove(sink.getKey()); if (removedSink != null) { log.info(String.format("Removing sink '%s'", sink.getKey())); removedSink.close(); } } } for (Map.Entry<String, Sink> sink : newSinkMap.entrySet()) { if (!sinkMap.containsKey( sink.getKey() ) ) { // added log.info(String.format("Adding sink '%s'", sink.getKey())); sink.getValue().open(); sinkMap.put(sink.getKey(), sink.getValue()); } } } catch (Exception e) { log.error("Exception on building SinkManager: " + e.getMessage(), e); if (sinkMap.isEmpty()) { throw new RuntimeException("At least one sink is needed"); } } } public Sink getSink(String id) { Sink sink = sinkMap.get(id); if (sink == null) { sink = sinkMap.get("default"); } return sink; } public String reportSinkStat() { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, Sink> entry : sinkMap.entrySet()) { sb.append(entry.getKey()).append(':').append(entry.getValue().getStat()).append("\n\n"); } return sb.toString(); } public Collection<Sink> getSinks() { return sinkMap.values(); } @PreDestroy public void shutdown() { log.info("SinkManager shutting down"); for (Map.Entry<String, Sink> entry : sinkMap.entrySet()) { entry.getValue().close(); } sinkMap.clear(); } }
1,454
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/sink/DynamicPropertySinkConfigurator.java
package com.netflix.suro.sink; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.Inject; import com.netflix.config.DynamicStringProperty; import com.netflix.governator.annotations.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import java.util.Map; /** * {@link com.netflix.config.DynamicProperty} driven sink configuration. Whenever a change is made to the * dynamic property, this module will parse the JSON and set a new configuration on the * main SinkManager. * * @author elandau */ public class DynamicPropertySinkConfigurator { private static final Logger log = LoggerFactory.getLogger(DynamicPropertySinkConfigurator.class); public static final String SINK_PROPERTY = "SuroServer.sinkConfig"; private final SinkManager sinkManager; private final ObjectMapper jsonMapper; @Configuration(SINK_PROPERTY) private String initialSink; @Inject public DynamicPropertySinkConfigurator( SinkManager sinkManager, ObjectMapper jsonMapper) { this.sinkManager = sinkManager; this.jsonMapper = jsonMapper; } @PostConstruct public void init() { DynamicStringProperty sinkDescription = new DynamicStringProperty(SINK_PROPERTY, initialSink) { @Override protected void propertyChanged() { buildSink(get(), false); } }; buildSink(sinkDescription.get(), true); } private void buildSink(String sink, boolean initStart) { try { Map<String, Sink> newSinkMap = jsonMapper.readValue(sink, new TypeReference<Map<String, Sink>>(){}); if ( !newSinkMap.containsKey("default") ) { throw new IllegalStateException("default sink should be defined"); } if (initStart) { sinkManager.initialSet(newSinkMap); } else { sinkManager.set(newSinkMap); } } catch (Exception e) { log.error("Exception on building SinkManager: " + e.getMessage(), e); } } }
1,455
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/sink/Sink.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.sink; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.netflix.suro.message.MessageContainer; /** * Suro Sink interface * * @author jbae */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") public interface Sink { /** * Write a single message into the sink * * @param message */ void writeTo(MessageContainer message); /** * Open the Sink by establishing any network connections and setting up writing threads */ void open(); /** * Close connections as part of system shutdown or if a Sink is removed */ void close(); String recvNotice(); String getStat(); long getNumOfPendingMessages(); long checkPause(); }
1,456
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/sink/QueuedSink.java
package com.netflix.suro.sink; import com.google.common.annotations.VisibleForTesting; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import com.netflix.servo.monitor.DynamicCounter; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.suro.TagKey; import com.netflix.suro.message.Message; import com.netflix.suro.queue.MessageQueue4Sink; import com.netflix.suro.servo.Meter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * Asynchronous sink would have the internal buffer to return on * {@link Sink#writeTo(com.netflix.suro.message.MessageContainer)} method. * Implementing asynchronous sink can be done by simply extending this class * and initialize itself with {@link MessageQueue4Sink}. This is extending * {@link Thread} and its start() method should be called. * * @author jbae */ public abstract class QueuedSink extends Thread { protected static Logger log = LoggerFactory.getLogger(QueuedSink.class); private long lastBatch = System.currentTimeMillis(); protected volatile boolean isRunning = false; private volatile boolean isStopped = false; public static int MAX_PENDING_MESSAGES_TO_PAUSE = 1000000; // not final for the test @VisibleForTesting protected MessageQueue4Sink queue4Sink; private int batchSize; private int batchTimeout; private String sinkId; protected Meter throughput; private boolean pauseOnLongQueue; // make queue occupied more than half, then should be paused // if throughput is too small at the beginning, pause can be too big // so, setting up minimum threshold as 1 message per millisecond public long checkPause() { if (pauseOnLongQueue && (getNumOfPendingMessages() > queue4Sink.remainingCapacity() || getNumOfPendingMessages() > MAX_PENDING_MESSAGES_TO_PAUSE)) { double throughputRate = Math.max(throughput.meanRate(), 1.0); return (long) (getNumOfPendingMessages() / throughputRate); } else { return 0; } } public String getSinkId() { return sinkId; } protected void initialize( String sinkId, MessageQueue4Sink queue4Sink, int batchSize, int batchTimeout, boolean pauseOnLongQueue) { this.sinkId = sinkId; this.queue4Sink = queue4Sink; this.batchSize = batchSize == 0 ? 1000 : batchSize; this.batchTimeout = batchTimeout == 0 ? 1000 : batchTimeout; this.pauseOnLongQueue = pauseOnLongQueue; throughput = new Meter(MonitorConfig.builder(sinkId + "_throughput_meter").build()); } protected void initialize(MessageQueue4Sink queue4Sink, int batchSize, int batchTimeout) { initialize("empty_sink_id", queue4Sink, batchSize, batchTimeout, false); } @VisibleForTesting protected AtomicLong droppedMessagesCount = new AtomicLong(0); protected void enqueue(Message message) { if (!queue4Sink.offer(message)) { droppedMessagesCount.incrementAndGet(); DynamicCounter.increment( MonitorConfig.builder(TagKey.DROPPED_COUNT) .withTag("reason", "queueFull") .withTag("sink", sinkId) .build()); } } @Override public void run() { isRunning = true; List<Message> msgList = new LinkedList<>(); while (isRunning || !msgList.isEmpty()) { try { beforePolling(); boolean full = (msgList.size() >= batchSize); boolean expired = false; if (!full) { Message msg = queue4Sink.poll( Math.max(0, lastBatch + batchTimeout - System.currentTimeMillis()), TimeUnit.MILLISECONDS); expired = (msg == null); if (!expired) { msgList.add(msg); queue4Sink.drain(batchSize - msgList.size(), msgList); } } full = (msgList.size() >= batchSize); if (expired || full) { if (msgList.size() > 0) { write(msgList); msgList.clear(); } lastBatch = System.currentTimeMillis(); } } catch (Throwable e) { log.error("Thrown on running: " + e.getMessage(), e); droppedMessagesCount.addAndGet(msgList.size()); DynamicCounter.increment( MonitorConfig.builder(TagKey.DROPPED_COUNT) .withTag("reason", "sinkException") .withTag("sink", sinkId) .build(), msgList.size()); msgList.clear(); // drop messages, otherwise, it will retry forever } } log.info("Shutdown request exit loop ..., queue.size at exit time: " + queue4Sink.size()); try { while (!queue4Sink.isEmpty()) { if (queue4Sink.drain(batchSize, msgList) > 0) { write(msgList); msgList.clear(); } } log.info("Shutdown request internalClose done ..."); } catch (Exception e) { log.error("Exception on terminating: " + e.getMessage(), e); } finally { isStopped = true; } } public void close() { isRunning = false; log.info("Starting to close and set isRunning to false"); do { try { Thread.sleep(500); isRunning = false; } catch (Exception ignored) { log.error("ignoring an exception on close"); } } while (!isStopped); try { queue4Sink.close(); innerClose(); } catch (Exception e) { // ignore exceptions when closing log.error("Exception while closing: " + e.getMessage(), e); } finally { log.info("close finished"); } } /** * Some preparation job before polling messages from the queue * * @throws IOException */ abstract protected void beforePolling() throws IOException; /** * Actual writing to the sink * * @param msgList * @throws IOException */ abstract protected void write(List<Message> msgList) throws IOException; /** * Actual close implementation * * @throws IOException */ abstract protected void innerClose() throws IOException; @Monitor(name = "numOfPendingMessages", type = DataSourceType.GAUGE) public long getNumOfPendingMessages() { return queue4Sink.size(); } }
1,457
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/sink/ThreadPoolQueuedSink.java
package com.netflix.suro.sink; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public abstract class ThreadPoolQueuedSink extends QueuedSink { protected final ThreadPoolExecutor senders; protected final ArrayBlockingQueue<Runnable> jobQueue; protected final long jobTimeout; @Monitor(name = "jobQueueSize", type = DataSourceType.GAUGE) public long getJobQueueSize() { return jobQueue.size(); } public ThreadPoolQueuedSink( int jobQueueSize, int corePoolSize, int maxPoolSize, long jobTimeout, String threadFactoryName) { jobQueue = new ArrayBlockingQueue<Runnable>(jobQueueSize == 0 ? 100 : jobQueueSize) { @Override public boolean offer(Runnable runnable) { try { put(runnable); // not to reject the task, slowing down } catch (InterruptedException e) { // do nothing } return true; } }; senders = new ThreadPoolExecutor( corePoolSize == 0 ? 3 : corePoolSize, maxPoolSize == 0 ? 10 : maxPoolSize, 10, TimeUnit.SECONDS, jobQueue, new ThreadFactoryBuilder().setNameFormat(threadFactoryName + "-Sender-%d").build()); this.jobTimeout = jobTimeout; } @Override protected void innerClose() { senders.shutdown(); try { senders.awaitTermination(jobTimeout == 0 ? Long.MAX_VALUE : jobTimeout, TimeUnit.MILLISECONDS); if (!senders.isTerminated()) { log.error(this.getClass().getSimpleName() + " not terminated gracefully"); } } catch (InterruptedException e) { log.error("Interrupted: " + e.getMessage()); } } @Override public long getNumOfPendingMessages() { long messagesInQueue = super.getNumOfPendingMessages(); // add messages in thread pool, either in job queue or active return messagesInQueue + getJobQueueSize() + senders.getActiveCount(); } }
1,458
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/sink/DataConverter.java
package com.netflix.suro.sink; import java.util.Map; public interface DataConverter { Map<String, Object> convert(Map<String, Object> msg); }
1,459
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/sink
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/sink/remotefile/RemotePrefixFormatter.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.sink.remotefile; import com.fasterxml.jackson.annotation.JsonTypeInfo; /** * When uploading files to the remote file system such as S3 or HDFS, the file * path should be specified. This interface is describing which file path would * be prefixed to the file name. * * @author jbae */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") public interface RemotePrefixFormatter { public String get(); }
1,460
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/sink
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/sink/notice/NoNotice.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.sink.notice; import com.netflix.util.Pair; /** * Do nothing for debugging purpose * * @author jbae */ public class NoNotice implements Notice<String> { public static final String TYPE = "no"; @Override public void init() { } @Override public boolean send(String message) { return true; } @Override public String recv() { return null; } @Override public Pair<String, String> peek() { return null; } @Override public void remove(String key) { } @Override public String getStat() { return "No"; } }
1,461
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/sink
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/sink/notice/Notice.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.sink.notice; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.netflix.util.Pair; /** * Notice interface is used to send a notice from the sink to somewhere. * This is a kind of pub-sub module, for example, {@link com.netflix.suro.sink.notice.QueueNotice} is used in * communication between LocalFileSink and S3FileSink. * * @param <E> type of notice * * @author jbae */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") public interface Notice<E> { void init(); boolean send(E message); E recv(); Pair<String, E> peek(); void remove(String key); String getStat(); }
1,462
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/sink
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/sink/notice/QueueNotice.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.sink.notice; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import com.netflix.servo.monitor.Monitors; import com.netflix.suro.TagKey; import com.netflix.util.Pair; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * Memory based implementation of {@link com.netflix.suro.sink.notice.Notice} * * @param <E> type of notice * * @author jbae */ public class QueueNotice<E> implements Notice<E> { public static final String TYPE = "queue"; private static final int DEFAULT_LENGTH = 100; private static final long DEFAULT_TIMEOUT = 1000; private final BlockingQueue<E> queue; private final long timeout; @Monitor(name = TagKey.SENT_COUNT, type = DataSourceType.COUNTER) private AtomicLong sentMessageCount = new AtomicLong(0); @Monitor(name = TagKey.RECV_COUNT, type = DataSourceType.COUNTER) private AtomicLong recvMessageCount = new AtomicLong(0); @Monitor(name = TagKey.LOST_COUNT, type = DataSourceType.COUNTER) private AtomicLong lostMessageCount = new AtomicLong(0); public QueueNotice() { queue = new LinkedBlockingQueue<E>(DEFAULT_LENGTH); timeout = DEFAULT_TIMEOUT; Monitors.registerObject(this); } @JsonCreator public QueueNotice( @JsonProperty("length") int length, @JsonProperty("recvTimeout") long timeout) { this.queue = new LinkedBlockingQueue<E>(length > 0 ? length : DEFAULT_LENGTH); this.timeout = timeout > 0 ? timeout : DEFAULT_TIMEOUT; } @Override public void init() { } @Override public boolean send(E message) { if (queue.offer(message)) { sentMessageCount.incrementAndGet(); return true; } else { lostMessageCount.incrementAndGet(); return false; } } @Override public E recv() { try { return queue.poll(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { return null; } } @Override public Pair<String, E> peek() { return new Pair<String, E>("", queue.peek()); } @Override public void remove(String key) { } @Override public String getStat() { return String.format("QueueNotice with the size: %d, sent : %d, received: %d, dropped: %d", queue.size(), sentMessageCount.get(), recvMessageCount.get(), lostMessageCount.get()); } }
1,463
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/message/Message.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.message; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Arrays; /** * Suro message payload contains routing key as String and payload as byte[]. * This implements Hadoop Writable interface, so it can be written to Hadoop * Sequence file. Empty constructor is needed for Writable interface. * * @author jbae */ public class Message { public static final BiMap<Byte, Class<? extends Message>> classMap = HashBiMap.create(); static { classMap.put((byte) 0, Message.class); } private String routingKey; private byte[] payload; public Message() {} public Message(String routingKey, byte[] payload) { this.routingKey = routingKey; this.payload = payload; } public String getRoutingKey() { return routingKey; } public byte[] getPayload() { return payload; } @Override public String toString() { return String.format("routingKey: %s, payload byte size: %d", routingKey, payload.length); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Message message = (Message) o; if (!Arrays.equals(payload, message.payload)) return false; return !(routingKey != null ? !routingKey.equals(message.routingKey) : message.routingKey != null); } @Override public int hashCode() { int result = routingKey != null ? routingKey.hashCode() : 0; result = 31 * result + (payload != null ? Arrays.hashCode(payload) : 0); return result; } public void write(DataOutput dataOutput) throws IOException { dataOutput.writeUTF(routingKey); dataOutput.writeInt(payload.length); dataOutput.write(payload); } public void readFields(DataInput dataInput) throws IOException { routingKey = dataInput.readUTF(); payload = new byte[dataInput.readInt()]; dataInput.readFully(payload); } }
1,464
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/message/MessageContainer.java
package com.netflix.suro.message; import com.fasterxml.jackson.core.type.TypeReference; /** * Wrapper for a message with caching for deserialization * * @author elandau */ public interface MessageContainer { /** * Get the 'routing' key for this message. Note that the routing key is not * part of the message and does not require deserialization. * @return */ public String getRoutingKey(); /** * Deserialize the message body into the requested entity. * @param clazz * @return * @throws Exception */ public <T> T getEntity(Class<T> clazz) throws Exception; public <T> T getEntity(TypeReference<T> typeReference) throws Exception; /** * Return the raw message * @return */ public Message getMessage(); }
1,465
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/message/StringMessage.java
package com.netflix.suro.message; import com.fasterxml.jackson.core.type.TypeReference; public class StringMessage implements MessageContainer { private final Message message; public static StringMessage from(String routingKey, String body) { return new StringMessage(routingKey, body); } public StringMessage(String routingKey, String body) { message = new Message(routingKey, body.getBytes()); } public StringMessage(Message message) { this.message = message; } @Override public String getRoutingKey() { return message.getRoutingKey(); } @Override public <T> T getEntity(Class<T> clazz) throws Exception { if (clazz.equals(byte[].class)) { return (T)message.getPayload(); } else if (clazz.equals(String.class)) { return (T)new String(message.getPayload()); } else { throw new RuntimeException("Message cannot be deserialized to " + clazz.getCanonicalName()); } } @Override public <T> T getEntity(TypeReference<T> typeReference) throws Exception { throw new RuntimeException("Message cannot be deserialized to TypeReference"); } @Override public Message getMessage() { return message; } }
1,466
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/message/StringSerDe.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.message; public class StringSerDe implements SerDe<String> { @Override public String deserialize(byte[] message) { return new String(message); } @Override public byte[] serialize(String content) { return content.getBytes(); } @Override public String toString(byte[] message) { return new String(message); } }
1,467
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/message/SerDe.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.message; /** * SerDe(Serialization/Deserialization) is necessary for converting POJO to * byte[] vice versa. serialize() receives POJO and returns byte[], deserialize * does reverse. For Java String, StringSerDe is implemented. * * @author jbae * * @param <T> */ public interface SerDe<T> { T deserialize(byte[] payload); byte[] serialize(T payload); String toString(byte[] payload); }
1,468
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/message/ByteArrayDataOutputStream.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.message; import com.google.common.io.ByteArrayDataOutput; import java.io.ByteArrayOutputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; /** * Exposing Guava's ByteStreams.ByteArrayDataOutput, which is private static. */ public class ByteArrayDataOutputStream implements ByteArrayDataOutput { private final DataOutput output; private final ByteArrayOutputStream byteArrayOutputSteam; public ByteArrayDataOutputStream(ByteArrayOutputStream byteArrayOutputSteam) { this.byteArrayOutputSteam = byteArrayOutputSteam; output = new DataOutputStream(byteArrayOutputSteam); } @Override public void write(int b) { try { output.write(b); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void write(byte[] b) { try { output.write(b); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void write(byte[] b, int off, int len) { try { output.write(b, off, len); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeBoolean(boolean v) { try { output.writeBoolean(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeByte(int v) { try { output.writeByte(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeBytes(String s) { try { output.writeBytes(s); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeChar(int v) { try { output.writeChar(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeChars(String s) { try { output.writeChars(s); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeDouble(double v) { try { output.writeDouble(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeFloat(float v) { try { output.writeFloat(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeInt(int v) { try { output.writeInt(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeLong(long v) { try { output.writeLong(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeShort(int v) { try { output.writeShort(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeUTF(String s) { try { output.writeUTF(s); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public byte[] toByteArray() { return byteArrayOutputSteam.toByteArray(); } }
1,469
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/message/DefaultMessageContainer.java
package com.netflix.suro.message; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import java.util.List; public class DefaultMessageContainer implements MessageContainer { private final Message message; private final ObjectMapper jsonMapper; class Item { TypeReference<?> tr; Object obj; } private List<Item> cache; public DefaultMessageContainer(Message message, ObjectMapper jsonMapper) { this.message = message; this.jsonMapper = jsonMapper; } @Override public <T> T getEntity(Class<T> clazz) throws Exception { if (clazz.equals(byte[].class)){ return (T)message.getPayload(); } else if (clazz.equals(String.class)) { return (T)new String(message.getPayload()); } else { return getEntity(new TypeReference<T>(){}); } } @Override public <T> T getEntity(TypeReference<T> typeReference) throws Exception { if (cache == null) { cache = Lists.newLinkedList(); } for (Item item : cache) { if (item.tr.equals(typeReference)) return (T)item.obj; } Item item = new Item(); item.tr = typeReference; item.obj = jsonMapper.readValue(message.getPayload(), typeReference); cache.add(item); return (T)item.obj; } @Override public String getRoutingKey() { return message.getRoutingKey(); } @Override public Message getMessage() { return message; } }
1,470
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/message/MessageSerDe.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.message; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.IOException; /** * Message itself should be (de)serialized. This serde is mainly used to persist * messages to somewhere including file based queue * * @author jbae */ public class MessageSerDe implements SerDe<Message> { private final static Logger log = LoggerFactory.getLogger(MessageSerDe.class); private ThreadLocal<ByteArrayOutputStream> outputStream = new ThreadLocal<ByteArrayOutputStream>() { @Override protected ByteArrayOutputStream initialValue() { return new ByteArrayOutputStream(); } @Override public ByteArrayOutputStream get() { ByteArrayOutputStream b = super.get(); b.reset(); return b; } }; @Override public Message deserialize(byte[] payload) { try { DataInput dataInput = ByteStreams.newDataInput(payload); Class<? extends Message> clazz = Message.classMap.get(dataInput.readByte()); Message msg = clazz.newInstance(); msg.readFields(dataInput); return msg; } catch (Exception e) { log.error("Exception on deserialize: " + e.getMessage(), e); return new Message(); } } @Override public byte[] serialize(Message payload) { try { ByteArrayDataOutput out = new ByteArrayDataOutputStream(outputStream.get()); out.writeByte(Message.classMap.inverse().get(payload.getClass())); payload.write(out); return out.toByteArray(); } catch (IOException e) { log.error("Exception on serialize: " + e.getMessage(), e); return new byte[]{}; } } @Override public String toString(byte[] payload) { return deserialize(payload).toString(); } }
1,471
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/queue/FileBlockingQueue.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.queue; import com.google.common.base.Preconditions; import com.leansoft.bigqueue.BigArrayImpl; import com.leansoft.bigqueue.IBigArray; import com.leansoft.bigqueue.page.IMappedPage; import com.leansoft.bigqueue.page.IMappedPageFactory; import com.leansoft.bigqueue.page.MappedPageFactoryImpl; import com.netflix.suro.message.SerDe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.util.AbstractQueue; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * File based blocking queue with <a href="https://github.com/bulldog2011/bigqueue">BigQueue</a> * @param <E> Type name should be given and its SerDe should be implemented. * * With the argument path and name, files will be created under the directory * [path]/[name]. BigQueue needs to do garge collection, which is deleting * unnecessary page file. Garbage collection is done in the background every * gcPeriodInSec seconds. * * When the messages are retrieved from the queue, * we can control the behavior whether to remove messages immediately or wait * until we commit. autoCommit true means removing messages immediately. * * @author jbae */ public class FileBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E> { private static final Logger log = LoggerFactory.getLogger(FileBlockingQueue.class); private final Lock lock = new ReentrantLock(); private final Condition notEmpty = lock.newCondition(); final IBigArray innerArray; // 2 ^ 3 = 8 final static int QUEUE_FRONT_INDEX_ITEM_LENGTH_BITS = 3; // size in bytes of queue front index page final static int QUEUE_FRONT_INDEX_PAGE_SIZE = 1 << QUEUE_FRONT_INDEX_ITEM_LENGTH_BITS; // only use the first page static final long QUEUE_FRONT_PAGE_INDEX = 0; // folder name for queue front index page final static String QUEUE_FRONT_INDEX_PAGE_FOLDER = "front_index"; // front index of the big queue, final AtomicLong queueFrontIndex = new AtomicLong(); // factory for queue front index page management(acquire, release, cache) IMappedPageFactory queueFrontIndexPageFactory; private final SerDe<E> serDe; private final long sizeLimit; public FileBlockingQueue( String path, String name, int gcPeriodInSec, SerDe<E> serDe) throws IOException { this(path, name, gcPeriodInSec, serDe, Long.MAX_VALUE); } public FileBlockingQueue( String path, String name, int gcPeriodInSec, SerDe<E> serDe, long sizeLimit) throws IOException { innerArray = new BigArrayImpl(path, name); // the ttl does not matter here since queue front index page is always cached this.queueFrontIndexPageFactory = new MappedPageFactoryImpl(QUEUE_FRONT_INDEX_PAGE_SIZE, ((BigArrayImpl)innerArray).getArrayDirectory() + QUEUE_FRONT_INDEX_PAGE_FOLDER, 10 * 1000/*does not matter*/); IMappedPage queueFrontIndexPage = this.queueFrontIndexPageFactory.acquirePage(QUEUE_FRONT_PAGE_INDEX); ByteBuffer queueFrontIndexBuffer = queueFrontIndexPage.getLocal(0); queueFrontIndex.set(queueFrontIndexBuffer.getLong()); Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() { @Override public void run() { try { gc(); } catch (Exception e) { log.error("Exception while gc: " + e.getMessage(), e); } } }, gcPeriodInSec, gcPeriodInSec, TimeUnit.SECONDS); this.serDe = serDe; this.sizeLimit = sizeLimit; } public void gc() throws IOException { long beforeIndex = queueFrontIndex.get(); if (beforeIndex > 0L) { // wrap beforeIndex--; try { innerArray.removeBeforeIndex(beforeIndex); } catch (IndexOutOfBoundsException e) { // do nothing } } try { innerArray.limitBackFileSize(sizeLimit); if (innerArray.getTailIndex() > queueFrontIndex.get()) { queueFrontIndex.set(innerArray.getTailIndex()); } } catch (IndexOutOfBoundsException e) { // do nothing } } private void commitInternal() throws IOException { // persist the queue front IMappedPage queueFrontIndexPage = null; queueFrontIndexPage = this.queueFrontIndexPageFactory.acquirePage(QUEUE_FRONT_PAGE_INDEX); ByteBuffer queueFrontIndexBuffer = queueFrontIndexPage.getLocal(0); queueFrontIndexBuffer.putLong(queueFrontIndex.get()); queueFrontIndexPage.setDirty(true); } public void close() { try { gc(); if (queueFrontIndexPageFactory != null) { queueFrontIndexPageFactory.releaseCachedPages(); } innerArray.close(); } catch(IOException e) { log.error("IOException while closing: " + e.getMessage(), e); } } @Override public E poll() { if (isEmpty()) { return null; } E x = null; lock.lock(); try { if (!isEmpty()) { x = consumeElement(); if (!isEmpty()) { notEmpty.signal(); } } } catch (IOException e) { log.error("IOException while poll: " + e.getMessage(), e); return null; } finally { lock.unlock(); } return x; } @Override public E peek() { if (isEmpty()) { return null; } lock.lock(); try { return consumeElement(); } catch (IOException e) { log.error("IOException while peek: " + e.getMessage(), e); return null; } finally { lock.unlock(); } } @Override public boolean offer(E e) { Preconditions.checkNotNull(e); try { innerArray.append(serDe.serialize(e)); signalNotEmpty(); return true; } catch (IOException ex) { return false; } } @Override public void put(E e) throws InterruptedException { offer(e); } @Override public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException { return offer(e); } @Override public E take() throws InterruptedException { E x; lock.lockInterruptibly(); try { while (isEmpty()) { notEmpty.await(); } x = consumeElement(); } catch (IOException e) { log.error("IOException on take: " + e.getMessage(), e); return null; } finally { lock.unlock(); } return x; } private E consumeElement() throws IOException { // restore consumedIndex if not committed E x = serDe.deserialize(innerArray.get(queueFrontIndex.getAndIncrement())); commitInternal(); return x; } @Override public E poll(long timeout, TimeUnit unit) throws InterruptedException { E x = null; long nanos = unit.toNanos(timeout); lock.lockInterruptibly(); try { while (isEmpty()) { if (nanos <= 0) return null; nanos = notEmpty.awaitNanos(nanos); } x = consumeElement(); } catch (IOException e) { log.error("IOException on poll: " + e.getMessage(), e); return null; } finally { lock.unlock(); } return x; } @Override public int remainingCapacity() { return Integer.MAX_VALUE; } @Override public int drainTo(Collection<? super E> c) { return drainTo(c, Integer.MAX_VALUE); } @Override public int drainTo(Collection<? super E> c, int maxElements) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); lock.lock(); // restore consumedIndex if not committed try { int n = Math.min(maxElements, size()); // count.get provides visibility to first n Nodes int i = 0; while (i < n && queueFrontIndex.get() < innerArray.getHeadIndex()) { c.add(serDe.deserialize(innerArray.get(queueFrontIndex.getAndIncrement()))); ++i; } commitInternal(); return n; } catch (Exception e) { throw new RuntimeException(e); } finally { lock.unlock(); } } @Override public Iterator<E> iterator() { return new Iterator<E>() { @Override public boolean hasNext() { return !isEmpty(); } @Override public E next() { try { E x = consumeElement(); return x; } catch (IOException e) { throw new RuntimeException(e); } } @Override public void remove() { throw new UnsupportedOperationException("remove is not supported, use dequeue()"); } }; } @Override public int size() { return (int)(innerArray.getHeadIndex() - queueFrontIndex.get()); } private void signalNotEmpty() { lock.lock(); try { notEmpty.signal(); } finally { lock.unlock(); } } }
1,472
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/queue/MemoryQueue4Sink.java
package com.netflix.suro.queue; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.suro.message.Message; import javax.annotation.concurrent.NotThreadSafe; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; /** * Memory based {@link MessageQueue4Sink} * <p/> * If capacity is not zero, it delegates to {@link ArrayBlockingQueue}. The queue is typically used as an asynchronous * buffer between the input and sink where adding messages to the queue will fail if queue is full. Otherwise when * capacity is zero, it delegates to {@link SynchronousQueue}, where the there is no buffer and input and sink are always * synchronized. This is helpful when the sink does not want to deal with back-pressure but want to slow down the * input without dropping messages. * * @author jbae */ @NotThreadSafe public class MemoryQueue4Sink implements MessageQueue4Sink { public static final String TYPE = "memory"; private final BlockingQueue<Message> queue; private final int capacity; @JsonCreator public MemoryQueue4Sink(@JsonProperty("capacity") int capacity) { this.capacity = capacity; if (capacity == 0) { this.queue = new SynchronousQueue(); } else { this.queue = new ArrayBlockingQueue(capacity); } } @Override public boolean offer(Message msg) { if (capacity == 0) { try { // for synchronous queue, this will block until the sink takes the message from the queue queue.put(msg); } catch (InterruptedException e) { return false; } return true; } else { return queue.offer(msg); } } @Override public Message poll(long timeout, TimeUnit timeUnit) throws InterruptedException { return queue.poll(timeout, timeUnit); } @Override public int drain(int batchSize, List<Message> msgList) { return queue.drainTo(msgList, batchSize); } @Override public void close() { // do nothing } @Override public boolean isEmpty() { return queue.isEmpty(); } @Override public long size() { return queue.size(); } @Override public long remainingCapacity() { return queue.remainingCapacity(); } }
1,473
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/queue/FileQueue4Sink.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.queue; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.suro.message.Message; import com.netflix.suro.message.MessageSerDe; import org.joda.time.Period; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.concurrent.NotThreadSafe; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; /** * File based {@link MessageQueue4Sink}, delegating actual logic to {@link FileBlockingQueue} * * @author jbae */ @NotThreadSafe public class FileQueue4Sink implements MessageQueue4Sink { private static final Logger log = LoggerFactory.getLogger(FileQueue4Sink.class); public static final String TYPE = "file"; private final FileBlockingQueue<Message> queue; @JsonCreator public FileQueue4Sink( @JsonProperty("path") String path, @JsonProperty("name") String name, @JsonProperty("gcPeriod") String gcPeriod, @JsonProperty("sizeLimit") long sizeLimit) throws IOException { queue = new FileBlockingQueue<Message>( path, name, new Period(gcPeriod == null ? "PT1m" : gcPeriod).toStandardSeconds().getSeconds(), new MessageSerDe(), sizeLimit == 0 ? Long.MAX_VALUE : sizeLimit); } @Override public boolean offer(Message msg) { try { return queue.offer(msg); } catch (Exception e) { log.error("Exception on offer: " + e.getMessage(), e); return false; } } @Override public int drain(int batchSize, List<Message> msgList) { return queue.drainTo(msgList, batchSize); } @Override public Message poll(long timeout, TimeUnit unit) throws InterruptedException { return queue.poll(timeout, unit); } @Override public void close() { queue.close(); } @Override public boolean isEmpty() { return queue.isEmpty(); } @Override public long size() { return queue.size(); } @Override public long remainingCapacity() { return Long.MAX_VALUE; // theoretically unlimited } }
1,474
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/queue/MessageQueue4Sink.java
package com.netflix.suro.queue; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.netflix.suro.message.Message; import java.util.List; import java.util.concurrent.TimeUnit; /** * Queue interface used in {@link com.netflix.suro.sink.Sink}. * With Java's {@code java.util.concurrent.BlockingQueue} interface, we cannot control 'commit' behavior such as * before writing messages retrieved from the queue to sink, when the process dies, * we will lose messages when messages are removed immediately after being polled. * To implement 'commit' behavior, we need to implement own queue interface. * * @author jbae */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") @JsonSubTypes(value = { @JsonSubTypes.Type(name = MemoryQueue4Sink.TYPE, value = MemoryQueue4Sink.class), @JsonSubTypes.Type(name = FileQueue4Sink.TYPE, value = FileQueue4Sink.class) }) public interface MessageQueue4Sink { boolean offer(Message msg); Message poll(long timeout, TimeUnit timeUnit) throws InterruptedException; int drain(int batchSize, List<Message> msgList); void close(); boolean isEmpty(); long size(); long remainingCapacity(); }
1,475
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/MessageRouter.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.routing; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Strings; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.servo.monitor.DynamicCounter; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.monitor.Monitors; import com.netflix.suro.TagKey; import com.netflix.suro.input.SuroInput; import com.netflix.suro.message.DefaultMessageContainer; import com.netflix.suro.message.Message; import com.netflix.suro.message.MessageContainer; import com.netflix.suro.routing.RoutingMap.Route; import com.netflix.suro.sink.Sink; import com.netflix.suro.sink.SinkManager; import java.util.List; /** * Message routing module according to {@link RoutingMap} * * @author jbae */ @Singleton public class MessageRouter { private final RoutingMap routingMap; private final SinkManager sinkManager; private final ObjectMapper jsonMapper; @Inject public MessageRouter( RoutingMap routingMap, SinkManager sinkManager, ObjectMapper jsonMapper) { this.routingMap = routingMap; this.sinkManager = sinkManager; this.jsonMapper = jsonMapper; Monitors.registerObject(this); } public void process(SuroInput input, MessageContainer msg) throws Exception { if (Strings.isNullOrEmpty(msg.getRoutingKey())) { DynamicCounter.increment( MonitorConfig.builder(TagKey.DROPPED_COUNT).withTag("reason", "emptyRoutingKey").build()); return; // discard message } DynamicCounter.increment( MonitorConfig .builder(TagKey.RECV_COUNT) .withTag("routingKey", msg.getRoutingKey()) .build()); RoutingMap.RoutingInfo info = routingMap.getRoutingInfo(msg.getRoutingKey()); if (info == null) { Sink defaultSink = sinkManager.getSink("default"); input.setPause(defaultSink.checkPause()); defaultSink.writeTo(msg); } else if (info.doFilter(msg)) { List<Route> routes = info.getWhere(); for (Route route : routes) { if (route.doFilter(msg)) { Sink sink = sinkManager.getSink(route.getSink()); input.setPause(sink.checkPause()); if (!Strings.isNullOrEmpty(route.getAlias())) { sink.writeTo( new DefaultMessageContainer( new Message(route.getAlias(), msg.getMessage().getPayload()), jsonMapper)); } else { sink.writeTo(msg); } DynamicCounter.increment( MonitorConfig .builder(TagKey.ATTEMPTED_COUNT) .withTag("routingKey", msg.getRoutingKey()) .withTag("sinkId", route.getSink()) .build()); } } } } }
1,476
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/RegexFilter.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.routing; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.suro.message.MessageContainer; import java.util.regex.Pattern; /** * An implementation of {@link Filter} that coerced message payload to a string, and applies * regex to the coerced string. The match is partial. * */ public class RegexFilter implements Filter { public static final String TYPE = "regex"; public static final String JSON_PROPERTY_REGEX = "regex"; private final Pattern filterPattern; @JsonCreator public RegexFilter(@JsonProperty(JSON_PROPERTY_REGEX) String regex) { filterPattern = Pattern.compile(regex); } @JsonProperty(JSON_PROPERTY_REGEX) public String getRegex() { return filterPattern.pattern(); } /** * * @param message The message that is to be matched against the filter's regex pattern * @return true if the message's string representation contains the regex pattern. False otherwise. * @throws Exception If filtering fails. For example, if the given message can't be coerced into a string. */ @Override public boolean doFilter(MessageContainer message) throws Exception { return filterPattern.matcher(message.getEntity(String.class)).find(); } }
1,477
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/XPathFilter.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.routing; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.suro.message.MessageContainer; import com.netflix.suro.routing.filter.MessageFilter; import com.netflix.suro.routing.filter.MessageFilterCompiler; import com.netflix.suro.routing.filter.lang.InvalidFilterException; /** * An implementation of {@link Filter} that coerced message payload to a string, and applies * regex to the coerced string. The match is partial. * */ public class XPathFilter implements Filter { public static final String TYPE = "xpath"; public static final String JSON_PROPERTY_FILTER = "filter"; public static final String JSON_PROPERTY_CONVERTER = "converter"; private final MessageFilter filter; private final String expression; private final MessageConverter converter; @JsonCreator public XPathFilter( @JsonProperty(JSON_PROPERTY_FILTER) String expression, @JsonProperty(JSON_PROPERTY_CONVERTER) MessageConverter converter) { this.expression = expression; try { filter = MessageFilterCompiler.compile(expression); } catch (InvalidFilterException e) { throw new IllegalArgumentException(String.format("Can't compile expression %s into a message filter: %s", expression, e.getMessage()), e); } this.converter = converter == null ? new JsonMapConverter() : converter; } /** * * @param message The message that is to be matched against the filter's regex pattern * @return true if the message's string representation contains the regex pattern. False otherwise. * @throws Exception If filtering fails. For example, if the given message can't be coerced into a string. */ @Override public boolean doFilter(MessageContainer message) throws Exception { return filter.apply(converter.convert(message)); } @JsonProperty(JSON_PROPERTY_CONVERTER) public MessageConverter getConverter() { return converter; } @JsonProperty(JSON_PROPERTY_FILTER) public String getExpression() { return expression; } }
1,478
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/JsonMapConverter.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.routing; import com.netflix.suro.message.MessageContainer; import java.util.Map; /** * An implementation of {@link MessageConverter} that converts the payload of a {@link com.netflix.suro.message.MessageContainer} * to a {@link java.util.Map} object with the assumption that the payload is a serialized JSON object. */ public class JsonMapConverter implements MessageConverter<Map>{ public final static String TYPE = "jsonmap"; @Override public Map convert(MessageContainer message) { try { return message.getEntity(Map.class); } catch (Exception e) { throw new IllegalArgumentException( String.format("Can't convert the given message with routing key %s to a JSON map: %s", message.getRoutingKey(), e.getMessage()), e); } } }
1,479
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/DynamicPropertyRoutingMapConfigurator.java
package com.netflix.suro.routing; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.config.DynamicStringProperty; import com.netflix.governator.annotations.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import java.util.Map; /** * {@link com.netflix.config.DynamicProperty} driven routing map configuration. Whenever a change is made to the * dynamic property of routing rules, this module will parse the JSON and set a new configuration on the * main {@link RoutingMap}. * * @author elandau */ @Singleton public class DynamicPropertyRoutingMapConfigurator { public static final String ROUTING_MAP_PROPERTY = "SuroServer.routingMap"; private static Logger LOG = LoggerFactory.getLogger(DynamicPropertyRoutingMapConfigurator.class); private final RoutingMap routingMap; private final ObjectMapper jsonMapper; @Configuration(ROUTING_MAP_PROPERTY) private String initialRoutingMap; @Inject public DynamicPropertyRoutingMapConfigurator( RoutingMap routingMap, ObjectMapper jsonMapper) { this.routingMap = routingMap; this.jsonMapper = jsonMapper; } @PostConstruct public void init() { DynamicStringProperty routingMapFP = new DynamicStringProperty(ROUTING_MAP_PROPERTY, initialRoutingMap) { @Override protected void propertyChanged() { buildMap(get()); } }; buildMap(routingMapFP.get()); } private void buildMap(String map) { try { Map<String, RoutingMap.RoutingInfo> routes = jsonMapper.readValue( map, new TypeReference<Map<String, RoutingMap.RoutingInfo>>() {}); routingMap.set(routes); } catch (Exception e) { LOG.info("Error reading routing map from fast property: "+e.getMessage(), e); } } }
1,480
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/RoutingPlugin.java
package com.netflix.suro.routing; import com.netflix.suro.SuroPlugin; public class RoutingPlugin extends SuroPlugin { @Override protected void configure() { this.addFilterType(RegexFilter.TYPE, RegexFilter.class); this.addFilterType(XPathFilter.TYPE, XPathFilter.class); } }
1,481
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/RoutingMap.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.routing; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.inject.Singleton; import com.netflix.suro.message.MessageContainer; import java.util.List; import java.util.Map; /** * A collection of {@link RoutingInfo}, each of which is mapped to a routing key. * * @author jbae * @author elandau * */ @Singleton public class RoutingMap { public static final String KEY_FOR_DEFAULT_ROUTING = "__default__"; public static class Route { public static final String JSON_PROPERTY_SINK = "sink"; public static final String JSON_PROPERTY_FILTER = "filter"; public static final String JSON_PROPERTY_ALIAS = "alias"; private final String sink; private final Filter filter; private final String alias; @JsonCreator public Route( @JsonProperty(JSON_PROPERTY_SINK) String sink, @JsonProperty(JSON_PROPERTY_FILTER) Filter filter, @JsonProperty(JSON_PROPERTY_ALIAS) String alias) { this.sink = sink; this.filter = filter; this.alias = alias; } @JsonProperty(JSON_PROPERTY_SINK) public String getSink() { return sink; } @JsonProperty(JSON_PROPERTY_FILTER) public Filter getFilter() { return filter; } @JsonProperty(JSON_PROPERTY_ALIAS) public String getAlias() { return alias; } public boolean doFilter(MessageContainer message) throws Exception { return filter == null || filter.doFilter(message); } } public static class RoutingInfo { public static final String JSON_PROPERTY_WHERE = "where"; public static final String JSON_PROPERTY_FILTER = "filter"; private final List<Route> where; private final Filter filter; @JsonCreator public RoutingInfo( @JsonProperty(JSON_PROPERTY_WHERE) List<Route> where, @JsonProperty(JSON_PROPERTY_FILTER) Filter filter ) { this.where = where; this.filter = filter; } @JsonProperty(JSON_PROPERTY_WHERE) public List<Route> getWhere() { return where; } @JsonProperty(JSON_PROPERTY_FILTER) public Filter getFilter() { return filter; } /** * Filters given messages based on filters defined in * this object. * @param message the message to be filtered. * @return true if there is no filter found or if the filter returns true when applied to the message. * @throws Exception thrown if filtering ran into an unexpected failure */ public boolean doFilter(MessageContainer message) throws Exception { return filter == null || filter.doFilter(message); } } private volatile ImmutableMap<String, RoutingInfo> routingMap = ImmutableMap.of(); private volatile RoutingInfo defaultRoutingInfo = null; public RoutingInfo getRoutingInfo(String routingKey) { RoutingInfo info = routingMap.get(routingKey); if(info == null) { info = defaultRoutingInfo; } return info; } public void set(Map<String, RoutingInfo> routes) { // We assume only a single thread will call this method, so // there's no need to synchronize this method routingMap = ImmutableMap.copyOf(routes); defaultRoutingInfo = routingMap.get(KEY_FOR_DEFAULT_ROUTING); } public Map<String, RoutingInfo> getRoutingMap() { return routingMap; } }
1,482
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/RoutingKeyFilter.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.routing; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.suro.message.MessageContainer; import java.util.regex.Pattern; /** * An implementation of {@link com.netflix.suro.routing.Filter} that filters a message's routing key by regex pattern. * The matching is partial. * */ public class RoutingKeyFilter implements Filter { public static final String TYPE = "routingkey"; public static final String JSON_PROPERTY_REGEX = "regex"; private final Pattern filterPattern; @JsonCreator public RoutingKeyFilter(@JsonProperty(JSON_PROPERTY_REGEX) String regex) { filterPattern = Pattern.compile(regex); } @JsonProperty(JSON_PROPERTY_REGEX) public String getRegex() { return filterPattern.pattern(); } /** * * @param message The message that is to be matched against the routing key's regex pattern * @return true if the message's routing key contains the regex pattern. False otherwise. * @throws Exception If filtering fails. */ @Override public boolean doFilter(MessageContainer message) throws Exception { return filterPattern.matcher(message.getRoutingKey()).find(); } }
1,483
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/Filter.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.suro.routing; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.netflix.suro.message.MessageContainer; import com.netflix.suro.queue.FileQueue4Sink; import com.netflix.suro.queue.MemoryQueue4Sink; /** * Interface for filtering messages. Implementation of this filter must be serializable into * JSON. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") @JsonSubTypes(value = { @JsonSubTypes.Type(name = RegexFilter.TYPE, value = RegexFilter.class), @JsonSubTypes.Type(name = XPathFilter.TYPE, value = XPathFilter.class), @JsonSubTypes.Type(name = RoutingKeyFilter.TYPE, value = RoutingKeyFilter.class) }) public interface Filter { /** * Performs message matching to help determine if a message should be filtered. * @param message The message container that will be matched against * @return true if the given message matches an implementation's filtering rule. False otherwise. * @throws Exception if unexpected error happens */ public boolean doFilter(MessageContainer message) throws Exception; }
1,484
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/MessageConverter.java
package com.netflix.suro.routing; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.netflix.suro.message.MessageContainer; /** * Converts an {@link com.netflix.suro.message.MessageContainer} to a Java object that is suitable * for filtering by {@link XPathFilter} */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") @JsonSubTypes(value = { @JsonSubTypes.Type(name = JsonMapConverter.TYPE, value = JsonMapConverter.class), }) public interface MessageConverter<T> { /** * Converts the message in the given message container to an object of type T * @param message The message container that contains the message to be converted. * * @return Converted object from the given message container */ public T convert(MessageContainer message); }
1,485
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/TimeRangeValuePredicate.java
package com.netflix.suro.routing.filter; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import org.joda.time.Interval; import org.joda.time.format.DateTimeFormatter; import javax.annotation.Nullable; public class TimeRangeValuePredicate implements ValuePredicate<Long> { private String timeFormat; private String start; private String end; private Interval interval; public TimeRangeValuePredicate(String timeFormat, String start, String end){ Preconditions.checkArgument(!Strings.isNullOrEmpty(timeFormat), "Time format can't be null or empty. "); Preconditions.checkArgument(!Strings.isNullOrEmpty(start), "The lower bound of time range can't be null or empty."); Preconditions.checkArgument(!Strings.isNullOrEmpty(end), "The upper bound of time range can't be null or empty. "); this.timeFormat = timeFormat; this.start = start; this.end = end; DateTimeFormatter format = TimeUtil.toDateTimeFormatter("time format", timeFormat); long startInstant = format.parseMillis(start); long endInstant = format.parseMillis(end); try{ this.interval = new Interval(startInstant, endInstant); }catch(IllegalArgumentException e) { String msg = String.format( "The lower bound should be smaller than or equal to upper bound for a time range. Given range: [%s, %s)", start, end); IllegalArgumentException iae = new IllegalArgumentException(msg, e.getCause()); iae.setStackTrace(e.getStackTrace()); throw iae; } } @Override public boolean apply(@Nullable Long input) { return null != input && this.interval.contains(input); } public String getStart(){ return start; } public String getTimeFormat(){ return this.timeFormat; } String getEnd() { return this.end; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("TimeRangeValuePredicate [timeFormat="); builder.append(timeFormat); builder.append(", start="); builder.append(start); builder.append(", end="); builder.append(end); builder.append(", interval="); builder.append(interval); builder.append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((end == null) ? 0 : end.hashCode()); result = prime * result + ((start == null) ? 0 : start.hashCode()); result = prime * result + ((timeFormat == null) ? 0 : timeFormat.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TimeRangeValuePredicate other = (TimeRangeValuePredicate) obj; if (end == null) { if (other.end != null) { return false; } } else if (!end.equals(other.end)) { return false; } if (start == null) { if (other.start != null) { return false; } } else if (!start.equals(other.start)) { return false; } if (timeFormat == null) { if (other.timeFormat != null) { return false; } } else if (!timeFormat.equals(other.timeFormat)) { return false; } return true; } }
1,486
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/BaseMessageFilter.java
package com.netflix.suro.routing.filter; /** * Base implementation of {@link SerializableMessageFilter} to implement serialization mechanism. <br/> * The idea behind serialization is to store the DSL from which this filter was created. This approach works as there is * no time where we create this instance without the DSL string. On top of that, creating the DSL from the filter * string is too much of work both at runtime and development time. * * @author Nitesh Kant ([email protected]) */ public abstract class BaseMessageFilter implements SerializableMessageFilter { protected String originalDslString; @Override public String serialize() { return originalDslString; } /** * This must be called at the top level MessageFilter and not for any sub-filters under the main filter. <br/> * eg: for an event filter, say filter0, which is expressed as (Filter1 AND Filter2), this method is required to * only be called for filter0 and not for filter1 and filter2. This value if set for filter1, filter2 will be ignored. * * @param originalDslString The original DSL string. */ public void setOriginalDslString(String originalDslString) { this.originalDslString = originalDslString; } }
1,487
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/ValuePredicate.java
package com.netflix.suro.routing.filter; import com.google.common.base.Predicate; public interface ValuePredicate<T> extends Predicate<T>{ // Emphasize that every {@code ValuePredicate} instance can be used as a key // in a collection. public int hashCode(); public boolean equals(Object o); }
1,488
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/BooleanValuePredicate.java
package com.netflix.suro.routing.filter; import com.google.common.base.Objects; import javax.annotation.Nullable; public class BooleanValuePredicate implements ValuePredicate<Boolean> { private Boolean value; private BooleanValuePredicate(@Nullable Boolean value){ this.value = value; } @Override public boolean apply(@Nullable Boolean input) { return Objects.equal(value, input); } public Boolean getValue(){ return value; } public static final BooleanValuePredicate TRUE = new BooleanValuePredicate(Boolean.TRUE); public static final BooleanValuePredicate FALSE = new BooleanValuePredicate(Boolean.FALSE); @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("BooleanValuePredicate [value="); builder.append(value); builder.append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } BooleanValuePredicate other = (BooleanValuePredicate) obj; if (value == null) { if (other.value != null) { return false; } } else if (!value.equals(other.value)) { return false; } return true; } }
1,489
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/MessageFilters.java
package com.netflix.suro.routing.filter; import com.google.common.collect.ImmutableList; /** * A number of static helper methods to simplify the construction of combined event filters. */ public class MessageFilters { private MessageFilters(){} public static MessageFilter alwaysTrue(){ return AlwaysTrueMessageFilter.INSTANCE; } public static MessageFilter alwaysFalse() { return AlwaysFalseMessageFilter.INSTANCE; } public static MessageFilter or(MessageFilter...filters) { return new OrMessageFilter(filters); } public static MessageFilter or(Iterable<MessageFilter> filters) { return new OrMessageFilter(ImmutableList.copyOf(filters)); } public static MessageFilter and(MessageFilter...filters) { return new AndMessageFilter(filters); } public static MessageFilter and(Iterable<MessageFilter> filters){ return new AndMessageFilter(ImmutableList.copyOf(filters)); } public static MessageFilter not(MessageFilter filter) { return new NotMessageFilter(filter); } }
1,490
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/PathValueMessageFilter.java
package com.netflix.suro.routing.filter; import org.apache.commons.jxpath.JXPathContext; public class PathValueMessageFilter extends BaseMessageFilter { private String xpath; private ValuePredicate predicate; public PathValueMessageFilter(String path, ValuePredicate predicate) { this.xpath = path; this.predicate = predicate; } @SuppressWarnings("unchecked") @Override public boolean apply(Object input) { JXPathContext jxpath = JXPathContext.newContext(input); // We should allow non-existing path, and let predicate handle it. jxpath.setLenient(true); Object value = jxpath.getValue(xpath); return predicate.apply(value); } public String getXpath() { return xpath; } public ValuePredicate getPredicate() { return predicate; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("PathValueMessageFilter [xpath="); builder.append(xpath); builder.append(", predicate="); builder.append(predicate); builder.append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((predicate == null) ? 0 : predicate.hashCode()); result = prime * result + ((xpath == null) ? 0 : xpath.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } PathValueMessageFilter other = (PathValueMessageFilter) obj; if (predicate == null) { if (other.predicate != null) { return false; } } else if (!predicate.equals(other.predicate)) { return false; } if (xpath == null) { if (other.xpath != null) { return false; } } else if (!xpath.equals(other.xpath)) { return false; } return true; } }
1,491
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/NotMessageFilter.java
package com.netflix.suro.routing.filter; import com.google.common.base.Predicate; import com.google.common.base.Predicates; public class NotMessageFilter extends BaseMessageFilter { final private Predicate<Object> notPredicate; public NotMessageFilter(MessageFilter filter) { this.notPredicate = Predicates.not(filter); } @Override public boolean apply(Object input) { return notPredicate.apply(input); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("NotMessageFilter"); sb.append("{notPredicate=").append(notPredicate); sb.append('}'); return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NotMessageFilter that = (NotMessageFilter) o; if (notPredicate != null ? !notPredicate.equals(that.notPredicate) : that.notPredicate != null) { return false; } return true; } @Override public int hashCode() { return notPredicate != null ? notPredicate.hashCode() : 0; } }
1,492
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/AlwaysTrueMessageFilter.java
package com.netflix.suro.routing.filter; final public class AlwaysTrueMessageFilter extends BaseMessageFilter { private AlwaysTrueMessageFilter() { setOriginalDslString("true"); } @Override public boolean apply(Object input) { return true; } public static final AlwaysTrueMessageFilter INSTANCE = new AlwaysTrueMessageFilter(); @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("AlwaysTrueMessageFilter []"); return builder.toString(); } @Override public int hashCode() { return Boolean.TRUE.hashCode(); } @Override public boolean equals(Object obj){ return obj instanceof AlwaysTrueMessageFilter; } }
1,493
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/NumericValuePredicate.java
package com.netflix.suro.routing.filter; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.google.common.primitives.Doubles; import java.util.Map; import java.util.Set; public class NumericValuePredicate implements ValuePredicate<Number> { private Number value; private Operator op; public NumericValuePredicate(Number value, String fnName) { Preconditions.checkNotNull(value, "A null number doesn't make sense. "); this.value = value; this.op = Operator.lookup(fnName); } public Number getValue() { return value; } public String getOpName () { return this.op.getOpName(); } @Override public boolean apply(Number input) { Preconditions.checkNotNull(input, "A null number doesn't make sense."); return op.compare(input, value); } private static enum Operator { GREATER_THAN(">") { @Override public boolean compare(Number left, Number right) { return doComparison(left, right) > 0; } }, GREATER_THAN_OR_EQUAL(">=") { @Override public boolean compare(Number left, Number right) { return doComparison(left, right) >= 0; } }, LESS_THAN("<") { @Override public boolean compare(Number left, Number right) { return doComparison(left, right) < 0; } }, LESS_THAN_OR_EQUAL("<=") { @Override public boolean compare(Number left, Number right) { return doComparison(left, right) <= 0; } }, EQUAL("=") { @Override public boolean compare(Number left, Number right) { return doComparison(left, right) == 0; } }, NOT_EQUAL("!=") { @Override public boolean compare(Number left, Number right) { return doComparison(left, right) != 0; } } ; private String name; private Operator(String name) { this.name = name; } public String getOpName() { return this.name; } public static Operator lookup(String opName) { Operator op = LOOKUP_TABLE.get(opName); if(op == null){ throw new IllegalArgumentException( String.format("The operator '%s' is not supported. Supported operations: %s", opName, getOperatorNames() )); } return op; } public static Set<String> getOperatorNames() { return LOOKUP_TABLE.keySet(); } private static int doComparison(Number a, Number b) { return Doubles.compare(a.doubleValue(), b.doubleValue()); } public abstract boolean compare(Number left, Number right); // According to JSR-133's FAQ (http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#finalRight), // " In addition, the visible values for any other object or array referenced by those final // fields will be at least as up-to-date as the final fields.". Therefore, no need to use sync'd map // here as this lookup table will be read-only. private static final Map<String, Operator> LOOKUP_TABLE = Maps.newHashMap(); static { for (Operator op : Operator.values()) { LOOKUP_TABLE.put(op.getOpName(), op); } } } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("NumericValuePredicate [value="); builder.append(value); builder.append(", op="); builder.append(op); builder.append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((op == null) ? 0 : op.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } NumericValuePredicate other = (NumericValuePredicate) obj; if (op != other.op) { return false; } if (value == null) { if (other.value != null) { return false; } } else if (!value.equals(other.value)) { return false; } return true; } }
1,494
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/SerializableMessageFilter.java
package com.netflix.suro.routing.filter; /** * An optional feature for a {@link MessageFilter} which indicates that the event filter can be converted back and forth * from a string. <br/> * Typically, if the filter is an expression of a language, as defined by {@link com.netflix.suro.routing.filter.lang}, then * it should implement this interface. On the other hand, if the filter is represented as code, implementation of this * interface is not required. <br/> * Any persistence of an {@link MessageFilter} will require the filter to implement this interface, else it will not be * persisted. Since, the filters created in code will typically be registered by the subscribers themselves, they * typically will not need any persistence. <br/> * One will notice that this filter only supports converting the object representation to a string and not back as the * conversion from arbitrary string is handled by {@link MessageFilterCompiler}. Such, factory * kind of methods are deliberately not provided here so that the filter classes do not have to provide any parsing * logic. * * @author Nitesh Kant ([email protected]) */ public interface SerializableMessageFilter extends MessageFilter { /** * Serializes this filter into the filter string * * @return String representation of the filter. */ String serialize(); }
1,495
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/AndMessageFilter.java
package com.netflix.suro.routing.filter; import com.google.common.base.Predicate; import com.google.common.base.Predicates; public class AndMessageFilter extends BaseMessageFilter { final private Predicate<Object> andPredicate; public AndMessageFilter(MessageFilter... filters) { this.andPredicate = Predicates.and(filters); } public AndMessageFilter(Iterable<? extends MessageFilter> filters) { this.andPredicate = Predicates.and(filters); } @Override public boolean apply(Object input) { return andPredicate.apply(input); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AndMessageFilter that = (AndMessageFilter) o; if (andPredicate != null ? !andPredicate.equals(that.andPredicate) : that.andPredicate != null) { return false; } return true; } @Override public int hashCode() { return andPredicate != null ? andPredicate.hashCode() : 0; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("AndMessageFilter"); sb.append("{andPredicate=").append(andPredicate); sb.append('}'); return sb.toString(); } }
1,496
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/RegexValuePredicate.java
package com.netflix.suro.routing.filter; import com.google.common.base.Preconditions; import javax.annotation.Nullable; import java.util.regex.Pattern; public class RegexValuePredicate implements ValuePredicate<String> { private String regex; private Pattern pattern; private MatchPolicy policy; public RegexValuePredicate(String regex, MatchPolicy policy){ Preconditions.checkArgument(regex != null, String.format("The regex should not be null.")); this.regex = regex; this.pattern = Pattern.compile(regex); this.policy = policy; } @Override public boolean apply(@Nullable String input) { if(input == null){ return false; } if(policy == MatchPolicy.PARTIAL){ return pattern.matcher(input).find(); } if(policy == MatchPolicy.FULL){ return pattern.matcher(input).matches(); } throw new UnsupportedOperationException(String.format("the match policy %s is not supported", policy)); } public String getPattern() { return this.pattern.pattern(); } public MatchPolicy getMatchPolicy() { return policy; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("RegexValuePredicate [pattern="); builder.append(regex); builder.append(", policy="); builder.append(policy); builder.append("]"); return builder.toString(); } public static enum MatchPolicy { PARTIAL, FULL } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((policy == null) ? 0 : policy.hashCode()); result = prime * result + ((regex == null) ? 0 : regex.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } RegexValuePredicate other = (RegexValuePredicate) obj; if (policy != other.policy) { return false; } if (regex == null) { if (other.regex != null) { return false; } } else if (!regex.equals(other.regex)) { return false; } return true; } }
1,497
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/TimeStringValuePredicate.java
package com.netflix.suro.routing.filter; import org.joda.time.format.DateTimeFormatter; import javax.annotation.Nullable; public class TimeStringValuePredicate implements ValuePredicate<String> { private String valueFormat; private String inputFormat; private String value; private String fnName; private DateTimeFormatter inputTimeFormatter; private TimeMillisValuePredicate timePredicate; public TimeStringValuePredicate(String valueFormat, String inputFormat, String value, String fnName){ this.valueFormat = valueFormat; this.inputFormat = inputFormat; this.value = value; this.fnName = fnName; this.inputTimeFormatter = TimeUtil.toDateTimeFormatter("input format", inputFormat); this.timePredicate = new TimeMillisValuePredicate(this.valueFormat, value, fnName); } @Override public boolean apply(@Nullable String input) { long timeValue = inputTimeFormatter.parseMillis(input); return timePredicate.apply(timeValue); } public String getValue(){ return value; } public String getValueFormat(){ return this.valueFormat; } public String getInputFormat() { return this.inputFormat; } String getFnName() { return this.fnName; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("TimeStringValuePredicate [valueFormat="); builder.append(valueFormat); builder.append(", inputFormat="); builder.append(inputFormat); builder.append(", value="); builder.append(value); builder.append(", fnName="); builder.append(fnName); builder.append(", inputTimeFormatter="); builder.append(inputTimeFormatter); builder.append(", timePredicate="); builder.append(timePredicate); builder.append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((fnName == null) ? 0 : fnName.hashCode()); result = prime * result + ((inputFormat == null) ? 0 : inputFormat.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); result = prime * result + ((valueFormat == null) ? 0 : valueFormat.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TimeStringValuePredicate other = (TimeStringValuePredicate) obj; if (fnName == null) { if (other.fnName != null) { return false; } } else if (!fnName.equals(other.fnName)) { return false; } if (inputFormat == null) { if (other.inputFormat != null) { return false; } } else if (!inputFormat.equals(other.inputFormat)) { return false; } if (value == null) { if (other.value != null) { return false; } } else if (!value.equals(other.value)) { return false; } if (valueFormat == null) { if (other.valueFormat != null) { return false; } } else if (!valueFormat.equals(other.valueFormat)) { return false; } return true; } }
1,498
0
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing
Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/MessageFilterCompiler.java
package com.netflix.suro.routing.filter; import com.netflix.suro.routing.filter.lang.InvalidFilterException; import com.netflix.suro.routing.filter.lang.MessageFilterParser; import com.netflix.suro.routing.filter.lang.MessageFilterParsingException; import com.netflix.suro.routing.filter.lang.MessageFilterTranslatable; import org.antlr.runtime.RecognitionException; /** * A compiler to compile the message filter string to an {@link MessageFilter} for consumption * */ public class MessageFilterCompiler { /** * Compiles a filter expressed in infix notation to an {@link MessageFilter} instance. * * @param filter Filter to compile. * * @return {@link MessageFilter} instance compiled from the passed filter. * * @throws InvalidFilterException If the input filter is invalid. */ public static MessageFilter compile(String filter) throws InvalidFilterException { MessageFilterParser parser = MessageFilterParser.createParser(filter); MessageFilterTranslatable t = parseToTranslatable(parser); MessageFilter translate = t.translate(); if (BaseMessageFilter.class.isAssignableFrom(translate.getClass())) { ((BaseMessageFilter) translate).setOriginalDslString(filter); } return translate; } private static MessageFilterTranslatable parseToTranslatable(MessageFilterParser parser) { try { MessageFilterParser.filter_return result = parser.filter(); return (MessageFilterTranslatable) result.getTree(); } catch (RecognitionException e) { throw new MessageFilterParsingException(e.toString(), e); } } }
1,499