Search is not available for this dataset
text stringlengths 75 104k |
|---|
def register_metric(self, name, metric, time_bucket_in_sec):
"""Registers a new metric to this context"""
collector = self.get_metrics_collector()
collector.register_metric(name, metric, time_bucket_in_sec) |
def get_sources(self, component_id):
"""Returns the declared inputs to specified component
:return: map <streamId namedtuple (same structure as protobuf msg) -> gtype>, or
None if not found
"""
# this is necessary because protobuf message is not hashable
StreamId = namedtuple('StreamId... |
def get_component_tasks(self, component_id):
"""Returns the task ids allocated for the given component id"""
ret = []
for task_id, comp_id in self.task_to_component_map.items():
if comp_id == component_id:
ret.append(task_id)
return ret |
def add_task_hook(self, task_hook):
"""Registers a specified task hook to this context
:type task_hook: heron.instance.src.python.utils.topology.ITaskHook
:param task_hook: Implementation of ITaskHook
"""
if not isinstance(task_hook, ITaskHook):
raise TypeError("In add_task_hook(): attempt to... |
def get_metrics_collector(self):
"""Returns this context's metrics collector"""
if self.metrics_collector is None or not isinstance(self.metrics_collector, MetricsCollector):
raise RuntimeError("Metrics collector is not registered in this context")
return self.metrics_collector |
def invoke_hook_prepare(self):
"""invoke task hooks for after the spout/bolt's initialize() method"""
for task_hook in self.task_hooks:
task_hook.prepare(self.get_cluster_config(), self) |
def invoke_hook_emit(self, values, stream_id, out_tasks):
"""invoke task hooks for every time a tuple is emitted in spout/bolt
:type values: list
:param values: values emitted
:type stream_id: str
:param stream_id: stream id into which tuple is emitted
:type out_tasks: list
:param out_tasks... |
def invoke_hook_spout_ack(self, message_id, complete_latency_ns):
"""invoke task hooks for every time spout acks a tuple
:type message_id: str
:param message_id: message id to which an acked tuple was anchored
:type complete_latency_ns: float
:param complete_latency_ns: complete latency in nano sec... |
def invoke_hook_spout_fail(self, message_id, fail_latency_ns):
"""invoke task hooks for every time spout fails a tuple
:type message_id: str
:param message_id: message id to which a failed tuple was anchored
:type fail_latency_ns: float
:param fail_latency_ns: fail latency in nano seconds
"""
... |
def invoke_hook_bolt_execute(self, heron_tuple, execute_latency_ns):
"""invoke task hooks for every time bolt processes a tuple
:type heron_tuple: HeronTuple
:param heron_tuple: tuple that is executed
:type execute_latency_ns: float
:param execute_latency_ns: execute latency in nano seconds
"""... |
def invoke_hook_bolt_ack(self, heron_tuple, process_latency_ns):
"""invoke task hooks for every time bolt acks a tuple
:type heron_tuple: HeronTuple
:param heron_tuple: tuple that is acked
:type process_latency_ns: float
:param process_latency_ns: process latency in nano seconds
"""
if len(... |
def invoke_hook_bolt_fail(self, heron_tuple, fail_latency_ns):
"""invoke task hooks for every time bolt fails a tuple
:type heron_tuple: HeronTuple
:param heron_tuple: tuple that is failed
:type fail_latency_ns: float
:param fail_latency_ns: fail latency in nano seconds
"""
if len(self.task... |
def create_parser(subparsers):
'''
Create a subparser for the submit command
:param subparsers:
:return:
'''
parser = subparsers.add_parser(
'submit',
help='Submit a topology',
usage="%(prog)s [options] cluster/[role]/[env] " + \
"topology-file-name topology-class-name [topolog... |
def launch_a_topology(cl_args, tmp_dir, topology_file, topology_defn_file, topology_name):
'''
Launch a topology given topology jar, its definition file and configurations
:param cl_args:
:param tmp_dir:
:param topology_file:
:param topology_defn_file:
:param topology_name:
:return:
'''
# get the no... |
def launch_topology_server(cl_args, topology_file, topology_defn_file, topology_name):
'''
Launch a topology given topology jar, its definition file and configurations
:param cl_args:
:param topology_file:
:param topology_defn_file:
:param topology_name:
:return:
'''
service_apiurl = cl_args['service_... |
def launch_topologies(cl_args, topology_file, tmp_dir):
'''
Launch topologies
:param cl_args:
:param topology_file:
:param tmp_dir:
:return: list(Responses)
'''
# the submitter would have written the .defn file to the tmp_dir
defn_files = glob.glob(tmp_dir + '/*.defn')
if len(defn_files) == 0:
... |
def submit_fatjar(cl_args, unknown_args, tmp_dir):
'''
We use the packer to make a package for the jar and dump it
to a well-known location. We then run the main method of class
with the specified arguments. We pass arguments as an environment variable HERON_OPTIONS.
This will run the jar file with the topol... |
def submit_tar(cl_args, unknown_args, tmp_dir):
'''
Extract and execute the java files inside the tar and then add topology
definition file created by running submitTopology
We use the packer to make a package for the tar and dump it
to a well-known location. We then run the main method of class
with the s... |
def run(command, parser, cl_args, unknown_args):
'''
Submits the topology to the scheduler
* Depending on the topology file name extension, we treat the file as a
fatjar (if the ext is .jar) or a tar file (if the ext is .tar/.tar.gz).
* We upload the topology file to the packer, update zookeeper and l... |
def get(self):
""" get method """
try:
cluster = self.get_argument_cluster()
role = self.get_argument_role()
environ = self.get_argument_environ()
topology_name = self.get_argument_topology()
container = self.get_argument(constants.PARAM_CONTAINER)
path = self.get_argument(co... |
def setup(self, context):
"""Implements TextFile Generator's setup method"""
myindex = context.get_partition_index()
self._files_to_consume = self._files[myindex::context.get_num_partitions()]
self.logger.info("TextFileSpout files to consume %s" % self._files_to_consume)
self._lines_to_consume = sel... |
def add_config(parser):
""" add config """
# the default config path
default_config_path = config.get_heron_conf_dir()
parser.add_argument(
'--config-path',
metavar='(a string; path to cluster config; default: "' + default_config_path + '")',
default=os.path.join(config.get_heron_dir(), defau... |
def add_verbose(parser):
""" add optional verbose argument"""
parser.add_argument(
'--verbose',
metavar='(a boolean; default: "false")',
type=bool,
default=False)
return parser |
def add_tracker_url(parser):
""" add optional tracker_url argument """
parser.add_argument(
'--tracker_url',
metavar='(tracker url; default: "' + DEFAULT_TRACKER_URL + '")',
type=str, default=DEFAULT_TRACKER_URL)
return parser |
def hex_escape(bin_str):
"""
Hex encode a binary string
"""
printable = string.ascii_letters + string.digits + string.punctuation + ' '
return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str) |
def make_shell_endpoint(topologyInfo, instance_id):
"""
Makes the http endpoint for the heron shell
if shell port is present, otherwise returns None.
"""
# Format: container_<id>_<instance_id>
pplan = topologyInfo["physical_plan"]
stmgrId = pplan["instances"][instance_id]["stmgrId"]
host = pplan["stmgrs... |
def make_shell_logfiles_url(host, shell_port, _, instance_id=None):
"""
Make the url for log-files in heron-shell
from the info stored in stmgr.
If no instance_id is provided, the link will
be to the dir for the whole container.
If shell port is not present, it returns None.
"""
if not shell_port:
r... |
def make_shell_logfile_data_url(host, shell_port, instance_id, offset, length):
"""
Make the url for log-file data in heron-shell
from the info stored in stmgr.
"""
return "http://%s:%d/filedata/log-files/%s.log.0?offset=%s&length=%s" % \
(host, shell_port, instance_id, offset, length) |
def cygpath(x):
"""
This will return the path of input arg for windows
:return: the path in windows
"""
command = ['cygpath', '-wp', x]
p = subprocess.Popen(command, stdout=subprocess.PIPE)
output, _ = p.communicate()
lines = output.split("\n")
return lines[0] |
def get_heron_tracker_dir():
"""
This will extract heron tracker directory from .pex file.
:return: root location for heron-tools.
"""
path = "/".join(os.path.realpath(__file__).split('/')[:-8])
return normalized_class_path(path) |
def parse_config_file(config_file):
"""
This will parse the config file for the tracker
:return: the config or None if the file is not found
"""
expanded_config_file_path = os.path.expanduser(config_file)
if not os.path.lexists(expanded_config_file_path):
return None
configs = {}
# Read the configu... |
def _handle_register_response(self, response):
"""Called when a register response (RegisterInstanceResponse) arrives"""
if response.status.status != common_pb2.StatusCode.Value("OK"):
raise RuntimeError("Stream Manager returned a not OK response for register")
Log.info("We registered ourselves to the ... |
def _handle_assignment_message(self, pplan):
"""Called when new NewInstanceAssignmentMessage arrives"""
Log.debug("In handle_assignment_message() of STStmgrClient, Physical Plan: \n%s", str(pplan))
self.heron_instance_cls.handle_assignment_msg(pplan) |
def decode_packet(packet):
"""Decodes an IncomingPacket object and returns (typename, reqid, serialized message)"""
if not packet.is_complete:
raise RuntimeError("In decode_packet(): Packet corrupted")
data = packet.data
len_typename = HeronProtocol.unpack_int(data[:4])
data = data[4:]
... |
def create_packet(reqid, message):
"""Creates Outgoing Packet from a given reqid and message
:param reqid: REQID object
:param message: protocol buffer object
"""
assert message.IsInitialized()
packet = ''
# calculate the totla size of the packet incl. header
typename = message.DESCRIP... |
def send(self, dispatcher):
"""Sends this outgoing packet to dispatcher's socket"""
if self.sent_complete:
return
sent = dispatcher.send(self.to_send)
self.to_send = self.to_send[sent:] |
def create_packet(header, data):
"""Creates an IncomingPacket object from header and data
This method is for testing purposes
"""
packet = IncomingPacket()
packet.header = header
packet.data = data
if len(header) == HeronProtocol.HEADER_SIZE:
packet.is_header_read = True
if len... |
def read(self, dispatcher):
"""Reads incoming data from asyncore.dispatcher"""
try:
if not self.is_header_read:
# try reading header
to_read = HeronProtocol.HEADER_SIZE - len(self.header)
self.header += dispatcher.recv(to_read)
if len(self.header) == HeronProtocol.HEADER_SI... |
def generate():
"""Generates a random REQID for request"""
data_bytes = bytearray(random.getrandbits(8) for i in range(REQID.REQID_SIZE))
return REQID(data_bytes) |
def create_parser(subparsers):
'''
:param subparsers:
:return:
'''
parser = subparsers.add_parser(
'restart',
help='Restart a topology',
usage="%(prog)s [options] cluster/[role]/[env] <topology-name> [container-id]",
add_help=True)
args.add_titles(parser)
args.add_cluster_role_env... |
def run(command, parser, cl_args, unknown_args):
'''
:param command:
:param parser:
:param cl_args:
:param unknown_args:
:return:
'''
Log.debug("Restart Args: %s", cl_args)
container_id = cl_args['container-id']
if cl_args['deploy_mode'] == config.SERVER_MODE:
dict_extra_args = {"container_id":... |
def get_heron_config():
'''
Get config opts from the global variable
:return:
'''
opt_list = []
for (key, value) in config_opts.items():
opt_list.append('%s=%s' % (key, value))
all_opts = (','.join(opt_list)).replace(' ', '%%%%')
return all_opts |
def yaml_config_reader(config_path):
"""Reads yaml config file and returns auto-typed config_dict"""
if not config_path.endswith(".yaml"):
raise ValueError("Config file not yaml")
with open(config_path, 'r') as f:
config = yaml.load(f)
return config |
def handle_new_tuple_set_2(self, hts2):
"""Called when new HeronTupleSet2 arrives
Convert(Assemble) HeronTupleSet2(raw byte array) to HeronTupleSet
See more at GitHub PR #1421
:param tuple_msg_set: HeronTupleSet2 type
"""
if self.my_pplan_helper is None or self.my_instance is None:
L... |
def handle_initiate_stateful_checkpoint(self, ckptmsg):
"""Called when we get InitiateStatefulCheckpoint message
:param ckptmsg: InitiateStatefulCheckpoint type
"""
self.in_stream.offer(ckptmsg)
if self.my_pplan_helper.is_topology_running():
self.my_instance.py_class.process_incoming_tuples() |
def handle_start_stateful_processing(self, start_msg):
"""Called when we receive StartInstanceStatefulProcessing message
:param start_msg: StartInstanceStatefulProcessing type
"""
Log.info("Received start stateful processing for %s" % start_msg.checkpoint_id)
self.is_stateful_started = True
self... |
def handle_restore_instance_state(self, restore_msg):
"""Called when we receive RestoreInstanceStateRequest message
:param restore_msg: RestoreInstanceStateRequest type
"""
Log.info("Restoring instance state to checkpoint %s" % restore_msg.state.checkpoint_id)
# Stop the instance
if self.is_stat... |
def send_buffered_messages(self):
"""Send messages in out_stream to the Stream Manager"""
while not self.out_stream.is_empty() and self._stmgr_client.is_registered:
tuple_set = self.out_stream.poll()
if isinstance(tuple_set, tuple_pb2.HeronTupleSet):
tuple_set.src_task_id = self.my_pplan_hel... |
def _handle_state_change_msg(self, new_helper):
"""Called when state change is commanded by stream manager"""
assert self.my_pplan_helper is not None
assert self.my_instance is not None and self.my_instance.py_class is not None
if self.my_pplan_helper.get_topology_state() != new_helper.get_topology_sta... |
def handle_assignment_msg(self, pplan):
"""Called when new NewInstanceAssignmentMessage arrives
Tells this instance to become either spout/bolt.
:param pplan: PhysicalPlan proto
"""
new_helper = PhysicalPlanHelper(pplan, self.instance.instance_id,
self.topo_pex... |
def check_output_schema(self, stream_id, tup):
"""Checks if a given stream_id and tuple matches with the output schema
:type stream_id: str
:param stream_id: stream id into which tuple is sent
:type tup: list
:param tup: tuple that is going to be sent
"""
# do some checking to make sure tha... |
def get_topology_config(self):
"""Returns the topology config"""
if self.pplan.topology.HasField("topology_config"):
return self._get_dict_from_config(self.pplan.topology.topology_config)
else:
return {} |
def set_topology_context(self, metrics_collector):
"""Sets a new topology context"""
Log.debug("Setting topology context")
cluster_config = self.get_topology_config()
cluster_config.update(self._get_dict_from_config(self.my_component.config))
task_to_component_map = self._get_task_to_comp_map()
... |
def _get_dict_from_config(topology_config):
"""Converts Config protobuf message to python dictionary
Values are converted according to the rules below:
- Number string (e.g. "12" or "1.2") is appropriately converted to ``int`` or ``float``
- Boolean string ("true", "True", "false" or "False") is conve... |
def _setup_custom_grouping(self, topology):
"""Checks whether there are any bolts that consume any of my streams using custom grouping"""
for i in range(len(topology.bolts)):
for in_stream in topology.bolts[i].inputs:
if in_stream.stream.component_name == self.my_component_name and \
in_... |
def add(self, stream_id, task_ids, grouping, source_comp_name):
"""Adds the target component
:type stream_id: str
:param stream_id: stream id into which tuples are emitted
:type task_ids: list of str
:param task_ids: list of task ids to which tuples are emitted
:type grouping: ICustomStreamGrou... |
def prepare(self, context):
"""Prepares the custom grouping for this component"""
for stream_id, targets in self.targets.items():
for target in targets:
target.prepare(context, stream_id) |
def choose_tasks(self, stream_id, values):
"""Choose tasks for a given stream_id and values and Returns a list of target tasks"""
if stream_id not in self.targets:
return []
ret = []
for target in self.targets[stream_id]:
ret.extend(target.choose_tasks(values))
return ret |
def prepare(self, context, stream_id):
"""Invoke prepare() of this custom grouping"""
self.grouping.prepare(context, self.source_comp_name, stream_id, self.task_ids) |
def choose_tasks(self, values):
"""Invoke choose_tasks() of this custom grouping"""
ret = self.grouping.choose_tasks(values)
if not isinstance(ret, list):
raise TypeError("Returned object after custom grouping's choose_tasks() "
"needs to be a list, given: %s" % str(type(ret)))
... |
def add_config(parser):
'''
:param parser:
:return:
'''
# the default config path
default_config_path = config.get_heron_conf_dir()
parser.add_argument(
'--config-path',
default=os.path.join(config.get_heron_dir(), default_config_path),
help='Path to cluster configuration files')
par... |
def add_dry_run(parser):
'''
:param parser:
:return:
'''
default_format = 'table'
resp_formats = ['raw', 'table', 'colored_table', 'json']
available_options = ', '.join(['%s' % opt for opt in resp_formats])
def dry_run_resp_format(value):
if value not in resp_formats:
raise argparse.ArgumentT... |
def read_server_mode_cluster_definition(cluster, cl_args):
'''
Read the cluster definition for server mode
:param cluster:
:param cl_args:
:param config_file:
:return:
'''
client_confs = dict()
client_confs[cluster] = cliconfig.cluster_config(cluster)
# now check if the service-url from command li... |
def check_direct_mode_cluster_definition(cluster, config_path):
'''
Check the cluster definition for direct mode
:param cluster:
:param config_path:
:return:
'''
config_path = config.get_heron_cluster_conf_dir(cluster, config_path)
if not os.path.isdir(config_path):
return False
return True |
def get(self, path):
''' get method '''
if not path:
path = "."
if not utils.check_path(path):
self.write("Only relative paths are allowed")
self.set_status(403)
self.finish()
return
t = Template(utils.get_asset("browse.html"))
args = dict(
path=path,
... |
def format_mode(sres):
"""
Format a line in the directory list based on the file's type and other attributes.
"""
mode = sres.st_mode
root = (mode & 0o700) >> 6
group = (mode & 0o070) >> 3
user = (mode & 0o7)
def stat_type(md):
''' stat type'''
if stat.S_ISDIR(md):
return 'd'
elif st... |
def format_mtime(mtime):
"""
Format the date associated with a file to be displayed in directory listing.
"""
now = datetime.now()
dt = datetime.fromtimestamp(mtime)
return '%s %2d %5s' % (
dt.strftime('%b'), dt.day,
dt.year if dt.year != now.year else dt.strftime('%H:%M')) |
def format_prefix(filename, sres):
"""
Prefix to a filename in the directory listing. This is to make the
listing similar to an output of "ls -alh".
"""
try:
pwent = pwd.getpwuid(sres.st_uid)
user = pwent.pw_name
except KeyError:
user = sres.st_uid
try:
grent = grp.getgrgid(sres.st_gid)
... |
def get_listing(path):
"""
Returns the list of files and directories in a path.
Prepents a ".." (parent directory link) if path is not current dir.
"""
if path != ".":
listing = sorted(['..'] + os.listdir(path))
else:
listing = sorted(os.listdir(path))
return listing |
def get_stat(path, filename):
''' get stat '''
return os.stat(os.path.join(path, filename)) |
def read_chunk(filename, offset=-1, length=-1, escape_data=False):
"""
Read a chunk of a file from an offset upto the length.
"""
try:
length = int(length)
offset = int(offset)
except ValueError:
return {}
if not os.path.isfile(filename):
return {}
try:
fstat = os.stat(filename)
ex... |
def pipe(prev_proc, to_cmd):
"""
Pipes output of prev_proc into to_cmd.
Returns piped process
"""
stdin = None if prev_proc is None else prev_proc.stdout
process = subprocess.Popen(to_cmd,
stdout=subprocess.PIPE,
stdin=stdin)
if prev_proc is not No... |
def str_cmd(cmd, cwd, env):
"""
Runs the command and returns its stdout and stderr.
"""
process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, cwd=cwd, env=env)
stdout_builder, stderr_builder = proc.async_stdout_stderr_builder(process)
process.wait()
s... |
def chain(cmd_list):
"""
Feed output of one command to the next and return final output
Returns string output of chained application of commands.
"""
command = ' | '.join(map(lambda x: ' '.join(x), cmd_list))
chained_proc = functools.reduce(pipe, [None] + cmd_list)
stdout_builder = proc.async_stdout_build... |
def create_parser(subparsers):
""" create parser """
metrics_parser = subparsers.add_parser(
'metrics',
help='Display info of a topology\'s metrics',
usage="%(prog)s cluster/[role]/[env] topology-name [options]",
add_help=False)
args.add_cluster_role_env(metrics_parser)
args.add_topology... |
def parse_topo_loc(cl_args):
""" parse topology location """
try:
topo_loc = cl_args['cluster/[role]/[env]'].split('/')
topo_name = cl_args['topology-name']
topo_loc.append(topo_name)
if len(topo_loc) != 4:
raise
return topo_loc
except Exception:
Log.error('Invalid topology location'... |
def to_table(metrics):
""" normalize raw metrics API result to table """
all_queries = tracker_access.metric_queries()
m = tracker_access.queries_map()
names = metrics.values()[0].keys()
stats = []
for n in names:
info = [n]
for field in all_queries:
try:
info.append(str(metrics[field]... |
def run_metrics(command, parser, cl_args, unknown_args):
""" run metrics subcommand """
cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ']
topology = cl_args['topology-name']
try:
result = tracker_access.get_topology_info(cluster, env, topology, role)
spouts = result['physical_... |
def run_bolts(command, parser, cl_args, unknown_args):
""" run bolts subcommand """
cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ']
topology = cl_args['topology-name']
try:
result = tracker_access.get_topology_info(cluster, env, topology, role)
bolts = result['physical_plan'... |
def run_containers(command, parser, cl_args, unknown_args):
""" run containers subcommand """
cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ']
topology = cl_args['topology-name']
container_id = cl_args['id']
try:
result = tracker_access.get_topology_info(cluster, env, topology,... |
def define_options(address, port, tracker_url, base_url):
'''
:param address:
:param port:
:param tracker_url:
:return:
'''
define("address", default=address)
define("port", default=port)
define("tracker_url", default=tracker_url)
define("base_url", default=base_url) |
def main():
'''
:param argv:
:return:
'''
log.configure(logging.DEBUG)
tornado.log.enable_pretty_logging()
# create the parser and parse the arguments
(parser, child_parser) = args.create_parsers()
(parsed_args, remaining) = parser.parse_known_args()
if remaining:
r = child_parser.parse_args(a... |
def spec(cls, name=None, inputs=None, par=1, config=None, optional_outputs=None):
"""Register this bolt to the topology and create ``HeronComponentSpec``
This method takes an optional ``outputs`` argument for supporting dynamic output fields
declaration. However, it is recommended that ``outputs`` should b... |
def emit(self, tup, stream=Stream.DEFAULT_STREAM_ID,
anchors=None, direct_task=None, need_task_ids=False):
"""Emits a new tuple from this Bolt
It is compatible with StreamParse API.
:type tup: list or tuple
:param tup: the new output Tuple to send from this bolt,
which shoul... |
def create_parser(subparsers):
""" create argument parser """
parser = subparsers.add_parser(
'clusters',
help='Display existing clusters',
usage="%(prog)s [options]",
add_help=True)
args.add_verbose(parser)
args.add_tracker_url(parser)
parser.set_defaults(subcommand='clusters')
retu... |
def run(command, parser, cl_args, unknown_args):
""" run command """
try:
clusters = tracker_access.get_clusters()
except:
Log.error("Fail to connect to tracker: \'%s\'", cl_args["tracker_url"])
return False
print('Available clusters:')
for cluster in clusters:
print(' %s' % cluster)
return... |
def get_time_ranges(ranges):
'''
:param ranges:
:return:
'''
# get the current time
now = int(time.time())
# form the new
time_slots = dict()
for key, value in ranges.items():
time_slots[key] = (now - value[0], now - value[1], value[2])
return (now, time_slots) |
def add_arguments(parser):
""" add arguments """
default_config_file = os.path.join(
utils.get_heron_tracker_conf_dir(), constants.DEFAULT_CONFIG_FILE)
parser.add_argument(
'--config-file',
metavar='(a string; path to config file; default: "' + default_config_file + '")',
default=default_... |
def create_parsers():
""" create argument parser """
parser = argparse.ArgumentParser(
epilog='For detailed documentation, go to http://github.com/apache/incubator-heron',
usage="%(prog)s [options] [help]",
add_help=False)
parser = add_titles(parser)
parser = add_arguments(parser)
ya_parse... |
def main():
""" main """
# create the parser and parse the arguments
(parser, _) = create_parsers()
(args, remaining) = parser.parse_known_args()
if remaining == ['help']:
parser.print_help()
parser.exit()
elif remaining == ['version']:
common_config.print_build_info()
parser.exit()
eli... |
def make_tuple(stream, tuple_key, values, roots=None):
"""Creates a HeronTuple
:param stream: protobuf message ``StreamId``
:param tuple_key: tuple id
:param values: a list of values
:param roots: a list of protobuf message ``RootId``
"""
component_name = stream.component_name
stream_id... |
def make_tick_tuple():
"""Creates a TickTuple"""
return HeronTuple(id=TupleHelper.TICK_TUPLE_ID, component=TupleHelper.TICK_SOURCE_COMPONENT,
stream=TupleHelper.TICK_TUPLE_ID, task=None, values=None,
creation_time=time.time(), roots=None) |
def make_root_tuple_info(stream_id, tuple_id):
"""Creates a RootTupleInfo"""
key = random.getrandbits(TupleHelper.MAX_SFIXED64_RAND_BITS)
return RootTupleInfo(stream_id=stream_id, tuple_id=tuple_id,
insertion_time=time.time(), key=key) |
def fetch_backpressure(self, cluster, metric, topology, component, instance, \
timerange, is_max, environ=None):
'''
:param cluster:
:param metric:
:param topology:
:param component:
:param instance:
:param timerange:
:param is_max:
:param environ:
:return:
'''
pass |
def ParseNolintSuppressions(filename, raw_line, linenum, error):
"""Updates the global list of line error-suppressions.
Parses any NOLINT comments on the current line, updating the global
error_suppressions store. Reports an error if the NOLINT comment
was malformed.
Args:
filename: str, the name of th... |
def ProcessGlobalSuppresions(lines):
"""Updates the list of global error suppressions.
Parses any lint directives in the file that have global effect.
Args:
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline... |
def IsErrorSuppressedByNolint(category, linenum):
"""Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
... |
def Match(pattern, s):
"""Matches the string with the pattern, caching the compiled regexp."""
# The regexp compilation caching is inlined in both Match and Search for
# performance reasons; factoring it out into a separate function turns out
# to be noticeably expensive.
if pattern not in _regexp_compile_cac... |
def ReplaceAll(pattern, rep, s):
"""Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if... |
def Search(pattern, s):
"""Searches the string for the pattern, caching the compiled regexp."""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].search(s) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.