Search is not available for this dataset
text stringlengths 75 104k |
|---|
def load_pex(path_to_pex, include_deps=True):
"""Loads pex file and its dependencies to the current python path"""
abs_path_to_pex = os.path.abspath(path_to_pex)
Log.debug("Add a pex to the path: %s" % abs_path_to_pex)
if abs_path_to_pex not in sys.path:
sys.path.insert(0, os.path.dirname(abs_path_to_pex))
... |
def resolve_heron_suffix_issue(abs_pex_path, class_path):
"""Resolves duplicate package suffix problems
When dynamically loading a pex file and a corresponding python class (bolt/spout/topology),
if the top level package in which to-be-loaded classes reside is named 'heron', the path conflicts
with this Heron ... |
def import_and_get_class(path_to_pex, python_class_name):
"""Imports and load a class from a given pex file path and python class name
For example, if you want to get a class called `Sample` in
/some-path/sample.pex/heron/examples/src/python/sample.py,
``path_to_pex`` needs to be ``/some-path/sample.pex``, and... |
def new_source(self, source):
"""Adds a new source to the computation DAG"""
source_streamlet = None
if callable(source):
source_streamlet = SupplierStreamlet(source)
elif isinstance(source, Generator):
source_streamlet = GeneratorStreamlet(source)
else:
raise RuntimeError("Builde... |
def build(self, bldr):
"""Builds the topology and returns the builder"""
stage_names = sets.Set()
for source in self._sources:
source._build(bldr, stage_names)
for source in self._sources:
if not source._all_built():
raise RuntimeError("Topology cannot be fully built! Are all sources... |
def get(self, path):
""" get method """
t = Template(utils.get_asset("file.html"))
if path is None:
self.set_status(404)
self.write("No such file")
self.finish()
return
if not utils.check_path(path):
self.write("Only relative paths are allowed")
self.set_status(403)
... |
def load_state_manager_locations(cluster, state_manager_config_file='heron-conf/statemgr.yaml',
overrides={}):
""" Reads configs to determine which state manager to use and converts them to state manager
locations. Handles a subset of config wildcard substitution supported in the su... |
def __replace(config, wildcards, config_file):
"""For each kvp in config, do wildcard substitution on the values"""
for config_key in config:
config_value = config[config_key]
original_value = config_value
if isinstance(config_value, str):
for token in wildcards:
if wildcards[token]:
... |
def get_command_handlers():
'''
Create a map of command names and handlers
'''
return {
'activate': activate,
'config': hconfig,
'deactivate': deactivate,
'help': cli_help,
'kill': kill,
'restart': restart,
'submit': submit,
'update': update,
'version': vers... |
def create_parser(command_handlers):
'''
Main parser
:return:
'''
parser = argparse.ArgumentParser(
prog='heron',
epilog=HELP_EPILOG,
formatter_class=config.SubcommandHelpFormatter,
add_help=True)
subparsers = parser.add_subparsers(
title="Available commands",
metavar='<... |
def run(handlers, command, parser, command_args, unknown_args):
'''
Run the command
:param command:
:param parser:
:param command_args:
:param unknown_args:
:return:
'''
if command in handlers:
return handlers[command].run(command, parser, command_args, unknown_args)
else:
err_context = 'Un... |
def cleanup(files):
'''
:param files:
:return:
'''
for cur_file in files:
if os.path.isdir(cur_file):
shutil.rmtree(cur_file)
else:
shutil.rmtree(os.path.dirname(cur_file)) |
def server_deployment_mode(command, parser, cluster, cl_args):
'''
check the server deployment mode for the given cluster
if it is valid return the valid set of args
:param cluster:
:param cl_args:
:return:
'''
# Read the cluster definition, if not found
client_confs = cdefs.read_server_mode_cluster_d... |
def direct_deployment_mode(command, parser, cluster, cl_args):
'''
check the direct deployment mode for the given cluster
if it is valid return the valid set of args
:param command:
:param parser:
:param cluster:
:param cl_args:
:return:
'''
cluster = cl_args['cluster']
try:
config_path = cl_... |
def extract_common_args(command, parser, cl_args):
'''
Extract all the common args for all commands
:param command:
:param parser:
:param cl_args:
:return:
'''
try:
cluster_role_env = cl_args.pop('cluster/[role]/[env]')
except KeyError:
try:
cluster_role_env = cl_args.pop('cluster') # f... |
def execute(handlers, local_commands):
'''
Run the command
:return:
'''
# verify if the environment variables are correctly set
check_environment()
# create the argument parser
parser = create_parser(handlers)
# if no argument is provided, print help and exit
if len(sys.argv[1:]) == 0:
parser.... |
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()
component = self.get_argument_component()
metric_names = self.get_required_arguments... |
def getComponentMetrics(self,
tmaster,
componentName,
metricNames,
instances,
interval,
callback=None):
"""
Get the specified metrics for the given componen... |
def floorTimestamps(self, start, end, timeline):
""" floor timestamp """
ret = {}
for timestamp, value in timeline.items():
ts = timestamp / 60 * 60
if start <= ts <= end:
ret[ts] = value
return ret |
def setDefault(self, constant, start, end):
""" set default time """
starttime = start / 60 * 60
if starttime < start:
starttime += 60
endtime = end / 60 * 60
while starttime <= endtime:
# STREAMCOMP-1559
# Second check is a work around, because the response from tmaster
# co... |
def initialize(self, config, context):
"""We initialize the window duration and slide interval
"""
if SlidingWindowBolt.WINDOW_DURATION_SECS in config:
self.window_duration = int(config[SlidingWindowBolt.WINDOW_DURATION_SECS])
else:
self.logger.fatal("Window Duration has to be specified in t... |
def process(self, tup):
"""Process a single tuple of input
We add the (time, tuple) pair into our current_tuples. And then look for expiring
elemnents
"""
curtime = int(time.time())
self.current_tuples.append((tup, curtime))
self._expire(curtime) |
def process_tick(self, tup):
"""Called every slide_interval
"""
curtime = int(time.time())
window_info = WindowContext(curtime - self.window_duration, curtime)
tuple_batch = []
for (tup, tm) in self.current_tuples:
tuple_batch.append(tup)
self.processWindow(window_info, tuple_batch)
... |
def initialize(self, config, context):
"""We initialize the window duration and slide interval
"""
if TumblingWindowBolt.WINDOW_DURATION_SECS in config:
self.window_duration = int(config[TumblingWindowBolt.WINDOW_DURATION_SECS])
else:
self.logger.fatal("Window Duration has to be specified in... |
def process_tick(self, tup):
"""Called every window_duration
"""
curtime = int(time.time())
window_info = WindowContext(curtime - self.window_duration, curtime)
self.processWindow(window_info, list(self.current_tuples))
for tup in self.current_tuples:
self.ack(tup)
self.current_tuples.... |
def get(self, path):
""" get method """
logging.debug("request to download: %s", path)
# If the file is large, we want to abandon downloading
# if user cancels the requests.
# pylint: disable=attribute-defined-outside-init
self.connection_closed = False
self.set_header("Content-Disposition... |
def getStmgrsRegSummary(self, tmaster, callback=None):
"""
Get summary of stream managers registration summary
"""
if not tmaster or not tmaster.host or not tmaster.stats_port:
return
reg_request = tmaster_pb2.StmgrsRegistrationSummaryRequest()
request_str = reg_request.SerializeToString()... |
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()
topology_info = self.tracker.getTopologyInfo(topology_name, cluster, role, environ)
... |
def atomic_write_file(path, content):
"""
file.write(...) is not atomic.
We write to a tmp file and then rename to target path since rename is atomic.
We do this to avoid the content of file is dirty read/partially read by others.
"""
# Write to a randomly tmp file
tmp_file = get_tmp_filename()
with ope... |
def setup(executor):
"""Set up log, process and signal handlers"""
# pylint: disable=unused-argument
def signal_handler(signal_to_handle, frame):
# We would do nothing here but just exit
# Just catch the SIGTERM and then cleanup(), registered with atexit, would invoke
Log.info('signal_handler invoked ... |
def main():
"""Register exit handlers, initialize the executor and run it."""
# Since Heron on YARN runs as headless users, pex compiled
# binaries should be exploded into the container working
# directory. In order to do this, we need to set the
# PEX_ROOT shell environment before forking the processes
she... |
def init_from_parsed_args(self, parsed_args):
""" initialize from parsed arguments """
self.shard = parsed_args.shard
self.topology_name = parsed_args.topology_name
self.topology_id = parsed_args.topology_id
self.topology_defn_file = parsed_args.topology_defn_file
self.state_manager_connection =... |
def parse_args(args):
"""Uses python argparse to collect positional args"""
Log.info("Input args: %r" % args)
parser = argparse.ArgumentParser()
parser.add_argument("--shard", type=int, required=True)
parser.add_argument("--topology-name", required=True)
parser.add_argument("--topology-id", re... |
def initialize(self):
"""
Initialize the environment. Done with a method call outside of the constructor for 2 reasons:
1. Unit tests probably won't want/need to do this
2. We don't initialize the logger (also something unit tests don't want) until after the
constructor
"""
create_folders = ... |
def _get_metricsmgr_cmd(self, metricsManagerId, sink_config_file, port):
''' get the command to start the metrics manager processes '''
metricsmgr_main_class = 'org.apache.heron.metricsmgr.MetricsManager'
metricsmgr_cmd = [os.path.join(self.heron_java_home, 'bin/java'),
# We could not... |
def _get_metrics_cache_cmd(self):
''' get the command to start the metrics manager processes '''
metricscachemgr_main_class = 'org.apache.heron.metricscachemgr.MetricsCacheManager'
metricscachemgr_cmd = [os.path.join(self.heron_java_home, 'bin/java'),
# We could not rely on the d... |
def _get_healthmgr_cmd(self):
''' get the command to start the topology health manager processes '''
healthmgr_main_class = 'org.apache.heron.healthmgr.HealthManager'
healthmgr_cmd = [os.path.join(self.heron_java_home, 'bin/java'),
# We could not rely on the default -Xmx setting, which... |
def _get_tmaster_processes(self):
''' get the command to start the tmaster processes '''
retval = {}
tmaster_cmd_lst = [
self.tmaster_binary,
'--topology_name=%s' % self.topology_name,
'--topology_id=%s' % self.topology_id,
'--zkhostportlist=%s' % self.state_manager_connectio... |
def _get_streaming_processes(self):
'''
Returns the processes to handle streams, including the stream-mgr and the user code containing
the stream logic of the topology
'''
retval = {}
instance_plans = self._get_instance_plans(self.packing_plan, self.shard)
instance_info = []
for instance... |
def _get_ckptmgr_process(self):
''' Get the command to start the checkpoint manager process'''
ckptmgr_main_class = 'org.apache.heron.ckptmgr.CheckpointManager'
ckptmgr_ram_mb = self.checkpoint_manager_ram / (1024 * 1024)
ckptmgr_cmd = [os.path.join(self.heron_java_home, "bin/java"),
... |
def _get_instance_plans(self, packing_plan, container_id):
"""
For the given packing_plan, return the container plan with the given container_id. If protobufs
supported maps, we could just get the plan by id, but it doesn't so we have a collection of
containers to iterate over.
"""
this_containe... |
def _get_heron_support_processes(self):
""" Get a map from all daemon services' name to the command to start them """
retval = {}
retval[self.heron_shell_ids[self.shard]] = Command([
'%s' % self.heron_shell_binary,
'--port=%s' % self.shell_port,
'--log_file_prefix=%s/heron-shell-%s.... |
def _wait_process_std_out_err(self, name, process):
''' Wait for the termination of a process and log its stdout & stderr '''
proc.stream_process_stdout(process, stdout_log_fn(name))
process.wait() |
def _start_processes(self, commands):
"""Start all commands and add them to the dict of processes to be monitored """
Log.info("Start processes")
processes_to_monitor = {}
# First start all the processes
for (name, command) in commands.items():
p = self._run_process(name, command)
proces... |
def start_process_monitor(self):
""" Monitor all processes in processes_to_monitor dict,
restarting any if they fail, up to max_runs times.
"""
# Now wait for any child to die
Log.info("Start process monitor")
while True:
if len(self.processes_to_monitor) > 0:
(pid, status) = os.wa... |
def get_commands_to_run(self):
"""
Prepare either TMaster or Streaming commands according to shard.
The Shell command is attached to all containers. The empty container plan and non-exist
container plan are bypassed.
"""
# During shutdown the watch might get triggered with the empty packing plan... |
def get_command_changes(self, current_commands, updated_commands):
"""
Compares the current command with updated command to return a 3-tuple of dicts,
keyed by command name: commands_to_kill, commands_to_keep and commands_to_start.
"""
commands_to_kill = {}
commands_to_keep = {}
commands_to_... |
def launch(self):
''' Determines the commands to be run and compares them with the existing running commands.
Then starts new ones required and kills old ones no longer required.
'''
with self.process_lock:
current_commands = dict(map((lambda process: (process.name, process.command)),
... |
def start_state_manager_watches(self):
"""
Receive updates to the packing plan from the statemgrs and update processes as needed.
"""
Log.info("Start state manager watches")
statemgr_config = StateMgrConfig()
statemgr_config.set_state_locations(configloader.load_state_manager_locations(
... |
def run(self, name, config, builder):
"""Builds the topology and submits it"""
if not isinstance(name, str):
raise RuntimeError("Name has to be a string type")
if not isinstance(config, Config):
raise RuntimeError("config has to be a Config type")
if not isinstance(builder, Builder):
r... |
def _modules_to_main(modList):
"""Force every module in modList to be placed into main"""
if not modList:
return
main = sys.modules['__main__']
for modname in modList:
if isinstance(modname, str):
try:
mod = __import__(modname)
except Exception:
sys.stderr.write(
... |
def _fill_function(func, globalsn, defaults, dictn, module):
""" Fills in the rest of function data into the skeleton function object
that were created via _make_skel_func().
"""
func.__globals__.update(globalsn)
func.__defaults__ = defaults
func.__dict__ = dictn
func.__module__ = module
return fu... |
def _make_skel_func(code, closures, base_globals=None):
""" Creates a skeleton function object that contains just the provided
code and the correct number of cells in func_closure. All other
func attributes (e.g. func_globals) are empty.
"""
closure = _reconstruct_closure(closures) if closures else None
... |
def _load_class(cls, d):
"""
Loads additional properties into class `cls`.
"""
for k, v in d.items():
if isinstance(k, tuple):
typ, k = k
if typ == 'property':
v = property(*v)
elif typ == 'staticmethod':
v = staticmethod(v) # pylint: disable=redefined-variable-type
e... |
def save_module(self, obj):
"""
Save a module as an import
"""
self.modules.add(obj)
self.save_reduce(subimport, (obj.__name__,), obj=obj) |
def save_function(self, obj, name=None):
""" Registered with the dispatch to handle all function types.
Determines what kind of function obj is (e.g. lambda, defined at
interactive prompt, etc) and handles the pickling appropriately.
"""
write = self.write
if name is None:
name = obj.__na... |
def save_function_tuple(self, func):
""" Pickles an actual func object.
A func comprises: code, globals, defaults, closure, and dict. We
extract and save these, injecting reducing functions at certain points
to recreate the func object. Keep in mind that some of these pieces
can contain a ref to ... |
def save_file(self, obj): # pylint: disable=too-many-branches
"""Save a file"""
try:
import StringIO as pystringIO #we can't use cStringIO as it lacks the name attribute
except ImportError:
import io as pystringIO # pylint: disable=reimported
if not hasattr(obj, 'name') or not hasattr(obj,... |
def tail(filename, n):
"""Returns last n lines from the filename. No exception handling"""
size = os.path.getsize(filename)
with open(filename, "rb") as f:
fm = mmap.mmap(f.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ)
try:
for i in xrange(size - 1, -1, -1):
if fm[i] == '\n':
n ... |
def get_serializer(context):
"""Returns a serializer for a given context"""
cluster_config = context.get_cluster_config()
serializer_clsname = cluster_config.get(constants.TOPOLOGY_SERIALIZER_CLASSNAME, None)
if serializer_clsname is None:
return PythonSerializer()
else:
try:
top... |
def _run_once(self):
"""Run once, should be called only from loop()"""
try:
self.do_wait()
self._execute_wakeup_tasks()
self._trigger_timers()
except Exception as e:
Log.error("Error occured during _run_once(): " + str(e))
Log.error(traceback.format_exc())
self.should_exi... |
def register_timer_task_in_sec(self, task, second):
"""Registers a new timer task
:param task: function to be run at a specified second from now
:param second: how many seconds to wait before the timer is triggered
"""
# Python time is in float
second_in_float = float(second)
expiration = t... |
def _get_next_timeout_interval(self):
"""Get the next timeout from now
This should be used from do_wait().
:returns (float) next_timeout, or 10.0 if there are no timer events
"""
if len(self.timer_tasks) == 0:
return sys.maxsize
else:
next_timeout_interval = self.timer_tasks[0][0] -... |
def _execute_wakeup_tasks(self):
"""Executes wakeup tasks, should only be called from loop()"""
# Check the length of wakeup tasks first to avoid concurrent issues
size = len(self.wakeup_tasks)
for i in range(size):
self.wakeup_tasks[i]() |
def _trigger_timers(self):
"""Triggers expired timers"""
current = time.time()
while len(self.timer_tasks) > 0 and (self.timer_tasks[0][0] - current <= 0):
task = heappop(self.timer_tasks)[1]
task() |
def post(self):
""" post method """
def status_finish(ret):
self.set_status(ret)
self.finish()
def kill_parent():
status_finish(200)
logger.info("Killing parent executor")
os.killpg(os.getppid(), signal.SIGTERM)
logger = logging.getLogger(__file__)
logger.info("Receiv... |
def execute_query(self, tmaster, query_string, start, end):
""" execute query """
if not tmaster:
raise Exception("No tmaster found")
self.tmaster = tmaster
root = self.parse_query_string(query_string)
metrics = yield root.execute(self.tracker, self.tmaster, start, end)
raise tornado.gen.R... |
def find_closing_braces(self, query):
"""Find the index of the closing braces for the opening braces
at the start of the query string. Note that first character
of input string must be an opening braces."""
if query[0] != '(':
raise Exception("Trying to find closing braces for no opening braces")
... |
def get_sub_parts(self, query):
"""The subparts are seperated by a comma. Make sure
that commas inside the part themselves are not considered."""
parts = []
num_open_braces = 0
delimiter = ','
last_starting_index = 0
for i in range(len(query)):
if query[i] == '(':
num_open_brac... |
def parse_query_string(self, query):
"""Returns a parse tree for the query, each of the node is a
subclass of Operator. This is both a lexical as well as syntax analyzer step."""
if not query:
return None
# Just braces do not matter
if query[0] == '(':
index = self.find_closing_braces(qu... |
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()
topology = self.tracker.getTopologyByClusterRoleEnvironAndName(
cluster, role, ... |
def executeMetricsQuery(self, tmaster, queryString, start_time, end_time, callback=None):
"""
Get the specified metrics for the given query in this topology.
Returns the following dict on success:
{
"timeline": [{
"instance": <instance>,
"data": {
<start_time> : <numeric ... |
def create_parser(subparsers):
'''
:param subparsers:
:return:
'''
parser = subparsers.add_parser(
'help',
help='Prints help for commands',
add_help=True)
# pylint: disable=protected-access
parser._positionals.title = "Required arguments"
parser._optionals.title = "Optional arguments"... |
def run(command, parser, args, unknown_args):
'''
:param command:
:param parser:
:param args:
:param unknown_args:
:return:
'''
# get the command for detailed help
command_help = args['help-command']
# if no command is provided, just print main help
if command_help == 'help':
parser.print_hel... |
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,
should only... |
def process_incoming_tuples(self):
"""Should be called when tuple was buffered into in_stream
This method is equivalent to ``addBoltTasks()`` but
is designed for event-driven single-thread bolt.
"""
# back-pressure
if self.output_helper.is_out_queue_available():
self._read_tuples_and_exec... |
def ack(self, tup):
"""Indicate that processing of a Tuple has succeeded
It is compatible with StreamParse API.
"""
if not isinstance(tup, HeronTuple):
Log.error("Only HeronTuple type is supported in ack()")
return
if self.acking_enabled:
ack_tuple = tuple_pb2.AckTuple()
ac... |
def fail(self, tup):
"""Indicate that processing of a Tuple has failed
It is compatible with StreamParse API.
"""
if not isinstance(tup, HeronTuple):
Log.error("Only HeronTuple type is supported in fail()")
return
if self.acking_enabled:
fail_tuple = tuple_pb2.AckTuple()
fa... |
def execute(handlers):
'''
Run the command
:return:
'''
# verify if the environment variables are correctly set
check_environment()
# create the argument parser
parser = create_parser(handlers)
# if no argument is provided, print help and exit
if len(sys.argv[1:]) == 0:
parser.print_help()
... |
def create_parser(subparsers):
'''
Create a subparser for the standalone command
:param subparsers:
:return:
'''
parser = subparsers.add_parser(
'standalone',
help='Start a standalone Heron cluster',
add_help=True
)
cli_args.add_titles(parser)
parser_action = parser.add_subparsers(... |
def run(command, parser, cl_args, unknown_args):
'''
runs parser
'''
action = cl_args["action"]
if action == Action.SET:
call_editor(get_inventory_file(cl_args))
update_config_files(cl_args)
elif action == Action.CLUSTER:
action_type = cl_args["type"]
if action_type == Cluster.START:
s... |
def template_slave_hcl(cl_args, masters):
'''
Template slave config file
'''
slave_config_template = "%s/standalone/templates/slave.template.hcl" % cl_args["config_path"]
slave_config_actual = "%s/standalone/resources/slave.hcl" % cl_args["config_path"]
masters_in_quotes = ['"%s"' % master for master in mas... |
def template_scheduler_yaml(cl_args, masters):
'''
Template scheduler.yaml
'''
single_master = masters[0]
scheduler_config_actual = "%s/standalone/scheduler.yaml" % cl_args["config_path"]
scheduler_config_template = "%s/standalone/templates/scheduler.template.yaml" \
% cl_args... |
def template_uploader_yaml(cl_args, masters):
'''
Tempate uploader.yaml
'''
single_master = masters[0]
uploader_config_template = "%s/standalone/templates/uploader.template.yaml" \
% cl_args["config_path"]
uploader_config_actual = "%s/standalone/uploader.yaml" % cl_args["config_... |
def template_apiserver_hcl(cl_args, masters, zookeepers):
"""
template apiserver.hcl
"""
single_master = masters[0]
apiserver_config_template = "%s/standalone/templates/apiserver.template.hcl" \
% cl_args["config_path"]
apiserver_config_actual = "%s/standalone/resources/apiserv... |
def template_statemgr_yaml(cl_args, zookeepers):
'''
Template statemgr.yaml
'''
statemgr_config_file_template = "%s/standalone/templates/statemgr.template.yaml" \
% cl_args["config_path"]
statemgr_config_file_actual = "%s/standalone/statemgr.yaml" % cl_args["config_path"]
... |
def template_heron_tools_hcl(cl_args, masters, zookeepers):
'''
template heron tools
'''
heron_tools_hcl_template = "%s/standalone/templates/heron_tools.template.hcl" \
% cl_args["config_path"]
heron_tools_hcl_actual = "%s/standalone/resources/heron_tools.hcl" \
... |
def print_cluster_info(cl_args):
'''
get cluster info for standalone cluster
'''
parsed_roles = read_and_parse_roles(cl_args)
masters = list(parsed_roles[Role.MASTERS])
slaves = list(parsed_roles[Role.SLAVES])
zookeepers = list(parsed_roles[Role.ZOOKEEPERS])
cluster = list(parsed_roles[Role.CLUSTER])
... |
def add_additional_args(parsers):
'''
add additional parameters to parser
'''
for parser in parsers:
cli_args.add_verbose(parser)
cli_args.add_config(parser)
parser.add_argument(
'--heron-dir',
default=config.get_heron_dir(),
help='Path to Heron home directory') |
def stop_cluster(cl_args):
'''
teardown the cluster
'''
Log.info("Terminating cluster...")
roles = read_and_parse_roles(cl_args)
masters = roles[Role.MASTERS]
slaves = roles[Role.SLAVES]
dist_nodes = masters.union(slaves)
# stop all jobs
if masters:
try:
single_master = list(masters)[0]
... |
def start_cluster(cl_args):
'''
Start a Heron standalone cluster
'''
roles = read_and_parse_roles(cl_args)
masters = roles[Role.MASTERS]
slaves = roles[Role.SLAVES]
zookeepers = roles[Role.ZOOKEEPERS]
Log.info("Roles:")
Log.info(" - Master Servers: %s" % list(masters))
Log.info(" - Slave Servers: %s... |
def start_heron_tools(masters, cl_args):
'''
Start Heron tracker and UI
'''
single_master = list(masters)[0]
wait_for_master_to_start(single_master)
cmd = "%s run %s >> /tmp/heron_tools_start.log 2>&1 &" \
% (get_nomad_path(cl_args), get_heron_tools_job_file(cl_args))
Log.info("Starting Heron Too... |
def distribute_package(roles, cl_args):
'''
distribute Heron packages to all nodes
'''
Log.info("Distributing heron package to nodes (this might take a while)...")
masters = roles[Role.MASTERS]
slaves = roles[Role.SLAVES]
tar_file = tempfile.NamedTemporaryFile(suffix=".tmp").name
Log.debug("TAR file %s... |
def wait_for_master_to_start(single_master):
'''
Wait for a nomad master to start
'''
i = 0
while True:
try:
r = requests.get("http://%s:4646/v1/status/leader" % single_master)
if r.status_code == 200:
break
except:
Log.debug(sys.exc_info()[0])
Log.info("Waiting for clu... |
def wait_for_job_to_start(single_master, job):
'''
Wait for a Nomad job to start
'''
i = 0
while True:
try:
r = requests.get("http://%s:4646/v1/job/%s" % (single_master, job))
if r.status_code == 200 and r.json()["Status"] == "running":
break
else:
raise RuntimeError()
... |
def scp_package(package_file, destinations, cl_args):
'''
scp and extract package
'''
pids = []
for dest in destinations:
if is_self(dest):
continue
Log.info("Server: %s" % dest)
file_path = "/tmp/heron.tar.gz"
dest_file_path = "%s:%s" % (dest, file_path)
remote_cmd = "rm -rf ~/.her... |
def make_tarfile(output_filename, source_dir):
'''
Tar a directory
'''
with tarfile.open(output_filename, "w:gz") as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir)) |
def start_master_nodes(masters, cl_args):
'''
Start master nodes
'''
pids = []
for master in masters:
Log.info("Starting master on %s" % master)
cmd = "%s agent -config %s >> /tmp/nomad_server_log 2>&1 &" \
% (get_nomad_path(cl_args), get_nomad_master_config_file(cl_args))
if not is_self... |
def start_slave_nodes(slaves, cl_args):
'''
Star slave nodes
'''
pids = []
for slave in slaves:
Log.info("Starting slave on %s" % slave)
cmd = "%s agent -config %s >> /tmp/nomad_client.log 2>&1 &" \
% (get_nomad_path(cl_args), get_nomad_slave_config_file(cl_args))
if not is_self(slave):
... |
def read_and_parse_roles(cl_args):
'''
read config files to get roles
'''
roles = dict()
with open(get_inventory_file(cl_args), 'r') as stream:
try:
roles = yaml.load(stream)
except yaml.YAMLError as exc:
Log.error("Error parsing inventory file: %s" % exc)
sys.exit(-1)
if Role.ZO... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.