def bubblesort(a): swapped = True while swapped: swapped = False for i in range(1, len(a)): with opentracing.start_child_span( parent_span, operation_name='bubblesort/check_length') as child_span: child_span.log_event( "Compare length of index versus the previous element.") child_span.set_tag('step', 'check_length') sleep_dot() if len(a[i - 1]) > len(a[i]): with opentracing.start_child_span( child_span, operation_name='bubblesort/swap_positions' ) as child_span: child_span.log_event( "Swap the index and the previous element.") child_span.set_tag('step', 'swap_positions') a[i], a[i - 1] = a[i - 1], a[i] print(a) swapped = True sleep_dot() return a
def add_spans(): """Calls the opentracing API, doesn't use any LightStep-specific code. """ with opentracing.tracer.start_span(operation_name='trivial/initial_request') as parent_span: parent_span.set_tag('url', 'localhost') sleep_dot() parent_span.log_event('All good here!', payload={'N': 42, 'pi': 3.14, 'abc': 'xyz'}) parent_span.log_kv({'foo': 'bar'}) parent_span.set_tag('span_type', 'parent') parent_span.set_tag('int_tag', 5) parent_span.set_tag('unicode_val', u'non-ascii: \u200b') parent_span.set_tag('bool_tag', True) parent_span.set_baggage_item('checked', 'baggage') sleep_dot() # This is how you would represent starting work locally. with opentracing.start_child_span(parent_span, operation_name='trivial/child_request') as child_span: child_span.set_tag('span_type', 'child') # Pretend there was an error child_span.set_tag('error', True) child_span.log_event('Uh Oh!', payload={'stacktrace': traceback.extract_stack()}) sleep_dot() # Play with the propagation APIs... this is not IPC and thus not # where they're intended to be used. text_carrier = {} opentracing.tracer.inject(child_span.context, opentracing.Format.TEXT_MAP, text_carrier) span_context = opentracing.tracer.extract(opentracing.Format.TEXT_MAP, text_carrier) with opentracing.tracer.start_span( 'trivial/remote_span', child_of=span_context) as remote_span: remote_span.log_event('Remote!') remote_span.set_tag('span_type', 'remote') sleep_dot()
def add_spans(): """Calls the opentracing API, doesn't use any X-Ray-specific code. """ with opentracing.tracer.start_span( operation_name='trivial/initial_request') as parent_span: parent_span.set_tag('url', 'localhost') sleep_dot() parent_span.log_event('All good here!', payload={ 'N': 42, 'pi': 3.14, 'abc': 'xyz' }) parent_span.log_kv({ 'foo': 'bar', 'int': 42, 'float': 4.2, 'bool': True, 'obj': { 'blargh': 'hmm', 'whee': 4324 } }) parent_span.set_tag('span_type', 'parent') parent_span.set_tag('int_tag', 5) parent_span.set_tag('unicode_val', u'non-ascii: \u200b') parent_span.set_tag('bool_tag', True) parent_span.set_baggage_item('checked', 'baggage') sleep_dot() # This is how you would represent starting work locally. with opentracing.start_child_span( parent_span, operation_name='trivial/child_request') as child_span: child_span.set_tag('span_type', 'child') # Pretend there was an error child_span.set_tag('error', True) child_span.log_event( 'Uh Oh!', payload={ 'stacktrace': [tuple(f) for f in traceback.extract_stack()] }) sleep_dot() # Play with the propagation APIs... this is not IPC and thus not # where they're intended to be used. text_carrier = {} opentracing.tracer.inject(child_span.context, opentracing.Format.TEXT_MAP, text_carrier) span_context = opentracing.tracer.extract( opentracing.Format.TEXT_MAP, text_carrier) with opentracing.tracer.start_span( 'trivial/remote_span', child_of=span_context) as remote_span: remote_span.log_event('Remote!') remote_span.set_tag('span_type', 'remote') sleep_dot()
def workspace_modules(self, path, parent_span) -> List[Module]: """Return a set of all python modules found within a given path.""" with opentracing.start_child_span( parent_span, "workspace_modules") as workspace_modules_span: workspace_modules_span.set_tag("path", path) dir = self.fs.listdir(path, workspace_modules_span) modules = [] for e in dir: if e.is_dir: subpath = filepath.join(path, e.name) subdir = self.fs.listdir(subpath, workspace_modules_span) if any([s.name == "__init__.py" for s in subdir]): modules.append( Module(e.name, filepath.join(subpath, "__init__.py"), True)) else: name, ext = filepath.splitext(e.name) if ext == ".py": if name == "__init__": name = filepath.basename(path) modules.append( Module(name, filepath.join(path, e.name), True)) else: modules.append( Module(name, filepath.join(path, e.name))) return modules
def mkspan(self, name, parent=None, tags={}): span = opentracing.start_child_span(parent, operation_name=name) \ if parent \ else self.tracer.start_span(operation_name=name) for k, v in tags.items(): span.set_tag(k, v) return span
def find_module_remote(string, dir=None, fullname=None): """A swap-in replacement for Jedi's find module function that uses the remote fs to resolve module imports.""" with opentracing.start_child_span( parent_span, "find_module_remote_callback") as find_module_span: if trace: print("find_module_remote", string, dir, fullname) the_module = None # default behavior is to search for built-ins first if fullname: the_module = self.workspace.find_stdlib_module(fullname) # after searching for built-ins, search the current project if not the_module: the_module = self.workspace.find_project_module(fullname) # finally, search 3rd party dependencies if not the_module: the_module = self.workspace.find_external_module(fullname) if not the_module: raise ImportError('Module "{}" not found in {}', string, dir) is_package = the_module.is_package module_file = DummyFile(self.workspace.open_module_file(the_module, find_module_span)) module_path = filepath.dirname(the_module.path) if is_package else the_module.path return module_file, module_path, is_package
def add_spans(): """Calls the opentracing API, doesn't use any LightStep-specific code. """ with opentracing.tracer.start_span(operation_name='trivial/initial_request') as parent_span: parent_span.set_tag('url', 'localhost') parent_span.log_event('All good here!', payload={'N': 42, 'pi': 3.14, 'abc': 'xyz'}) parent_span.set_tag('span_type', 'parent') parent_span.set_baggage_item('checked', 'baggage') rng = random.SystemRandom() for i in range(50): time.sleep(rng.random() * 0.2) sys.stdout.write('.') sys.stdout.flush() # This is how you would represent starting work locally. with opentracing.start_child_span(parent_span, operation_name='trivial/child_request') as child_span: child_span.log_event('Uh Oh!', payload={'error': True}) child_span.set_tag('span_type', 'child') # Play with the propagation APIs... this is not IPC and thus not # where they're intended to be used. text_carrier = {} opentracing.tracer.inject(child_span.context, opentracing.Format.TEXT_MAP, text_carrier) span_context = opentracing.tracer.extract(opentracing.Format.TEXT_MAP, text_carrier) with opentracing.tracer.start_span( 'nontrivial/remote_span', child_of=span_context) as remote_span: remote_span.log_event('Remote!') remote_span.set_tag('span_type', 'remote') time.sleep(rng.random() * 0.1) opentracing.tracer.flush()
def load_source(path) -> str: with opentracing.start_child_span( parent_span, "load_source_callback") as load_source_span: load_source_span.set_tag("path", path) if trace: print("load_source", path) result = self.fs.open(path, load_source_span) return result
def test_start_child_span(self): tracer = self.tracer() parent_span = tracer.start_span(operation_name='parent') assert parent_span is not None child_span = opentracing.start_child_span( parent_span, operation_name='Leela') child_span.finish() parent_span.finish()
def test_start_child_span(self): tracer = self.tracer() parent_span = tracer.start_span(operation_name='parent') assert parent_span is not None child_span = opentracing.start_child_span(parent_span, operation_name='Leela') child_span.finish() parent_span.finish()
def listdir(self, path, parent_span=None): if parent_span is None: return self._listdir(path) with opentracing.start_child_span( parent_span, "RemoteFileSystem.listdir") as list_span: list_span.set_tag("path", path) # TODO(keegan) Use workspace/xfiles + cache return self._listdir(path)
def quicksort(a): with opentracing.start_child_span(parent_span, operation_name='quicksort/check_sorted') as child_span: child_span.log_event("What's left to sort?", payload={str(a)} ) child_span.set_tag('step', 'check_sorted') if len(a)<=1: child_span.log_event("Nothing left to sort in this partition!", payload={str(a)} ) return a sleep_dot() with opentracing.start_child_span(parent_span, operation_name='quicksort/select_pivot') as child_span: child_span.set_tag('step', 'select_pivot') pivot = a[randint(0,len(a)-1)] smaller, equal, larger = [],[],[] child_span.log_event("Let's choose a new pivot string!", payload={pivot} ) sleep_dot() for word in a: with opentracing.start_child_span(child_span, operation_name='quicksort/sort_partition') as child_span: child_span.set_tag('step', 'sort_partition') child_span.log_event("Compare the pivot to elements in current partition.", payload={pivot, word} ) if len(word) < len(pivot): smaller.append(word) child_span.set_tag('pivot', pivot) child_span.log_event("Append to array of smaller strings.", payload={str(smaller)} ) elif len(word) == len(pivot): equal.append(word) child_span.set_tag('pivot', pivot) child_span.log_event("Append to array of equal strings.", payload={str(equal)} ) else: larger.append(word) child_span.set_tag('pivot', pivot) child_span.log_event("Append to array of larger strings.", payload={str(larger)} ) # Print the pivot and each array to help visualize the recursion. print(pivot) print(smaller, equal, larger) sleep_dot() return quicksort(smaller)+equal+quicksort(larger)
def find_module_remote(string, dir=None, fullname=None): """A swap-in replacement for Jedi's find module function that uses the remote fs to resolve module imports.""" if dir is None: dir = get_module_search_paths(string, path) with opentracing.start_child_span( parent_span, "find_module_remote_callback") as find_module_span: if trace: print("find_module_remote", string, dir, fullname) the_module = None # TODO: move this bit of logic into the Workspace? # default behavior is to search for built-ins first, but skip # this if we're actually in the stdlib repo if fullname and not self.workspace.is_stdlib: the_module = self.workspace.find_stdlib_module(fullname) if the_module == "native": # break if we get a native module raise ImportError('Module "{}" not found in {}', string, dir) # TODO: use this clause's logic for the other clauses too # (stdlib and external modules) after searching for built-ins, # search the current project if not the_module: module_file, module_path, is_package = self.workspace.find_internal_module( string, fullname, dir) if module_file or module_path: if is_package and module_path.endswith(".py"): module_path = os.path.dirname(module_path) return module_file, module_path, is_package # finally, search 3rd party dependencies if not the_module: the_module = self.workspace.find_external_module(fullname) if not the_module: raise ImportError('Module "{}" not found in {}', string, dir) is_package = the_module.is_package module_file = self.workspace.open_module_file( the_module, find_module_span) module_path = the_module.path if is_package and the_module.is_namespace_package: module_path = jedi._compatibility.ImplicitNSInfo( fullname, [module_path]) is_package = False elif is_package and module_path.endswith(".py"): module_path = filepath.dirname(module_path) return module_file, module_path, is_package
def listdir(self, path, parent_span): with opentracing.start_child_span( parent_span, "RemoteFileSystem.listdir") as list_span: list_span.set_tag("path", path) # TODO(keegan) Use workspace/xfiles + cache resp = self.conn.send_request("fs/readDir", path) if resp.get("error") is not None: raise FileException(resp["error"]) entries = [] for e in resp["result"]: entries.append(Entry(e["name"], e["dir"], e["size"])) return entries
def open(self, path, parent_span): with opentracing.start_child_span( parent_span, "RemoteFileSystem.open") as open_span: open_span.set_tag("path", path) resp = self.conn.send_request( "textDocument/xcontent", {"textDocument": { "uri": "file://" + path }}) if "error" in resp: raise FileException(resp["error"]) return resp["result"]["text"]
def route_and_respond(self, request): log.info("REQUEST %s %s", request.get("id"), request.get("method")) def noop(*args): return None handler = { "initialize": self.serve_initialize, "textDocument/hover": self.serve_hover, "textDocument/definition": self.serve_definition, "textDocument/xdefinition": self.serve_x_definition, "textDocument/references": self.serve_references, "workspace/xreferences": self.serve_x_references, "textDocument/documentSymbol": self.serve_document_symbols, "workspace/symbol": self.serve_symbols, "workspace/xpackages": self.serve_x_packages, "workspace/xdependencies": self.serve_x_dependencies, "$/cancelRequest": noop, "shutdown": noop, "exit": self.serve_exit, }.get(request["method"], self.serve_default) # We handle notifications differently since we can't respond if "id" not in request: try: handler(request) except Exception as e: log.warning("error handling notification %s", request, exc_info=True) return try: resp = handler(request) except JSONRPC2Error as e: self.conn.write_error(request["id"], code=e.code, message=e.message, data=e.data) except Exception as e: log.warning("handler for %s failed", request, exc_info=True) self.conn.write_error(request["id"], code=-32603, message=str(e), data={ "traceback": traceback.format_exc(), }) log.warning("error handling request %s", request, exc_info=True) else: with opentracing.start_child_span(request["span"], "send_response"): self.conn.write_response(request["id"], resp)
def goto_definitions(script, request): parent_span = request["span"] try: with opentracing.start_child_span(parent_span, "Script.goto_definitions"): return script.goto_definitions() except Exception as e: # TODO return these errors using JSONRPC properly. Doing it # this way initially for debugging purposes. log.error("Failed goto_definitions for %s", request, exc_info=True) parent_span.log_kv( {"error", "Failed goto_definitions for %s" % request}) return []
def new_script(self, *args, **kwargs): """Return an initialized Jedi API Script object.""" if "parent_span" in kwargs: parent_span = kwargs.get("parent_span") del kwargs["parent_span"] else: parent_span = opentracing.tracer.start_span("new_script_parent") with opentracing.start_child_span(parent_span, "new_script") as new_script_span: path = kwargs.get("path") new_script_span.set_tag("path", path) return self._new_script_impl(new_script_span, *args, **kwargs)
def before_sending_request(request, parent_span): """Context manager creates Span and encodes the span's SpanContext into request. """ span = opentracing.start_child_span(parent_span, 'trivial/node_request') span.log_event('include', ['client']) host = request.get_host() if host: span.set_tag(opentracing.ext.tags.PEER_HOSTNAME, host) carrier_dict = {} span.tracer.inject(span.context, opentracing.Format.HTTP_HEADERS, carrier_dict) for k, v in carrier_dict.iteritems(): request.add_header(k, v) return span
def bubble_sort(array, parent_span): with opentracing.start_child_span( parent_span, operation_name='bubbleSort/bubbleSortExecution') as child_span: child_span.log_event('Executing bubbleSort', payload={'array': array}) child_span.set_tag('span_type', 'child') for i in range(len(array)): for j in range(i + 1, len(array)): if len(array[j]) < len(array[i]): time.sleep(0.05) array[j], array[i] = array[i], array[j] payLoadMessage = '({},{}) => swapped => ({},{})'.format( array[j], array[i], array[i], array[j]) print(payLoadMessage) child_span.log_event('Swapping elements', payload={'swapped': payLoadMessage}) opentracing.tracer.flush() return array
def batch_open(self, paths, parent_span): with opentracing.start_child_span( parent_span, "RemoteFileSystem.batch_open") as batch_open_span: # We need to read the iterator paths twice, so convert to list paths = list(paths) responses = self.conn.send_request_batch( ("textDocument/xcontent", { "textDocument": { "uri": "file://" + path } }) for path in paths) for path, resp in zip(paths, responses): if "error" in resp: # Consume rest of generator to ensure resources are shutdown for _ in responses: pass raise FileException(resp["error"]) yield (path, resp["result"]["text"])
def add_spans(): """Calls the opentracing API, doesn't use any LightStep-specific code. """ with opentracing.tracer.start_span( operation_name='trivial/initial_request') as parent_span: parent_span.set_tag('url', 'localhost') sleep_dot() parent_span.log_event('All good here!', payload={ 'N': 42, 'pi': 3.14, 'abc': 'xyz' }) parent_span.set_tag('span_type', 'parent') parent_span.set_baggage_item('checked', 'baggage') sleep_dot() # This is how you would represent starting work locally. with opentracing.start_child_span( parent_span, operation_name='trivial/child_request') as child_span: child_span.set_tag('span_type', 'child') # Pretend there was an error child_span.set_tag('error', True) child_span.log_event( 'Uh Oh!', payload={'stacktrace': traceback.extract_stack()}) sleep_dot() # Play with the propagation APIs... this is not IPC and thus not # where they're intended to be used. text_carrier = {} opentracing.tracer.inject(child_span.context, opentracing.Format.TEXT_MAP, text_carrier) span_context = opentracing.tracer.extract( opentracing.Format.TEXT_MAP, text_carrier) with opentracing.tracer.start_span( 'trivial/remote_span', child_of=span_context) as remote_span: remote_span.log_event('Remote!') remote_span.set_tag('span_type', 'remote') sleep_dot()
def quick_sorter(array, span, depth=0): #The code that figues what child+depth we are in the call stack operationName = 'quickSort/execution' childName = 'quick' + str(depth) with opentracing.start_child_span( span, operation_name=operationName) as child_span: child_span.log_event('Starting quickSort call...', payload={ 'childName': childName, 'array': array }) child_span.set_tag('span_type', childName) less = [] equal = [] greater = [] if len(array) > 1: pivot = len(array[0]) for x in array: if len(x) < pivot: less.append(x) if len(x) == pivot: equal.append(x) if len(x) > pivot: greater.append(x) toReturn = quick_sorter( less, span=child_span, depth=depth + 1) + equal + quick_sorter( greater, span=child_span, depth=depth + 1) else: toReturn = array child_span.log_event('Done quickSort call', payload={ 'childName': childName, 'array': array }) time.sleep(0.05) opentracing.tracer.flush() return toReturn
service_name='Weather-client', # config opentracing to zipkin server collector_host='localhost', collector_port=9411, verbosity=1) as tracer: opentracing.tracer = tracer while True: with opentracing.tracer.start_span('Weather information') as root_span: text_carrier = {} # inject text_carrier and send to server opentracing.tracer.inject(root_span.context, opentracing.Format.TEXT_MAP, text_carrier) # create child span of root_span name client_span with opentracing.start_child_span(root_span, 'Client process') as client_span: # create child span of client_span name getLocation_span with opentracing.start_child_span( client_span, 'Get location') as getLocation_span: address = raw_input("Enter the address: ") # create child span of client_span name sendLocation_span with opentracing.start_child_span( client_span, 'Send location') as sendLocation_span: message = json.dumps(text_carrier) # send text_carrier that is injected to server s.send(message) s.send(address) weatherInfor = s.recv(1024) print "weather infor ", weatherInfor root_span.finish() s.close()
data = c.recv(2048) # receive data from client if not data: break try: text_carrier = json.loads(data) # deserialize carrier if text_carrier: span_context = opentracing.tracer.extract( opentracing.Format.TEXT_MAP, text_carrier) with opentracing.tracer.start_span( 'process at server', child_of=span_context) as parent_span: carrier = {} opentracing.tracer.inject(parent_span.context, opentracing.Format.TEXT_MAP, carrier) with opentracing.start_child_span( parent_span, 'load csv file') as load_csv_span: monan = helper.loadCSV() load_csv_span.finish() except ValueError: text_carrier = None print 'Received:', data dish_name = data if dish_name and carrier and monan: span_ctx = opentracing.tracer.extract( opentracing.Format.TEXT_MAP, carrier) with opentracing.tracer.start_span( 'process data', child_of=span_ctx) as process_span: message = process_data(dish_name.decode('utf-8'), monan) # process user input process_span.finish() parent_span.finish()
def usages(script, parent_span): with opentracing.start_child_span(parent_span, "Script.usages"): return script.usages()
def serve_hover(self, request): params = request["params"] pos = params["position"] path = path_from_uri(params["textDocument"]["uri"]) parent_span = request.get("span", None) source = self.fs.open(path, parent_span) if len(source.split("\n")[pos["line"]]) < pos["character"]: return {} script = self.new_script(path=path, source=source, line=pos["line"] + 1, column=pos["character"], parent_span=parent_span) # get the Jedi Definition instances from which to extract the hover # information. We filter out string literal Definitions # (they are useless and distracting), which have exactly one # Definition named 'str', while preserving Definitions # for variables with inferred 'str' types and references to the builtin # `str` function. defs = LangServer.goto_definitions(script, request) if (len(defs) == 1 and defs[0].full_name == 'str' and defs[0].in_builtin_module() and defs[0].type == 'instance'): if len(LangServer.goto_assignments(script, request)) == 0: # omit string literal Definitions defs = [] elif len(defs) == 0: defs = LangServer.goto_assignments(script, request) # The code from this point onwards is modified from the MIT licensed # github.com/DonJayamanne/pythonVSCode def generate_signature(completion): if completion.type in ['module' ] or not hasattr(completion, 'params'): return '' return '%s(%s)' % (completion.name, ', '.join( p.description for p in completion.params if p)) def get_definition_type(definition): definition.in_builtin_module try: if definition.type in ['statement' ] and definition.name.isupper(): return 'constant' basic_types = { 'module': 'import', 'instance': 'variable', 'statement': 'value', 'param': 'variable', } return basic_types.get(definition.type, definition.type) except Exception: return 'builtin' results = [] with opentracing.start_child_span(parent_span, "accumulate_definitions"): for definition in defs: signature = definition.name description = None if definition.type in ('class', 'function'): signature = generate_signature(definition) try: description = definition.docstring(raw=True).strip() except Exception: description = '' if not description and not hasattr(definition, 'get_line_code'): # jedi returns an empty string for compiled objects description = definition.docstring().strip() if definition.type == 'module': try: signature = definition.full_name description = definition.docstring(raw=True).strip() except Exception: description = '' if not description and hasattr(definition, 'get_line_code'): # jedi returns an empty string for compiled objects description = definition.docstring().strip() def_type = get_definition_type(definition) if def_type in ('function', 'method'): signature = 'def ' + signature elif def_type == 'class': signature = 'class ' + signature else: # TODO(keegan) vscode python uses the current word if # definition.name is empty signature = definition.name # TODO(keegan) implement the rest of # https://sourcegraph.com/github.com/DonJayamanne/pythonVSCode/-/blob/src/client/providers/hoverProvider.ts#L34 results.append({ "language": "python", "value": signature, }) if description: results.append(description) elif definition.type == "param": results.append("parameter `" + definition.name + "`") elif definition.type == "statement": results.append("variable `" + definition.name + "`") if results: return {"contents": results} else: return {}
exit() s = socket.socket() # create socket host = sys.argv[1] # create host port = 12345 s.connect((host, port)) # bind port to host # Use OpenZipkin's opentracing implementation while True: data = raw_input('Món ăn: ') # get user input if not data: break with opentracing.tracer.start_span( operation_name='Tim kiem mon an') as parent_span: with opentracing.start_child_span( parent_span, operation_name='Gui ten mon an') as child_span: text_carrier = {} opentracing.tracer.inject(parent_span.context, opentracing.Format.TEXT_MAP, text_carrier) with opentracing.start_child_span( parent_span, 'send text_carrier') as remote_span: message = json.dumps(text_carrier) s.send(message) s.send(data) print s.recv(2048) parent_span.finish() s.close()