idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
32,100
def add_stack_frame ( self , stack_frame ) : if len ( self . stack_frames ) >= MAX_FRAMES : self . dropped_frames_count += 1 else : self . stack_frames . append ( stack_frame . format_stack_frame_json ( ) )
Add StackFrame to frames list .
32,101
def format_stack_trace_json ( self ) : stack_trace_json = { } if self . stack_frames : stack_trace_json [ 'stack_frames' ] = { 'frame' : self . stack_frames , 'dropped_frames_count' : self . dropped_frames_count } stack_trace_json [ 'stack_trace_hash_id' ] = self . stack_trace_hash_id return stack_trace_json
Convert a StackTrace object to json format .
32,102
def register_view ( self , view ) : self . measure_to_view_map . register_view ( view = view , timestamp = self . time )
registers the given view
32,103
def get_view ( self , view_name ) : return self . measure_to_view_map . get_view ( view_name = view_name , timestamp = self . time )
gets the view given the view name
32,104
def new_stats_exporter ( options = None , interval = None ) : if options is None : _ , project_id = google . auth . default ( ) options = Options ( project_id = project_id ) if str ( options . project_id ) . strip ( ) == "" : raise ValueError ( ERROR_BLANK_PROJECT_ID ) ci = client_info . ClientInfo ( client_library_ver...
Get a stats exporter and running transport thread .
32,105
def namespaced_view_name ( view_name , metric_prefix ) : metric_prefix = metric_prefix or "custom.googleapis.com/opencensus" return os . path . join ( metric_prefix , view_name ) . replace ( '\\' , '/' )
create string to be used as metric type
32,106
def new_label_descriptors ( defaults , keys ) : label_descriptors = [ ] for lk in itertools . chain . from_iterable ( ( defaults . keys ( ) , keys ) ) : label = { } label [ "key" ] = sanitize_label ( lk . key ) label [ "description" ] = lk . description label_descriptors . append ( label ) return label_descriptors
create labels for the metric_descriptor that will be sent to Stackdriver Monitoring
32,107
def sanitize_label ( text ) : if not text : return text text = re . sub ( '\\W+' , '_' , text ) if text [ 0 ] in string . digits : text = "key_" + text elif text [ 0 ] == '_' : text = "key" + text return text [ : 100 ]
Remove characters not accepted in labels key
32,108
def _convert_series ( self , metric , ts ) : series = monitoring_v3 . types . TimeSeries ( ) series . metric . type = self . get_metric_type ( metric . descriptor ) for lk , lv in self . options . default_monitoring_labels . items ( ) : series . metric . labels [ lk . key ] = lv . value for key , val in zip ( metric . ...
Convert an OC timeseries to a SD series .
32,109
def _convert_point ( self , metric , ts , point , sd_point ) : if ( metric . descriptor . type == metric_descriptor . MetricDescriptorType . CUMULATIVE_DISTRIBUTION ) : sd_dist_val = sd_point . value . distribution_value sd_dist_val . count = point . value . count sd_dist_val . sum_of_squared_deviation = point . value ...
Convert an OC metric point to a SD point .
32,110
def get_metric_descriptor ( self , oc_md ) : try : metric_kind , value_type = OC_MD_TO_SD_TYPE [ oc_md . type ] except KeyError : raise TypeError ( "Unsupported metric type: {}" . format ( oc_md . type ) ) if self . options . metric_prefix : display_name_prefix = self . options . metric_prefix else : display_name_prefi...
Convert an OC metric descriptor to a SD metric descriptor .
32,111
def register_metric_descriptor ( self , oc_md ) : metric_type = self . get_metric_type ( oc_md ) with self . _md_lock : if metric_type in self . _md_cache : return self . _md_cache [ metric_type ] descriptor = self . get_metric_descriptor ( oc_md ) project_name = self . client . project_path ( self . options . project_...
Register a metric descriptor with stackdriver .
32,112
def from_headers ( self , headers ) : if headers is None : return SpanContext ( ) header = headers . get ( _TRACE_CONTEXT_HEADER_NAME ) if header is None : return SpanContext ( ) header = str ( header . encode ( 'utf-8' ) ) return self . from_header ( header )
Generate a SpanContext object using the trace context header .
32,113
def to_header ( self , span_context ) : trace_id = span_context . trace_id span_id = span_context . span_id trace_options = span_context . trace_options . trace_options_byte header = '{}/{};o={}' . format ( trace_id , span_id , int ( trace_options ) ) return header
Convert a SpanContext object to header string .
32,114
def _extract_annotations_from_span ( span ) : if span . time_events is None : return [ ] annotations = [ ] for time_event in span . time_events : annotation = time_event . annotation if not annotation : continue event_timestamp_mus = timestamp_to_microseconds ( time_event . timestamp ) annotations . append ( { 'timesta...
Extract and convert time event annotations to zipkin annotations
32,115
def emit ( self , span_datas ) : try : zipkin_spans = self . translate_to_zipkin ( span_datas ) result = requests . post ( url = self . url , data = json . dumps ( zipkin_spans ) , headers = ZIPKIN_HEADERS ) if result . status_code not in SUCCESS_STATUS_CODE : logging . error ( "Failed to send spans to Zipkin server! S...
Send SpanData tuples to Zipkin server default using the v2 API .
32,116
def translate_to_zipkin ( self , span_datas ) : local_endpoint = { 'serviceName' : self . service_name , 'port' : self . port , } if self . ipv4 is not None : local_endpoint [ 'ipv4' ] = self . ipv4 if self . ipv6 is not None : local_endpoint [ 'ipv6' ] = self . ipv6 zipkin_spans = [ ] for span in span_datas : start_ti...
Translate the opencensus spans to zipkin spans .
32,117
def trace_engine ( engine ) : event . listen ( engine , 'before_cursor_execute' , _before_cursor_execute ) event . listen ( engine , 'after_cursor_execute' , _after_cursor_execute )
Register the event before cursor execute and after cursor execute to the event listner of the engine .
32,118
def check_points_type ( self , type_class ) : for point in self . points : if ( point . value is not None and not isinstance ( point . value , type_class ) ) : return False return True
Check that each point s value is an instance of type_class .
32,119
def get_log_attrs ( ) : try : tracer = execution_context . get_opencensus_tracer ( ) if tracer is None : raise RuntimeError except Exception : _meta_logger . error ( "Failed to get opencensus tracer" ) return ATTR_DEFAULTS try : trace_id = tracer . span_context . trace_id if trace_id is None : trace_id = ATTR_DEFAULTS ...
Get logging attributes from the opencensus context .
32,120
def trace_integration ( tracer = None ) : log . info ( 'Integrated module: {}' . format ( MODULE_NAME ) ) trace_grpc ( tracer ) trace_http ( tracer )
Trace the Google Cloud Client libraries by integrating with the transport level including HTTP and gRPC .
32,121
def trace_grpc ( tracer = None ) : make_secure_channel_func = getattr ( _helpers , MAKE_SECURE_CHANNEL ) make_secure_channel_wrapped = wrap_make_secure_channel ( make_secure_channel_func , tracer ) setattr ( _helpers , MAKE_SECURE_CHANNEL , make_secure_channel_wrapped ) insecure_channel_func = getattr ( grpc , INSECURE...
Integrate with gRPC .
32,122
def wrap_make_secure_channel ( make_secure_channel_func , tracer = None ) : def call ( * args , ** kwargs ) : channel = make_secure_channel_func ( * args , ** kwargs ) try : host = kwargs . get ( 'host' ) tracer_interceptor = OpenCensusClientInterceptor ( tracer , host ) intercepted_channel = grpc . intercept_channel (...
Wrap the google . cloud . _helpers . make_secure_channel .
32,123
def wrap_insecure_channel ( insecure_channel_func , tracer = None ) : def call ( * args , ** kwargs ) : channel = insecure_channel_func ( * args , ** kwargs ) try : target = kwargs . get ( 'target' ) tracer_interceptor = OpenCensusClientInterceptor ( tracer , target ) intercepted_channel = grpc . intercept_channel ( ch...
Wrap the grpc . insecure_channel .
32,124
def _convert_reftype_to_jaeger_reftype ( ref ) : if ref == link_module . Type . CHILD_LINKED_SPAN : return jaeger . SpanRefType . CHILD_OF if ref == link_module . Type . PARENT_LINKED_SPAN : return jaeger . SpanRefType . FOLLOWS_FROM return None
Convert opencensus reference types to jaeger reference types .
32,125
def _convert_hex_str_to_int ( val ) : if val is None : return None hex_num = int ( val , 16 ) if hex_num > 0x7FFFFFFFFFFFFFFF : hex_num -= 0x10000000000000000 assert - 9223372036854775808 <= hex_num <= 9223372036854775807 return hex_num
Convert hexadecimal formatted ids to signed int64
32,126
def _convert_attribute_to_tag ( key , attr ) : if isinstance ( attr , bool ) : return jaeger . Tag ( key = key , vBool = attr , vType = jaeger . TagType . BOOL ) if isinstance ( attr , str ) : return jaeger . Tag ( key = key , vStr = attr , vType = jaeger . TagType . STRING ) if isinstance ( attr , int ) : return jaege...
Convert the attributes to jaeger tags .
32,127
def translate_to_jaeger ( self , span_datas ) : top_span = span_datas [ 0 ] trace_id = top_span . context . trace_id if top_span . context is not None else None jaeger_spans = [ ] for span in span_datas : start_timestamp_ms = timestamp_to_microseconds ( span . start_time ) end_timestamp_ms = timestamp_to_microseconds (...
Translate the spans to Jaeger format .
32,128
def emit ( self , batch ) : try : self . client . submitBatches ( [ batch ] ) code = self . http_transport . code msg = self . http_transport . message if code >= 300 or code < 200 : logging . error ( "Traces cannot be uploaded;\ HTTP status code: {}, message {}" . format ( code , msg ) ) except ...
Submits batches to Thrift HTTP Server through Binary Protocol .
32,129
def get_tag_values ( self , tags , columns ) : tag_values = [ ] i = 0 while i < len ( columns ) : tag_key = columns [ i ] if tag_key in tags : tag_values . append ( tags . get ( tag_key ) ) else : tag_values . append ( None ) i += 1 return tag_values
function to get the tag values from tags and columns
32,130
def record ( self , context , value , timestamp , attachments = None ) : if context is None : tags = dict ( ) else : tags = context . map tag_values = self . get_tag_values ( tags = tags , columns = self . view . columns ) tuple_vals = tuple ( tag_values ) if tuple_vals not in self . tag_value_aggregation_data_map : se...
records the view data against context
32,131
def trace_integration ( tracer = None ) : log . info ( 'Integrated module: {}' . format ( MODULE_NAME ) ) request_func = getattr ( httplib . HTTPConnection , HTTPLIB_REQUEST_FUNC ) wrapped_request = wrap_httplib_request ( request_func ) setattr ( httplib . HTTPConnection , request_func . __name__ , wrapped_request ) re...
Wrap the httplib to trace .
32,132
def wrap_httplib_request ( request_func ) : def call ( self , method , url , body , headers , * args , ** kwargs ) : _tracer = execution_context . get_opencensus_tracer ( ) blacklist_hostnames = execution_context . get_opencensus_attr ( 'blacklist_hostnames' ) dest_url = '{}:{}' . format ( self . _dns_host , self . por...
Wrap the httplib request function to trace . Create a new span and update and close the span in the response later .
32,133
def wrap_httplib_response ( response_func ) : def call ( self , * args , ** kwargs ) : _tracer = execution_context . get_opencensus_tracer ( ) current_span_id = execution_context . get_opencensus_attr ( 'httplib/current_span_id' ) span = _tracer . current_span ( ) if not span or span . span_id != current_span_id : retu...
Wrap the httplib response function to trace .
32,134
def get_timeseries_list ( points , timestamp ) : ts_list = [ ] for lv , gp in points . items ( ) : point = point_module . Point ( gp . to_point_value ( ) , timestamp ) ts_list . append ( time_series . TimeSeries ( lv , [ point ] , timestamp ) ) return ts_list
Convert a list of GaugePoint s into a list of TimeSeries .
32,135
def add ( self , val ) : if not isinstance ( val , six . integer_types ) : raise ValueError ( "GaugePointLong only supports integer types" ) with self . _value_lock : self . value += val
Add val to the current value .
32,136
def get_value ( self ) : try : val = self . func ( ) ( ) except TypeError : return None self . gauge_point . _set ( val ) return self . gauge_point . get_value ( )
Get the current value of the underlying measurement .
32,137
def remove_time_series ( self , label_values ) : if label_values is None : raise ValueError if any ( lv is None for lv in label_values ) : raise ValueError if len ( label_values ) != self . _len_label_keys : raise ValueError self . _remove_time_series ( label_values )
Remove the time series for specific label values .
32,138
def get_metric ( self , timestamp ) : if not self . points : return None with self . _points_lock : ts_list = get_timeseries_list ( self . points , timestamp ) return metric . Metric ( self . descriptor , ts_list )
Get a metric including all current time series .
32,139
def get_or_create_time_series ( self , label_values ) : if label_values is None : raise ValueError if any ( lv is None for lv in label_values ) : raise ValueError if len ( label_values ) != self . _len_label_keys : raise ValueError return self . _get_or_create_time_series ( label_values )
Get a mutable measurement for the given set of label values .
32,140
def create_time_series ( self , label_values , func ) : if label_values is None : raise ValueError if any ( lv is None for lv in label_values ) : raise ValueError if len ( label_values ) != self . _len_label_keys : raise ValueError if func is None : raise ValueError return self . _create_time_series ( label_values , fu...
Create a derived measurement to trac func .
32,141
def create_default_time_series ( self , func ) : if func is None : raise ValueError return self . _create_time_series ( self . default_label_values , func )
Create the default derived measurement for this gauge .
32,142
def add_gauge ( self , gauge ) : if gauge is None : raise ValueError name = gauge . descriptor . name with self . _gauges_lock : if name in self . gauges : raise ValueError ( 'Another gauge named "{}" is already registered' . format ( name ) ) self . gauges [ name ] = gauge
Add gauge to the registry .
32,143
def get_metrics ( self ) : now = datetime . utcnow ( ) metrics = set ( ) for gauge in self . gauges . values ( ) : metrics . add ( gauge . get_metric ( now ) ) return metrics
Get a metric for each gauge in the registry at the current time .
32,144
def _initialize_metadata_service ( cls ) : if cls . inited : return instance_id = cls . get_attribute ( 'instance/id' ) if instance_id is not None : cls . is_running = True _GCP_METADATA_MAP [ 'instance_id' ] = instance_id for attribute_key , attribute_uri in _GCE_ATTRIBUTES . items ( ) : if attribute_key not in _GCP_M...
Initialize metadata service once and load gcp metadata into map This method should only be called once .
32,145
def to_header ( self , span_context ) : trace_id = span_context . trace_id span_id = span_context . span_id trace_options = int ( span_context . trace_options . trace_options_byte ) if span_id is None : span_id = span_context_module . INVALID_SPAN_ID return struct . pack ( BINARY_FORMAT , VERSION_ID , TRACE_ID_FIELD_ID...
Convert a SpanContext object to header in binary format .
32,146
def from_carrier ( self , carrier ) : trace_id = None span_id = None trace_options = None for key in carrier : key = key . lower ( ) if key == _TRACE_ID_KEY : trace_id = carrier [ key ] if key == _SPAN_ID_KEY : span_id = carrier [ key ] if key == _TRACE_OPTIONS_KEY : trace_options = bool ( carrier [ key ] ) if trace_op...
Generate a SpanContext object using the information in the carrier .
32,147
def to_carrier ( self , span_context , carrier ) : carrier [ _TRACE_ID_KEY ] = str ( span_context . trace_id ) if span_context . span_id is not None : carrier [ _SPAN_ID_KEY ] = str ( span_context . span_id ) carrier [ _TRACE_OPTIONS_KEY ] = str ( span_context . trace_options . trace_options_byte ) return carrier
Inject the SpanContext fields to carrier dict .
32,148
def from_headers ( self , headers ) : if headers is None : return SpanContext ( from_header = False ) trace_id , span_id , sampled = None , None , None state = headers . get ( _STATE_HEADER_KEY ) if state : fields = state . split ( '-' , 4 ) if len ( fields ) == 1 : sampled = fields [ 0 ] elif len ( fields ) == 2 : tra...
Generate a SpanContext object from B3 propagation headers .
32,149
def to_headers ( self , span_context ) : if not span_context . span_id : span_id = INVALID_SPAN_ID else : span_id = span_context . span_id sampled = span_context . trace_options . enabled return { _TRACE_ID_KEY : span_context . trace_id , _SPAN_ID_KEY : span_id , _SAMPLED_KEY : '1' if sampled else '0' }
Convert a SpanContext object to B3 propagation headers .
32,150
def _check_span_id ( self , span_id ) : if span_id is None : return None assert isinstance ( span_id , six . string_types ) if span_id is INVALID_SPAN_ID : logging . warning ( 'Span_id {} is invalid (cannot be all zero)' . format ( span_id ) ) self . from_header = False return None match = SPAN_ID_PATTERN . match ( spa...
Check the format of the span_id to ensure it is 16 - character hex value representing a 64 - bit number . If span_id is invalid logs a warning message and returns None
32,151
def _check_trace_id ( self , trace_id ) : assert isinstance ( trace_id , six . string_types ) if trace_id is _INVALID_TRACE_ID : logging . warning ( 'Trace_id {} is invalid (cannot be all zero), ' 'generating a new one.' . format ( trace_id ) ) self . from_header = False return generate_trace_id ( ) match = TRACE_ID_PA...
Check the format of the trace_id to ensure it is 32 - character hex value representing a 128 - bit number . If trace_id is invalid returns a randomly generated trace id
32,152
def format_status_json ( self ) : status_json = { } status_json [ 'code' ] = self . code status_json [ 'message' ] = self . message if self . details is not None : status_json [ 'details' ] = self . details return status_json
Convert a Status object to json format .
32,153
def from_headers ( self , headers ) : if headers is None : return SpanContext ( ) header = headers . get ( _TRACEPARENT_HEADER_NAME ) if header is None : return SpanContext ( ) match = re . search ( _TRACEPARENT_HEADER_FORMAT_RE , header ) if not match : return SpanContext ( ) version = match . group ( 1 ) trace_id = m...
Generate a SpanContext object using the W3C Distributed Tracing headers .
32,154
def to_headers ( self , span_context ) : trace_id = span_context . trace_id span_id = span_context . span_id trace_options = span_context . trace_options . enabled trace_options = '01' if trace_options else '00' headers = { _TRACEPARENT_HEADER_NAME : '00-{}-{}-{}' . format ( trace_id , span_id , trace_options ) , } tra...
Convert a SpanContext object to W3C Distributed Tracing headers using version 0 .
32,155
def get_truncatable_str ( str_to_convert ) : truncated , truncated_byte_count = check_str_length ( str_to_convert , MAX_LENGTH ) result = { 'value' : truncated , 'truncated_byte_count' : truncated_byte_count , } return result
Truncate a string if exceed limit and record the truncated bytes count .
32,156
def check_str_length ( str_to_check , limit = MAX_LENGTH ) : str_bytes = str_to_check . encode ( UTF8 ) str_len = len ( str_bytes ) truncated_byte_count = 0 if str_len > limit : truncated_byte_count = str_len - limit str_bytes = str_bytes [ : limit ] result = str ( str_bytes . decode ( UTF8 , errors = 'ignore' ) ) retu...
Check the length of a string . If exceeds limit then truncate it .
32,157
def iuniq ( ible ) : items = set ( ) for item in ible : if item not in items : items . add ( item ) yield item
Get an iterator over unique items of ible .
32,158
def window ( ible , length ) : if length <= 0 : raise ValueError ible = iter ( ible ) while True : elts = [ xx for ii , xx in zip ( range ( length ) , ible ) ] if elts : yield elts else : break
Split ible into multiple lists of length length .
32,159
def get_weakref ( func ) : if func is None : raise ValueError if not hasattr ( func , '__self__' ) : return weakref . ref ( func ) return WeakMethod ( func )
Get a weak reference to bound or unbound func .
32,160
def wrap_conn ( conn_func ) : def call ( * args , ** kwargs ) : try : conn = conn_func ( * args , ** kwargs ) cursor_func = getattr ( conn , CURSOR_WRAP_METHOD ) wrapped = wrap_cursor ( cursor_func ) setattr ( conn , cursor_func . __name__ , wrapped ) return conn except Exception : logging . warning ( 'Fail to wrap con...
Wrap the mysql conn object with TraceConnection .
32,161
def measure_int_put ( self , measure , value ) : if value < 0 : logger . warning ( "Cannot record negative values" ) self . _measurement_map [ measure ] = value
associates the measure of type Int with the given value
32,162
def measure_float_put ( self , measure , value ) : if value < 0 : logger . warning ( "Cannot record negative values" ) self . _measurement_map [ measure ] = value
associates the measure of type Float with the given value
32,163
def measure_put_attachment ( self , key , value ) : if self . _attachments is None : self . _attachments = dict ( ) if key is None or not isinstance ( key , str ) : raise TypeError ( 'attachment key should not be ' 'empty and should be a string' ) if value is None or not isinstance ( value , str ) : raise TypeError ( '...
Associate the contextual information of an Exemplar to this MeasureMap Contextual information is represented as key - value string pairs . If this method is called multiple times with the same key only the last value will be kept .
32,164
def record ( self , tags = None ) : if tags is None : tags = TagContext . get ( ) if self . _invalid : logger . warning ( "Measurement map has included negative value " "measurements, refusing to record" ) return for measure , value in self . measurement_map . items ( ) : if value < 0 : self . _invalid = True logger . ...
records all the measures at the same time with a tag_map . tag_map could either be explicitly passed to the method or implicitly read from current runtime context .
32,165
def translate_to_trace_proto ( span_data ) : if not span_data : return None pb_span = trace_pb2 . Span ( name = trace_pb2 . TruncatableString ( value = span_data . name ) , kind = span_data . span_kind , trace_id = hex_str_to_bytes_str ( span_data . context . trace_id ) , span_id = hex_str_to_bytes_str ( span_data . sp...
Translates the opencensus spans to ocagent proto spans .
32,166
def set_proto_message_event ( pb_message_event , span_data_message_event ) : pb_message_event . type = span_data_message_event . type pb_message_event . id = span_data_message_event . id pb_message_event . uncompressed_size = span_data_message_event . uncompressed_size_bytes pb_message_event . compressed_size = span_da...
Sets properties on the protobuf message event .
32,167
def set_proto_annotation ( pb_annotation , span_data_annotation ) : pb_annotation . description . value = span_data_annotation . description if span_data_annotation . attributes is not None and span_data_annotation . attributes . attributes is not None : for attribute_key , attribute_value in span_data_annotation . att...
Sets properties on the protobuf Span annotation .
32,168
def add_proto_attribute_value ( pb_attributes , attribute_key , attribute_value ) : if isinstance ( attribute_value , bool ) : pb_attributes . attribute_map [ attribute_key ] . bool_value = attribute_value elif isinstance ( attribute_value , int ) : pb_attributes . attribute_map [ attribute_key ] . int_value = attribut...
Sets string int boolean or float value on protobuf span link or annotation attributes .
32,169
def generate_span_requests ( self , span_datas ) : pb_spans = [ utils . translate_to_trace_proto ( span_data ) for span_data in span_datas ] yield trace_service_pb2 . ExportTraceServiceRequest ( node = self . node , spans = pb_spans )
Span request generator .
32,170
def update_config ( self , config ) : lock = Lock ( ) with lock : config_responses = self . client . Config ( self . generate_config_request ( config ) ) agent_config = next ( config_responses ) return agent_config
Sends TraceConfig to the agent and gets agent s config in reply .
32,171
def generate_config_request ( self , config ) : request = trace_service_pb2 . CurrentLibraryConfig ( node = self . node , config = config ) yield request
ConfigTraceServiceRequest generator .
32,172
def _set_default_configs ( user_settings , default ) : for key in default : if key not in user_settings : user_settings [ key ] = default [ key ] return user_settings
Set the default value to user settings if user not specified the value .
32,173
def format_link_json ( self ) : link_json = { } link_json [ 'trace_id' ] = self . trace_id link_json [ 'span_id' ] = self . span_id link_json [ 'type' ] = self . type if self . attributes is not None : link_json [ 'attributes' ] = self . attributes return link_json
Convert a Link object to json format .
32,174
def _wrap_rpc_behavior ( handler , fn ) : if handler is None : return None if handler . request_streaming and handler . response_streaming : behavior_fn = handler . stream_stream handler_factory = grpc . stream_stream_rpc_method_handler elif handler . request_streaming and not handler . response_streaming : behavior_fn...
Returns a new rpc handler that wraps the given function
32,175
def _get_span_name ( servicer_context ) : method_name = servicer_context . _rpc_event . call_details . method [ 1 : ] if isinstance ( method_name , bytes ) : method_name = method_name . decode ( 'utf-8' ) method_name = method_name . replace ( '/' , '.' ) return '{}.{}' . format ( RECV_PREFIX , method_name )
Generates a span name based off of the gRPC server rpc_request_info
32,176
def new_stats_exporter ( option ) : if option . namespace == "" : raise ValueError ( "Namespace can not be empty string." ) collector = new_collector ( option ) exporter = PrometheusStatsExporter ( options = option , gatherer = option . registry , collector = collector ) return exporter
new_stats_exporter returns an exporter that exports stats to Prometheus .
32,177
def get_view_name ( namespace , view ) : name = "" if namespace != "" : name = namespace + "_" return sanitize ( name + view . name )
create the name for the view
32,178
def register_view ( self , view ) : v_name = get_view_name ( self . options . namespace , view ) if v_name not in self . registered_views : desc = { 'name' : v_name , 'documentation' : view . description , 'labels' : list ( map ( sanitize , view . columns ) ) } self . registered_views [ v_name ] = desc self . registry ...
register_view will create the needed structure in order to be able to sent all data to Prometheus
32,179
def add_view_data ( self , view_data ) : self . register_view ( view_data . view ) v_name = get_view_name ( self . options . namespace , view_data . view ) self . view_name_to_data_map [ v_name ] = view_data
Add view data object to be sent to server
32,180
def to_metric ( self , desc , tag_values , agg_data ) : metric_name = desc [ 'name' ] metric_description = desc [ 'documentation' ] label_keys = desc [ 'labels' ] assert ( len ( tag_values ) == len ( label_keys ) ) tag_values = [ tv if tv else "" for tv in tag_values ] if isinstance ( agg_data , aggregation_data_module...
to_metric translate the data that OpenCensus create to Prometheus format using Prometheus Metric object
32,181
def collect ( self ) : for v_name , view_data in self . view_name_to_data_map . items ( ) : if v_name not in self . registered_views : continue desc = self . registered_views [ v_name ] for tag_values in view_data . tag_value_aggregation_data_map : agg_data = view_data . tag_value_aggregation_data_map [ tag_values ] me...
Collect fetches the statistics from OpenCensus and delivers them as Prometheus Metrics . Collect is invoked every time a prometheus . Gatherer is run for example when the HTTP endpoint is invoked by Prometheus .
32,182
def serve_http ( self ) : start_http_server ( port = self . options . port , addr = str ( self . options . address ) )
serve_http serves the Prometheus endpoint .
32,183
def format_time_event_json ( self ) : time_event = { } time_event [ 'time' ] = self . timestamp if self . annotation is not None : time_event [ 'annotation' ] = self . annotation . format_annotation_json ( ) if self . message_event is not None : time_event [ 'message_event' ] = self . message_event . format_message_eve...
Convert a TimeEvent object to json format .
32,184
def should_sample ( self , trace_id ) : lower_long = get_lower_long_from_trace_id ( trace_id ) bound = self . rate * MAX_VALUE if lower_long <= bound : return True else : return False
Make the sampling decision based on the lower 8 bytes of the trace ID . If the value is less than the bound return True else False .
32,185
def add ( self , val ) : if not isinstance ( val , six . integer_types ) : raise ValueError ( "CumulativePointLong only supports integer types" ) if val > 0 : super ( CumulativePointLong , self ) . add ( val )
Add val to the current value if it s positive .
32,186
def should_sample ( self ) : return self . span_context . trace_options . enabled or self . sampler . should_sample ( self . span_context . trace_id )
Determine whether to sample this request or not . If the context enables tracing return True . Else follow the decision of the sampler .
32,187
def get_tracer ( self ) : sampled = self . should_sample ( ) if sampled : self . span_context . trace_options . set_enabled ( True ) return context_tracer . ContextTracer ( exporter = self . exporter , span_context = self . span_context ) else : return noop_tracer . NoopTracer ( )
Return a tracer according to the sampling decision .
32,188
def trace_decorator ( self ) : def decorator ( func ) : def wrapper ( * args , ** kwargs ) : self . tracer . start_span ( name = func . __name__ ) return_value = func ( * args , ** kwargs ) self . tracer . end_span ( ) return return_value return wrapper return decorator
Decorator to trace a function .
32,189
def set_attributes ( trace ) : spans = trace . get ( 'spans' ) for span in spans : if span . get ( 'attributes' ) is None : span [ 'attributes' ] = { } if is_gae_environment ( ) : set_gae_attributes ( span ) set_common_attributes ( span ) set_monitored_resource_attributes ( span )
Automatically set attributes for Google Cloud environment .
32,190
def set_common_attributes ( span ) : common = { attributes_helper . COMMON_ATTRIBUTES . get ( 'AGENT' ) : AGENT , } common_attrs = Attributes ( common ) . format_attributes_json ( ) . get ( 'attributeMap' ) _update_attr_map ( span , common_attrs )
Set the common attributes .
32,191
def set_gae_attributes ( span ) : for env_var , attribute_key in GAE_ATTRIBUTES . items ( ) : attribute_value = os . environ . get ( env_var ) if attribute_value is not None : pair = { attribute_key : attribute_value } pair_attrs = Attributes ( pair ) . format_attributes_json ( ) . get ( 'attributeMap' ) _update_attr_m...
Set the GAE environment common attributes .
32,192
def translate_to_stackdriver ( self , trace ) : set_attributes ( trace ) spans_json = trace . get ( 'spans' ) trace_id = trace . get ( 'traceId' ) for span in spans_json : span_name = 'projects/{}/traces/{}/spans/{}' . format ( self . project_id , trace_id , span . get ( 'spanId' ) ) span_json = { 'name' : span_name , ...
Translate the spans json to Stackdriver format .
32,193
def merge_resources ( resource_list ) : if not resource_list : raise ValueError rtype = None for rr in resource_list : if rr . type : rtype = rr . type break labels = { } for rr in reversed ( resource_list ) : labels . update ( rr . labels ) return Resource ( rtype , labels )
Merge multiple resources to get a new resource .
32,194
def check_ascii_256 ( string ) : if string is None : return if len ( string ) > 256 : raise ValueError ( "Value is longer than 256 characters" ) bad_char = _NON_PRINTABLE_ASCII . search ( string ) if bad_char : raise ValueError ( u'Character "{}" at position {} is not printable ' 'ASCII' . format ( string [ bad_char . ...
Check that string is printable ASCII and at most 256 chars .
32,195
def parse_labels ( labels_str ) : if not _LABELS_RE . match ( labels_str ) : return None labels = { } for kv in _KV_RE . finditer ( labels_str ) : gd = kv . groupdict ( ) key = unquote ( gd [ 'key' ] ) if key in labels : logger . warning ( 'Duplicate label key "%s"' , key ) labels [ key ] = unquote ( gd [ 'val' ] ) ret...
Parse label keys and values following the Resource spec .
32,196
def get_from_env ( ) : type_env = os . getenv ( OC_RESOURCE_TYPE ) if type_env is None : return None type_env = type_env . strip ( ) labels_env = os . getenv ( OC_RESOURCE_LABELS ) if labels_env is None : return Resource ( type_env ) labels = parse_labels ( labels_env ) return Resource ( type_env , labels )
Get a Resource from environment variables .
32,197
def apply ( self , snapshot ) : for name in snapshot : setattr ( self , name , snapshot [ name ] )
Set the current context from a given snapshot dictionary
32,198
def snapshot ( self ) : return dict ( ( n , self . _slots [ n ] . get ( ) ) for n in self . _slots . keys ( ) )
Return a dictionary of current slots by reference .
32,199
def with_current_context ( self , func ) : caller_context = self . snapshot ( ) def call_with_current_context ( * args , ** kwargs ) : try : backup_context = self . snapshot ( ) self . apply ( caller_context ) return func ( * args , ** kwargs ) finally : self . apply ( backup_context ) return call_with_current_context
Capture the current context and apply it to the provided func