idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
118,100
public void tick ( ) { final long count = uncounted . sumThenReset ( ) ; final double instantRate = count / interval ; if ( initialized ) { rate += ( alpha * ( instantRate - rate ) ) ; } else { rate = instantRate ; initialized = true ; } }
Mark the passage of time and decay the current rate accordingly .
118,101
public void pruneZeroCounts ( ) { int i = 0 ; while ( i < rankedItems . size ( ) ) { if ( rankedItems . get ( i ) . getCount ( ) == 0 ) { rankedItems . remove ( i ) ; } else { i ++ ; } } }
Removes ranking entries that have a count of zero .
118,102
public static final void validateKey ( String key ) throws IllegalArgumentException { if ( StringUtils . isEmpty ( key ) || ".." . equals ( key ) || "." . equals ( key ) || ! KEY_PATTERN . matcher ( key ) . matches ( ) ) { LOG . error ( "'{}' does not appear to be valid {}" , key , KEY_PATTERN ) ; throw new IllegalArgu...
Validates key checking for potentially harmful patterns
118,103
public void readBlobTo ( String key , OutputStream out ) throws IOException , KeyNotFoundException { InputStreamWithMeta in = getBlob ( key ) ; if ( in == null ) { throw new IOException ( "Could not find " + key ) ; } byte [ ] buffer = new byte [ 2048 ] ; int len = 0 ; try { while ( ( len = in . read ( buffer ) ) > 0 )...
Reads the blob from the blob store and writes it into the output stream .
118,104
public byte [ ] readBlob ( String key ) throws IOException , KeyNotFoundException { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; readBlobTo ( key , out ) ; byte [ ] bytes = out . toByteArray ( ) ; out . close ( ) ; return bytes ; }
Wrapper around readBlobTo which returns a ByteArray output stream .
118,105
private void logProgress ( String fileOffset , boolean prefixNewLine ) throws IOException { long now = System . currentTimeMillis ( ) ; LogEntry entry = new LogEntry ( now , componentID , fileOffset ) ; String line = entry . toString ( ) ; if ( prefixNewLine ) { lockFileStream . writeBytes ( System . lineSeparator ( ) ...
partial writes of prior lines
118,106
public void release ( ) throws IOException { lockFileStream . close ( ) ; if ( ! fs . delete ( lockFile , false ) ) { LOG . warn ( "Unable to delete lock file, Spout = {}" , componentID ) ; throw new IOException ( "Unable to delete lock file" ) ; } LOG . debug ( "Released lock file {}. Spout {}" , lockFile , componentI...
Release lock by deleting file
118,107
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 ( "Acqui...
returns lock on file or null if file is already locked . throws if unexpected problem
118,108
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 . rea...
returns the last log entry
118,109
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. Ca...
Takes ownership of the lock file if possible .
118,110
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 .
118,111
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
118,112
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
118,113
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 . unFlushe...
flush temp counter data to all windows & assoc metrics .
118,114
public List < Integer > grouper ( List < Object > values ) { if ( GrouperType . global . equals ( groupType ) ) { return JStormUtils . mk_list ( outTasks . get ( 0 ) ) ; } else if ( GrouperType . fields . equals ( groupType ) ) { return fieldsGrouper . grouper ( values ) ; } else if ( GrouperType . all . equals ( group...
get which task should tuple be sent to
118,115
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 .
118,116
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 .
118,117
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 ( ) !=...
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 .
118,118
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 .
118,119
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 " ; for ( int i ...
Download a set of files from the remote server to a local directory .
118,120
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 p...
Authorizes request from to the DRPC server .
118,121
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 , selfRegistrationP...
Get the absolute path to where the service has registered itself . This includes the base registry path Null until the service is registered
118,122
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 ) ; regi...
Add a component
118,123
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 ) ; } reg...
Add a service under a path optionally purging any history
118,124
public void deleteComponent ( String componentName ) throws IOException { String path = RegistryUtils . componentPath ( user , jstormServiceClass , instanceName , componentName ) ; registryOperations . delete ( path , false ) ; }
Delete a component
118,125
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 ) ; registryOper...
Delete the children of a path - but not the path itself . It is not an error if the path does not exist
118,126
public BaseWindowedBolt < T > countWindow ( long size ) { ensurePositiveTime ( size ) ; setSizeAndSlide ( size , DEFAULT_SLIDE ) ; this . windowAssigner = TumblingCountWindows . create ( size ) ; return this ; }
define a tumbling count window
118,127
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
118,128
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
118,129
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 = TumblingEventTimeWind...
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 .
118,130
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 ...
define a sliding processing time window
118,131
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
118,132
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 ) ;...
define a sliding ingestion time window
118,133
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
118,134
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 ...
define a sliding event time window
118,135
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
118,136
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
118,137
public BaseWindowedBolt < T > withMaxLagMs ( Time maxLag ) { this . maxLagMs = maxLag . toMilliseconds ( ) ; ensureNonNegativeTime ( maxLagMs ) ; return this ; }
define max lag in ms only for event time windows
118,138
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
118,139
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 ScriptProcess...
return false if the health check failed when running the scripts under the path
118,140
public String toLocal ( Principal principal ) { return principal == null ? null : principal . getName ( ) . split ( "[/@]" ) [ 0 ] ; }
Convert a Principal to a local user name .
118,141
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 .
118,142
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 {}, tx...
Invokes handleCheckpoint once checkpoint tuple is received on all input checkpoint streams to this component .
118,143
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_comp...
returns the total number of input checkpoint streams across all input tasks to this component .
118,144
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 { transactionRequestC...
Checks if check points have been received from all tasks across all input streams to this component
118,145
public static NestableFieldValidator fv ( final Class cls , final boolean nullAllowed ) { return new NestableFieldValidator ( ) { public void validateField ( String pd , String name , Object field ) throws IllegalArgumentException { if ( nullAllowed && field == null ) { return ; } if ( ! cls . isInstance ( field ) ) { ...
Returns a new NestableFieldValidator for a given class .
118,146
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 .
118,147
public static NestableFieldValidator listFv ( final NestableFieldValidator validator , final boolean nullAllowed ) { return new NestableFieldValidator ( ) { public void validateField ( String pd , String name , Object field ) throws IllegalArgumentException { if ( nullAllowed && field == null ) { return ; } if ( field ...
Returns a new NestableFieldValidator for a List where each item is validated by validator .
118,148
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 .
118,149
public static NestableFieldValidator mapFv ( final NestableFieldValidator key , final NestableFieldValidator val , final boolean nullAllowed ) { return new NestableFieldValidator ( ) { @ SuppressWarnings ( "unchecked" ) public void validateField ( String pd , String name , Object field ) throws IllegalArgumentException...
Returns a new NestableFieldValidator for a Map .
118,150
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 ( ) ; st...
do heartbeat and update LocalState
118,151
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 histogr...
almost the same implementation of above update but improves performance for histograms
118,152
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 .
118,153
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...
Extra dir from the jar to destdir
118,154
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 (...
Check whether the zipfile contain the resources
118,155
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 <=...
Check if the incoming batch would be discarded . Generally the incoming batch shall be discarded while bolt is under rollback or it is expired .
118,156
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 ( ) ) ; } } r...
filter the map
118,157
public static void exec_command ( String command ) throws IOException { launchProcess ( command , new HashMap < String , String > ( ) , false ) ; }
use launchProcess to execute a command
118,158
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
118,159
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 : split...
balance all T
118,160
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 :" + cp...
calculate port number from cpu number and physical memory size
118,161
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 ( co...
Get Topology Metrics
118,162
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 .
118,163
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 . e...
a port must be assigned to a topology
118,164
@ 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 = ...
get local node s tasks
118,165
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 ( ) ; Assi...
get master code dir for each topology
118,166
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 run...
118,167
private boolean monitorApplication ( ApplicationId appId ) throws YarnException , IOException { Integer monitorTimes = JOYConstants . MONITOR_TIMES ; while ( true ) { try { Thread . sleep ( JOYConstants . MONITOR_TIME_INTERVAL ) ; } catch ( InterruptedException e ) { LOG . debug ( "Thread sleep in monitoring loop inter...
Monitor the submitted application for completion . Kill application if time expires .
118,168
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
118,169
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 + "=" + keySt...
Produce a blowfish key to be used in Storm jar command
118,170
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...
check supervisor s heartBeat
118,171
public boolean setJstormConf ( String key , String value ) { 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
118,172
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 . get...
Do we need just handle the case when type is ASSIGN_TYPE_NEW?
118,173
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
118,174
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 (...
get topology ids that need to be cleaned up
118,175
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 . loca...
make assignments for a topology The nimbus core function this function has been totally rewrite
118,176
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 ) { Res...
get all task ids which are newly assigned or reassigned
118,177
public static List < WorkerSlot > sortSlots ( Set < WorkerSlot > allSlots , int needSlotNum ) { Map < String , List < WorkerSlot > > nodeMap = new HashMap < > ( ) ; for ( WorkerSlot np : allSlots ) { String node = np . getNodeId ( ) ; List < WorkerSlot > list = nodeMap . get ( node ) ; if ( list == null ) { list = new ...
sort slots the purpose is to ensure that the tasks are assigned in balancing
118,178
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 ( )...
Get unstopped slots from alive task list
118,179
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 ( ) ) { As...
Get free resources
118,180
public Set < Integer > getAliveTasks ( String topologyId , Set < Integer > taskIds ) throws Exception { Set < Integer > aliveTasks = new HashSet < > ( ) ; for ( int taskId : taskIds ) { boolean isDead = NimbusUtils . isTaskDead ( nimbusData , topologyId , taskId ) ; if ( ! isDead ) { aliveTasks . add ( taskId ) ; } } r...
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
118,181
public void backupAssignment ( Assignment assignment , TopologyAssignEvent event ) { String topologyId = event . getTopologyId ( ) ; String topologyName = event . getTopologyName ( ) ; try { StormClusterState zkClusterState = nimbusData . getStormClusterState ( ) ; Map < Integer , String > tasks = Cluster . get_all_tas...
Backup topology assignment to ZK
118,182
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 BoltDecla...
map from stream name to batch id
118,183
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 ( f...
will commit progress into lock file if commit threshold is reached
118,184
private FileLock getOldestExpiredLock ( ) throws IOException { 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 DirLoc...
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
118,185
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 { Clas...
Creates a reader that reads from beginning of file
118,186
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 , ne...
Renames files with . inprogress suffix
118,187
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 ( sour...
Returns the corresponding input file in the sourceDirPath for the specified lock file . If no such file is found then returns null
118,188
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 + Pa...
renames files and returns the new file path
118,189
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
118,190
public void enqueue ( TaskMessage message , Channel channel ) { 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 . ...
enqueue a received message
118,191
protected void closeChannel ( Channel channel ) { MessageDecoder . removeTransmitHistogram ( channel ) ; channel . close ( ) . awaitUninterruptibly ( ) ; allChannels . remove ( channel ) ; }
close a channel
118,192
public void close ( ) { LOG . info ( "Begin to shutdown NettyServer" ) ; if ( allChannels != null ) { new Thread ( new Runnable ( ) { public void run ( ) { try { allChannels . close ( ) . await ( 1 , TimeUnit . SECONDS ) ; LOG . info ( "Successfully close all channel" ) ; factory . releaseExternalResources ( ) ; } catc...
close all channels and release resources
118,193
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 .
118,194
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 ( ) )...
get MetricSnapshot formatted value string
118,195
public static String extractGroup ( String [ ] strs ) { if ( strs . length < 6 ) return null ; return strs [ strs . length - 2 ] ; }
Extract Group from WM
118,196
public static String extractMetricName ( String [ ] strs ) { if ( strs . length < 6 ) return null ; return strs [ strs . length - 1 ] ; }
Extract MetricName from CC
118,197
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 the specific component metric
118,198
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 nam...
get all task metrics in the specific component
118,199
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 . Entr...
get the specific task metric