idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
118,200
public Object remove ( K key ) { for ( Map < K , V > bucket : buckets ) { Object value = bucket . remove ( key ) ; if ( value != null ) { return value ; } } return null ; }
On the side of performance scanning from header is faster on the side of logic it should scan from the end to first .
118,201
public Principal principal ( ) { if ( _subject == null ) return null ; Set < Principal > princs = _subject . getPrincipals ( ) ; if ( princs . size ( ) == 0 ) return null ; return ( Principal ) ( princs . toArray ( ) [ 0 ] ) ; }
The primary principal associated current subject
118,202
public void init ( Cluster cluster , Map < String , Node > nodeIdToNode ) { _cluster = cluster ; _nodeIdToNode = nodeIdToNode ; }
Initialize the pool .
118,203
public void init ( ) { try { initPlugin ( ) ; } catch ( RuntimeException e ) { LOG . error ( "init metrics plugin error:" , e ) ; System . exit ( - 1 ) ; } pushRefreshEvent ( ) ; pushFlushEvent ( ) ; pushMergeEvent ( ) ; pushUploadEvent ( ) ; pushDiagnosisEvent ( ) ; LOG . info ( "Finish" ) ; }
init plugins and start event
118,204
public TopologyMetric getTopologyMetric ( String topologyId ) { long start = System . nanoTime ( ) ; try { TopologyMetric ret = new TopologyMetric ( ) ; List < MetricInfo > topologyMetrics = metricCache . getMetricData ( topologyId , MetaType . TOPOLOGY ) ; List < MetricInfo > componentMetrics = metricCache . getMetric...
get topology metrics note that only topology & component & worker metrics are returned
118,205
public void start ( ) { rotationTimer = new Timer ( true ) ; TimerTask task = new TimerTask ( ) { public void run ( ) { rotationTimerTriggered . set ( true ) ; } } ; rotationTimer . scheduleAtFixedRate ( task , interval , interval ) ; }
Start the timer to run at fixed intervals .
118,206
@ SuppressWarnings ( "unchecked" ) public Object commit ( long batchId , Object state ) { List < Object > stateList = ( List < Object > ) state ; if ( stateOperator != null ) { Object commitState = stateOperator . commit ( batchId , stateList ) ; stateList . add ( commitState ) ; } return stateList ; }
to topology master for persistence
118,207
public void mergeMeters ( MetricInfo metricInfo , String meta , Map < Integer , MetricSnapshot > data ) { Map < Integer , MetricSnapshot > existing = metricInfo . get_metrics ( ) . get ( meta ) ; if ( existing == null ) { metricInfo . put_to_metrics ( meta , data ) ; } else { for ( Map . Entry < Integer , MetricSnapsho...
meters are not sampled .
118,208
public void mergeHistograms ( MetricInfo metricInfo , String meta , Map < Integer , MetricSnapshot > data , Map < String , Integer > metaCounters , Map < String , Map < Integer , Histogram > > histograms ) { Map < Integer , MetricSnapshot > existing = metricInfo . get_metrics ( ) . get ( meta ) ; if ( existing == null ...
histograms are sampled but we just update points
118,209
protected void updateMetricCounters ( String metricName , Map < String , Integer > metricNameCounters ) { if ( metricNameCounters . containsKey ( metricName ) ) { metricNameCounters . put ( metricName , metricNameCounters . get ( metricName ) + 1 ) ; } else { metricNameCounters . put ( metricName , 1 ) ; } }
computes occurrences of specified metric name
118,210
private void mergeCounters ( Map < String , Map < Integer , MetricSnapshot > > newCounters , Map < String , Map < Integer , MetricSnapshot > > oldCounters ) { for ( Map . Entry < String , Map < Integer , MetricSnapshot > > entry : newCounters . entrySet ( ) ) { String metricName = entry . getKey ( ) ; Map < Integer , M...
sum old counter snapshots and new counter snapshots sums are stored in new snapshots .
118,211
private void track ( Event < T > windowEvent ) { evictionPolicy . track ( windowEvent ) ; triggerPolicy . track ( windowEvent ) ; }
feed the event to the eviction and trigger policies for bookkeeping and optionally firing the trigger .
118,212
private List < Event < T > > scanEvents ( boolean fullScan ) { LOG . debug ( "Scan events, eviction policy {}" , evictionPolicy ) ; List < T > eventsToExpire = new ArrayList < > ( ) ; List < Event < T > > eventsToProcess = new ArrayList < > ( ) ; try { lock . lock ( ) ; Iterator < Event < T > > it = queue . iterator ( ...
Scan events in the queue using the expiration policy to check if the event should be evicted or not .
118,213
public long getEarliestEventTs ( long startTs , long endTs ) { long minTs = Long . MAX_VALUE ; for ( Event < T > event : queue ) { if ( event . getTimestamp ( ) > startTs && event . getTimestamp ( ) <= endTs ) { minTs = Math . min ( minTs , event . getTimestamp ( ) ) ; } } return minTs ; }
Scans the event queue and returns the next earliest event ts between the startTs and endTs
118,214
public int getEventCount ( long referenceTime ) { int count = 0 ; for ( Event < T > event : queue ) { if ( event . getTimestamp ( ) <= referenceTime ) { ++ count ; } } return count ; }
Scans the event queue and returns number of events having timestamp less than or equal to the reference time .
118,215
private void mkRefreshConfThread ( final NimbusData nimbusData ) { nimbusData . getScheduExec ( ) . scheduleAtFixedRate ( new RunnableCallback ( ) { public void run ( ) { LOG . debug ( "checking changes in storm.yaml..." ) ; Map newConf = Utils . readStormConfig ( ) ; if ( Utils . isConfigChanged ( nimbusData . getConf...
handle manual conf changes check every 15 sec
118,216
public static List < HostAndPort > splitToHostsAndPorts ( String hostPortQuorumList ) { String [ ] strings = StringUtils . getStrings ( hostPortQuorumList ) ; int len = 0 ; if ( strings != null ) { len = strings . length ; } List < HostAndPort > list = new ArrayList < HostAndPort > ( len ) ; if ( strings != null ) { fo...
Split a quorum list into a list of hostnames and ports
118,217
public static String buildHostsOnlyList ( List < HostAndPort > hostAndPorts ) { StringBuilder sb = new StringBuilder ( ) ; for ( HostAndPort hostAndPort : hostAndPorts ) { sb . append ( hostAndPort . getHostText ( ) ) . append ( "," ) ; } if ( sb . length ( ) > 0 ) { sb . delete ( sb . length ( ) - 1 , sb . length ( ) ...
Build up to a hosts only list
118,218
public static Config buildConfig ( TopologyDef topologyDef ) { Config conf = new Config ( ) ; conf . putAll ( topologyDef . getConfig ( ) ) ; return conf ; }
Given a topology definition return a populated org . apache . storm . Config instance .
118,219
public static StormTopology buildTopology ( ExecutionContext context ) throws IllegalAccessException , InstantiationException , ClassNotFoundException , NoSuchMethodException , InvocationTargetException { StormTopology topology = null ; TopologyDef topologyDef = context . getTopologyDef ( ) ; if ( ! topologyDef . valid...
Given a topology definition return a Storm topology that can be run either locally or remotely .
118,220
private static void buildComponents ( ExecutionContext context ) throws ClassNotFoundException , NoSuchMethodException , IllegalAccessException , InvocationTargetException , InstantiationException { Collection < BeanDef > cDefs = context . getTopologyDef ( ) . getComponents ( ) ; if ( cDefs != null ) { for ( BeanDef be...
Given a topology definition resolve and instantiate all components found and return a map keyed by the component id .
118,221
private static IRichSpout buildSpout ( SpoutDef def , ExecutionContext context ) throws ClassNotFoundException , IllegalAccessException , InstantiationException , NoSuchMethodException , InvocationTargetException { return ( IRichSpout ) buildObject ( def , context ) ; }
Given a spout definition return a Storm spout implementation by attempting to find a matching constructor in the given spout class . Perform list to array conversion as necessary .
118,222
private static void buildBolts ( ExecutionContext context ) throws ClassNotFoundException , IllegalAccessException , InstantiationException , NoSuchMethodException , InvocationTargetException { for ( BoltDef def : context . getTopologyDef ( ) . getBolts ( ) ) { Class clazz = Class . forName ( def . getClassName ( ) ) ;...
Given a list of bolt definitions build a map of Storm bolts with the bolt definition id as the key . Attempt to coerce the given constructor arguments to a matching bolt constructor as much as possible .
118,223
private static Map mapifySerializations ( List sers ) { Map rtn = new HashMap ( ) ; if ( sers != null ) { int size = sers . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { if ( sers . get ( i ) instanceof Map ) { rtn . putAll ( ( Map ) sers . get ( i ) ) ; } else { rtn . put ( sers . get ( i ) , null ) ; } } } return ...
add custom KRYO serialization
118,224
public static StormTopology normalizeTopology ( Map stormConf , StormTopology topology , boolean fromConf ) { StormTopology ret = topology . deepCopy ( ) ; Map < String , Object > rawComponents = ThriftTopologyUtils . getComponents ( topology ) ; Map < String , Object > components = ThriftTopologyUtils . getComponents ...
finalize component s task parallelism
118,225
public static void cleanupCorruptTopologies ( NimbusData data ) throws Exception { BlobStore blobStore = data . getBlobStore ( ) ; Set < String > code_ids = Sets . newHashSet ( BlobStoreUtils . code_ids ( blobStore . listKeys ( ) ) ) ; Set < String > active_ids = Sets . newHashSet ( data . getStormClusterState ( ) . ac...
clean the topology which is in ZK but not in local dir
118,226
public Set < String > getGroups ( String user ) throws IOException { if ( cachedGroups . containsKey ( user ) ) { return cachedGroups . get ( user ) ; } Set < String > groups = getUnixGroups ( user ) ; if ( ! groups . isEmpty ( ) ) cachedGroups . put ( user , groups ) ; return groups ; }
Returns list of groups for a user
118,227
private static Set < String > getUnixGroups ( final String user ) throws IOException { String result = "" ; try { result = ShellUtils . execCommand ( ShellUtils . getGroupsForUserCommand ( user ) ) ; } catch ( ExitCodeException e ) { LOG . warn ( "got exception trying to get groups for user " + user , e ) ; return new ...
Get the current user s group list from Unix by running the command groups NOTE . For non - existing user it will return EMPTY list
118,228
public Map < String , Object > toMap ( ) { Map < String , Object > ret = new HashMap < > ( ) ; ret . put ( MetricUploader . METRIC_TIME , timestamp ) ; ret . put ( MetricUploader . METRIC_TYPE , type ) ; return ret ; }
metrics report time
118,229
public void update ( Number obj ) { if ( enable == false ) { return ; } if ( intervalCheck . check ( ) ) { flush ( ) ; } synchronized ( this ) { unflushed = updater . update ( obj , unflushed ) ; } }
In order to improve performance Do
118,230
public void onEvent ( Object event , long sequence , boolean endOfBatch ) throws Exception { if ( event == null ) { return ; } handleEvent ( event , endOfBatch ) ; }
This function need to be implements
118,231
public void refreshTopologies ( ) { TimeTicker ticker = new TimeTicker ( TimeUnit . MILLISECONDS , true ) ; try { doRefreshTopologies ( ) ; LOG . debug ( "Refresh topologies, cost:{}" , ticker . stopAndRestart ( ) ) ; if ( ! context . getNimbusData ( ) . isLeader ( ) ) { syncTopologyMetaForFollower ( ) ; LOG . debug ( ...
refresh metric settings of topologies & metric meta
118,232
private void syncMetaFromCache ( String topology , TopologyMetricContext tmContext ) { if ( ! tmContext . syncMeta ( ) ) { Map < String , Long > meta = context . getMetricCache ( ) . getMeta ( topology ) ; if ( meta != null ) { tmContext . getMemMeta ( ) . putAll ( meta ) ; } tmContext . setSyncMeta ( true ) ; } }
sync metric meta from rocks db into mem cache on startup
118,233
private void syncSysMetaFromRemote ( ) { for ( String topology : JStormMetrics . SYS_TOPOLOGIES ) { if ( context . getTopologyMetricContexts ( ) . containsKey ( topology ) ) { syncMetaFromRemote ( topology , context . getTopologyMetricContexts ( ) . get ( topology ) , Lists . newArrayList ( MetaType . TOPOLOGY , MetaTy...
sync sys topologies from remote because we want to keep all historic metric data thus metric id cannot be changed .
118,234
private void tryHostLock ( String hostPath ) throws Exception { if ( registryOperations . exists ( hostPath ) ) { try { ServiceRecord host = registryOperations . resolve ( hostPath ) ; Long cTime = Long . parseLong ( host . get ( JOYConstants . CTIME , JOYConstants . DEFAULT_CTIME ) ) ; Date now = new Date ( ) ; if ( n...
see if anyone is updating host s port list if not start update this host itself timeout is 45 seconds
118,235
public static List < TaskEntity > getTaskEntities ( TopologyInfo topologyInfo ) { Map < Integer , TaskEntity > tasks = new HashMap < > ( ) ; for ( TaskSummary ts : topologyInfo . get_tasks ( ) ) { tasks . put ( ts . get_taskId ( ) , new TaskEntity ( ts ) ) ; } for ( ComponentSummary cs : topologyInfo . get_components (...
get all task entities in the specific topology
118,236
public static List < TaskEntity > getTaskEntities ( TopologyInfo topologyInfo , String componentName ) { TreeMap < Integer , TaskEntity > tasks = new TreeMap < > ( ) ; for ( ComponentSummary cs : topologyInfo . get_components ( ) ) { String compName = cs . get_name ( ) ; String type = cs . get_type ( ) ; if ( component...
get the task entities in the specific component
118,237
public static TaskEntity getTaskEntity ( List < TaskSummary > tasks , int taskId ) { TaskEntity entity = null ; for ( TaskSummary task : tasks ) { if ( task . get_taskId ( ) == taskId ) { entity = new TaskEntity ( task ) ; break ; } } return entity ; }
get the specific task entity
118,238
public static Map resetZKConfig ( Map conf , String clusterName ) { ClusterConfig nimbus = clusterConfig . get ( clusterName ) ; if ( nimbus == null ) return conf ; conf . put ( Config . STORM_ZOOKEEPER_ROOT , nimbus . getZkRoot ( ) ) ; conf . put ( Config . STORM_ZOOKEEPER_SERVERS , nimbus . getZkServers ( ) ) ; conf ...
to get nimbus client we should reset ZK config
118,239
public static String prettyUptime ( int secs ) { String [ ] [ ] PRETTYSECDIVIDERS = { new String [ ] { "s" , "60" } , new String [ ] { "m" , "60" } , new String [ ] { "h" , "24" } , new String [ ] { "d" , null } } ; int diversize = PRETTYSECDIVIDERS . length ; LinkedList < String > tmp = new LinkedList < > ( ) ; int di...
seconds to string like 30m 40s and 1d 20h 30m 40s
118,240
public static Long parseLong ( String s , long defaultValue ) { try { Long value = Long . parseLong ( s ) ; return value ; } catch ( NumberFormatException e ) { } return defaultValue ; }
return the default value instead of throw an exception
118,241
private static void fillValue2Node ( List < MetricInfo > componentMetrics , Map < String , TopologyNode > nodes ) { String NODE_DIM = MetricDef . EMMITTED_NUM ; List < String > FILTER = Arrays . asList ( MetricDef . EMMITTED_NUM , MetricDef . SEND_TPS , MetricDef . RECV_TPS ) ; for ( MetricInfo info : componentMetrics ...
fill emitted num to nodes
118,242
private static void fillTLCValue2Edge ( List < MetricInfo > componentMetrics , Map < String , TopologyEdge > edges ) { String EDGE_DIM = "." + MetricDef . TUPLE_LIEF_CYCLE ; for ( MetricInfo info : componentMetrics ) { if ( info == null ) continue ; for ( Map . Entry < String , Map < Integer , MetricSnapshot > > metric...
fill tuple life cycle time to edges
118,243
public BoltDeclarer setBolt ( String id , BaseWindowedBolt < Tuple > bolt , Number parallelism_hint ) throws IllegalArgumentException { boolean isEventTime = WindowAssigner . isEventTime ( bolt . getWindowAssigner ( ) ) ; if ( isEventTime && bolt . getTimestampExtractor ( ) == null ) { throw new IllegalArgumentExceptio...
Define a new bolt in this topology . This defines a windowed bolt intended for windowing operations .
118,244
public SpoutDeclarer setSpout ( String id , IRichSpout spout , Number parallelism_hint ) throws IllegalArgumentException { validateUnusedId ( id ) ; initCommon ( id , spout , parallelism_hint ) ; _spouts . put ( id , spout ) ; return new SpoutGetter ( id ) ; }
Define a new spout in this topology with the specified parallelism . If the spout declares itself as non - distributed the parallelism_hint will be ignored and only one task will be allocated to this component .
118,245
public SpoutDeclarer setSpout ( String id , IControlSpout spout ) { return setSpout ( id , spout , null ) ; }
Define a new bolt in this topology . This defines a control spout which is a simpler to use but more restricted kind of bolt . Control spouts are intended for making sending control message more simply
118,246
public BoltDeclarer setBolt ( String id , IControlBolt bolt , Number parallelism_hint ) { return setBolt ( id , new ControlBoltExecutor ( bolt ) , parallelism_hint ) ; }
Define a new bolt in this topology . This defines a control bolt which is a simpler to use but more restricted kind of bolt . Control bolts are intended for making sending control message more simply
118,247
public void addWorkerHook ( IWorkerHook workerHook ) { if ( null == workerHook ) { throw new IllegalArgumentException ( "WorkerHook must not be null." ) ; } _workerHooks . add ( ByteBuffer . wrap ( Utils . javaSerialize ( workerHook ) ) ) ; }
Add a new worker lifecycle hook
118,248
private void maybeAddWatermarkInputs ( ComponentCommon common , IRichBolt bolt ) { if ( bolt instanceof WindowedBoltExecutor ) { Set < String > comps = new HashSet < > ( ) ; for ( GlobalStreamId globalStreamId : common . get_inputs ( ) . keySet ( ) ) { comps . add ( globalStreamId . get_componentId ( ) ) ; } for ( Stri...
Add watermark stream to source components of window bolts
118,249
public static String getShowTimeStr ( Integer time ) { if ( time == null ) { return MINUTE_WINDOW_STR ; } else if ( time . equals ( MINUTE_WINDOW ) ) { return MINUTE_WINDOW_STR ; } else if ( time . equals ( HOUR_WINDOW ) ) { return HOUR_WINDOW_STR ; } else if ( time . equals ( DAY_WINDOW ) ) { return DAY_WINDOW_STR ; }...
Default is the latest result
118,250
public static String prettyUptimeStr ( int secs ) { int diversize = PRETTYSECDIVIDERS . length ; List < String > tmp = new ArrayList < String > ( ) ; int div = secs ; for ( int i = 0 ; i < diversize ; i ++ ) { if ( PRETTYSECDIVIDERS [ i ] [ 1 ] != null ) { Integer d = Integer . parseInt ( PRETTYSECDIVIDERS [ i ] [ 1 ] ...
seconds to string like 1d20h30m40s
118,251
public static < T > List < T > getParents ( DirectedGraph g , T n ) { List < IndexedEdge > incoming = new ArrayList ( g . incomingEdgesOf ( n ) ) ; Collections . sort ( incoming ) ; List < T > ret = new ArrayList ( ) ; for ( IndexedEdge e : incoming ) { ret . add ( ( T ) e . source ) ; } return ret ; }
Assumes edge contains an index
118,252
public Set < ResourceWorkerSlot > getKeepAssign ( DefaultTopologyAssignContext defaultContext , Set < Integer > needAssigns ) { Set < Integer > keepAssignIds = new HashSet < > ( ) ; keepAssignIds . addAll ( defaultContext . getAllTaskIds ( ) ) ; keepAssignIds . removeAll ( defaultContext . getUnstoppedTaskIds ( ) ) ; k...
Get the task Map which the task is alive and will be kept only when type is ASSIGN_TYPE_MONITOR it is valid
118,253
public JStormCache putMetricData ( String topologyId , TopologyMetric tpMetric ) { Map < String , Object > batchData = new HashMap < > ( ) ; long ts = System . currentTimeMillis ( ) ; int tp = 0 , comp = 0 , compStream = 0 , task = 0 , stream = 0 , worker = 0 , netty = 0 ; if ( tpMetric . get_componentMetric ( ) . get_...
store 30min metric data . the metric data is stored in a ring .
118,254
public Stream setMemoryLoad ( Number onHeap , Number offHeap ) { _node . setMemoryLoad ( onHeap , offHeap ) ; return this ; }
Sets the Memory Load resources for the current operation .
118,255
public Stream project ( Fields keepFields ) { projectionValidation ( keepFields ) ; return _topology . addSourcedNode ( this , new ProcessorNode ( _topology . getUniqueStreamId ( ) , _name , keepFields , new Fields ( ) , new ProjectedProcessor ( keepFields ) ) ) ; }
Filters out fields from a stream resulting in a Stream containing only the fields specified by keepFields .
118,256
public Stream partitionAggregate ( Fields inputFields , Aggregator agg , Fields functionFields ) { projectionValidation ( inputFields ) ; return _topology . addSourcedNode ( this , new ProcessorNode ( _topology . getUniqueStreamId ( ) , _name , functionFields , functionFields , new AggregateProcessor ( inputFields , ag...
creates brand new tuples with brand new fields
118,257
public Stream map ( MapFunction function ) { projectionValidation ( getOutputFields ( ) ) ; return _topology . addSourcedNode ( this , new ProcessorNode ( _topology . getUniqueStreamId ( ) , _name , getOutputFields ( ) , getOutputFields ( ) , new MapProcessor ( getOutputFields ( ) , new MapFunctionExecutor ( function )...
Returns a stream consisting of the result of applying the given mapping function to the values of this stream .
118,258
public Stream flatMap ( FlatMapFunction function ) { projectionValidation ( getOutputFields ( ) ) ; return _topology . addSourcedNode ( this , new ProcessorNode ( _topology . getUniqueStreamId ( ) , _name , getOutputFields ( ) , getOutputFields ( ) , new MapProcessor ( getOutputFields ( ) , new FlatMapFunctionExecutor ...
Returns a stream consisting of the results of replacing each value of this stream with the contents produced by applying the provided mapping function to each value . This has the effect of applying a one - to - many transformation to the values of the stream and then flattening the resulting elements into a new stream...
118,259
public Stream peek ( Consumer action ) { projectionValidation ( getOutputFields ( ) ) ; return _topology . addSourcedNode ( this , new ProcessorNode ( _topology . getUniqueStreamId ( ) , _name , getOutputFields ( ) , getOutputFields ( ) , new MapProcessor ( getOutputFields ( ) , new ConsumerExecutor ( action ) ) ) ) ; ...
Returns a stream consisting of the trident tuples of this stream additionally performing the provided action on each trident tuple as they are consumed from the resulting stream . This is mostly useful for debugging to see the tuples as they flow past a certain point in a pipeline .
118,260
public Stream window ( WindowConfig windowConfig , Fields inputFields , Aggregator aggregator , Fields functionFields ) { InMemoryWindowsStoreFactory inMemoryWindowsStoreFactory = new InMemoryWindowsStoreFactory ( ) ; return window ( windowConfig , inMemoryWindowsStoreFactory , inputFields , aggregator , functionFields...
Returns a stream of aggregated results based on the given window configuration which uses inmemory windowing tuple store .
118,261
public Stream window ( WindowConfig windowConfig , WindowsStoreFactory windowStoreFactory , Fields inputFields , Aggregator aggregator , Fields functionFields ) { return window ( windowConfig , windowStoreFactory , inputFields , aggregator , functionFields , true ) ; }
Returns stream of aggregated results based on the given window configuration .
118,262
public static String get_topology_id ( StormClusterState zkCluster , String storm_name ) throws Exception { List < String > active_storms = zkCluster . active_storms ( ) ; String rtn = null ; if ( active_storms != null ) { for ( String topology_id : active_storms ) { if ( ! topology_id . contains ( storm_name ) ) { con...
if a topology s name is equal to the input storm_name then return the topology id otherwise return null
118,263
public static HashMap < String , StormBase > get_all_StormBase ( StormClusterState zkCluster ) throws Exception { HashMap < String , StormBase > rtn = new HashMap < > ( ) ; List < String > active_storms = zkCluster . active_storms ( ) ; if ( active_storms != null ) { for ( String topology_id : active_storms ) { StormBa...
get all topology s StormBase
118,264
public static Map < String , SupervisorInfo > get_all_SupervisorInfo ( StormClusterState stormClusterState , RunnableCallback callback ) throws Exception { Map < String , SupervisorInfo > rtn = new TreeMap < > ( ) ; List < String > supervisorIds = stormClusterState . supervisors ( callback ) ; List < String > blacklist...
get all SupervisorInfo of storm cluster
118,265
public static DirLock tryLock ( FileSystem fs , Path dir ) throws IOException { Path lockFile = getDirLockFile ( dir ) ; try { FSDataOutputStream ostream = HdfsUtils . tryCreateFile ( fs , lockFile ) ; if ( ostream != null ) { LOG . debug ( "Thread ({}) Acquired lock on dir {}" , threadInfo ( ) , dir ) ; ostream . clos...
Get a lock on file if not already locked
118,266
public void release ( ) throws IOException { if ( ! fs . delete ( lockFile , false ) ) { LOG . error ( "Thread {} could not delete dir lock {} " , threadInfo ( ) , lockFile ) ; } else { LOG . debug ( "Thread {} Released dir lock {} " , threadInfo ( ) , lockFile ) ; } }
Release lock on dir by deleting the lock file
118,267
public static DirLock takeOwnershipIfStale ( FileSystem fs , Path dirToLock , int lockTimeoutSec ) { Path dirLockFile = getDirLockFile ( dirToLock ) ; long now = System . currentTimeMillis ( ) ; long expiryTime = now - ( lockTimeoutSec * 1000 ) ; try { long modTime = fs . getFileStatus ( dirLockFile ) . getModification...
if the lock on the directory is stale take ownership
118,268
private void setupBlobstore ( ) throws Exception { BlobStore blobStore = data . getBlobStore ( ) ; StormClusterState clusterState = data . getStormClusterState ( ) ; Set < String > localSetOfKeys = Sets . newHashSet ( blobStore . listKeys ( ) ) ; Set < String > allKeys = Sets . newHashSet ( clusterState . active_keys (...
sets up blobstore state for all current keys
118,269
private boolean check_nimbus_priority ( ) throws Exception { int gap = update_nimbus_detail ( ) ; if ( gap == 0 ) { return true ; } int left = SLAVE_NIMBUS_WAIT_TIME ; while ( left > 0 ) { LOG . info ( "nimbus.differ.count.zk is {}, so after {} seconds, nimbus will try to be leader!" , gap , left ) ; Thread . sleep ( 1...
Compared with other nimbus to get priority of this nimbus
118,270
private void checkOwnMaster ( ) throws Exception { int retry_times = 10 ; StormClusterState zkClient = data . getStormClusterState ( ) ; for ( int i = 0 ; i < retry_times ; i ++ , JStormUtils . sleepMs ( sleepTime ) ) { if ( ! zkClient . leader_existed ( ) ) { continue ; } String zkHost = zkClient . get_leader_host ( )...
Check whether current node is master
118,271
protected void doFlush ( ) { long [ ] values = unFlushed . getSnapshot ( ) . getValues ( ) ; for ( JHistogram histogram : histogramMap . values ( ) ) { for ( long val : values ) { histogram . update ( val ) ; } } if ( MetricUtils . metricAccurateCal ) { for ( long val : values ) { for ( AsmMetric metric : this . assocM...
flush temp histogram data to all windows & assoc metrics .
118,272
public void emitDirect ( int taskId , String streamId , List < Object > tuple , Object messageId ) { _delegate . emitDirect ( taskId , streamId , tuple , messageId ) ; }
Emits a tuple to the specified task on the specified output stream . This output stream must have been declared as a direct stream and the specified task must use a direct grouping on this stream to receive the message . The emitted values must be immutable .
118,273
public boolean exists ( String key ) { Path dir = getKeyDir ( key ) ; boolean res = false ; try { _fs = dir . getFileSystem ( _hadoopConf ) ; res = _fs . exists ( dir ) ; } catch ( IOException e ) { LOG . warn ( "Exception checking for exists on: " + key ) ; } return res ; }
Check if the key exists in the blob store .
118,274
public static EPlatform getOSname ( ) { if ( isAix ( ) ) { _instance . platform = EPlatform . AIX ; } else if ( isDigitalUnix ( ) ) { _instance . platform = EPlatform . Digital_Unix ; } else if ( isFreeBSD ( ) ) { _instance . platform = EPlatform . FreeBSD ; } else if ( isHPUX ( ) ) { _instance . platform = EPlatform ....
Get OS name
118,275
public void channelConnected ( ChannelHandlerContext ctx , ChannelStateEvent event ) { Channel channel = event . getChannel ( ) ; LOG . info ( "connection established to :{}, local port:{}" , client . getRemoteAddr ( ) , channel . getLocalAddress ( ) ) ; client . connectChannel ( ctx . getChannel ( ) ) ; client . handl...
Sometime when connecting to a bad channel which isn t writable this method will be called
118,276
public static void main ( String [ ] args ) { Thread . setDefaultUncaughtExceptionHandler ( new DefaultUncaughtExceptionHandler ( ) ) ; JStormServerUtils . startTaobaoJvmMonitor ( ) ; Supervisor instance = new Supervisor ( ) ; instance . run ( ) ; }
start supervisor daemon
118,277
private void refreshLocalNodeTasks ( ) { Set < Integer > localNodeTasks = workerData . getLocalNodeTasks ( ) ; if ( localNodeTasks == null || localNodeTasks . equals ( lastLocalNodeTasks ) ) { return ; } LOG . info ( "Old localNodeTasks:" + lastLocalNodeTasks + ", new:" + localNodeTasks ) ; lastLocalNodeTasks = localNo...
Don t need to take care of multiple thread racing condition one thread per task
118,278
private void updateClusterMetrics ( String topologyId , TopologyMetric tpMetric ) { if ( tpMetric . get_topologyMetric ( ) . get_metrics_size ( ) == 0 ) { return ; } MetricInfo topologyMetrics = tpMetric . get_topologyMetric ( ) ; MetricInfo clusterMetrics = MetricUtils . mkMetricInfo ( ) ; Set < String > metricNames =...
update cluster metrics local cache
118,279
public void freeAllSlots ( Cluster cluster ) { if ( ! _isAlive ) { LOG . warn ( "Freeing all slots on a dead node {} " , _nodeId ) ; } for ( Entry < String , Set < WorkerSlot > > entry : _topIdToUsedSlots . entrySet ( ) ) { cluster . freeSlots ( entry . getValue ( ) ) ; if ( _isAlive ) { _freeSlots . addAll ( entry . g...
Free all slots on this node . This will update the Cluster too .
118,280
public void free ( WorkerSlot ws , Cluster cluster , boolean forceFree ) { if ( _freeSlots . contains ( ws ) ) return ; boolean wasFound = false ; for ( Entry < String , Set < WorkerSlot > > entry : _topIdToUsedSlots . entrySet ( ) ) { Set < WorkerSlot > slots = entry . getValue ( ) ; if ( slots . remove ( ws ) ) { clu...
Frees a single slot in this node
118,281
public void freeTopology ( String topId , Cluster cluster ) { Set < WorkerSlot > slots = _topIdToUsedSlots . get ( topId ) ; if ( slots == null || slots . isEmpty ( ) ) return ; for ( WorkerSlot ws : slots ) { cluster . freeSlot ( ws ) ; if ( _isAlive ) { _freeSlots . add ( ws ) ; } } _topIdToUsedSlots . remove ( topId...
Frees all the slots for a topology .
118,282
public void assign ( String topId , Collection < ExecutorDetails > executors , Cluster cluster ) { if ( ! _isAlive ) { throw new IllegalStateException ( "Trying to adding to a dead node " + _nodeId ) ; } if ( _freeSlots . isEmpty ( ) ) { throw new IllegalStateException ( "Trying to assign to a full node " + _nodeId ) ;...
Assign a free slot on the node to the following topology and executors . This will update the cluster too .
118,283
private void updateStreamState ( Map < TaskStream , WindowState > state ) { for ( Map . Entry < TaskStream , WindowState > entry : state . entrySet ( ) ) { TaskStream taskStream = entry . getKey ( ) ; WindowState newState = entry . getValue ( ) ; WindowState curState = streamState . get ( taskStream ) ; if ( curState =...
update streamState based on stateUpdates
118,284
private void updateKeySetForBlobStore ( Set < String > keySetBlobStore , CuratorFramework zkClient ) { try { for ( String key : keySetBlobStore ) { LOG . debug ( "updating blob" ) ; BlobStoreUtils . updateKeyForBlobStore ( conf , blobStore , zkClient , key , nimbusInfo ) ; } } catch ( Exception exp ) { throw new Runtim...
Update current key list inside the blobstore if the version changes
118,285
public Set < String > getKeySetToDownload ( Set < String > blobStoreKeySet , Set < String > zookeeperKeySet ) { zookeeperKeySet . removeAll ( blobStoreKeySet ) ; LOG . debug ( "Key list to download {}" , zookeeperKeySet ) ; return zookeeperKeySet ; }
Make a key list to download
118,286
public void updateBatch ( V batch ) { if ( intervalCheck . check ( ) ) { rolling ( ) ; } synchronized ( this ) { unflushed = updater . updateBatch ( batch , unflushed ) ; } }
In order to improve performance Flush one batch to rollingWindow
118,287
public static Set < Integer > worker_output_tasks ( WorkerData workerData ) { ContextMaker context_maker = workerData . getContextMaker ( ) ; Set < Integer > taskIds = workerData . getTaskIds ( ) ; StormTopology topology = workerData . getSysTopology ( ) ; Set < Integer > rtn = new HashSet < > ( ) ; for ( Integer taskI...
get current task s output task list
118,288
@ SuppressWarnings ( "rawtypes" ) public static WorkerShutdown mk_worker ( Map conf , IContext context , String topologyId , String supervisorId , int port , String workerId , String jarPath ) throws Exception { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "topologyId:" ) . append ( topologyId ) . append ( ...
create worker instance and run it
118,289
public static List < Integer > getOldPortPids ( String port ) { String currPid = JStormUtils . process_pid ( ) ; List < Integer > ret = new ArrayList < > ( ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( "ps -Af " ) ; try { LOG . info ( "Begin to execute " + sb . toString ( ) ) ; String output = JStormUtil...
Note that if the worker s start parameter length is longer than 4096 ps - ef|grep com . alibaba . jstorm . daemon . worker . Worker can t find worker
118,290
protected boolean sample ( ) { if ( curr . increment ( ) >= freq ) { curr . set ( 0 ) ; target . set ( rand . nextInt ( freq ) ) ; } return curr . get ( ) == target . get ( ) ; }
a faster sampling way
118,291
public BaseStatefulWindowedBolt < T > withMessageIdField ( String fieldName ) { windowConfiguration . put ( Config . TOPOLOGY_BOLTS_MESSAGE_ID_FIELD_NAME , fieldName ) ; return this ; }
Specify the name of the field in the tuple that holds the message id . This is used to track the windowing boundaries and re - evaluating the windowing operation during recovery of IStatefulWindowedBolt
118,292
public void unsubscribe ( ) { List < InvocationHandler > handler = this . handlers . get ( target ) ; if ( handler != null ) { handler . remove ( this . handler ) ; } }
Removes the client method handler represented by this subscription .
118,293
public boolean shouldSendEvent ( Event event ) { double randomDouble = random . nextDouble ( ) ; return sampleRate >= Math . abs ( randomDouble ) ; }
Handles event sampling logic .
118,294
public static Set < String > parseMdcTags ( String mdcTagsString ) { if ( isNullOrEmpty ( mdcTagsString ) ) { return Collections . emptySet ( ) ; } return new HashSet < > ( Arrays . asList ( mdcTagsString . split ( "," ) ) ) ; }
Parses the provided Strings into a Set of Strings .
118,295
public static String trimString ( String string , int maxMessageLength ) { if ( string == null ) { return null ; } else if ( string . length ( ) > maxMessageLength ) { return string . substring ( 0 , maxMessageLength - 3 ) + "..." ; } else { return string ; } }
Trims a String ensuring that the maximum length isn t reached .
118,296
public static boolean safelyRemoveShutdownHook ( Thread shutDownHook ) { try { return Runtime . getRuntime ( ) . removeShutdownHook ( shutDownHook ) ; } catch ( IllegalStateException e ) { if ( e . getMessage ( ) . equals ( "Shutdown in progress" ) ) { } else { throw e ; } } return false ; }
Try to remove the shutDownHook handling the case where the VM is in shutdown process .
118,297
public void tick ( long duration , TimeUnit unit ) { this . date = new Date ( date . getTime ( ) + unit . toMillis ( duration ) ) ; }
Adjust the FixedClock by the given amount .
118,298
public UserBuilder withData ( String name , Object value ) { if ( this . data == null ) { this . data = new HashMap < > ( ) ; } this . data . put ( name , value ) ; return this ; }
Adds to the extra data for the user .
118,299
public static String jndiLookup ( String key ) { String value = null ; try { Context c = new InitialContext ( ) ; value = ( String ) c . lookup ( JNDI_PREFIX + key ) ; } catch ( NoInitialContextException e ) { logger . trace ( "JNDI not configured for Sentry (NoInitialContextEx)" ) ; } catch ( NamingException e ) { log...
Looks up for a JNDI definition of the provided key .