id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
25,300
alibaba/jstorm
jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/FileLock.java
FileLock.tryLock
public static FileLock tryLock(FileSystem fs, Path fileToLock, Path lockDirPath, String spoutId) throws IOException { Path lockFile = new Path(lockDirPath, fileToLock.getName()); try { FSDataOutputStream ostream = HdfsUtils.tryCreateFile(fs, lockFile); if (ostream != null) { LOG.debug("Acquired lock on file {}. LockFile= {}, Spout = {}", fileToLock, lockFile, spoutId); return new FileLock(fs, lockFile, ostream, spoutId); } else { LOG.debug("Cannot lock file {} as its already locked. Spout = {}", fileToLock, spoutId); return null; } } catch (IOException e) { LOG.error("Error when acquiring lock on file " + fileToLock + " Spout = " + spoutId, e); throw e; } }
java
public static FileLock tryLock(FileSystem fs, Path fileToLock, Path lockDirPath, String spoutId) throws IOException { Path lockFile = new Path(lockDirPath, fileToLock.getName()); try { FSDataOutputStream ostream = HdfsUtils.tryCreateFile(fs, lockFile); if (ostream != null) { LOG.debug("Acquired lock on file {}. LockFile= {}, Spout = {}", fileToLock, lockFile, spoutId); return new FileLock(fs, lockFile, ostream, spoutId); } else { LOG.debug("Cannot lock file {} as its already locked. Spout = {}", fileToLock, spoutId); return null; } } catch (IOException e) { LOG.error("Error when acquiring lock on file " + fileToLock + " Spout = " + spoutId, e); throw e; } }
[ "public", "static", "FileLock", "tryLock", "(", "FileSystem", "fs", ",", "Path", "fileToLock", ",", "Path", "lockDirPath", ",", "String", "spoutId", ")", "throws", "IOException", "{", "Path", "lockFile", "=", "new", "Path", "(", "lockDirPath", ",", "fileToLock", ".", "getName", "(", ")", ")", ";", "try", "{", "FSDataOutputStream", "ostream", "=", "HdfsUtils", ".", "tryCreateFile", "(", "fs", ",", "lockFile", ")", ";", "if", "(", "ostream", "!=", "null", ")", "{", "LOG", ".", "debug", "(", "\"Acquired lock on file {}. LockFile= {}, Spout = {}\"", ",", "fileToLock", ",", "lockFile", ",", "spoutId", ")", ";", "return", "new", "FileLock", "(", "fs", ",", "lockFile", ",", "ostream", ",", "spoutId", ")", ";", "}", "else", "{", "LOG", ".", "debug", "(", "\"Cannot lock file {} as its already locked. Spout = {}\"", ",", "fileToLock", ",", "spoutId", ")", ";", "return", "null", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "error", "(", "\"Error when acquiring lock on file \"", "+", "fileToLock", "+", "\" Spout = \"", "+", "spoutId", ",", "e", ")", ";", "throw", "e", ";", "}", "}" ]
returns lock on file or null if file is already locked. throws if unexpected problem
[ "returns", "lock", "on", "file", "or", "null", "if", "file", "is", "already", "locked", ".", "throws", "if", "unexpected", "problem" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/FileLock.java#L113-L130
25,301
alibaba/jstorm
jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/FileLock.java
FileLock.getLastEntry
public static LogEntry getLastEntry(FileSystem fs, Path lockFile) throws IOException { FSDataInputStream in = fs.open(lockFile); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String lastLine = null; for(String line = reader.readLine(); line!=null; line = reader.readLine() ) { lastLine=line; } return LogEntry.deserialize(lastLine); }
java
public static LogEntry getLastEntry(FileSystem fs, Path lockFile) throws IOException { FSDataInputStream in = fs.open(lockFile); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String lastLine = null; for(String line = reader.readLine(); line!=null; line = reader.readLine() ) { lastLine=line; } return LogEntry.deserialize(lastLine); }
[ "public", "static", "LogEntry", "getLastEntry", "(", "FileSystem", "fs", ",", "Path", "lockFile", ")", "throws", "IOException", "{", "FSDataInputStream", "in", "=", "fs", ".", "open", "(", "lockFile", ")", ";", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "in", ")", ")", ";", "String", "lastLine", "=", "null", ";", "for", "(", "String", "line", "=", "reader", ".", "readLine", "(", ")", ";", "line", "!=", "null", ";", "line", "=", "reader", ".", "readLine", "(", ")", ")", "{", "lastLine", "=", "line", ";", "}", "return", "LogEntry", ".", "deserialize", "(", "lastLine", ")", ";", "}" ]
returns the last log entry @param fs @param lockFile @return @throws IOException
[ "returns", "the", "last", "log", "entry" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/FileLock.java#L171-L180
25,302
alibaba/jstorm
jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/FileLock.java
FileLock.takeOwnership
public static FileLock takeOwnership(FileSystem fs, Path lockFile, LogEntry lastEntry, String spoutId) throws IOException { try { if(fs instanceof DistributedFileSystem ) { if( !((DistributedFileSystem) fs).recoverLease(lockFile) ) { LOG.warn("Unable to recover lease on lock file {} right now. Cannot transfer ownership. Will need to try later. Spout = {}", lockFile, spoutId); return null; } } return new FileLock(fs, lockFile, spoutId, lastEntry); } catch (IOException e) { if (e instanceof RemoteException && ((RemoteException) e).unwrapRemoteException() instanceof AlreadyBeingCreatedException) { LOG.warn("Lock file " + lockFile + "is currently open. Cannot transfer ownership now. Will need to try later. Spout= " + spoutId, e); return null; } else { // unexpected error LOG.warn("Cannot transfer ownership now for lock file " + lockFile + ". Will need to try later. Spout =" + spoutId, e); throw e; } } }
java
public static FileLock takeOwnership(FileSystem fs, Path lockFile, LogEntry lastEntry, String spoutId) throws IOException { try { if(fs instanceof DistributedFileSystem ) { if( !((DistributedFileSystem) fs).recoverLease(lockFile) ) { LOG.warn("Unable to recover lease on lock file {} right now. Cannot transfer ownership. Will need to try later. Spout = {}", lockFile, spoutId); return null; } } return new FileLock(fs, lockFile, spoutId, lastEntry); } catch (IOException e) { if (e instanceof RemoteException && ((RemoteException) e).unwrapRemoteException() instanceof AlreadyBeingCreatedException) { LOG.warn("Lock file " + lockFile + "is currently open. Cannot transfer ownership now. Will need to try later. Spout= " + spoutId, e); return null; } else { // unexpected error LOG.warn("Cannot transfer ownership now for lock file " + lockFile + ". Will need to try later. Spout =" + spoutId, e); throw e; } } }
[ "public", "static", "FileLock", "takeOwnership", "(", "FileSystem", "fs", ",", "Path", "lockFile", ",", "LogEntry", "lastEntry", ",", "String", "spoutId", ")", "throws", "IOException", "{", "try", "{", "if", "(", "fs", "instanceof", "DistributedFileSystem", ")", "{", "if", "(", "!", "(", "(", "DistributedFileSystem", ")", "fs", ")", ".", "recoverLease", "(", "lockFile", ")", ")", "{", "LOG", ".", "warn", "(", "\"Unable to recover lease on lock file {} right now. Cannot transfer ownership. Will need to try later. Spout = {}\"", ",", "lockFile", ",", "spoutId", ")", ";", "return", "null", ";", "}", "}", "return", "new", "FileLock", "(", "fs", ",", "lockFile", ",", "spoutId", ",", "lastEntry", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "if", "(", "e", "instanceof", "RemoteException", "&&", "(", "(", "RemoteException", ")", "e", ")", ".", "unwrapRemoteException", "(", ")", "instanceof", "AlreadyBeingCreatedException", ")", "{", "LOG", ".", "warn", "(", "\"Lock file \"", "+", "lockFile", "+", "\"is currently open. Cannot transfer ownership now. Will need to try later. Spout= \"", "+", "spoutId", ",", "e", ")", ";", "return", "null", ";", "}", "else", "{", "// unexpected error", "LOG", ".", "warn", "(", "\"Cannot transfer ownership now for lock file \"", "+", "lockFile", "+", "\". Will need to try later. Spout =\"", "+", "spoutId", ",", "e", ")", ";", "throw", "e", ";", "}", "}", "}" ]
Takes ownership of the lock file if possible. @param lockFile @param lastEntry last entry in the lock file. this param is an optimization. we dont scan the lock file again to find its last entry here since its already been done once by the logic used to check if the lock file is stale. so this value comes from that earlier scan. @param spoutId spout id @throws IOException if unable to acquire @return null if lock File is not recoverable
[ "Takes", "ownership", "of", "the", "lock", "file", "if", "possible", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/FileLock.java#L193-L213
25,303
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/worker/JStormDebugger.java
JStormDebugger.sample
private static boolean sample(Long rootId) { if (Double.compare(sampleRate, 1.0d) >= 0) return true; int mod = (int) (Math.abs(rootId) % PRECISION); int threshold = (int) (sampleRate * PRECISION); return mod < threshold; }
java
private static boolean sample(Long rootId) { if (Double.compare(sampleRate, 1.0d) >= 0) return true; int mod = (int) (Math.abs(rootId) % PRECISION); int threshold = (int) (sampleRate * PRECISION); return mod < threshold; }
[ "private", "static", "boolean", "sample", "(", "Long", "rootId", ")", "{", "if", "(", "Double", ".", "compare", "(", "sampleRate", ",", "1.0d", ")", ">=", "0", ")", "return", "true", ";", "int", "mod", "=", "(", "int", ")", "(", "Math", ".", "abs", "(", "rootId", ")", "%", "PRECISION", ")", ";", "int", "threshold", "=", "(", "int", ")", "(", "sampleRate", "*", "PRECISION", ")", ";", "return", "mod", "<", "threshold", ";", "}" ]
the tuple debug logs only output `rate`% the tuples with same rootId, should be logged or not logged together.
[ "the", "tuple", "debug", "logs", "only", "output", "rate", "%", "the", "tuples", "with", "same", "rootId", "should", "be", "logged", "or", "not", "logged", "together", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/worker/JStormDebugger.java#L97-L103
25,304
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/worker/JStormDebugger.java
JStormDebugger.sample
private static boolean sample(Set<Long> rootIds) { if (Double.compare(sampleRate, 1.0d) >= 0) return true; int threshold = (int) (sampleRate * PRECISION); for (Long id : rootIds) { int mod = (int) (Math.abs(id) % PRECISION); if (mod < threshold) { return true; } } return false; }
java
private static boolean sample(Set<Long> rootIds) { if (Double.compare(sampleRate, 1.0d) >= 0) return true; int threshold = (int) (sampleRate * PRECISION); for (Long id : rootIds) { int mod = (int) (Math.abs(id) % PRECISION); if (mod < threshold) { return true; } } return false; }
[ "private", "static", "boolean", "sample", "(", "Set", "<", "Long", ">", "rootIds", ")", "{", "if", "(", "Double", ".", "compare", "(", "sampleRate", ",", "1.0d", ")", ">=", "0", ")", "return", "true", ";", "int", "threshold", "=", "(", "int", ")", "(", "sampleRate", "*", "PRECISION", ")", ";", "for", "(", "Long", "id", ":", "rootIds", ")", "{", "int", "mod", "=", "(", "int", ")", "(", "Math", ".", "abs", "(", "id", ")", "%", "PRECISION", ")", ";", "if", "(", "mod", "<", "threshold", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
one of the rootIds has been chosen , the logs should be output
[ "one", "of", "the", "rootIds", "has", "been", "chosen", "the", "logs", "should", "be", "output" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/worker/JStormDebugger.java#L108-L119
25,305
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/worker/JStormDebugger.java
JStormDebugger.sample
private static boolean sample(Collection<Tuple> anchors) { if (Double.compare(sampleRate, 1.0d) >= 0) return true; for (Tuple t : anchors) { if (sample(t.getMessageId().getAnchors())) { return true; } } return false; }
java
private static boolean sample(Collection<Tuple> anchors) { if (Double.compare(sampleRate, 1.0d) >= 0) return true; for (Tuple t : anchors) { if (sample(t.getMessageId().getAnchors())) { return true; } } return false; }
[ "private", "static", "boolean", "sample", "(", "Collection", "<", "Tuple", ">", "anchors", ")", "{", "if", "(", "Double", ".", "compare", "(", "sampleRate", ",", "1.0d", ")", ">=", "0", ")", "return", "true", ";", "for", "(", "Tuple", "t", ":", "anchors", ")", "{", "if", "(", "sample", "(", "t", ".", "getMessageId", "(", ")", ".", "getAnchors", "(", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
one of the tuples has been chosen, the logs should be output
[ "one", "of", "the", "tuples", "has", "been", "chosen", "the", "logs", "should", "be", "output" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/worker/JStormDebugger.java#L124-L133
25,306
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/common/metric/AsmCounter.java
AsmCounter.doFlush
protected void doFlush() { long v; synchronized (unFlushed) { v = unFlushed.getCount(); } for (Counter counter : counterMap.values()) { counter.inc(v); } if (MetricUtils.metricAccurateCal) { for (AsmMetric assocMetric : assocMetrics) { assocMetric.updateDirectly(v); } } this.unFlushed.dec(v); }
java
protected void doFlush() { long v; synchronized (unFlushed) { v = unFlushed.getCount(); } for (Counter counter : counterMap.values()) { counter.inc(v); } if (MetricUtils.metricAccurateCal) { for (AsmMetric assocMetric : assocMetrics) { assocMetric.updateDirectly(v); } } this.unFlushed.dec(v); }
[ "protected", "void", "doFlush", "(", ")", "{", "long", "v", ";", "synchronized", "(", "unFlushed", ")", "{", "v", "=", "unFlushed", ".", "getCount", "(", ")", ";", "}", "for", "(", "Counter", "counter", ":", "counterMap", ".", "values", "(", ")", ")", "{", "counter", ".", "inc", "(", "v", ")", ";", "}", "if", "(", "MetricUtils", ".", "metricAccurateCal", ")", "{", "for", "(", "AsmMetric", "assocMetric", ":", "assocMetrics", ")", "{", "assocMetric", ".", "updateDirectly", "(", "v", ")", ";", "}", "}", "this", ".", "unFlushed", ".", "dec", "(", "v", ")", ";", "}" ]
flush temp counter data to all windows & assoc metrics.
[ "flush", "temp", "counter", "data", "to", "all", "windows", "&", "assoc", "metrics", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/common/metric/AsmCounter.java#L73-L87
25,307
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/task/group/MkGrouper.java
MkGrouper.grouper
public List<Integer> grouper(List<Object> values) { if (GrouperType.global.equals(groupType)) { // send to task which taskId is 0 return JStormUtils.mk_list(outTasks.get(0)); } else if (GrouperType.fields.equals(groupType)) { // field grouping return fieldsGrouper.grouper(values); } else if (GrouperType.all.equals(groupType)) { // send to every task return outTasks; } else if (GrouperType.shuffle.equals(groupType)) { // random, but the random is different from none return shuffer.grouper(values); } else if (GrouperType.none.equals(groupType)) { int rnd = Math.abs(random.nextInt() % outTasks.size()); return JStormUtils.mk_list(outTasks.get(rnd)); } else if (GrouperType.custom_obj.equals(groupType)) { return customGrouper.grouper(values); } else if (GrouperType.custom_serialized.equals(groupType)) { return customGrouper.grouper(values); } else { LOG.warn("Unsupported group type"); } return new ArrayList<>(); }
java
public List<Integer> grouper(List<Object> values) { if (GrouperType.global.equals(groupType)) { // send to task which taskId is 0 return JStormUtils.mk_list(outTasks.get(0)); } else if (GrouperType.fields.equals(groupType)) { // field grouping return fieldsGrouper.grouper(values); } else if (GrouperType.all.equals(groupType)) { // send to every task return outTasks; } else if (GrouperType.shuffle.equals(groupType)) { // random, but the random is different from none return shuffer.grouper(values); } else if (GrouperType.none.equals(groupType)) { int rnd = Math.abs(random.nextInt() % outTasks.size()); return JStormUtils.mk_list(outTasks.get(rnd)); } else if (GrouperType.custom_obj.equals(groupType)) { return customGrouper.grouper(values); } else if (GrouperType.custom_serialized.equals(groupType)) { return customGrouper.grouper(values); } else { LOG.warn("Unsupported group type"); } return new ArrayList<>(); }
[ "public", "List", "<", "Integer", ">", "grouper", "(", "List", "<", "Object", ">", "values", ")", "{", "if", "(", "GrouperType", ".", "global", ".", "equals", "(", "groupType", ")", ")", "{", "// send to task which taskId is 0", "return", "JStormUtils", ".", "mk_list", "(", "outTasks", ".", "get", "(", "0", ")", ")", ";", "}", "else", "if", "(", "GrouperType", ".", "fields", ".", "equals", "(", "groupType", ")", ")", "{", "// field grouping", "return", "fieldsGrouper", ".", "grouper", "(", "values", ")", ";", "}", "else", "if", "(", "GrouperType", ".", "all", ".", "equals", "(", "groupType", ")", ")", "{", "// send to every task", "return", "outTasks", ";", "}", "else", "if", "(", "GrouperType", ".", "shuffle", ".", "equals", "(", "groupType", ")", ")", "{", "// random, but the random is different from none", "return", "shuffer", ".", "grouper", "(", "values", ")", ";", "}", "else", "if", "(", "GrouperType", ".", "none", ".", "equals", "(", "groupType", ")", ")", "{", "int", "rnd", "=", "Math", ".", "abs", "(", "random", ".", "nextInt", "(", ")", "%", "outTasks", ".", "size", "(", ")", ")", ";", "return", "JStormUtils", ".", "mk_list", "(", "outTasks", ".", "get", "(", "rnd", ")", ")", ";", "}", "else", "if", "(", "GrouperType", ".", "custom_obj", ".", "equals", "(", "groupType", ")", ")", "{", "return", "customGrouper", ".", "grouper", "(", "values", ")", ";", "}", "else", "if", "(", "GrouperType", ".", "custom_serialized", ".", "equals", "(", "groupType", ")", ")", "{", "return", "customGrouper", ".", "grouper", "(", "values", ")", ";", "}", "else", "{", "LOG", ".", "warn", "(", "\"Unsupported group type\"", ")", ";", "}", "return", "new", "ArrayList", "<>", "(", ")", ";", "}" ]
get which task should tuple be sent to
[ "get", "which", "task", "should", "tuple", "be", "sent", "to" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/task/group/MkGrouper.java#L160-L185
25,308
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/MyScpClient.java
MyScpClient.put
public void put(String localFile, String remoteTargetDirectory) throws IOException { put(new String[]{localFile}, remoteTargetDirectory, "0600"); }
java
public void put(String localFile, String remoteTargetDirectory) throws IOException { put(new String[]{localFile}, remoteTargetDirectory, "0600"); }
[ "public", "void", "put", "(", "String", "localFile", ",", "String", "remoteTargetDirectory", ")", "throws", "IOException", "{", "put", "(", "new", "String", "[", "]", "{", "localFile", "}", ",", "remoteTargetDirectory", ",", "\"0600\"", ")", ";", "}" ]
Copy a local file to a remote directory, uses mode 0600 when creating the file on the remote side. @param localFile Path and name of local file. @param remoteTargetDirectory Remote target directory. @throws IOException
[ "Copy", "a", "local", "file", "to", "a", "remote", "directory", "uses", "mode", "0600", "when", "creating", "the", "file", "on", "the", "remote", "side", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/MyScpClient.java#L303-L305
25,309
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/MyScpClient.java
MyScpClient.put
public void put(byte[] data, String remoteFileName, String remoteTargetDirectory) throws IOException { put(data, remoteFileName, remoteTargetDirectory, "0600"); }
java
public void put(byte[] data, String remoteFileName, String remoteTargetDirectory) throws IOException { put(data, remoteFileName, remoteTargetDirectory, "0600"); }
[ "public", "void", "put", "(", "byte", "[", "]", "data", ",", "String", "remoteFileName", ",", "String", "remoteTargetDirectory", ")", "throws", "IOException", "{", "put", "(", "data", ",", "remoteFileName", ",", "remoteTargetDirectory", ",", "\"0600\"", ")", ";", "}" ]
Create a remote file and copy the contents of the passed byte array into it. Uses mode 0600 for creating the remote file. @param data the data to be copied into the remote file. @param remoteFileName The name of the file which will be created in the remote target directory. @param remoteTargetDirectory Remote target directory. @throws IOException
[ "Create", "a", "remote", "file", "and", "copy", "the", "contents", "of", "the", "passed", "byte", "array", "into", "it", ".", "Uses", "mode", "0600", "for", "creating", "the", "remote", "file", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/MyScpClient.java#L343-L345
25,310
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/MyScpClient.java
MyScpClient.put
public void put(byte[] data, String remoteFileName, String remoteTargetDirectory, String mode) throws IOException { Session sess = null; if ((remoteFileName == null) || (remoteTargetDirectory == null) || (mode == null)) throw new IllegalArgumentException("Null argument."); if (mode.length() != 4) throw new IllegalArgumentException("Invalid mode."); for (int i = 0; i < mode.length(); i++) if (Character.isDigit(mode.charAt(i)) == false) throw new IllegalArgumentException("Invalid mode."); String cmd = "scp -t -d " + remoteTargetDirectory; try { sess = conn.openSession(); sess.execCommand(cmd); sendBytes(sess, data, remoteFileName, mode); sess.close(); } catch (IOException e) { if (sess != null) sess.close(); throw (IOException) new IOException("Error during SCP transfer.").initCause(e); } }
java
public void put(byte[] data, String remoteFileName, String remoteTargetDirectory, String mode) throws IOException { Session sess = null; if ((remoteFileName == null) || (remoteTargetDirectory == null) || (mode == null)) throw new IllegalArgumentException("Null argument."); if (mode.length() != 4) throw new IllegalArgumentException("Invalid mode."); for (int i = 0; i < mode.length(); i++) if (Character.isDigit(mode.charAt(i)) == false) throw new IllegalArgumentException("Invalid mode."); String cmd = "scp -t -d " + remoteTargetDirectory; try { sess = conn.openSession(); sess.execCommand(cmd); sendBytes(sess, data, remoteFileName, mode); sess.close(); } catch (IOException e) { if (sess != null) sess.close(); throw (IOException) new IOException("Error during SCP transfer.").initCause(e); } }
[ "public", "void", "put", "(", "byte", "[", "]", "data", ",", "String", "remoteFileName", ",", "String", "remoteTargetDirectory", ",", "String", "mode", ")", "throws", "IOException", "{", "Session", "sess", "=", "null", ";", "if", "(", "(", "remoteFileName", "==", "null", ")", "||", "(", "remoteTargetDirectory", "==", "null", ")", "||", "(", "mode", "==", "null", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Null argument.\"", ")", ";", "if", "(", "mode", ".", "length", "(", ")", "!=", "4", ")", "throw", "new", "IllegalArgumentException", "(", "\"Invalid mode.\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "mode", ".", "length", "(", ")", ";", "i", "++", ")", "if", "(", "Character", ".", "isDigit", "(", "mode", ".", "charAt", "(", "i", ")", ")", "==", "false", ")", "throw", "new", "IllegalArgumentException", "(", "\"Invalid mode.\"", ")", ";", "String", "cmd", "=", "\"scp -t -d \"", "+", "remoteTargetDirectory", ";", "try", "{", "sess", "=", "conn", ".", "openSession", "(", ")", ";", "sess", ".", "execCommand", "(", "cmd", ")", ";", "sendBytes", "(", "sess", ",", "data", ",", "remoteFileName", ",", "mode", ")", ";", "sess", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "if", "(", "sess", "!=", "null", ")", "sess", ".", "close", "(", ")", ";", "throw", "(", "IOException", ")", "new", "IOException", "(", "\"Error during SCP transfer.\"", ")", ".", "initCause", "(", "e", ")", ";", "}", "}" ]
Create a remote file and copy the contents of the passed byte array into it. The method use the specified mode when creating the file on the remote side. @param data the data to be copied into the remote file. @param remoteFileName The name of the file which will be created in the remote target directory. @param remoteTargetDirectory Remote target directory. @param mode a four digit string (e.g., 0644, see "man chmod", "man open") @throws IOException
[ "Create", "a", "remote", "file", "and", "copy", "the", "contents", "of", "the", "passed", "byte", "array", "into", "it", ".", "The", "method", "use", "the", "specified", "mode", "when", "creating", "the", "file", "on", "the", "remote", "side", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/MyScpClient.java#L357-L382
25,311
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/MyScpClient.java
MyScpClient.get
public void get(String remoteFile, String localTargetDirectory) throws IOException { get(new String[]{remoteFile}, localTargetDirectory); }
java
public void get(String remoteFile, String localTargetDirectory) throws IOException { get(new String[]{remoteFile}, localTargetDirectory); }
[ "public", "void", "get", "(", "String", "remoteFile", ",", "String", "localTargetDirectory", ")", "throws", "IOException", "{", "get", "(", "new", "String", "[", "]", "{", "remoteFile", "}", ",", "localTargetDirectory", ")", ";", "}" ]
Download a file from the remote server to a local directory. @param remoteFile Path and name of the remote file. @param localTargetDirectory Local directory to put the downloaded file. @throws IOException
[ "Download", "a", "file", "from", "the", "remote", "server", "to", "a", "local", "directory", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/MyScpClient.java#L435-L437
25,312
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/MyScpClient.java
MyScpClient.get
public void get(String remoteFiles[], String localTargetDirectory) throws IOException { Session sess = null; if ((remoteFiles == null) || (localTargetDirectory == null)) throw new IllegalArgumentException("Null argument."); if (remoteFiles.length == 0) return; // String cmd = "scp -f -r"; String cmd = "scp -f "; for (int i = 0; i < remoteFiles.length; i++) { if (remoteFiles[i] == null) throw new IllegalArgumentException("Cannot accept null filename."); cmd += (" " + remoteFiles[i]); } try { sess = conn.openSession(); sess.execCommand(cmd); receiveFiles(sess, remoteFiles, localTargetDirectory); sess.close(); } catch (IOException e) { if (sess != null) sess.close(); throw (IOException) new IOException("Error during SCP transfer.").initCause(e); } }
java
public void get(String remoteFiles[], String localTargetDirectory) throws IOException { Session sess = null; if ((remoteFiles == null) || (localTargetDirectory == null)) throw new IllegalArgumentException("Null argument."); if (remoteFiles.length == 0) return; // String cmd = "scp -f -r"; String cmd = "scp -f "; for (int i = 0; i < remoteFiles.length; i++) { if (remoteFiles[i] == null) throw new IllegalArgumentException("Cannot accept null filename."); cmd += (" " + remoteFiles[i]); } try { sess = conn.openSession(); sess.execCommand(cmd); receiveFiles(sess, remoteFiles, localTargetDirectory); sess.close(); } catch (IOException e) { if (sess != null) sess.close(); throw (IOException) new IOException("Error during SCP transfer.").initCause(e); } }
[ "public", "void", "get", "(", "String", "remoteFiles", "[", "]", ",", "String", "localTargetDirectory", ")", "throws", "IOException", "{", "Session", "sess", "=", "null", ";", "if", "(", "(", "remoteFiles", "==", "null", ")", "||", "(", "localTargetDirectory", "==", "null", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Null argument.\"", ")", ";", "if", "(", "remoteFiles", ".", "length", "==", "0", ")", "return", ";", "// String cmd = \"scp -f -r\";", "String", "cmd", "=", "\"scp -f \"", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "remoteFiles", ".", "length", ";", "i", "++", ")", "{", "if", "(", "remoteFiles", "[", "i", "]", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"Cannot accept null filename.\"", ")", ";", "cmd", "+=", "(", "\" \"", "+", "remoteFiles", "[", "i", "]", ")", ";", "}", "try", "{", "sess", "=", "conn", ".", "openSession", "(", ")", ";", "sess", ".", "execCommand", "(", "cmd", ")", ";", "receiveFiles", "(", "sess", ",", "remoteFiles", ",", "localTargetDirectory", ")", ";", "sess", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "if", "(", "sess", "!=", "null", ")", "sess", ".", "close", "(", ")", ";", "throw", "(", "IOException", ")", "new", "IOException", "(", "\"Error during SCP transfer.\"", ")", ".", "initCause", "(", "e", ")", ";", "}", "}" ]
Download a set of files from the remote server to a local directory. @param remoteFiles Paths and names of the remote files. @param localTargetDirectory Local directory to put the downloaded files. @throws IOException
[ "Download", "a", "set", "of", "files", "from", "the", "remote", "server", "to", "a", "local", "directory", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/MyScpClient.java#L446-L476
25,313
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/security/auth/authorizer/DRPCAuthorizerBase.java
DRPCAuthorizerBase.permit
@Override public boolean permit(ReqContext context, String operation, Map params) { if ("execute".equals(operation)) { return permitClientRequest(context, operation, params); } else if ("failRequest".equals(operation) || "fetchRequest".equals(operation) || "result".equals(operation)) { return permitInvocationRequest(context, operation, params); } // Deny unsupported operations. LOG.warn("Denying unsupported operation \"" + operation + "\" from " + context.remoteAddress()); return false; }
java
@Override public boolean permit(ReqContext context, String operation, Map params) { if ("execute".equals(operation)) { return permitClientRequest(context, operation, params); } else if ("failRequest".equals(operation) || "fetchRequest".equals(operation) || "result".equals(operation)) { return permitInvocationRequest(context, operation, params); } // Deny unsupported operations. LOG.warn("Denying unsupported operation \"" + operation + "\" from " + context.remoteAddress()); return false; }
[ "@", "Override", "public", "boolean", "permit", "(", "ReqContext", "context", ",", "String", "operation", ",", "Map", "params", ")", "{", "if", "(", "\"execute\"", ".", "equals", "(", "operation", ")", ")", "{", "return", "permitClientRequest", "(", "context", ",", "operation", ",", "params", ")", ";", "}", "else", "if", "(", "\"failRequest\"", ".", "equals", "(", "operation", ")", "||", "\"fetchRequest\"", ".", "equals", "(", "operation", ")", "||", "\"result\"", ".", "equals", "(", "operation", ")", ")", "{", "return", "permitInvocationRequest", "(", "context", ",", "operation", ",", "params", ")", ";", "}", "// Deny unsupported operations.", "LOG", ".", "warn", "(", "\"Denying unsupported operation \\\"\"", "+", "operation", "+", "\"\\\" from \"", "+", "context", ".", "remoteAddress", "(", ")", ")", ";", "return", "false", ";", "}" ]
Authorizes request from to the DRPC server. @param context the client request context @param operation the operation requested by the DRPC server @param params a Map with any key-value entries of use to the authorization implementation
[ "Authorizes", "request", "from", "to", "the", "DRPC", "server", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/security/auth/authorizer/DRPCAuthorizerBase.java#L50-L60
25,314
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/registry/YarnRegistryViewForProviders.java
YarnRegistryViewForProviders.getAbsoluteSelfRegistrationPath
public String getAbsoluteSelfRegistrationPath() { if (selfRegistrationPath == null) { return null; } String root = registryOperations.getConfig().getTrimmed( RegistryConstants.KEY_REGISTRY_ZK_ROOT, RegistryConstants.DEFAULT_ZK_REGISTRY_ROOT); return RegistryPathUtils.join(root, selfRegistrationPath); }
java
public String getAbsoluteSelfRegistrationPath() { if (selfRegistrationPath == null) { return null; } String root = registryOperations.getConfig().getTrimmed( RegistryConstants.KEY_REGISTRY_ZK_ROOT, RegistryConstants.DEFAULT_ZK_REGISTRY_ROOT); return RegistryPathUtils.join(root, selfRegistrationPath); }
[ "public", "String", "getAbsoluteSelfRegistrationPath", "(", ")", "{", "if", "(", "selfRegistrationPath", "==", "null", ")", "{", "return", "null", ";", "}", "String", "root", "=", "registryOperations", ".", "getConfig", "(", ")", ".", "getTrimmed", "(", "RegistryConstants", ".", "KEY_REGISTRY_ZK_ROOT", ",", "RegistryConstants", ".", "DEFAULT_ZK_REGISTRY_ROOT", ")", ";", "return", "RegistryPathUtils", ".", "join", "(", "root", ",", "selfRegistrationPath", ")", ";", "}" ]
Get the absolute path to where the service has registered itself. This includes the base registry path Null until the service is registered @return the service registration path.
[ "Get", "the", "absolute", "path", "to", "where", "the", "service", "has", "registered", "itself", ".", "This", "includes", "the", "base", "registry", "path", "Null", "until", "the", "service", "is", "registered" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/registry/YarnRegistryViewForProviders.java#L126-L134
25,315
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/registry/YarnRegistryViewForProviders.java
YarnRegistryViewForProviders.putComponent
public void putComponent(String serviceClass, String serviceName, String componentName, ServiceRecord record) throws IOException { String path = RegistryUtils.componentPath( user, serviceClass, serviceName, componentName); registryOperations.mknode(RegistryPathUtils.parentOf(path), true); registryOperations.bind(path, record, BindFlags.OVERWRITE); }
java
public void putComponent(String serviceClass, String serviceName, String componentName, ServiceRecord record) throws IOException { String path = RegistryUtils.componentPath( user, serviceClass, serviceName, componentName); registryOperations.mknode(RegistryPathUtils.parentOf(path), true); registryOperations.bind(path, record, BindFlags.OVERWRITE); }
[ "public", "void", "putComponent", "(", "String", "serviceClass", ",", "String", "serviceName", ",", "String", "componentName", ",", "ServiceRecord", "record", ")", "throws", "IOException", "{", "String", "path", "=", "RegistryUtils", ".", "componentPath", "(", "user", ",", "serviceClass", ",", "serviceName", ",", "componentName", ")", ";", "registryOperations", ".", "mknode", "(", "RegistryPathUtils", ".", "parentOf", "(", "path", ")", ",", "true", ")", ";", "registryOperations", ".", "bind", "(", "path", ",", "record", ",", "BindFlags", ".", "OVERWRITE", ")", ";", "}" ]
Add a component @param serviceClass service class to use under ~user @param componentName component name @param record record to put @throws IOException
[ "Add", "a", "component" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/registry/YarnRegistryViewForProviders.java#L157-L165
25,316
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/registry/YarnRegistryViewForProviders.java
YarnRegistryViewForProviders.putService
public String putService(String username, String serviceClass, String serviceName, ServiceRecord record, boolean deleteTreeFirst) throws IOException { String path = RegistryUtils.servicePath( username, serviceClass, serviceName); if (deleteTreeFirst) { registryOperations.delete(path, true); } registryOperations.mknode(RegistryPathUtils.parentOf(path), true); registryOperations.bind(path, record, BindFlags.OVERWRITE); return path; }
java
public String putService(String username, String serviceClass, String serviceName, ServiceRecord record, boolean deleteTreeFirst) throws IOException { String path = RegistryUtils.servicePath( username, serviceClass, serviceName); if (deleteTreeFirst) { registryOperations.delete(path, true); } registryOperations.mknode(RegistryPathUtils.parentOf(path), true); registryOperations.bind(path, record, BindFlags.OVERWRITE); return path; }
[ "public", "String", "putService", "(", "String", "username", ",", "String", "serviceClass", ",", "String", "serviceName", ",", "ServiceRecord", "record", ",", "boolean", "deleteTreeFirst", ")", "throws", "IOException", "{", "String", "path", "=", "RegistryUtils", ".", "servicePath", "(", "username", ",", "serviceClass", ",", "serviceName", ")", ";", "if", "(", "deleteTreeFirst", ")", "{", "registryOperations", ".", "delete", "(", "path", ",", "true", ")", ";", "}", "registryOperations", ".", "mknode", "(", "RegistryPathUtils", ".", "parentOf", "(", "path", ")", ",", "true", ")", ";", "registryOperations", ".", "bind", "(", "path", ",", "record", ",", "BindFlags", ".", "OVERWRITE", ")", ";", "return", "path", ";", "}" ]
Add a service under a path, optionally purging any history @param username user @param serviceClass service class to use under ~user @param serviceName name of the service @param record service record @param deleteTreeFirst perform recursive delete of the path first. @return the path the service was created at @throws IOException
[ "Add", "a", "service", "under", "a", "path", "optionally", "purging", "any", "history" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/registry/YarnRegistryViewForProviders.java#L177-L190
25,317
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/registry/YarnRegistryViewForProviders.java
YarnRegistryViewForProviders.deleteComponent
public void deleteComponent(String componentName) throws IOException { String path = RegistryUtils.componentPath( user, jstormServiceClass, instanceName, componentName); registryOperations.delete(path, false); }
java
public void deleteComponent(String componentName) throws IOException { String path = RegistryUtils.componentPath( user, jstormServiceClass, instanceName, componentName); registryOperations.delete(path, false); }
[ "public", "void", "deleteComponent", "(", "String", "componentName", ")", "throws", "IOException", "{", "String", "path", "=", "RegistryUtils", ".", "componentPath", "(", "user", ",", "jstormServiceClass", ",", "instanceName", ",", "componentName", ")", ";", "registryOperations", ".", "delete", "(", "path", ",", "false", ")", ";", "}" ]
Delete a component @param componentName component name @throws IOException
[ "Delete", "a", "component" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/registry/YarnRegistryViewForProviders.java#L240-L245
25,318
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/registry/YarnRegistryViewForProviders.java
YarnRegistryViewForProviders.deleteChildren
public void deleteChildren(String path, boolean recursive) throws IOException { List<String> childNames = null; try { childNames = registryOperations.list(path); } catch (PathNotFoundException e) { return; } for (String childName : childNames) { String child = join(path, childName); registryOperations.delete(child, recursive); } }
java
public void deleteChildren(String path, boolean recursive) throws IOException { List<String> childNames = null; try { childNames = registryOperations.list(path); } catch (PathNotFoundException e) { return; } for (String childName : childNames) { String child = join(path, childName); registryOperations.delete(child, recursive); } }
[ "public", "void", "deleteChildren", "(", "String", "path", ",", "boolean", "recursive", ")", "throws", "IOException", "{", "List", "<", "String", ">", "childNames", "=", "null", ";", "try", "{", "childNames", "=", "registryOperations", ".", "list", "(", "path", ")", ";", "}", "catch", "(", "PathNotFoundException", "e", ")", "{", "return", ";", "}", "for", "(", "String", "childName", ":", "childNames", ")", "{", "String", "child", "=", "join", "(", "path", ",", "childName", ")", ";", "registryOperations", ".", "delete", "(", "child", ",", "recursive", ")", ";", "}", "}" ]
Delete the children of a path -but not the path itself. It is not an error if the path does not exist @param path path to delete @param recursive flag to request recursive deletes @throws IOException IO problems
[ "Delete", "the", "children", "of", "a", "path", "-", "but", "not", "the", "path", "itself", ".", "It", "is", "not", "an", "error", "if", "the", "path", "does", "not", "exist" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/registry/YarnRegistryViewForProviders.java#L254-L265
25,319
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java
BaseWindowedBolt.countWindow
public BaseWindowedBolt<T> countWindow(long size) { ensurePositiveTime(size); setSizeAndSlide(size, DEFAULT_SLIDE); this.windowAssigner = TumblingCountWindows.create(size); return this; }
java
public BaseWindowedBolt<T> countWindow(long size) { ensurePositiveTime(size); setSizeAndSlide(size, DEFAULT_SLIDE); this.windowAssigner = TumblingCountWindows.create(size); return this; }
[ "public", "BaseWindowedBolt", "<", "T", ">", "countWindow", "(", "long", "size", ")", "{", "ensurePositiveTime", "(", "size", ")", ";", "setSizeAndSlide", "(", "size", ",", "DEFAULT_SLIDE", ")", ";", "this", ".", "windowAssigner", "=", "TumblingCountWindows", ".", "create", "(", "size", ")", ";", "return", "this", ";", "}" ]
define a tumbling count window @param size count size
[ "define", "a", "tumbling", "count", "window" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java#L51-L57
25,320
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java
BaseWindowedBolt.countWindow
public BaseWindowedBolt<T> countWindow(long size, long slide) { ensurePositiveTime(size, slide); ensureSizeGreaterThanSlide(size, slide); setSizeAndSlide(size, slide); this.windowAssigner = SlidingCountWindows.create(size, slide); return this; }
java
public BaseWindowedBolt<T> countWindow(long size, long slide) { ensurePositiveTime(size, slide); ensureSizeGreaterThanSlide(size, slide); setSizeAndSlide(size, slide); this.windowAssigner = SlidingCountWindows.create(size, slide); return this; }
[ "public", "BaseWindowedBolt", "<", "T", ">", "countWindow", "(", "long", "size", ",", "long", "slide", ")", "{", "ensurePositiveTime", "(", "size", ",", "slide", ")", ";", "ensureSizeGreaterThanSlide", "(", "size", ",", "slide", ")", ";", "setSizeAndSlide", "(", "size", ",", "slide", ")", ";", "this", ".", "windowAssigner", "=", "SlidingCountWindows", ".", "create", "(", "size", ",", "slide", ")", ";", "return", "this", ";", "}" ]
define a sliding count window @param size count size @param slide slide size
[ "define", "a", "sliding", "count", "window" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java#L65-L72
25,321
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java
BaseWindowedBolt.timeWindow
public BaseWindowedBolt<T> timeWindow(Time size) { long s = size.toMilliseconds(); ensurePositiveTime(s); setSizeAndSlide(s, DEFAULT_SLIDE); this.windowAssigner = TumblingProcessingTimeWindows.of(s); return this; }
java
public BaseWindowedBolt<T> timeWindow(Time size) { long s = size.toMilliseconds(); ensurePositiveTime(s); setSizeAndSlide(s, DEFAULT_SLIDE); this.windowAssigner = TumblingProcessingTimeWindows.of(s); return this; }
[ "public", "BaseWindowedBolt", "<", "T", ">", "timeWindow", "(", "Time", "size", ")", "{", "long", "s", "=", "size", ".", "toMilliseconds", "(", ")", ";", "ensurePositiveTime", "(", "s", ")", ";", "setSizeAndSlide", "(", "s", ",", "DEFAULT_SLIDE", ")", ";", "this", ".", "windowAssigner", "=", "TumblingProcessingTimeWindows", ".", "of", "(", "s", ")", ";", "return", "this", ";", "}" ]
define a tumbling processing time window @param size window size
[ "define", "a", "tumbling", "processing", "time", "window" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java#L79-L86
25,322
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java
BaseWindowedBolt.withStateSize
public BaseWindowedBolt<T> withStateSize(Time size) { long s = size.toMilliseconds(); ensurePositiveTime(s); ensureStateSizeGreaterThanWindowSize(this.size, s); this.stateSize = s; if (WindowAssigner.isEventTime(this.windowAssigner)) { this.stateWindowAssigner = TumblingEventTimeWindows.of(s); } else if (WindowAssigner.isProcessingTime(this.windowAssigner)) { this.stateWindowAssigner = TumblingProcessingTimeWindows.of(s); } else if (WindowAssigner.isIngestionTime(this.windowAssigner)) { this.stateWindowAssigner = TumblingIngestionTimeWindows.of(s); } return this; }
java
public BaseWindowedBolt<T> withStateSize(Time size) { long s = size.toMilliseconds(); ensurePositiveTime(s); ensureStateSizeGreaterThanWindowSize(this.size, s); this.stateSize = s; if (WindowAssigner.isEventTime(this.windowAssigner)) { this.stateWindowAssigner = TumblingEventTimeWindows.of(s); } else if (WindowAssigner.isProcessingTime(this.windowAssigner)) { this.stateWindowAssigner = TumblingProcessingTimeWindows.of(s); } else if (WindowAssigner.isIngestionTime(this.windowAssigner)) { this.stateWindowAssigner = TumblingIngestionTimeWindows.of(s); } return this; }
[ "public", "BaseWindowedBolt", "<", "T", ">", "withStateSize", "(", "Time", "size", ")", "{", "long", "s", "=", "size", ".", "toMilliseconds", "(", ")", ";", "ensurePositiveTime", "(", "s", ")", ";", "ensureStateSizeGreaterThanWindowSize", "(", "this", ".", "size", ",", "s", ")", ";", "this", ".", "stateSize", "=", "s", ";", "if", "(", "WindowAssigner", ".", "isEventTime", "(", "this", ".", "windowAssigner", ")", ")", "{", "this", ".", "stateWindowAssigner", "=", "TumblingEventTimeWindows", ".", "of", "(", "s", ")", ";", "}", "else", "if", "(", "WindowAssigner", ".", "isProcessingTime", "(", "this", ".", "windowAssigner", ")", ")", "{", "this", ".", "stateWindowAssigner", "=", "TumblingProcessingTimeWindows", ".", "of", "(", "s", ")", ";", "}", "else", "if", "(", "WindowAssigner", ".", "isIngestionTime", "(", "this", ".", "windowAssigner", ")", ")", "{", "this", ".", "stateWindowAssigner", "=", "TumblingIngestionTimeWindows", ".", "of", "(", "s", ")", ";", "}", "return", "this", ";", "}" ]
add state window to tumbling windows. If set, jstorm will use state window size to accumulate user states instead of deleting the states right after purging a window. e.g., if a user defines a window of 10 sec as well as a state window of 60 sec, then the window will be purged every 10 sec, while the state of the window will be kept (and accumulated) until 60 sec is due. @param size state window size
[ "add", "state", "window", "to", "tumbling", "windows", ".", "If", "set", "jstorm", "will", "use", "state", "window", "size", "to", "accumulate", "user", "states", "instead", "of", "deleting", "the", "states", "right", "after", "purging", "a", "window", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java#L100-L115
25,323
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java
BaseWindowedBolt.timeWindow
public BaseWindowedBolt<T> timeWindow(Time size, Time slide) { long s = size.toMilliseconds(); long l = slide.toMilliseconds(); ensurePositiveTime(s, l); ensureSizeGreaterThanSlide(s, l); setSizeAndSlide(s, l); this.windowAssigner = SlidingProcessingTimeWindows.of(s, l); return this; }
java
public BaseWindowedBolt<T> timeWindow(Time size, Time slide) { long s = size.toMilliseconds(); long l = slide.toMilliseconds(); ensurePositiveTime(s, l); ensureSizeGreaterThanSlide(s, l); setSizeAndSlide(s, l); this.windowAssigner = SlidingProcessingTimeWindows.of(s, l); return this; }
[ "public", "BaseWindowedBolt", "<", "T", ">", "timeWindow", "(", "Time", "size", ",", "Time", "slide", ")", "{", "long", "s", "=", "size", ".", "toMilliseconds", "(", ")", ";", "long", "l", "=", "slide", ".", "toMilliseconds", "(", ")", ";", "ensurePositiveTime", "(", "s", ",", "l", ")", ";", "ensureSizeGreaterThanSlide", "(", "s", ",", "l", ")", ";", "setSizeAndSlide", "(", "s", ",", "l", ")", ";", "this", ".", "windowAssigner", "=", "SlidingProcessingTimeWindows", ".", "of", "(", "s", ",", "l", ")", ";", "return", "this", ";", "}" ]
define a sliding processing time window @param size window size @param slide slide size
[ "define", "a", "sliding", "processing", "time", "window" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java#L123-L132
25,324
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java
BaseWindowedBolt.ingestionTimeWindow
public BaseWindowedBolt<T> ingestionTimeWindow(Time size) { long s = size.toMilliseconds(); ensurePositiveTime(s); setSizeAndSlide(s, DEFAULT_SLIDE); this.windowAssigner = TumblingIngestionTimeWindows.of(s); return this; }
java
public BaseWindowedBolt<T> ingestionTimeWindow(Time size) { long s = size.toMilliseconds(); ensurePositiveTime(s); setSizeAndSlide(s, DEFAULT_SLIDE); this.windowAssigner = TumblingIngestionTimeWindows.of(s); return this; }
[ "public", "BaseWindowedBolt", "<", "T", ">", "ingestionTimeWindow", "(", "Time", "size", ")", "{", "long", "s", "=", "size", ".", "toMilliseconds", "(", ")", ";", "ensurePositiveTime", "(", "s", ")", ";", "setSizeAndSlide", "(", "s", ",", "DEFAULT_SLIDE", ")", ";", "this", ".", "windowAssigner", "=", "TumblingIngestionTimeWindows", ".", "of", "(", "s", ")", ";", "return", "this", ";", "}" ]
define a tumbling ingestion time window @param size window size
[ "define", "a", "tumbling", "ingestion", "time", "window" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java#L139-L146
25,325
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java
BaseWindowedBolt.ingestionTimeWindow
public BaseWindowedBolt<T> ingestionTimeWindow(Time size, Time slide) { long s = size.toMilliseconds(); long l = slide.toMilliseconds(); ensurePositiveTime(s, l); ensureSizeGreaterThanSlide(s, l); setSizeAndSlide(s, l); this.windowAssigner = SlidingIngestionTimeWindows.of(s, l); return this; }
java
public BaseWindowedBolt<T> ingestionTimeWindow(Time size, Time slide) { long s = size.toMilliseconds(); long l = slide.toMilliseconds(); ensurePositiveTime(s, l); ensureSizeGreaterThanSlide(s, l); setSizeAndSlide(s, l); this.windowAssigner = SlidingIngestionTimeWindows.of(s, l); return this; }
[ "public", "BaseWindowedBolt", "<", "T", ">", "ingestionTimeWindow", "(", "Time", "size", ",", "Time", "slide", ")", "{", "long", "s", "=", "size", ".", "toMilliseconds", "(", ")", ";", "long", "l", "=", "slide", ".", "toMilliseconds", "(", ")", ";", "ensurePositiveTime", "(", "s", ",", "l", ")", ";", "ensureSizeGreaterThanSlide", "(", "s", ",", "l", ")", ";", "setSizeAndSlide", "(", "s", ",", "l", ")", ";", "this", ".", "windowAssigner", "=", "SlidingIngestionTimeWindows", ".", "of", "(", "s", ",", "l", ")", ";", "return", "this", ";", "}" ]
define a sliding ingestion time window @param size window size @param slide slide size
[ "define", "a", "sliding", "ingestion", "time", "window" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java#L154-L163
25,326
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java
BaseWindowedBolt.eventTimeWindow
public BaseWindowedBolt<T> eventTimeWindow(Time size) { long s = size.toMilliseconds(); ensurePositiveTime(s); setSizeAndSlide(s, DEFAULT_SLIDE); this.windowAssigner = TumblingEventTimeWindows.of(s); return this; }
java
public BaseWindowedBolt<T> eventTimeWindow(Time size) { long s = size.toMilliseconds(); ensurePositiveTime(s); setSizeAndSlide(s, DEFAULT_SLIDE); this.windowAssigner = TumblingEventTimeWindows.of(s); return this; }
[ "public", "BaseWindowedBolt", "<", "T", ">", "eventTimeWindow", "(", "Time", "size", ")", "{", "long", "s", "=", "size", ".", "toMilliseconds", "(", ")", ";", "ensurePositiveTime", "(", "s", ")", ";", "setSizeAndSlide", "(", "s", ",", "DEFAULT_SLIDE", ")", ";", "this", ".", "windowAssigner", "=", "TumblingEventTimeWindows", ".", "of", "(", "s", ")", ";", "return", "this", ";", "}" ]
define a tumbling event time window @param size window size
[ "define", "a", "tumbling", "event", "time", "window" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java#L170-L177
25,327
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java
BaseWindowedBolt.eventTimeWindow
public BaseWindowedBolt<T> eventTimeWindow(Time size, Time slide) { long s = size.toMilliseconds(); long l = slide.toMilliseconds(); ensurePositiveTime(s, l); ensureSizeGreaterThanSlide(s, l); setSizeAndSlide(s, l); this.windowAssigner = SlidingEventTimeWindows.of(s, l); return this; }
java
public BaseWindowedBolt<T> eventTimeWindow(Time size, Time slide) { long s = size.toMilliseconds(); long l = slide.toMilliseconds(); ensurePositiveTime(s, l); ensureSizeGreaterThanSlide(s, l); setSizeAndSlide(s, l); this.windowAssigner = SlidingEventTimeWindows.of(s, l); return this; }
[ "public", "BaseWindowedBolt", "<", "T", ">", "eventTimeWindow", "(", "Time", "size", ",", "Time", "slide", ")", "{", "long", "s", "=", "size", ".", "toMilliseconds", "(", ")", ";", "long", "l", "=", "slide", ".", "toMilliseconds", "(", ")", ";", "ensurePositiveTime", "(", "s", ",", "l", ")", ";", "ensureSizeGreaterThanSlide", "(", "s", ",", "l", ")", ";", "setSizeAndSlide", "(", "s", ",", "l", ")", ";", "this", ".", "windowAssigner", "=", "SlidingEventTimeWindows", ".", "of", "(", "s", ",", "l", ")", ";", "return", "this", ";", "}" ]
define a sliding event time window @param size window size @param slide slide size
[ "define", "a", "sliding", "event", "time", "window" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java#L185-L194
25,328
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java
BaseWindowedBolt.sessionTimeWindow
public BaseWindowedBolt<T> sessionTimeWindow(Time size) { long s = size.toMilliseconds(); ensurePositiveTime(s); setSizeAndSlide(s, DEFAULT_SLIDE); this.windowAssigner = ProcessingTimeSessionWindows.withGap(s); return this; }
java
public BaseWindowedBolt<T> sessionTimeWindow(Time size) { long s = size.toMilliseconds(); ensurePositiveTime(s); setSizeAndSlide(s, DEFAULT_SLIDE); this.windowAssigner = ProcessingTimeSessionWindows.withGap(s); return this; }
[ "public", "BaseWindowedBolt", "<", "T", ">", "sessionTimeWindow", "(", "Time", "size", ")", "{", "long", "s", "=", "size", ".", "toMilliseconds", "(", ")", ";", "ensurePositiveTime", "(", "s", ")", ";", "setSizeAndSlide", "(", "s", ",", "DEFAULT_SLIDE", ")", ";", "this", ".", "windowAssigner", "=", "ProcessingTimeSessionWindows", ".", "withGap", "(", "s", ")", ";", "return", "this", ";", "}" ]
define a session processing time window @param size window size, i.e., session gap
[ "define", "a", "session", "processing", "time", "window" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java#L202-L209
25,329
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java
BaseWindowedBolt.sessionEventTimeWindow
public BaseWindowedBolt<T> sessionEventTimeWindow(Time size) { long s = size.toMilliseconds(); ensurePositiveTime(s); setSizeAndSlide(s, DEFAULT_SLIDE); this.windowAssigner = EventTimeSessionWindows.withGap(s); return this; }
java
public BaseWindowedBolt<T> sessionEventTimeWindow(Time size) { long s = size.toMilliseconds(); ensurePositiveTime(s); setSizeAndSlide(s, DEFAULT_SLIDE); this.windowAssigner = EventTimeSessionWindows.withGap(s); return this; }
[ "public", "BaseWindowedBolt", "<", "T", ">", "sessionEventTimeWindow", "(", "Time", "size", ")", "{", "long", "s", "=", "size", ".", "toMilliseconds", "(", ")", ";", "ensurePositiveTime", "(", "s", ")", ";", "setSizeAndSlide", "(", "s", ",", "DEFAULT_SLIDE", ")", ";", "this", ".", "windowAssigner", "=", "EventTimeSessionWindows", ".", "withGap", "(", "s", ")", ";", "return", "this", ";", "}" ]
define a session event time window @param size window size, i.e., session gap
[ "define", "a", "session", "event", "time", "window" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java#L216-L223
25,330
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java
BaseWindowedBolt.withMaxLagMs
public BaseWindowedBolt<T> withMaxLagMs(Time maxLag) { this.maxLagMs = maxLag.toMilliseconds(); ensureNonNegativeTime(maxLagMs); return this; }
java
public BaseWindowedBolt<T> withMaxLagMs(Time maxLag) { this.maxLagMs = maxLag.toMilliseconds(); ensureNonNegativeTime(maxLagMs); return this; }
[ "public", "BaseWindowedBolt", "<", "T", ">", "withMaxLagMs", "(", "Time", "maxLag", ")", "{", "this", ".", "maxLagMs", "=", "maxLag", ".", "toMilliseconds", "(", ")", ";", "ensureNonNegativeTime", "(", "maxLagMs", ")", ";", "return", "this", ";", "}" ]
define max lag in ms, only for event time windows @param maxLag max lag time
[ "define", "max", "lag", "in", "ms", "only", "for", "event", "time", "windows" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/window/BaseWindowedBolt.java#L268-L272
25,331
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/supervisor/ShutdownWork.java
ShutdownWork.getPid
public static List<String> getPid(Map conf, String workerId) throws IOException { String workerPidPath = StormConfig.worker_pids_root(conf, workerId); return PathUtils.read_dir_contents(workerPidPath); }
java
public static List<String> getPid(Map conf, String workerId) throws IOException { String workerPidPath = StormConfig.worker_pids_root(conf, workerId); return PathUtils.read_dir_contents(workerPidPath); }
[ "public", "static", "List", "<", "String", ">", "getPid", "(", "Map", "conf", ",", "String", "workerId", ")", "throws", "IOException", "{", "String", "workerPidPath", "=", "StormConfig", ".", "worker_pids_root", "(", "conf", ",", "workerId", ")", ";", "return", "PathUtils", ".", "read_dir_contents", "(", "workerPidPath", ")", ";", "}" ]
When worker has been started by manually and supervisor, it will return multiple pid @param conf storm conf @param workerId worker id
[ "When", "worker", "has", "been", "started", "by", "manually", "and", "supervisor", "it", "will", "return", "multiple", "pid" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/supervisor/ShutdownWork.java#L169-L173
25,332
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/command/HealthCheck.java
HealthCheck.isHealthyUnderPath
private static boolean isHealthyUnderPath(String path, long timeout) { if (path == null) { return true; } List<String> commands = generateCommands(path); if (commands != null && commands.size() > 0) { for (String command : commands) { ScriptProcessLauncher scriptProcessLauncher = new ScriptProcessLauncher(command, timeout); ExitStatus exit = scriptProcessLauncher.launch(); if (exit.equals(ExitStatus.FAILED)) { return false; } } return true; } else { return true; } }
java
private static boolean isHealthyUnderPath(String path, long timeout) { if (path == null) { return true; } List<String> commands = generateCommands(path); if (commands != null && commands.size() > 0) { for (String command : commands) { ScriptProcessLauncher scriptProcessLauncher = new ScriptProcessLauncher(command, timeout); ExitStatus exit = scriptProcessLauncher.launch(); if (exit.equals(ExitStatus.FAILED)) { return false; } } return true; } else { return true; } }
[ "private", "static", "boolean", "isHealthyUnderPath", "(", "String", "path", ",", "long", "timeout", ")", "{", "if", "(", "path", "==", "null", ")", "{", "return", "true", ";", "}", "List", "<", "String", ">", "commands", "=", "generateCommands", "(", "path", ")", ";", "if", "(", "commands", "!=", "null", "&&", "commands", ".", "size", "(", ")", ">", "0", ")", "{", "for", "(", "String", "command", ":", "commands", ")", "{", "ScriptProcessLauncher", "scriptProcessLauncher", "=", "new", "ScriptProcessLauncher", "(", "command", ",", "timeout", ")", ";", "ExitStatus", "exit", "=", "scriptProcessLauncher", ".", "launch", "(", ")", ";", "if", "(", "exit", ".", "equals", "(", "ExitStatus", ".", "FAILED", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "else", "{", "return", "true", ";", "}", "}" ]
return false if the health check failed when running the scripts under the path
[ "return", "false", "if", "the", "health", "check", "failed", "when", "running", "the", "scripts", "under", "the", "path" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/command/HealthCheck.java#L65-L82
25,333
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/security/auth/KerberosPrincipalToLocal.java
KerberosPrincipalToLocal.toLocal
public String toLocal(Principal principal) { // This technically does not conform with rfc1964, but should work so // long as you don't have any really odd names in your KDC. return principal == null ? null : principal.getName().split("[/@]")[0]; }
java
public String toLocal(Principal principal) { // This technically does not conform with rfc1964, but should work so // long as you don't have any really odd names in your KDC. return principal == null ? null : principal.getName().split("[/@]")[0]; }
[ "public", "String", "toLocal", "(", "Principal", "principal", ")", "{", "// This technically does not conform with rfc1964, but should work so", "// long as you don't have any really odd names in your KDC.", "return", "principal", "==", "null", "?", "null", ":", "principal", ".", "getName", "(", ")", ".", "split", "(", "\"[/@]\"", ")", "[", "0", "]", ";", "}" ]
Convert a Principal to a local user name. @param principal the principal to convert @return The local user name.
[ "Convert", "a", "Principal", "to", "a", "local", "user", "name", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/security/auth/KerberosPrincipalToLocal.java#L43-L47
25,334
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/topology/CheckpointTupleForwarder.java
CheckpointTupleForwarder.handleCheckpoint
protected void handleCheckpoint(Tuple checkpointTuple, Action action, long txid) { collector.emit(CheckpointSpout.CHECKPOINT_STREAM_ID, checkpointTuple, new Values(txid, action)); collector.ack(checkpointTuple); }
java
protected void handleCheckpoint(Tuple checkpointTuple, Action action, long txid) { collector.emit(CheckpointSpout.CHECKPOINT_STREAM_ID, checkpointTuple, new Values(txid, action)); collector.ack(checkpointTuple); }
[ "protected", "void", "handleCheckpoint", "(", "Tuple", "checkpointTuple", ",", "Action", "action", ",", "long", "txid", ")", "{", "collector", ".", "emit", "(", "CheckpointSpout", ".", "CHECKPOINT_STREAM_ID", ",", "checkpointTuple", ",", "new", "Values", "(", "txid", ",", "action", ")", ")", ";", "collector", ".", "ack", "(", "checkpointTuple", ")", ";", "}" ]
Forwards the checkpoint tuple downstream. Sub-classes can override with the logic for handling checkpoint tuple. @param checkpointTuple the checkpoint tuple @param action the action (prepare, commit, rollback or initstate) @param txid the transaction id.
[ "Forwards", "the", "checkpoint", "tuple", "downstream", ".", "Sub", "-", "classes", "can", "override", "with", "the", "logic", "for", "handling", "checkpoint", "tuple", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/topology/CheckpointTupleForwarder.java#L103-L106
25,335
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/topology/CheckpointTupleForwarder.java
CheckpointTupleForwarder.processCheckpoint
private void processCheckpoint(Tuple input) { Action action = (Action) input.getValueByField(CheckpointSpout.CHECKPOINT_FIELD_ACTION); long txid = input.getLongByField(CheckpointSpout.CHECKPOINT_FIELD_TXID); if (shouldProcessTransaction(action, txid)) { LOG.debug("Processing action {}, txid {}", action, txid); try { if (txid >= lastTxid) { handleCheckpoint(input, action, txid); if (action == CheckPointState.Action.ROLLBACK) { lastTxid = txid - 1; } else { lastTxid = txid; } } else { LOG.debug("Ignoring old transaction. Action {}, txid {}", action, txid); collector.ack(input); } } catch (Throwable th) { LOG.error("Got error while processing checkpoint tuple", th); collector.fail(input); collector.reportError(th); } } else { LOG.debug("Waiting for action {}, txid {} from all input tasks. checkPointInputTaskCount {}, " + "transactionRequestCount {}", action, txid, checkPointInputTaskCount, transactionRequestCount); collector.ack(input); } }
java
private void processCheckpoint(Tuple input) { Action action = (Action) input.getValueByField(CheckpointSpout.CHECKPOINT_FIELD_ACTION); long txid = input.getLongByField(CheckpointSpout.CHECKPOINT_FIELD_TXID); if (shouldProcessTransaction(action, txid)) { LOG.debug("Processing action {}, txid {}", action, txid); try { if (txid >= lastTxid) { handleCheckpoint(input, action, txid); if (action == CheckPointState.Action.ROLLBACK) { lastTxid = txid - 1; } else { lastTxid = txid; } } else { LOG.debug("Ignoring old transaction. Action {}, txid {}", action, txid); collector.ack(input); } } catch (Throwable th) { LOG.error("Got error while processing checkpoint tuple", th); collector.fail(input); collector.reportError(th); } } else { LOG.debug("Waiting for action {}, txid {} from all input tasks. checkPointInputTaskCount {}, " + "transactionRequestCount {}", action, txid, checkPointInputTaskCount, transactionRequestCount); collector.ack(input); } }
[ "private", "void", "processCheckpoint", "(", "Tuple", "input", ")", "{", "Action", "action", "=", "(", "Action", ")", "input", ".", "getValueByField", "(", "CheckpointSpout", ".", "CHECKPOINT_FIELD_ACTION", ")", ";", "long", "txid", "=", "input", ".", "getLongByField", "(", "CheckpointSpout", ".", "CHECKPOINT_FIELD_TXID", ")", ";", "if", "(", "shouldProcessTransaction", "(", "action", ",", "txid", ")", ")", "{", "LOG", ".", "debug", "(", "\"Processing action {}, txid {}\"", ",", "action", ",", "txid", ")", ";", "try", "{", "if", "(", "txid", ">=", "lastTxid", ")", "{", "handleCheckpoint", "(", "input", ",", "action", ",", "txid", ")", ";", "if", "(", "action", "==", "CheckPointState", ".", "Action", ".", "ROLLBACK", ")", "{", "lastTxid", "=", "txid", "-", "1", ";", "}", "else", "{", "lastTxid", "=", "txid", ";", "}", "}", "else", "{", "LOG", ".", "debug", "(", "\"Ignoring old transaction. Action {}, txid {}\"", ",", "action", ",", "txid", ")", ";", "collector", ".", "ack", "(", "input", ")", ";", "}", "}", "catch", "(", "Throwable", "th", ")", "{", "LOG", ".", "error", "(", "\"Got error while processing checkpoint tuple\"", ",", "th", ")", ";", "collector", ".", "fail", "(", "input", ")", ";", "collector", ".", "reportError", "(", "th", ")", ";", "}", "}", "else", "{", "LOG", ".", "debug", "(", "\"Waiting for action {}, txid {} from all input tasks. checkPointInputTaskCount {}, \"", "+", "\"transactionRequestCount {}\"", ",", "action", ",", "txid", ",", "checkPointInputTaskCount", ",", "transactionRequestCount", ")", ";", "collector", ".", "ack", "(", "input", ")", ";", "}", "}" ]
Invokes handleCheckpoint once checkpoint tuple is received on all input checkpoint streams to this component.
[ "Invokes", "handleCheckpoint", "once", "checkpoint", "tuple", "is", "received", "on", "all", "input", "checkpoint", "streams", "to", "this", "component", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/topology/CheckpointTupleForwarder.java#L126-L153
25,336
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/topology/CheckpointTupleForwarder.java
CheckpointTupleForwarder.getCheckpointInputTaskCount
private int getCheckpointInputTaskCount(TopologyContext context) { int count = 0; for (GlobalStreamId inputStream : context.getThisSources().keySet()) { if (CheckpointSpout.CHECKPOINT_STREAM_ID.equals(inputStream.get_streamId())) { count += context.getComponentTasks(inputStream.get_componentId()).size(); } } return count; }
java
private int getCheckpointInputTaskCount(TopologyContext context) { int count = 0; for (GlobalStreamId inputStream : context.getThisSources().keySet()) { if (CheckpointSpout.CHECKPOINT_STREAM_ID.equals(inputStream.get_streamId())) { count += context.getComponentTasks(inputStream.get_componentId()).size(); } } return count; }
[ "private", "int", "getCheckpointInputTaskCount", "(", "TopologyContext", "context", ")", "{", "int", "count", "=", "0", ";", "for", "(", "GlobalStreamId", "inputStream", ":", "context", ".", "getThisSources", "(", ")", ".", "keySet", "(", ")", ")", "{", "if", "(", "CheckpointSpout", ".", "CHECKPOINT_STREAM_ID", ".", "equals", "(", "inputStream", ".", "get_streamId", "(", ")", ")", ")", "{", "count", "+=", "context", ".", "getComponentTasks", "(", "inputStream", ".", "get_componentId", "(", ")", ")", ".", "size", "(", ")", ";", "}", "}", "return", "count", ";", "}" ]
returns the total number of input checkpoint streams across all input tasks to this component.
[ "returns", "the", "total", "number", "of", "input", "checkpoint", "streams", "across", "all", "input", "tasks", "to", "this", "component", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/topology/CheckpointTupleForwarder.java#L159-L167
25,337
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/topology/CheckpointTupleForwarder.java
CheckpointTupleForwarder.shouldProcessTransaction
private boolean shouldProcessTransaction(Action action, long txid) { TransactionRequest request = new TransactionRequest(action, txid); Integer count; if ((count = transactionRequestCount.get(request)) == null) { transactionRequestCount.put(request, 1); count = 1; } else { transactionRequestCount.put(request, ++count); } if (count == checkPointInputTaskCount) { transactionRequestCount.remove(request); return true; } return false; }
java
private boolean shouldProcessTransaction(Action action, long txid) { TransactionRequest request = new TransactionRequest(action, txid); Integer count; if ((count = transactionRequestCount.get(request)) == null) { transactionRequestCount.put(request, 1); count = 1; } else { transactionRequestCount.put(request, ++count); } if (count == checkPointInputTaskCount) { transactionRequestCount.remove(request); return true; } return false; }
[ "private", "boolean", "shouldProcessTransaction", "(", "Action", "action", ",", "long", "txid", ")", "{", "TransactionRequest", "request", "=", "new", "TransactionRequest", "(", "action", ",", "txid", ")", ";", "Integer", "count", ";", "if", "(", "(", "count", "=", "transactionRequestCount", ".", "get", "(", "request", ")", ")", "==", "null", ")", "{", "transactionRequestCount", ".", "put", "(", "request", ",", "1", ")", ";", "count", "=", "1", ";", "}", "else", "{", "transactionRequestCount", ".", "put", "(", "request", ",", "++", "count", ")", ";", "}", "if", "(", "count", "==", "checkPointInputTaskCount", ")", "{", "transactionRequestCount", ".", "remove", "(", "request", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks if check points have been received from all tasks across all input streams to this component
[ "Checks", "if", "check", "points", "have", "been", "received", "from", "all", "tasks", "across", "all", "input", "streams", "to", "this", "component" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/topology/CheckpointTupleForwarder.java#L173-L187
25,338
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/ConfigValidation.java
ConfigValidation.fv
public static NestableFieldValidator fv(final Class cls, final boolean nullAllowed) { return new NestableFieldValidator() { @Override public void validateField(String pd, String name, Object field) throws IllegalArgumentException { if (nullAllowed && field == null) { return; } if (!cls.isInstance(field)) { throw new IllegalArgumentException(pd + name + " must be a " + cls.getName() + ". (" + field + ")"); } } }; }
java
public static NestableFieldValidator fv(final Class cls, final boolean nullAllowed) { return new NestableFieldValidator() { @Override public void validateField(String pd, String name, Object field) throws IllegalArgumentException { if (nullAllowed && field == null) { return; } if (!cls.isInstance(field)) { throw new IllegalArgumentException(pd + name + " must be a " + cls.getName() + ". (" + field + ")"); } } }; }
[ "public", "static", "NestableFieldValidator", "fv", "(", "final", "Class", "cls", ",", "final", "boolean", "nullAllowed", ")", "{", "return", "new", "NestableFieldValidator", "(", ")", "{", "@", "Override", "public", "void", "validateField", "(", "String", "pd", ",", "String", "name", ",", "Object", "field", ")", "throws", "IllegalArgumentException", "{", "if", "(", "nullAllowed", "&&", "field", "==", "null", ")", "{", "return", ";", "}", "if", "(", "!", "cls", ".", "isInstance", "(", "field", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "pd", "+", "name", "+", "\" must be a \"", "+", "cls", ".", "getName", "(", ")", "+", "\". (\"", "+", "field", "+", "\")\"", ")", ";", "}", "}", "}", ";", "}" ]
Returns a new NestableFieldValidator for a given class. @param cls the Class the field should be a type of @param nullAllowed whether or not a value of null is valid @return a NestableFieldValidator for that class
[ "Returns", "a", "new", "NestableFieldValidator", "for", "a", "given", "class", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/ConfigValidation.java#L68-L80
25,339
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/ConfigValidation.java
ConfigValidation.listFv
public static NestableFieldValidator listFv(Class cls, boolean nullAllowed) { return listFv(fv(cls, false), nullAllowed); }
java
public static NestableFieldValidator listFv(Class cls, boolean nullAllowed) { return listFv(fv(cls, false), nullAllowed); }
[ "public", "static", "NestableFieldValidator", "listFv", "(", "Class", "cls", ",", "boolean", "nullAllowed", ")", "{", "return", "listFv", "(", "fv", "(", "cls", ",", "false", ")", ",", "nullAllowed", ")", ";", "}" ]
Returns a new NestableFieldValidator for a List of the given Class. @param cls the Class of elements composing the list @param nullAllowed whether or not a value of null is valid @return a NestableFieldValidator for a list of the given class
[ "Returns", "a", "new", "NestableFieldValidator", "for", "a", "List", "of", "the", "given", "Class", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/ConfigValidation.java#L89-L91
25,340
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/ConfigValidation.java
ConfigValidation.listFv
public static NestableFieldValidator listFv(final NestableFieldValidator validator, final boolean nullAllowed) { return new NestableFieldValidator() { @Override public void validateField(String pd, String name, Object field) throws IllegalArgumentException { if (nullAllowed && field == null) { return; } if (field instanceof Iterable) { for (Object e : (Iterable) field) { validator.validateField(pd + "Each element of the list ", name, e); } return; } throw new IllegalArgumentException("Field " + name + " must be an Iterable but was " + ((field == null) ? "null" : ("a " + field.getClass()))); } }; }
java
public static NestableFieldValidator listFv(final NestableFieldValidator validator, final boolean nullAllowed) { return new NestableFieldValidator() { @Override public void validateField(String pd, String name, Object field) throws IllegalArgumentException { if (nullAllowed && field == null) { return; } if (field instanceof Iterable) { for (Object e : (Iterable) field) { validator.validateField(pd + "Each element of the list ", name, e); } return; } throw new IllegalArgumentException("Field " + name + " must be an Iterable but was " + ((field == null) ? "null" : ("a " + field.getClass()))); } }; }
[ "public", "static", "NestableFieldValidator", "listFv", "(", "final", "NestableFieldValidator", "validator", ",", "final", "boolean", "nullAllowed", ")", "{", "return", "new", "NestableFieldValidator", "(", ")", "{", "@", "Override", "public", "void", "validateField", "(", "String", "pd", ",", "String", "name", ",", "Object", "field", ")", "throws", "IllegalArgumentException", "{", "if", "(", "nullAllowed", "&&", "field", "==", "null", ")", "{", "return", ";", "}", "if", "(", "field", "instanceof", "Iterable", ")", "{", "for", "(", "Object", "e", ":", "(", "Iterable", ")", "field", ")", "{", "validator", ".", "validateField", "(", "pd", "+", "\"Each element of the list \"", ",", "name", ",", "e", ")", ";", "}", "return", ";", "}", "throw", "new", "IllegalArgumentException", "(", "\"Field \"", "+", "name", "+", "\" must be an Iterable but was \"", "+", "(", "(", "field", "==", "null", ")", "?", "\"null\"", ":", "(", "\"a \"", "+", "field", ".", "getClass", "(", ")", ")", ")", ")", ";", "}", "}", ";", "}" ]
Returns a new NestableFieldValidator for a List where each item is validated by validator. @param validator used to validate each item in the list @param nullAllowed whether or not a value of null is valid @return a NestableFieldValidator for a list with each item validated by a different validator.
[ "Returns", "a", "new", "NestableFieldValidator", "for", "a", "List", "where", "each", "item", "is", "validated", "by", "validator", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/ConfigValidation.java#L100-L116
25,341
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/ConfigValidation.java
ConfigValidation.mapFv
public static NestableFieldValidator mapFv(Class key, Class val, boolean nullAllowed) { return mapFv(fv(key, false), fv(val, false), nullAllowed); }
java
public static NestableFieldValidator mapFv(Class key, Class val, boolean nullAllowed) { return mapFv(fv(key, false), fv(val, false), nullAllowed); }
[ "public", "static", "NestableFieldValidator", "mapFv", "(", "Class", "key", ",", "Class", "val", ",", "boolean", "nullAllowed", ")", "{", "return", "mapFv", "(", "fv", "(", "key", ",", "false", ")", ",", "fv", "(", "val", ",", "false", ")", ",", "nullAllowed", ")", ";", "}" ]
Returns a new NestableFieldValidator for a Map of key to val. @param key the Class of keys in the map @param val the Class of values in the map @param nullAllowed whether or not a value of null is valid @return a NestableFieldValidator for a Map of key to val
[ "Returns", "a", "new", "NestableFieldValidator", "for", "a", "Map", "of", "key", "to", "val", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/ConfigValidation.java#L126-L128
25,342
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/ConfigValidation.java
ConfigValidation.mapFv
public static NestableFieldValidator mapFv(final NestableFieldValidator key, final NestableFieldValidator val, final boolean nullAllowed) { return new NestableFieldValidator() { @SuppressWarnings("unchecked") @Override public void validateField(String pd, String name, Object field) throws IllegalArgumentException { if (nullAllowed && field == null) { return; } if (field instanceof Map) { for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) field).entrySet()) { key.validateField("Each key of the map ", name, entry.getKey()); val.validateField("Each value in the map ", name, entry.getValue()); } return; } throw new IllegalArgumentException("Field " + name + " must be a Map"); } }; }
java
public static NestableFieldValidator mapFv(final NestableFieldValidator key, final NestableFieldValidator val, final boolean nullAllowed) { return new NestableFieldValidator() { @SuppressWarnings("unchecked") @Override public void validateField(String pd, String name, Object field) throws IllegalArgumentException { if (nullAllowed && field == null) { return; } if (field instanceof Map) { for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) field).entrySet()) { key.validateField("Each key of the map ", name, entry.getKey()); val.validateField("Each value in the map ", name, entry.getValue()); } return; } throw new IllegalArgumentException("Field " + name + " must be a Map"); } }; }
[ "public", "static", "NestableFieldValidator", "mapFv", "(", "final", "NestableFieldValidator", "key", ",", "final", "NestableFieldValidator", "val", ",", "final", "boolean", "nullAllowed", ")", "{", "return", "new", "NestableFieldValidator", "(", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "Override", "public", "void", "validateField", "(", "String", "pd", ",", "String", "name", ",", "Object", "field", ")", "throws", "IllegalArgumentException", "{", "if", "(", "nullAllowed", "&&", "field", "==", "null", ")", "{", "return", ";", "}", "if", "(", "field", "instanceof", "Map", ")", "{", "for", "(", "Map", ".", "Entry", "<", "Object", ",", "Object", ">", "entry", ":", "(", "(", "Map", "<", "Object", ",", "Object", ">", ")", "field", ")", ".", "entrySet", "(", ")", ")", "{", "key", ".", "validateField", "(", "\"Each key of the map \"", ",", "name", ",", "entry", ".", "getKey", "(", ")", ")", ";", "val", ".", "validateField", "(", "\"Each value in the map \"", ",", "name", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "return", ";", "}", "throw", "new", "IllegalArgumentException", "(", "\"Field \"", "+", "name", "+", "\" must be a Map\"", ")", ";", "}", "}", ";", "}" ]
Returns a new NestableFieldValidator for a Map. @param key a validator for the keys in the map @param val a validator for the values in the map @param nullAllowed whether or not a value of null is valid @return a NestableFieldValidator for a Map
[ "Returns", "a", "new", "NestableFieldValidator", "for", "a", "Map", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/ConfigValidation.java#L138-L157
25,343
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/worker/hearbeat/WorkerHeartbeatRunable.java
WorkerHeartbeatRunable.doHeartbeat
public void doHeartbeat() throws IOException { int curTime = TimeUtils.current_time_secs(); WorkerHeartbeat hb = new WorkerHeartbeat(curTime, topologyId, taskIds, port); LOG.debug("Doing heartbeat:" + workerId + ",port:" + port + ",hb" + hb.toString()); LocalState state = getWorkerState(); state.put(Common.LS_WORKER_HEARTBEAT, hb); }
java
public void doHeartbeat() throws IOException { int curTime = TimeUtils.current_time_secs(); WorkerHeartbeat hb = new WorkerHeartbeat(curTime, topologyId, taskIds, port); LOG.debug("Doing heartbeat:" + workerId + ",port:" + port + ",hb" + hb.toString()); LocalState state = getWorkerState(); state.put(Common.LS_WORKER_HEARTBEAT, hb); }
[ "public", "void", "doHeartbeat", "(", ")", "throws", "IOException", "{", "int", "curTime", "=", "TimeUtils", ".", "current_time_secs", "(", ")", ";", "WorkerHeartbeat", "hb", "=", "new", "WorkerHeartbeat", "(", "curTime", ",", "topologyId", ",", "taskIds", ",", "port", ")", ";", "LOG", ".", "debug", "(", "\"Doing heartbeat:\"", "+", "workerId", "+", "\",port:\"", "+", "port", "+", "\",hb\"", "+", "hb", ".", "toString", "(", ")", ")", ";", "LocalState", "state", "=", "getWorkerState", "(", ")", ";", "state", ".", "put", "(", "Common", ".", "LS_WORKER_HEARTBEAT", ",", "hb", ")", ";", "}" ]
do heartbeat and update LocalState
[ "do", "heartbeat", "and", "update", "LocalState" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/worker/hearbeat/WorkerHeartbeatRunable.java#L86-L93
25,344
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/task/TaskBaseMetric.java
TaskBaseMetric.updateTime
public void updateTime(String streamId, String name, long start, long end, int count, boolean mergeTopology) { if (start > 0 && count > 0) { AsmMetric existingMetric = findMetric(streamId, name, MetricType.HISTOGRAM, mergeTopology); if (existingMetric instanceof AsmHistogram) { AsmHistogram histogram = (AsmHistogram) existingMetric; if (histogram.okToUpdate(end)) { long elapsed = ((end - start) * TimeUtils.US_PER_MS) / count; if (elapsed >= 0) { histogram.update(elapsed); histogram.setLastUpdateTime(end); } } } } }
java
public void updateTime(String streamId, String name, long start, long end, int count, boolean mergeTopology) { if (start > 0 && count > 0) { AsmMetric existingMetric = findMetric(streamId, name, MetricType.HISTOGRAM, mergeTopology); if (existingMetric instanceof AsmHistogram) { AsmHistogram histogram = (AsmHistogram) existingMetric; if (histogram.okToUpdate(end)) { long elapsed = ((end - start) * TimeUtils.US_PER_MS) / count; if (elapsed >= 0) { histogram.update(elapsed); histogram.setLastUpdateTime(end); } } } } }
[ "public", "void", "updateTime", "(", "String", "streamId", ",", "String", "name", ",", "long", "start", ",", "long", "end", ",", "int", "count", ",", "boolean", "mergeTopology", ")", "{", "if", "(", "start", ">", "0", "&&", "count", ">", "0", ")", "{", "AsmMetric", "existingMetric", "=", "findMetric", "(", "streamId", ",", "name", ",", "MetricType", ".", "HISTOGRAM", ",", "mergeTopology", ")", ";", "if", "(", "existingMetric", "instanceof", "AsmHistogram", ")", "{", "AsmHistogram", "histogram", "=", "(", "AsmHistogram", ")", "existingMetric", ";", "if", "(", "histogram", ".", "okToUpdate", "(", "end", ")", ")", "{", "long", "elapsed", "=", "(", "(", "end", "-", "start", ")", "*", "TimeUtils", ".", "US_PER_MS", ")", "/", "count", ";", "if", "(", "elapsed", ">=", "0", ")", "{", "histogram", ".", "update", "(", "elapsed", ")", ";", "histogram", ".", "setLastUpdateTime", "(", "end", ")", ";", "}", "}", "}", "}", "}" ]
almost the same implementation of above update, but improves performance for histograms
[ "almost", "the", "same", "implementation", "of", "above", "update", "but", "improves", "performance", "for", "histograms" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/task/TaskBaseMetric.java#L87-L102
25,345
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/JStormUtils.java
JStormUtils.process_pid
public static String process_pid() { String name = ManagementFactory.getRuntimeMXBean().getName(); String[] split = name.split("@"); if (split.length != 2) { throw new RuntimeException("Got unexpected process name: " + name); } return split[0]; }
java
public static String process_pid() { String name = ManagementFactory.getRuntimeMXBean().getName(); String[] split = name.split("@"); if (split.length != 2) { throw new RuntimeException("Got unexpected process name: " + name); } return split[0]; }
[ "public", "static", "String", "process_pid", "(", ")", "{", "String", "name", "=", "ManagementFactory", ".", "getRuntimeMXBean", "(", ")", ".", "getName", "(", ")", ";", "String", "[", "]", "split", "=", "name", ".", "split", "(", "\"@\"", ")", ";", "if", "(", "split", ".", "length", "!=", "2", ")", "{", "throw", "new", "RuntimeException", "(", "\"Got unexpected process name: \"", "+", "name", ")", ";", "}", "return", "split", "[", "0", "]", ";", "}" ]
Gets the pid of this JVM, because Java doesn't provide a real way to do this. @return
[ "Gets", "the", "pid", "of", "this", "JVM", "because", "Java", "doesn", "t", "provide", "a", "real", "way", "to", "do", "this", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/JStormUtils.java#L202-L210
25,346
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/JStormUtils.java
JStormUtils.extractDirFromJar
public static void extractDirFromJar(String jarpath, String dir, String destdir) { ZipFile zipFile = null; try { zipFile = new ZipFile(jarpath); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries != null && entries.hasMoreElements()) { ZipEntry ze = entries.nextElement(); if (!ze.isDirectory() && ze.getName().startsWith(dir)) { InputStream in = zipFile.getInputStream(ze); try { File file = new File(destdir, ze.getName()); if (!file.getParentFile().mkdirs()) { if (!file.getParentFile().isDirectory()) { throw new IOException("Mkdirs failed to create " + file.getParentFile().toString()); } } OutputStream out = new FileOutputStream(file); try { byte[] buffer = new byte[8192]; int i; while ((i = in.read(buffer)) != -1) { out.write(buffer, 0, i); } } finally { out.close(); } } finally { if (in != null) in.close(); } } } } catch (Exception e) { LOG.warn("No " + dir + " from " + jarpath + "!\n" + e.getMessage()); } finally { if (zipFile != null) try { zipFile.close(); } catch (Exception e) { LOG.warn(e.getMessage()); } } }
java
public static void extractDirFromJar(String jarpath, String dir, String destdir) { ZipFile zipFile = null; try { zipFile = new ZipFile(jarpath); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries != null && entries.hasMoreElements()) { ZipEntry ze = entries.nextElement(); if (!ze.isDirectory() && ze.getName().startsWith(dir)) { InputStream in = zipFile.getInputStream(ze); try { File file = new File(destdir, ze.getName()); if (!file.getParentFile().mkdirs()) { if (!file.getParentFile().isDirectory()) { throw new IOException("Mkdirs failed to create " + file.getParentFile().toString()); } } OutputStream out = new FileOutputStream(file); try { byte[] buffer = new byte[8192]; int i; while ((i = in.read(buffer)) != -1) { out.write(buffer, 0, i); } } finally { out.close(); } } finally { if (in != null) in.close(); } } } } catch (Exception e) { LOG.warn("No " + dir + " from " + jarpath + "!\n" + e.getMessage()); } finally { if (zipFile != null) try { zipFile.close(); } catch (Exception e) { LOG.warn(e.getMessage()); } } }
[ "public", "static", "void", "extractDirFromJar", "(", "String", "jarpath", ",", "String", "dir", ",", "String", "destdir", ")", "{", "ZipFile", "zipFile", "=", "null", ";", "try", "{", "zipFile", "=", "new", "ZipFile", "(", "jarpath", ")", ";", "Enumeration", "<", "?", "extends", "ZipEntry", ">", "entries", "=", "zipFile", ".", "entries", "(", ")", ";", "while", "(", "entries", "!=", "null", "&&", "entries", ".", "hasMoreElements", "(", ")", ")", "{", "ZipEntry", "ze", "=", "entries", ".", "nextElement", "(", ")", ";", "if", "(", "!", "ze", ".", "isDirectory", "(", ")", "&&", "ze", ".", "getName", "(", ")", ".", "startsWith", "(", "dir", ")", ")", "{", "InputStream", "in", "=", "zipFile", ".", "getInputStream", "(", "ze", ")", ";", "try", "{", "File", "file", "=", "new", "File", "(", "destdir", ",", "ze", ".", "getName", "(", ")", ")", ";", "if", "(", "!", "file", ".", "getParentFile", "(", ")", ".", "mkdirs", "(", ")", ")", "{", "if", "(", "!", "file", ".", "getParentFile", "(", ")", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "IOException", "(", "\"Mkdirs failed to create \"", "+", "file", ".", "getParentFile", "(", ")", ".", "toString", "(", ")", ")", ";", "}", "}", "OutputStream", "out", "=", "new", "FileOutputStream", "(", "file", ")", ";", "try", "{", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "8192", "]", ";", "int", "i", ";", "while", "(", "(", "i", "=", "in", ".", "read", "(", "buffer", ")", ")", "!=", "-", "1", ")", "{", "out", ".", "write", "(", "buffer", ",", "0", ",", "i", ")", ";", "}", "}", "finally", "{", "out", ".", "close", "(", ")", ";", "}", "}", "finally", "{", "if", "(", "in", "!=", "null", ")", "in", ".", "close", "(", ")", ";", "}", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "warn", "(", "\"No \"", "+", "dir", "+", "\" from \"", "+", "jarpath", "+", "\"!\\n\"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "finally", "{", "if", "(", "zipFile", "!=", "null", ")", "try", "{", "zipFile", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "warn", "(", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "}" ]
Extra dir from the jar to destdir @param jarpath @param dir @param destdir
[ "Extra", "dir", "from", "the", "jar", "to", "destdir" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/JStormUtils.java#L231-L275
25,347
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/JStormUtils.java
JStormUtils.zipContainsDir
public static boolean zipContainsDir(String zipfile, String resources) { Enumeration<? extends ZipEntry> entries = null; try { entries = (new ZipFile(zipfile)).entries(); while (entries != null && entries.hasMoreElements()) { ZipEntry ze = entries.nextElement(); String name = ze.getName(); if (name.startsWith(resources + "/")) { return true; } } } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); LOG.error(e + "zipContainsDir error"); } return false; }
java
public static boolean zipContainsDir(String zipfile, String resources) { Enumeration<? extends ZipEntry> entries = null; try { entries = (new ZipFile(zipfile)).entries(); while (entries != null && entries.hasMoreElements()) { ZipEntry ze = entries.nextElement(); String name = ze.getName(); if (name.startsWith(resources + "/")) { return true; } } } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); LOG.error(e + "zipContainsDir error"); } return false; }
[ "public", "static", "boolean", "zipContainsDir", "(", "String", "zipfile", ",", "String", "resources", ")", "{", "Enumeration", "<", "?", "extends", "ZipEntry", ">", "entries", "=", "null", ";", "try", "{", "entries", "=", "(", "new", "ZipFile", "(", "zipfile", ")", ")", ".", "entries", "(", ")", ";", "while", "(", "entries", "!=", "null", "&&", "entries", ".", "hasMoreElements", "(", ")", ")", "{", "ZipEntry", "ze", "=", "entries", ".", "nextElement", "(", ")", ";", "String", "name", "=", "ze", ".", "getName", "(", ")", ";", "if", "(", "name", ".", "startsWith", "(", "resources", "+", "\"/\"", ")", ")", "{", "return", "true", ";", "}", "}", "}", "catch", "(", "IOException", "e", ")", "{", "// TODO Auto-generated catch block", "// e.printStackTrace();", "LOG", ".", "error", "(", "e", "+", "\"zipContainsDir error\"", ")", ";", "}", "return", "false", ";", "}" ]
Check whether the zipfile contain the resources @param zipfile @param resources @return
[ "Check", "whether", "the", "zipfile", "contain", "the", "resources" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/JStormUtils.java#L797-L816
25,348
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/transactional/bolt/TransactionBolt.java
TransactionBolt.isDiscarded
protected boolean isDiscarded(long batchId) { if (batchId == TransactionCommon.INIT_BATCH_ID) { return false; } else if (!boltStatus.equals(State.ACTIVE)) { LOG.debug("Bolt is not active, state={}, tuple is going to be discarded", boltStatus.toString()); return true; } else if (batchId <= lastSuccessfulBatch) { LOG.info("Received expired event of batch-{}, current batchId={}", batchId, lastSuccessfulBatch); return true; } else { return false; } }
java
protected boolean isDiscarded(long batchId) { if (batchId == TransactionCommon.INIT_BATCH_ID) { return false; } else if (!boltStatus.equals(State.ACTIVE)) { LOG.debug("Bolt is not active, state={}, tuple is going to be discarded", boltStatus.toString()); return true; } else if (batchId <= lastSuccessfulBatch) { LOG.info("Received expired event of batch-{}, current batchId={}", batchId, lastSuccessfulBatch); return true; } else { return false; } }
[ "protected", "boolean", "isDiscarded", "(", "long", "batchId", ")", "{", "if", "(", "batchId", "==", "TransactionCommon", ".", "INIT_BATCH_ID", ")", "{", "return", "false", ";", "}", "else", "if", "(", "!", "boltStatus", ".", "equals", "(", "State", ".", "ACTIVE", ")", ")", "{", "LOG", ".", "debug", "(", "\"Bolt is not active, state={}, tuple is going to be discarded\"", ",", "boltStatus", ".", "toString", "(", ")", ")", ";", "return", "true", ";", "}", "else", "if", "(", "batchId", "<=", "lastSuccessfulBatch", ")", "{", "LOG", ".", "info", "(", "\"Received expired event of batch-{}, current batchId={}\"", ",", "batchId", ",", "lastSuccessfulBatch", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Check if the incoming batch would be discarded. Generally, the incoming batch shall be discarded while bolt is under rollback, or it is expired. @param batchId @return
[ "Check", "if", "the", "incoming", "batch", "would", "be", "discarded", ".", "Generally", "the", "incoming", "batch", "shall", "be", "discarded", "while", "bolt", "is", "under", "rollback", "or", "it", "is", "expired", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/transactional/bolt/TransactionBolt.java#L384-L396
25,349
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/utils/JStormUtils.java
JStormUtils.select_keys_pred
public static <K, V> Map<K, V> select_keys_pred(Set<K> filter, Map<K, V> all) { Map<K, V> filterMap = new HashMap<>(); for (Entry<K, V> entry : all.entrySet()) { if (!filter.contains(entry.getKey())) { filterMap.put(entry.getKey(), entry.getValue()); } } return filterMap; }
java
public static <K, V> Map<K, V> select_keys_pred(Set<K> filter, Map<K, V> all) { Map<K, V> filterMap = new HashMap<>(); for (Entry<K, V> entry : all.entrySet()) { if (!filter.contains(entry.getKey())) { filterMap.put(entry.getKey(), entry.getValue()); } } return filterMap; }
[ "public", "static", "<", "K", ",", "V", ">", "Map", "<", "K", ",", "V", ">", "select_keys_pred", "(", "Set", "<", "K", ">", "filter", ",", "Map", "<", "K", ",", "V", ">", "all", ")", "{", "Map", "<", "K", ",", "V", ">", "filterMap", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Entry", "<", "K", ",", "V", ">", "entry", ":", "all", ".", "entrySet", "(", ")", ")", "{", "if", "(", "!", "filter", ".", "contains", "(", "entry", ".", "getKey", "(", ")", ")", ")", "{", "filterMap", ".", "put", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "}", "return", "filterMap", ";", "}" ]
filter the map
[ "filter", "the", "map" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/utils/JStormUtils.java#L144-L154
25,350
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/utils/JStormUtils.java
JStormUtils.exec_command
public static void exec_command(String command) throws IOException { launchProcess(command, new HashMap<String, String>(), false); }
java
public static void exec_command(String command) throws IOException { launchProcess(command, new HashMap<String, String>(), false); }
[ "public", "static", "void", "exec_command", "(", "String", "command", ")", "throws", "IOException", "{", "launchProcess", "(", "command", ",", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ",", "false", ")", ";", "}" ]
use launchProcess to execute a command @param command command to be executed @throws ExecuteException @throws IOException
[ "use", "launchProcess", "to", "execute", "a", "command" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/utils/JStormUtils.java#L263-L265
25,351
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/utils/JStormUtils.java
JStormUtils.isProcDead
public static boolean isProcDead(String pid) { if (!OSInfo.isLinux()) { return false; } String path = "/proc/" + pid; File file = new File(path); if (!file.exists()) { LOG.info("Process " + pid + " is dead"); return true; } return false; }
java
public static boolean isProcDead(String pid) { if (!OSInfo.isLinux()) { return false; } String path = "/proc/" + pid; File file = new File(path); if (!file.exists()) { LOG.info("Process " + pid + " is dead"); return true; } return false; }
[ "public", "static", "boolean", "isProcDead", "(", "String", "pid", ")", "{", "if", "(", "!", "OSInfo", ".", "isLinux", "(", ")", ")", "{", "return", "false", ";", "}", "String", "path", "=", "\"/proc/\"", "+", "pid", ";", "File", "file", "=", "new", "File", "(", "path", ")", ";", "if", "(", "!", "file", ".", "exists", "(", ")", ")", "{", "LOG", ".", "info", "(", "\"Process \"", "+", "pid", "+", "\" is dead\"", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
This function is only for linux
[ "This", "function", "is", "only", "for", "linux" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/utils/JStormUtils.java#L369-L383
25,352
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/utils/JStormUtils.java
JStormUtils.interleave_all
public static <T> List<T> interleave_all(List<List<T>> splitup) { ArrayList<T> rtn = new ArrayList<>(); int maxLength = 0; for (List<T> e : splitup) { int len = e.size(); if (maxLength < len) { maxLength = len; } } for (int i = 0; i < maxLength; i++) { for (List<T> e : splitup) { if (e.size() > i) { rtn.add(e.get(i)); } } } return rtn; }
java
public static <T> List<T> interleave_all(List<List<T>> splitup) { ArrayList<T> rtn = new ArrayList<>(); int maxLength = 0; for (List<T> e : splitup) { int len = e.size(); if (maxLength < len) { maxLength = len; } } for (int i = 0; i < maxLength; i++) { for (List<T> e : splitup) { if (e.size() > i) { rtn.add(e.get(i)); } } } return rtn; }
[ "public", "static", "<", "T", ">", "List", "<", "T", ">", "interleave_all", "(", "List", "<", "List", "<", "T", ">", ">", "splitup", ")", "{", "ArrayList", "<", "T", ">", "rtn", "=", "new", "ArrayList", "<>", "(", ")", ";", "int", "maxLength", "=", "0", ";", "for", "(", "List", "<", "T", ">", "e", ":", "splitup", ")", "{", "int", "len", "=", "e", ".", "size", "(", ")", ";", "if", "(", "maxLength", "<", "len", ")", "{", "maxLength", "=", "len", ";", "}", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "maxLength", ";", "i", "++", ")", "{", "for", "(", "List", "<", "T", ">", "e", ":", "splitup", ")", "{", "if", "(", "e", ".", "size", "(", ")", ">", "i", ")", "{", "rtn", ".", "add", "(", "e", ".", "get", "(", "i", ")", ")", ";", "}", "}", "}", "return", "rtn", ";", "}" ]
balance all T
[ "balance", "all", "T" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/utils/JStormUtils.java#L824-L843
25,353
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/utils/JStormUtils.java
JStormUtils.getSupervisorPortNum
public static int getSupervisorPortNum(Map conf, int sysCpuNum, Long physicalMemSize) { double cpuWeight = ConfigExtension.getSupervisorSlotsPortCpuWeight(conf); int cpuPortNum = (int) (sysCpuNum / cpuWeight); if (cpuPortNum < 1) { LOG.info("Invalid supervisor.slots.port.cpu.weight setting :" + cpuWeight + ", cpu cores:" + sysCpuNum); cpuPortNum = 1; } Double memWeight = ConfigExtension.getSupervisorSlotsPortMemWeight(conf); int memPortNum = Integer.MAX_VALUE; if (physicalMemSize == null) { LOG.info("Failed to get memory size"); } else { LOG.debug("Get system memory size: " + physicalMemSize); long workerMemSize = ConfigExtension.getMemSizePerWorker(conf); memPortNum = (int) (physicalMemSize / (workerMemSize * memWeight)); if (memPortNum < 1) { LOG.info("System memory is too small for Jstorm"); memPortNum = 1; // minimal port number set to 1 if memory is not enough } } return Math.min(cpuPortNum, memPortNum); }
java
public static int getSupervisorPortNum(Map conf, int sysCpuNum, Long physicalMemSize) { double cpuWeight = ConfigExtension.getSupervisorSlotsPortCpuWeight(conf); int cpuPortNum = (int) (sysCpuNum / cpuWeight); if (cpuPortNum < 1) { LOG.info("Invalid supervisor.slots.port.cpu.weight setting :" + cpuWeight + ", cpu cores:" + sysCpuNum); cpuPortNum = 1; } Double memWeight = ConfigExtension.getSupervisorSlotsPortMemWeight(conf); int memPortNum = Integer.MAX_VALUE; if (physicalMemSize == null) { LOG.info("Failed to get memory size"); } else { LOG.debug("Get system memory size: " + physicalMemSize); long workerMemSize = ConfigExtension.getMemSizePerWorker(conf); memPortNum = (int) (physicalMemSize / (workerMemSize * memWeight)); if (memPortNum < 1) { LOG.info("System memory is too small for Jstorm"); memPortNum = 1; // minimal port number set to 1 if memory is not enough } } return Math.min(cpuPortNum, memPortNum); }
[ "public", "static", "int", "getSupervisorPortNum", "(", "Map", "conf", ",", "int", "sysCpuNum", ",", "Long", "physicalMemSize", ")", "{", "double", "cpuWeight", "=", "ConfigExtension", ".", "getSupervisorSlotsPortCpuWeight", "(", "conf", ")", ";", "int", "cpuPortNum", "=", "(", "int", ")", "(", "sysCpuNum", "/", "cpuWeight", ")", ";", "if", "(", "cpuPortNum", "<", "1", ")", "{", "LOG", ".", "info", "(", "\"Invalid supervisor.slots.port.cpu.weight setting :\"", "+", "cpuWeight", "+", "\", cpu cores:\"", "+", "sysCpuNum", ")", ";", "cpuPortNum", "=", "1", ";", "}", "Double", "memWeight", "=", "ConfigExtension", ".", "getSupervisorSlotsPortMemWeight", "(", "conf", ")", ";", "int", "memPortNum", "=", "Integer", ".", "MAX_VALUE", ";", "if", "(", "physicalMemSize", "==", "null", ")", "{", "LOG", ".", "info", "(", "\"Failed to get memory size\"", ")", ";", "}", "else", "{", "LOG", ".", "debug", "(", "\"Get system memory size: \"", "+", "physicalMemSize", ")", ";", "long", "workerMemSize", "=", "ConfigExtension", ".", "getMemSizePerWorker", "(", "conf", ")", ";", "memPortNum", "=", "(", "int", ")", "(", "physicalMemSize", "/", "(", "workerMemSize", "*", "memWeight", ")", ")", ";", "if", "(", "memPortNum", "<", "1", ")", "{", "LOG", ".", "info", "(", "\"System memory is too small for Jstorm\"", ")", ";", "memPortNum", "=", "1", ";", "// minimal port number set to 1 if memory is not enough", "}", "}", "return", "Math", ".", "min", "(", "cpuPortNum", ",", "memPortNum", ")", ";", "}" ]
calculate port number from cpu number and physical memory size
[ "calculate", "port", "number", "from", "cpu", "number", "and", "physical", "memory", "size" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/utils/JStormUtils.java#L1394-L1424
25,354
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/utils/JStormUtils.java
JStormUtils.getMetrics
public static Map<String, Double> getMetrics(Map conf, String topologyName, MetaType metricType, Integer window) { NimbusClientWrapper nimbusClient = null; Iface client = null; Map<String, Double> summary = new HashMap<>(); try { nimbusClient = new NimbusClientWrapper(); nimbusClient.init(conf); client = nimbusClient.getClient(); String topologyId = client.getTopologyId(topologyName); if (metricType == null) { metricType = MetaType.TASK; } List<MetricInfo> allTaskMetrics = client.getMetrics(topologyId, metricType.getT()); if (allTaskMetrics == null) { throw new RuntimeException("Failed to get metrics"); } if (window == null || !AsmWindow.TIME_WINDOWS.contains(window)) { window = AsmWindow.M1_WINDOW; } for (MetricInfo taskMetrics : allTaskMetrics) { Map<String, Map<Integer, MetricSnapshot>> metrics = taskMetrics.get_metrics(); if (metrics == null) { System.out.println("Failed to get task metrics"); continue; } for (Entry<String, Map<Integer, MetricSnapshot>> entry : metrics.entrySet()) { String key = entry.getKey(); MetricSnapshot metric = entry.getValue().get(window); if (metric == null) { throw new RuntimeException("Failed to get one minute metrics of " + key); } if (metric.get_metricType() == MetricType.COUNTER.getT()) { summary.put(key, (double) metric.get_longValue()); } else if (metric.get_metricType() == MetricType.GAUGE.getT()) { summary.put(key, metric.get_doubleValue()); } else { summary.put(key, metric.get_mean()); } } } return summary; } catch (Exception e) { throw new RuntimeException(e); } finally { if (client != null) { nimbusClient.cleanup(); } } }
java
public static Map<String, Double> getMetrics(Map conf, String topologyName, MetaType metricType, Integer window) { NimbusClientWrapper nimbusClient = null; Iface client = null; Map<String, Double> summary = new HashMap<>(); try { nimbusClient = new NimbusClientWrapper(); nimbusClient.init(conf); client = nimbusClient.getClient(); String topologyId = client.getTopologyId(topologyName); if (metricType == null) { metricType = MetaType.TASK; } List<MetricInfo> allTaskMetrics = client.getMetrics(topologyId, metricType.getT()); if (allTaskMetrics == null) { throw new RuntimeException("Failed to get metrics"); } if (window == null || !AsmWindow.TIME_WINDOWS.contains(window)) { window = AsmWindow.M1_WINDOW; } for (MetricInfo taskMetrics : allTaskMetrics) { Map<String, Map<Integer, MetricSnapshot>> metrics = taskMetrics.get_metrics(); if (metrics == null) { System.out.println("Failed to get task metrics"); continue; } for (Entry<String, Map<Integer, MetricSnapshot>> entry : metrics.entrySet()) { String key = entry.getKey(); MetricSnapshot metric = entry.getValue().get(window); if (metric == null) { throw new RuntimeException("Failed to get one minute metrics of " + key); } if (metric.get_metricType() == MetricType.COUNTER.getT()) { summary.put(key, (double) metric.get_longValue()); } else if (metric.get_metricType() == MetricType.GAUGE.getT()) { summary.put(key, metric.get_doubleValue()); } else { summary.put(key, metric.get_mean()); } } } return summary; } catch (Exception e) { throw new RuntimeException(e); } finally { if (client != null) { nimbusClient.cleanup(); } } }
[ "public", "static", "Map", "<", "String", ",", "Double", ">", "getMetrics", "(", "Map", "conf", ",", "String", "topologyName", ",", "MetaType", "metricType", ",", "Integer", "window", ")", "{", "NimbusClientWrapper", "nimbusClient", "=", "null", ";", "Iface", "client", "=", "null", ";", "Map", "<", "String", ",", "Double", ">", "summary", "=", "new", "HashMap", "<>", "(", ")", ";", "try", "{", "nimbusClient", "=", "new", "NimbusClientWrapper", "(", ")", ";", "nimbusClient", ".", "init", "(", "conf", ")", ";", "client", "=", "nimbusClient", ".", "getClient", "(", ")", ";", "String", "topologyId", "=", "client", ".", "getTopologyId", "(", "topologyName", ")", ";", "if", "(", "metricType", "==", "null", ")", "{", "metricType", "=", "MetaType", ".", "TASK", ";", "}", "List", "<", "MetricInfo", ">", "allTaskMetrics", "=", "client", ".", "getMetrics", "(", "topologyId", ",", "metricType", ".", "getT", "(", ")", ")", ";", "if", "(", "allTaskMetrics", "==", "null", ")", "{", "throw", "new", "RuntimeException", "(", "\"Failed to get metrics\"", ")", ";", "}", "if", "(", "window", "==", "null", "||", "!", "AsmWindow", ".", "TIME_WINDOWS", ".", "contains", "(", "window", ")", ")", "{", "window", "=", "AsmWindow", ".", "M1_WINDOW", ";", "}", "for", "(", "MetricInfo", "taskMetrics", ":", "allTaskMetrics", ")", "{", "Map", "<", "String", ",", "Map", "<", "Integer", ",", "MetricSnapshot", ">", ">", "metrics", "=", "taskMetrics", ".", "get_metrics", "(", ")", ";", "if", "(", "metrics", "==", "null", ")", "{", "System", ".", "out", ".", "println", "(", "\"Failed to get task metrics\"", ")", ";", "continue", ";", "}", "for", "(", "Entry", "<", "String", ",", "Map", "<", "Integer", ",", "MetricSnapshot", ">", ">", "entry", ":", "metrics", ".", "entrySet", "(", ")", ")", "{", "String", "key", "=", "entry", ".", "getKey", "(", ")", ";", "MetricSnapshot", "metric", "=", "entry", ".", "getValue", "(", ")", ".", "get", "(", "window", ")", ";", "if", "(", "metric", "==", "null", ")", "{", "throw", "new", "RuntimeException", "(", "\"Failed to get one minute metrics of \"", "+", "key", ")", ";", "}", "if", "(", "metric", ".", "get_metricType", "(", ")", "==", "MetricType", ".", "COUNTER", ".", "getT", "(", ")", ")", "{", "summary", ".", "put", "(", "key", ",", "(", "double", ")", "metric", ".", "get_longValue", "(", ")", ")", ";", "}", "else", "if", "(", "metric", ".", "get_metricType", "(", ")", "==", "MetricType", ".", "GAUGE", ".", "getT", "(", ")", ")", "{", "summary", ".", "put", "(", "key", ",", "metric", ".", "get_doubleValue", "(", ")", ")", ";", "}", "else", "{", "summary", ".", "put", "(", "key", ",", "metric", ".", "get_mean", "(", ")", ")", ";", "}", "}", "}", "return", "summary", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "finally", "{", "if", "(", "client", "!=", "null", ")", "{", "nimbusClient", ".", "cleanup", "(", ")", ";", "}", "}", "}" ]
Get Topology Metrics @param topologyName topology name @param metricType, please refer to MetaType, default to MetaType.TASK.getT() @param window, please refer to AsmWindow, default to AsmWindow.M1_WINDOW @return topology metrics
[ "Get", "Topology", "Metrics" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/utils/JStormUtils.java#L1610-L1670
25,355
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/common/metric/old/Timer.java
Timer.time
public <T> T time(Callable<T> event) throws Exception { final long startTime = System.currentTimeMillis(); try { return event.call(); } finally { update(System.currentTimeMillis() - startTime); } }
java
public <T> T time(Callable<T> event) throws Exception { final long startTime = System.currentTimeMillis(); try { return event.call(); } finally { update(System.currentTimeMillis() - startTime); } }
[ "public", "<", "T", ">", "T", "time", "(", "Callable", "<", "T", ">", "event", ")", "throws", "Exception", "{", "final", "long", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "try", "{", "return", "event", ".", "call", "(", ")", ";", "}", "finally", "{", "update", "(", "System", ".", "currentTimeMillis", "(", ")", "-", "startTime", ")", ";", "}", "}" ]
Times and records the duration of event. @param event a {@link Callable} whose {@link Callable#call()} method implements a process whose duration should be timed @param <T> the type of the value returned by {@code event} @return the value returned by {@code event} @throws Exception if {@code event} throws an {@link Exception}
[ "Times", "and", "records", "the", "duration", "of", "event", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/common/metric/old/Timer.java#L84-L91
25,356
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/supervisor/SyncSupervisorEvent.java
SyncSupervisorEvent.getLocalAssign
private Map<Integer, LocalAssignment> getLocalAssign(StormClusterState stormClusterState, String supervisorId, Map<String, Assignment> assignments) throws Exception { Map<Integer, LocalAssignment> portToAssignment = new HashMap<>(); for (Entry<String, Assignment> assignEntry : assignments.entrySet()) { String topologyId = assignEntry.getKey(); Assignment assignment = assignEntry.getValue(); Map<Integer, LocalAssignment> portTasks = readMyTasks(stormClusterState, topologyId, supervisorId, assignment); if (portTasks == null) { continue; } // a port must be assigned to one assignment for (Entry<Integer, LocalAssignment> entry : portTasks.entrySet()) { Integer port = entry.getKey(); LocalAssignment la = entry.getValue(); if (!portToAssignment.containsKey(port)) { portToAssignment.put(port, la); } else { throw new RuntimeException("Should not have multiple topologies assigned to one port"); } } } return portToAssignment; }
java
private Map<Integer, LocalAssignment> getLocalAssign(StormClusterState stormClusterState, String supervisorId, Map<String, Assignment> assignments) throws Exception { Map<Integer, LocalAssignment> portToAssignment = new HashMap<>(); for (Entry<String, Assignment> assignEntry : assignments.entrySet()) { String topologyId = assignEntry.getKey(); Assignment assignment = assignEntry.getValue(); Map<Integer, LocalAssignment> portTasks = readMyTasks(stormClusterState, topologyId, supervisorId, assignment); if (portTasks == null) { continue; } // a port must be assigned to one assignment for (Entry<Integer, LocalAssignment> entry : portTasks.entrySet()) { Integer port = entry.getKey(); LocalAssignment la = entry.getValue(); if (!portToAssignment.containsKey(port)) { portToAssignment.put(port, la); } else { throw new RuntimeException("Should not have multiple topologies assigned to one port"); } } } return portToAssignment; }
[ "private", "Map", "<", "Integer", ",", "LocalAssignment", ">", "getLocalAssign", "(", "StormClusterState", "stormClusterState", ",", "String", "supervisorId", ",", "Map", "<", "String", ",", "Assignment", ">", "assignments", ")", "throws", "Exception", "{", "Map", "<", "Integer", ",", "LocalAssignment", ">", "portToAssignment", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Entry", "<", "String", ",", "Assignment", ">", "assignEntry", ":", "assignments", ".", "entrySet", "(", ")", ")", "{", "String", "topologyId", "=", "assignEntry", ".", "getKey", "(", ")", ";", "Assignment", "assignment", "=", "assignEntry", ".", "getValue", "(", ")", ";", "Map", "<", "Integer", ",", "LocalAssignment", ">", "portTasks", "=", "readMyTasks", "(", "stormClusterState", ",", "topologyId", ",", "supervisorId", ",", "assignment", ")", ";", "if", "(", "portTasks", "==", "null", ")", "{", "continue", ";", "}", "// a port must be assigned to one assignment", "for", "(", "Entry", "<", "Integer", ",", "LocalAssignment", ">", "entry", ":", "portTasks", ".", "entrySet", "(", ")", ")", "{", "Integer", "port", "=", "entry", ".", "getKey", "(", ")", ";", "LocalAssignment", "la", "=", "entry", ".", "getValue", "(", ")", ";", "if", "(", "!", "portToAssignment", ".", "containsKey", "(", "port", ")", ")", "{", "portToAssignment", ".", "put", "(", "port", ",", "la", ")", ";", "}", "else", "{", "throw", "new", "RuntimeException", "(", "\"Should not have multiple topologies assigned to one port\"", ")", ";", "}", "}", "}", "return", "portToAssignment", ";", "}" ]
a port must be assigned to a topology @return map: [port,LocalAssignment]
[ "a", "port", "must", "be", "assigned", "to", "a", "topology" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/supervisor/SyncSupervisorEvent.java#L223-L248
25,357
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/supervisor/SyncSupervisorEvent.java
SyncSupervisorEvent.readMyTasks
@SuppressWarnings("unused") private Map<Integer, LocalAssignment> readMyTasks(StormClusterState stormClusterState, String topologyId, String supervisorId, Assignment assignmentInfo) throws Exception { Map<Integer, LocalAssignment> portTasks = new HashMap<>(); Set<ResourceWorkerSlot> workers = assignmentInfo.getWorkers(); if (workers == null) { LOG.error("No worker found for assignment {}!", assignmentInfo); return portTasks; } for (ResourceWorkerSlot worker : workers) { if (!supervisorId.equals(worker.getNodeId())) { continue; } portTasks.put(worker.getPort(), new LocalAssignment( topologyId, worker.getTasks(), Common.topologyIdToName(topologyId), worker.getMemSize(), worker.getCpu(), worker.getJvm(), assignmentInfo.getTimeStamp())); } return portTasks; }
java
@SuppressWarnings("unused") private Map<Integer, LocalAssignment> readMyTasks(StormClusterState stormClusterState, String topologyId, String supervisorId, Assignment assignmentInfo) throws Exception { Map<Integer, LocalAssignment> portTasks = new HashMap<>(); Set<ResourceWorkerSlot> workers = assignmentInfo.getWorkers(); if (workers == null) { LOG.error("No worker found for assignment {}!", assignmentInfo); return portTasks; } for (ResourceWorkerSlot worker : workers) { if (!supervisorId.equals(worker.getNodeId())) { continue; } portTasks.put(worker.getPort(), new LocalAssignment( topologyId, worker.getTasks(), Common.topologyIdToName(topologyId), worker.getMemSize(), worker.getCpu(), worker.getJvm(), assignmentInfo.getTimeStamp())); } return portTasks; }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "private", "Map", "<", "Integer", ",", "LocalAssignment", ">", "readMyTasks", "(", "StormClusterState", "stormClusterState", ",", "String", "topologyId", ",", "String", "supervisorId", ",", "Assignment", "assignmentInfo", ")", "throws", "Exception", "{", "Map", "<", "Integer", ",", "LocalAssignment", ">", "portTasks", "=", "new", "HashMap", "<>", "(", ")", ";", "Set", "<", "ResourceWorkerSlot", ">", "workers", "=", "assignmentInfo", ".", "getWorkers", "(", ")", ";", "if", "(", "workers", "==", "null", ")", "{", "LOG", ".", "error", "(", "\"No worker found for assignment {}!\"", ",", "assignmentInfo", ")", ";", "return", "portTasks", ";", "}", "for", "(", "ResourceWorkerSlot", "worker", ":", "workers", ")", "{", "if", "(", "!", "supervisorId", ".", "equals", "(", "worker", ".", "getNodeId", "(", ")", ")", ")", "{", "continue", ";", "}", "portTasks", ".", "put", "(", "worker", ".", "getPort", "(", ")", ",", "new", "LocalAssignment", "(", "topologyId", ",", "worker", ".", "getTasks", "(", ")", ",", "Common", ".", "topologyIdToName", "(", "topologyId", ")", ",", "worker", ".", "getMemSize", "(", ")", ",", "worker", ".", "getCpu", "(", ")", ",", "worker", ".", "getJvm", "(", ")", ",", "assignmentInfo", ".", "getTimeStamp", "(", ")", ")", ")", ";", "}", "return", "portTasks", ";", "}" ]
get local node's tasks @return Map: [port, LocalAssignment]
[ "get", "local", "node", "s", "tasks" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/supervisor/SyncSupervisorEvent.java#L255-L276
25,358
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/supervisor/SyncSupervisorEvent.java
SyncSupervisorEvent.getTopologyCodeLocations
public static Map<String, String> getTopologyCodeLocations( Map<String, Assignment> assignments, String supervisorId) throws Exception { Map<String, String> rtn = new HashMap<>(); for (Entry<String, Assignment> entry : assignments.entrySet()) { String topologyId = entry.getKey(); Assignment assignmentInfo = entry.getValue(); Set<ResourceWorkerSlot> workers = assignmentInfo.getWorkers(); for (ResourceWorkerSlot worker : workers) { String node = worker.getNodeId(); if (supervisorId.equals(node)) { rtn.put(topologyId, assignmentInfo.getMasterCodeDir()); break; } } } return rtn; }
java
public static Map<String, String> getTopologyCodeLocations( Map<String, Assignment> assignments, String supervisorId) throws Exception { Map<String, String> rtn = new HashMap<>(); for (Entry<String, Assignment> entry : assignments.entrySet()) { String topologyId = entry.getKey(); Assignment assignmentInfo = entry.getValue(); Set<ResourceWorkerSlot> workers = assignmentInfo.getWorkers(); for (ResourceWorkerSlot worker : workers) { String node = worker.getNodeId(); if (supervisorId.equals(node)) { rtn.put(topologyId, assignmentInfo.getMasterCodeDir()); break; } } } return rtn; }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "getTopologyCodeLocations", "(", "Map", "<", "String", ",", "Assignment", ">", "assignments", ",", "String", "supervisorId", ")", "throws", "Exception", "{", "Map", "<", "String", ",", "String", ">", "rtn", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Entry", "<", "String", ",", "Assignment", ">", "entry", ":", "assignments", ".", "entrySet", "(", ")", ")", "{", "String", "topologyId", "=", "entry", ".", "getKey", "(", ")", ";", "Assignment", "assignmentInfo", "=", "entry", ".", "getValue", "(", ")", ";", "Set", "<", "ResourceWorkerSlot", ">", "workers", "=", "assignmentInfo", ".", "getWorkers", "(", ")", ";", "for", "(", "ResourceWorkerSlot", "worker", ":", "workers", ")", "{", "String", "node", "=", "worker", ".", "getNodeId", "(", ")", ";", "if", "(", "supervisorId", ".", "equals", "(", "node", ")", ")", "{", "rtn", ".", "put", "(", "topologyId", ",", "assignmentInfo", ".", "getMasterCodeDir", "(", ")", ")", ";", "break", ";", "}", "}", "}", "return", "rtn", ";", "}" ]
get master code dir for each topology @return Map: [topologyId, master-code-dir] from zookeeper
[ "get", "master", "code", "dir", "for", "each", "topology" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/supervisor/SyncSupervisorEvent.java#L283-L301
25,359
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/task/OutputCollector.java
OutputCollector.emitDirect
public void emitDirect(int taskId, String streamId, Tuple anchor, List<Object> tuple) { emitDirect(taskId, streamId, Arrays.asList(anchor), tuple); }
java
public void emitDirect(int taskId, String streamId, Tuple anchor, List<Object> tuple) { emitDirect(taskId, streamId, Arrays.asList(anchor), tuple); }
[ "public", "void", "emitDirect", "(", "int", "taskId", ",", "String", "streamId", ",", "Tuple", "anchor", ",", "List", "<", "Object", ">", "tuple", ")", "{", "emitDirect", "(", "taskId", ",", "streamId", ",", "Arrays", ".", "asList", "(", "anchor", ")", ",", "tuple", ")", ";", "}" ]
Emits a tuple directly to the specified task id on the specified stream. If the target bolt does not subscribe to this bolt using a direct grouping, the tuple will not be sent. If the specified output stream is not declared as direct, or the target bolt subscribes with a non-direct grouping, an error will occur at runtime. The emitted values must be immutable. @param taskId the taskId to send the new tuple to @param streamId the stream to send the tuple on. It must be declared as a direct stream in the topology definition. @param anchor the tuple to anchor to @param tuple the new output tuple from this bolt
[ "Emits", "a", "tuple", "directly", "to", "the", "specified", "task", "id", "on", "the", "specified", "stream", ".", "If", "the", "target", "bolt", "does", "not", "subscribe", "to", "this", "bolt", "using", "a", "direct", "grouping", "the", "tuple", "will", "not", "be", "sent", ".", "If", "the", "specified", "output", "stream", "is", "not", "declared", "as", "direct", "or", "the", "target", "bolt", "subscribes", "with", "a", "non", "-", "direct", "grouping", "an", "error", "will", "occur", "at", "runtime", ".", "The", "emitted", "values", "must", "be", "immutable", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/task/OutputCollector.java#L188-L191
25,360
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/JstormOnYarn.java
JstormOnYarn.monitorApplication
private boolean monitorApplication(ApplicationId appId) throws YarnException, IOException { Integer monitorTimes = JOYConstants.MONITOR_TIMES; while (true) { // Check app status every 1 second. try { Thread.sleep(JOYConstants.MONITOR_TIME_INTERVAL); } catch (InterruptedException e) { LOG.debug("Thread sleep in monitoring loop interrupted"); } // Get application report for the appId we are interested in ApplicationReport report = jstormClientContext.yarnClient.getApplicationReport(appId); try { File writename = new File(JOYConstants.RPC_ADDRESS_FILE); writename.createNewFile(); BufferedWriter out = new BufferedWriter(new FileWriter(writename)); out.write(report.getHost() + JOYConstants.NEW_LINE); out.write(report.getRpcPort() + JOYConstants.NEW_LINE); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } LOG.info("Got application report from ASM for" + ", appId=" + appId.getId() + ", clientToAMToken=" + report.getClientToAMToken() + ", appDiagnostics=" + report.getDiagnostics() + ", appMasterHost=" + report.getHost() + ", appQueue=" + report.getQueue() + ", appMasterRpcPort=" + report.getRpcPort() + ", appStartTime=" + report.getStartTime() + ", yarnAppState=" + report.getYarnApplicationState().toString() + ", distributedFinalState=" + report.getFinalApplicationStatus().toString() + ", appTrackingUrl=" + report.getTrackingUrl() + ", appUser=" + report.getUser()); YarnApplicationState state = report.getYarnApplicationState(); FinalApplicationStatus dsStatus = report.getFinalApplicationStatus(); if (YarnApplicationState.FINISHED == state) { if (FinalApplicationStatus.SUCCEEDED == dsStatus) { LOG.info("Application has completed successfully. Breaking monitoring loop"); return true; } else { LOG.info("Application did finished unsuccessfully." + " YarnState=" + state.toString() + ", DSFinalStatus=" + dsStatus.toString() + ". Breaking monitoring loop"); return false; } } else if (YarnApplicationState.KILLED == state || YarnApplicationState.FAILED == state) { LOG.info("Application did not finish." + " YarnState=" + state.toString() + ", DSFinalStatus=" + dsStatus.toString() + ". Breaking monitoring loop"); return false; } else if (YarnApplicationState.RUNNING == state) { LOG.info("Application is running successfully. Breaking monitoring loop"); return true; } else { if (monitorTimes-- <= 0) { forceKillApplication(appId); return false; } } } }
java
private boolean monitorApplication(ApplicationId appId) throws YarnException, IOException { Integer monitorTimes = JOYConstants.MONITOR_TIMES; while (true) { // Check app status every 1 second. try { Thread.sleep(JOYConstants.MONITOR_TIME_INTERVAL); } catch (InterruptedException e) { LOG.debug("Thread sleep in monitoring loop interrupted"); } // Get application report for the appId we are interested in ApplicationReport report = jstormClientContext.yarnClient.getApplicationReport(appId); try { File writename = new File(JOYConstants.RPC_ADDRESS_FILE); writename.createNewFile(); BufferedWriter out = new BufferedWriter(new FileWriter(writename)); out.write(report.getHost() + JOYConstants.NEW_LINE); out.write(report.getRpcPort() + JOYConstants.NEW_LINE); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } LOG.info("Got application report from ASM for" + ", appId=" + appId.getId() + ", clientToAMToken=" + report.getClientToAMToken() + ", appDiagnostics=" + report.getDiagnostics() + ", appMasterHost=" + report.getHost() + ", appQueue=" + report.getQueue() + ", appMasterRpcPort=" + report.getRpcPort() + ", appStartTime=" + report.getStartTime() + ", yarnAppState=" + report.getYarnApplicationState().toString() + ", distributedFinalState=" + report.getFinalApplicationStatus().toString() + ", appTrackingUrl=" + report.getTrackingUrl() + ", appUser=" + report.getUser()); YarnApplicationState state = report.getYarnApplicationState(); FinalApplicationStatus dsStatus = report.getFinalApplicationStatus(); if (YarnApplicationState.FINISHED == state) { if (FinalApplicationStatus.SUCCEEDED == dsStatus) { LOG.info("Application has completed successfully. Breaking monitoring loop"); return true; } else { LOG.info("Application did finished unsuccessfully." + " YarnState=" + state.toString() + ", DSFinalStatus=" + dsStatus.toString() + ". Breaking monitoring loop"); return false; } } else if (YarnApplicationState.KILLED == state || YarnApplicationState.FAILED == state) { LOG.info("Application did not finish." + " YarnState=" + state.toString() + ", DSFinalStatus=" + dsStatus.toString() + ". Breaking monitoring loop"); return false; } else if (YarnApplicationState.RUNNING == state) { LOG.info("Application is running successfully. Breaking monitoring loop"); return true; } else { if (monitorTimes-- <= 0) { forceKillApplication(appId); return false; } } } }
[ "private", "boolean", "monitorApplication", "(", "ApplicationId", "appId", ")", "throws", "YarnException", ",", "IOException", "{", "Integer", "monitorTimes", "=", "JOYConstants", ".", "MONITOR_TIMES", ";", "while", "(", "true", ")", "{", "// Check app status every 1 second.", "try", "{", "Thread", ".", "sleep", "(", "JOYConstants", ".", "MONITOR_TIME_INTERVAL", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "LOG", ".", "debug", "(", "\"Thread sleep in monitoring loop interrupted\"", ")", ";", "}", "// Get application report for the appId we are interested in", "ApplicationReport", "report", "=", "jstormClientContext", ".", "yarnClient", ".", "getApplicationReport", "(", "appId", ")", ";", "try", "{", "File", "writename", "=", "new", "File", "(", "JOYConstants", ".", "RPC_ADDRESS_FILE", ")", ";", "writename", ".", "createNewFile", "(", ")", ";", "BufferedWriter", "out", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "writename", ")", ")", ";", "out", ".", "write", "(", "report", ".", "getHost", "(", ")", "+", "JOYConstants", ".", "NEW_LINE", ")", ";", "out", ".", "write", "(", "report", ".", "getRpcPort", "(", ")", "+", "JOYConstants", ".", "NEW_LINE", ")", ";", "out", ".", "flush", "(", ")", ";", "out", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "LOG", ".", "info", "(", "\"Got application report from ASM for\"", "+", "\", appId=\"", "+", "appId", ".", "getId", "(", ")", "+", "\", clientToAMToken=\"", "+", "report", ".", "getClientToAMToken", "(", ")", "+", "\", appDiagnostics=\"", "+", "report", ".", "getDiagnostics", "(", ")", "+", "\", appMasterHost=\"", "+", "report", ".", "getHost", "(", ")", "+", "\", appQueue=\"", "+", "report", ".", "getQueue", "(", ")", "+", "\", appMasterRpcPort=\"", "+", "report", ".", "getRpcPort", "(", ")", "+", "\", appStartTime=\"", "+", "report", ".", "getStartTime", "(", ")", "+", "\", yarnAppState=\"", "+", "report", ".", "getYarnApplicationState", "(", ")", ".", "toString", "(", ")", "+", "\", distributedFinalState=\"", "+", "report", ".", "getFinalApplicationStatus", "(", ")", ".", "toString", "(", ")", "+", "\", appTrackingUrl=\"", "+", "report", ".", "getTrackingUrl", "(", ")", "+", "\", appUser=\"", "+", "report", ".", "getUser", "(", ")", ")", ";", "YarnApplicationState", "state", "=", "report", ".", "getYarnApplicationState", "(", ")", ";", "FinalApplicationStatus", "dsStatus", "=", "report", ".", "getFinalApplicationStatus", "(", ")", ";", "if", "(", "YarnApplicationState", ".", "FINISHED", "==", "state", ")", "{", "if", "(", "FinalApplicationStatus", ".", "SUCCEEDED", "==", "dsStatus", ")", "{", "LOG", ".", "info", "(", "\"Application has completed successfully. Breaking monitoring loop\"", ")", ";", "return", "true", ";", "}", "else", "{", "LOG", ".", "info", "(", "\"Application did finished unsuccessfully.\"", "+", "\" YarnState=\"", "+", "state", ".", "toString", "(", ")", "+", "\", DSFinalStatus=\"", "+", "dsStatus", ".", "toString", "(", ")", "+", "\". Breaking monitoring loop\"", ")", ";", "return", "false", ";", "}", "}", "else", "if", "(", "YarnApplicationState", ".", "KILLED", "==", "state", "||", "YarnApplicationState", ".", "FAILED", "==", "state", ")", "{", "LOG", ".", "info", "(", "\"Application did not finish.\"", "+", "\" YarnState=\"", "+", "state", ".", "toString", "(", ")", "+", "\", DSFinalStatus=\"", "+", "dsStatus", ".", "toString", "(", ")", "+", "\". Breaking monitoring loop\"", ")", ";", "return", "false", ";", "}", "else", "if", "(", "YarnApplicationState", ".", "RUNNING", "==", "state", ")", "{", "LOG", ".", "info", "(", "\"Application is running successfully. Breaking monitoring loop\"", ")", ";", "return", "true", ";", "}", "else", "{", "if", "(", "monitorTimes", "--", "<=", "0", ")", "{", "forceKillApplication", "(", "appId", ")", ";", "return", "false", ";", "}", "}", "}", "}" ]
Monitor the submitted application for completion. Kill application if time expires. @param appId Application Id of application to be monitored @return true if application completed successfully @throws YarnException @throws IOException
[ "Monitor", "the", "submitted", "application", "for", "completion", ".", "Kill", "application", "if", "time", "expires", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/JstormOnYarn.java#L434-L503
25,361
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/utils/VersionedStore.java
VersionedStore.getAllVersions
public List<Long> getAllVersions() throws IOException { List<Long> ret = new ArrayList<>(); for (String s : listDir(_root)) { if (s.endsWith(FINISHED_VERSION_SUFFIX)) { ret.add(validateAndGetVersion(s)); } } Collections.sort(ret); Collections.reverse(ret); return ret; }
java
public List<Long> getAllVersions() throws IOException { List<Long> ret = new ArrayList<>(); for (String s : listDir(_root)) { if (s.endsWith(FINISHED_VERSION_SUFFIX)) { ret.add(validateAndGetVersion(s)); } } Collections.sort(ret); Collections.reverse(ret); return ret; }
[ "public", "List", "<", "Long", ">", "getAllVersions", "(", ")", "throws", "IOException", "{", "List", "<", "Long", ">", "ret", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "s", ":", "listDir", "(", "_root", ")", ")", "{", "if", "(", "s", ".", "endsWith", "(", "FINISHED_VERSION_SUFFIX", ")", ")", "{", "ret", ".", "add", "(", "validateAndGetVersion", "(", "s", ")", ")", ";", "}", "}", "Collections", ".", "sort", "(", "ret", ")", ";", "Collections", ".", "reverse", "(", "ret", ")", ";", "return", "ret", ";", "}" ]
Sorted from most recent to oldest
[ "Sorted", "from", "most", "recent", "to", "oldest" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/utils/VersionedStore.java#L139-L149
25,362
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/security/serialization/BlowfishTupleSerializer.java
BlowfishTupleSerializer.main
public static void main(String[] args) { try { KeyGenerator kgen = KeyGenerator.getInstance("Blowfish"); SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); String keyString = new String(Hex.encodeHex(raw)); System.out.println("storm -c " + SECRET_KEY + "=" + keyString + " -c " + Config.TOPOLOGY_TUPLE_SERIALIZER + "=" + BlowfishTupleSerializer.class.getName() + " ..."); } catch (Exception ex) { LOG.error(ex.getMessage()); ex.printStackTrace(); } }
java
public static void main(String[] args) { try { KeyGenerator kgen = KeyGenerator.getInstance("Blowfish"); SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); String keyString = new String(Hex.encodeHex(raw)); System.out.println("storm -c " + SECRET_KEY + "=" + keyString + " -c " + Config.TOPOLOGY_TUPLE_SERIALIZER + "=" + BlowfishTupleSerializer.class.getName() + " ..."); } catch (Exception ex) { LOG.error(ex.getMessage()); ex.printStackTrace(); } }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "try", "{", "KeyGenerator", "kgen", "=", "KeyGenerator", ".", "getInstance", "(", "\"Blowfish\"", ")", ";", "SecretKey", "skey", "=", "kgen", ".", "generateKey", "(", ")", ";", "byte", "[", "]", "raw", "=", "skey", ".", "getEncoded", "(", ")", ";", "String", "keyString", "=", "new", "String", "(", "Hex", ".", "encodeHex", "(", "raw", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"storm -c \"", "+", "SECRET_KEY", "+", "\"=\"", "+", "keyString", "+", "\" -c \"", "+", "Config", ".", "TOPOLOGY_TUPLE_SERIALIZER", "+", "\"=\"", "+", "BlowfishTupleSerializer", ".", "class", ".", "getName", "(", ")", "+", "\" ...\"", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOG", ".", "error", "(", "ex", ".", "getMessage", "(", ")", ")", ";", "ex", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Produce a blowfish key to be used in "Storm jar" command
[ "Produce", "a", "blowfish", "key", "to", "be", "used", "in", "Storm", "jar", "command" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/security/serialization/BlowfishTupleSerializer.java#L79-L91
25,363
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/container/Executor.java
Executor.checkHeartBeat
public boolean checkHeartBeat() { String dataPath = executorMeta.getLocalDir(); File localstate = new File(dataPath + "/data/" + startType + "/" + startType + ".heartbeat/"); Long modefyTime = localstate.lastModified(); if (System.currentTimeMillis() - modefyTime > JOYConstants.EXECUTOR_HEARTBEAT_TIMEOUT) { LOG.info("----------------------"); modefyTime = localstate.lastModified(); LOG.info(modefyTime.toString()); LOG.info(Long.toString(new Date().getTime())); LOG.info(dataPath + "/data/" + startType + "/" + startType + ".heartbeat/"); LOG.info("can't get heartbeat over " + String.valueOf(JOYConstants.EXECUTOR_HEARTBEAT_TIMEOUT) + " seconds"); return false; } else return true; }
java
public boolean checkHeartBeat() { String dataPath = executorMeta.getLocalDir(); File localstate = new File(dataPath + "/data/" + startType + "/" + startType + ".heartbeat/"); Long modefyTime = localstate.lastModified(); if (System.currentTimeMillis() - modefyTime > JOYConstants.EXECUTOR_HEARTBEAT_TIMEOUT) { LOG.info("----------------------"); modefyTime = localstate.lastModified(); LOG.info(modefyTime.toString()); LOG.info(Long.toString(new Date().getTime())); LOG.info(dataPath + "/data/" + startType + "/" + startType + ".heartbeat/"); LOG.info("can't get heartbeat over " + String.valueOf(JOYConstants.EXECUTOR_HEARTBEAT_TIMEOUT) + " seconds"); return false; } else return true; }
[ "public", "boolean", "checkHeartBeat", "(", ")", "{", "String", "dataPath", "=", "executorMeta", ".", "getLocalDir", "(", ")", ";", "File", "localstate", "=", "new", "File", "(", "dataPath", "+", "\"/data/\"", "+", "startType", "+", "\"/\"", "+", "startType", "+", "\".heartbeat/\"", ")", ";", "Long", "modefyTime", "=", "localstate", ".", "lastModified", "(", ")", ";", "if", "(", "System", ".", "currentTimeMillis", "(", ")", "-", "modefyTime", ">", "JOYConstants", ".", "EXECUTOR_HEARTBEAT_TIMEOUT", ")", "{", "LOG", ".", "info", "(", "\"----------------------\"", ")", ";", "modefyTime", "=", "localstate", ".", "lastModified", "(", ")", ";", "LOG", ".", "info", "(", "modefyTime", ".", "toString", "(", ")", ")", ";", "LOG", ".", "info", "(", "Long", ".", "toString", "(", "new", "Date", "(", ")", ".", "getTime", "(", ")", ")", ")", ";", "LOG", ".", "info", "(", "dataPath", "+", "\"/data/\"", "+", "startType", "+", "\"/\"", "+", "startType", "+", "\".heartbeat/\"", ")", ";", "LOG", ".", "info", "(", "\"can't get heartbeat over \"", "+", "String", ".", "valueOf", "(", "JOYConstants", ".", "EXECUTOR_HEARTBEAT_TIMEOUT", ")", "+", "\" seconds\"", ")", ";", "return", "false", ";", "}", "else", "return", "true", ";", "}" ]
check supervisor's heartBeat, @return
[ "check", "supervisor", "s", "heartBeat" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/container/Executor.java#L84-L103
25,364
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/container/Executor.java
Executor.setJstormConf
public boolean setJstormConf(String key, String value) { //todo: how to set conf from a signal // could pull configuration file from nimbus String line = " " + key + ": " + value; try { Files.write(Paths.get("deploy/jstorm/conf/storm.yaml"), line.getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { LOG.error(e); return false; } return true; }
java
public boolean setJstormConf(String key, String value) { //todo: how to set conf from a signal // could pull configuration file from nimbus String line = " " + key + ": " + value; try { Files.write(Paths.get("deploy/jstorm/conf/storm.yaml"), line.getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { LOG.error(e); return false; } return true; }
[ "public", "boolean", "setJstormConf", "(", "String", "key", ",", "String", "value", ")", "{", "//todo: how to set conf from a signal", "// could pull configuration file from nimbus", "String", "line", "=", "\" \"", "+", "key", "+", "\": \"", "+", "value", ";", "try", "{", "Files", ".", "write", "(", "Paths", ".", "get", "(", "\"deploy/jstorm/conf/storm.yaml\"", ")", ",", "line", ".", "getBytes", "(", ")", ",", "StandardOpenOption", ".", "APPEND", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "error", "(", "e", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
set local conf @param key @param value @return
[ "set", "local", "conf" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/container/Executor.java#L284-L296
25,365
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/schedule/default_assign/DefaultTopologyAssignContext.java
DefaultTopologyAssignContext.generateSidToHost
private Map<String, String> generateSidToHost() { Map<String, String> sidToHostname = new HashMap<>(); if (oldAssignment != null) { sidToHostname.putAll(oldAssignment.getNodeHost()); } for (Entry<String, SupervisorInfo> entry : cluster.entrySet()) { String supervisorId = entry.getKey(); SupervisorInfo supervisorInfo = entry.getValue(); sidToHostname.put(supervisorId, supervisorInfo.getHostName()); } return sidToHostname; }
java
private Map<String, String> generateSidToHost() { Map<String, String> sidToHostname = new HashMap<>(); if (oldAssignment != null) { sidToHostname.putAll(oldAssignment.getNodeHost()); } for (Entry<String, SupervisorInfo> entry : cluster.entrySet()) { String supervisorId = entry.getKey(); SupervisorInfo supervisorInfo = entry.getValue(); sidToHostname.put(supervisorId, supervisorInfo.getHostName()); } return sidToHostname; }
[ "private", "Map", "<", "String", ",", "String", ">", "generateSidToHost", "(", ")", "{", "Map", "<", "String", ",", "String", ">", "sidToHostname", "=", "new", "HashMap", "<>", "(", ")", ";", "if", "(", "oldAssignment", "!=", "null", ")", "{", "sidToHostname", ".", "putAll", "(", "oldAssignment", ".", "getNodeHost", "(", ")", ")", ";", "}", "for", "(", "Entry", "<", "String", ",", "SupervisorInfo", ">", "entry", ":", "cluster", ".", "entrySet", "(", ")", ")", "{", "String", "supervisorId", "=", "entry", ".", "getKey", "(", ")", ";", "SupervisorInfo", "supervisorInfo", "=", "entry", ".", "getValue", "(", ")", ";", "sidToHostname", ".", "put", "(", "supervisorId", ",", "supervisorInfo", ".", "getHostName", "(", ")", ")", ";", "}", "return", "sidToHostname", ";", "}" ]
Do we need just handle the case when type is ASSIGN_TYPE_NEW?
[ "Do", "we", "need", "just", "handle", "the", "case", "when", "type", "is", "ASSIGN_TYPE_NEW?" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/schedule/default_assign/DefaultTopologyAssignContext.java#L137-L152
25,366
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/utils/NetWorkUtils.java
NetWorkUtils.tryPort
public static int tryPort(int port) throws IOException { ServerSocket socket = new ServerSocket(port); int rtn = socket.getLocalPort(); socket.close(); return rtn; }
java
public static int tryPort(int port) throws IOException { ServerSocket socket = new ServerSocket(port); int rtn = socket.getLocalPort(); socket.close(); return rtn; }
[ "public", "static", "int", "tryPort", "(", "int", "port", ")", "throws", "IOException", "{", "ServerSocket", "socket", "=", "new", "ServerSocket", "(", "port", ")", ";", "int", "rtn", "=", "socket", ".", "getLocalPort", "(", ")", ";", "socket", ".", "close", "(", ")", ";", "return", "rtn", ";", "}" ]
Check whether the port is available to bind @param port port @return -1 means unavailable, otherwise available @throws IOException
[ "Check", "whether", "the", "port", "is", "available", "to", "bind" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/utils/NetWorkUtils.java#L68-L73
25,367
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java
TopologyAssign.get_cleanup_ids
private Set<String> get_cleanup_ids(StormClusterState clusterState, List<String> activeTopologies) throws Exception { List<String> task_ids = clusterState.task_storms(); List<String> heartbeat_ids = clusterState.heartbeat_storms(); List<String> error_ids = clusterState.task_error_storms(); List<String> assignment_ids = clusterState.assignments(null); List<String> metric_ids = clusterState.get_metrics(); HashSet<String> latest_code_ids = new HashSet<>(); Set<String> code_ids = BlobStoreUtils.code_ids(nimbusData.getBlobStore()); Set<String> to_cleanup_ids = new HashSet<>(); Set<String> pendingTopologies = nimbusData.getPendingSubmitTopologies().buildMap().keySet(); if (task_ids != null) { to_cleanup_ids.addAll(task_ids); } if (heartbeat_ids != null) { to_cleanup_ids.addAll(heartbeat_ids); } if (error_ids != null) { to_cleanup_ids.addAll(error_ids); } if (assignment_ids != null) { to_cleanup_ids.addAll(assignment_ids); } if (code_ids != null) { to_cleanup_ids.addAll(code_ids); } if (metric_ids != null) { to_cleanup_ids.addAll(metric_ids); } if (activeTopologies != null) { to_cleanup_ids.removeAll(activeTopologies); latest_code_ids.removeAll(activeTopologies); } to_cleanup_ids.removeAll(pendingTopologies); /** * Why need to remove latest code. Due to competition between Thrift.threads and TopologyAssign thread */ to_cleanup_ids.removeAll(latest_code_ids); LOG.info("Skip removing topology of " + latest_code_ids); return to_cleanup_ids; }
java
private Set<String> get_cleanup_ids(StormClusterState clusterState, List<String> activeTopologies) throws Exception { List<String> task_ids = clusterState.task_storms(); List<String> heartbeat_ids = clusterState.heartbeat_storms(); List<String> error_ids = clusterState.task_error_storms(); List<String> assignment_ids = clusterState.assignments(null); List<String> metric_ids = clusterState.get_metrics(); HashSet<String> latest_code_ids = new HashSet<>(); Set<String> code_ids = BlobStoreUtils.code_ids(nimbusData.getBlobStore()); Set<String> to_cleanup_ids = new HashSet<>(); Set<String> pendingTopologies = nimbusData.getPendingSubmitTopologies().buildMap().keySet(); if (task_ids != null) { to_cleanup_ids.addAll(task_ids); } if (heartbeat_ids != null) { to_cleanup_ids.addAll(heartbeat_ids); } if (error_ids != null) { to_cleanup_ids.addAll(error_ids); } if (assignment_ids != null) { to_cleanup_ids.addAll(assignment_ids); } if (code_ids != null) { to_cleanup_ids.addAll(code_ids); } if (metric_ids != null) { to_cleanup_ids.addAll(metric_ids); } if (activeTopologies != null) { to_cleanup_ids.removeAll(activeTopologies); latest_code_ids.removeAll(activeTopologies); } to_cleanup_ids.removeAll(pendingTopologies); /** * Why need to remove latest code. Due to competition between Thrift.threads and TopologyAssign thread */ to_cleanup_ids.removeAll(latest_code_ids); LOG.info("Skip removing topology of " + latest_code_ids); return to_cleanup_ids; }
[ "private", "Set", "<", "String", ">", "get_cleanup_ids", "(", "StormClusterState", "clusterState", ",", "List", "<", "String", ">", "activeTopologies", ")", "throws", "Exception", "{", "List", "<", "String", ">", "task_ids", "=", "clusterState", ".", "task_storms", "(", ")", ";", "List", "<", "String", ">", "heartbeat_ids", "=", "clusterState", ".", "heartbeat_storms", "(", ")", ";", "List", "<", "String", ">", "error_ids", "=", "clusterState", ".", "task_error_storms", "(", ")", ";", "List", "<", "String", ">", "assignment_ids", "=", "clusterState", ".", "assignments", "(", "null", ")", ";", "List", "<", "String", ">", "metric_ids", "=", "clusterState", ".", "get_metrics", "(", ")", ";", "HashSet", "<", "String", ">", "latest_code_ids", "=", "new", "HashSet", "<>", "(", ")", ";", "Set", "<", "String", ">", "code_ids", "=", "BlobStoreUtils", ".", "code_ids", "(", "nimbusData", ".", "getBlobStore", "(", ")", ")", ";", "Set", "<", "String", ">", "to_cleanup_ids", "=", "new", "HashSet", "<>", "(", ")", ";", "Set", "<", "String", ">", "pendingTopologies", "=", "nimbusData", ".", "getPendingSubmitTopologies", "(", ")", ".", "buildMap", "(", ")", ".", "keySet", "(", ")", ";", "if", "(", "task_ids", "!=", "null", ")", "{", "to_cleanup_ids", ".", "addAll", "(", "task_ids", ")", ";", "}", "if", "(", "heartbeat_ids", "!=", "null", ")", "{", "to_cleanup_ids", ".", "addAll", "(", "heartbeat_ids", ")", ";", "}", "if", "(", "error_ids", "!=", "null", ")", "{", "to_cleanup_ids", ".", "addAll", "(", "error_ids", ")", ";", "}", "if", "(", "assignment_ids", "!=", "null", ")", "{", "to_cleanup_ids", ".", "addAll", "(", "assignment_ids", ")", ";", "}", "if", "(", "code_ids", "!=", "null", ")", "{", "to_cleanup_ids", ".", "addAll", "(", "code_ids", ")", ";", "}", "if", "(", "metric_ids", "!=", "null", ")", "{", "to_cleanup_ids", ".", "addAll", "(", "metric_ids", ")", ";", "}", "if", "(", "activeTopologies", "!=", "null", ")", "{", "to_cleanup_ids", ".", "removeAll", "(", "activeTopologies", ")", ";", "latest_code_ids", ".", "removeAll", "(", "activeTopologies", ")", ";", "}", "to_cleanup_ids", ".", "removeAll", "(", "pendingTopologies", ")", ";", "/**\n * Why need to remove latest code. Due to competition between Thrift.threads and TopologyAssign thread\n */", "to_cleanup_ids", ".", "removeAll", "(", "latest_code_ids", ")", ";", "LOG", ".", "info", "(", "\"Skip removing topology of \"", "+", "latest_code_ids", ")", ";", "return", "to_cleanup_ids", ";", "}" ]
get topology ids that need to be cleaned up
[ "get", "topology", "ids", "that", "need", "to", "be", "cleaned", "up" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java#L232-L283
25,368
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java
TopologyAssign.mkAssignment
public Assignment mkAssignment(TopologyAssignEvent event) throws Exception { String topologyId = event.getTopologyId(); LOG.info("Determining assignment for " + topologyId); TopologyAssignContext context = prepareTopologyAssign(event); Set<ResourceWorkerSlot> assignments; if (!StormConfig.local_mode(nimbusData.getConf())) { IToplogyScheduler scheduler = schedulers.get(DEFAULT_SCHEDULER_NAME); assignments = scheduler.assignTasks(context); } else { assignments = mkLocalAssignment(context); } Assignment assignment = null; if (assignments != null && assignments.size() > 0) { Map<String, String> nodeHost = getTopologyNodeHost( context.getCluster(), context.getOldAssignment(), assignments); Map<Integer, Integer> startTimes = getTaskStartTimes( context, nimbusData, topologyId, context.getOldAssignment(), assignments); String codeDir = (String) nimbusData.getConf().get(Config.STORM_LOCAL_DIR); assignment = new Assignment(codeDir, assignments, nodeHost, startTimes); // the topology binary changed. if (event.isScaleTopology()) { assignment.setAssignmentType(Assignment.AssignmentType.ScaleTopology); } StormClusterState stormClusterState = nimbusData.getStormClusterState(); stormClusterState.set_assignment(topologyId, assignment); // update task heartbeat's start time NimbusUtils.updateTaskHbStartTime(nimbusData, assignment, topologyId); // Update metrics information in ZK when rebalance or reassignment // Only update metrics monitor status when creating topology // if (context.getAssignType() == // TopologyAssignContext.ASSIGN_TYPE_REBALANCE // || context.getAssignType() == // TopologyAssignContext.ASSIGN_TYPE_MONITOR) // NimbusUtils.updateMetricsInfo(nimbusData, topologyId, assignment); NimbusUtils.updateTopologyTaskTimeout(nimbusData, topologyId); LOG.info("Successfully make assignment for topology id " + topologyId + ": " + assignment); } return assignment; }
java
public Assignment mkAssignment(TopologyAssignEvent event) throws Exception { String topologyId = event.getTopologyId(); LOG.info("Determining assignment for " + topologyId); TopologyAssignContext context = prepareTopologyAssign(event); Set<ResourceWorkerSlot> assignments; if (!StormConfig.local_mode(nimbusData.getConf())) { IToplogyScheduler scheduler = schedulers.get(DEFAULT_SCHEDULER_NAME); assignments = scheduler.assignTasks(context); } else { assignments = mkLocalAssignment(context); } Assignment assignment = null; if (assignments != null && assignments.size() > 0) { Map<String, String> nodeHost = getTopologyNodeHost( context.getCluster(), context.getOldAssignment(), assignments); Map<Integer, Integer> startTimes = getTaskStartTimes( context, nimbusData, topologyId, context.getOldAssignment(), assignments); String codeDir = (String) nimbusData.getConf().get(Config.STORM_LOCAL_DIR); assignment = new Assignment(codeDir, assignments, nodeHost, startTimes); // the topology binary changed. if (event.isScaleTopology()) { assignment.setAssignmentType(Assignment.AssignmentType.ScaleTopology); } StormClusterState stormClusterState = nimbusData.getStormClusterState(); stormClusterState.set_assignment(topologyId, assignment); // update task heartbeat's start time NimbusUtils.updateTaskHbStartTime(nimbusData, assignment, topologyId); // Update metrics information in ZK when rebalance or reassignment // Only update metrics monitor status when creating topology // if (context.getAssignType() == // TopologyAssignContext.ASSIGN_TYPE_REBALANCE // || context.getAssignType() == // TopologyAssignContext.ASSIGN_TYPE_MONITOR) // NimbusUtils.updateMetricsInfo(nimbusData, topologyId, assignment); NimbusUtils.updateTopologyTaskTimeout(nimbusData, topologyId); LOG.info("Successfully make assignment for topology id " + topologyId + ": " + assignment); } return assignment; }
[ "public", "Assignment", "mkAssignment", "(", "TopologyAssignEvent", "event", ")", "throws", "Exception", "{", "String", "topologyId", "=", "event", ".", "getTopologyId", "(", ")", ";", "LOG", ".", "info", "(", "\"Determining assignment for \"", "+", "topologyId", ")", ";", "TopologyAssignContext", "context", "=", "prepareTopologyAssign", "(", "event", ")", ";", "Set", "<", "ResourceWorkerSlot", ">", "assignments", ";", "if", "(", "!", "StormConfig", ".", "local_mode", "(", "nimbusData", ".", "getConf", "(", ")", ")", ")", "{", "IToplogyScheduler", "scheduler", "=", "schedulers", ".", "get", "(", "DEFAULT_SCHEDULER_NAME", ")", ";", "assignments", "=", "scheduler", ".", "assignTasks", "(", "context", ")", ";", "}", "else", "{", "assignments", "=", "mkLocalAssignment", "(", "context", ")", ";", "}", "Assignment", "assignment", "=", "null", ";", "if", "(", "assignments", "!=", "null", "&&", "assignments", ".", "size", "(", ")", ">", "0", ")", "{", "Map", "<", "String", ",", "String", ">", "nodeHost", "=", "getTopologyNodeHost", "(", "context", ".", "getCluster", "(", ")", ",", "context", ".", "getOldAssignment", "(", ")", ",", "assignments", ")", ";", "Map", "<", "Integer", ",", "Integer", ">", "startTimes", "=", "getTaskStartTimes", "(", "context", ",", "nimbusData", ",", "topologyId", ",", "context", ".", "getOldAssignment", "(", ")", ",", "assignments", ")", ";", "String", "codeDir", "=", "(", "String", ")", "nimbusData", ".", "getConf", "(", ")", ".", "get", "(", "Config", ".", "STORM_LOCAL_DIR", ")", ";", "assignment", "=", "new", "Assignment", "(", "codeDir", ",", "assignments", ",", "nodeHost", ",", "startTimes", ")", ";", "// the topology binary changed.", "if", "(", "event", ".", "isScaleTopology", "(", ")", ")", "{", "assignment", ".", "setAssignmentType", "(", "Assignment", ".", "AssignmentType", ".", "ScaleTopology", ")", ";", "}", "StormClusterState", "stormClusterState", "=", "nimbusData", ".", "getStormClusterState", "(", ")", ";", "stormClusterState", ".", "set_assignment", "(", "topologyId", ",", "assignment", ")", ";", "// update task heartbeat's start time", "NimbusUtils", ".", "updateTaskHbStartTime", "(", "nimbusData", ",", "assignment", ",", "topologyId", ")", ";", "// Update metrics information in ZK when rebalance or reassignment", "// Only update metrics monitor status when creating topology", "// if (context.getAssignType() ==", "// TopologyAssignContext.ASSIGN_TYPE_REBALANCE", "// || context.getAssignType() ==", "// TopologyAssignContext.ASSIGN_TYPE_MONITOR)", "// NimbusUtils.updateMetricsInfo(nimbusData, topologyId, assignment);", "NimbusUtils", ".", "updateTopologyTaskTimeout", "(", "nimbusData", ",", "topologyId", ")", ";", "LOG", ".", "info", "(", "\"Successfully make assignment for topology id \"", "+", "topologyId", "+", "\": \"", "+", "assignment", ")", ";", "}", "return", "assignment", ";", "}" ]
make assignments for a topology The nimbus core function, this function has been totally rewrite @throws Exception
[ "make", "assignments", "for", "a", "topology", "The", "nimbus", "core", "function", "this", "function", "has", "been", "totally", "rewrite" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java#L439-L486
25,369
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java
TopologyAssign.getNewOrChangedTaskIds
public static Set<Integer> getNewOrChangedTaskIds(Set<ResourceWorkerSlot> oldWorkers, Set<ResourceWorkerSlot> workers) { Set<Integer> rtn = new HashSet<>(); HashMap<String, ResourceWorkerSlot> workerPortMap = HostPortToWorkerMap(oldWorkers); for (ResourceWorkerSlot worker : workers) { ResourceWorkerSlot oldWorker = workerPortMap.get(worker.getHostPort()); if (oldWorker != null) { Set<Integer> oldTasks = oldWorker.getTasks(); for (Integer task : worker.getTasks()) { if (!(oldTasks.contains(task))) rtn.add(task); } } else { if (worker.getTasks() != null) { rtn.addAll(worker.getTasks()); } } } return rtn; }
java
public static Set<Integer> getNewOrChangedTaskIds(Set<ResourceWorkerSlot> oldWorkers, Set<ResourceWorkerSlot> workers) { Set<Integer> rtn = new HashSet<>(); HashMap<String, ResourceWorkerSlot> workerPortMap = HostPortToWorkerMap(oldWorkers); for (ResourceWorkerSlot worker : workers) { ResourceWorkerSlot oldWorker = workerPortMap.get(worker.getHostPort()); if (oldWorker != null) { Set<Integer> oldTasks = oldWorker.getTasks(); for (Integer task : worker.getTasks()) { if (!(oldTasks.contains(task))) rtn.add(task); } } else { if (worker.getTasks() != null) { rtn.addAll(worker.getTasks()); } } } return rtn; }
[ "public", "static", "Set", "<", "Integer", ">", "getNewOrChangedTaskIds", "(", "Set", "<", "ResourceWorkerSlot", ">", "oldWorkers", ",", "Set", "<", "ResourceWorkerSlot", ">", "workers", ")", "{", "Set", "<", "Integer", ">", "rtn", "=", "new", "HashSet", "<>", "(", ")", ";", "HashMap", "<", "String", ",", "ResourceWorkerSlot", ">", "workerPortMap", "=", "HostPortToWorkerMap", "(", "oldWorkers", ")", ";", "for", "(", "ResourceWorkerSlot", "worker", ":", "workers", ")", "{", "ResourceWorkerSlot", "oldWorker", "=", "workerPortMap", ".", "get", "(", "worker", ".", "getHostPort", "(", ")", ")", ";", "if", "(", "oldWorker", "!=", "null", ")", "{", "Set", "<", "Integer", ">", "oldTasks", "=", "oldWorker", ".", "getTasks", "(", ")", ";", "for", "(", "Integer", "task", ":", "worker", ".", "getTasks", "(", ")", ")", "{", "if", "(", "!", "(", "oldTasks", ".", "contains", "(", "task", ")", ")", ")", "rtn", ".", "add", "(", "task", ")", ";", "}", "}", "else", "{", "if", "(", "worker", ".", "getTasks", "(", ")", "!=", "null", ")", "{", "rtn", ".", "addAll", "(", "worker", ".", "getTasks", "(", ")", ")", ";", "}", "}", "}", "return", "rtn", ";", "}" ]
get all task ids which are newly assigned or reassigned
[ "get", "all", "task", "ids", "which", "are", "newly", "assigned", "or", "reassigned" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java#L595-L613
25,370
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java
TopologyAssign.sortSlots
public static List<WorkerSlot> sortSlots(Set<WorkerSlot> allSlots, int needSlotNum) { Map<String, List<WorkerSlot>> nodeMap = new HashMap<>(); // group by first for (WorkerSlot np : allSlots) { String node = np.getNodeId(); List<WorkerSlot> list = nodeMap.get(node); if (list == null) { list = new ArrayList<>(); nodeMap.put(node, list); } list.add(np); } for (Entry<String, List<WorkerSlot>> entry : nodeMap.entrySet()) { List<WorkerSlot> ports = entry.getValue(); Collections.sort(ports, new Comparator<WorkerSlot>() { @Override public int compare(WorkerSlot first, WorkerSlot second) { String firstNode = first.getNodeId(); String secondNode = second.getNodeId(); if (!firstNode.equals(secondNode)) { return firstNode.compareTo(secondNode); } else { return first.getPort() - second.getPort(); } } }); } // interleave List<List<WorkerSlot>> splitup = new ArrayList<>(nodeMap.values()); Collections.sort(splitup, new Comparator<List<WorkerSlot>>() { public int compare(List<WorkerSlot> o1, List<WorkerSlot> o2) { return o2.size() - o1.size(); } }); List<WorkerSlot> sortedFreeSlots = JStormUtils.interleave_all(splitup); if (sortedFreeSlots.size() <= needSlotNum) { return sortedFreeSlots; } // sortedFreeSlots > needSlotNum return sortedFreeSlots.subList(0, needSlotNum); }
java
public static List<WorkerSlot> sortSlots(Set<WorkerSlot> allSlots, int needSlotNum) { Map<String, List<WorkerSlot>> nodeMap = new HashMap<>(); // group by first for (WorkerSlot np : allSlots) { String node = np.getNodeId(); List<WorkerSlot> list = nodeMap.get(node); if (list == null) { list = new ArrayList<>(); nodeMap.put(node, list); } list.add(np); } for (Entry<String, List<WorkerSlot>> entry : nodeMap.entrySet()) { List<WorkerSlot> ports = entry.getValue(); Collections.sort(ports, new Comparator<WorkerSlot>() { @Override public int compare(WorkerSlot first, WorkerSlot second) { String firstNode = first.getNodeId(); String secondNode = second.getNodeId(); if (!firstNode.equals(secondNode)) { return firstNode.compareTo(secondNode); } else { return first.getPort() - second.getPort(); } } }); } // interleave List<List<WorkerSlot>> splitup = new ArrayList<>(nodeMap.values()); Collections.sort(splitup, new Comparator<List<WorkerSlot>>() { public int compare(List<WorkerSlot> o1, List<WorkerSlot> o2) { return o2.size() - o1.size(); } }); List<WorkerSlot> sortedFreeSlots = JStormUtils.interleave_all(splitup); if (sortedFreeSlots.size() <= needSlotNum) { return sortedFreeSlots; } // sortedFreeSlots > needSlotNum return sortedFreeSlots.subList(0, needSlotNum); }
[ "public", "static", "List", "<", "WorkerSlot", ">", "sortSlots", "(", "Set", "<", "WorkerSlot", ">", "allSlots", ",", "int", "needSlotNum", ")", "{", "Map", "<", "String", ",", "List", "<", "WorkerSlot", ">", ">", "nodeMap", "=", "new", "HashMap", "<>", "(", ")", ";", "// group by first", "for", "(", "WorkerSlot", "np", ":", "allSlots", ")", "{", "String", "node", "=", "np", ".", "getNodeId", "(", ")", ";", "List", "<", "WorkerSlot", ">", "list", "=", "nodeMap", ".", "get", "(", "node", ")", ";", "if", "(", "list", "==", "null", ")", "{", "list", "=", "new", "ArrayList", "<>", "(", ")", ";", "nodeMap", ".", "put", "(", "node", ",", "list", ")", ";", "}", "list", ".", "add", "(", "np", ")", ";", "}", "for", "(", "Entry", "<", "String", ",", "List", "<", "WorkerSlot", ">", ">", "entry", ":", "nodeMap", ".", "entrySet", "(", ")", ")", "{", "List", "<", "WorkerSlot", ">", "ports", "=", "entry", ".", "getValue", "(", ")", ";", "Collections", ".", "sort", "(", "ports", ",", "new", "Comparator", "<", "WorkerSlot", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "WorkerSlot", "first", ",", "WorkerSlot", "second", ")", "{", "String", "firstNode", "=", "first", ".", "getNodeId", "(", ")", ";", "String", "secondNode", "=", "second", ".", "getNodeId", "(", ")", ";", "if", "(", "!", "firstNode", ".", "equals", "(", "secondNode", ")", ")", "{", "return", "firstNode", ".", "compareTo", "(", "secondNode", ")", ";", "}", "else", "{", "return", "first", ".", "getPort", "(", ")", "-", "second", ".", "getPort", "(", ")", ";", "}", "}", "}", ")", ";", "}", "// interleave", "List", "<", "List", "<", "WorkerSlot", ">", ">", "splitup", "=", "new", "ArrayList", "<>", "(", "nodeMap", ".", "values", "(", ")", ")", ";", "Collections", ".", "sort", "(", "splitup", ",", "new", "Comparator", "<", "List", "<", "WorkerSlot", ">", ">", "(", ")", "{", "public", "int", "compare", "(", "List", "<", "WorkerSlot", ">", "o1", ",", "List", "<", "WorkerSlot", ">", "o2", ")", "{", "return", "o2", ".", "size", "(", ")", "-", "o1", ".", "size", "(", ")", ";", "}", "}", ")", ";", "List", "<", "WorkerSlot", ">", "sortedFreeSlots", "=", "JStormUtils", ".", "interleave_all", "(", "splitup", ")", ";", "if", "(", "sortedFreeSlots", ".", "size", "(", ")", "<=", "needSlotNum", ")", "{", "return", "sortedFreeSlots", ";", "}", "// sortedFreeSlots > needSlotNum", "return", "sortedFreeSlots", ".", "subList", "(", "0", ",", "needSlotNum", ")", ";", "}" ]
sort slots, the purpose is to ensure that the tasks are assigned in balancing @return List<WorkerSlot>
[ "sort", "slots", "the", "purpose", "is", "to", "ensure", "that", "the", "tasks", "are", "assigned", "in", "balancing" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java#L648-L697
25,371
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java
TopologyAssign.getUnstoppedSlots
public Set<Integer> getUnstoppedSlots(Set<Integer> aliveTasks, Map<String, SupervisorInfo> supInfos, Assignment existAssignment) { Set<Integer> ret = new HashSet<>(); Set<ResourceWorkerSlot> oldWorkers = existAssignment.getWorkers(); Set<String> aliveSupervisors = supInfos.keySet(); for (ResourceWorkerSlot worker : oldWorkers) { for (Integer taskId : worker.getTasks()) { if (!aliveTasks.contains(taskId)) { // task is dead continue; } String oldTaskSupervisorId = worker.getNodeId(); if (!aliveSupervisors.contains(oldTaskSupervisorId)) { // supervisor is dead ret.add(taskId); } } } return ret; }
java
public Set<Integer> getUnstoppedSlots(Set<Integer> aliveTasks, Map<String, SupervisorInfo> supInfos, Assignment existAssignment) { Set<Integer> ret = new HashSet<>(); Set<ResourceWorkerSlot> oldWorkers = existAssignment.getWorkers(); Set<String> aliveSupervisors = supInfos.keySet(); for (ResourceWorkerSlot worker : oldWorkers) { for (Integer taskId : worker.getTasks()) { if (!aliveTasks.contains(taskId)) { // task is dead continue; } String oldTaskSupervisorId = worker.getNodeId(); if (!aliveSupervisors.contains(oldTaskSupervisorId)) { // supervisor is dead ret.add(taskId); } } } return ret; }
[ "public", "Set", "<", "Integer", ">", "getUnstoppedSlots", "(", "Set", "<", "Integer", ">", "aliveTasks", ",", "Map", "<", "String", ",", "SupervisorInfo", ">", "supInfos", ",", "Assignment", "existAssignment", ")", "{", "Set", "<", "Integer", ">", "ret", "=", "new", "HashSet", "<>", "(", ")", ";", "Set", "<", "ResourceWorkerSlot", ">", "oldWorkers", "=", "existAssignment", ".", "getWorkers", "(", ")", ";", "Set", "<", "String", ">", "aliveSupervisors", "=", "supInfos", ".", "keySet", "(", ")", ";", "for", "(", "ResourceWorkerSlot", "worker", ":", "oldWorkers", ")", "{", "for", "(", "Integer", "taskId", ":", "worker", ".", "getTasks", "(", ")", ")", "{", "if", "(", "!", "aliveTasks", ".", "contains", "(", "taskId", ")", ")", "{", "// task is dead", "continue", ";", "}", "String", "oldTaskSupervisorId", "=", "worker", ".", "getNodeId", "(", ")", ";", "if", "(", "!", "aliveSupervisors", ".", "contains", "(", "oldTaskSupervisorId", ")", ")", "{", "// supervisor is dead", "ret", ".", "add", "(", "taskId", ")", ";", "}", "}", "}", "return", "ret", ";", "}" ]
Get unstopped slots from alive task list
[ "Get", "unstopped", "slots", "from", "alive", "task", "list" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java#L702-L724
25,372
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java
TopologyAssign.getFreeSlots
public static void getFreeSlots(Map<String, SupervisorInfo> supervisorInfos, StormClusterState stormClusterState) throws Exception { Map<String, Assignment> assignments = Cluster.get_all_assignment(stormClusterState, null); for (Entry<String, Assignment> entry : assignments.entrySet()) { Assignment assignment = entry.getValue(); Set<ResourceWorkerSlot> workers = assignment.getWorkers(); for (ResourceWorkerSlot worker : workers) { SupervisorInfo supervisorInfo = supervisorInfos.get(worker.getNodeId()); if (supervisorInfo == null) { // the supervisor is dead continue; } supervisorInfo.getAvailableWorkerPorts().remove(worker.getPort()); } } }
java
public static void getFreeSlots(Map<String, SupervisorInfo> supervisorInfos, StormClusterState stormClusterState) throws Exception { Map<String, Assignment> assignments = Cluster.get_all_assignment(stormClusterState, null); for (Entry<String, Assignment> entry : assignments.entrySet()) { Assignment assignment = entry.getValue(); Set<ResourceWorkerSlot> workers = assignment.getWorkers(); for (ResourceWorkerSlot worker : workers) { SupervisorInfo supervisorInfo = supervisorInfos.get(worker.getNodeId()); if (supervisorInfo == null) { // the supervisor is dead continue; } supervisorInfo.getAvailableWorkerPorts().remove(worker.getPort()); } } }
[ "public", "static", "void", "getFreeSlots", "(", "Map", "<", "String", ",", "SupervisorInfo", ">", "supervisorInfos", ",", "StormClusterState", "stormClusterState", ")", "throws", "Exception", "{", "Map", "<", "String", ",", "Assignment", ">", "assignments", "=", "Cluster", ".", "get_all_assignment", "(", "stormClusterState", ",", "null", ")", ";", "for", "(", "Entry", "<", "String", ",", "Assignment", ">", "entry", ":", "assignments", ".", "entrySet", "(", ")", ")", "{", "Assignment", "assignment", "=", "entry", ".", "getValue", "(", ")", ";", "Set", "<", "ResourceWorkerSlot", ">", "workers", "=", "assignment", ".", "getWorkers", "(", ")", ";", "for", "(", "ResourceWorkerSlot", "worker", ":", "workers", ")", "{", "SupervisorInfo", "supervisorInfo", "=", "supervisorInfos", ".", "get", "(", "worker", ".", "getNodeId", "(", ")", ")", ";", "if", "(", "supervisorInfo", "==", "null", ")", "{", "// the supervisor is dead", "continue", ";", "}", "supervisorInfo", ".", "getAvailableWorkerPorts", "(", ")", ".", "remove", "(", "worker", ".", "getPort", "(", ")", ")", ";", "}", "}", "}" ]
Get free resources
[ "Get", "free", "resources" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java#L746-L761
25,373
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java
TopologyAssign.getAliveTasks
public Set<Integer> getAliveTasks(String topologyId, Set<Integer> taskIds) throws Exception { Set<Integer> aliveTasks = new HashSet<>(); // taskIds is the list from ZK /ZK-DIR/tasks/topologyId for (int taskId : taskIds) { boolean isDead = NimbusUtils.isTaskDead(nimbusData, topologyId, taskId); if (!isDead) { aliveTasks.add(taskId); } } return aliveTasks; }
java
public Set<Integer> getAliveTasks(String topologyId, Set<Integer> taskIds) throws Exception { Set<Integer> aliveTasks = new HashSet<>(); // taskIds is the list from ZK /ZK-DIR/tasks/topologyId for (int taskId : taskIds) { boolean isDead = NimbusUtils.isTaskDead(nimbusData, topologyId, taskId); if (!isDead) { aliveTasks.add(taskId); } } return aliveTasks; }
[ "public", "Set", "<", "Integer", ">", "getAliveTasks", "(", "String", "topologyId", ",", "Set", "<", "Integer", ">", "taskIds", ")", "throws", "Exception", "{", "Set", "<", "Integer", ">", "aliveTasks", "=", "new", "HashSet", "<>", "(", ")", ";", "// taskIds is the list from ZK /ZK-DIR/tasks/topologyId", "for", "(", "int", "taskId", ":", "taskIds", ")", "{", "boolean", "isDead", "=", "NimbusUtils", ".", "isTaskDead", "(", "nimbusData", ",", "topologyId", ",", "taskId", ")", ";", "if", "(", "!", "isDead", ")", "{", "aliveTasks", ".", "add", "(", "taskId", ")", ";", "}", "}", "return", "aliveTasks", ";", "}" ]
find all alive task ids. Do not assume that clocks are synchronized. Task heartbeat is only used so that nimbus knows when it's received a new heartbeat. All timing is done by nimbus and tracked through task-heartbeat-cache @return Set<Integer> : task id set
[ "find", "all", "alive", "task", "ids", ".", "Do", "not", "assume", "that", "clocks", "are", "synchronized", ".", "Task", "heartbeat", "is", "only", "used", "so", "that", "nimbus", "knows", "when", "it", "s", "received", "a", "new", "heartbeat", ".", "All", "timing", "is", "done", "by", "nimbus", "and", "tracked", "through", "task", "-", "heartbeat", "-", "cache" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java#L770-L781
25,374
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java
TopologyAssign.backupAssignment
public void backupAssignment(Assignment assignment, TopologyAssignEvent event) { String topologyId = event.getTopologyId(); String topologyName = event.getTopologyName(); try { StormClusterState zkClusterState = nimbusData.getStormClusterState(); // one little problem, get tasks twice when assign one topology Map<Integer, String> tasks = Cluster.get_all_task_component(zkClusterState, topologyId, null); Map<String, List<Integer>> componentTasks = JStormUtils.reverse_map(tasks); for (Entry<String, List<Integer>> entry : componentTasks.entrySet()) { List<Integer> keys = entry.getValue(); Collections.sort(keys); } AssignmentBak assignmentBak = new AssignmentBak(componentTasks, assignment); zkClusterState.backup_assignment(topologyName, assignmentBak); } catch (Exception e) { LOG.warn("Failed to backup " + topologyId + " assignment " + assignment, e); } }
java
public void backupAssignment(Assignment assignment, TopologyAssignEvent event) { String topologyId = event.getTopologyId(); String topologyName = event.getTopologyName(); try { StormClusterState zkClusterState = nimbusData.getStormClusterState(); // one little problem, get tasks twice when assign one topology Map<Integer, String> tasks = Cluster.get_all_task_component(zkClusterState, topologyId, null); Map<String, List<Integer>> componentTasks = JStormUtils.reverse_map(tasks); for (Entry<String, List<Integer>> entry : componentTasks.entrySet()) { List<Integer> keys = entry.getValue(); Collections.sort(keys); } AssignmentBak assignmentBak = new AssignmentBak(componentTasks, assignment); zkClusterState.backup_assignment(topologyName, assignmentBak); } catch (Exception e) { LOG.warn("Failed to backup " + topologyId + " assignment " + assignment, e); } }
[ "public", "void", "backupAssignment", "(", "Assignment", "assignment", ",", "TopologyAssignEvent", "event", ")", "{", "String", "topologyId", "=", "event", ".", "getTopologyId", "(", ")", ";", "String", "topologyName", "=", "event", ".", "getTopologyName", "(", ")", ";", "try", "{", "StormClusterState", "zkClusterState", "=", "nimbusData", ".", "getStormClusterState", "(", ")", ";", "// one little problem, get tasks twice when assign one topology", "Map", "<", "Integer", ",", "String", ">", "tasks", "=", "Cluster", ".", "get_all_task_component", "(", "zkClusterState", ",", "topologyId", ",", "null", ")", ";", "Map", "<", "String", ",", "List", "<", "Integer", ">", ">", "componentTasks", "=", "JStormUtils", ".", "reverse_map", "(", "tasks", ")", ";", "for", "(", "Entry", "<", "String", ",", "List", "<", "Integer", ">", ">", "entry", ":", "componentTasks", ".", "entrySet", "(", ")", ")", "{", "List", "<", "Integer", ">", "keys", "=", "entry", ".", "getValue", "(", ")", ";", "Collections", ".", "sort", "(", "keys", ")", ";", "}", "AssignmentBak", "assignmentBak", "=", "new", "AssignmentBak", "(", "componentTasks", ",", "assignment", ")", ";", "zkClusterState", ".", "backup_assignment", "(", "topologyName", ",", "assignmentBak", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "warn", "(", "\"Failed to backup \"", "+", "topologyId", "+", "\" assignment \"", "+", "assignment", ",", "e", ")", ";", "}", "}" ]
Backup topology assignment to ZK todo: Do we need to do backup operation every time?
[ "Backup", "topology", "assignment", "to", "ZK" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java#L809-L830
25,375
alibaba/jstorm
jstorm-core/src/main/java/storm/trident/topology/TridentTopologyBuilder.java
TridentTopologyBuilder.setBolt
public BoltDeclarer setBolt(String id, ITridentBatchBolt bolt, Integer parallelism, Set<String> committerBatches, Map<String, String> batchGroups) { markBatchGroups(id, batchGroups); Component c = new Component(bolt, parallelism, committerBatches); _bolts.put(id, c); return new BoltDeclarerImpl(c); }
java
public BoltDeclarer setBolt(String id, ITridentBatchBolt bolt, Integer parallelism, Set<String> committerBatches, Map<String, String> batchGroups) { markBatchGroups(id, batchGroups); Component c = new Component(bolt, parallelism, committerBatches); _bolts.put(id, c); return new BoltDeclarerImpl(c); }
[ "public", "BoltDeclarer", "setBolt", "(", "String", "id", ",", "ITridentBatchBolt", "bolt", ",", "Integer", "parallelism", ",", "Set", "<", "String", ">", "committerBatches", ",", "Map", "<", "String", ",", "String", ">", "batchGroups", ")", "{", "markBatchGroups", "(", "id", ",", "batchGroups", ")", ";", "Component", "c", "=", "new", "Component", "(", "bolt", ",", "parallelism", ",", "committerBatches", ")", ";", "_bolts", ".", "put", "(", "id", ",", "c", ")", ";", "return", "new", "BoltDeclarerImpl", "(", "c", ")", ";", "}" ]
map from stream name to batch id
[ "map", "from", "stream", "name", "to", "batch", "id" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/storm/trident/topology/TridentTopologyBuilder.java#L67-L73
25,376
alibaba/jstorm
jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/HdfsSpout.java
HdfsSpout.commitProgress
private void commitProgress(FileOffset position) { if(position==null) { return; } if ( lock!=null && canCommitNow() ) { try { String pos = position.toString(); lock.heartbeat(pos); LOG.debug("{} Committed progress. {}", spoutId, pos); acksSinceLastCommit = 0; commitTimeElapsed.set(false); setupCommitElapseTimer(); } catch (IOException e) { LOG.error("Unable to commit progress Will retry later. Spout ID = " + spoutId, e); } } }
java
private void commitProgress(FileOffset position) { if(position==null) { return; } if ( lock!=null && canCommitNow() ) { try { String pos = position.toString(); lock.heartbeat(pos); LOG.debug("{} Committed progress. {}", spoutId, pos); acksSinceLastCommit = 0; commitTimeElapsed.set(false); setupCommitElapseTimer(); } catch (IOException e) { LOG.error("Unable to commit progress Will retry later. Spout ID = " + spoutId, e); } } }
[ "private", "void", "commitProgress", "(", "FileOffset", "position", ")", "{", "if", "(", "position", "==", "null", ")", "{", "return", ";", "}", "if", "(", "lock", "!=", "null", "&&", "canCommitNow", "(", ")", ")", "{", "try", "{", "String", "pos", "=", "position", ".", "toString", "(", ")", ";", "lock", ".", "heartbeat", "(", "pos", ")", ";", "LOG", ".", "debug", "(", "\"{} Committed progress. {}\"", ",", "spoutId", ",", "pos", ")", ";", "acksSinceLastCommit", "=", "0", ";", "commitTimeElapsed", ".", "set", "(", "false", ")", ";", "setupCommitElapseTimer", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "error", "(", "\"Unable to commit progress Will retry later. Spout ID = \"", "+", "spoutId", ",", "e", ")", ";", "}", "}", "}" ]
will commit progress into lock file if commit threshold is reached
[ "will", "commit", "progress", "into", "lock", "file", "if", "commit", "threshold", "is", "reached" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/HdfsSpout.java#L192-L208
25,377
alibaba/jstorm
jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/HdfsSpout.java
HdfsSpout.getOldestExpiredLock
private FileLock getOldestExpiredLock() throws IOException { // 1 - acquire lock on dir DirLock dirlock = DirLock.tryLock(hdfs, lockDirPath); if (dirlock == null) { dirlock = DirLock.takeOwnershipIfStale(hdfs, lockDirPath, lockTimeoutSec); if (dirlock == null) { LOG.debug("Spout {} could not take over ownership of DirLock for {}", spoutId, lockDirPath); return null; } LOG.debug("Spout {} now took over ownership of abandoned DirLock for {}", spoutId, lockDirPath); } else { LOG.debug("Spout {} now owns DirLock for {}", spoutId, lockDirPath); } try { // 2 - if clocks are in sync then simply take ownership of the oldest expired lock if (clocksInSync) { return FileLock.acquireOldestExpiredLock(hdfs, lockDirPath, lockTimeoutSec, spoutId); } // 3 - if clocks are not in sync .. if( lastExpiredLock == null ) { // just make a note of the oldest expired lock now and check if its still unmodified after lockTimeoutSec lastExpiredLock = FileLock.locateOldestExpiredLock(hdfs, lockDirPath, lockTimeoutSec); lastExpiredLockTime = System.currentTimeMillis(); return null; } // see if lockTimeoutSec time has elapsed since we last selected the lock file if( hasExpired(lastExpiredLockTime) ) { return null; } // If lock file has expired, then own it FileLock.LogEntry lastEntry = FileLock.getLastEntry(hdfs, lastExpiredLock.getKey()); if( lastEntry.equals(lastExpiredLock.getValue()) ) { FileLock result = FileLock.takeOwnership(hdfs, lastExpiredLock.getKey(), lastEntry, spoutId); lastExpiredLock = null; return result; } else { // if lock file has been updated since last time, then leave this lock file alone lastExpiredLock = null; return null; } } finally { dirlock.release(); LOG.debug("Released DirLock {}, SpoutID {} ", dirlock.getLockFile(), spoutId); } }
java
private FileLock getOldestExpiredLock() throws IOException { // 1 - acquire lock on dir DirLock dirlock = DirLock.tryLock(hdfs, lockDirPath); if (dirlock == null) { dirlock = DirLock.takeOwnershipIfStale(hdfs, lockDirPath, lockTimeoutSec); if (dirlock == null) { LOG.debug("Spout {} could not take over ownership of DirLock for {}", spoutId, lockDirPath); return null; } LOG.debug("Spout {} now took over ownership of abandoned DirLock for {}", spoutId, lockDirPath); } else { LOG.debug("Spout {} now owns DirLock for {}", spoutId, lockDirPath); } try { // 2 - if clocks are in sync then simply take ownership of the oldest expired lock if (clocksInSync) { return FileLock.acquireOldestExpiredLock(hdfs, lockDirPath, lockTimeoutSec, spoutId); } // 3 - if clocks are not in sync .. if( lastExpiredLock == null ) { // just make a note of the oldest expired lock now and check if its still unmodified after lockTimeoutSec lastExpiredLock = FileLock.locateOldestExpiredLock(hdfs, lockDirPath, lockTimeoutSec); lastExpiredLockTime = System.currentTimeMillis(); return null; } // see if lockTimeoutSec time has elapsed since we last selected the lock file if( hasExpired(lastExpiredLockTime) ) { return null; } // If lock file has expired, then own it FileLock.LogEntry lastEntry = FileLock.getLastEntry(hdfs, lastExpiredLock.getKey()); if( lastEntry.equals(lastExpiredLock.getValue()) ) { FileLock result = FileLock.takeOwnership(hdfs, lastExpiredLock.getKey(), lastEntry, spoutId); lastExpiredLock = null; return result; } else { // if lock file has been updated since last time, then leave this lock file alone lastExpiredLock = null; return null; } } finally { dirlock.release(); LOG.debug("Released DirLock {}, SpoutID {} ", dirlock.getLockFile(), spoutId); } }
[ "private", "FileLock", "getOldestExpiredLock", "(", ")", "throws", "IOException", "{", "// 1 - acquire lock on dir", "DirLock", "dirlock", "=", "DirLock", ".", "tryLock", "(", "hdfs", ",", "lockDirPath", ")", ";", "if", "(", "dirlock", "==", "null", ")", "{", "dirlock", "=", "DirLock", ".", "takeOwnershipIfStale", "(", "hdfs", ",", "lockDirPath", ",", "lockTimeoutSec", ")", ";", "if", "(", "dirlock", "==", "null", ")", "{", "LOG", ".", "debug", "(", "\"Spout {} could not take over ownership of DirLock for {}\"", ",", "spoutId", ",", "lockDirPath", ")", ";", "return", "null", ";", "}", "LOG", ".", "debug", "(", "\"Spout {} now took over ownership of abandoned DirLock for {}\"", ",", "spoutId", ",", "lockDirPath", ")", ";", "}", "else", "{", "LOG", ".", "debug", "(", "\"Spout {} now owns DirLock for {}\"", ",", "spoutId", ",", "lockDirPath", ")", ";", "}", "try", "{", "// 2 - if clocks are in sync then simply take ownership of the oldest expired lock", "if", "(", "clocksInSync", ")", "{", "return", "FileLock", ".", "acquireOldestExpiredLock", "(", "hdfs", ",", "lockDirPath", ",", "lockTimeoutSec", ",", "spoutId", ")", ";", "}", "// 3 - if clocks are not in sync ..", "if", "(", "lastExpiredLock", "==", "null", ")", "{", "// just make a note of the oldest expired lock now and check if its still unmodified after lockTimeoutSec", "lastExpiredLock", "=", "FileLock", ".", "locateOldestExpiredLock", "(", "hdfs", ",", "lockDirPath", ",", "lockTimeoutSec", ")", ";", "lastExpiredLockTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "return", "null", ";", "}", "// see if lockTimeoutSec time has elapsed since we last selected the lock file", "if", "(", "hasExpired", "(", "lastExpiredLockTime", ")", ")", "{", "return", "null", ";", "}", "// If lock file has expired, then own it", "FileLock", ".", "LogEntry", "lastEntry", "=", "FileLock", ".", "getLastEntry", "(", "hdfs", ",", "lastExpiredLock", ".", "getKey", "(", ")", ")", ";", "if", "(", "lastEntry", ".", "equals", "(", "lastExpiredLock", ".", "getValue", "(", ")", ")", ")", "{", "FileLock", "result", "=", "FileLock", ".", "takeOwnership", "(", "hdfs", ",", "lastExpiredLock", ".", "getKey", "(", ")", ",", "lastEntry", ",", "spoutId", ")", ";", "lastExpiredLock", "=", "null", ";", "return", "result", ";", "}", "else", "{", "// if lock file has been updated since last time, then leave this lock file alone", "lastExpiredLock", "=", "null", ";", "return", "null", ";", "}", "}", "finally", "{", "dirlock", ".", "release", "(", ")", ";", "LOG", ".", "debug", "(", "\"Released DirLock {}, SpoutID {} \"", ",", "dirlock", ".", "getLockFile", "(", ")", ",", "spoutId", ")", ";", "}", "}" ]
If clocks in sync, then acquires the oldest expired lock Else, on first call, just remembers the oldest expired lock, on next call check if the lock is updated. if not updated then acquires the lock @return a lock object @throws IOException
[ "If", "clocks", "in", "sync", "then", "acquires", "the", "oldest", "expired", "lock", "Else", "on", "first", "call", "just", "remembers", "the", "oldest", "expired", "lock", "on", "next", "call", "check", "if", "the", "lock", "is", "updated", ".", "if", "not", "updated", "then", "acquires", "the", "lock" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/HdfsSpout.java#L538-L585
25,378
alibaba/jstorm
jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/HdfsSpout.java
HdfsSpout.createFileReader
private FileReader createFileReader(Path file) throws IOException { if(readerType.equalsIgnoreCase(Configs.SEQ)) { return new SequenceFileReader(this.hdfs, file, conf); } if(readerType.equalsIgnoreCase(Configs.TEXT)) { return new TextFileReader(this.hdfs, file, conf); } try { Class<?> clsType = Class.forName(readerType); Constructor<?> constructor = clsType.getConstructor(FileSystem.class, Path.class, Map.class); return (FileReader) constructor.newInstance(this.hdfs, file, conf); } catch (Exception e) { LOG.error(e.getMessage(), e); throw new RuntimeException("Unable to instantiate " + readerType + " reader", e); } }
java
private FileReader createFileReader(Path file) throws IOException { if(readerType.equalsIgnoreCase(Configs.SEQ)) { return new SequenceFileReader(this.hdfs, file, conf); } if(readerType.equalsIgnoreCase(Configs.TEXT)) { return new TextFileReader(this.hdfs, file, conf); } try { Class<?> clsType = Class.forName(readerType); Constructor<?> constructor = clsType.getConstructor(FileSystem.class, Path.class, Map.class); return (FileReader) constructor.newInstance(this.hdfs, file, conf); } catch (Exception e) { LOG.error(e.getMessage(), e); throw new RuntimeException("Unable to instantiate " + readerType + " reader", e); } }
[ "private", "FileReader", "createFileReader", "(", "Path", "file", ")", "throws", "IOException", "{", "if", "(", "readerType", ".", "equalsIgnoreCase", "(", "Configs", ".", "SEQ", ")", ")", "{", "return", "new", "SequenceFileReader", "(", "this", ".", "hdfs", ",", "file", ",", "conf", ")", ";", "}", "if", "(", "readerType", ".", "equalsIgnoreCase", "(", "Configs", ".", "TEXT", ")", ")", "{", "return", "new", "TextFileReader", "(", "this", ".", "hdfs", ",", "file", ",", "conf", ")", ";", "}", "try", "{", "Class", "<", "?", ">", "clsType", "=", "Class", ".", "forName", "(", "readerType", ")", ";", "Constructor", "<", "?", ">", "constructor", "=", "clsType", ".", "getConstructor", "(", "FileSystem", ".", "class", ",", "Path", ".", "class", ",", "Map", ".", "class", ")", ";", "return", "(", "FileReader", ")", "constructor", ".", "newInstance", "(", "this", ".", "hdfs", ",", "file", ",", "conf", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "throw", "new", "RuntimeException", "(", "\"Unable to instantiate \"", "+", "readerType", "+", "\" reader\"", ",", "e", ")", ";", "}", "}" ]
Creates a reader that reads from beginning of file @param file file to read @return @throws IOException
[ "Creates", "a", "reader", "that", "reads", "from", "beginning", "of", "file" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/HdfsSpout.java#L597-L613
25,379
alibaba/jstorm
jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/HdfsSpout.java
HdfsSpout.renameToInProgressFile
private Path renameToInProgressFile(Path file) throws IOException { Path newFile = new Path( file.toString() + inprogress_suffix ); try { if (hdfs.rename(file, newFile)) { return newFile; } throw new RenameException(file, newFile); } catch (IOException e){ throw new RenameException(file, newFile, e); } }
java
private Path renameToInProgressFile(Path file) throws IOException { Path newFile = new Path( file.toString() + inprogress_suffix ); try { if (hdfs.rename(file, newFile)) { return newFile; } throw new RenameException(file, newFile); } catch (IOException e){ throw new RenameException(file, newFile, e); } }
[ "private", "Path", "renameToInProgressFile", "(", "Path", "file", ")", "throws", "IOException", "{", "Path", "newFile", "=", "new", "Path", "(", "file", ".", "toString", "(", ")", "+", "inprogress_suffix", ")", ";", "try", "{", "if", "(", "hdfs", ".", "rename", "(", "file", ",", "newFile", ")", ")", "{", "return", "newFile", ";", "}", "throw", "new", "RenameException", "(", "file", ",", "newFile", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RenameException", "(", "file", ",", "newFile", ",", "e", ")", ";", "}", "}" ]
Renames files with .inprogress suffix @return path of renamed file @throws if operation fails
[ "Renames", "files", "with", ".", "inprogress", "suffix" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/HdfsSpout.java#L647-L658
25,380
alibaba/jstorm
jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/HdfsSpout.java
HdfsSpout.getFileForLockFile
private Path getFileForLockFile(Path lockFile, Path sourceDirPath) throws IOException { String lockFileName = lockFile.getName(); Path dataFile = new Path(sourceDirPath + Path.SEPARATOR + lockFileName + inprogress_suffix); if( hdfs.exists(dataFile) ) { return dataFile; } dataFile = new Path(sourceDirPath + Path.SEPARATOR + lockFileName); if(hdfs.exists(dataFile)) { return dataFile; } return null; }
java
private Path getFileForLockFile(Path lockFile, Path sourceDirPath) throws IOException { String lockFileName = lockFile.getName(); Path dataFile = new Path(sourceDirPath + Path.SEPARATOR + lockFileName + inprogress_suffix); if( hdfs.exists(dataFile) ) { return dataFile; } dataFile = new Path(sourceDirPath + Path.SEPARATOR + lockFileName); if(hdfs.exists(dataFile)) { return dataFile; } return null; }
[ "private", "Path", "getFileForLockFile", "(", "Path", "lockFile", ",", "Path", "sourceDirPath", ")", "throws", "IOException", "{", "String", "lockFileName", "=", "lockFile", ".", "getName", "(", ")", ";", "Path", "dataFile", "=", "new", "Path", "(", "sourceDirPath", "+", "Path", ".", "SEPARATOR", "+", "lockFileName", "+", "inprogress_suffix", ")", ";", "if", "(", "hdfs", ".", "exists", "(", "dataFile", ")", ")", "{", "return", "dataFile", ";", "}", "dataFile", "=", "new", "Path", "(", "sourceDirPath", "+", "Path", ".", "SEPARATOR", "+", "lockFileName", ")", ";", "if", "(", "hdfs", ".", "exists", "(", "dataFile", ")", ")", "{", "return", "dataFile", ";", "}", "return", "null", ";", "}" ]
Returns the corresponding input file in the 'sourceDirPath' for the specified lock file. If no such file is found then returns null
[ "Returns", "the", "corresponding", "input", "file", "in", "the", "sourceDirPath", "for", "the", "specified", "lock", "file", ".", "If", "no", "such", "file", "is", "found", "then", "returns", "null" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/HdfsSpout.java#L663-L675
25,381
alibaba/jstorm
jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/HdfsSpout.java
HdfsSpout.renameCompletedFile
private Path renameCompletedFile(Path file) throws IOException { String fileName = file.toString(); String fileNameMinusSuffix = fileName.substring(0, fileName.indexOf(inprogress_suffix)); String newName = new Path(fileNameMinusSuffix).getName(); Path newFile = new Path( archiveDirPath + Path.SEPARATOR + newName ); LOG.info("Completed consuming file {}", fileNameMinusSuffix); if (!hdfs.rename(file, newFile) ) { throw new IOException("Rename failed for file: " + file); } LOG.debug("Renamed file {} to {} ", file, newFile); return newFile; }
java
private Path renameCompletedFile(Path file) throws IOException { String fileName = file.toString(); String fileNameMinusSuffix = fileName.substring(0, fileName.indexOf(inprogress_suffix)); String newName = new Path(fileNameMinusSuffix).getName(); Path newFile = new Path( archiveDirPath + Path.SEPARATOR + newName ); LOG.info("Completed consuming file {}", fileNameMinusSuffix); if (!hdfs.rename(file, newFile) ) { throw new IOException("Rename failed for file: " + file); } LOG.debug("Renamed file {} to {} ", file, newFile); return newFile; }
[ "private", "Path", "renameCompletedFile", "(", "Path", "file", ")", "throws", "IOException", "{", "String", "fileName", "=", "file", ".", "toString", "(", ")", ";", "String", "fileNameMinusSuffix", "=", "fileName", ".", "substring", "(", "0", ",", "fileName", ".", "indexOf", "(", "inprogress_suffix", ")", ")", ";", "String", "newName", "=", "new", "Path", "(", "fileNameMinusSuffix", ")", ".", "getName", "(", ")", ";", "Path", "newFile", "=", "new", "Path", "(", "archiveDirPath", "+", "Path", ".", "SEPARATOR", "+", "newName", ")", ";", "LOG", ".", "info", "(", "\"Completed consuming file {}\"", ",", "fileNameMinusSuffix", ")", ";", "if", "(", "!", "hdfs", ".", "rename", "(", "file", ",", "newFile", ")", ")", "{", "throw", "new", "IOException", "(", "\"Rename failed for file: \"", "+", "file", ")", ";", "}", "LOG", ".", "debug", "(", "\"Renamed file {} to {} \"", ",", "file", ",", "newFile", ")", ";", "return", "newFile", ";", "}" ]
renames files and returns the new file path
[ "renames", "files", "and", "returns", "the", "new", "file", "path" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/HdfsSpout.java#L679-L691
25,382
alibaba/jstorm
example/sequence-split-merge/src/main/java/com/alibaba/starter/utils/JStormHelper.java
JStormHelper.mkStormZkClusterState
@Deprecated public static StormZkClusterState mkStormZkClusterState(Map conf) throws Exception { Map realConf = getFullConf(conf); return new StormZkClusterState(realConf); }
java
@Deprecated public static StormZkClusterState mkStormZkClusterState(Map conf) throws Exception { Map realConf = getFullConf(conf); return new StormZkClusterState(realConf); }
[ "@", "Deprecated", "public", "static", "StormZkClusterState", "mkStormZkClusterState", "(", "Map", "conf", ")", "throws", "Exception", "{", "Map", "realConf", "=", "getFullConf", "(", "conf", ")", ";", "return", "new", "StormZkClusterState", "(", "realConf", ")", ";", "}" ]
This function bring some hacks to JStorm, this isn't a good way
[ "This", "function", "bring", "some", "hacks", "to", "JStorm", "this", "isn", "t", "a", "good", "way" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alibaba/starter/utils/JStormHelper.java#L190-L195
25,383
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/message/netty/NettyServer.java
NettyServer.enqueue
public void enqueue(TaskMessage message, Channel channel) { // lots of messages may be lost when deserialize queue hasn't finished init operation while (!bstartRec) { LOG.info("check whether deserialize queues have already been created"); boolean isFinishInit = true; for (Integer task : workerTasks) { if (deserializeQueues.get(task) == null) { isFinishInit = false; JStormUtils.sleepMs(10); break; } } if (isFinishInit) { bstartRec = isFinishInit; } } short type = message.get_type(); if (type == TaskMessage.NORMAL_MESSAGE) { // enqueue a received message int task = message.task(); DisruptorQueue queue = deserializeQueues.get(task); if (queue == null) { LOG.warn("Received invalid message directed at task {}. Dropping...", task); LOG.debug("Message data: {}", JStormUtils.toPrintableString(message.message())); return; } if (!isBackpressureEnable) { queue.publish(message.message()); } else { flowCtrlHandler.flowCtrl(channel, queue, task, message.message()); } } else if (type == TaskMessage.CONTROL_MESSAGE) { // enqueue a control message if (recvControlQueue == null) { LOG.info("Can not find the recvControlQueue. Dropping this control message"); return; } recvControlQueue.publish(message); } else { LOG.warn("Unexpected message (type={}) was received from task {}", type, message.task()); } }
java
public void enqueue(TaskMessage message, Channel channel) { // lots of messages may be lost when deserialize queue hasn't finished init operation while (!bstartRec) { LOG.info("check whether deserialize queues have already been created"); boolean isFinishInit = true; for (Integer task : workerTasks) { if (deserializeQueues.get(task) == null) { isFinishInit = false; JStormUtils.sleepMs(10); break; } } if (isFinishInit) { bstartRec = isFinishInit; } } short type = message.get_type(); if (type == TaskMessage.NORMAL_MESSAGE) { // enqueue a received message int task = message.task(); DisruptorQueue queue = deserializeQueues.get(task); if (queue == null) { LOG.warn("Received invalid message directed at task {}. Dropping...", task); LOG.debug("Message data: {}", JStormUtils.toPrintableString(message.message())); return; } if (!isBackpressureEnable) { queue.publish(message.message()); } else { flowCtrlHandler.flowCtrl(channel, queue, task, message.message()); } } else if (type == TaskMessage.CONTROL_MESSAGE) { // enqueue a control message if (recvControlQueue == null) { LOG.info("Can not find the recvControlQueue. Dropping this control message"); return; } recvControlQueue.publish(message); } else { LOG.warn("Unexpected message (type={}) was received from task {}", type, message.task()); } }
[ "public", "void", "enqueue", "(", "TaskMessage", "message", ",", "Channel", "channel", ")", "{", "// lots of messages may be lost when deserialize queue hasn't finished init operation", "while", "(", "!", "bstartRec", ")", "{", "LOG", ".", "info", "(", "\"check whether deserialize queues have already been created\"", ")", ";", "boolean", "isFinishInit", "=", "true", ";", "for", "(", "Integer", "task", ":", "workerTasks", ")", "{", "if", "(", "deserializeQueues", ".", "get", "(", "task", ")", "==", "null", ")", "{", "isFinishInit", "=", "false", ";", "JStormUtils", ".", "sleepMs", "(", "10", ")", ";", "break", ";", "}", "}", "if", "(", "isFinishInit", ")", "{", "bstartRec", "=", "isFinishInit", ";", "}", "}", "short", "type", "=", "message", ".", "get_type", "(", ")", ";", "if", "(", "type", "==", "TaskMessage", ".", "NORMAL_MESSAGE", ")", "{", "// enqueue a received message", "int", "task", "=", "message", ".", "task", "(", ")", ";", "DisruptorQueue", "queue", "=", "deserializeQueues", ".", "get", "(", "task", ")", ";", "if", "(", "queue", "==", "null", ")", "{", "LOG", ".", "warn", "(", "\"Received invalid message directed at task {}. Dropping...\"", ",", "task", ")", ";", "LOG", ".", "debug", "(", "\"Message data: {}\"", ",", "JStormUtils", ".", "toPrintableString", "(", "message", ".", "message", "(", ")", ")", ")", ";", "return", ";", "}", "if", "(", "!", "isBackpressureEnable", ")", "{", "queue", ".", "publish", "(", "message", ".", "message", "(", ")", ")", ";", "}", "else", "{", "flowCtrlHandler", ".", "flowCtrl", "(", "channel", ",", "queue", ",", "task", ",", "message", ".", "message", "(", ")", ")", ";", "}", "}", "else", "if", "(", "type", "==", "TaskMessage", ".", "CONTROL_MESSAGE", ")", "{", "// enqueue a control message", "if", "(", "recvControlQueue", "==", "null", ")", "{", "LOG", ".", "info", "(", "\"Can not find the recvControlQueue. Dropping this control message\"", ")", ";", "return", ";", "}", "recvControlQueue", ".", "publish", "(", "message", ")", ";", "}", "else", "{", "LOG", ".", "warn", "(", "\"Unexpected message (type={}) was received from task {}\"", ",", "type", ",", "message", ".", "task", "(", ")", ")", ";", "}", "}" ]
enqueue a received message
[ "enqueue", "a", "received", "message" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/message/netty/NettyServer.java#L118-L159
25,384
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/message/netty/NettyServer.java
NettyServer.closeChannel
protected void closeChannel(Channel channel) { MessageDecoder.removeTransmitHistogram(channel); channel.close().awaitUninterruptibly(); allChannels.remove(channel); }
java
protected void closeChannel(Channel channel) { MessageDecoder.removeTransmitHistogram(channel); channel.close().awaitUninterruptibly(); allChannels.remove(channel); }
[ "protected", "void", "closeChannel", "(", "Channel", "channel", ")", "{", "MessageDecoder", ".", "removeTransmitHistogram", "(", "channel", ")", ";", "channel", ".", "close", "(", ")", ".", "awaitUninterruptibly", "(", ")", ";", "allChannels", ".", "remove", "(", "channel", ")", ";", "}" ]
close a channel
[ "close", "a", "channel" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/message/netty/NettyServer.java#L189-L193
25,385
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/message/netty/NettyServer.java
NettyServer.close
public void close() { LOG.info("Begin to shutdown NettyServer"); if (allChannels != null) { new Thread(new Runnable() { @Override public void run() { try { // await(5, TimeUnit.SECONDS) // sometimes allChannels.close() will block the exit thread allChannels.close().await(1, TimeUnit.SECONDS); LOG.info("Successfully close all channel"); factory.releaseExternalResources(); } catch (Exception ignored) { } allChannels = null; } }).start(); JStormUtils.sleepMs(1000); } LOG.info("Successfully shutdown NettyServer"); }
java
public void close() { LOG.info("Begin to shutdown NettyServer"); if (allChannels != null) { new Thread(new Runnable() { @Override public void run() { try { // await(5, TimeUnit.SECONDS) // sometimes allChannels.close() will block the exit thread allChannels.close().await(1, TimeUnit.SECONDS); LOG.info("Successfully close all channel"); factory.releaseExternalResources(); } catch (Exception ignored) { } allChannels = null; } }).start(); JStormUtils.sleepMs(1000); } LOG.info("Successfully shutdown NettyServer"); }
[ "public", "void", "close", "(", ")", "{", "LOG", ".", "info", "(", "\"Begin to shutdown NettyServer\"", ")", ";", "if", "(", "allChannels", "!=", "null", ")", "{", "new", "Thread", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "// await(5, TimeUnit.SECONDS)", "// sometimes allChannels.close() will block the exit thread", "allChannels", ".", "close", "(", ")", ".", "await", "(", "1", ",", "TimeUnit", ".", "SECONDS", ")", ";", "LOG", ".", "info", "(", "\"Successfully close all channel\"", ")", ";", "factory", ".", "releaseExternalResources", "(", ")", ";", "}", "catch", "(", "Exception", "ignored", ")", "{", "}", "allChannels", "=", "null", ";", "}", "}", ")", ".", "start", "(", ")", ";", "JStormUtils", ".", "sleepMs", "(", "1000", ")", ";", "}", "LOG", ".", "info", "(", "\"Successfully shutdown NettyServer\"", ")", ";", "}" ]
close all channels, and release resources
[ "close", "all", "channels", "and", "release", "resources" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/message/netty/NettyServer.java#L198-L220
25,386
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/window/WindowedBoltExecutor.java
WindowedBoltExecutor.mergeSessionWindows
private TimeWindow mergeSessionWindows(TimeWindow oldWindow, TimeWindow newWindow) { if (oldWindow.intersects(newWindow)) { return oldWindow.cover(newWindow); } return newWindow; }
java
private TimeWindow mergeSessionWindows(TimeWindow oldWindow, TimeWindow newWindow) { if (oldWindow.intersects(newWindow)) { return oldWindow.cover(newWindow); } return newWindow; }
[ "private", "TimeWindow", "mergeSessionWindows", "(", "TimeWindow", "oldWindow", ",", "TimeWindow", "newWindow", ")", "{", "if", "(", "oldWindow", ".", "intersects", "(", "newWindow", ")", ")", "{", "return", "oldWindow", ".", "cover", "(", "newWindow", ")", ";", "}", "return", "newWindow", ";", "}" ]
merges two windows, if there's an overlap between two windows, return merged window; otherwise return the new window itself.
[ "merges", "two", "windows", "if", "there", "s", "an", "overlap", "between", "two", "windows", "return", "merged", "window", ";", "otherwise", "return", "the", "new", "window", "itself", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/window/WindowedBoltExecutor.java#L433-L438
25,387
alibaba/jstorm
jstorm-ui/src/main/java/com/alibaba/jstorm/ui/utils/UIMetricUtils.java
UIMetricUtils.getMetricValue
public static String getMetricValue(MetricSnapshot snapshot) { if (snapshot == null) return null; MetricType type = MetricType.parse(snapshot.get_metricType()); switch (type) { case COUNTER: return format(snapshot.get_longValue()); case GAUGE: return format(snapshot.get_doubleValue()); case METER: return format(snapshot.get_m1()); case HISTOGRAM: return format(snapshot.get_mean()); default: return "0"; } }
java
public static String getMetricValue(MetricSnapshot snapshot) { if (snapshot == null) return null; MetricType type = MetricType.parse(snapshot.get_metricType()); switch (type) { case COUNTER: return format(snapshot.get_longValue()); case GAUGE: return format(snapshot.get_doubleValue()); case METER: return format(snapshot.get_m1()); case HISTOGRAM: return format(snapshot.get_mean()); default: return "0"; } }
[ "public", "static", "String", "getMetricValue", "(", "MetricSnapshot", "snapshot", ")", "{", "if", "(", "snapshot", "==", "null", ")", "return", "null", ";", "MetricType", "type", "=", "MetricType", ".", "parse", "(", "snapshot", ".", "get_metricType", "(", ")", ")", ";", "switch", "(", "type", ")", "{", "case", "COUNTER", ":", "return", "format", "(", "snapshot", ".", "get_longValue", "(", ")", ")", ";", "case", "GAUGE", ":", "return", "format", "(", "snapshot", ".", "get_doubleValue", "(", ")", ")", ";", "case", "METER", ":", "return", "format", "(", "snapshot", ".", "get_m1", "(", ")", ")", ";", "case", "HISTOGRAM", ":", "return", "format", "(", "snapshot", ".", "get_mean", "(", ")", ")", ";", "default", ":", "return", "\"0\"", ";", "}", "}" ]
get MetricSnapshot formatted value string
[ "get", "MetricSnapshot", "formatted", "value", "string" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-ui/src/main/java/com/alibaba/jstorm/ui/utils/UIMetricUtils.java#L77-L92
25,388
alibaba/jstorm
jstorm-ui/src/main/java/com/alibaba/jstorm/ui/utils/UIMetricUtils.java
UIMetricUtils.extractGroup
public static String extractGroup(String[] strs) { if (strs.length < 6) return null; return strs[strs.length - 2]; }
java
public static String extractGroup(String[] strs) { if (strs.length < 6) return null; return strs[strs.length - 2]; }
[ "public", "static", "String", "extractGroup", "(", "String", "[", "]", "strs", ")", "{", "if", "(", "strs", ".", "length", "<", "6", ")", "return", "null", ";", "return", "strs", "[", "strs", ".", "length", "-", "2", "]", ";", "}" ]
Extract Group from 'WM@SequenceTest2-2-1439865106@10.218.132.134@6800@sys@MemUsed',which is 'sys'
[ "Extract", "Group", "from", "WM" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-ui/src/main/java/com/alibaba/jstorm/ui/utils/UIMetricUtils.java#L159-L162
25,389
alibaba/jstorm
jstorm-ui/src/main/java/com/alibaba/jstorm/ui/utils/UIMetricUtils.java
UIMetricUtils.extractMetricName
public static String extractMetricName(String[] strs) { if (strs.length < 6) return null; return strs[strs.length - 1]; }
java
public static String extractMetricName(String[] strs) { if (strs.length < 6) return null; return strs[strs.length - 1]; }
[ "public", "static", "String", "extractMetricName", "(", "String", "[", "]", "strs", ")", "{", "if", "(", "strs", ".", "length", "<", "6", ")", "return", "null", ";", "return", "strs", "[", "strs", ".", "length", "-", "1", "]", ";", "}" ]
Extract MetricName from 'CC@SequenceTest4-1-1439469823@Merge@0@@sys@Emitted',which is 'Emitted'
[ "Extract", "MetricName", "from", "CC" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-ui/src/main/java/com/alibaba/jstorm/ui/utils/UIMetricUtils.java#L165-L168
25,390
alibaba/jstorm
jstorm-ui/src/main/java/com/alibaba/jstorm/ui/utils/UIMetricUtils.java
UIMetricUtils.getComponentMetric
public static UIComponentMetric getComponentMetric(MetricInfo info, int window, String compName, List<ComponentSummary> componentSummaries) { UIComponentMetric compMetric = new UIComponentMetric(compName); if (info != null) { for (Map.Entry<String, Map<Integer, MetricSnapshot>> metric : info.get_metrics().entrySet()) { String name = metric.getKey(); String[] split_name = name.split("@"); String componentName = UIMetricUtils.extractComponentName(split_name); if (componentName != null && !componentName.equals(compName)) continue; //only handle the specific component String metricName = UIMetricUtils.extractMetricName(split_name); String parentComp = null; if (metricName != null && metricName.contains(".")) { parentComp = metricName.split("\\.")[0]; metricName = metricName.split("\\.")[1]; } MetricSnapshot snapshot = metric.getValue().get(window); compMetric.setMetricValue(snapshot, parentComp, metricName); } } compMetric.mergeValue(); ComponentSummary summary = null; for (ComponentSummary cs : componentSummaries) { if (cs.get_name().equals(compName)) { summary = cs; break; } } if (summary != null) { compMetric.setParallel(summary.get_parallel()); compMetric.setType(summary.get_type()); } return compMetric; }
java
public static UIComponentMetric getComponentMetric(MetricInfo info, int window, String compName, List<ComponentSummary> componentSummaries) { UIComponentMetric compMetric = new UIComponentMetric(compName); if (info != null) { for (Map.Entry<String, Map<Integer, MetricSnapshot>> metric : info.get_metrics().entrySet()) { String name = metric.getKey(); String[] split_name = name.split("@"); String componentName = UIMetricUtils.extractComponentName(split_name); if (componentName != null && !componentName.equals(compName)) continue; //only handle the specific component String metricName = UIMetricUtils.extractMetricName(split_name); String parentComp = null; if (metricName != null && metricName.contains(".")) { parentComp = metricName.split("\\.")[0]; metricName = metricName.split("\\.")[1]; } MetricSnapshot snapshot = metric.getValue().get(window); compMetric.setMetricValue(snapshot, parentComp, metricName); } } compMetric.mergeValue(); ComponentSummary summary = null; for (ComponentSummary cs : componentSummaries) { if (cs.get_name().equals(compName)) { summary = cs; break; } } if (summary != null) { compMetric.setParallel(summary.get_parallel()); compMetric.setType(summary.get_type()); } return compMetric; }
[ "public", "static", "UIComponentMetric", "getComponentMetric", "(", "MetricInfo", "info", ",", "int", "window", ",", "String", "compName", ",", "List", "<", "ComponentSummary", ">", "componentSummaries", ")", "{", "UIComponentMetric", "compMetric", "=", "new", "UIComponentMetric", "(", "compName", ")", ";", "if", "(", "info", "!=", "null", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Map", "<", "Integer", ",", "MetricSnapshot", ">", ">", "metric", ":", "info", ".", "get_metrics", "(", ")", ".", "entrySet", "(", ")", ")", "{", "String", "name", "=", "metric", ".", "getKey", "(", ")", ";", "String", "[", "]", "split_name", "=", "name", ".", "split", "(", "\"@\"", ")", ";", "String", "componentName", "=", "UIMetricUtils", ".", "extractComponentName", "(", "split_name", ")", ";", "if", "(", "componentName", "!=", "null", "&&", "!", "componentName", ".", "equals", "(", "compName", ")", ")", "continue", ";", "//only handle the specific component", "String", "metricName", "=", "UIMetricUtils", ".", "extractMetricName", "(", "split_name", ")", ";", "String", "parentComp", "=", "null", ";", "if", "(", "metricName", "!=", "null", "&&", "metricName", ".", "contains", "(", "\".\"", ")", ")", "{", "parentComp", "=", "metricName", ".", "split", "(", "\"\\\\.\"", ")", "[", "0", "]", ";", "metricName", "=", "metricName", ".", "split", "(", "\"\\\\.\"", ")", "[", "1", "]", ";", "}", "MetricSnapshot", "snapshot", "=", "metric", ".", "getValue", "(", ")", ".", "get", "(", "window", ")", ";", "compMetric", ".", "setMetricValue", "(", "snapshot", ",", "parentComp", ",", "metricName", ")", ";", "}", "}", "compMetric", ".", "mergeValue", "(", ")", ";", "ComponentSummary", "summary", "=", "null", ";", "for", "(", "ComponentSummary", "cs", ":", "componentSummaries", ")", "{", "if", "(", "cs", ".", "get_name", "(", ")", ".", "equals", "(", "compName", ")", ")", "{", "summary", "=", "cs", ";", "break", ";", "}", "}", "if", "(", "summary", "!=", "null", ")", "{", "compMetric", ".", "setParallel", "(", "summary", ".", "get_parallel", "(", ")", ")", ";", "compMetric", ".", "setType", "(", "summary", ".", "get_type", "(", ")", ")", ";", "}", "return", "compMetric", ";", "}" ]
get the specific component metric @param info metric info @param window window duration for metrics in seconds @param compName component name @param componentSummaries list of component summaries @return the component metric
[ "get", "the", "specific", "component", "metric" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-ui/src/main/java/com/alibaba/jstorm/ui/utils/UIMetricUtils.java#L284-L320
25,391
alibaba/jstorm
jstorm-ui/src/main/java/com/alibaba/jstorm/ui/utils/UIMetricUtils.java
UIMetricUtils.getTaskMetrics
public static List<UITaskMetric> getTaskMetrics(MetricInfo info, String component, int window) { TreeMap<Integer, UITaskMetric> taskData = new TreeMap<>(); if (info != null) { for (Map.Entry<String, Map<Integer, MetricSnapshot>> metric : info.get_metrics().entrySet()) { String name = metric.getKey(); String[] split_name = name.split("@"); int taskId = JStormUtils.parseInt(UIMetricUtils.extractTaskId(split_name)); String componentName = UIMetricUtils.extractComponentName(split_name); if (componentName != null && !componentName.equals(component)) continue; //only handle the tasks belongs to the specific component String metricName = UIMetricUtils.extractMetricName(split_name); String parentComp = null; if (metricName != null && metricName.contains(".")) { parentComp = metricName.split("\\.")[0]; metricName = metricName.split("\\.")[1]; } if (!metric.getValue().containsKey(window)) { LOG.info("task snapshot {} missing window:{}", metric.getKey(), window); continue; } MetricSnapshot snapshot = metric.getValue().get(window); UITaskMetric taskMetric; if (taskData.containsKey(taskId)) { taskMetric = taskData.get(taskId); } else { taskMetric = new UITaskMetric(component, taskId); taskData.put(taskId, taskMetric); } taskMetric.setMetricValue(snapshot, parentComp, metricName); } } for (UITaskMetric t : taskData.values()) { t.mergeValue(); } return new ArrayList<>(taskData.values()); }
java
public static List<UITaskMetric> getTaskMetrics(MetricInfo info, String component, int window) { TreeMap<Integer, UITaskMetric> taskData = new TreeMap<>(); if (info != null) { for (Map.Entry<String, Map<Integer, MetricSnapshot>> metric : info.get_metrics().entrySet()) { String name = metric.getKey(); String[] split_name = name.split("@"); int taskId = JStormUtils.parseInt(UIMetricUtils.extractTaskId(split_name)); String componentName = UIMetricUtils.extractComponentName(split_name); if (componentName != null && !componentName.equals(component)) continue; //only handle the tasks belongs to the specific component String metricName = UIMetricUtils.extractMetricName(split_name); String parentComp = null; if (metricName != null && metricName.contains(".")) { parentComp = metricName.split("\\.")[0]; metricName = metricName.split("\\.")[1]; } if (!metric.getValue().containsKey(window)) { LOG.info("task snapshot {} missing window:{}", metric.getKey(), window); continue; } MetricSnapshot snapshot = metric.getValue().get(window); UITaskMetric taskMetric; if (taskData.containsKey(taskId)) { taskMetric = taskData.get(taskId); } else { taskMetric = new UITaskMetric(component, taskId); taskData.put(taskId, taskMetric); } taskMetric.setMetricValue(snapshot, parentComp, metricName); } } for (UITaskMetric t : taskData.values()) { t.mergeValue(); } return new ArrayList<>(taskData.values()); }
[ "public", "static", "List", "<", "UITaskMetric", ">", "getTaskMetrics", "(", "MetricInfo", "info", ",", "String", "component", ",", "int", "window", ")", "{", "TreeMap", "<", "Integer", ",", "UITaskMetric", ">", "taskData", "=", "new", "TreeMap", "<>", "(", ")", ";", "if", "(", "info", "!=", "null", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Map", "<", "Integer", ",", "MetricSnapshot", ">", ">", "metric", ":", "info", ".", "get_metrics", "(", ")", ".", "entrySet", "(", ")", ")", "{", "String", "name", "=", "metric", ".", "getKey", "(", ")", ";", "String", "[", "]", "split_name", "=", "name", ".", "split", "(", "\"@\"", ")", ";", "int", "taskId", "=", "JStormUtils", ".", "parseInt", "(", "UIMetricUtils", ".", "extractTaskId", "(", "split_name", ")", ")", ";", "String", "componentName", "=", "UIMetricUtils", ".", "extractComponentName", "(", "split_name", ")", ";", "if", "(", "componentName", "!=", "null", "&&", "!", "componentName", ".", "equals", "(", "component", ")", ")", "continue", ";", "//only handle the tasks belongs to the specific component", "String", "metricName", "=", "UIMetricUtils", ".", "extractMetricName", "(", "split_name", ")", ";", "String", "parentComp", "=", "null", ";", "if", "(", "metricName", "!=", "null", "&&", "metricName", ".", "contains", "(", "\".\"", ")", ")", "{", "parentComp", "=", "metricName", ".", "split", "(", "\"\\\\.\"", ")", "[", "0", "]", ";", "metricName", "=", "metricName", ".", "split", "(", "\"\\\\.\"", ")", "[", "1", "]", ";", "}", "if", "(", "!", "metric", ".", "getValue", "(", ")", ".", "containsKey", "(", "window", ")", ")", "{", "LOG", ".", "info", "(", "\"task snapshot {} missing window:{}\"", ",", "metric", ".", "getKey", "(", ")", ",", "window", ")", ";", "continue", ";", "}", "MetricSnapshot", "snapshot", "=", "metric", ".", "getValue", "(", ")", ".", "get", "(", "window", ")", ";", "UITaskMetric", "taskMetric", ";", "if", "(", "taskData", ".", "containsKey", "(", "taskId", ")", ")", "{", "taskMetric", "=", "taskData", ".", "get", "(", "taskId", ")", ";", "}", "else", "{", "taskMetric", "=", "new", "UITaskMetric", "(", "component", ",", "taskId", ")", ";", "taskData", ".", "put", "(", "taskId", ",", "taskMetric", ")", ";", "}", "taskMetric", ".", "setMetricValue", "(", "snapshot", ",", "parentComp", ",", "metricName", ")", ";", "}", "}", "for", "(", "UITaskMetric", "t", ":", "taskData", ".", "values", "(", ")", ")", "{", "t", ".", "mergeValue", "(", ")", ";", "}", "return", "new", "ArrayList", "<>", "(", "taskData", ".", "values", "(", ")", ")", ";", "}" ]
get all task metrics in the specific component @param info raw metric info @param component component id @param window window duration for metrics in seconds @return the list of task metrics
[ "get", "all", "task", "metrics", "in", "the", "specific", "component" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-ui/src/main/java/com/alibaba/jstorm/ui/utils/UIMetricUtils.java#L399-L438
25,392
alibaba/jstorm
jstorm-ui/src/main/java/com/alibaba/jstorm/ui/utils/UIMetricUtils.java
UIMetricUtils.getTaskMetric
public static UITaskMetric getTaskMetric(List<MetricInfo> taskStreamMetrics, String component, int id, int window) { UITaskMetric taskMetric = new UITaskMetric(component, id); if (taskStreamMetrics.size() > 1) { MetricInfo info = taskStreamMetrics.get(0); if (info != null) { for (Map.Entry<String, Map<Integer, MetricSnapshot>> metric : info.get_metrics().entrySet()) { String name = metric.getKey(); String[] split_name = name.split("@"); int taskId = JStormUtils.parseInt(UIMetricUtils.extractTaskId(split_name)); if (taskId != id) continue; //only handle the specific task String metricName = UIMetricUtils.extractMetricName(split_name); String parentComp = null; if (metricName != null && metricName.contains(".")) { parentComp = metricName.split("\\.")[0]; metricName = metricName.split("\\.")[1]; } MetricSnapshot snapshot = metric.getValue().get(window); taskMetric.setMetricValue(snapshot, parentComp, metricName); } } } taskMetric.mergeValue(); return taskMetric; }
java
public static UITaskMetric getTaskMetric(List<MetricInfo> taskStreamMetrics, String component, int id, int window) { UITaskMetric taskMetric = new UITaskMetric(component, id); if (taskStreamMetrics.size() > 1) { MetricInfo info = taskStreamMetrics.get(0); if (info != null) { for (Map.Entry<String, Map<Integer, MetricSnapshot>> metric : info.get_metrics().entrySet()) { String name = metric.getKey(); String[] split_name = name.split("@"); int taskId = JStormUtils.parseInt(UIMetricUtils.extractTaskId(split_name)); if (taskId != id) continue; //only handle the specific task String metricName = UIMetricUtils.extractMetricName(split_name); String parentComp = null; if (metricName != null && metricName.contains(".")) { parentComp = metricName.split("\\.")[0]; metricName = metricName.split("\\.")[1]; } MetricSnapshot snapshot = metric.getValue().get(window); taskMetric.setMetricValue(snapshot, parentComp, metricName); } } } taskMetric.mergeValue(); return taskMetric; }
[ "public", "static", "UITaskMetric", "getTaskMetric", "(", "List", "<", "MetricInfo", ">", "taskStreamMetrics", ",", "String", "component", ",", "int", "id", ",", "int", "window", ")", "{", "UITaskMetric", "taskMetric", "=", "new", "UITaskMetric", "(", "component", ",", "id", ")", ";", "if", "(", "taskStreamMetrics", ".", "size", "(", ")", ">", "1", ")", "{", "MetricInfo", "info", "=", "taskStreamMetrics", ".", "get", "(", "0", ")", ";", "if", "(", "info", "!=", "null", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Map", "<", "Integer", ",", "MetricSnapshot", ">", ">", "metric", ":", "info", ".", "get_metrics", "(", ")", ".", "entrySet", "(", ")", ")", "{", "String", "name", "=", "metric", ".", "getKey", "(", ")", ";", "String", "[", "]", "split_name", "=", "name", ".", "split", "(", "\"@\"", ")", ";", "int", "taskId", "=", "JStormUtils", ".", "parseInt", "(", "UIMetricUtils", ".", "extractTaskId", "(", "split_name", ")", ")", ";", "if", "(", "taskId", "!=", "id", ")", "continue", ";", "//only handle the specific task", "String", "metricName", "=", "UIMetricUtils", ".", "extractMetricName", "(", "split_name", ")", ";", "String", "parentComp", "=", "null", ";", "if", "(", "metricName", "!=", "null", "&&", "metricName", ".", "contains", "(", "\".\"", ")", ")", "{", "parentComp", "=", "metricName", ".", "split", "(", "\"\\\\.\"", ")", "[", "0", "]", ";", "metricName", "=", "metricName", ".", "split", "(", "\"\\\\.\"", ")", "[", "1", "]", ";", "}", "MetricSnapshot", "snapshot", "=", "metric", ".", "getValue", "(", ")", ".", "get", "(", "window", ")", ";", "taskMetric", ".", "setMetricValue", "(", "snapshot", ",", "parentComp", ",", "metricName", ")", ";", "}", "}", "}", "taskMetric", ".", "mergeValue", "(", ")", ";", "return", "taskMetric", ";", "}" ]
get the specific task metric @param taskStreamMetrics raw metric info @param component component name @param id task id @param window window duration for metrics in seconds @return the task metric
[ "get", "the", "specific", "task", "metric" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-ui/src/main/java/com/alibaba/jstorm/ui/utils/UIMetricUtils.java#L449-L477
25,393
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/utils/RotatingMap.java
RotatingMap.remove
@Override public Object remove(K key) { for (Map<K, V> bucket : buckets) { Object value = bucket.remove(key); if (value != null) { return value; } } return null; }
java
@Override public Object remove(K key) { for (Map<K, V> bucket : buckets) { Object value = bucket.remove(key); if (value != null) { return value; } } return null; }
[ "@", "Override", "public", "Object", "remove", "(", "K", "key", ")", "{", "for", "(", "Map", "<", "K", ",", "V", ">", "bucket", ":", "buckets", ")", "{", "Object", "value", "=", "bucket", ".", "remove", "(", "key", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "return", "value", ";", "}", "}", "return", "null", ";", "}" ]
On the side of performance, scanning from header is faster on the side of logic, it should scan from the end to first.
[ "On", "the", "side", "of", "performance", "scanning", "from", "header", "is", "faster", "on", "the", "side", "of", "logic", "it", "should", "scan", "from", "the", "end", "to", "first", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/utils/RotatingMap.java#L141-L150
25,394
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/security/auth/ReqContext.java
ReqContext.principal
public Principal principal() { if (_subject == null) return null; Set<Principal> princs = _subject.getPrincipals(); if (princs.size() == 0) return null; return (Principal) (princs.toArray()[0]); }
java
public Principal principal() { if (_subject == null) return null; Set<Principal> princs = _subject.getPrincipals(); if (princs.size() == 0) return null; return (Principal) (princs.toArray()[0]); }
[ "public", "Principal", "principal", "(", ")", "{", "if", "(", "_subject", "==", "null", ")", "return", "null", ";", "Set", "<", "Principal", ">", "princs", "=", "_subject", ".", "getPrincipals", "(", ")", ";", "if", "(", "princs", ".", "size", "(", ")", "==", "0", ")", "return", "null", ";", "return", "(", "Principal", ")", "(", "princs", ".", "toArray", "(", ")", "[", "0", "]", ")", ";", "}" ]
The primary principal associated current subject
[ "The", "primary", "principal", "associated", "current", "subject" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/security/auth/ReqContext.java#L105-L112
25,395
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/scheduler/multitenant/NodePool.java
NodePool.init
public void init(Cluster cluster, Map<String, Node> nodeIdToNode) { _cluster = cluster; _nodeIdToNode = nodeIdToNode; }
java
public void init(Cluster cluster, Map<String, Node> nodeIdToNode) { _cluster = cluster; _nodeIdToNode = nodeIdToNode; }
[ "public", "void", "init", "(", "Cluster", "cluster", ",", "Map", "<", "String", ",", "Node", ">", "nodeIdToNode", ")", "{", "_cluster", "=", "cluster", ";", "_nodeIdToNode", "=", "nodeIdToNode", ";", "}" ]
Initialize the pool. @param cluster the cluster @param nodeIdToNode the mapping of node id to nodes
[ "Initialize", "the", "pool", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/scheduler/multitenant/NodePool.java#L177-L180
25,396
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/metric/ClusterMetricsContext.java
ClusterMetricsContext.init
public void init() { try { initPlugin(); } catch (RuntimeException e) { LOG.error("init metrics plugin error:", e); System.exit(-1); } pushRefreshEvent(); pushFlushEvent(); pushMergeEvent(); pushUploadEvent(); pushDiagnosisEvent(); LOG.info("Finish"); }
java
public void init() { try { initPlugin(); } catch (RuntimeException e) { LOG.error("init metrics plugin error:", e); System.exit(-1); } pushRefreshEvent(); pushFlushEvent(); pushMergeEvent(); pushUploadEvent(); pushDiagnosisEvent(); LOG.info("Finish"); }
[ "public", "void", "init", "(", ")", "{", "try", "{", "initPlugin", "(", ")", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "LOG", ".", "error", "(", "\"init metrics plugin error:\"", ",", "e", ")", ";", "System", ".", "exit", "(", "-", "1", ")", ";", "}", "pushRefreshEvent", "(", ")", ";", "pushFlushEvent", "(", ")", ";", "pushMergeEvent", "(", ")", ";", "pushUploadEvent", "(", ")", ";", "pushDiagnosisEvent", "(", ")", ";", "LOG", ".", "info", "(", "\"Finish\"", ")", ";", "}" ]
init plugins and start event
[ "init", "plugins", "and", "start", "event" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/metric/ClusterMetricsContext.java#L148-L162
25,397
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/metric/ClusterMetricsContext.java
ClusterMetricsContext.getTopologyMetric
public TopologyMetric getTopologyMetric(String topologyId) { long start = System.nanoTime(); try { TopologyMetric ret = new TopologyMetric(); List<MetricInfo> topologyMetrics = metricCache.getMetricData(topologyId, MetaType.TOPOLOGY); List<MetricInfo> componentMetrics = metricCache.getMetricData(topologyId, MetaType.COMPONENT); List<MetricInfo> workerMetrics = metricCache.getMetricData(topologyId, MetaType.WORKER); MetricInfo dummy = MetricUtils.mkMetricInfo(); if (topologyMetrics.size() > 0) { // get the last min topology metric ret.set_topologyMetric(topologyMetrics.get(topologyMetrics.size() - 1)); } else { ret.set_topologyMetric(dummy); } if (componentMetrics.size() > 0) { ret.set_componentMetric(componentMetrics.get(0)); } else { ret.set_componentMetric(dummy); } if (workerMetrics.size() > 0) { ret.set_workerMetric(workerMetrics.get(0)); } else { ret.set_workerMetric(dummy); } ret.set_taskMetric(dummy); ret.set_streamMetric(dummy); ret.set_nettyMetric(dummy); return ret; } finally { long end = System.nanoTime(); SimpleJStormMetric.updateNimbusHistogram("getTopologyMetric", (end - start) / TimeUtils.NS_PER_US); } }
java
public TopologyMetric getTopologyMetric(String topologyId) { long start = System.nanoTime(); try { TopologyMetric ret = new TopologyMetric(); List<MetricInfo> topologyMetrics = metricCache.getMetricData(topologyId, MetaType.TOPOLOGY); List<MetricInfo> componentMetrics = metricCache.getMetricData(topologyId, MetaType.COMPONENT); List<MetricInfo> workerMetrics = metricCache.getMetricData(topologyId, MetaType.WORKER); MetricInfo dummy = MetricUtils.mkMetricInfo(); if (topologyMetrics.size() > 0) { // get the last min topology metric ret.set_topologyMetric(topologyMetrics.get(topologyMetrics.size() - 1)); } else { ret.set_topologyMetric(dummy); } if (componentMetrics.size() > 0) { ret.set_componentMetric(componentMetrics.get(0)); } else { ret.set_componentMetric(dummy); } if (workerMetrics.size() > 0) { ret.set_workerMetric(workerMetrics.get(0)); } else { ret.set_workerMetric(dummy); } ret.set_taskMetric(dummy); ret.set_streamMetric(dummy); ret.set_nettyMetric(dummy); return ret; } finally { long end = System.nanoTime(); SimpleJStormMetric.updateNimbusHistogram("getTopologyMetric", (end - start) / TimeUtils.NS_PER_US); } }
[ "public", "TopologyMetric", "getTopologyMetric", "(", "String", "topologyId", ")", "{", "long", "start", "=", "System", ".", "nanoTime", "(", ")", ";", "try", "{", "TopologyMetric", "ret", "=", "new", "TopologyMetric", "(", ")", ";", "List", "<", "MetricInfo", ">", "topologyMetrics", "=", "metricCache", ".", "getMetricData", "(", "topologyId", ",", "MetaType", ".", "TOPOLOGY", ")", ";", "List", "<", "MetricInfo", ">", "componentMetrics", "=", "metricCache", ".", "getMetricData", "(", "topologyId", ",", "MetaType", ".", "COMPONENT", ")", ";", "List", "<", "MetricInfo", ">", "workerMetrics", "=", "metricCache", ".", "getMetricData", "(", "topologyId", ",", "MetaType", ".", "WORKER", ")", ";", "MetricInfo", "dummy", "=", "MetricUtils", ".", "mkMetricInfo", "(", ")", ";", "if", "(", "topologyMetrics", ".", "size", "(", ")", ">", "0", ")", "{", "// get the last min topology metric", "ret", ".", "set_topologyMetric", "(", "topologyMetrics", ".", "get", "(", "topologyMetrics", ".", "size", "(", ")", "-", "1", ")", ")", ";", "}", "else", "{", "ret", ".", "set_topologyMetric", "(", "dummy", ")", ";", "}", "if", "(", "componentMetrics", ".", "size", "(", ")", ">", "0", ")", "{", "ret", ".", "set_componentMetric", "(", "componentMetrics", ".", "get", "(", "0", ")", ")", ";", "}", "else", "{", "ret", ".", "set_componentMetric", "(", "dummy", ")", ";", "}", "if", "(", "workerMetrics", ".", "size", "(", ")", ">", "0", ")", "{", "ret", ".", "set_workerMetric", "(", "workerMetrics", ".", "get", "(", "0", ")", ")", ";", "}", "else", "{", "ret", ".", "set_workerMetric", "(", "dummy", ")", ";", "}", "ret", ".", "set_taskMetric", "(", "dummy", ")", ";", "ret", ".", "set_streamMetric", "(", "dummy", ")", ";", "ret", ".", "set_nettyMetric", "(", "dummy", ")", ";", "return", "ret", ";", "}", "finally", "{", "long", "end", "=", "System", ".", "nanoTime", "(", ")", ";", "SimpleJStormMetric", ".", "updateNimbusHistogram", "(", "\"getTopologyMetric\"", ",", "(", "end", "-", "start", ")", "/", "TimeUtils", ".", "NS_PER_US", ")", ";", "}", "}" ]
get topology metrics, note that only topology & component & worker metrics are returned
[ "get", "topology", "metrics", "note", "that", "only", "topology", "&", "component", "&", "worker", "metrics", "are", "returned" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/metric/ClusterMetricsContext.java#L263-L297
25,398
alibaba/jstorm
jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/trident/rotation/TimedRotationPolicy.java
TimedRotationPolicy.start
@Override public void start() { rotationTimer = new Timer(true); TimerTask task = new TimerTask() { @Override public void run() { rotationTimerTriggered.set(true); } }; rotationTimer.scheduleAtFixedRate(task, interval, interval); }
java
@Override public void start() { rotationTimer = new Timer(true); TimerTask task = new TimerTask() { @Override public void run() { rotationTimerTriggered.set(true); } }; rotationTimer.scheduleAtFixedRate(task, interval, interval); }
[ "@", "Override", "public", "void", "start", "(", ")", "{", "rotationTimer", "=", "new", "Timer", "(", "true", ")", ";", "TimerTask", "task", "=", "new", "TimerTask", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "rotationTimerTriggered", ".", "set", "(", "true", ")", ";", "}", "}", ";", "rotationTimer", ".", "scheduleAtFixedRate", "(", "task", ",", "interval", ",", "interval", ")", ";", "}" ]
Start the timer to run at fixed intervals.
[ "Start", "the", "timer", "to", "run", "at", "fixed", "intervals", "." ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/trident/rotation/TimedRotationPolicy.java#L88-L98
25,399
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/window/TransactionalWindowedBoltExecutor.java
TransactionalWindowedBoltExecutor.commit
@SuppressWarnings("unchecked") @Override public Object commit(long batchId, Object state) { List<Object> stateList = (List<Object>) state; if (stateOperator != null) { Object commitState = stateOperator.commit(batchId, stateList); stateList.add(commitState); } return stateList; }
java
@SuppressWarnings("unchecked") @Override public Object commit(long batchId, Object state) { List<Object> stateList = (List<Object>) state; if (stateOperator != null) { Object commitState = stateOperator.commit(batchId, stateList); stateList.add(commitState); } return stateList; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "Override", "public", "Object", "commit", "(", "long", "batchId", ",", "Object", "state", ")", "{", "List", "<", "Object", ">", "stateList", "=", "(", "List", "<", "Object", ">", ")", "state", ";", "if", "(", "stateOperator", "!=", "null", ")", "{", "Object", "commitState", "=", "stateOperator", ".", "commit", "(", "batchId", ",", "stateList", ")", ";", "stateList", ".", "add", "(", "commitState", ")", ";", "}", "return", "stateList", ";", "}" ]
to topology master for persistence
[ "to", "topology", "master", "for", "persistence" ]
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/window/TransactionalWindowedBoltExecutor.java#L118-L127