idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
7,100
public final boolean hasProperty ( final String property ) { final String val = properties . get ( property ) ; if ( val == null ) return false ; if ( val . isEmpty ( ) ) return false ; return true ; }
Determines if the given propery is in the map
7,101
public final String dumpConfiguration ( ) { if ( properties . isEmpty ( ) ) return "No configuration settings stored" ; StringBuilder response = new StringBuilder ( "TSD Configuration:\n" ) ; response . append ( "File [" + config_location + "]\n" ) ; int line = 0 ; for ( Map . Entry < String , String > entry : properti...
Returns a simple string with the configured properties for debugging
7,102
protected void loadConfig ( ) throws IOException { if ( config_location != null && ! config_location . isEmpty ( ) ) { loadConfig ( config_location ) ; return ; } final ArrayList < String > file_locations = new ArrayList < String > ( ) ; file_locations . add ( "opentsdb.conf" ) ; if ( System . getProperty ( "os.name" )...
Searches a list of locations for a valid opentsdb . conf file
7,103
protected void loadConfig ( final String file ) throws FileNotFoundException , IOException { final FileInputStream file_stream = new FileInputStream ( file ) ; try { final Properties props = new Properties ( ) ; props . load ( file_stream ) ; loadHashMap ( props ) ; LOG . info ( "Successfully loaded configuration file:...
Attempts to load the configuration from the given location
7,104
public void loadStaticVariables ( ) { auto_metric = this . getBoolean ( "tsd.core.auto_create_metrics" ) ; auto_tagk = this . getBoolean ( "tsd.core.auto_create_tagks" ) ; auto_tagv = this . getBoolean ( "tsd.core.auto_create_tagvs" ) ; enable_compactions = this . getBoolean ( "tsd.storage.enable_compaction" ) ; enable...
Loads the static class variables for values that are called often . This should be called any time the configuration changes .
7,105
public void add ( final String name , final String value ) { ArrayList < String > values = super . get ( name ) ; if ( values == null ) { values = new ArrayList < String > ( 1 ) ; super . put ( name , values ) ; } values . add ( value ) ; }
Adds a query string element .
7,106
public ChannelBuffer formatPutV1 ( final Map < String , Object > results ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatPutV1" ) ; }
Formats the results of an HTTP data point storage request
7,107
public ChannelBuffer formatSuggestV1 ( final List < String > suggestions ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatSuggestV1" ) ; }
Formats a suggestion response
7,108
public ChannelBuffer formatAggregatorsV1 ( final Set < String > aggregators ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatAggregatorsV1" ) ; }
Format the list of implemented aggregators
7,109
public ChannelBuffer formatVersionV1 ( final Map < String , String > version ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatVersionV1" ) ; }
Format a hash map of information about the OpenTSDB version
7,110
public ChannelBuffer formatDropCachesV1 ( final Map < String , String > response ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatDropCachesV1" ) ; }
Format a response from the DropCaches call
7,111
public ChannelBuffer formatLastPointQueryV1 ( final List < IncomingDataPoint > data_points ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatLastPointQueryV1" ) ; }
Format a list of last data points
7,112
public ChannelBuffer formatTSMetaListV1 ( final List < TSMeta > metas ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatTSMetaV1" ) ; }
Format a a list of TSMeta objects
7,113
public ChannelBuffer formatTreesV1 ( final List < Tree > trees ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatTreesV1" ) ; }
Format a list of tree objects . Note that the list may be empty if no trees were present .
7,114
public ChannelBuffer formatTreeCollisionNotMatchedV1 ( final Map < String , String > results , final boolean is_collisions ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented...
Format a map of one or more TSUIDs that collided or were not matched
7,115
public ChannelBuffer formatAnnotationsV1 ( final List < Annotation > notes ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatAnnotationsV1" ) ; }
Format a list of annotation objects
7,116
public ChannelBuffer formatStatsV1 ( final List < IncomingDataPoint > stats ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatStatsV1" ) ; }
Format a list of statistics
7,117
public ChannelBuffer formatThreadStatsV1 ( final List < Map < String , Object > > stats ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatThreadStatsV1" ) ; }
Format a list of thread statistics
7,118
public ChannelBuffer formatQueryStatsV1 ( final Map < String , Object > query_stats ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatQueryStatsV1" ) ; }
Format the query stats
7,119
public static final String getDurationUnits ( final String duration ) { if ( duration == null || duration . isEmpty ( ) ) { throw new IllegalArgumentException ( "Duration cannot be null or empty" ) ; } int unit = 0 ; while ( unit < duration . length ( ) && Character . isDigit ( duration . charAt ( unit ) ) ) { unit ++ ...
Returns the suffix or units of the duration as a string . The result will be ms s m h d w n or y .
7,120
public static final int getDurationInterval ( final String duration ) { if ( duration == null || duration . isEmpty ( ) ) { throw new IllegalArgumentException ( "Duration cannot be null or empty" ) ; } if ( duration . contains ( "." ) ) { throw new IllegalArgumentException ( "Floating point intervals are not supported"...
Parses the prefix of the duration the interval and returns it as a number . E . g . if you supply 1d it will return 1 . If you supply 60m it will return 60 .
7,121
public static void setTimeZone ( final SimpleDateFormat fmt , final String tzname ) { if ( tzname == null ) { return ; } final TimeZone tz = DateTime . timezones . get ( tzname ) ; if ( tz != null ) { fmt . setTimeZone ( tz ) ; } else { throw new IllegalArgumentException ( "Invalid timezone name: " + tzname ) ; } }
Applies the given timezone to the given date format .
7,122
public static double msFromNanoDiff ( final long end , final long start ) { if ( end < start ) { throw new IllegalArgumentException ( "End (" + end + ") cannot be less " + "than start (" + start + ")" ) ; } return ( ( double ) end - ( double ) start ) / 1000000 ; }
Calculates the difference between two values and returns the time in milliseconds as a double .
7,123
public static int unitsToCalendarType ( final String units ) { if ( units == null || units . isEmpty ( ) ) { throw new IllegalArgumentException ( "Units cannot be null or empty" ) ; } final String lc = units . toLowerCase ( ) ; if ( lc . equals ( "ms" ) ) { return Calendar . MILLISECOND ; } else if ( lc . equals ( "s" ...
Return the proper Calendar time unit as an integer given the string
7,124
public void validate ( ) { if ( id == null || id . isEmpty ( ) ) { throw new IllegalArgumentException ( "missing or empty id" ) ; } Query . validateId ( id ) ; }
Validates the output
7,125
public static Aggregator get ( final String name ) { final Aggregator agg = aggregators . get ( name ) ; if ( agg != null ) { return agg ; } throw new NoSuchElementException ( "No such aggregator: " + name ) ; }
Returns the aggregator corresponding to the given name .
7,126
public Deferred < Object > delete ( final TSDB tsdb ) { if ( start_time < 1 ) { throw new IllegalArgumentException ( "The start timestamp has not been set" ) ; } final byte [ ] tsuid_byte = tsuid != null && ! tsuid . isEmpty ( ) ? UniqueId . stringToUid ( tsuid ) : null ; final DeleteRequest delete = new DeleteRequest ...
Attempts to mark an Annotation object for deletion . Note that if the annoation does not exist in storage this delete call will not throw an error .
7,127
public static Deferred < Annotation > getAnnotation ( final TSDB tsdb , final long start_time ) { return getAnnotation ( tsdb , ( byte [ ] ) null , start_time ) ; }
Attempts to fetch a global annotation from storage
7,128
public static Deferred < List < Annotation > > getGlobalAnnotations ( final TSDB tsdb , final long start_time , final long end_time ) { if ( end_time < 1 ) { throw new IllegalArgumentException ( "The end timestamp has not been set" ) ; } if ( end_time < start_time ) { throw new IllegalArgumentException ( "The end times...
Scans through the global annotation storage rows and returns a list of parsed annotation objects . If no annotations were found for the given timespan the resulting list will be empty .
7,129
private static long timeFromQualifier ( final byte [ ] qualifier , final long base_time ) { final long offset ; if ( qualifier . length == 3 ) { offset = Bytes . getUnsignedShort ( qualifier , 1 ) ; return ( base_time + offset ) * 1000 ; } else { offset = Bytes . getUnsignedInt ( qualifier , 1 ) ; return ( base_time * ...
Returns a timestamp after parsing an annotation qualifier .
7,130
static void checkMetricAndTags ( final String metric , final Map < String , String > tags ) { if ( tags . size ( ) <= 0 ) { throw new IllegalArgumentException ( "Need at least one tag (metric=" + metric + ", tags=" + tags + ')' ) ; } else if ( tags . size ( ) > Const . MAX_NUM_TAGS ( ) ) { throw new IllegalArgumentExce...
Validates the given metric and tags .
7,131
private static void copyInRowKey ( final byte [ ] row , final short offset , final byte [ ] bytes ) { System . arraycopy ( bytes , 0 , row , offset , bytes . length ) ; }
Copies the specified byte array at the specified offset in the row key .
7,132
private long updateBaseTime ( final long timestamp ) { final long base_time = timestamp - ( timestamp % Const . MAX_TIMESPAN ) ; row = Arrays . copyOf ( row , row . length ) ; Bytes . setInt ( row , ( int ) base_time , Const . SALT_WIDTH ( ) + tsdb . metrics . width ( ) ) ; RowKey . prefixKeyWithSalt ( row ) ; tsdb . s...
Updates the base time in the row key .
7,133
public static void addTSDBFunctions ( final TSDB tsdb ) { available_functions . put ( "divideSeries" , new DivideSeries ( tsdb ) ) ; available_functions . put ( "divide" , new DivideSeries ( tsdb ) ) ; available_functions . put ( "sumSeries" , new SumSeries ( tsdb ) ) ; available_functions . put ( "sum" , new SumSeries...
Adds more functions to the map that depend on an instantiated TSDB object . Only call this once please .
7,134
public static Expression getByName ( final String function ) { final Expression expression = available_functions . get ( function ) ; if ( expression == null ) { throw new UnsupportedOperationException ( "Function " + function + " has not been implemented" ) ; } return expression ; }
Returns the expression function given the name
7,135
public void setRow ( final KeyValue column ) { if ( key != null ) { throw new IllegalStateException ( "setRow was already called on " + this ) ; } key = column . key ( ) ; if ( need_count ) { System . out . println ( "AGG ID: " + agg_id + " COUNT ID: " + count_id + " MASK: " + ( column . qualifier ( ) [ 0 ] & RollupU...
Sets the row this instance holds in RAM using a row from a scanner .
7,136
public static void main ( String [ ] args ) throws Exception { ArgP argp = new ArgP ( ) ; CliOptions . addCommon ( argp ) ; argp . addOption ( "--use-data-table" , "Scan against the raw data table instead of the meta data table." ) ; args = CliOptions . parse ( argp , args ) ; if ( args == null ) { usage ( argp , "Inva...
Entry point to run the search utility
7,137
private static int runCommand ( final TSDB tsdb , final boolean use_data_table , final String [ ] args ) throws Exception { final int nargs = args . length ; if ( args [ 0 ] . equals ( "lookup" ) ) { if ( nargs < 2 ) { usage ( null , "Not enough arguments" ) ; return 2 ; } return lookup ( tsdb , use_data_table , args )...
Determines the command requested of the user can calls the appropriate method .
7,138
protected Deferred < Object > importDataPoint ( final TSDB tsdb , final String [ ] words ) { words [ 0 ] = null ; if ( words . length < 5 ) { throw new IllegalArgumentException ( "not enough arguments" + " (need least 4, got " + ( words . length - 1 ) + ')' ) ; } final String metric = words [ 1 ] ; if ( metric . length...
Imports a single data point .
7,139
final private HashMap < String , Object > getHttpDetails ( final String message , final IncomingDataPoint dp ) { final HashMap < String , Object > map = new HashMap < String , Object > ( ) ; map . put ( "error" , message ) ; map . put ( "datapoint" , dp ) ; return map ; }
Simple helper to format an error trying to save a data point
7,140
void handleStorageException ( final TSDB tsdb , final IncomingDataPoint dp , final Exception e ) { final StorageExceptionHandler handler = tsdb . getStorageExceptionHandler ( ) ; if ( handler != null ) { handler . handleError ( dp , e ) ; } }
Passes a data point off to the storage handler plugin if it has been configured .
7,141
public void addOption ( final String name , final String meta , final String help ) { if ( name . isEmpty ( ) ) { throw new IllegalArgumentException ( "empty name" ) ; } else if ( name . charAt ( 0 ) != '-' ) { throw new IllegalArgumentException ( "name must start with a `-': " + name ) ; } else if ( meta != null && me...
Registers an option in this argument parser .
7,142
public String [ ] parse ( final String [ ] args ) { parsed = new HashMap < String , String > ( options . size ( ) ) ; ArrayList < String > unparsed = null ; for ( int i = 0 ; i < args . length ; i ++ ) { final String arg = args [ i ] ; String [ ] opt = options . get ( arg ) ; if ( opt != null ) { if ( opt [ 0 ] != null...
Parses the command line given in argument .
7,143
public String get ( final String name , final String defaultv ) { final String value = get ( name ) ; return value == null ? defaultv : value ; }
Returns the value of the given option or a default value .
7,144
public boolean has ( final String name ) { if ( ! options . containsKey ( name ) ) { throw new IllegalArgumentException ( "Unknown option " + name ) ; } else if ( parsed == null ) { throw new IllegalStateException ( "parse() wasn't called" ) ; } return parsed . containsKey ( name ) ; }
Returns whether or not the given option was given .
7,145
public void addUsageTo ( final StringBuilder buf ) { final ArrayList < String > names = new ArrayList < String > ( options . keySet ( ) ) ; Collections . sort ( names ) ; int max_length = 0 ; for ( final String name : names ) { final String [ ] opt = options . get ( name ) ; final int length = name . length ( ) + ( opt...
Appends the usage to the given buffer .
7,146
public String usage ( ) { final StringBuilder buf = new StringBuilder ( 16 * options . size ( ) ) ; addUsageTo ( buf ) ; return buf . toString ( ) ; }
Returns a usage string .
7,147
private static BufferedReader open ( final String path ) throws IOException { if ( path . equals ( "-" ) ) { return new BufferedReader ( new InputStreamReader ( System . in ) ) ; } InputStream is = new FileInputStream ( path ) ; if ( path . endsWith ( ".gz" ) ) { is = new GZIPInputStream ( is ) ; } return new BufferedR...
Opens a file for reading handling gzipped files .
7,148
public void validate ( ) { if ( id == null || id . isEmpty ( ) ) { throw new IllegalArgumentException ( "missing or empty id" ) ; } Query . validateId ( id ) ; if ( expr == null || expr . isEmpty ( ) ) { throw new IllegalArgumentException ( "missing or empty expr" ) ; } parsed_expression = ExpressionIterator . JEXL_ENG...
Validates the expression
7,149
static String [ ] parse ( final ArgP argp , String [ ] args ) { try { args = argp . parse ( args ) ; } catch ( IllegalArgumentException e ) { System . err . println ( "Invalid usage. " + e . getMessage ( ) ) ; System . exit ( 2 ) ; } honorVerboseFlag ( argp ) ; return args ; }
Parse the command line arguments with the given options .
7,150
static final Config getConfig ( final ArgP argp ) throws IOException { final Config config ; final String config_file = argp . get ( "--config" , "" ) ; if ( ! config_file . isEmpty ( ) ) config = new Config ( config_file ) ; else config = new Config ( true ) ; overloadConfig ( argp , config ) ; config . setAutoMetric ...
Attempts to load a configuration given a file or default files and overrides with command line arguments
7,151
protected static void loadConfigSource ( ConfigArgP config , String source ) { Properties p = loadConfig ( source ) ; Config c = config . getConfig ( ) ; for ( String key : p . stringPropertyNames ( ) ) { String value = p . getProperty ( key ) ; ConfigurationItem ci = config . getConfigurationItem ( key ) ; if ( ci != ...
Applies the properties from the named source to the main configuration
7,152
protected static Properties loadConfig ( String name ) { try { URL url = new URL ( name ) ; return loadConfig ( url ) ; } catch ( Exception ex ) { return loadConfig ( new File ( name ) ) ; } }
Loads properties from a file or url with the passed name
7,153
protected static Properties loadConfig ( String source , InputStream is ) { try { Properties p = new Properties ( ) ; p . load ( is ) ; Set < String > keys = p . stringPropertyNames ( ) ; for ( String key : keys ) { p . setProperty ( key , p . getProperty ( key ) . trim ( ) ) ; } return p ; } catch ( IllegalArgumentExc...
Loads properties from the passed input stream
7,154
protected static Properties loadConfig ( File file ) { InputStream is = null ; try { is = new FileInputStream ( file ) ; return loadConfig ( file . getAbsolutePath ( ) , is ) ; } catch ( Exception ex ) { throw new IllegalArgumentException ( "Failed to load configuration from [" + file . getAbsolutePath ( ) + "]" ) ; } ...
Loads properties from the passed file
7,155
public String [ ] applyArgs ( String [ ] clargs ) { LOG . debug ( "Applying Command Line Args {}" , Arrays . toString ( clargs ) ) ; final List < String > nonFlagArgs = new ArrayList < String > ( Arrays . asList ( clargs ) ) ; extractAndApplyFlags ( nonFlagArgs ) ; String [ ] args = nonFlagArgs . toArray ( new String [...
Parses the command line arguments and where the options are recognized config items the value is validated then applied to the config
7,156
public String getDefaultUsage ( String ... msgs ) { StringBuilder b = new StringBuilder ( "\n" ) ; for ( String msg : msgs ) { b . append ( msg ) . append ( "\n" ) ; } b . append ( dargp . usage ( ) ) ; return b . toString ( ) ; }
Returns a default usage banner with optional prefixed messages one per line .
7,157
public String getExtendedUsage ( String ... msgs ) { StringBuilder b = new StringBuilder ( "\n" ) ; for ( String msg : msgs ) { b . append ( msg ) . append ( "\n" ) ; } b . append ( argp . usage ( ) ) ; return b . toString ( ) ; }
Returns an extended usage banner with optional prefixed messages one per line .
7,158
public static void log ( String format , Object ... args ) { System . out . println ( String . format ( format , args ) ) ; }
System out logger
7,159
public static String processConfigValue ( CharSequence text ) { final String pv = evaluate ( tokenReplaceSysProps ( text ) ) ; return ( pv == null || pv . trim ( ) . isEmpty ( ) ) ? null : pv ; }
Performs sys - prop and js evals on the passed value
7,160
public static String tokenReplaceSysProps ( CharSequence text ) { if ( text == null ) return null ; Matcher m = SYS_PROP_PATTERN . matcher ( text ) ; StringBuffer ret = new StringBuffer ( ) ; while ( m . find ( ) ) { String replacement = decodeToken ( m . group ( 1 ) , m . group ( 2 ) == null ? "<null>" : m . group ( 2...
Replaces all matched tokens with the matching system property value or a configured default
7,161
public static String evaluate ( CharSequence text ) { if ( text == null ) return null ; Matcher m = JS_PATTERN . matcher ( text ) ; StringBuffer ret = new StringBuffer ( ) ; final boolean isNas = scriptEngine . getFactory ( ) . getEngineName ( ) . toLowerCase ( ) . contains ( "nashorn" ) ; while ( m . find ( ) ) { Stri...
Evaluates JS expressions defines as configuration values
7,162
public boolean hasNonOption ( String nonOptionKey ) { if ( nonOptionArgs == null || nonOptionArgs . length == 0 || nonOptionKey == null || nonOptionKey . trim ( ) . isEmpty ( ) ) return false ; return Arrays . binarySearch ( nonOptionArgs , nonOptionKey ) >= 0 ; }
Determines if the passed key is contained in the non option args
7,163
private final SearchQuery parseQueryString ( final HttpQuery query , final SearchType type ) { final SearchQuery search_query = new SearchQuery ( ) ; if ( type == SearchType . LOOKUP ) { final String query_string = query . getRequiredQueryStringParam ( "m" ) ; search_query . setTags ( new ArrayList < Pair < String , St...
Parses required search values from the query string
7,164
public void internalError ( final Exception cause ) { logError ( "Internal Server Error on " + request ( ) . getUri ( ) , cause ) ; if ( this . api_version > 0 ) { switch ( this . api_version ) { case 1 : default : sendReply ( HttpResponseStatus . INTERNAL_SERVER_ERROR , serializer . formatErrorV1 ( cause ) ) ; } retur...
Sends a 500 error page to the client . Handles responses from deprecated API calls as well as newer versioned API calls
7,165
public void badRequest ( final BadRequestException exception ) { logWarn ( "Bad Request on " + request ( ) . getUri ( ) + ": " + exception . getMessage ( ) ) ; if ( this . api_version > 0 ) { switch ( this . api_version ) { case 1 : default : sendReply ( exception . getStatus ( ) , serializer . formatErrorV1 ( exceptio...
Sends an error message to the client . Handles responses from deprecated API calls .
7,166
public void notFound ( ) { logWarn ( "Not Found: " + request ( ) . getUri ( ) ) ; if ( this . api_version > 0 ) { switch ( this . api_version ) { case 1 : default : sendReply ( HttpResponseStatus . NOT_FOUND , serializer . formatNotFoundV1 ( ) ) ; } return ; } if ( hasQueryStringParam ( "json" ) ) { sendReply ( HttpRes...
Sends a 404 error page to the client . Handles responses from deprecated API calls
7,167
public void redirect ( final String location ) { response ( ) . headers ( ) . set ( "Location" , location ) ; sendReply ( HttpResponseStatus . OK , new StringBuilder ( "<html></head><meta http-equiv=\"refresh\" content=\"0; url=" + location + "\"></head></html>" ) . toString ( ) . getBytes ( this . getCharset ( ) ) ) ;...
Redirects the client s browser to the given location .
7,168
static void escapeJson ( final String s , final StringBuilder buf ) { final int length = s . length ( ) ; int extra = 0 ; for ( int i = 0 ; i < length ; i ++ ) { final char c = s . charAt ( i ) ; switch ( c ) { case '"' : case '\\' : case '\b' : case '\f' : case '\n' : case '\r' : case '\t' : extra ++ ; continue ; } if...
Escapes a string appropriately to be a valid in JSON . Valid JSON strings are defined in RFC 4627 Section 2 . 5 .
7,169
public void done ( ) { final int processing_time = processingTimeMillis ( ) ; httplatency . add ( processing_time ) ; logInfo ( "HTTP " + request ( ) . getUri ( ) + " done in " + processing_time + "ms" ) ; deferred . callback ( null ) ; }
Method to call after writing the HTTP response to the wire .
7,170
private String guessMimeType ( final ChannelBuffer buf ) { final String mimetype = guessMimeTypeFromUri ( request ( ) . getUri ( ) ) ; return mimetype == null ? guessMimeTypeFromContents ( buf ) : mimetype ; }
Returns the result of an attempt to guess the MIME type of the response .
7,171
private static String guessMimeTypeFromUri ( final String uri ) { final int questionmark = uri . indexOf ( '?' , 1 ) ; final int end = ( questionmark > 0 ? questionmark : uri . length ( ) ) - 1 ; if ( end < 5 ) { return null ; } final char a = uri . charAt ( end - 3 ) ; final char b = uri . charAt ( end - 2 ) ; final c...
Attempts to guess the MIME type by looking at the URI requested .
7,172
private String guessMimeTypeFromContents ( final ChannelBuffer buf ) { if ( ! buf . readable ( ) ) { logWarn ( "Sending an empty result?! buf=" + buf ) ; return "text/plain" ; } final int firstbyte = buf . getUnsignedByte ( buf . readerIndex ( ) ) ; switch ( firstbyte ) { case '<' : return HTML_CONTENT_TYPE ; case '{' ...
Simple content sniffing . May not be a great idea but will do until this class has a better API .
7,173
public static StringBuilder makePage ( final String htmlheader , final String title , final String subtitle , final String body ) { final StringBuilder buf = new StringBuilder ( BOILERPLATE_LENGTH + ( htmlheader == null ? 0 : htmlheader . length ( ) ) + title . length ( ) + subtitle . length ( ) + body . length ( ) ) ;...
Easy way to generate a small simple HTML page .
7,174
public static void addDataOptions ( final ArgP argp ) { argp . addOption ( "--full-scan" , "Scan the entire data table." ) ; argp . addOption ( "--fix" , "Fix errors as they're found. Use in combination with" + " other flags." ) ; argp . addOption ( "--fix-all" , "Set all flags and fix errors as they're found." ) ; arg...
Add data table fsck options to the command line parser
7,175
private DataPoints abs ( final DataPoints points ) { final List < DataPoint > dps = new ArrayList < DataPoint > ( ) ; final SeekableView view = points . iterator ( ) ; while ( view . hasNext ( ) ) { DataPoint pt = view . next ( ) ; if ( pt . isInteger ( ) ) { dps . add ( MutableDataPoint . ofLongValue ( pt . timestamp ...
Iterate over each data point and store the absolute value
7,176
private void processParsedValue ( final String parsed_value ) { if ( rule . getCompiledRegex ( ) == null && ( rule . getSeparator ( ) == null || rule . getSeparator ( ) . isEmpty ( ) ) ) { setCurrentName ( parsed_value , parsed_value ) ; } else if ( rule . getCompiledRegex ( ) != null ) { processRegexRule ( parsed_valu...
Routes the parsed value to the proper processing method for altering the display name depending on the current rule . This can route to the regex handler or the split processor . Or if neither splits or regex are specified for the rule the parsed value is set as the branch name .
7,177
private void processRegexRule ( final String parsed_value ) { if ( rule . getCompiledRegex ( ) == null ) { throw new IllegalArgumentException ( "Regex was null for rule: " + rule ) ; } final Matcher matcher = rule . getCompiledRegex ( ) . matcher ( parsed_value ) ; if ( matcher . find ( ) ) { if ( matcher . groupCount ...
Runs the parsed string through a regex and attempts to extract a value from the specified group index . Group indexes start at 0 . If the regex was not matched or an extracted value for the requested group did not exist then the processor returns and the rule will be considered a no - match .
7,178
private void resetState ( ) { meta = null ; splits = null ; rule_idx = 0 ; split_idx = 0 ; current_branch = null ; rule = null ; not_matched = null ; if ( root != null ) { if ( root . getBranches ( ) != null ) { root . getBranches ( ) . clear ( ) ; } if ( root . getLeaves ( ) != null ) { root . getLeaves ( ) . clear ( ...
Resets local state variables to their defaults
7,179
public final Deferred < Object > sinkDataPoint ( final String metric , final long timestamp , final byte [ ] value , final Map < String , String > tags , final byte [ ] tsuid , final short flags ) { if ( ( flags & Const . FLAG_FLOAT ) != 0x0 ) { return publishDataPoint ( metric , timestamp , Internal . extractFloatingP...
Called by the TSD when a new raw data point is published . Because this is called after a data point is queued the value has been converted to a byte array so we need to convert it back to an integer or floating point value . Instead of requiring every implementation to perform the calculation we perform it here and le...
7,180
public Deferred < Object > publishHistogramPoint ( final String metric , final long timestamp , final byte [ ] value , final Map < String , String > tags , final byte [ ] tsuid ) { throw new UnsupportedOperationException ( "Not yet implemented" ) ; }
Called any time a new histogram point is published
7,181
void validateAndCompile ( ) { if ( temporal_table_name == null || temporal_table_name . isEmpty ( ) ) { throw new IllegalArgumentException ( "The rollup table cannot be null or empty" ) ; } temporal_table = temporal_table_name . getBytes ( Const . ASCII_CHARSET ) ; if ( groupby_table_name == null || groupby_table_name ...
Calculates the number of intervals in a given span for the rollup interval and makes sure we have table names . It also sets the table byte arrays .
7,182
public byte [ ] getBytes ( ) { final byte [ ] bytes = new byte [ qualifier . length + value . length ] ; System . arraycopy ( this . qualifier , 0 , bytes , 0 , qualifier . length ) ; System . arraycopy ( value , 0 , bytes , qualifier . length , value . length ) ; return bytes ; }
Concatenates the qualifier and value for appending to a column in the backing data store .
7,183
static long getMaxMetricID ( final TSDB tsdb ) { final GetRequest get = new GetRequest ( tsdb . uidTable ( ) , new byte [ ] { 0 } ) ; get . family ( "id" . getBytes ( CHARSET ) ) ; get . qualifier ( "metrics" . getBytes ( CHARSET ) ) ; ArrayList < KeyValue > row ; try { row = tsdb . getClient ( ) . get ( get ) . joinUn...
Returns the max metric ID from the UID table
7,184
static final Scanner getDataTableScanner ( final TSDB tsdb , final long start_id , final long end_id ) throws HBaseException { final short metric_width = TSDB . metrics_width ( ) ; final byte [ ] start_row = Arrays . copyOfRange ( Bytes . fromLong ( start_id ) , 8 - metric_width , 8 ) ; final byte [ ] end_row = Arrays ...
Returns a scanner set to iterate over a range of metrics in the main tsdb - data table .
7,185
private List < Filter > getFilters ( final boolean group_by ) { final int ntags = getNumTags ( ) ; final List < Filter > filters = new ArrayList < Filter > ( ntags ) ; for ( int tag = 0 ; tag < ntags ; tag ++ ) { final Filter filter = new Filter ( ) ; filter . tagk = getTagName ( tag ) ; filter . tagv = getTagValue ( t...
Helper method to extract the tags from the row set and sort them before sending to the API so that we avoid a bug wherein the sort order changes on reload .
7,186
private void setSelectedItem ( final ListBox list , final String item ) { final int nitems = list . getItemCount ( ) ; for ( int i = 0 ; i < nitems ; i ++ ) { if ( item . equals ( list . getValue ( i ) ) ) { list . setSelectedIndex ( i ) ; return ; } } }
If the given item is in the list mark it as selected .
7,187
public static HashedWheelTimer newTimer ( final int ticks , final int ticks_per_wheel , final String name ) { class TimerThreadNamer implements ThreadNameDeterminer { public String determineThreadName ( String currentThreadName , String proposedThreadName ) throws Exception { return "OpenTSDB Timer " + name + " #" + TI...
Returns a new HashedWheelTimer with a name and default ticks
7,188
public void validate ( ) { if ( interval == null || interval . isEmpty ( ) ) { throw new IllegalArgumentException ( "Missing or empty interval" ) ; } DateTime . parseDuration ( interval ) ; if ( aggregator == null || aggregator . isEmpty ( ) ) { throw new IllegalArgumentException ( "Missing or empty aggregator" ) ; } t...
Validates the downsampler
7,189
public void validate ( ) { if ( policy == null ) { if ( value == 0 ) { policy = FillPolicy . ZERO ; } else if ( Double . isNaN ( value ) ) { policy = FillPolicy . NOT_A_NUMBER ; } else { policy = FillPolicy . SCALAR ; } } else { switch ( policy ) { case NONE : case NOT_A_NUMBER : if ( value != 0 && ! Double . isNaN ( v...
Makes sure the policy name and value are a suitable combination . If one or the other is missing then we set the other with the proper value .
7,190
public HistogramDataPointCodec getCodec ( final int id ) { final HistogramDataPointCodec codec = codecs . get ( id ) ; if ( codec == null ) { throw new IllegalArgumentException ( "No codec found mapped to ID " + id ) ; } return codec ; }
Return the instance of the given codec .
7,191
public int getCodec ( final Class < ? > clazz ) { if ( clazz == null ) { throw new IllegalArgumentException ( "Clazz cannot be null." ) ; } final Integer id = codecs_ids . get ( clazz ) ; if ( id == null ) { throw new IllegalArgumentException ( "No codec ID assigned to class " + clazz ) ; } return id ; }
Return the ID of the given codec .
7,192
public byte [ ] encode ( final int id , final Histogram data_point , final boolean include_id ) { final HistogramDataPointCodec codec = getCodec ( id ) ; return codec . encode ( data_point , include_id ) ; }
Finds the proper codec and calls it s encode method to create a byte array with the given ID as the first byte .
7,193
public Histogram decode ( final int id , final byte [ ] raw_data , final boolean includes_id ) { final HistogramDataPointCodec codec = getCodec ( id ) ; return codec . decode ( raw_data , includes_id ) ; }
Finds the proper codec and calls it s decode method to return the histogram data point for queries or validation .
7,194
public Deferred < Object > execute ( final TSDB tsdb , final Channel chan , final String [ ] cmd ) { final boolean canonical = tsdb . getConfig ( ) . getBoolean ( "tsd.stats.canonical" ) ; final StringBuilder buf = new StringBuilder ( 1024 ) ; final ASCIICollector collector = new ASCIICollector ( "tsd" , buf , null ) ;...
Telnet RPC responder that returns the stats in ASCII style
7,195
public void execute ( final TSDB tsdb , final HttpQuery query ) { if ( query . method ( ) != HttpMethod . GET && query . method ( ) != HttpMethod . POST ) { throw new BadRequestException ( HttpResponseStatus . METHOD_NOT_ALLOWED , "Method not allowed" , "The HTTP method [" + query . method ( ) . getName ( ) + "] is not...
HTTP resposne handler
7,196
private void doCollectStats ( final TSDB tsdb , final StatsCollector collector , final boolean canonical ) { collector . addHostTag ( canonical ) ; ConnectionManager . collectStats ( collector ) ; RpcHandler . collectStats ( collector ) ; RpcManager . collectStats ( collector ) ; collectThreadStats ( collector ) ; tsdb...
Helper to record the statistics for the current TSD
7,197
private void printRegionClientStats ( final TSDB tsdb , final HttpQuery query ) { final List < RegionClientStats > region_stats = tsdb . getClient ( ) . regionStats ( ) ; final List < Map < String , Object > > stats = new ArrayList < Map < String , Object > > ( region_stats . size ( ) ) ; for ( final RegionClientStats ...
Display stats for each region client
7,198
private void printThreadStats ( final HttpQuery query ) { final Set < Thread > threads = Thread . getAllStackTraces ( ) . keySet ( ) ; final List < Map < String , Object > > output = new ArrayList < Map < String , Object > > ( threads . size ( ) ) ; for ( final Thread thread : threads ) { final Map < String , Object > ...
Grabs a snapshot of all JVM thread states and formats it in a manner to be displayed via API .
7,199
private void collectThreadStats ( final StatsCollector collector ) { final Set < Thread > threads = Thread . getAllStackTraces ( ) . keySet ( ) ; final Map < String , Integer > states = new HashMap < String , Integer > ( 6 ) ; states . put ( "new" , 0 ) ; states . put ( "runnable" , 0 ) ; states . put ( "blocked" , 0 )...
Runs through the live threads and counts captures a coune of their states for dumping in the stats page .