idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
34,200 | private String limitStringLength ( String str ) { if ( str . length ( ) > MAX_STRING_LENGTH ) { str = str . substring ( 0 , MAX_STRING_LENGTH ) + " ..." ; } return str ; } | prevents gigantic messages |
34,201 | private Map < String , Object > getRateLimitTemplateProperties ( SingularityRequest request , final SingularityEmailType emailType ) { final Builder < String , Object > templateProperties = ImmutableMap . < String , Object > builder ( ) ; templateProperties . put ( "singularityRequestLink" , mailTemplateHelpers . getSingularityRequestLink ( request . getId ( ) ) ) ; templateProperties . put ( "rateLimitAfterNotifications" , Integer . toString ( smtpConfiguration . getRateLimitAfterNotifications ( ) ) ) ; templateProperties . put ( "rateLimitPeriodFormat" , DurationFormatUtils . formatDurationHMS ( smtpConfiguration . getRateLimitPeriodMillis ( ) ) ) ; templateProperties . put ( "rateLimitCooldownFormat" , DurationFormatUtils . formatDurationHMS ( smtpConfiguration . getRateLimitCooldownMillis ( ) ) ) ; templateProperties . put ( "emailType" , emailType . name ( ) ) ; templateProperties . put ( "requestId" , request . getId ( ) ) ; templateProperties . put ( "color" , emailType . getColor ( ) ) ; return templateProperties . build ( ) ; } | Add needed information to the rate limit email Jade context . |
34,202 | private void queueMail ( final Collection < SingularityEmailDestination > destination , final SingularityRequest request , final SingularityEmailType emailType , final Optional < String > actionTaker , String subject , String body ) { RateLimitResult result = checkRateLimitForMail ( request , emailType ) ; if ( result == RateLimitResult . DONT_SEND_MAIL_IN_COOLDOWN ) { return ; } if ( result == RateLimitResult . SEND_COOLDOWN_STARTED_MAIL ) { subject = String . format ( "%s notifications for %s are being rate limited" , emailType . name ( ) , request . getId ( ) ) ; body = Jade4J . render ( rateLimitedTemplate , getRateLimitTemplateProperties ( request , emailType ) ) ; } final Set < String > toList = new HashSet < > ( ) ; final Set < String > ccList = new HashSet < > ( ) ; if ( destination . contains ( SingularityEmailDestination . OWNERS ) && request . getOwners ( ) . isPresent ( ) && ! request . getOwners ( ) . get ( ) . isEmpty ( ) ) { toList . addAll ( request . getOwners ( ) . get ( ) ) ; } if ( destination . contains ( SingularityEmailDestination . ADMINS ) && ! smtpConfiguration . getAdmins ( ) . isEmpty ( ) ) { if ( toList . isEmpty ( ) ) { toList . addAll ( smtpConfiguration . getAdmins ( ) ) ; } else { ccList . addAll ( smtpConfiguration . getAdmins ( ) ) ; } } if ( actionTaker . isPresent ( ) && ! Strings . isNullOrEmpty ( actionTaker . get ( ) ) ) { if ( destination . contains ( SingularityEmailDestination . ACTION_TAKER ) ) { toList . add ( actionTaker . get ( ) ) ; } else { final Iterator < String > i = toList . iterator ( ) ; while ( i . hasNext ( ) ) { if ( actionTaker . get ( ) . equalsIgnoreCase ( i . next ( ) ) ) { i . remove ( ) ; } } } } Set < String > emailBlacklist = Sets . newHashSet ( notificationsManager . getBlacklist ( ) ) ; toList . removeAll ( emailBlacklist ) ; ccList . removeAll ( emailBlacklist ) ; smtpSender . queueMail ( Lists . newArrayList ( toList ) , Lists . newArrayList ( ccList ) , subject , body ) ; } | Check to see if email should be rate limited and if so send a rate limit email notification . Next attempt to email will immediately return . |
34,203 | public Collection < SingularityRequestParent > getSingularityRequests ( ) { final Function < String , String > requestUri = ( host ) -> String . format ( REQUESTS_FORMAT , getApiBase ( host ) ) ; return getCollection ( requestUri , "[ACTIVE, PAUSED, COOLDOWN] requests" , REQUESTS_COLLECTION ) ; } | Get all singularity requests that their state is either ACTIVE PAUSED or COOLDOWN |
34,204 | public Collection < SingularityRequestParent > getActiveSingularityRequests ( ) { final Function < String , String > requestUri = ( host ) -> String . format ( REQUESTS_GET_ACTIVE_FORMAT , getApiBase ( host ) ) ; return getCollection ( requestUri , "ACTIVE requests" , REQUESTS_COLLECTION ) ; } | Get all requests that their state is ACTIVE |
34,205 | public Collection < SingularityRequestParent > getPausedSingularityRequests ( ) { final Function < String , String > requestUri = ( host ) -> String . format ( REQUESTS_GET_PAUSED_FORMAT , getApiBase ( host ) ) ; return getCollection ( requestUri , "PAUSED requests" , REQUESTS_COLLECTION ) ; } | Get all requests that their state is PAUSED ACTIVE requests are paused by users which is equivalent to stop their tasks from running without undeploying them |
34,206 | public Collection < SingularityRequestParent > getCoolDownSingularityRequests ( ) { final Function < String , String > requestUri = ( host ) -> String . format ( REQUESTS_GET_COOLDOWN_FORMAT , getApiBase ( host ) ) ; return getCollection ( requestUri , "COOLDOWN requests" , REQUESTS_COLLECTION ) ; } | Get all requests that has been set to a COOLDOWN state by singularity |
34,207 | public Collection < SingularityPendingRequest > getPendingSingularityRequests ( ) { final Function < String , String > requestUri = ( host ) -> String . format ( REQUESTS_GET_PENDING_FORMAT , getApiBase ( host ) ) ; return getCollection ( requestUri , "pending requests" , PENDING_REQUESTS_COLLECTION ) ; } | Get all requests that are pending to become ACTIVE |
34,208 | public Collection < SingularitySlave > getSlaves ( Optional < MachineState > slaveState ) { final Function < String , String > requestUri = ( host ) -> String . format ( SLAVES_FORMAT , getApiBase ( host ) ) ; Optional < Map < String , Object > > maybeQueryParams = Optional . absent ( ) ; String type = "slaves" ; if ( slaveState . isPresent ( ) ) { maybeQueryParams = Optional . of ( ImmutableMap . of ( "state" , slaveState . get ( ) . toString ( ) ) ) ; type = String . format ( "%s slaves" , slaveState . get ( ) . toString ( ) ) ; } return getCollectionWithParams ( requestUri , type , maybeQueryParams , SLAVES_COLLECTION ) ; } | Retrieve the list of all known slaves optionally filtering by a particular slave state |
34,209 | public Optional < SingularitySlave > getSlave ( String slaveId ) { final Function < String , String > requestUri = ( host ) -> String . format ( SLAVE_DETAIL_FORMAT , getApiBase ( host ) , slaveId ) ; return getSingle ( requestUri , "slave" , slaveId , SingularitySlave . class ) ; } | Retrieve a single slave by ID |
34,210 | public Optional < SingularityTaskHistory > getHistoryForTask ( String taskId ) { final Function < String , String > requestUri = ( host ) -> String . format ( TASK_HISTORY_FORMAT , getApiBase ( host ) , taskId ) ; return getSingle ( requestUri , "task history" , taskId , SingularityTaskHistory . class ) ; } | Retrieve information about an inactive task by its id |
34,211 | public Optional < SingularityTaskIdHistory > getHistoryForTask ( String requestId , String runId ) { return getTaskIdHistoryByRunId ( requestId , runId ) ; } | Retrieve the task id and state for an inactive task by its runId |
34,212 | public Optional < SingularitySandbox > browseTaskSandBox ( String taskId , String path ) { final Function < String , String > requestUrl = ( host ) -> String . format ( SANDBOX_BROWSE_FORMAT , getApiBase ( host ) , taskId ) ; return getSingleWithParams ( requestUrl , "browse sandbox for task" , taskId , Optional . of ( ImmutableMap . of ( "path" , path ) ) , SingularitySandbox . class ) ; } | Retrieve information about a specific task s sandbox |
34,213 | public Optional < MesosFileChunkObject > readSandBoxFile ( String taskId , String path , Optional < String > grep , Optional < Long > offset , Optional < Long > length ) { final Function < String , String > requestUrl = ( host ) -> String . format ( SANDBOX_READ_FILE_FORMAT , getApiBase ( host ) , taskId ) ; Builder < String , Object > queryParamBuider = ImmutableMap . < String , Object > builder ( ) . put ( "path" , path ) ; if ( grep . isPresent ( ) ) { queryParamBuider . put ( "grep" , grep . get ( ) ) ; } if ( offset . isPresent ( ) ) { queryParamBuider . put ( "offset" , offset . get ( ) ) ; } if ( length . isPresent ( ) ) { queryParamBuider . put ( "length" , length . get ( ) ) ; } return getSingleWithParams ( requestUrl , "Read sandbox file for task" , taskId , Optional . of ( queryParamBuider . build ( ) ) , MesosFileChunkObject . class ) ; } | Retrieve part of the contents of a file in a specific task s sandbox . |
34,214 | public Collection < SingularityS3Log > getTaskLogs ( String taskId ) { final Function < String , String > requestUri = ( host ) -> String . format ( S3_LOG_GET_TASK_LOGS , getApiBase ( host ) , taskId ) ; final String type = String . format ( "S3 logs for task %s" , taskId ) ; return getCollection ( requestUri , type , S3_LOG_COLLECTION ) ; } | Retrieve the list of logs stored in S3 for a specific task |
34,215 | public Collection < SingularityS3Log > getRequestLogs ( String requestId ) { final Function < String , String > requestUri = ( host ) -> String . format ( S3_LOG_GET_REQUEST_LOGS , getApiBase ( host ) , requestId ) ; final String type = String . format ( "S3 logs for request %s" , requestId ) ; return getCollection ( requestUri , type , S3_LOG_COLLECTION ) ; } | Retrieve the list of logs stored in S3 for a specific request |
34,216 | public Collection < SingularityS3Log > getDeployLogs ( String requestId , String deployId ) { final Function < String , String > requestUri = ( host ) -> String . format ( S3_LOG_GET_DEPLOY_LOGS , getApiBase ( host ) , requestId , deployId ) ; final String type = String . format ( "S3 logs for deploy %s of request %s" , deployId , requestId ) ; return getCollection ( requestUri , type , S3_LOG_COLLECTION ) ; } | Retrieve the list of logs stored in S3 for a specific deploy if a singularity request |
34,217 | public Collection < SingularityRequestGroup > getRequestGroups ( ) { final Function < String , String > requestUri = ( host ) -> String . format ( REQUEST_GROUPS_FORMAT , getApiBase ( host ) ) ; return getCollection ( requestUri , "request groups" , REQUEST_GROUP_COLLECTION ) ; } | Retrieve the list of request groups |
34,218 | public Optional < SingularityRequestGroup > getRequestGroup ( String requestGroupId ) { final Function < String , String > requestUri = ( host ) -> String . format ( REQUEST_GROUP_FORMAT , getApiBase ( host ) , requestGroupId ) ; return getSingle ( requestUri , "request group" , requestGroupId , SingularityRequestGroup . class ) ; } | Retrieve a specific request group by id |
34,219 | public boolean isUserAuthorized ( String requestId , String userId , SingularityAuthorizationScope scope ) { final Function < String , String > requestUri = ( host ) -> String . format ( AUTH_CHECK_USER_FORMAT , getApiBase ( host ) , requestId , userId ) ; Map < String , Object > params = Collections . singletonMap ( "scope" , scope . name ( ) ) ; HttpResponse response = executeGetSingleWithParams ( requestUri , "auth check" , "" , Optional . of ( params ) ) ; return response . isSuccess ( ) ; } | Check if a user is authorized for the specified scope on the specified request |
34,220 | public Optional < SingularityTaskState > getTaskState ( String requestId , String runId ) { final Function < String , String > requestUri = ( host ) -> String . format ( TRACK_BY_RUN_ID_FORMAT , getApiBase ( host ) , requestId , runId ) ; return getSingle ( requestUri , "track by task id" , String . format ( "%s-%s" , requestId , runId ) , SingularityTaskState . class ) ; } | Get the current state of a task by its run IDg |
34,221 | private void prepareCommand ( final TaskInfo . Builder bldr , final SingularityTaskId taskId , final SingularityTaskRequest task , final SingularityOfferHolder offerHolder , final Optional < long [ ] > ports ) { CommandInfo . Builder commandBldr = CommandInfo . newBuilder ( ) ; Optional < String > specifiedUser = task . getPendingTask ( ) . getRunAsUserOverride ( ) . or ( task . getDeploy ( ) . getUser ( ) ) ; if ( specifiedUser . isPresent ( ) ) { commandBldr . setUser ( specifiedUser . get ( ) ) ; } if ( task . getDeploy ( ) . getCommand ( ) . isPresent ( ) ) { commandBldr . setValue ( task . getDeploy ( ) . getCommand ( ) . get ( ) ) ; } if ( task . getDeploy ( ) . getArguments ( ) . isPresent ( ) ) { commandBldr . addAllArguments ( task . getDeploy ( ) . getArguments ( ) . get ( ) ) ; } if ( task . getPendingTask ( ) . getCmdLineArgsList ( ) . isPresent ( ) ) { commandBldr . addAllArguments ( task . getPendingTask ( ) . getCmdLineArgsList ( ) . get ( ) ) ; } if ( task . getDeploy ( ) . getShell ( ) . isPresent ( ) ) { commandBldr . setShell ( task . getDeploy ( ) . getShell ( ) . get ( ) ) ; } else if ( ( task . getDeploy ( ) . getArguments ( ) . isPresent ( ) && ! task . getDeploy ( ) . getArguments ( ) . get ( ) . isEmpty ( ) ) || task . getDeploy ( ) . getContainerInfo ( ) . isPresent ( ) || ( task . getPendingTask ( ) . getCmdLineArgsList ( ) . isPresent ( ) && ! task . getPendingTask ( ) . getCmdLineArgsList ( ) . get ( ) . isEmpty ( ) ) ) { commandBldr . setShell ( false ) ; } List < SingularityMesosArtifact > combinedArtifacts = new ArrayList < > ( ) ; combinedArtifacts . addAll ( task . getDeploy ( ) . getUris ( ) . or ( Collections . emptyList ( ) ) ) ; combinedArtifacts . addAll ( task . getPendingTask ( ) . getExtraArtifacts ( ) ) ; prepareMesosUriDownloads ( combinedArtifacts , commandBldr ) ; prepareEnvironment ( task , taskId , commandBldr , offerHolder , ports ) ; bldr . setCommand ( commandBldr ) ; } | Prepares the Mesos TaskInfo object when using the Mesos Default Executor . |
34,222 | public static AsyncSemaphoreBuilder newBuilder ( Supplier < Integer > concurrentRequestLimit , ScheduledExecutorService flushingExecutor ) { return new AsyncSemaphoreBuilder ( new PermitSource ( concurrentRequestLimit ) , flushingExecutor ) ; } | Create an AsyncSemaphore with the given limit . |
34,223 | private boolean tryEnqueueAttempt ( DelayedExecution < T > delayedExecution ) { int rejectionThreshold = queueRejectionThreshold . get ( ) ; if ( rejectionThreshold < 0 ) { return requestQueue . offer ( delayedExecution ) ; } long stamp = stampedLock . readLock ( ) ; try { while ( requestQueue . size ( ) < rejectionThreshold ) { long writeStamp = stampedLock . tryConvertToWriteLock ( stamp ) ; if ( writeStamp != 0L ) { stamp = writeStamp ; return requestQueue . offer ( delayedExecution ) ; } else { stampedLock . unlock ( stamp ) ; stamp = stampedLock . writeLock ( ) ; } } return false ; } finally { stampedLock . unlock ( stamp ) ; } } | enqueue the attempt into our underlying queue . since it s expensive to dynamically resize the queue we have a separate rejection threshold which if less than 0 is ignored but otherwise is the practical cap on the size of the queue . |
34,224 | private static boolean validateToken ( String originalToken , String storedToken ) throws NoSuchAlgorithmException , InvalidKeySpecException { String [ ] parts = storedToken . split ( ":" ) ; int iterations = Integer . parseInt ( parts [ 0 ] ) ; byte [ ] salt = fromHex ( parts [ 1 ] ) ; byte [ ] hash = fromHex ( parts [ 2 ] ) ; PBEKeySpec spec = new PBEKeySpec ( originalToken . toCharArray ( ) , salt , iterations , hash . length * 8 ) ; SecretKeyFactory skf = SecretKeyFactory . getInstance ( "PBKDF2WithHmacSHA1" ) ; byte [ ] testHash = skf . generateSecret ( spec ) . getEncoded ( ) ; int diff = hash . length ^ testHash . length ; for ( int i = 0 ; i < hash . length && i < testHash . length ; i ++ ) { diff |= hash [ i ] ^ testHash [ i ] ; } return diff == 0 ; } | Implementation of PBKDF2WithHmacSHA1 |
34,225 | public void registered ( ExecutorDriver executorDriver , Protos . ExecutorInfo executorInfo , Protos . FrameworkInfo frameworkInfo , Protos . SlaveInfo slaveInfo ) { LOG . debug ( "Registered {} with Mesos slave {} for framework {}" , executorInfo . getExecutorId ( ) . getValue ( ) , slaveInfo . getId ( ) . getValue ( ) , frameworkInfo . getId ( ) . getValue ( ) ) ; LOG . trace ( "Registered {} with Mesos slave {} for framework {}" , MesosUtils . formatForLogging ( executorInfo ) , MesosUtils . formatForLogging ( slaveInfo ) , MesosUtils . formatForLogging ( frameworkInfo ) ) ; } | Invoked once the executor driver has been able to successfully connect with Mesos . In particular a scheduler can pass some data to it s executors through the FrameworkInfo . ExecutorInfo s data field . |
34,226 | public void reregistered ( ExecutorDriver executorDriver , Protos . SlaveInfo slaveInfo ) { LOG . debug ( "Re-registered with Mesos slave {}" , slaveInfo . getId ( ) . getValue ( ) ) ; LOG . info ( "Re-registered with Mesos slave {}" , MesosUtils . formatForLogging ( slaveInfo ) ) ; } | Invoked when the executor re - registers with a restarted slave . |
34,227 | public void subscribe ( URI mesosMasterURI , SingularityMesosScheduler scheduler ) throws URISyntaxException { FrameworkInfo frameworkInfo = buildFrameworkInfo ( ) ; if ( mesosMasterURI == null || mesosMasterURI . getScheme ( ) . contains ( "zk" ) ) { throw new IllegalArgumentException ( String . format ( "Must use master address for http api (e.g. http://localhost:5050/api/v1/scheduler) was %s" , mesosMasterURI ) ) ; } if ( openStream == null || openStream . isUnsubscribed ( ) ) { if ( subscriberThread != null ) { subscriberThread . interrupt ( ) ; } subscriberThread = new Thread ( ) { public void run ( ) { try { connect ( mesosMasterURI , frameworkInfo , scheduler ) ; } catch ( RuntimeException | URISyntaxException e ) { LOG . error ( "Could not connect: " , e ) ; scheduler . onConnectException ( e ) ; } } } ; subscriberThread . start ( ) ; } } | The first call to mesos needed to setup connection properly and identify a framework . |
34,228 | public void acknowledge ( AgentID agentId , TaskID taskId , ByteString uuid ) { Builder acknowledge = build ( ) . setAcknowledge ( Acknowledge . newBuilder ( ) . setAgentId ( agentId ) . setTaskId ( taskId ) . setUuid ( uuid ) ) ; sendCall ( acknowledge , Type . ACKNOWLEDGE ) ; } | Sent by the scheduler to acknowledge a status update . Note that with the new API schedulers are responsible for explicitly acknowledging the receipt of status updates that have status . uuid set . These status updates are retried until they are acknowledged by the scheduler . The scheduler must not acknowledge status updates that do not have status . uuid set as they are not retried . The uuid field contains raw bytes encoded in Base64 . |
34,229 | public void reconcile ( List < Reconcile . Task > tasks ) { Builder reconsile = build ( ) . setReconcile ( Reconcile . newBuilder ( ) . addAllTasks ( tasks ) ) ; sendCall ( reconsile , Type . RECONCILE ) ; } | Sent by the scheduler to query the status of non - terminal tasks . This causes the master to send back UPDATE events for each task in the list . Tasks that are no longer known to Mesos will result in TASK_LOST updates . If the list of tasks is empty master will send UPDATE events for all currently known tasks of the framework . |
34,230 | public void frameworkMessage ( ExecutorID executorId , AgentID agentId , byte [ ] data ) { Builder message = build ( ) . setMessage ( Message . newBuilder ( ) . setAgentId ( agentId ) . setExecutorId ( executorId ) . setData ( ByteString . copyFrom ( data ) ) ) ; sendCall ( message , Type . MESSAGE ) ; } | Sent by the scheduler to send arbitrary binary data to the executor . Mesos neither interprets this data nor makes any guarantees about the delivery of this message to the executor . data is raw bytes encoded in Base64 . |
34,231 | public static CompletableFuture < Timeout > timeoutFuture ( HashedWheelTimer hwt , long delay , TimeUnit timeUnit ) { try { CompletableFuture < Timeout > future = new CompletableFuture < > ( ) ; hwt . newTimeout ( future :: complete , delay , timeUnit ) ; return future ; } catch ( Throwable t ) { return exceptionalFuture ( t ) ; } } | Return a future that completes with a timeout after a delay . |
34,232 | private Collection < String > getS3PrefixesForTask ( S3Configuration s3Configuration , SingularityTaskId taskId , Optional < Long > startArg , Optional < Long > endArg , String group , SingularityUser user ) { Optional < SingularityTaskHistory > history = getTaskHistory ( taskId , user ) ; long start = taskId . getStartedAt ( ) ; if ( startArg . isPresent ( ) ) { start = Math . max ( startArg . get ( ) , start ) ; } long end = start + s3Configuration . getMissingTaskDefaultS3SearchPeriodMillis ( ) ; if ( history . isPresent ( ) ) { SimplifiedTaskState taskState = SingularityTaskHistoryUpdate . getCurrentState ( history . get ( ) . getTaskUpdates ( ) ) ; if ( taskState == SimplifiedTaskState . DONE ) { end = Iterables . getLast ( history . get ( ) . getTaskUpdates ( ) ) . getTimestamp ( ) ; } else { end = System . currentTimeMillis ( ) ; } } if ( endArg . isPresent ( ) ) { end = Math . min ( endArg . get ( ) , end ) ; } Optional < String > tag = Optional . absent ( ) ; if ( history . isPresent ( ) && history . get ( ) . getTask ( ) . getTaskRequest ( ) . getDeploy ( ) . getExecutorData ( ) . isPresent ( ) ) { tag = history . get ( ) . getTask ( ) . getTaskRequest ( ) . getDeploy ( ) . getExecutorData ( ) . get ( ) . getLoggingTag ( ) ; } Collection < String > prefixes = SingularityS3FormatHelper . getS3KeyPrefixes ( s3Configuration . getS3KeyFormat ( ) , taskId , tag , start , end , group ) ; for ( SingularityS3UploaderFile additionalFile : s3Configuration . getS3UploaderAdditionalFiles ( ) ) { if ( additionalFile . getS3UploaderKeyPattern ( ) . isPresent ( ) && ! additionalFile . getS3UploaderKeyPattern ( ) . get ( ) . equals ( s3Configuration . getS3KeyFormat ( ) ) ) { prefixes . addAll ( SingularityS3FormatHelper . getS3KeyPrefixes ( additionalFile . getS3UploaderKeyPattern ( ) . get ( ) , taskId , tag , start , end , group ) ) ; } } LOG . trace ( "Task {} got S3 prefixes {} for start {}, end {}, tag {}" , taskId , prefixes , start , end , tag ) ; return prefixes ; } | Generation of prefixes |
34,233 | private Optional < String > getRequestGroupForTask ( final SingularityTaskId taskId , SingularityUser user ) { Optional < SingularityTaskHistory > maybeTaskHistory = getTaskHistory ( taskId , user ) ; if ( maybeTaskHistory . isPresent ( ) ) { SingularityRequest request = maybeTaskHistory . get ( ) . getTask ( ) . getTaskRequest ( ) . getRequest ( ) ; authorizationHelper . checkForAuthorization ( request , user , SingularityAuthorizationScope . READ ) ; return request . getGroup ( ) ; } else { return getRequestGroup ( taskId . getRequestId ( ) , user ) ; } } | Finding request group |
34,234 | public void saveTaskUpdateForRetry ( SingularityTaskHistoryUpdate taskHistoryUpdate ) { String parentPath = ZKPaths . makePath ( SNS_TASK_RETRY_ROOT , taskHistoryUpdate . getTaskId ( ) . getRequestId ( ) ) ; if ( ! isChildNodeCountSafe ( parentPath ) ) { LOG . warn ( "Too many queued webhooks for path {}, dropping" , parentPath ) ; return ; } String updatePath = ZKPaths . makePath ( SNS_TASK_RETRY_ROOT , taskHistoryUpdate . getTaskId ( ) . getRequestId ( ) , getTaskHistoryUpdateId ( taskHistoryUpdate ) ) ; save ( updatePath , taskHistoryUpdate , taskHistoryUpdateTranscoder ) ; } | Methods for use with sns poller |
34,235 | private Optional < Long > getMaybeTaskLogReadOffset ( final String slaveHostname , final String fullPath , final Long logLength , Optional < SingularityTask > task ) { long offset = 0 ; long maxOffset = smtpConfiguration . get ( ) . getMaxTaskLogSearchOffset ( ) ; Optional < Pattern > maybePattern = getLogErrorRegex ( task ) ; Pattern pattern ; if ( maybePattern . isPresent ( ) ) { pattern = maybePattern . get ( ) ; } else { LOG . trace ( "Could not get regex pattern. Reading from bottom of file instead." ) ; return getMaybeTaskLogEndOfFileOffset ( slaveHostname , fullPath , logLength ) ; } long length = logLength + pattern . toString ( ) . length ( ) ; Optional < MesosFileChunkObject > logChunkObject ; Optional < MesosFileChunkObject > previous = Optional . absent ( ) ; while ( offset <= maxOffset ) { try { logChunkObject = sandboxManager . read ( slaveHostname , fullPath , Optional . of ( offset ) , Optional . of ( length ) ) ; } catch ( RuntimeException e ) { LOG . error ( "Sandboxmanager failed to read {} on slave {}" , fullPath , slaveHostname , e ) ; return Optional . absent ( ) ; } if ( logChunkObject . isPresent ( ) ) { if ( logChunkObject . get ( ) . getData ( ) . equals ( "" ) ) { if ( previous . isPresent ( ) ) { long end = previous . get ( ) . getOffset ( ) + previous . get ( ) . getData ( ) . length ( ) ; return Optional . of ( end - logLength ) ; } return Optional . absent ( ) ; } Matcher matcher = pattern . matcher ( logChunkObject . get ( ) . getData ( ) ) ; if ( matcher . find ( ) ) { return Optional . of ( offset + matcher . start ( ) ) ; } else { offset += logLength ; } } else { LOG . error ( "Failed to read log file {}" , fullPath ) ; return Optional . absent ( ) ; } previous = logChunkObject ; } LOG . trace ( "Searched through the first {} bytes of file {} and didn't find an error. Tailing bottom of file instead" , maxOffset , fullPath ) ; return getMaybeTaskLogEndOfFileOffset ( slaveHostname , fullPath , logLength ) ; } | Searches through the file looking for first error |
34,236 | private MBeanPluginContext createMBeanPluginContext ( ) { return new MBeanPluginContext ( ) { public ObjectName registerMBean ( Object pMBean , String ... pOptionalName ) throws MalformedObjectNameException , NotCompliantMBeanException , InstanceAlreadyExistsException { return MBeanServerHandler . this . registerMBean ( pMBean , pOptionalName ) ; } public void each ( ObjectName pObjectName , MBeanEachCallback pCallback ) throws IOException , ReflectionException , MBeanException { mBeanServerManager . each ( pObjectName , pCallback ) ; } public < R > R call ( ObjectName pObjectName , MBeanAction < R > pMBeanAction , Object ... pExtraArgs ) throws IOException , ReflectionException , MBeanException , AttributeNotFoundException , InstanceNotFoundException { return mBeanServerManager . call ( pObjectName , pMBeanAction , pExtraArgs ) ; } public Set < ObjectName > queryNames ( ObjectName pObjectName ) throws IOException { return mBeanServerManager . queryNames ( pObjectName ) ; } public boolean hasMBeansListChangedSince ( long pTimestamp ) { return mBeanServerManager . hasMBeansListChangedSince ( pTimestamp ) ; } } ; } | Delegate to internal objects |
34,237 | private void initServerHandle ( Configuration pConfig , LogHandler pLogHandler , List < ServerDetector > pDetectors ) { serverHandle = detectServers ( pDetectors , pLogHandler ) ; if ( serverHandle != null ) { serverHandle . postDetect ( mBeanServerManager , pConfig , pLogHandler ) ; } } | Initialize the server handle . |
34,238 | public Object dispatchRequest ( JsonRequestHandler pRequestHandler , JmxRequest pJmxReq ) throws InstanceNotFoundException , AttributeNotFoundException , ReflectionException , MBeanException , NotChangedException { serverHandle . preDispatch ( mBeanServerManager , pJmxReq ) ; if ( pRequestHandler . handleAllServersAtOnce ( pJmxReq ) ) { try { return pRequestHandler . handleRequest ( mBeanServerManager , pJmxReq ) ; } catch ( IOException e ) { throw new IllegalStateException ( "Internal: IOException " + e + ". Shouldn't happen." , e ) ; } } else { return mBeanServerManager . handleRequest ( pRequestHandler , pJmxReq ) ; } } | Dispatch a request to the MBeanServer which can handle it |
34,239 | public final ObjectName registerMBean ( Object pMBean , String ... pOptionalName ) throws MalformedObjectNameException , NotCompliantMBeanException , InstanceAlreadyExistsException { synchronized ( mBeanHandles ) { MBeanServer server = ManagementFactory . getPlatformMBeanServer ( ) ; try { String name = pOptionalName != null && pOptionalName . length > 0 ? pOptionalName [ 0 ] : null ; ObjectName registeredName = serverHandle . registerMBeanAtServer ( server , pMBean , name ) ; mBeanHandles . add ( new MBeanHandle ( server , registeredName ) ) ; return registeredName ; } catch ( RuntimeException exp ) { throw new IllegalStateException ( "Could not register " + pMBean + ": " + exp , exp ) ; } catch ( MBeanRegistrationException exp ) { throw new IllegalStateException ( "Could not register " + pMBean + ": " + exp , exp ) ; } } } | Register a MBean under a certain name to the platform MBeanServer |
34,240 | public final void destroy ( ) throws JMException { synchronized ( mBeanHandles ) { List < JMException > exceptions = new ArrayList < JMException > ( ) ; List < MBeanHandle > unregistered = new ArrayList < MBeanHandle > ( ) ; for ( MBeanHandle handle : mBeanHandles ) { try { unregistered . add ( handle ) ; handle . server . unregisterMBean ( handle . objectName ) ; } catch ( InstanceNotFoundException e ) { exceptions . add ( e ) ; } catch ( MBeanRegistrationException e ) { exceptions . add ( e ) ; } } mBeanHandles . removeAll ( unregistered ) ; if ( exceptions . size ( ) == 1 ) { throw exceptions . get ( 0 ) ; } else if ( exceptions . size ( ) > 1 ) { StringBuilder ret = new StringBuilder ( ) ; for ( JMException e : exceptions ) { ret . append ( e . getMessage ( ) ) . append ( ", " ) ; } throw new JMException ( ret . substring ( 0 , ret . length ( ) - 2 ) ) ; } } mBeanServerManager . destroy ( ) ; } | Unregister all previously registered MBean . This is tried for all previously registered MBeans |
34,241 | private void initMBean ( ) { try { registerMBean ( this , getObjectName ( ) ) ; } catch ( InstanceAlreadyExistsException exp ) { } catch ( MalformedObjectNameException e ) { throw new IllegalStateException ( "Internal Error: Own ObjectName " + getObjectName ( ) + " is malformed" , e ) ; } catch ( NotCompliantMBeanException e ) { throw new IllegalStateException ( "Internal Error: " + this . getClass ( ) . getName ( ) + " is not a compliant MBean" , e ) ; } } | Initialise this server handler and register as an MBean |
34,242 | public static List < ServerDetector > lookupDetectors ( ) { List < ServerDetector > detectors = ServiceObjectFactory . createServiceObjects ( "META-INF/detectors-default" , "META-INF/detectors" ) ; detectors . add ( new FallbackServerDetector ( ) ) ; return detectors ; } | Lookup all registered detectors + a default detector |
34,243 | private ServerHandle detectServers ( List < ServerDetector > pDetectors , LogHandler pLogHandler ) { for ( ServerDetector detector : pDetectors ) { try { ServerHandle info = detector . detect ( mBeanServerManager ) ; if ( info != null ) { return info ; } } catch ( Exception exp ) { pLogHandler . error ( "Error while using detector " + detector . getClass ( ) . getSimpleName ( ) + ": " + exp , exp ) ; } } return null ; } | by a lookup mechanism queried and thrown away after this method |
34,244 | private boolean hasComplexKeys ( TabularType pType ) { List < String > indexes = pType . getIndexNames ( ) ; CompositeType rowType = pType . getRowType ( ) ; for ( String index : indexes ) { if ( ! ( rowType . getType ( index ) instanceof SimpleType ) ) { return true ; } } return false ; } | Check whether all keys are simple types or not |
34,245 | private Object convertTabularDataDirectly ( TabularData pTd , Stack < String > pExtraArgs , ObjectToJsonConverter pConverter ) throws AttributeNotFoundException { if ( ! pExtraArgs . empty ( ) ) { throw new IllegalArgumentException ( "Cannot use a path for converting tabular data with complex keys (" + pTd . getTabularType ( ) . getRowType ( ) + ")" ) ; } JSONObject ret = new JSONObject ( ) ; JSONArray indexNames = new JSONArray ( ) ; TabularType type = pTd . getTabularType ( ) ; for ( String index : type . getIndexNames ( ) ) { indexNames . add ( index ) ; } ret . put ( "indexNames" , indexNames ) ; JSONArray values = new JSONArray ( ) ; for ( CompositeData cd : ( Collection < CompositeData > ) pTd . values ( ) ) { values . add ( pConverter . extractObject ( cd , pExtraArgs , true ) ) ; } ret . put ( "values" , values ) ; return ret ; } | Convert to a direct representation of the tabular data |
34,246 | ObjectName findMatchingMBeanPattern ( ObjectName pName ) { for ( ObjectName pattern : patterns ) { if ( pattern . apply ( pName ) ) { return pattern ; } } return null ; } | Given a MBean name return a pattern previously added and which matches this MBean name . Note that patterns might not overlap since the order in which they are tried is undefined . |
34,247 | private static ClassLoader createClassLoader ( File toolsJar ) throws MalformedURLException { final URL urls [ ] = new URL [ ] { toolsJar . toURI ( ) . toURL ( ) } ; if ( System . getSecurityManager ( ) == null ) { return new URLClassLoader ( urls , getParentClassLoader ( ) ) ; } else { return AccessController . doPrivileged ( new PrivilegedAction < ClassLoader > ( ) { public ClassLoader run ( ) { return new URLClassLoader ( urls , getParentClassLoader ( ) ) ; } } ) ; } } | Create a classloader and respect a security manager if installed |
34,248 | public boolean authenticate ( HttpServletRequest pRequest ) { String auth = pRequest . getHeader ( "Authorization" ) ; if ( auth == null ) { return false ; } AuthorizationHeaderParser . Result authInfo = AuthorizationHeaderParser . parse ( auth ) ; return authInfo . isValid ( ) && doAuthenticate ( pRequest , authInfo ) ; } | Authenticate the given request |
34,249 | public static Result parse ( String pAuthInfo ) { StringTokenizer stok = new StringTokenizer ( pAuthInfo ) ; String method = stok . nextToken ( ) ; if ( ! HttpServletRequest . BASIC_AUTH . equalsIgnoreCase ( method ) ) { throw new IllegalArgumentException ( "Only BasicAuthentication is supported" ) ; } String b64Auth = stok . nextToken ( ) ; String auth = new String ( Base64Util . decode ( b64Auth ) ) ; int p = auth . indexOf ( ':' ) ; String user ; String password ; boolean valid ; if ( p != - 1 ) { user = auth . substring ( 0 , p ) ; password = auth . substring ( p + 1 ) ; valid = true ; } else { valid = false ; user = null ; password = null ; } return new Result ( method , user , password , valid ) ; } | Parse the HTTP authorization header |
34,250 | public Object doHandleRequest ( MBeanServerConnection pServer , JmxReadRequest pRequest ) throws InstanceNotFoundException , AttributeNotFoundException , ReflectionException , MBeanException , IOException { checkRestriction ( pRequest . getObjectName ( ) , pRequest . getAttributeName ( ) ) ; return pServer . getAttribute ( pRequest . getObjectName ( ) , pRequest . getAttributeName ( ) ) ; } | Used for a request to a single attribute from a single MBean . Merging of MBeanServers is done one layer above . |
34,251 | private List < String > filterAttributeNames ( MBeanServerExecutor pSeverManager , ObjectName pName , List < String > pNames ) throws IOException , ReflectionException , MBeanException , AttributeNotFoundException , InstanceNotFoundException { Set < String > attrs = new HashSet < String > ( getAllAttributesNames ( pSeverManager , pName ) ) ; List < String > ret = new ArrayList < String > ( ) ; for ( String name : pNames ) { if ( attrs . contains ( name ) ) { ret . add ( name ) ; } } return ret ; } | Return only those attributes of an mbean which has one of the given names |
34,252 | private List < String > resolveAttributes ( MBeanServerExecutor pServers , ObjectName pMBeanName , List < String > pAttributeNames ) throws IOException , ReflectionException , MBeanException , AttributeNotFoundException , InstanceNotFoundException { List < String > attributes = pAttributeNames ; if ( shouldAllAttributesBeFetched ( pAttributeNames ) ) { attributes = getAllAttributesNames ( pServers , pMBeanName ) ; } return attributes ; } | Resolve attributes and look up attribute names if all attributes need to be fetched . |
34,253 | private MBeanInfo getMBeanInfo ( MBeanServerExecutor pServerManager , ObjectName pObjectName ) throws IOException , ReflectionException , MBeanException , AttributeNotFoundException , InstanceNotFoundException { return pServerManager . call ( pObjectName , MBEAN_INFO_HANDLER ) ; } | Get the MBeanInfo from one of the provided MBeanServers |
34,254 | private Object getAttribute ( MBeanServerExecutor pServerManager , ObjectName pMBeanName , String attribute ) throws MBeanException , ReflectionException , IOException , AttributeNotFoundException , InstanceNotFoundException { return pServerManager . call ( pMBeanName , MBEAN_ATTRIBUTE_READ_HANDLER , attribute ) ; } | Try multiple servers for fetching an attribute |
34,255 | private List < String > getAllAttributesNames ( MBeanServerExecutor pServerManager , ObjectName pObjectName ) throws IOException , ReflectionException , MBeanException , AttributeNotFoundException , InstanceNotFoundException { MBeanInfo mBeanInfo = getMBeanInfo ( pServerManager , pObjectName ) ; List < String > ret = new ArrayList < String > ( ) ; for ( MBeanAttributeInfo attrInfo : mBeanInfo . getAttributes ( ) ) { if ( attrInfo . isReadable ( ) ) { ret . add ( attrInfo . getName ( ) ) ; } } return ret ; } | Return a set of attributes as a map with the attribute name as key and their values as values |
34,256 | public String getAttributeName ( ) { if ( attributeNames == null ) { return null ; } if ( isMultiAttributeMode ( ) ) { throw new IllegalStateException ( "Request contains more than one attribute (attrs = " + "" + attributeNames + "). Use getAttributeNames() instead." ) ; } return attributeNames . get ( 0 ) ; } | Get a single attribute name . If this request was initialized with more than one attribute this methods throws an exception . |
34,257 | private void initAttribute ( Object pAttrval ) { if ( pAttrval instanceof String ) { attributeNames = EscapeUtil . split ( ( String ) pAttrval , EscapeUtil . CSV_ESCAPE , "," ) ; multiAttributeMode = attributeNames . size ( ) > 1 ; } else if ( pAttrval instanceof Collection ) { Collection < String > attributes = ( Collection < String > ) pAttrval ; if ( attributes . size ( ) == 1 && attributes . iterator ( ) . next ( ) == null ) { attributeNames = null ; multiAttributeMode = false ; } else { attributeNames = new ArrayList < String > ( attributes ) ; multiAttributeMode = true ; } } else if ( pAttrval == null ) { attributeNames = null ; multiAttributeMode = false ; } else { throw new IllegalArgumentException ( "Attribute names must be either a String, Collection or null (and not " + pAttrval . getClass ( ) + ")" ) ; } } | initialize and detect multi attribute mode |
34,258 | public static String combineToPath ( List < String > pParts ) { if ( pParts != null && pParts . size ( ) > 0 ) { StringBuilder buf = new StringBuilder ( ) ; Iterator < String > it = pParts . iterator ( ) ; while ( it . hasNext ( ) ) { String part = it . next ( ) ; buf . append ( escapePart ( part != null ? part : "*" ) ) ; if ( it . hasNext ( ) ) { buf . append ( "/" ) ; } } return buf . toString ( ) ; } else { return null ; } } | Combine a list of strings to a single path with proper escaping . |
34,259 | public static List < String > parsePath ( String pPath ) { if ( pPath == null || pPath . equals ( "" ) || pPath . equals ( "/" ) ) { return null ; } return replaceWildcardsWithNull ( split ( pPath , PATH_ESCAPE , "/" ) ) ; } | Parse a string path and return a list of split up parts . |
34,260 | public static Stack < String > reversePath ( List < String > pathParts ) { Stack < String > pathStack = new Stack < String > ( ) ; if ( pathParts != null ) { for ( int i = pathParts . size ( ) - 1 ; i >= 0 ; i -- ) { pathStack . push ( pathParts . get ( i ) ) ; } } return pathStack ; } | Reverse path and return as a stack . First path element is on top of the stack . |
34,261 | public static String escape ( String pArg , String pEscape , String pDelimiter ) { return pArg . replaceAll ( pEscape , pEscape + pEscape ) . replaceAll ( pDelimiter , pEscape + pDelimiter ) ; } | Escape the delimiter in an argument with the given escape char . |
34,262 | private static Pattern [ ] createSplitPatterns ( String pEscape , String pDel ) { return new Pattern [ ] { Pattern . compile ( "(.*?)" + "(?:" + "(?<!" + pEscape + ")((?:" + pEscape + ".)*)" + pDel + "|" + "$" + ")" , Pattern . DOTALL ) , Pattern . compile ( pEscape + "(.)" , Pattern . DOTALL ) } ; } | Create a split pattern for a given delimiter |
34,263 | @ SuppressWarnings ( "PMD.ExceptionAsFlowControl" ) public static void main ( String ... args ) { OptionsAndArgs options ; try { options = new OptionsAndArgs ( CommandDispatcher . getAvailableCommands ( ) , args ) ; VirtualMachineHandler vmHandler = new VirtualMachineHandler ( options ) ; CommandDispatcher dispatcher = new CommandDispatcher ( options ) ; Object vm = options . needsVm ( ) ? vmHandler . attachVirtualMachine ( ) : null ; int exitCode = 0 ; try { exitCode = dispatcher . dispatchCommand ( vm , vmHandler ) ; } catch ( InvocationTargetException e ) { throw new ProcessingException ( "InvocationTargetException" , e , options ) ; } catch ( NoSuchMethodException e ) { throw new ProcessingException ( "Internal: NoSuchMethod" , e , options ) ; } catch ( IllegalAccessException e ) { throw new ProcessingException ( "IllegalAccess" , e , options ) ; } finally { if ( vm != null ) { vmHandler . detachAgent ( vm ) ; } } System . exit ( exitCode ) ; } catch ( IllegalArgumentException exp ) { System . err . println ( "Error: " + exp . getMessage ( ) + "\n" ) ; CommandDispatcher . printHelp ( ) ; System . exit ( 1 ) ; } catch ( ProcessingException exp ) { exp . printErrorMessage ( ) ; System . exit ( 1 ) ; } } | We use processing exception thrown here for better error reporting not flow control . |
34,264 | public Object prepareValue ( String pExpectedClassName , Object pValue ) { if ( pValue == null ) { return null ; } else { Class expectedClass = ClassUtil . classForName ( pExpectedClassName ) ; Object param = null ; if ( expectedClass != null ) { param = prepareValue ( expectedClass , pValue ) ; } if ( param == null ) { return convertFromString ( pExpectedClassName , pValue . toString ( ) ) ; } return param ; } } | Prepare a value from a either a given object or its string representation . If the value is already assignable to the given class name it is returned directly . |
34,265 | private Object prepareForDirectUsage ( Class expectedClass , Object pArgument ) { Class givenClass = pArgument . getClass ( ) ; if ( expectedClass . isArray ( ) && List . class . isAssignableFrom ( givenClass ) ) { return convertListToArray ( expectedClass , ( List ) pArgument ) ; } else { return expectedClass . isAssignableFrom ( givenClass ) ? pArgument : null ; } } | Returns null if a string conversion should happen |
34,266 | public Object convertFromString ( String pType , String pValue ) { String value = convertSpecialStringTags ( pValue ) ; if ( value == null ) { return null ; } if ( pType . startsWith ( "[" ) && pType . length ( ) >= 2 ) { return convertToArray ( pType , value ) ; } Parser parser = PARSER_MAP . get ( pType ) ; if ( parser != null ) { return parser . extract ( value ) ; } Object cValue = convertByConstructor ( pType , pValue ) ; if ( cValue != null ) { return cValue ; } throw new IllegalArgumentException ( "Cannot convert string " + value + " to type " + pType + " because no converter could be found" ) ; } | Deserialize a string representation to an object for a given type |
34,267 | private Object convertToArray ( String pType , String pValue ) { String t = pType . substring ( 1 , 2 ) ; Class valueType ; if ( t . equals ( "L" ) ) { String oType = pType . substring ( 2 , pType . length ( ) - 1 ) . replace ( '/' , '.' ) ; valueType = ClassUtil . classForName ( oType ) ; if ( valueType == null ) { throw new IllegalArgumentException ( "No class of type " + oType + "found" ) ; } } else { valueType = TYPE_SIGNATURE_MAP . get ( t ) ; if ( valueType == null ) { throw new IllegalArgumentException ( "Cannot convert to unknown array type " + t ) ; } } String [ ] values = EscapeUtil . splitAsArray ( pValue , EscapeUtil . PATH_ESCAPE , "," ) ; Object ret = Array . newInstance ( valueType , values . length ) ; int i = 0 ; for ( String value : values ) { Array . set ( ret , i ++ , value . equals ( "[null]" ) ? null : convertFromString ( valueType . getCanonicalName ( ) , value ) ) ; } return ret ; } | Convert an array |
34,268 | private Object convertListToArray ( Class pType , List pList ) { Class valueType = pType . getComponentType ( ) ; Object ret = Array . newInstance ( valueType , pList . size ( ) ) ; int i = 0 ; for ( Object value : pList ) { if ( value == null ) { if ( ! valueType . isPrimitive ( ) ) { Array . set ( ret , i ++ , null ) ; } else { throw new IllegalArgumentException ( "Cannot use a null value in an array of type " + valueType . getSimpleName ( ) ) ; } } else { if ( valueType . isAssignableFrom ( value . getClass ( ) ) ) { Array . set ( ret , i ++ , value ) ; } else { Array . set ( ret , i ++ , convertFromString ( valueType . getCanonicalName ( ) , value . toString ( ) ) ) ; } } } return ret ; } | Convert a list to an array of the given type |
34,269 | public Object dispatchRequest ( JmxRequest pJmxReq ) throws InstanceNotFoundException , AttributeNotFoundException , ReflectionException , MBeanException , IOException , NotChangedException { JsonRequestHandler handler = requestHandlerManager . getRequestHandler ( pJmxReq . getType ( ) ) ; JMXConnector connector = null ; try { connector = createConnector ( pJmxReq ) ; connector . connect ( ) ; MBeanServerConnection connection = connector . getMBeanServerConnection ( ) ; if ( handler . handleAllServersAtOnce ( pJmxReq ) ) { MBeanServerExecutor manager = new MBeanServerExecutorRemote ( connection ) ; return handler . handleRequest ( manager , pJmxReq ) ; } else { return handler . handleRequest ( connection , pJmxReq ) ; } } finally { releaseConnector ( connector ) ; } } | Call a remote connector based on the connection information contained in the request . |
34,270 | protected Map < String , Object > prepareEnv ( Map < String , String > pTargetConfig ) { if ( pTargetConfig == null || pTargetConfig . size ( ) == 0 ) { return null ; } Map < String , Object > ret = new HashMap < String , Object > ( pTargetConfig ) ; String user = ( String ) ret . remove ( "user" ) ; String password = ( String ) ret . remove ( "password" ) ; if ( user != null && password != null ) { ret . put ( Context . SECURITY_PRINCIPAL , user ) ; ret . put ( Context . SECURITY_CREDENTIALS , password ) ; ret . put ( "jmx.remote.credentials" , new String [ ] { user , password } ) ; } return ret ; } | Override this if a special environment setup is required for JSR - 160 connection |
34,271 | private boolean acceptTargetUrl ( String urlS ) { if ( whiteList != null ) { return checkPattern ( whiteList , urlS , true ) ; } if ( blackList != null ) { return checkPattern ( blackList , urlS , false ) ; } return true ; } | Whether a given JMX Service URL is acceptable |
34,272 | public < T extends J4pResponse > List < T > getResponses ( ) { List < T > ret = new ArrayList < T > ( ) ; for ( Object entry : results ) { if ( entry instanceof J4pResponse ) { ret . add ( ( T ) entry ) ; } } return ret ; } | Get the a list of responses for successful requests . |
34,273 | public void addMBeanServers ( Set < MBeanServerConnection > servers ) { try { Class locatorClass = Class . forName ( "org.jboss.mx.util.MBeanServerLocator" ) ; Method method = locatorClass . getMethod ( "locateJBoss" ) ; servers . add ( ( MBeanServer ) method . invoke ( null ) ) ; } catch ( ClassNotFoundException e ) { } catch ( NoSuchMethodException e ) { } catch ( IllegalAccessException e ) { } catch ( InvocationTargetException e ) { } } | Special handling for JBoss |
34,274 | private static byte [ ] decodeBytes ( byte [ ] pInBytes ) { byte [ ] decodabet = DECODABET ; int len34 = pInBytes . length * 3 / 4 ; byte [ ] outBuff = new byte [ len34 ] ; int outBuffPosn = 0 ; byte [ ] b4 = new byte [ 4 ] ; int b4Posn = 0 ; int i = 0 ; byte sbiCrop = 0 ; byte sbiDecode = 0 ; for ( i = 0 ; i < 0 + pInBytes . length ; i ++ ) { sbiCrop = ( byte ) ( pInBytes [ i ] & 0x7f ) ; sbiDecode = decodabet [ sbiCrop ] ; if ( sbiDecode >= WHITE_SPACE_ENC ) { if ( sbiDecode >= EQUALS_SIGN_ENC ) { b4 [ b4Posn ++ ] = sbiCrop ; if ( b4Posn > 3 ) { outBuffPosn += decode4to3 ( b4 , 0 , outBuff , outBuffPosn ) ; b4Posn = 0 ; if ( sbiCrop == EQUALS_SIGN ) { break ; } } } } else { throw new IllegalArgumentException ( String . format ( "Bad Base64 input character '%d' in array position %d" , pInBytes [ i ] , i ) ) ; } } byte [ ] out = new byte [ outBuffPosn ] ; System . arraycopy ( outBuff , 0 , out , 0 , outBuffPosn ) ; return out ; } | Do the conversion to bytes |
34,275 | private static void verifyArguments ( byte [ ] source , int srcOffset , byte [ ] destination , int destOffset ) { if ( source == null ) { throw new IllegalArgumentException ( "Source array was null." ) ; } if ( destination == null ) { throw new IllegalArgumentException ( "Destination array was null." ) ; } if ( srcOffset < 0 || srcOffset + 3 >= source . length ) { throw new IllegalArgumentException ( String . format ( "Source array with length %d cannot have offset of %d and still process four bytes." , source . length , srcOffset ) ) ; } if ( destOffset < 0 || destOffset + 2 >= destination . length ) { throw new IllegalArgumentException ( String . format ( "Destination array with length %d cannot have offset of %d and still store three bytes." , destination . length , destOffset ) ) ; } } | Check for argument validity |
34,276 | public static boolean shouldBeUsed ( String authMode ) { return authMode != null && ( authMode . equalsIgnoreCase ( AUTHMODE_SERVICE_ALL ) || authMode . equalsIgnoreCase ( AUTHMODE_SERVICE_ANY ) ) ; } | Check whether for the given authmode an instance of this context should be used ( i . e . when the auth - mode is service - any or service - all |
34,277 | private boolean checkForMapKey ( TabularType pType ) { List < String > indexNames = pType . getIndexNames ( ) ; return indexNames . size ( ) == 1 && indexNames . contains ( TD_KEY_KEY ) && pType . getRowType ( ) . getType ( TD_KEY_KEY ) instanceof SimpleType ; } | The tabular data representing a map must have a single index named key which must be a simple type |
34,278 | private boolean checkForFullTabularDataRepresentation ( JSONObject pValue , TabularType pType ) { if ( pValue . containsKey ( "indexNames" ) && pValue . containsKey ( "values" ) && pValue . size ( ) == 2 ) { Object jsonVal = pValue . get ( "indexNames" ) ; if ( ! ( jsonVal instanceof JSONArray ) ) { throw new IllegalArgumentException ( "Index names for tabular data must given as JSON array, not " + jsonVal . getClass ( ) ) ; } JSONArray indexNames = ( JSONArray ) jsonVal ; List < String > tabularIndexNames = pType . getIndexNames ( ) ; if ( indexNames . size ( ) != tabularIndexNames . size ( ) ) { throw new IllegalArgumentException ( "Given array with index names must have " + tabularIndexNames . size ( ) + " entries " + "(given: " + indexNames + ", required: " + tabularIndexNames + ")" ) ; } for ( Object index : indexNames ) { if ( ! tabularIndexNames . contains ( index . toString ( ) ) ) { throw new IllegalArgumentException ( "No index with name '" + index + "' known " + "(given: " + indexNames + ", required: " + tabularIndexNames + ")" ) ; } } return true ; } return false ; } | Check for a full table data representation and do some sanity checks |
34,279 | private TabularData convertTabularDataFromFullRepresentation ( JSONObject pValue , TabularType pType ) { JSONAware jsonVal ; jsonVal = ( JSONAware ) pValue . get ( "values" ) ; if ( ! ( jsonVal instanceof JSONArray ) ) { throw new IllegalArgumentException ( "Values for tabular data of type " + pType + " must given as JSON array, not " + jsonVal . getClass ( ) ) ; } TabularDataSupport tabularData = new TabularDataSupport ( pType ) ; for ( Object val : ( JSONArray ) jsonVal ) { if ( ! ( val instanceof JSONObject ) ) { throw new IllegalArgumentException ( "Tabular-Data values must be given as JSON objects, not " + val . getClass ( ) ) ; } tabularData . put ( ( CompositeData ) getDispatcher ( ) . convertToObject ( pType . getRowType ( ) , val ) ) ; } return tabularData ; } | Convert complex representation containing indexNames and values |
34,280 | public static InetAddress getLocalAddress ( ) throws UnknownHostException , SocketException { InetAddress addr = InetAddress . getLocalHost ( ) ; NetworkInterface nif = NetworkInterface . getByInetAddress ( addr ) ; if ( addr . isLoopbackAddress ( ) || addr instanceof Inet6Address || nif == null ) { InetAddress lookedUpAddr = findLocalAddressViaNetworkInterface ( ) ; addr = lookedUpAddr != null ? lookedUpAddr : InetAddress . getByName ( "127.0.0.1" ) ; } return addr ; } | Get a local IP4 Address preferable a non - loopback address which is bound to an interface . |
34,281 | public static InetAddress findLocalAddressViaNetworkInterface ( ) { Enumeration < NetworkInterface > networkInterfaces ; try { networkInterfaces = NetworkInterface . getNetworkInterfaces ( ) ; } catch ( SocketException e ) { return null ; } while ( networkInterfaces . hasMoreElements ( ) ) { NetworkInterface nif = networkInterfaces . nextElement ( ) ; for ( Enumeration < InetAddress > addrEnum = nif . getInetAddresses ( ) ; addrEnum . hasMoreElements ( ) ; ) { InetAddress interfaceAddress = addrEnum . nextElement ( ) ; if ( useInetAddress ( nif , interfaceAddress ) ) { return interfaceAddress ; } } } return null ; } | returns null if none has been found |
34,282 | public static boolean isMulticastSupported ( NetworkInterface pNif ) { return pNif != null && checkMethod ( pNif , isUp ) && checkMethod ( pNif , supportsMulticast ) ; } | Check whether the given interface supports multicast and is up |
34,283 | public static List < InetAddress > getMulticastAddresses ( ) throws SocketException { Enumeration < NetworkInterface > nifs = NetworkInterface . getNetworkInterfaces ( ) ; List < InetAddress > ret = new ArrayList < InetAddress > ( ) ; while ( nifs . hasMoreElements ( ) ) { NetworkInterface nif = nifs . nextElement ( ) ; if ( checkMethod ( nif , supportsMulticast ) && checkMethod ( nif , isUp ) ) { Enumeration < InetAddress > addresses = nif . getInetAddresses ( ) ; while ( addresses . hasMoreElements ( ) ) { InetAddress addr = addresses . nextElement ( ) ; if ( ! ( addr instanceof Inet6Address ) ) { ret . add ( addr ) ; } } } } return ret ; } | Get all local addresses on which a multicast can be send |
34,284 | private static boolean useInetAddress ( NetworkInterface networkInterface , InetAddress interfaceAddress ) { return checkMethod ( networkInterface , isUp ) && checkMethod ( networkInterface , supportsMulticast ) && ! ( interfaceAddress instanceof Inet6Address ) && ! interfaceAddress . isLoopbackAddress ( ) ; } | Only use the given interface on the given network interface if it is up and supports multicast |
34,285 | private static Boolean checkMethod ( NetworkInterface iface , Method toCheck ) { if ( toCheck != null ) { try { return ( Boolean ) toCheck . invoke ( iface , ( Object [ ] ) null ) ; } catch ( IllegalAccessException e ) { return false ; } catch ( InvocationTargetException e ) { return false ; } } return true ; } | Call a method and return the result as boolean . In case of problems return false . |
34,286 | private static InetAddress findLocalAddressListeningOnPort ( String pHost , int pPort ) throws UnknownHostException , SocketException { InetAddress address = InetAddress . getByName ( pHost ) ; if ( address . isLoopbackAddress ( ) ) { InetAddress localAddress = getLocalAddress ( ) ; if ( ! localAddress . isLoopbackAddress ( ) && isPortOpen ( localAddress , pPort ) ) { return localAddress ; } localAddress = getLocalAddressFromNetworkInterfacesListeningOnPort ( pPort ) ; if ( localAddress != null ) { return localAddress ; } } return address ; } | Check for an non - loopback local adress listening on the given port |
34,287 | private static boolean isPortOpen ( InetAddress pAddress , int pPort ) { Socket socket = null ; try { socket = new Socket ( ) ; socket . setReuseAddress ( true ) ; SocketAddress sa = new InetSocketAddress ( pAddress , pPort ) ; socket . connect ( sa , 200 ) ; return socket . isConnected ( ) ; } catch ( IOException e ) { return false ; } finally { if ( socket != null ) { try { socket . close ( ) ; } catch ( IOException e ) { } } } } | Check a port by connecting to it . Try only 200ms . |
34,288 | private static String getProcessId ( ) { final String jvmName = ManagementFactory . getRuntimeMXBean ( ) . getName ( ) ; final int index = jvmName . indexOf ( '@' ) ; return index < 0 ? jvmName : jvmName . substring ( 0 , index ) ; } | Hack for finding the process id . Used in creating an unique agent id . |
34,289 | public static String dumpLocalNetworkInfo ( ) throws UnknownHostException , SocketException { StringBuffer buffer = new StringBuffer ( ) ; InetAddress addr = InetAddress . getLocalHost ( ) ; buffer . append ( "Localhost: " + getAddrInfo ( addr ) + "\n" ) ; Enumeration < NetworkInterface > nifs = NetworkInterface . getNetworkInterfaces ( ) ; buffer . append ( "Network interfaces:\n" ) ; while ( nifs . hasMoreElements ( ) ) { NetworkInterface nif = nifs . nextElement ( ) ; buffer . append ( " - " + getNetworkInterfaceInfo ( nif ) + "\n" ) ; Enumeration < InetAddress > addresses = nif . getInetAddresses ( ) ; while ( addresses . hasMoreElements ( ) ) { addr = addresses . nextElement ( ) ; buffer . append ( " " + getAddrInfo ( addr ) + "\n" ) ; } } return buffer . toString ( ) ; } | Get the local network info as a string |
34,290 | protected void registerForMBeanNotifications ( ) { Set < MBeanServerConnection > servers = getMBeanServers ( ) ; Exception lastExp = null ; StringBuilder errors = new StringBuilder ( ) ; for ( MBeanServerConnection server : servers ) { try { JmxUtil . addMBeanRegistrationListener ( server , this , null ) ; } catch ( IllegalStateException e ) { lastExp = updateErrorMsg ( errors , e ) ; } } if ( lastExp != null ) { throw new IllegalStateException ( errors . substring ( 0 , errors . length ( ) - 1 ) , lastExp ) ; } } | Add this executor as listener for MBeanServer notification so that we can update the local timestamp for when the set of registered MBeans has changed last . |
34,291 | private Exception updateErrorMsg ( StringBuilder pErrors , Exception exp ) { pErrors . append ( exp . getClass ( ) ) . append ( ": " ) . append ( exp . getMessage ( ) ) . append ( "\n" ) ; return exp ; } | Helper method for adding the exception for an appropriate error message |
34,292 | public static void updateWithCaPem ( KeyStore pTrustStore , File pCaCert ) throws IOException , CertificateException , KeyStoreException , NoSuchAlgorithmException { InputStream is = new FileInputStream ( pCaCert ) ; try { CertificateFactory certFactory = CertificateFactory . getInstance ( "X509" ) ; X509Certificate cert = ( X509Certificate ) certFactory . generateCertificate ( is ) ; String alias = cert . getSubjectX500Principal ( ) . getName ( ) ; pTrustStore . setCertificateEntry ( alias , cert ) ; } finally { is . close ( ) ; } } | Update a keystore with a CA certificate |
34,293 | public static void updateWithServerPems ( KeyStore pKeyStore , File pServerCert , File pServerKey , String pKeyAlgo , char [ ] pPassword ) throws IOException , CertificateException , NoSuchAlgorithmException , InvalidKeySpecException , KeyStoreException { InputStream is = new FileInputStream ( pServerCert ) ; try { CertificateFactory certFactory = CertificateFactory . getInstance ( "X509" ) ; X509Certificate cert = ( X509Certificate ) certFactory . generateCertificate ( is ) ; byte [ ] keyBytes = decodePem ( pServerKey ) ; PrivateKey privateKey ; KeyFactory keyFactory = KeyFactory . getInstance ( pKeyAlgo ) ; try { privateKey = keyFactory . generatePrivate ( new PKCS8EncodedKeySpec ( keyBytes ) ) ; } catch ( InvalidKeySpecException e ) { RSAPrivateCrtKeySpec keySpec = PKCS1Util . decodePKCS1 ( keyBytes ) ; privateKey = keyFactory . generatePrivate ( keySpec ) ; } String alias = cert . getSubjectX500Principal ( ) . getName ( ) ; pKeyStore . setKeyEntry ( alias , privateKey , pPassword , new Certificate [ ] { cert } ) ; } finally { is . close ( ) ; } } | Update a key store with the keys found in a server PEM and its key file . |
34,294 | public static void updateWithSelfSignedServerCertificate ( KeyStore pKeyStore ) throws NoSuchProviderException , NoSuchAlgorithmException , IOException , InvalidKeyException , CertificateException , SignatureException , KeyStoreException { final Object x500Name ; final Object [ ] certAttributes = { "Jolokia Agent " + Version . getAgentVersion ( ) , "JVM" , "jolokia.org" , "Pegnitz" , "Franconia" , "DE" } ; if ( ClassUtil . checkForClass ( X500_NAME_SUN ) ) { x500Name = ClassUtil . newInstance ( X500_NAME_SUN , certAttributes ) ; } else if ( ClassUtil . checkForClass ( X500_NAME_IBM ) ) { x500Name = ClassUtil . newInstance ( X500_NAME_IBM , certAttributes ) ; } else { throw new IllegalStateException ( "Neither Sun- nor IBM-style JVM found." ) ; } Object keypair = createKeyPair ( ) ; PrivateKey privKey = getPrivateKey ( keypair ) ; X509Certificate [ ] chain = new X509Certificate [ 1 ] ; chain [ 0 ] = getSelfCertificate ( keypair , x500Name , new Date ( ) , ( long ) 3650 * 24 * 60 * 60 ) ; pKeyStore . setKeyEntry ( "jolokia-agent" , privKey , new char [ 0 ] , chain ) ; } | Update the given keystore with a self signed server certificate . This can be used if no server certificate is provided from the outside and no SSL verification is used by the client . |
34,295 | public Object setObjectValue ( StringToObjectConverter pConverter , Object pInner , String pIndex , Object pValue ) throws IllegalAccessException , InvocationTargetException { List list = ( List ) pInner ; int idx ; try { idx = Integer . parseInt ( pIndex ) ; } catch ( NumberFormatException exp ) { throw new IllegalArgumentException ( "Non-numeric index for accessing collection " + pInner + ". (index = " + pIndex + ", value to set = " + pValue + ")" , exp ) ; } Object oldValue = list . get ( idx ) ; Object value = oldValue != null ? pConverter . prepareValue ( oldValue . getClass ( ) . getName ( ) , pValue ) : pValue ; list . set ( idx , value ) ; return oldValue ; } | Set a value within a list |
34,296 | static RequestCreator < JmxListRequest > newCreator ( ) { return new RequestCreator < JmxListRequest > ( ) { public JmxListRequest create ( Stack < String > pStack , ProcessingParameters pParams ) throws MalformedObjectNameException { return new JmxListRequest ( prepareExtraArgs ( pStack ) , pParams ) ; } public JmxListRequest create ( Map < String , ? > requestMap , ProcessingParameters pParams ) throws MalformedObjectNameException { return new JmxListRequest ( requestMap , pParams ) ; } } ; } | Create a new creator used for creating list requests |
34,297 | private static void awaitServerInitialization ( JvmAgentConfig pConfig , final Instrumentation instrumentation ) { List < ServerDetector > detectors = MBeanServerHandler . lookupDetectors ( ) ; for ( ServerDetector detector : detectors ) { detector . jvmAgentStartup ( instrumentation ) ; } } | Lookup the server detectors and notify detector about the JVM startup |
34,298 | public void start ( boolean pLazy ) { Restrictor restrictor = createRestrictor ( ) ; backendManager = new BackendManager ( configuration , logHandler , restrictor , pLazy ) ; requestHandler = new HttpRequestHandler ( configuration , backendManager , logHandler ) ; if ( listenForDiscoveryMcRequests ( configuration ) ) { try { discoveryMulticastResponder = new DiscoveryMulticastResponder ( backendManager , restrictor , logHandler ) ; discoveryMulticastResponder . start ( ) ; } catch ( IOException e ) { logHandler . error ( "Cannot start discovery multicast handler: " + e , e ) ; } } } | Start the handler |
34,299 | public void start ( boolean pLazy , String pUrl , boolean pSecured ) { start ( pLazy ) ; AgentDetails details = backendManager . getAgentDetails ( ) ; details . setUrl ( pUrl ) ; details . setSecured ( pSecured ) ; } | Start the handler and remember connection details which are useful for discovery messages |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.