INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns the representation of logical plan that will be returned from Tracker.
def extract_logical_plan(self, topology): """ Returns the representation of logical plan that will be returned from Tracker. """ logicalPlan = { "spouts": {}, "bolts": {}, } # Add spouts. for spout in topology.spouts(): spoutName = spout.comp.name spoutType =...
Returns the representation of physical plan that will be returned from Tracker.
def extract_physical_plan(self, topology): """ Returns the representation of physical plan that will be returned from Tracker. """ physicalPlan = { "instances": {}, "instance_groups": {}, "stmgrs": {}, "spouts": {}, "bolts": {}, "config": {}, "...
Returns the representation of packing plan that will be returned from Tracker.
def extract_packing_plan(self, topology): """ Returns the representation of packing plan that will be returned from Tracker. """ packingPlan = { "id": "", "container_plans": [] } if not topology.packing_plan: return packingPlan container_plans = topology.packing_p...
Extracts info from the stored proto states and convert it into representation that is exposed using the API. This method is called on any change for the topology. For example when a container moves and its host or some port changes. All the information is parsed all over again and cache is updated.
def setTopologyInfo(self, topology): """ Extracts info from the stored proto states and convert it into representation that is exposed using the API. This method is called on any change for the topology. For example, when a container moves and its host or some port changes. All the informati...
Returns the JSON representation of a topology by its name cluster environ and an optional role parameter. Raises exception if no such topology is found.
def getTopologyInfo(self, topologyName, cluster, role, environ): """ Returns the JSON representation of a topology by its name, cluster, environ, and an optional role parameter. Raises exception if no such topology is found. """ # Iterate over the values to filter the desired topology. for (...
load config files
def load_configs(self): """load config files""" self.statemgr_config.set_state_locations(self.configs[STATEMGRS_KEY]) if EXTRA_LINKS_KEY in self.configs: for extra_link in self.configs[EXTRA_LINKS_KEY]: self.extra_links.append(self.validate_extra_link(extra_link))
validate extra link
def validate_extra_link(self, extra_link): """validate extra link""" if EXTRA_LINK_NAME_KEY not in extra_link or EXTRA_LINK_FORMATTER_KEY not in extra_link: raise Exception("Invalid extra.links format. " + "Extra link must include a 'name' and 'formatter' field") self.validated_...
validate visualization url format
def validated_formatter(self, url_format): """validate visualization url format""" # We try to create a string by substituting all known # parameters. If an unknown parameter is present, an error # will be thrown valid_parameters = { "${CLUSTER}": "cluster", "${ENVIRON}": "environ", ...
Emits a new tuple from this Spout
def emit(self, tup, tup_id=None, stream=Stream.DEFAULT_STREAM_ID, direct_task=None, need_task_ids=False): """Emits a new tuple from this Spout It is compatible with StreamParse API. :type tup: list or tuple :param tup: the new output Tuple to send from this spout, should con...
Checks whether we still need to do more work
def _is_continue_to_work(self): """Checks whether we still need to do more work When the topology state is RUNNING: 1. if the out_queue is not full and ack is not enabled, we could wake up next time to produce more tuples and push to the out_queue 2. if the out_queue is not full but the acking i...
create parser
def create_parser(subparsers): """ create parser """ components_parser = subparsers.add_parser( 'components', help='Display information of a topology\'s components', usage="%(prog)s cluster/[role]/[env] topology-name [options]", add_help=False) args.add_cluster_role_env(components_parser) ...
normalize raw logical plan info to table
def to_table(components, topo_info): """ normalize raw logical plan info to table """ inputs, outputs = defaultdict(list), defaultdict(list) for ctype, component in components.items(): if ctype == 'bolts': for component_name, component_info in component.items(): for input_stream in component_inf...
filter to keep bolts
def filter_bolts(table, header): """ filter to keep bolts """ bolts_info = [] for row in table: if row[0] == 'bolt': bolts_info.append(row) return bolts_info, header
filter to keep spouts
def filter_spouts(table, header): """ filter to keep spouts """ spouts_info = [] for row in table: if row[0] == 'spout': spouts_info.append(row) return spouts_info, header
run command
def run(cl_args, compo_type): """ run command """ cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ'] topology = cl_args['topology-name'] spouts_only, bolts_only = cl_args['spout'], cl_args['bolt'] try: components = tracker_access.get_logical_plan(cluster, env, topology, role) ...
state Zookeeper
def start(self): """ state Zookeeper """ if self.is_host_port_reachable(): self.client = self._kazoo_client(_makehostportlist(self.hostportlist)) else: localhostports = self.establish_ssh_tunnel() self.client = self._kazoo_client(_makehostportlist(localhostports)) self.client.start() ...
get topologies
def get_topologies(self, callback=None): """ get topologies """ isWatching = False # Temp dict used to return result # if callback is not provided. ret = { "result": None } if callback: isWatching = True else: def callback(data): """Custom callback to get the...
Helper function to get topologies with a callback. The future watch is placed only if isWatching is True.
def _get_topologies_with_watch(self, callback, isWatching): """ Helper function to get topologies with a callback. The future watch is placed only if isWatching is True. """ path = self.get_topologies_path() if isWatching: LOG.info("Adding children watch for path: " + path) # pyli...
get topologies
def get_topology(self, topologyName, callback=None): """ get topologies """ isWatching = False # Temp dict used to return result # if callback is not provided. ret = { "result": None } if callback: isWatching = True else: def callback(data): """Custom callbac...
Helper function to get pplan with a callback. The future watch is placed only if isWatching is True.
def _get_topology_with_watch(self, topologyName, callback, isWatching): """ Helper function to get pplan with a callback. The future watch is placed only if isWatching is True. """ path = self.get_topology_path(topologyName) if isWatching: LOG.info("Adding data watch for path: " + path...
crate topology
def create_topology(self, topologyName, topology): """ crate topology """ if not topology or not topology.IsInitialized(): raise_(StateException("Topology protobuf not init properly", StateException.EX_TYPE_PROTOBUF_ERROR), sys.exc_info()[2]) path = self.get_topology_path(...
delete topology
def delete_topology(self, topologyName): """ delete topology """ path = self.get_topology_path(topologyName) LOG.info("Removing topology: {0} from path: {1}".format( topologyName, path)) try: self.client.delete(path) return True except NoNodeError: raise_(StateException("No...
get packing plan
def get_packing_plan(self, topologyName, callback=None): """ get packing plan """ isWatching = False # Temp dict used to return result # if callback is not provided. ret = { "result": None } if callback: isWatching = True else: def callback(data): """ Custom ...
Helper function to get packing_plan with a callback. The future watch is placed only if isWatching is True.
def _get_packing_plan_with_watch(self, topologyName, callback, isWatching): """ Helper function to get packing_plan with a callback. The future watch is placed only if isWatching is True. """ path = self.get_packing_plan_path(topologyName) if isWatching: LOG.info("Adding data watch for...
get physical plan
def get_pplan(self, topologyName, callback=None): """ get physical plan """ isWatching = False # Temp dict used to return result # if callback is not provided. ret = { "result": None } if callback: isWatching = True else: def callback(data): """ Custo...
Helper function to get pplan with a callback. The future watch is placed only if isWatching is True.
def _get_pplan_with_watch(self, topologyName, callback, isWatching): """ Helper function to get pplan with a callback. The future watch is placed only if isWatching is True. """ path = self.get_pplan_path(topologyName) if isWatching: LOG.info("Adding data watch for path: " + path) ...
create physical plan
def create_pplan(self, topologyName, pplan): """ create physical plan """ if not pplan or not pplan.IsInitialized(): raise_(StateException("Physical Plan protobuf not init properly", StateException.EX_TYPE_PROTOBUF_ERROR), sys.exc_info()[2]) path = self.get_pplan_path(topo...
get execution state
def get_execution_state(self, topologyName, callback=None): """ get execution state """ isWatching = False # Temp dict used to return result # if callback is not provided. ret = { "result": None } if callback: isWatching = True else: def callback(data): """ ...
Helper function to get execution state with a callback. The future watch is placed only if isWatching is True.
def _get_execution_state_with_watch(self, topologyName, callback, isWatching): """ Helper function to get execution state with a callback. The future watch is placed only if isWatching is True. """ path = self.get_execution_state_path(topologyName) if isWatching: LOG.info("Adding data ...
create execution state
def create_execution_state(self, topologyName, executionState): """ create execution state """ if not executionState or not executionState.IsInitialized(): raise_(StateException("Execution State protobuf not init properly", StateException.EX_TYPE_PROTOBUF_ERROR), sys.exc_info()...
get tmaster
def get_tmaster(self, topologyName, callback=None): """ get tmaster """ isWatching = False # Temp dict used to return result # if callback is not provided. ret = { "result": None } if callback: isWatching = True else: def callback(data): """ Custom ca...
Helper function to get pplan with a callback. The future watch is placed only if isWatching is True.
def _get_tmaster_with_watch(self, topologyName, callback, isWatching): """ Helper function to get pplan with a callback. The future watch is placed only if isWatching is True. """ path = self.get_tmaster_path(topologyName) if isWatching: LOG.info("Adding data watch for path: " + path) ...
get scheduler location
def get_scheduler_location(self, topologyName, callback=None): """ get scheduler location """ isWatching = False # Temp dict used to return result # if callback is not provided. ret = { "result": None } if callback: isWatching = True else: def callback(data): ...
Helper function to get scheduler location with a callback. The future watch is placed only if isWatching is True.
def _get_scheduler_location_with_watch(self, topologyName, callback, isWatching): """ Helper function to get scheduler location with a callback. The future watch is placed only if isWatching is True. """ path = self.get_scheduler_location_path(topologyName) if isWatching: LOG.info("Add...
Deserializes Java primitive data and objects serialized by ObjectOutputStream from a file - like object.
def load(file_object): """ Deserializes Java primitive data and objects serialized by ObjectOutputStream from a file-like object. """ marshaller = JavaObjectUnmarshaller(file_object) marshaller.add_transformer(DefaultObjectTransformer()) return marshaller.readObject()
Deserializes Java objects and primitive data serialized by ObjectOutputStream from a string.
def loads(string): """ Deserializes Java objects and primitive data serialized by ObjectOutputStream from a string. """ f = StringIO.StringIO(string) marshaller = JavaObjectUnmarshaller(f) marshaller.add_transformer(DefaultObjectTransformer()) return marshaller.readObject()
copy an object
def copy(self, new_object): """copy an object""" new_object.classdesc = self.classdesc for name in self.classdesc.fields_names: new_object.__setattr__(name, getattr(self, name))
read object
def readObject(self): """read object""" try: _, res = self._read_and_exec_opcode(ident=0) position_bak = self.object_stream.tell() the_rest = self.object_stream.read() if len(the_rest): log_error("Warning!!!!: Stream still has %s bytes left.\ Enable debug mode of logging to see ...
do_classdesc
def do_classdesc(self, parent=None, ident=0): """do_classdesc""" # TC_CLASSDESC className serialVersionUID newHandle classDescInfo # classDescInfo: # classDescFlags fields classAnnotation superClassDesc # classDescFlags: # (byte) // Defined in Terminal Symbols and Constants ...
Get the specified metrics for the given component name of this topology. Returns the following dict on success: { timeline: { <metricname >: { <instance >: { <start_time >: <numeric value > <start_time >: <numeric value >... }... }... } starttime: <numeric value > endtime: <numeric value > component:... }
def getMetricsTimeline(tmaster, component_name, metric_names, instances, start_time, end_time, callback=None): """ Get the specified metrics for the given component name of this ...
: param subparsers:: return:
def create_parser(subparsers): ''' :param subparsers: :return: ''' parser = subparsers.add_parser( 'version', help='Print version of heron-cli', usage="%(prog)s [options] [cluster]", add_help=True) add_version_titles(parser) parser.add_argument( 'cluster', nargs='?', ...
: param command:: param parser:: param args:: param unknown_args:: return:
def run(command, parser, cl_args, unknown_args): ''' :param command: :param parser: :param args: :param unknown_args: :return: ''' cluster = cl_args['cluster'] # server mode if cluster: config_file = config.heron_rc_file() client_confs = dict() # Read the cluster definition, if not fou...
Names of all state locations must be unique.
def validate_state_locations(self): """ Names of all state locations must be unique. """ names = map(lambda loc: loc["name"], self.locations) assert len(names) == len(set(names)), "Names of state locations must be unique"
: param parser:: return:
def add_arguments(parser): ''' :param parser: :return: ''' parser.add_argument( '--tracker_url', metavar='(a url; path to tracker; default: "' + consts.DEFAULT_TRACKER_URL + '")', default=consts.DEFAULT_TRACKER_URL) parser.add_argument( '--address', metavar='(an string; addres...
: return:
def get(self): ''' :return: ''' cluster = self.get_argument("cluster") environ = self.get_argument("environ") topology = self.get_argument("topology") component = self.get_argument("component", default=None) metricnames = self.get_arguments("metricname") instances = self.get_argument...
: return:
def get(self): ''' :return: ''' cluster = self.get_argument("cluster") environ = self.get_argument("environ") topology = self.get_argument("topology") component = self.get_argument("component", default=None) metric = self.get_argument("metric") instances = self.get_argument("instance...
get method
def get(self, instance_id): ''' get method ''' self.content_type = 'application/json' self.write(json.dumps(utils.chain([ ['ps', 'auxwwww'], ['grep', instance_id], ['grep', 'java'], ['awk', '\'{print $2}\'']])).strip()) self.finish()
get method
def get(self, path): """ get method """ if path is None: return {} if not utils.check_path(path): self.write("Only relative paths are allowed") self.set_status(403) self.finish() return offset = self.get_argument("offset", default=-1) length = self.get_argument("lengt...
Implements Pulsar Spout s initialize method
def initialize(self, config, context): """Implements Pulsar Spout's initialize method""" self.logger.info("Initializing PulsarSpout with the following") self.logger.info("Component-specific config: \n%s" % str(config)) self.logger.info("Context: \n%s" % str(context)) self.emit_count = 0 self.ac...
get method
def get(self): """ get method """ # Get all the values for parameter "cluster". clusters = self.get_arguments(constants.PARAM_CLUSTER) # Get all the values for parameter "environ". environs = self.get_arguments(constants.PARAM_ENVIRON) role = self.get_argument_role() ret = {} topologi...
Fetches Instance jstack from heron - shell.
def getInstanceJstack(self, topology_info, instance_id): """ Fetches Instance jstack from heron-shell. """ pid_response = yield getInstancePid(topology_info, instance_id) try: http_client = tornado.httpclient.AsyncHTTPClient() pid_json = json.loads(pid_response) pid = pid_json['std...
Create the parse for the update command
def create_parser(subparsers): """ Create the parse for the update command """ parser = subparsers.add_parser( 'update', help='Update a topology', usage="%(prog)s [options] cluster/[role]/[env] <topology-name> " + "[--component-parallelism <name:value>] " + "[--container-number value] ...
Build extra args map
def build_extra_args_dict(cl_args): """ Build extra args map """ # Check parameters component_parallelism = cl_args['component_parallelism'] runtime_configs = cl_args['runtime_config'] container_number = cl_args['container_number'] # Users need to provide either (component-parallelism || container_number) o...
flatten extra args
def convert_args_dict_to_list(dict_extra_args): """ flatten extra args """ list_extra_args = [] if 'component_parallelism' in dict_extra_args: list_extra_args += ["--component_parallelism", ','.join(dict_extra_args['component_parallelism'])] if 'runtime_config' in dict_extra_args: ...
run the update command
def run(command, parser, cl_args, unknown_args): """ run the update command """ Log.debug("Update Args: %s", cl_args) # Build jar list extra_lib_jars = jars.packing_jars() action = "update topology%s" % (' in dry-run mode' if cl_args["dry_run"] else '') # Build extra args dict_extra_args = {} try: ...
This method is used by other modules and so it is not a part of the class. Fetches Instance pid from heron - shell.
def getInstancePid(topology_info, instance_id): """ This method is used by other modules, and so it is not a part of the class. Fetches Instance pid from heron-shell. """ try: http_client = tornado.httpclient.AsyncHTTPClient() endpoint = utils.make_shell_endpoint(topology_info, instance_id) url ...
get method
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() instance = self.get_argument_instance() topology_info = self.tracker.getTopologyInfo...
Checks if a given gtype is sane
def is_grouping_sane(cls, gtype): """Checks if a given gtype is sane""" if gtype == cls.SHUFFLE or gtype == cls.ALL or gtype == cls.LOWEST or gtype == cls.NONE: return True elif isinstance(gtype, cls.FIELDS): return gtype.gtype == topology_pb2.Grouping.Value("FIELDS") and \ gtype.fi...
Field grouping
def fields(cls, *fields): """Field grouping""" if len(fields) == 1 and isinstance(fields[0], list): fields = fields[0] else: fields = list(fields) for i in fields: if not isinstance(i, str): raise TypeError("Non-string cannot be specified in fields") if not fields: ...
Custom grouping from a given implementation of ICustomGrouping
def custom(cls, customgrouper): """Custom grouping from a given implementation of ICustomGrouping :param customgrouper: The ICustomGrouping implemention to use """ if customgrouper is None: raise TypeError("Argument to custom() must be ICustomGrouping instance or classpath") if not isinstance...
Custom grouping from a given serialized string
def custom_serialized(cls, serialized, is_java=True): """Custom grouping from a given serialized string This class is created for compatibility with ``custom_serialized(cls, java_serialized)`` method of StreamParse API, although its functionality is not yet implemented (Java-serialized). Currently only...
Registers its metrics to a given metrics collector with a given interval
def register_metrics(self, metrics_collector, interval): """Registers its metrics to a given metrics collector with a given interval""" for field, metrics in self.metrics.items(): metrics_collector.register_metric(field, metrics, interval)
Update the value of CountMetric or MultiCountMetric
def update_count(self, name, incr_by=1, key=None): """Update the value of CountMetric or MultiCountMetric :type name: str :param name: name of the registered metric to be updated. :type incr_by: int :param incr_by: specifies how much to increment. Default is 1. :type key: str or None :param...
Update the value of ReducedMetric or MultiReducedMetric
def update_reduced_metric(self, name, value, key=None): """Update the value of ReducedMetric or MultiReducedMetric :type name: str :param name: name of the registered metric to be updated. :param value: specifies a value to be reduced. :type key: str or None :param key: specifies a key for Mult...
Update received packet metrics
def update_received_packet(self, received_pkt_size_bytes): """Update received packet metrics""" self.update_count(self.RECEIVED_PKT_COUNT) self.update_count(self.RECEIVED_PKT_SIZE, incr_by=received_pkt_size_bytes)
Update sent packet metrics
def update_sent_packet(self, sent_pkt_size_bytes): """Update sent packet metrics""" self.update_count(self.SENT_PKT_COUNT) self.update_count(self.SENT_PKT_SIZE, incr_by=sent_pkt_size_bytes)
Registers metrics to context
def register_metrics(self, context): """Registers metrics to context :param context: Topology Context """ sys_config = system_config.get_sys_config() interval = float(sys_config[constants.HERON_METRICS_EXPORT_INTERVAL_SEC]) collector = context.get_metrics_collector() super(ComponentMetrics,...
Apply update to serialization metrics
def serialize_data_tuple(self, stream_id, latency_in_ns): """Apply update to serialization metrics""" self.update_count(self.TUPLE_SERIALIZATION_TIME_NS, incr_by=latency_in_ns, key=stream_id)
Initializes the default values for a necessary set of MultiCountMetrics
def _init_multi_count_metrics(self, pplan_helper): """Initializes the default values for a necessary set of MultiCountMetrics""" to_init = [self.metrics[i] for i in self.to_multi_init if i in self.metrics and isinstance(self.metrics[i], MultiCountMetric)] for out_stream in pplan_helper.get_my...
Apply updates to the next tuple metrics
def next_tuple(self, latency_in_ns): """Apply updates to the next tuple metrics""" self.update_reduced_metric(self.NEXT_TUPLE_LATENCY, latency_in_ns) self.update_count(self.NEXT_TUPLE_COUNT)
Apply updates to the ack metrics
def acked_tuple(self, stream_id, complete_latency_ns): """Apply updates to the ack metrics""" self.update_count(self.ACK_COUNT, key=stream_id) self.update_reduced_metric(self.COMPLETE_LATENCY, complete_latency_ns, key=stream_id)
Apply updates to the fail metrics
def failed_tuple(self, stream_id, fail_latency_ns): """Apply updates to the fail metrics""" self.update_count(self.FAIL_COUNT, key=stream_id) self.update_reduced_metric(self.FAIL_LATENCY, fail_latency_ns, key=stream_id)
Initializes the default values for a necessary set of MultiCountMetrics
def _init_multi_count_metrics(self, pplan_helper): """Initializes the default values for a necessary set of MultiCountMetrics""" # inputs to_in_init = [self.metrics[i] for i in self.inputs_init if i in self.metrics and isinstance(self.metrics[i], MultiCountMetric)] for in_stream in ppl...
Apply updates to the execute metrics
def execute_tuple(self, stream_id, source_component, latency_in_ns): """Apply updates to the execute metrics""" self.update_count(self.EXEC_COUNT, key=stream_id) self.update_reduced_metric(self.EXEC_LATENCY, latency_in_ns, stream_id) self.update_count(self.EXEC_TIME_NS, incr_by=latency_in_ns, key=stream...
Apply updates to the deserialization metrics
def deserialize_data_tuple(self, stream_id, source_component, latency_in_ns): """Apply updates to the deserialization metrics""" self.update_count(self.TUPLE_DESERIALIZATION_TIME_NS, incr_by=latency_in_ns, key=stream_id) global_stream_id = source_component + "/" + stream_id self.update_count(self.TUPLE_...
Apply updates to the ack metrics
def acked_tuple(self, stream_id, source_component, latency_in_ns): """Apply updates to the ack metrics""" self.update_count(self.ACK_COUNT, key=stream_id) self.update_reduced_metric(self.PROCESS_LATENCY, latency_in_ns, stream_id) global_stream_id = source_component + '/' + stream_id self.update_coun...
Apply updates to the fail metrics
def failed_tuple(self, stream_id, source_component, latency_in_ns): """Apply updates to the fail metrics""" self.update_count(self.FAIL_COUNT, key=stream_id) self.update_reduced_metric(self.FAIL_LATENCY, latency_in_ns, stream_id) global_stream_id = source_component + '/' + stream_id self.update_coun...
Registers a given metric
def register_metric(self, name, metric, time_bucket_in_sec): """Registers a given metric :param name: name of the metric :param metric: IMetric object to be registered :param time_bucket_in_sec: time interval for update to the metrics manager """ if name in self.metrics_map: raise Runtime...
Poll from the buffer
def poll(self): """Poll from the buffer It is a non-blocking operation, and when the buffer is empty, it raises Queue.Empty exception """ try: # non-blocking ret = self._buffer.get(block=False) if self._producer_callback is not None: self._producer_callback() return ret ...
Offer to the buffer
def offer(self, item): """Offer to the buffer It is a non-blocking operation, and when the buffer is full, it raises Queue.Full exception """ try: # non-blocking self._buffer.put(item, block=False) if self._consumer_callback is not None: self._consumer_callback() return ...
Parse version to major minor patch pre - release build parts.
def parse(version): """ Parse version to major, minor, patch, pre-release, build parts. """ match = _REGEX.match(version) if match is None: raise ValueError('%s is not valid SemVer string' % version) verinfo = match.groupdict() verinfo['major'] = int(verinfo['major']) verinfo['...
: param subparsers:: param action:: param help_arg:: return:
def create_parser(subparsers, action, help_arg): ''' :param subparsers: :param action: :param help_arg: :return: ''' parser = subparsers.add_parser( action, help=help_arg, usage="%(prog)s [options] cluster/[role]/[env] <topology-name>", add_help=True) args.add_titles(parser) a...
helper function to take action on topologies using REST API: param command:: param cl_args:: param action: description of action taken: return:
def run_server(command, cl_args, action, extra_args=dict()): ''' helper function to take action on topologies using REST API :param command: :param cl_args: :param action: description of action taken :return: ''' topology_name = cl_args['topology-name'] service_endpoint = cl_args['service_url'...
helper function to take action on topologies: param command:: param cl_args:: param action: description of action taken: return:
def run_direct(command, cl_args, action, extra_args=[], extra_lib_jars=[]): ''' helper function to take action on topologies :param command: :param cl_args: :param action: description of action taken :return: ''' topology_name = cl_args['topology-name'] new_args = [ "--cluster", cl_args[...
Creates all the zookeeper state_managers and returns them in a list
def get_all_zk_state_managers(conf): """ Creates all the zookeeper state_managers and returns them in a list """ state_managers = [] state_locations = conf.get_state_locations_of_type("zookeeper") for location in state_locations: name = location['name'] hostport = location['hostport'] hostport...
Returns all the file state_managers.
def get_all_file_state_managers(conf): """ Returns all the file state_managers. """ state_managers = [] state_locations = conf.get_state_locations_of_type("file") for location in state_locations: name = location['name'] rootpath = os.path.expanduser(location['rootpath']) LOG.info("Connecting to ...
Increments the value of a given key by to_add
def incr(self, key, to_add=1): """Increments the value of a given key by ``to_add``""" if key not in self.value: self.value[key] = CountMetric() self.value[key].incr(to_add)
Updates a value of a given key and apply reduction
def update(self, key, value): """Updates a value of a given key and apply reduction""" if key not in self.value: self.value[key] = ReducedMetric(self.reducer) self.value[key].update(value)
Adds a new key to this metric
def add_key(self, key): """Adds a new key to this metric""" if key not in self.value: self.value[key] = ReducedMetric(self.reducer)
Add a new data tuple to the currently buffered set of tuples
def add_data_tuple(self, stream_id, new_data_tuple, tuple_size_in_bytes): """Add a new data tuple to the currently buffered set of tuples""" if (self.current_data_tuple_set is None) or \ (self.current_data_tuple_set.stream.id != stream_id) or \ (len(self.current_data_tuple_set.tuples) >= self.da...
Add a new control ( Ack/ Fail ) tuple to the currently buffered set of tuples
def add_control_tuple(self, new_control_tuple, tuple_size_in_bytes, is_ack): """Add a new control (Ack/Fail) tuple to the currently buffered set of tuples :param is_ack: ``True`` if Ack, ``False`` if Fail """ if self.current_control_tuple_set is None: self._init_new_control_tuple() elif is_ac...
Add the checkpoint state message to be sent back the stmgr
def add_ckpt_state(self, ckpt_id, ckpt_state): """Add the checkpoint state message to be sent back the stmgr :param ckpt_id: The id of the checkpoint :ckpt_state: The checkpoint state """ # first flush any buffered tuples self._flush_remaining() msg = ckptmgr_pb2.StoreInstanceStateCheckpoin...
: param subparsers:: return:
def create_parser(subparsers): ''' :param subparsers: :return: ''' parser = subparsers.add_parser( 'config', help='Config properties for a cluster', usage="%(prog)s [cluster]", add_help=True) parser.add_argument( 'cluster', help='Cluster to configure' ) ex_subparser...
: param command:: param parser:: param args:: param unknown_args:: return:
def run(command, parser, cl_args, unknown_args): ''' :param command: :param parser: :param args: :param unknown_args: :return: ''' configcommand = cl_args.get('configcommand', None) if configcommand == 'set': return _set(cl_args) elif configcommand == 'unset': return _unset(cl_args) else: ...
Check if an entry in the class path exists as either a directory or a file
def valid_path(path): ''' Check if an entry in the class path exists as either a directory or a file ''' # check if the suffic of classpath suffix exists as directory if path.endswith('*'): Log.debug('Checking classpath entry suffix as directory: %s', path[:-1]) if os.path.isdir(path[:-1]): retu...
Given a java classpath check whether the path entries are valid or not
def valid_java_classpath(classpath): ''' Given a java classpath, check whether the path entries are valid or not ''' paths = classpath.split(':') for path_entry in paths: if not valid_path(path_entry.strip()): return False return True
: param U:: param V:: return:
def add_edge(self, U, V): ''' :param U: :param V: :return: ''' if not U in self.edges: self.edges[U] = set() if not V in self.edges: self.edges[V] = set() if not V in self.edges[U]: self.edges[U].add(V)
Returns the maximum distance between any vertex and U in the connected component containing U: param U:: return:
def bfs_depth(self, U): ''' Returns the maximum distance between any vertex and U in the connected component containing U :param U: :return: ''' bfs_queue = [[U, 0]] # Stores the vertices whose BFS hadn't been completed. visited = set() max_depth = 0 while bfs_queue: [V, d...
Returns the maximum distance between any vertex and U in the connected component containing U: return:
def diameter(self): ''' Returns the maximum distance between any vertex and U in the connected component containing U :return: ''' diameter = 0 for U in self.edges: depth = self.bfs_depth(U) if depth > diameter: diameter = depth return diameter
Get a list of paths to included dependencies in the specified pex file
def _get_deps_list(abs_path_to_pex): """Get a list of paths to included dependencies in the specified pex file Note that dependencies are located under `.deps` directory """ pex = zipfile.ZipFile(abs_path_to_pex, mode='r') deps = list(set([re.match(egg_regex, i).group(1) for i in pex.namelist() ...