idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
35,600
public Map < String , WorkerHeartbeat > readWorkerHeartbeats ( Map conf ) throws Exception { Map < String , WorkerHeartbeat > workerHeartbeats = new HashMap < > ( ) ; String path = StormConfig . worker_root ( conf ) ; List < String > workerIds = PathUtils . read_dir_contents ( path ) ; if ( workerIds == null ) { LOG . info ( "No worker dir under " + path ) ; return workerHeartbeats ; } for ( String workerId : workerIds ) { WorkerHeartbeat whb = readWorkerHeartbeat ( conf , workerId ) ; workerHeartbeats . put ( workerId , whb ) ; } return workerHeartbeats ; }
get all workers heartbeats of the supervisor
35,601
public WorkerHeartbeat readWorkerHeartbeat ( Map conf , String workerId ) throws Exception { try { LocalState ls = StormConfig . worker_state ( conf , workerId ) ; return ( WorkerHeartbeat ) ls . get ( Common . LS_WORKER_HEARTBEAT ) ; } catch ( Exception e ) { LOG . error ( "Failed to get heartbeat for worker:{}" , workerId , e ) ; return null ; } }
get worker heartbeat by workerId
35,602
public void launchWorker ( Map conf , IContext sharedContext , String topologyId , String supervisorId , Integer port , String workerId , ConcurrentHashMap < String , String > workerThreadPidsAtom ) throws Exception { String pid = UUID . randomUUID ( ) . toString ( ) ; WorkerShutdown worker = Worker . mk_worker ( conf , sharedContext , topologyId , supervisorId , port , workerId , null ) ; ProcessSimulator . registerProcess ( pid , worker ) ; workerThreadPidsAtom . put ( workerId , pid ) ; }
launch a worker in local mode
35,603
private Set < String > setFilterJars ( Map totalConf ) { Set < String > filterJars = new HashSet < > ( ) ; boolean enableClassLoader = ConfigExtension . isEnableTopologyClassLoader ( totalConf ) ; if ( ! enableClassLoader ) { boolean enableLog4j = false ; String userDefLog4jConf = ConfigExtension . getUserDefinedLog4jConf ( totalConf ) ; if ( ! StringUtils . isBlank ( userDefLog4jConf ) ) { enableLog4j = true ; } if ( enableLog4j ) { filterJars . add ( "log4j-over-slf4j" ) ; filterJars . add ( "logback-core" ) ; filterJars . add ( "logback-classic" ) ; } else { filterJars . add ( "slf4j-log4j" ) ; filterJars . add ( "log4j" ) ; } } String excludeJars = ( String ) totalConf . get ( "exclude.jars" ) ; if ( ! StringUtils . isBlank ( excludeJars ) ) { String [ ] jars = excludeJars . split ( "," ) ; for ( String jar : jars ) { filterJars . add ( jar ) ; } } LOG . info ( "Remove jars " + filterJars ) ; return filterJars ; }
filter conflict jar
35,604
public String getWorkerMemParameter ( LocalAssignment assignment , Map totalConf , String topologyId , Integer port ) { long memSize = assignment . getMem ( ) ; long memMinSize = ConfigExtension . getMemMinSizePerWorker ( totalConf ) ; long memGsize = memSize / JStormUtils . SIZE_1_G ; int gcThreadsNum = memGsize > 4 ? ( int ) ( memGsize * 1.5 ) : 4 ; String childOpts = getChildOpts ( totalConf ) ; childOpts += getGcDumpParam ( topologyId , port , totalConf ) ; StringBuilder commandSB = new StringBuilder ( ) ; memMinSize = memMinSize < memSize ? memMinSize : memSize ; commandSB . append ( " -Xms" ) . append ( memMinSize ) . append ( " -Xmx" ) . append ( memSize ) . append ( " " ) ; if ( memMinSize <= ( memSize / 2 ) ) { commandSB . append ( " -Xmn" ) . append ( memMinSize / 2 ) . append ( " " ) ; } else { commandSB . append ( " -Xmn" ) . append ( memSize / 2 ) . append ( " " ) ; } if ( JDKInfo . isJdk7 ( ) || JDKInfo . lessThanJdk7 ( ) ) { if ( memGsize >= 2 ) { commandSB . append ( " -XX:PermSize=" ) . append ( memSize / 32 ) ; } else { commandSB . append ( " -XX:PermSize=" ) . append ( memSize / 16 ) ; } commandSB . append ( " -XX:MaxPermSize=" ) . append ( memSize / 16 ) ; } else if ( JDKInfo . isJdk8 ( ) ) { if ( memGsize >= 2 ) { commandSB . append ( " -XX:MetaspaceSize=" ) . append ( memSize / 32 ) ; } else { commandSB . append ( " -XX:MetaspaceSize=" ) . append ( memSize / 16 ) ; } commandSB . append ( " -XX:MaxMetaspaceSize=" ) . append ( memSize / 16 ) ; } commandSB . append ( " -XX:ParallelGCThreads=" ) . append ( gcThreadsNum ) ; commandSB . append ( " " ) . append ( childOpts ) ; if ( ! StringUtils . isBlank ( assignment . getJvm ( ) ) ) { commandSB . append ( " " ) . append ( assignment . getJvm ( ) ) ; } return commandSB . toString ( ) ; }
Get worker s JVM memory setting
35,605
public String getWorkerGcParameter ( LocalAssignment assignment , Map totalConf , String topologyId , Integer port ) { StringBuilder commandSB = new StringBuilder ( ) ; GcStrategy gcStrategy = GcStrategyManager . getGcStrategy ( totalConf ) ; return gcStrategy . toString ( ) ; }
Get worker s JVM gc setting
35,606
public void launchWorker ( Map conf , IContext sharedContext , String topologyId , String supervisorId , Integer port , String workerId , LocalAssignment assignment ) throws IOException { Map stormConf = StormConfig . read_supervisor_topology_conf ( conf , topologyId ) ; String stormHome = System . getProperty ( "jstorm.home" ) ; if ( StringUtils . isBlank ( stormHome ) ) { stormHome = "./" ; } String topologyRoot = StormConfig . supervisor_stormdist_root ( conf , topologyId ) ; Map workerConf = StormConfig . read_topology_conf ( topologyRoot , topologyId ) ; Map totalConf = new HashMap ( ) ; totalConf . putAll ( conf ) ; totalConf . putAll ( stormConf ) ; totalConf . putAll ( workerConf ) ; Map < String , String > environment = new HashMap < > ( ) ; if ( ConfigExtension . getWorkerRedirectOutput ( totalConf ) ) { environment . put ( "REDIRECT" , "true" ) ; } else { environment . put ( "REDIRECT" , "false" ) ; } environment . put ( "LD_LIBRARY_PATH" , ( String ) totalConf . get ( Config . JAVA_LIBRARY_PATH ) ) ; environment . put ( "jstorm.home" , stormHome ) ; environment . put ( "jstorm.workerId" , workerId ) ; environment . put ( "jstorm.on.yarn" , isJstormOnYarn ? "1" : "0" ) ; String launcherCmd = getLauncherParameter ( assignment , totalConf , stormHome , topologyId , port ) ; String workerCmd = getWorkerParameter ( assignment , totalConf , stormHome , topologyId , supervisorId , workerId , port ) ; String cmd = launcherCmd + " " + workerCmd ; cmd = cmd . replace ( "%JSTORM_HOME%" , stormHome ) ; LOG . info ( "Launching worker with command: " + cmd ) ; LOG . info ( "Environment:" + environment . toString ( ) ) ; boolean backend = ! isJstormOnYarn ; LOG . info ( "backend mode is " + backend ) ; JStormUtils . launchProcess ( cmd , environment , backend ) ; }
launch a worker in distributed mode
35,607
public List < TopologyDetails > needsSchedulingTopologies ( Topologies topologies ) { List < TopologyDetails > ret = new ArrayList < > ( ) ; for ( TopologyDetails topology : topologies . getTopologies ( ) ) { if ( needsScheduling ( topology ) ) { ret . add ( topology ) ; } } return ret ; }
Gets all the topologies which needs scheduling .
35,608
public boolean needsScheduling ( TopologyDetails topology ) { int desiredNumWorkers = topology . getNumWorkers ( ) ; int assignedNumWorkers = this . getAssignedNumWorkers ( topology ) ; if ( desiredNumWorkers > assignedNumWorkers ) { return true ; } return this . getUnassignedExecutors ( topology ) . size ( ) > 0 ; }
Does the topology need scheduling?
35,609
public Map < ExecutorDetails , String > getNeedsSchedulingExecutorToComponents ( TopologyDetails topology ) { Collection < ExecutorDetails > allExecutors = new HashSet < > ( topology . getExecutors ( ) ) ; SchedulerAssignment assignment = this . assignments . get ( topology . getId ( ) ) ; if ( assignment != null ) { Collection < ExecutorDetails > assignedExecutors = assignment . getExecutors ( ) ; allExecutors . removeAll ( assignedExecutors ) ; } return topology . selectExecutorToComponent ( allExecutors ) ; }
Gets a executor - > component - id map which needs scheduling in this topology .
35,610
public Map < String , List < ExecutorDetails > > getNeedsSchedulingComponentToExecutors ( TopologyDetails topology ) { Map < ExecutorDetails , String > executorToComponents = this . getNeedsSchedulingExecutorToComponents ( topology ) ; Map < String , List < ExecutorDetails > > componentToExecutors = new HashMap < > ( ) ; for ( ExecutorDetails executor : executorToComponents . keySet ( ) ) { String component = executorToComponents . get ( executor ) ; if ( ! componentToExecutors . containsKey ( component ) ) { componentToExecutors . put ( component , new ArrayList < ExecutorDetails > ( ) ) ; } componentToExecutors . get ( component ) . add ( executor ) ; } return componentToExecutors ; }
Gets a component - id - > executors map which needs scheduling in this topology .
35,611
public Set < Integer > getUsedPorts ( SupervisorDetails supervisor ) { Map < String , SchedulerAssignment > assignments = this . getAssignments ( ) ; Set < Integer > usedPorts = new HashSet < > ( ) ; for ( SchedulerAssignment assignment : assignments . values ( ) ) { for ( WorkerSlot slot : assignment . getExecutorToSlot ( ) . values ( ) ) { if ( slot . getNodeId ( ) . equals ( supervisor . getId ( ) ) ) { usedPorts . add ( slot . getPort ( ) ) ; } } } return usedPorts ; }
Get all the used ports of this supervisor .
35,612
public Set < Integer > getAvailablePorts ( SupervisorDetails supervisor ) { Set < Integer > usedPorts = this . getUsedPorts ( supervisor ) ; Set < Integer > ret = new HashSet < > ( ) ; ret . addAll ( getAssignablePorts ( supervisor ) ) ; ret . removeAll ( usedPorts ) ; return ret ; }
Return the available ports of this supervisor .
35,613
public List < WorkerSlot > getAvailableSlots ( SupervisorDetails supervisor ) { Set < Integer > ports = this . getAvailablePorts ( supervisor ) ; List < WorkerSlot > slots = new ArrayList < > ( ports . size ( ) ) ; for ( Integer port : ports ) { slots . add ( new WorkerSlot ( supervisor . getId ( ) , port ) ) ; } return slots ; }
Return all the available slots on this supervisor .
35,614
public Collection < ExecutorDetails > getUnassignedExecutors ( TopologyDetails topology ) { if ( topology == null ) { return new ArrayList < > ( 0 ) ; } Collection < ExecutorDetails > ret = new HashSet < > ( topology . getExecutors ( ) ) ; SchedulerAssignment assignment = this . getAssignmentById ( topology . getId ( ) ) ; if ( assignment != null ) { Set < ExecutorDetails > assignedExecutors = assignment . getExecutors ( ) ; ret . removeAll ( assignedExecutors ) ; } return ret ; }
get the unassigned executors of the topology .
35,615
public int getAssignedNumWorkers ( TopologyDetails topology ) { SchedulerAssignment assignment = this . getAssignmentById ( topology . getId ( ) ) ; if ( assignment == null ) { return 0 ; } Set < WorkerSlot > slots = new HashSet < > ( ) ; slots . addAll ( assignment . getExecutorToSlot ( ) . values ( ) ) ; return slots . size ( ) ; }
Gets the number of workers assigned to this topology .
35,616
public void assign ( WorkerSlot slot , String topologyId , Collection < ExecutorDetails > executors ) { if ( this . isSlotOccupied ( slot ) ) { throw new RuntimeException ( "slot: [" + slot . getNodeId ( ) + ", " + slot . getPort ( ) + "] is already occupied." ) ; } SchedulerAssignmentImpl assignment = ( SchedulerAssignmentImpl ) this . getAssignmentById ( topologyId ) ; if ( assignment == null ) { assignment = new SchedulerAssignmentImpl ( topologyId , new HashMap < ExecutorDetails , WorkerSlot > ( ) ) ; this . assignments . put ( topologyId , assignment ) ; } else { for ( ExecutorDetails executor : executors ) { if ( assignment . isExecutorAssigned ( executor ) ) { throw new RuntimeException ( "the executor is already assigned, you should un-assign it first " + "before assign it to another slot." ) ; } } } assignment . assign ( slot , executors ) ; }
Assign the slot to the executors for this topology .
35,617
public List < WorkerSlot > getAvailableSlots ( ) { List < WorkerSlot > slots = new ArrayList < > ( ) ; for ( SupervisorDetails supervisor : this . supervisors . values ( ) ) { slots . addAll ( this . getAvailableSlots ( supervisor ) ) ; } return slots ; }
Gets all the available slots in the cluster .
35,618
public void freeSlot ( WorkerSlot slot ) { for ( SchedulerAssignmentImpl assignment : this . assignments . values ( ) ) { if ( assignment . isSlotOccupied ( slot ) ) { assignment . unassignBySlot ( slot ) ; } } }
Free the specified slot .
35,619
public void freeSlots ( Collection < WorkerSlot > slots ) { if ( slots != null ) { for ( WorkerSlot slot : slots ) { this . freeSlot ( slot ) ; } } }
free the slots .
35,620
public boolean isSlotOccupied ( WorkerSlot slot ) { for ( SchedulerAssignment assignment : this . assignments . values ( ) ) { if ( assignment . isSlotOccupied ( slot ) ) { return true ; } } return false ; }
Checks the specified slot is occupied .
35,621
public SchedulerAssignment getAssignmentById ( String topologyId ) { if ( this . assignments . containsKey ( topologyId ) ) { return this . assignments . get ( topologyId ) ; } return null ; }
get the current assignment for the topology .
35,622
public Map < String , SchedulerAssignment > getAssignments ( ) { Map < String , SchedulerAssignment > ret = new HashMap < > ( this . assignments . size ( ) ) ; for ( String topologyId : this . assignments . keySet ( ) ) { ret . put ( topologyId , this . assignments . get ( topologyId ) ) ; } return ret ; }
Get all the assignments .
35,623
public String getUserName ( HttpServletRequest req ) { Principal princ = null ; if ( req != null && ( princ = req . getUserPrincipal ( ) ) != null ) { String userName = princ . getName ( ) ; if ( userName != null && ! userName . isEmpty ( ) ) { LOG . debug ( "HTTP request had user (" + userName + ")" ) ; return userName ; } } return null ; }
Gets the user name from the request principal .
35,624
public ReqContext populateContext ( ReqContext context , HttpServletRequest req ) { String userName = getUserName ( req ) ; String doAsUser = req . getHeader ( "doAsUser" ) ; if ( doAsUser == null ) { doAsUser = req . getParameter ( "doAsUser" ) ; } if ( doAsUser != null ) { context . setRealPrincipal ( new SingleUserPrincipal ( userName ) ) ; userName = doAsUser ; } Set < Principal > principals = new HashSet < Principal > ( ) ; if ( userName != null ) { Principal p = new SingleUserPrincipal ( userName ) ; principals . add ( p ) ; } Subject s = new Subject ( true , principals , new HashSet ( ) , new HashSet ( ) ) ; context . setSubject ( s ) ; return context ; }
Populates a given context with a new Subject derived from the credentials in a servlet request .
35,625
public void run ( ) { try { GrayUpgradeConfig grayUpgradeConf = ( GrayUpgradeConfig ) stormClusterState . get_gray_upgrade_conf ( topologyId ) ; if ( grayUpgradeConf == null ) { LOG . debug ( "gray upgrade conf is null, skip..." ) ; return ; } if ( grayUpgradeConf . isCompleted ( ) && ! grayUpgradeConf . isRollback ( ) ) { LOG . debug ( "detected a complete upgrade, skip..." ) ; return ; } if ( grayUpgradeConf . isExpired ( ) && ! grayUpgradeConf . isRollback ( ) ) { LOG . info ( "detected an expired upgrade, completing..." ) ; GrayUpgradeConfig . completeUpgrade ( grayUpgradeConf ) ; stormClusterState . set_gray_upgrade_conf ( topologyId , grayUpgradeConf ) ; stormClusterState . update_storm ( topologyId , new StormStatus ( StatusType . active ) ) ; return ; } if ( this . totalWorkers . size ( ) == 0 ) { setTotalWorkers ( tmContext ) ; } Set < String > upgradingWorkers = Sets . newHashSet ( stormClusterState . get_upgrading_workers ( topologyId ) ) ; if ( upgradingWorkers . size ( ) > 0 ) { LOG . info ( "Following workers are under upgrade:{}" , upgradingWorkers ) ; for ( String worker : upgradingWorkers ) { notifyToUpgrade ( worker ) ; } return ; } Set < String > upgradedWorkers = Sets . newHashSet ( stormClusterState . get_upgraded_workers ( topologyId ) ) ; if ( grayUpgradeConf . isRollback ( ) ) { LOG . info ( "Rollback has completed, removing upgrade info in zk and updating storm status..." ) ; stormClusterState . remove_gray_upgrade_info ( topologyId ) ; stormClusterState . update_storm ( topologyId , new StormStatus ( StatusType . active ) ) ; return ; } if ( isUpgradeCompleted ( upgradedWorkers , totalWorkers ) ) { LOG . info ( "This upgraded has finished! Marking upgrade config as completed..." ) ; GrayUpgradeConfig . completeUpgrade ( grayUpgradeConf ) ; stormClusterState . set_gray_upgrade_conf ( topologyId , grayUpgradeConf ) ; stormClusterState . update_storm ( topologyId , new StormStatus ( StatusType . active ) ) ; return ; } if ( grayUpgradeConf . continueUpgrading ( ) ) { pickWorkersToUpgrade ( grayUpgradeConf , upgradedWorkers ) ; } grayUpgradeConf . setContinueUpgrade ( false ) ; stormClusterState . set_gray_upgrade_conf ( topologyId , grayUpgradeConf ) ; } catch ( Exception ex ) { LOG . error ( "Failed to get upgrade config from zk, will abort this upgrade..." , ex ) ; recover ( ) ; } }
scheduled runnable callback called periodically
35,626
public boolean tryPublishEvent ( EventTranslatorVararg < E > translator , Object ... args ) { try { final long sequence = sequencer . tryNext ( ) ; translateAndPublish ( translator , sequence , args ) ; return true ; } catch ( InsufficientCapacityException e ) { return false ; } }
Allows a variable number of user supplied arguments
35,627
public < A > void publishEvents ( EventTranslatorOneArg < E , A > translator , int batchStartsAt , int batchSize , A [ ] arg0 ) { checkBounds ( arg0 , batchStartsAt , batchSize ) ; final long finalSequence = sequencer . next ( batchSize ) ; translateAndPublishBatch ( translator , arg0 , batchStartsAt , batchSize , finalSequence ) ; }
Allows one user supplied argument per event .
35,628
public < A , B , C > void publishEvents ( EventTranslatorThreeArg < E , A , B , C > translator , int batchStartsAt , int batchSize , A [ ] arg0 , B [ ] arg1 , C [ ] arg2 ) { checkBounds ( arg0 , arg1 , arg2 , batchStartsAt , batchSize ) ; final long finalSequence = sequencer . next ( batchSize ) ; translateAndPublishBatch ( translator , arg0 , arg1 , arg2 , batchStartsAt , batchSize , finalSequence ) ; }
Allows three user supplied arguments per event .
35,629
private static SpoutNode getDRPCSpoutNode ( Collection < Node > g ) { for ( Node n : g ) { if ( n instanceof SpoutNode ) { SpoutNode . SpoutType type = ( ( SpoutNode ) n ) . type ; if ( type == SpoutNode . SpoutType . DRPC ) { return ( SpoutNode ) n ; } } } return null ; }
returns null if it s not a drpc group
35,630
public String sandboxPolicy ( String workerId , Map < String , String > replaceMap ) throws IOException { if ( ! isEnable ) { return "" ; } replaceMap . putAll ( replaceBaseMap ) ; String tmpPolicy = generatePolicyFile ( replaceMap ) ; File file = new File ( tmpPolicy ) ; String policyPath = StormConfig . worker_root ( conf , workerId ) + File . separator + SANBOX_TEMPLATE_NAME ; File dest = new File ( policyPath ) ; file . renameTo ( dest ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( " -Djava.security.manager -Djava.security.policy=" ) ; sb . append ( policyPath ) ; return sb . toString ( ) ; }
Generate command string
35,631
public < T extends ISubscribedState > T setSubscribedState ( String componentId , T obj ) { return setSubscribedState ( componentId , Utils . DEFAULT_STREAM_ID , obj ) ; }
Synchronizes the default stream from the specified state spout component id with the provided ISubscribedState object .
35,632
public Map < String , List < String > > getThisOutputFieldsForStreams ( ) { Map < String , List < String > > streamToFields = new HashMap < > ( ) ; for ( String stream : this . getThisStreams ( ) ) { streamToFields . put ( stream , this . getThisOutputFields ( stream ) . toList ( ) ) ; } return streamToFields ; }
Gets the declared output fields for the specified stream id for the component this task is a part of .
35,633
public void process ( Object event ) throws Exception { int secOffset = TimeUtils . secOffset ( ) ; if ( secOffset < UPLOAD_TIME_OFFSET_SEC ) { JStormUtils . sleepMs ( ( UPLOAD_TIME_OFFSET_SEC - secOffset ) * 1000 ) ; } else if ( secOffset == UPLOAD_TIME_OFFSET_SEC ) { } else { JStormUtils . sleepMs ( ( 60 - secOffset + UPLOAD_TIME_OFFSET_SEC ) * 1000 ) ; } if ( topologyMetricContext . getUploadedWorkerNum ( ) > 0 ) { metricLogger . info ( "force upload metrics." ) ; mergeAndUploadMetrics ( ) ; } }
Wait UPLOAD_TIME_OFFSET_SEC sec to ensure we ve collected enough metrics from topology workers note that it s not guaranteed metrics from all workers will be collected .
35,634
public static Double getDiskUsage ( ) { if ( ! OSInfo . isLinux ( ) && ! OSInfo . isMac ( ) ) { return 0.0 ; } try { String output = SystemOperation . exec ( "df -h " + duHome ) ; if ( output != null ) { String [ ] lines = output . split ( "[\\r\\n]+" ) ; if ( lines . length >= 2 ) { String [ ] parts = lines [ 1 ] . split ( "\\s+" ) ; if ( parts . length >= 5 ) { String pct = parts [ 4 ] ; if ( pct . endsWith ( "%" ) ) { return Integer . valueOf ( pct . substring ( 0 , pct . length ( ) - 1 ) ) / 100.0 ; } } } } } catch ( Exception e ) { LOG . warn ( "failed to get disk usage." ) ; } return 0.0 ; }
calculate the disk usage at current filesystem
35,635
public static void submitTopologyWithProgressBar ( String name , Map stormConf , StormTopology topology , SubmitOptions opts ) throws AlreadyAliveException , InvalidTopologyException { submitTopology ( name , stormConf , topology , opts ) ; }
Submits a topology to run on the cluster with a progress bar . A topology runs forever or until explicitly killed .
35,636
private Map < Integer , Map < K , V > > classifyBatch ( Map < K , V > batch ) { Map < Integer , Map < K , V > > classifiedBatch = new HashMap < Integer , Map < K , V > > ( ) ; for ( Entry < K , V > entry : batch . entrySet ( ) ) { int keyRange = hash ( entry . getKey ( ) ) ; Map < K , V > subBatch = classifiedBatch . get ( keyRange ) ; if ( subBatch == null ) { subBatch = new HashMap < K , V > ( ) ; classifiedBatch . put ( keyRange , subBatch ) ; } subBatch . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } return classifiedBatch ; }
classify batch into several sub - batches for each key range
35,637
public CuratorFramework mkClient ( Map conf , List < String > servers , Object port , String root , final WatcherCallBack watcher ) { CuratorFramework fk = Utils . newCurator ( conf , servers , port , root ) ; fk . getCuratorListenable ( ) . addListener ( new CuratorListener ( ) { public void eventReceived ( CuratorFramework _fk , CuratorEvent e ) throws Exception { if ( e . getType ( ) . equals ( CuratorEventType . WATCHED ) ) { WatchedEvent event = e . getWatchedEvent ( ) ; watcher . execute ( event . getState ( ) , event . getType ( ) , event . getPath ( ) ) ; } } } ) ; fk . getUnhandledErrorListenable ( ) . addListener ( new UnhandledErrorListener ( ) { public void unhandledError ( String msg , Throwable error ) { String errmsg = "Unrecoverable zookeeper error, halting process: " + msg ; LOG . error ( errmsg , error ) ; JStormUtils . halt_process ( 1 , "Unrecoverable zookeeper error" ) ; } } ) ; fk . start ( ) ; return fk ; }
connect ZK register watchers
35,638
protected void prepareInternal ( Map conf , String overrideBase , Configuration hadoopConf ) { this . conf = conf ; if ( overrideBase == null ) { overrideBase = ( String ) conf . get ( Config . BLOBSTORE_DIR ) ; } if ( overrideBase == null ) { throw new RuntimeException ( "You must specify a blobstore directory for HDFS to use!" ) ; } LOG . debug ( "directory is: {}" , overrideBase ) ; Path baseDir = new Path ( overrideBase , BASE_BLOBS_DIR_NAME ) ; try { if ( hadoopConf != null ) { _hbs = new HdfsBlobStoreImpl ( baseDir , conf , hadoopConf ) ; } else { _hbs = new HdfsBlobStoreImpl ( baseDir , conf ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Allow a Hadoop Configuration to be passed for testing . If it s null then the hadoop configs must be in your classpath .
35,639
private TxnRecord getTxnRecord ( Path indexFilePath ) throws IOException { Path tmpPath = tmpFilePath ( indexFilePath . toString ( ) ) ; if ( this . options . fs . exists ( indexFilePath ) ) { return readTxnRecord ( indexFilePath ) ; } else if ( this . options . fs . exists ( tmpPath ) ) { return readTxnRecord ( tmpPath ) ; } return new TxnRecord ( 0 , options . currentFile . toString ( ) , 0 ) ; }
Reads the last txn record from index file if it exists if not from . tmp file if exists .
35,640
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 .
35,641
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 .
35,642
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 IllegalArgumentException ( key + " does not appear to be a valid blob key" ) ; } }
Validates key checking for potentially harmful patterns
35,643
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 ) { out . write ( buffer , 0 , len ) ; } } finally { in . close ( ) ; out . flush ( ) ; } }
Reads the blob from the blob store and writes it into the output stream .
35,644
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 .
35,645
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 ( ) + line ) ; } else { lockFileStream . writeBytes ( line ) ; } lockFileStream . hflush ( ) ; lastEntry = entry ; }
partial writes of prior lines
35,646
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 , componentID ) ; }
Release lock by deleting file
35,647
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
35,648
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
35,649
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 { 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 .
35,650
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 .
35,651
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
35,652
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
35,653
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 .
35,654
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 ( groupType ) ) { return outTasks ; } else if ( GrouperType . shuffle . equals ( groupType ) ) { 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
35,655
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 .
35,656
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 .
35,657
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 .
35,658
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 .
35,659
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 = 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 .
35,660
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 ) ; } LOG . warn ( "Denying unsupported operation \"" + operation + "\" from " + context . remoteAddress ( ) ) ; return false ; }
Authorizes request from to the DRPC server .
35,661
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
35,662
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
35,663
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
35,664
public void deleteComponent ( String componentName ) throws IOException { String path = RegistryUtils . componentPath ( user , jstormServiceClass , instanceName , componentName ) ; registryOperations . delete ( path , false ) ; }
Delete a component
35,665
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
35,666
public BaseWindowedBolt < T > countWindow ( long size ) { ensurePositiveTime ( size ) ; setSizeAndSlide ( size , DEFAULT_SLIDE ) ; this . windowAssigner = TumblingCountWindows . create ( size ) ; return this ; }
define a tumbling count window
35,667
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
35,668
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
35,669
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 .
35,670
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
35,671
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
35,672
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
35,673
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
35,674
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
35,675
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
35,676
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
35,677
public BaseWindowedBolt < T > withMaxLagMs ( Time maxLag ) { this . maxLagMs = maxLag . toMilliseconds ( ) ; ensureNonNegativeTime ( maxLagMs ) ; return this ; }
define max lag in ms only for event time windows
35,678
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
35,679
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
35,680
public String toLocal ( Principal principal ) { return principal == null ? null : principal . getName ( ) . split ( "[/@]" ) [ 0 ] ; }
Convert a Principal to a local user name .
35,681
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 .
35,682
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 .
35,683
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 .
35,684
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
35,685
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 ) ) { throw new IllegalArgumentException ( pd + name + " must be a " + cls . getName ( ) + ". (" + field + ")" ) ; } } } ; }
Returns a new NestableFieldValidator for a given class .
35,686
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 .
35,687
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 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 .
35,688
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 .
35,689
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 { 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 .
35,690
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
35,691
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
35,692
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 .
35,693
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
35,694
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 ) { LOG . error ( e + "zipContainsDir error" ) ; } return false ; }
Check whether the zipfile contain the resources
35,695
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 .
35,696
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
35,697
public static void exec_command ( String command ) throws IOException { launchProcess ( command , new HashMap < String , String > ( ) , false ) ; }
use launchProcess to execute a command
35,698
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
35,699
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