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 . ...
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:{}" , wor...
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 ...
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 . getUserDefinedLog4jC...
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 ?...
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 ( "jstor...
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 ) { C...
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 < > ( )...
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 . getExecutorToSl...
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 ) ) ; } retur...
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 ( )...
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...
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 = ( SchedulerAssig...
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 userNam...
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 SingleUserP...
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 ( )...
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 , fina...
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 ) ; translateAndPublishBa...
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 (...
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 ...
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 ] . sp...
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 . g...
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 ( CuratorFra...
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 HDF...
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 ( tmpPat...
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 IllegalArgu...
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 )...
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 ( ) ...
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 , componentI...
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 ( "Acqui...
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 . rea...
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. Ca...
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 . unFlushe...
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 ( group...
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 ( ) !=...
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 ...
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 p...
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 , selfRegistrationP...
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 ) ; regi...
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 ) ; } reg...
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 ) ; registryOper...
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 = 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 .
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 ...
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 ) ;...
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 ...
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 ScriptProcess...
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 {}, tx...
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_comp...
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 { transactionRequestC...
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 ) ) { ...
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 ...
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...
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 ( ) ; st...
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 histogr...
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...
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 (...
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 <=...
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 ( ) ) ; } } r...
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 : split...
balance all T