You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@aurora.apache.org by ma...@apache.org on 2015/01/08 02:07:16 UTC
[4/5] incubator-aurora git commit: Removing client v1 code.
http://git-wip-us.apache.org/repos/asf/incubator-aurora/blob/9a817f24/src/main/python/apache/aurora/client/commands/core.py
----------------------------------------------------------------------
diff --git a/src/main/python/apache/aurora/client/commands/core.py b/src/main/python/apache/aurora/client/commands/core.py
deleted file mode 100644
index 7c9505b..0000000
--- a/src/main/python/apache/aurora/client/commands/core.py
+++ /dev/null
@@ -1,905 +0,0 @@
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""Command-line client for managing jobs with the Aurora scheduler.
-"""
-
-from __future__ import print_function
-
-import json
-import os
-import pprint
-import subprocess
-import sys
-import time
-from copy import deepcopy
-from datetime import datetime
-from tempfile import NamedTemporaryFile
-
-from twitter.common import app, log
-
-from apache.aurora.client.api.disambiguator import LiveJobDisambiguator
-from apache.aurora.client.api.job_monitor import JobMonitor
-from apache.aurora.client.api.quota_check import print_quota
-from apache.aurora.client.api.updater_util import UpdaterConfig
-from apache.aurora.client.base import (
- AURORA_V1_USER_AGENT_NAME,
- check_and_log_response,
- combine_messages,
- deprecation_warning,
- die,
- get_populated_task_config,
- handle_open,
- requires,
- synthesize_url,
- user_agent
-)
-from apache.aurora.client.config import get_config, GlobalHookRegistry
-from apache.aurora.client.factory import make_client, make_client_factory
-from apache.aurora.client.options import (
- BATCH_OPTION,
- CLUSTER_CONFIG_OPTION,
- CLUSTER_INVOKE_OPTION,
- CLUSTER_NAME_OPTION,
- DISABLE_HOOKS_OPTION,
- ENV_CONFIG_OPTION,
- ENVIRONMENT_BIND_OPTION,
- FROM_JOBKEY_OPTION,
- HEALTH_CHECK_INTERVAL_SECONDS_OPTION,
- JSON_OPTION,
- MAX_FAILURES_OPTION,
- OPEN_BROWSER_OPTION,
- SHARDS_OPTION,
- WAIT_UNTIL_OPTION
-)
-from apache.aurora.common.aurora_job_key import AuroraJobKey
-from apache.aurora.common.pex_version import pex_version, UnknownVersion
-
-from gen.apache.aurora.api.constants import ACTIVE_STATES, AURORA_EXECUTOR_NAME, CURRENT_API_VERSION
-from gen.apache.aurora.api.ttypes import ExecutorConfig, ResponseCode, ScheduleStatus
-
-
-def make_v1_client_factory():
- return make_client_factory(user_agent(AURORA_V1_USER_AGENT_NAME))
-
-
-def make_v1_client(cluster):
- return make_client(cluster, AURORA_V1_USER_AGENT_NAME)
-
-
-class CoreCommandHook(object):
- """Limited version of the command hooks framework ported to clientv1 commands.
- Core command hooks can only be created by invoking "CoreCommandHook.register_hook"
- in a module compiled into the aurora client executable.
- Core command hooks are currently only supported for the following commands:
- create, kill, killall, restart, start_cron, update, cancel_update
- """
-
- def execute(self, cmd, options, *args, **kwargs):
- """
- :param cmd: the command being invoked
- :param options: the options object created by processing command line options
- :param args: all other positional arguments taken by the command.
- :param kwargs: all other keyword argumetns taken by the command.
-
- This is invoked by each core client command before the command is executed, *after* options
- are parsed. If this returns non-zero, the command execution will be aborted and the return
- code of this method will be used as the exit code. To make a hook work with a specific
- command, hook implementors should check the "cmd" parameter.
- """
- pass
-
- ALL_HOOKS = []
-
- @property
- def name(self):
- pass
-
- @classmethod
- def register_hook(cls, hook):
- cls.ALL_HOOKS.append(hook)
-
- @classmethod
- def clear_hooks(cls):
- cls.ALL_HOOKS = []
-
- @classmethod
- def run_hooks(cls, cmd, options, *args, **kwargs):
- for hook in cls.ALL_HOOKS:
- result = hook.execute(cmd, options, *args, **kwargs)
- if result != 0:
- print("Command execution aborted by hook %s" % hook.name)
- exit(result)
-
-
-def get_job_config(job_spec, config_file, options):
- try:
- job_key = AuroraJobKey.from_path(job_spec)
- select_cluster = job_key.cluster
- select_env = job_key.env
- select_role = job_key.role
- jobname = job_key.name
- except AuroraJobKey.Error:
- deprecation_warning('Please refer to your job in CLUSTER/ROLE/ENV/NAME format.')
- select_cluster = options.cluster if options.cluster else None
- select_env = options.env
- select_role = None
- jobname = job_spec
- try:
- json_option = options.json
- except AttributeError:
- json_option = False
- try:
- bindings = options.bindings
- except AttributeError:
- bindings = ()
- return get_config(
- jobname,
- config_file,
- json_option,
- bindings,
- select_cluster=select_cluster,
- select_role=select_role,
- select_env=select_env)
-
-
-def wait_kill_tasks(scheduler, job_key, instances=None):
- monitor = JobMonitor(scheduler, job_key)
- if not monitor.wait_until(monitor.terminal, instances=instances, with_timeout=True):
- die('Tasks were not killed in time.')
-
-
-_API_VERSION_MESSAGE = "Aurora API version: %s" % CURRENT_API_VERSION
-_BUILD_INFO_HEADER = "Aurora client build info:"
-_NO_BUILD_INFO_MESSAGE = "Aurora client build info not available"
-
-
-def _version(_argv=sys.argv, _print=print, _pex_version=pex_version):
- try:
- build_sha, build_date = _pex_version(_argv[0])
-
- _print(_BUILD_INFO_HEADER)
- _print("\tsha: %s" % build_sha)
- _print("\tdate: %s" % build_date)
-
- except UnknownVersion:
- _print(_NO_BUILD_INFO_MESSAGE)
- _print(_API_VERSION_MESSAGE)
-
-
-@app.command
-def version():
- """usage: version
-
- Prints information about the version of the aurora client being run.
- """
- _version()
-
-
-def maybe_disable_hooks(options):
- """Checks the hooks disable option, and disables the hooks if required.
- This could be done with a callback in the option, but this is better for the way that
- we test clientv1.
- """
- if options.disable_all_hooks_reason is not None:
- GlobalHookRegistry.disable_hooks()
- log.info('Client hooks disabled; reason given by user: %s' % options.disable_all_hooks_reason)
-
-
-def v1_deprecation_warning(old, new):
- print("WARNING: %s is an aurora clientv1 command which will be deprecated soon" % old)
- print("To run this command using clientv2, use 'aurora %s'" % " ".join(new))
-
-
-def really_create(job_spec, config_file, options):
- try:
- config = get_job_config(job_spec, config_file, options)
- except ValueError as v:
- print("Error: %s" % v)
- sys.exit(1)
- api = make_v1_client(config.cluster())
- resp = api.create_job(config)
- check_and_log_response(resp)
- handle_open(api.scheduler_proxy.scheduler_client().url, config.role(), config.environment(),
- config.name())
- if options.wait_until == 'RUNNING':
- JobMonitor(api.scheduler_proxy, config.job_key()).wait_until(JobMonitor.running_or_finished)
- elif options.wait_until == 'FINISHED':
- JobMonitor(api.scheduler_proxy, config.job_key()).wait_until(JobMonitor.terminal)
-
-
-@app.command
-@app.command_option(ENVIRONMENT_BIND_OPTION)
-@app.command_option(OPEN_BROWSER_OPTION)
-@app.command_option(CLUSTER_CONFIG_OPTION)
-@app.command_option(ENV_CONFIG_OPTION)
-@app.command_option(JSON_OPTION)
-@app.command_option(WAIT_UNTIL_OPTION)
-@app.command_option(DISABLE_HOOKS_OPTION)
-@requires.exactly('cluster/role/env/job', 'config')
-def create(job_spec, config_file):
- """usage: create cluster/role/env/job config
-
- Creates a job based on a configuration file.
- """
- options = app.get_options()
- CoreCommandHook.run_hooks("create", options, job_spec, config_file)
- maybe_disable_hooks(options)
- newcmd = ["job create"]
- newcmd.append(job_spec)
- newcmd.append(config_file)
- if options.open_browser:
- newcmd.append('--open-browser')
- if options.json:
- newcmd.append('--read-json')
- if options.wait_until != "PENDING":
- newcmd.append('--wait-until=%s' % options.wait_until)
-
- v1_deprecation_warning("create", newcmd)
- return really_create(job_spec, config_file, options)
-
-
-@app.command
-@app.command_option(ENVIRONMENT_BIND_OPTION)
-@app.command_option(CLUSTER_CONFIG_OPTION)
-@app.command_option(ENV_CONFIG_OPTION)
-@app.command_option(JSON_OPTION)
-@app.command_option(FROM_JOBKEY_OPTION)
-@requires.exactly('cluster/role/env/job', 'config')
-def diff(job_spec, config_file):
- """usage: diff cluster/role/env/job config
-
- Compares a job configuration against a running job.
- By default the diff will be displayed using 'diff', though you may choose an alternate
- diff program by specifying the DIFF_VIEWER environment variable."""
- options = app.get_options()
-
- newcmd = ["job", "diff", job_spec, config_file]
- if options.json:
- newcmd.append("--read-json")
-
- v1_deprecation_warning("diff", newcmd)
-
- config = get_job_config(job_spec, config_file, options)
- if options.rename_from:
- cluster, role, env, name = options.rename_from
- else:
- cluster = config.cluster()
- role = config.role()
- env = config.environment()
- name = config.name()
- api = make_v1_client(cluster)
- resp = api.query(api.build_query(role, name, statuses=ACTIVE_STATES, env=env))
- if resp.responseCode != ResponseCode.OK:
- die('Request failed, server responded with "%s"' % combine_messages(resp))
- remote_tasks = [t.assignedTask.task for t in resp.result.scheduleStatusResult.tasks]
- resp = api.populate_job_config(config)
- if resp.responseCode != ResponseCode.OK:
- die('Request failed, server responded with "%s"' % combine_messages(resp))
- local_tasks = [deepcopy(get_populated_task_config(resp)) for _ in range(config.instances())]
-
- pp = pprint.PrettyPrinter(indent=2)
- def pretty_print_task(task):
- # The raw configuration is not interesting - we only care about what gets parsed.
- task.configuration = None
- task.executorConfig = ExecutorConfig(
- name=AURORA_EXECUTOR_NAME,
- data=json.loads(task.executorConfig.data))
-
- return pp.pformat(vars(task))
-
- def pretty_print_tasks(tasks):
- return ',\n'.join([pretty_print_task(t) for t in tasks])
-
- def dump_tasks(tasks, out_file):
- out_file.write(pretty_print_tasks(tasks))
- out_file.write('\n')
- out_file.flush()
-
- diff_program = os.environ.get('DIFF_VIEWER', 'diff')
- with NamedTemporaryFile() as local:
- dump_tasks(local_tasks, local)
- with NamedTemporaryFile() as remote:
- dump_tasks(remote_tasks, remote)
- result = subprocess.call([diff_program, remote.name, local.name])
- # Unlike most commands, diff doesn't return zero on success; it returns
- # 1 when a successful diff is non-empty.
- if result != 0 and result != 1:
- return result
- else:
- return 0
-
-
-@app.command(name='open')
-def do_open(args, _):
- """usage: open cluster[/role[/env/job]]
-
- Opens the scheduler page for a cluster, role or job in the default web browser.
- """
- cluster_name = role = env = job = None
- if len(args) == 0:
- print('Open command requires a jobkey parameter.')
- exit(1)
- v1_deprecation_warning("open", ["job", "open"])
- args = args[0].split("/")
- if len(args) > 0:
- cluster_name = args[0]
- if len(args) > 1:
- role = args[1]
- if len(args) > 2:
- env = args[2]
- if len(args) > 3:
- job = args[3]
- else:
- # TODO(ksweeney): Remove this after MESOS-2945 is completed.
- die('env scheduler pages are not yet implemented, please specify job')
-
- if not cluster_name:
- die('cluster is required')
-
- api = make_v1_client(cluster_name)
-
- import webbrowser
- webbrowser.open_new_tab(
- synthesize_url(api.scheduler_proxy.scheduler_client().url, role, env, job))
-
-
-@app.command
-@app.command_option('--local', dest='local', default=False, action='store_true',
- help='Inspect the configuration as would be created by the "spawn" command.')
-@app.command_option('--raw', dest='raw', default=False, action='store_true',
- help='Show the raw configuration.')
-@app.command_option(ENVIRONMENT_BIND_OPTION)
-@app.command_option(CLUSTER_CONFIG_OPTION)
-@app.command_option(ENV_CONFIG_OPTION)
-@app.command_option(JSON_OPTION)
-@requires.exactly('cluster/role/env/job', 'config')
-def inspect(job_spec, config_file):
- """usage: inspect cluster/role/env/job config
-
- Verifies that a job can be parsed from a configuration file, and displays
- the parsed configuration.
- """
- options = app.get_options()
- newcmd = ["job", "inspect", job_spec, config_file]
- if options.json:
- newcmd.append("--read-json")
- v1_deprecation_warning("inspect", newcmd)
-
- config = get_job_config(job_spec, config_file, options)
- if options.raw:
- print('Parsed job config: %s' % config.job())
- return
-
- job_thrift = config.job()
- job = config.raw()
- job_thrift = config.job()
- print('Job level information')
- print(' name: %s' % job.name())
- print(' role: %s' % job.role())
- print(' contact: %s' % job.contact())
- print(' cluster: %s' % job.cluster())
- print(' instances: %s' % job.instances())
- if job.has_cron_schedule():
- print(' cron:')
- print(' schedule: %s' % job.cron_schedule())
- print(' policy: %s' % job.cron_collision_policy())
- if job.has_constraints():
- print(' constraints:')
- for constraint, value in job.constraints().get().items():
- print(' %s: %s' % (constraint, value))
- print(' service: %s' % job_thrift.taskConfig.isService)
- print(' production: %s' % bool(job.production().get()))
- print()
-
- task = job.task()
- print('Task level information')
- print(' name: %s' % task.name())
- if len(task.constraints().get()) > 0:
- print(' constraints:')
- for constraint in task.constraints():
- print(' %s' % (' < '.join(st.get() for st in constraint.order())))
- print()
-
- processes = task.processes()
- for process in processes:
- print('Process %s:' % process.name())
- if process.daemon().get():
- print(' daemon')
- if process.ephemeral().get():
- print(' ephemeral')
- if process.final().get():
- print(' final')
- print(' cmdline:')
- for line in process.cmdline().get().splitlines():
- print(' ' + line)
- print()
-
-
-def really_start_cron(args, options):
- api, job_key, config_file = LiveJobDisambiguator.disambiguate_args_or_die(
- args, options, make_v1_client_factory())
- config = get_job_config(job_key.to_path(), config_file, options) if config_file else None
- resp = api.start_cronjob(job_key, config=config)
- check_and_log_response(resp)
- handle_open(api.scheduler_proxy.scheduler_client().url, job_key.role, job_key.env, job_key.name)
-
-
-@app.command
-@app.command_option(CLUSTER_INVOKE_OPTION)
-@app.command_option(OPEN_BROWSER_OPTION)
-@app.command_option(DISABLE_HOOKS_OPTION)
-def start_cron(args, options):
- """usage: start_cron cluster/role/env/job
-
- Invokes a cron job immediately, out of its normal cron cycle.
- This does not affect the cron cycle in any way.
- """
- newcmd = ["cron", "start"]
- if options.disable_all_hooks_reason is not None:
- newcmd.append("--disable-all-hooks-reason=%s" % options.disable_all_hooks_reason)
- v1_deprecation_warning("start_cron", newcmd)
- CoreCommandHook.run_hooks("start_cron", options, *args)
- maybe_disable_hooks(options)
- return really_start_cron(args, options)
-
-
-@app.command
-@app.command_option(
- '--pretty',
- dest='pretty',
- default=False,
- action='store_true',
- help='Show job information in prettyprinted format')
-@app.command_option(
- '--show-cron',
- '-c',
- dest='show_cron_schedule',
- default=False,
- action='store_true',
- help='List jobs registered with the Aurora scheduler')
-@requires.exactly('cluster/role')
-def list_jobs(cluster_and_role):
- """usage: list_jobs [--show-cron] cluster/role/env/job
-
- Shows all jobs that match the job-spec known by the scheduler.
- If --show-cron is specified, then also shows the registered cron schedule.
- """
- def show_job_simple(job):
- if options.show_cron_schedule:
- print(('{0}/{1.key.role}/{1.key.environment}/{1.key.name}' +
- '\t\'{1.cronSchedule}\'\t{1.cronCollisionPolicy}').format(cluster, job))
- else:
- print('{0}/{1.key.role}/{1.key.environment}/{1.key.name}'.format(cluster, job))
-
- def show_job_pretty(job):
- print("Job %s/%s/%s/%s:" %
- (cluster, job.key.role, job.key.environment, job.key.name))
- print('\tcron schedule: %s' % job.cronSchedule)
- print('\tcron policy: %s' % job.cronCollisionPolicy)
-
- options = app.get_options()
- v1_deprecation_warning("list_jobs", ["job", "list", cluster_and_role])
-
- if options.show_cron_schedule and options.pretty:
- print_fn = show_job_pretty
- else:
- print_fn = show_job_simple
- # Take the cluster_and_role parameter, and split it into its two components.
- if cluster_and_role.count('/') != 1:
- die('list_jobs parameter must be in cluster/role format')
- cluster, role = cluster_and_role.split('/')
- api = make_v1_client(cluster)
- resp = api.get_jobs(role)
- check_and_log_response(resp)
- for job in resp.result.getJobsResult.configs:
- print_fn(job)
-
-
-@app.command
-@app.command_option(CLUSTER_INVOKE_OPTION)
-@app.command_option(OPEN_BROWSER_OPTION)
-@app.command_option(SHARDS_OPTION)
-@app.command_option(DISABLE_HOOKS_OPTION)
-@app.command_option(BATCH_OPTION)
-@app.command_option(MAX_FAILURES_OPTION)
-def kill(args, options):
- """usage: kill --shards=shardspec cluster/role/env/job
-
- Kills a group of tasks in a running job, blocking until all specified tasks have terminated.
-
- """
- CoreCommandHook.run_hooks("kill", options, *args)
- maybe_disable_hooks(options)
- return really_kill(args, options)
-
-
-def really_kill(args, options):
- if options.shards is None:
- print('Shards option is required for kill; use killall to kill all shards', file=sys.stderr)
- exit(1)
- api, job_key, config_file = LiveJobDisambiguator.disambiguate_args_or_die(
- args, options, make_v1_client_factory())
- instance_key = str(job_key)
- if options.shards is not None:
- instance_key = "%s/%s" % (instance_key, ",".join(map(str, options.shards)))
- new_cmd = ["job", "kill", instance_key]
- if config_file is not None:
- new_cmd.append("--config=%s" % config_file)
- if options.open_browser:
- new_cmd.append("--open-browser")
- if options.batch_size is not None:
- new_cmd.append("--batch-size=%s" % options.batch_size)
- if options.max_total_failures is not None:
- new_cmd.append("--max-total-failures=%s" % options.max_total_failures)
- v1_deprecation_warning("kill", new_cmd)
-
- config = get_job_config(job_key.to_path(), config_file, options) if config_file else None
- if options.batch_size is not None:
- kill_in_batches(api, job_key, options.shards, options.batch_size, options.max_failures_option)
- else:
- resp = api.kill_job(job_key, options.shards, config=config)
- check_and_log_response(resp)
- handle_open(api.scheduler_proxy.scheduler_client().url, job_key.role, job_key.env, job_key.name)
- wait_kill_tasks(api.scheduler_proxy, job_key, options.shards)
-
-
-def kill_in_batches(api, job_key, instances_arg, batch_size, max_failures):
- """ Common behavior shared by kill and killAll for killing instances in
- a sequence of batches.
- """
- def make_batches(instances, batch_size):
- result = []
- while (len(instances) > 0):
- batch = []
- for i in range(min(batch_size, len(instances))):
- batch.append(instances.pop())
- result.append(batch)
- return result
-
- resp = api.check_status(job_key)
- if resp.responseCode is not ResponseCode.OK:
- log.error("Job %s could not be found" % job_key)
- exit(1)
- tasks = resp.result.scheduleStatusResult.tasks or None
- if batch_size is not None and batch_size > 0 and tasks is not None:
- instance_ids = set(instance.assignedTask.instanceId for instance in tasks)
- instances_to_kill = instance_ids & set(instances_arg or instance_ids)
- errors = 0
- for batch in make_batches(instances_to_kill, batch_size):
- resp = api.kill_job(job_key, batch)
- if resp.responseCode is not ResponseCode.OK:
- log.info("Kill of shards %s failed with error %s" % (batch, combine_messages(resp)))
- print('ERROR IN KILL_JOB')
- errors += 1
- if errors > max_failures:
- log.error("Exceeded maximum number of errors while killing instances")
- exit(1)
- if errors > 0:
- print("Warning: errors occurred during batch kill")
- exit(1)
- else:
- if tasks is None or len(tasks) == 0:
- log.error('No tasks to kill found for job %s' % job_key)
- return 1
-
-
-def really_killall(args, options):
- """Helper for testing purposes: make it easier to mock out the actual kill process,
- while testing hooks in the command dispatch process.
- """
- maybe_disable_hooks(options)
- job_key = AuroraJobKey.from_path(args[0])
- config_file = args[1] if len(args) > 1 else None # the config for hooks
- new_cmd = ["job", "killall", args[0]]
- if config_file is not None:
- new_cmd.append("--config=%s" % config_file)
- if options.open_browser:
- new_cmd.append("--open-browser")
- if options.batch_size is not None:
- new_cmd.append("--batch-size=%s" % options.batch_size)
- if options.max_total_failures is not None:
- new_cmd.append("--max-total-failures=%s" % options.max_total_failures)
- v1_deprecation_warning("killall", new_cmd)
-
- config = get_job_config(job_key.to_path(), config_file, options) if config_file else None
- api = make_v1_client(job_key.cluster)
- if options.batch_size is not None:
- kill_in_batches(api, job_key, None, options.batch_size, options.max_failures_option)
- else:
- resp = api.kill_job(job_key, None, config=config)
- check_and_log_response(resp)
- handle_open(api.scheduler_proxy.scheduler_client().url, job_key.role, job_key.env, job_key.name)
- wait_kill_tasks(api.scheduler_proxy, job_key)
-
-
-@app.command
-@app.command_option(CLUSTER_INVOKE_OPTION)
-@app.command_option(OPEN_BROWSER_OPTION)
-@app.command_option(DISABLE_HOOKS_OPTION)
-@app.command_option(BATCH_OPTION)
-@app.command_option(MAX_FAILURES_OPTION)
-def killall(args, options):
- """usage: killall cluster/role/env/job
- Kills all tasks in a running job, blocking until all specified tasks have been terminated.
- """
- CoreCommandHook.run_hooks("killall", options, *args)
- really_killall(args, options)
-
-
-@app.command
-@app.command_option(CLUSTER_INVOKE_OPTION)
-def status(args, options):
- """usage: status cluster/role/env/job
-
- Fetches and prints information about the active tasks in a job.
- """
- def is_active(task):
- return task.status in ACTIVE_STATES
-
- def print_task(scheduled_task):
- assigned_task = scheduled_task.assignedTask
- taskInfo = assigned_task.task
- taskString = ''
- if taskInfo:
- taskString += '''cpus: %s, ram: %s MB, disk: %s MB''' % (taskInfo.numCpus,
- taskInfo.ramMb,
- taskInfo.diskMb)
- if assigned_task.assignedPorts:
- taskString += '\n\tports: %s' % assigned_task.assignedPorts
- taskString += '\n\tfailure count: %s (max %s)' % (scheduled_task.failureCount,
- taskInfo.maxTaskFailures)
- taskString += '\n\tevents:'
- for event in scheduled_task.taskEvents:
- taskString += '\n\t\t %s %s: %s' % (datetime.fromtimestamp(event.timestamp / 1000),
- ScheduleStatus._VALUES_TO_NAMES[event.status],
- event.message)
- taskString += '\n\tmetadata:'
- if assigned_task.task.metadata is not None:
- for md in assigned_task.task.metadata:
- taskString += ('\n\t\t%s: %s' % (md.key, md.value))
-
- return taskString
-
- def print_tasks(tasks):
- for scheduled in tasks:
- taskString = print_task(scheduled)
-
- assigned = scheduled.assignedTask
- log.info('role: %s, env: %s, name: %s, shard: %s, status: %s on %s\n%s' %
- (assigned.task.job.role if assigned.task.job else assigned.task.owner.role,
- assigned.task.job.environment if assigned.task.job else assigned.task.environment,
- assigned.task.job.name if assigned.task.job else assigned.task.jobName,
- assigned.instanceId,
- ScheduleStatus._VALUES_TO_NAMES[scheduled.status],
- assigned.slaveHost,
- taskString))
-
- api, job_key, _ = LiveJobDisambiguator.disambiguate_args_or_die(
- args, options, make_v1_client_factory())
- v1_deprecation_warning("status", ["job", "status", args[0]])
- resp = api.check_status(job_key)
- check_and_log_response(resp)
-
- tasks = resp.result.scheduleStatusResult.tasks
- if tasks:
- active_tasks = filter(is_active, tasks)
- log.info('Active Tasks (%s)' % len(active_tasks))
- print_tasks(active_tasks)
- inactive_tasks = filter(lambda x: not is_active(x), tasks)
- log.info('Inactive Tasks (%s)' % len(inactive_tasks))
- print_tasks(inactive_tasks)
- else:
- log.info('No tasks found.')
-
-
-def really_update(job_spec, config_file, options):
- def warn_if_dangerous_change(api, config):
- # Get the current job status, so that we can check if there's anything
- # dangerous about this update.
- resp = api.query_no_configs(api.build_query(config.role(), config.name(),
- statuses=ACTIVE_STATES, env=config.environment()))
- if resp.responseCode != ResponseCode.OK:
- die('Could not get job status from server for comparison: %s' % combine_messages(resp))
- remote_tasks = [t.assignedTask.task for t in resp.result.scheduleStatusResult.tasks]
- local_task_count = config.instances()
- remote_task_count = len(remote_tasks)
- if (local_task_count >= 4 * remote_task_count or local_task_count <= 4 * remote_task_count
- or local_task_count == 0):
- print('Warning: this update is a large change. Press ^c within 5 seconds to abort')
- time.sleep(5)
-
- maybe_disable_hooks(options)
- config = get_job_config(job_spec, config_file, options)
- api = make_v1_client(config.cluster())
- if not options.force:
- warn_if_dangerous_change(api, job_spec, config)
- resp = api.update_job(config, options.health_check_interval_seconds, options.shards)
- check_and_log_response(resp)
-
-
-@app.command
-@app.command_option(SHARDS_OPTION)
-@app.command_option(ENVIRONMENT_BIND_OPTION)
-@app.command_option(CLUSTER_CONFIG_OPTION)
-@app.command_option(ENV_CONFIG_OPTION)
-@app.command_option(JSON_OPTION)
-@app.command_option(HEALTH_CHECK_INTERVAL_SECONDS_OPTION)
-@app.command_option(DISABLE_HOOKS_OPTION)
-@app.command_option(
- '--force',
- dest='force',
- default=True, # TODO(maximk): Temporary bandaid for MESOS-4310 until a better fix is available.
- action='store_true',
- help='Turn off warning message that the update looks large enough to be disruptive.')
-@requires.exactly('cluster/role/env/job', 'config')
-def update(job_spec, config_file):
- """usage: update cluster/role/env/job config
-
- Performs a rolling upgrade on a running job, using the update configuration
- within the config file as a control for update velocity and failure tolerance.
-
- Updates are fully controlled client-side, so aborting an update halts the
- update and leaves the job in a 'locked' state on the scheduler.
- Subsequent update attempts will fail until the update is 'unlocked' using the
- 'cancel_update' command.
-
- The updater only takes action on shards in a job that have changed, meaning
- that changing a single shard will only induce a restart on the changed shard.
-
- You may want to consider using the 'diff' subcommand before updating,
- to preview what changes will take effect.
- """
- options = app.get_options()
- CoreCommandHook.run_hooks("update", options, job_spec, config_file)
- new_cmd = ["job", "update"]
- instance_spec = job_spec
- if options.shards is not None:
- instance_spec = "%s/%s" % (job_spec, ",".join(map(str, options.shards)))
- new_cmd.append(instance_spec)
- new_cmd.append(config_file)
- if options.json:
- new_cmd.append("--read-json")
- if options.health_check_interval_seconds is not None:
- new_cmd.append("--health-check-interval-seconds=%s" % options.health_check_interval_seconds)
- v1_deprecation_warning("update", new_cmd)
- return really_update(job_spec, config_file, options)
-
-
-def really_restart(args, options):
- if options.max_total_failures < 0:
- print("max_total_failures option must be >0, but you specified %s" % options.max_total_failures,
- file=sys.stderr)
- exit(1)
- maybe_disable_hooks(options)
- api, job_key, config_file = LiveJobDisambiguator.disambiguate_args_or_die(
- args, options, make_v1_client_factory())
- config = get_job_config(job_key.to_path(), config_file, options) if config_file else None
- updater_config = UpdaterConfig(
- options.batch_size,
- options.restart_threshold,
- options.watch_secs,
- options.max_per_shard_failures,
- options.max_total_failures)
- resp = api.restart(job_key, options.shards, updater_config,
- options.health_check_interval_seconds, config=config)
- check_and_log_response(resp)
- handle_open(api.scheduler_proxy.scheduler_client().url, job_key.role, job_key.env, job_key.name)
-
-
-@app.command
-@app.command_option(CLUSTER_INVOKE_OPTION)
-@app.command_option(HEALTH_CHECK_INTERVAL_SECONDS_OPTION)
-@app.command_option(OPEN_BROWSER_OPTION)
-@app.command_option(SHARDS_OPTION)
-@app.command_option(
- '--batch_size',
- dest='batch_size',
- type=int,
- default=1,
- help='Number of shards to be restarted in one iteration.')
-@app.command_option(
- '--max_per_shard_failures',
- dest='max_per_shard_failures',
- type=int,
- default=0,
- help='Maximum number of restarts per shard during restart. Increments total failure count when '
- 'this limit is exceeded.')
-@app.command_option(
- '--max_total_failures',
- dest='max_total_failures',
- type=int,
- default=0,
- help='Maximum number of shard failures to be tolerated in total during restart.')
-@app.command_option(
- '--restart_threshold',
- dest='restart_threshold',
- type=int,
- default=60,
- help='Maximum number of seconds before a shard must move into the RUNNING state before '
- 'considered a failure.')
-@app.command_option(
- '--watch_secs',
- dest='watch_secs',
- type=int,
- default=30,
- help='Minimum number of seconds a shard must remain in RUNNING state before considered a '
- 'success.')
-@app.command_option(DISABLE_HOOKS_OPTION)
-def restart(args, options):
- """usage: restart cluster/role/env/job
- [--shards=SHARDS]
- [--batch_size=INT]
- [--updater_health_check_interval_seconds=SECONDS]
- [--max_per_shard_failures=INT]
- [--max_total_failures=INT]
- [--restart_threshold=INT]
- [--watch_secs=SECONDS]
-
- Performs a rolling restart of shards within a job.
-
- Restarts are fully controlled client-side, so aborting halts the restart.
- """
- CoreCommandHook.run_hooks("restart", options, *args)
- return really_restart(args, options)
-
-
-def really_cancel_update(args, options):
- api, job_key, config_file = LiveJobDisambiguator.disambiguate_args_or_die(
- args, options, make_v1_client_factory())
- new_cmd = ["job", "cancel-update", str(job_key)]
- v1_deprecation_warning("cancel_update", new_cmd)
- config = get_job_config(job_key.to_path(), config_file, options) if config_file else None
- resp = api.cancel_update(job_key, config=config)
- check_and_log_response(resp)
-
-
-@app.command
-@app.command_option(CLUSTER_INVOKE_OPTION)
-def cancel_update(args, options):
- """usage: cancel_update cluster/role/env/job
-
- Unlocks a job for updates.
- A job may be locked if a client's update session terminated abnormally,
- or if another user is actively updating the job. This command should only
- be used when the user is confident that they are not conflicting with another user.
- """
- CoreCommandHook.run_hooks("cancel_update", options, *args)
- v1_deprecation_warning("cancel_update", ["job", "cancel_update"] + args)
- return really_cancel_update(args, options)
-
-
-@app.command
-@app.command_option(CLUSTER_NAME_OPTION)
-@requires.exactly('role')
-def get_quota(role):
- """usage: get_quota --cluster=CLUSTER role
-
- Prints the production quota that has been allocated to a user.
- """
- options = app.get_options()
- v1_deprecation_warning("get_quota", ["quota", "get", "%s/%s" % (options.cluster, role)])
- resp = make_v1_client(options.cluster).get_quota(role)
- quota_result = resp.result.getQuotaResult
- print_quota(quota_result.quota, 'Total allocated quota', role)
-
- if resp.result.getQuotaResult.prodConsumption:
- print_quota(quota_result.prodConsumption,
- 'Resources consumed by production jobs',
- role)
-
- if resp.result.getQuotaResult.nonProdConsumption:
- print_quota(quota_result.nonProdConsumption,
- 'Resources consumed by non-production jobs',
- role)
http://git-wip-us.apache.org/repos/asf/incubator-aurora/blob/9a817f24/src/main/python/apache/aurora/client/commands/help.py
----------------------------------------------------------------------
diff --git a/src/main/python/apache/aurora/client/commands/help.py b/src/main/python/apache/aurora/client/commands/help.py
deleted file mode 100644
index f79e971..0000000
--- a/src/main/python/apache/aurora/client/commands/help.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from __future__ import print_function
-
-import collections
-import sys
-
-from twitter.common import app
-
-from apache.aurora.client.base import die
-
-
-def make_commands_str(commands):
- commands.sort()
- if len(commands) == 1:
- return str(commands[0])
- elif len(commands) == 2:
- return '%s (or %s)' % (str(commands[0]), str(commands[1]))
- else:
- return '%s (or any of: %s)' % (str(commands[0]), ' '.join(map(str, commands[1:])))
-
-
-def generate_full_usage():
- docs_to_commands = collections.defaultdict(list)
- for (command, doc) in app.get_commands_and_docstrings():
- if doc is not None:
- docs_to_commands[doc].append(command)
- def make_docstring(item):
- (doc_text, commands) = item
- def format_line(line):
- return ' %s\n' % line.lstrip()
- stripped = ''.join(map(format_line, doc_text.splitlines()))
- return '%s\n%s' % (make_commands_str(commands), stripped)
- usage = sorted(map(make_docstring, docs_to_commands.items()))
- return 'Available commands:\n\n' + '\n'.join(usage)
-
-
-@app.command(name='help')
-def help_command(args):
- """usage: help [subcommand]
-
- Prints help for using the aurora client, or one of its specific subcommands.
- """
- if not args:
- print(generate_full_usage())
- sys.exit(0)
-
- if len(args) > 1:
- die('Please specify at most one subcommand.')
-
- subcmd = args[0]
- if subcmd in app.get_commands():
- app.command_parser(subcmd).print_help()
- else:
- print('Subcommand %s not found.' % subcmd)
- sys.exit(1)
http://git-wip-us.apache.org/repos/asf/incubator-aurora/blob/9a817f24/src/main/python/apache/aurora/client/commands/maintenance.py
----------------------------------------------------------------------
diff --git a/src/main/python/apache/aurora/client/commands/maintenance.py b/src/main/python/apache/aurora/client/commands/maintenance.py
deleted file mode 100644
index 5321eb6..0000000
--- a/src/main/python/apache/aurora/client/commands/maintenance.py
+++ /dev/null
@@ -1,137 +0,0 @@
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from twitter.common import app, log
-
-from apache.aurora.admin.admin_util import (
- FILENAME_OPTION,
- HOSTS_OPTION,
- OVERRIDE_SLA_DURATION_OPTION,
- OVERRIDE_SLA_PERCENTAGE_OPTION,
- OVERRIDE_SLA_REASON_OPTION,
- parse_and_validate_sla_overrides,
- parse_hostnames,
- parse_script,
- POST_DRAIN_SCRIPT_OPTION,
- UNSAFE_SLA_HOSTS_FILE_OPTION
-)
-from apache.aurora.admin.host_maintenance import HostMaintenance
-from apache.aurora.client.base import get_grouping_or_die, GROUPING_OPTION, requires
-from apache.aurora.common.clusters import CLUSTERS
-
-
-@app.command
-@app.command_option(FILENAME_OPTION)
-@app.command_option(HOSTS_OPTION)
-@requires.exactly('cluster')
-def host_deactivate(cluster):
- """usage: host_deactivate {--filename=filename | --hosts=hosts}
- cluster
-
- Puts hosts into maintenance mode.
-
- The list of hosts is marked for maintenance, and will be de-prioritized
- from consideration for scheduling. Note, they are not removed from
- consideration, and may still schedule tasks if resources are very scarce.
- Usually you would mark a larger set of machines for drain, and then do
- them in batches within the larger set, to help drained tasks not land on
- future hosts that will be drained shortly in subsequent batches.
- """
- options = app.get_options()
- HostMaintenance(CLUSTERS[cluster], options.verbosity).start_maintenance(
- parse_hostnames(options.filename, options.hosts))
-
-
-@app.command
-@app.command_option(FILENAME_OPTION)
-@app.command_option(HOSTS_OPTION)
-@requires.exactly('cluster')
-def host_activate(cluster):
- """usage: host_activate {--filename=filename | --hosts=hosts}
- cluster
-
- Removes maintenance mode from hosts.
-
- The list of hosts is marked as not in a drained state anymore. This will
- allow normal scheduling to resume on the given list of hosts.
- """
- options = app.get_options()
- HostMaintenance(CLUSTERS[cluster], options.verbosity).end_maintenance(
- parse_hostnames(options.filename, options.hosts))
-
-
-@app.command
-@app.command_option(FILENAME_OPTION)
-@app.command_option(HOSTS_OPTION)
-@app.command_option(POST_DRAIN_SCRIPT_OPTION)
-@app.command_option(GROUPING_OPTION)
-@app.command_option(OVERRIDE_SLA_PERCENTAGE_OPTION)
-@app.command_option(OVERRIDE_SLA_DURATION_OPTION)
-@app.command_option(OVERRIDE_SLA_REASON_OPTION)
-@app.command_option(UNSAFE_SLA_HOSTS_FILE_OPTION)
-@requires.exactly('cluster')
-def host_drain(cluster):
- """usage: host_drain {--filename=filename | --hosts=hosts}
- [--post_drain_script=path]
- [--grouping=function]
- [--override_percentage=percentage]
- [--override_duration=duration]
- [--override_reason=reason]
- [--unsafe_hosts_file=unsafe_hosts_filename]
- cluster
-
- Asks the scheduler to start maintenance on the list of provided hosts (see host_deactivate
- for more details) and drains any active tasks on them.
-
- The list of hosts is drained and marked in a drained state. This will kill
- off any tasks currently running on these hosts, as well as prevent future
- tasks from scheduling on these hosts while they are drained.
-
- The hosts are left in maintenance mode upon completion. Use host_activate to
- return hosts back to service and allow scheduling tasks on them.
- """
- options = app.get_options()
- drainable_hosts = parse_hostnames(options.filename, options.hosts)
- get_grouping_or_die(options.grouping)
-
- override_percentage, override_duration = parse_and_validate_sla_overrides(
- options,
- drainable_hosts)
-
- post_drain_callback = parse_script(options.post_drain_script)
-
- HostMaintenance(CLUSTERS[cluster], options.verbosity).perform_maintenance(
- drainable_hosts,
- grouping_function=options.grouping,
- percentage=override_percentage,
- duration=override_duration,
- output_file=options.unsafe_hosts_filename,
- callback=post_drain_callback)
-
-
-@app.command
-@app.command_option(FILENAME_OPTION)
-@app.command_option(HOSTS_OPTION)
-@requires.exactly('cluster')
-def host_status(cluster):
- """usage: host_status {--filename=filename | --hosts=hosts}
- cluster
-
- Print the drain status of each supplied host.
- """
- options = app.get_options()
- checkable_hosts = parse_hostnames(options.filename, options.hosts)
- statuses = HostMaintenance(CLUSTERS[cluster], options.verbosity).check_status(checkable_hosts)
- for pair in statuses:
- log.info("%s is in state: %s" % pair)
http://git-wip-us.apache.org/repos/asf/incubator-aurora/blob/9a817f24/src/main/python/apache/aurora/client/commands/run.py
----------------------------------------------------------------------
diff --git a/src/main/python/apache/aurora/client/commands/run.py b/src/main/python/apache/aurora/client/commands/run.py
deleted file mode 100644
index 6844ac3..0000000
--- a/src/main/python/apache/aurora/client/commands/run.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from twitter.common import app
-
-from apache.aurora.client.api.command_runner import DistributedCommandRunner
-from apache.aurora.client.base import die
-from apache.aurora.client.options import EXECUTOR_SANDBOX_OPTION, SSH_USER_OPTION
-from apache.aurora.common.aurora_job_key import AuroraJobKey
-from apache.aurora.common.clusters import CLUSTERS
-
-
-# duplicate of same function in core.py; since this is a temporary deprecation warning,
-# we don't want to add new source files or inter-source dependencies. Duplicating this
-# two-line function is the lesser evil.
-def v1_deprecation_warning(old, new):
- print("WARNING: %s is an aurora clientv1 command which will be deprecated soon" % old)
- print("To run this command using clientv2, use 'aurora %s'" % " ".join(new))
-
-
-@app.command
-@app.command_option('-t', '--threads', type=int, default=1, dest='num_threads',
- help='The number of threads to use.')
-@app.command_option(SSH_USER_OPTION)
-@app.command_option(EXECUTOR_SANDBOX_OPTION)
-def run(args, options):
- """usage: run cluster/role/env/job cmd
-
- Runs a shell command on all machines currently hosting shards of a single job.
-
- This feature supports the same command line wildcards that are used to
- populate a job's commands.
-
- This means anything in the {{mesos.*}} and {{thermos.*}} namespaces.
- """
- # TODO(William Farner): Add support for invoking on individual shards.
- # TODO(Kevin Sweeney): Restore the ability to run across jobs with globs (See MESOS-3010).
- if not args:
- die('job path is required')
- job_path = args.pop(0)
- new_cmd = ["task", "run"]
- if options.num_threads != 1:
- new_cmd.append("--threads=%s" % options.num_threads)
- if options.ssh_user is not None:
- new_cmd.append("--ssh-user=%s" % options.ssh_user)
- if options.executor_sandbox:
- new_cmd.append("--executor-sandbox")
- new_cmd.append("\"%s\"" % " ".join(args))
- v1_deprecation_warning("ssh", new_cmd)
-
- try:
- cluster_name, role, env, name = AuroraJobKey.from_path(job_path)
- except AuroraJobKey.Error as e:
- die('Invalid job path "%s": %s' % (job_path, e))
-
- command = ' '.join(args)
- cluster = CLUSTERS[cluster_name]
- dcr = DistributedCommandRunner(cluster, role, env, [name], options.ssh_user)
- dcr.run(command, parallelism=options.num_threads, executor_sandbox=options.executor_sandbox)
http://git-wip-us.apache.org/repos/asf/incubator-aurora/blob/9a817f24/src/main/python/apache/aurora/client/commands/ssh.py
----------------------------------------------------------------------
diff --git a/src/main/python/apache/aurora/client/commands/ssh.py b/src/main/python/apache/aurora/client/commands/ssh.py
deleted file mode 100644
index ab6832c..0000000
--- a/src/main/python/apache/aurora/client/commands/ssh.py
+++ /dev/null
@@ -1,101 +0,0 @@
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import subprocess
-
-from twitter.common import app
-
-from apache.aurora.client.api.command_runner import DistributedCommandRunner
-from apache.aurora.client.base import AURORA_V1_USER_AGENT_NAME, check_and_log_response, die
-from apache.aurora.client.factory import make_client
-from apache.aurora.client.options import EXECUTOR_SANDBOX_OPTION, SSH_USER_OPTION
-from apache.aurora.common.aurora_job_key import AuroraJobKey
-
-
-# duplicate of same function in core.py; since this is a temporary deprecation warning,
-# we don't want to add new source files or inter-source dependencies. Duplicating this
-# two-line function is the lesser evil.
-def v1_deprecation_warning(old, new):
- print("WARNING: %s is an aurora clientv1 command which will be deprecated soon" % old)
- print("To run this command using clientv2, use 'aurora %s'" % " ".join(new))
-
-
-@app.command
-@app.command_option(EXECUTOR_SANDBOX_OPTION)
-@app.command_option(SSH_USER_OPTION)
-@app.command_option('-L', dest='tunnels', action='append', metavar='PORT:NAME',
- default=[],
- help="Add tunnel from local port PORT to remote named port NAME.")
-def ssh(args, options):
- """usage: ssh cluster/role/env/job shard [args...]
-
- Initiate an SSH session on the machine that a shard is running on.
- """
- if not args:
- die('Job path is required')
- job_path = args.pop(0)
- try:
- cluster_name, role, env, name = AuroraJobKey.from_path(job_path)
- except AuroraJobKey.Error as e:
- die('Invalid job path "%s": %s' % (job_path, e))
- if not args:
- die('Shard is required')
- try:
- shard = int(args.pop(0))
- except ValueError:
- die('Shard must be an integer')
-
- newcmd = ["task", "ssh", "%s/%s" % (job_path, shard)]
- if len(options.tunnels) > 0:
- for t in options.tunnels:
- newcmd.append("--tunnels=%s" % t)
- if options.ssh_user is not None:
- newcmd.append("--ssh-user=%s" % options.ssh_user)
- if options.executor_sandbox:
- newcmd.append("--executor-sandbox")
- if len(args) > 0:
- newcmd.append("--command=\"%s\"" % " ".join(args))
- v1_deprecation_warning("ssh", newcmd)
-
- api = make_client(cluster_name, AURORA_V1_USER_AGENT_NAME)
- resp = api.query(api.build_query(role, name, set([int(shard)]), env=env))
- check_and_log_response(resp)
-
- if (resp.result.scheduleStatusResult.tasks is None or
- len(resp.result.scheduleStatusResult.tasks) == 0):
- die("Job %s not found" % job_path)
- first_task = resp.result.scheduleStatusResult.tasks[0]
- remote_cmd = 'bash' if not args else ' '.join(args)
- command = DistributedCommandRunner.substitute(remote_cmd, first_task,
- api.cluster, executor_sandbox=options.executor_sandbox)
-
- ssh_command = ['ssh', '-t']
-
- assigned = first_task.assignedTask
- role = assigned.task.job.role if assigned.task.job else assigned.task.owner.role
- slave_host = assigned.slaveHost
-
- for tunnel in options.tunnels:
- try:
- port, name = tunnel.split(':')
- port = int(port)
- except ValueError:
- die('Could not parse tunnel: %s. Must be of form PORT:NAME' % tunnel)
- if name not in assigned.assignedPorts:
- die('Task %s has no port named %s' % (assigned.taskId, name))
- ssh_command += [
- '-L', '%d:%s:%d' % (port, slave_host, assigned.assignedPorts[name])]
-
- ssh_command += ['%s@%s' % (options.ssh_user or role, slave_host), command]
- return subprocess.call(ssh_command)
http://git-wip-us.apache.org/repos/asf/incubator-aurora/blob/9a817f24/src/main/python/apache/aurora/client/options.py
----------------------------------------------------------------------
diff --git a/src/main/python/apache/aurora/client/options.py b/src/main/python/apache/aurora/client/options.py
deleted file mode 100644
index f43aced..0000000
--- a/src/main/python/apache/aurora/client/options.py
+++ /dev/null
@@ -1,245 +0,0 @@
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import optparse
-
-from apache.aurora.common.aurora_job_key import AuroraJobKey
-from apache.thermos.common.options import add_binding_to
-
-__all__ = (
- 'BATCH_OPTION',
- 'CLUSTER_CONFIG_OPTION',
- 'CLUSTER_INVOKE_OPTION',
- 'CLUSTER_NAME_OPTION',
- 'DISABLE_HOOKS_OPTION',
- 'ENVIRONMENT_BIND_OPTION',
- 'ENV_CONFIG_OPTION',
- 'EXECUTOR_SANDBOX_OPTION',
- 'FROM_JOBKEY_OPTION',
- 'HEALTH_CHECK_INTERVAL_SECONDS_OPTION',
- 'JSON_OPTION',
- 'MAX_FAILURES_OPTION',
- 'OPEN_BROWSER_OPTION',
- 'SHARDS_OPTION',
- 'SSH_USER_OPTION',
- 'WAIT_UNTIL_OPTION',
-)
-
-
-def add_verbosity_options():
- from twitter.common import app
- from twitter.common.log.options import LogOptions
-
- def set_quiet(option, _1, _2, parser):
- setattr(parser.values, option.dest, 'quiet')
- LogOptions.set_stderr_log_level('NONE')
-
- def set_verbose(option, _1, _2, parser):
- setattr(parser.values, option.dest, 'verbose')
- LogOptions.set_stderr_log_level('DEBUG')
-
- app.add_option('-v',
- dest='verbosity',
- default='normal',
- action='callback',
- callback=set_verbose,
- help='Verbose logging. (default: %default)')
-
- app.add_option('-q',
- dest='verbosity',
- default='normal',
- action='callback',
- callback=set_quiet,
- help='Quiet logging. (default: %default)')
-
-
-def parse_shards_into(option, opt, value, parser):
- """Parse lists of shard or shard ranges into a set().
-
- Examples:
- 0-2
- 0,1-3,5
- 1,3,5
- """
- def shard_range_parser(shards):
- result = set()
- for part in shards.split(','):
- x = part.split('-')
- result.update(range(int(x[0]), int(x[-1]) + 1))
- return sorted(result)
-
- try:
- setattr(parser.values, option.dest, shard_range_parser(value))
- except ValueError as e:
- raise optparse.OptionValueError('Failed to parse: %s' % e)
-
-
-def parse_aurora_job_key_into(option, opt, value, parser):
- try:
- setattr(parser.values, option.dest, AuroraJobKey.from_path(value))
- except AuroraJobKey.Error as e:
- raise optparse.OptionValueError('Failed to parse: %s' % e)
-
-
-def make_env_option(explanation):
- return optparse.Option(
- '--env',
- dest='env',
- default=None,
- help=explanation)
-
-# Note: in these predefined options, "OPTION" is used in names of optional arguments,
-# and "PARAMETER" is used in names of required ones.
-
-DISABLE_HOOKS_OPTION = optparse.Option(
- '--disable_all_hooks_reason',
- type=str,
- default=None,
- help='Override standard behavior and disable the builtin hooks')
-
-
-OPEN_BROWSER_OPTION = optparse.Option(
- '-o',
- '--open_browser',
- dest='open_browser',
- action='store_true',
- default=False,
- help='Open a browser window to the job page after a job mutation.')
-
-
-SHARDS_OPTION = optparse.Option(
- '--shards',
- type='string',
- dest='shards',
- default=None,
- action='callback',
- callback=parse_shards_into,
- help='A list of shard ids to act on. Can either be a comma-separated list (e.g. 0,1,2) '
- 'or a range (e.g. 0-2) or any combination of the two (e.g. 0-2,5,7-9). If not set, '
- 'all shards will be acted on.')
-
-
-BATCH_OPTION = optparse.Option(
- '--batch_size', type='int', dest='batch_size', default=None,
- help='The maximum number of instances to act on at a time')
-
-
-MAX_FAILURES_OPTION = optparse.Option(
- '--max_total_failures',
- type='int',
- default=1,
- help='The maximum number of errors in a batch operation before the operation should abort')
-
-
-FROM_JOBKEY_OPTION = optparse.Option('--from', dest='rename_from', type='string', default=None,
- metavar='CLUSTER/ROLE/ENV/JOB', action='callback', callback=parse_aurora_job_key_into,
- help='Job key to diff against.')
-
-
-JSON_OPTION = optparse.Option(
- '-j',
- '--json',
- dest='json',
- default=False,
- action='store_true',
- help='If specified, configuration is read in JSON format.')
-
-
-CLUSTER_CONFIG_OPTION = optparse.Option(
- '--cluster',
- dest='cluster',
- default=None,
- type='string',
- help='Cluster to match when selecting a job from a configuration. Optional if only one job '
- 'matching the given job name exists in the config.')
-
-
-CLUSTER_INVOKE_OPTION = optparse.Option(
- '--cluster',
- dest='cluster',
- default=None,
- type='string',
- help='Cluster to invoke this command against. Deprecated in favor of the CLUSTER/ROLE/ENV/NAME '
- 'syntax.')
-
-
-CLUSTER_NAME_OPTION = optparse.Option(
- '--cluster',
- dest='cluster',
- default=None,
- type='string',
- help='Cluster to invoke this command against.')
-
-
-ENV_CONFIG_OPTION = make_env_option(
- 'Environment to match when selecting a job from a configuration.')
-
-
-# This is for binding arbitrary points in the Thermos namespace to specific strings, e.g.
-# if a Thermos configuration has {{jvm.version}}, it can be bound explicitly from the
-# command-line with, for example, -E jvm.version=7
-ENVIRONMENT_BIND_OPTION = optparse.Option(
- '-E',
- type='string',
- nargs=1,
- action='callback',
- default=[],
- metavar='NAME=VALUE',
- callback=add_binding_to('bindings'),
- dest='bindings',
- help='Bind a thermos mustache variable name to a value. '
- 'Multiple flags may be used to specify multiple values.')
-
-
-EXECUTOR_SANDBOX_OPTION = optparse.Option(
- '-e',
- '--executor_sandbox',
- action='store_true',
- default=False,
- dest='executor_sandbox',
- help='Run the command in the executor sandbox instead of the task sandbox.')
-
-
-SSH_USER_OPTION = optparse.Option(
- '--user',
- dest='ssh_user',
- default=None,
- help="ssh as this user instead of the role.")
-
-
-CREATE_STATES = (
- 'PENDING',
- 'RUNNING',
- 'FINISHED'
-)
-
-
-WAIT_UNTIL_OPTION = optparse.Option(
- '--wait_until',
- default='PENDING',
- type='choice',
- choices=('PENDING', 'RUNNING', 'FINISHED'),
- metavar='STATE',
- dest='wait_until',
- help='Block the client until all the tasks have transitioned into the '
- 'requested state. Options: %s. Default: %%default' % (', '.join(CREATE_STATES)))
-
-
-HEALTH_CHECK_INTERVAL_SECONDS_OPTION = optparse.Option(
- '--updater_health_check_interval_seconds',
- dest='health_check_interval_seconds',
- type=int,
- default=3,
- help='Time interval between subsequent shard status checks.'
-)
http://git-wip-us.apache.org/repos/asf/incubator-aurora/blob/9a817f24/src/test/python/apache/aurora/__init__.py
----------------------------------------------------------------------
diff --git a/src/test/python/apache/aurora/__init__.py b/src/test/python/apache/aurora/__init__.py
new file mode 100644
index 0000000..0663a9a
--- /dev/null
+++ b/src/test/python/apache/aurora/__init__.py
@@ -0,0 +1,13 @@
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
http://git-wip-us.apache.org/repos/asf/incubator-aurora/blob/9a817f24/src/test/python/apache/aurora/admin/BUILD
----------------------------------------------------------------------
diff --git a/src/test/python/apache/aurora/admin/BUILD b/src/test/python/apache/aurora/admin/BUILD
index 3a21680..89cd875 100644
--- a/src/test/python/apache/aurora/admin/BUILD
+++ b/src/test/python/apache/aurora/admin/BUILD
@@ -14,14 +14,32 @@
python_test_suite(name = 'all',
dependencies = [
+ ':admin',
':host_maintenance',
- ':admin_util',
+ ':maintenance'
+ ],
+)
+
+python_tests(
+ name='admin',
+ sources = [
+ 'test_admin.py',
+ 'test_admin_sla.py',
+ 'test_admin_util.py',
+ ],
+ dependencies = [
+ ':util',
+ '3rdparty/python:mock',
+ '3rdparty/python:twitter.common.contextutil',
+ 'src/main/python/apache/aurora/admin:admin',
+ 'api/src/main/thrift/org/apache/aurora/gen:py-thrift',
],
)
python_tests(name = 'host_maintenance',
sources = ['test_host_maintenance.py'],
dependencies = [
+ ':util',
'3rdparty/python:mock',
'3rdparty/python:twitter.common.log',
'3rdparty/python:twitter.common.quantity',
@@ -32,13 +50,25 @@ python_tests(name = 'host_maintenance',
],
)
-python_tests(name = 'admin_util',
- sources = ['test_admin_util.py'],
+python_tests(
+ name='maintenance',
+ sources = [
+ 'test_maintenance.py',
+ ],
dependencies = [
+ ':util',
'3rdparty/python:mock',
- '3rdparty/python:twitter.common.quantity',
- '3rdparty/python:twitter.common.contextutil',
- 'src/main/python/apache/aurora/admin:util',
+ 'src/main/python/apache/aurora/admin:maintenance',
],
)
+python_library(
+ name='util',
+ sources = [ 'util.py' ],
+ dependencies = [
+ '3rdparty/python:mock',
+ 'src/main/python/apache/aurora/client/hooks:hooks',
+ 'api/src/main/thrift/org/apache/aurora/gen:py-thrift',
+ 'src/main/python/apache/aurora/client:config',
+ ],
+)
http://git-wip-us.apache.org/repos/asf/incubator-aurora/blob/9a817f24/src/test/python/apache/aurora/admin/__init__.py
----------------------------------------------------------------------
diff --git a/src/test/python/apache/aurora/admin/__init__.py b/src/test/python/apache/aurora/admin/__init__.py
new file mode 100644
index 0000000..0663a9a
--- /dev/null
+++ b/src/test/python/apache/aurora/admin/__init__.py
@@ -0,0 +1,13 @@
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
http://git-wip-us.apache.org/repos/asf/incubator-aurora/blob/9a817f24/src/test/python/apache/aurora/admin/test_admin.py
----------------------------------------------------------------------
diff --git a/src/test/python/apache/aurora/admin/test_admin.py b/src/test/python/apache/aurora/admin/test_admin.py
new file mode 100644
index 0000000..4e34ef1
--- /dev/null
+++ b/src/test/python/apache/aurora/admin/test_admin.py
@@ -0,0 +1,258 @@
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import contextlib
+
+from mock import create_autospec, patch, PropertyMock
+
+from apache.aurora.admin.admin import get_locks, get_scheduler, increase_quota, query, set_quota
+from apache.aurora.client.api import AuroraClientAPI
+from apache.aurora.client.api.scheduler_client import SchedulerClient, SchedulerProxy
+
+from .util import AuroraClientCommandTest
+
+from gen.apache.aurora.api.ttypes import (
+ AssignedTask,
+ GetLocksResult,
+ GetQuotaResult,
+ Identity,
+ JobKey,
+ Lock,
+ LockKey,
+ ResourceAggregate,
+ Response,
+ ResponseCode,
+ ResponseDetail,
+ Result,
+ ScheduledTask,
+ ScheduleStatus,
+ ScheduleStatusResult,
+ TaskConfig,
+ TaskQuery
+)
+
+
+class TestQueryCommand(AuroraClientCommandTest):
+
+ @classmethod
+ def setup_mock_options(cls, force=False, shards=None, states='RUNNING', listformat=None):
+ mock_options = create_autospec(
+ spec=['force', 'shards', 'states', 'listformat', 'verbosity'],
+ spec_set=False,
+ instance=True)
+ mock_options.force = force
+ mock_options.shards = shards
+ mock_options.states = states
+ mock_options.listformat = listformat or '%role%/%jobName%/%instanceId% %status%'
+ mock_options.verbosity = False
+ return mock_options
+
+ @classmethod
+ def create_response(cls, tasks, response_code=ResponseCode.OK):
+ return Response(
+ responseCode=response_code,
+ details=[ResponseDetail(message='test')],
+ result=Result(scheduleStatusResult=ScheduleStatusResult(tasks=tasks)))
+
+ @classmethod
+ def create_task(cls):
+ return [ScheduledTask(
+ assignedTask=AssignedTask(
+ instanceId=0,
+ task=TaskConfig(owner=Identity(role='test_role'), jobName='test_job')),
+ status=ScheduleStatus.RUNNING
+ )]
+
+ @classmethod
+ def task_query(cls):
+ return TaskQuery(
+ role='test_role',
+ jobName='test_job',
+ instanceIds=set([0]),
+ statuses=set([ScheduleStatus.RUNNING]))
+
+ def test_query(self):
+ """Tests successful execution of the query command."""
+ mock_options = self.setup_mock_options(force=True, shards="0")
+ with contextlib.nested(
+ patch('twitter.common.app.get_options', return_value=mock_options),
+ patch('apache.aurora.admin.admin.make_admin_client',
+ return_value=create_autospec(spec=AuroraClientAPI)),
+ patch('apache.aurora.admin.admin.CLUSTERS', new=self.TEST_CLUSTERS)
+ ) as (_, mock_make_admin_client, _):
+
+ api = mock_make_admin_client.return_value
+ api.query.return_value = self.create_response(self.create_task())
+
+ query([self.TEST_CLUSTER, 'test_role', 'test_job'], mock_options)
+
+ api.query.assert_called_with(self.task_query())
+
+ def test_query_fails(self):
+ """Tests failed execution of the query command."""
+ mock_options = self.setup_mock_options(shards="0")
+ with contextlib.nested(
+ patch('twitter.common.app.get_options', return_value=mock_options),
+ patch('apache.aurora.admin.admin.make_admin_client',
+ return_value=create_autospec(spec=AuroraClientAPI)),
+ patch('apache.aurora.admin.admin.CLUSTERS', new=self.TEST_CLUSTERS)
+ ) as (_, mock_make_admin_client, _):
+
+ api = mock_make_admin_client.return_value
+ api.query.return_value = self.create_response(self.create_task())
+
+ try:
+ query([self.TEST_CLUSTER, 'test_role', 'test_job'], mock_options)
+ except SystemExit:
+ pass
+ else:
+ assert 'Expected exception is not raised'
+
+ api.query.assert_called_with(self.task_query())
+
+
+class TestIncreaseQuotaCommand(AuroraClientCommandTest):
+
+ @classmethod
+ def create_response(cls, quota, prod, non_prod, response_code=ResponseCode.OK):
+ return Response(
+ responseCode=response_code,
+ details=[ResponseDetail(message='test')],
+ result=Result(getQuotaResult=GetQuotaResult(
+ quota=quota, prodConsumption=prod, nonProdConsumption=non_prod))
+ )
+
+ def test_increase_quota(self):
+ """Tests successful execution of the increase_quota command."""
+ mock_options = self.setup_mock_options()
+ with contextlib.nested(
+ patch('twitter.common.app.get_options', return_value=mock_options),
+ patch('apache.aurora.admin.admin.make_admin_client',
+ return_value=create_autospec(spec=AuroraClientAPI)),
+ patch('apache.aurora.admin.admin.CLUSTERS', new=self.TEST_CLUSTERS)
+ ) as (_, mock_make_admin_client, _):
+
+ api = mock_make_admin_client.return_value
+ role = 'test_role'
+ api.get_quota.return_value = self.create_response(
+ ResourceAggregate(20.0, 4000, 6000),
+ ResourceAggregate(15.0, 2000, 3000),
+ ResourceAggregate(6.0, 200, 600),
+ )
+ api.set_quota.return_value = self.create_simple_success_response()
+
+ increase_quota([self.TEST_CLUSTER, role, '4.0', '1MB', '1MB'])
+
+ api.set_quota.assert_called_with(role, 24.0, 4001, 6001)
+ assert type(api.set_quota.call_args[0][1]) == type(float())
+ assert type(api.set_quota.call_args[0][2]) == type(int())
+ assert type(api.set_quota.call_args[0][3]) == type(int())
+
+
+class TestSetQuotaCommand(AuroraClientCommandTest):
+
+ @classmethod
+ def create_response(cls, quota, prod, non_prod, response_code=None):
+ response_code = ResponseCode.OK if response_code is None else response_code
+ resp = Response(responseCode=response_code, details=[ResponseDetail(message='test')])
+ resp.result = Result(getQuotaResult=GetQuotaResult(
+ quota=quota, prodConsumption=prod, nonProdConsumption=non_prod))
+ return resp
+
+ def test_set_quota(self):
+ """Tests successful execution of the set_quota command."""
+ mock_options = self.setup_mock_options()
+ with contextlib.nested(
+ patch('twitter.common.app.get_options', return_value=mock_options),
+ patch('apache.aurora.admin.admin.make_admin_client',
+ return_value=create_autospec(spec=AuroraClientAPI)),
+ patch('apache.aurora.admin.admin.CLUSTERS', new=self.TEST_CLUSTERS)
+ ) as (_, mock_make_admin_client, _):
+
+ api = mock_make_admin_client.return_value
+ role = 'test_role'
+ api.set_quota.return_value = self.create_simple_success_response()
+
+ set_quota([self.TEST_CLUSTER, role, '4.0', '10MB', '10MB'])
+
+ api.set_quota.assert_called_with(role, 4.0, 10, 10)
+ assert type(api.set_quota.call_args[0][1]) == type(float())
+ assert type(api.set_quota.call_args[0][2]) == type(int())
+ assert type(api.set_quota.call_args[0][3]) == type(int())
+
+
+class TestGetLocksCommand(AuroraClientCommandTest):
+
+ MESSAGE = 'test message'
+ USER = 'test user'
+ LOCKS = [Lock(
+ key=LockKey(job=JobKey('role', 'env', 'name')),
+ token='test token',
+ user=USER,
+ timestampMs='300',
+ message=MESSAGE)]
+
+ @classmethod
+ def create_response(cls, locks, response_code=None):
+ response_code = ResponseCode.OK if response_code is None else response_code
+ resp = Response(responseCode=response_code, details=[ResponseDetail(message='test')])
+ resp.result = Result(getLocksResult=GetLocksResult(locks=locks))
+ return resp
+
+ def test_get_locks(self):
+ """Tests successful execution of the get_locks command."""
+ mock_options = self.setup_mock_options()
+ with contextlib.nested(
+ patch('twitter.common.app.get_options', return_value=mock_options),
+ patch('apache.aurora.admin.admin.make_admin_client',
+ return_value=create_autospec(spec=AuroraClientAPI)),
+ patch('apache.aurora.admin.admin.CLUSTERS', new=self.TEST_CLUSTERS),
+ patch('apache.aurora.admin.admin.print_results'),
+ ) as (_, mock_make_admin_client, _, mock_print_results):
+
+ api = mock_make_admin_client.return_value
+ api.get_locks.return_value = self.create_response(self.LOCKS)
+
+ get_locks([self.TEST_CLUSTER])
+
+ assert api.get_locks.call_count == 1
+ assert mock_print_results.call_count == 1
+ assert "'message': '%s'" % self.MESSAGE in mock_print_results.call_args[0][0][0]
+ assert "'user': '%s'" % self.USER in mock_print_results.call_args[0][0][0]
+
+
+class TestGetSchedulerCommand(AuroraClientCommandTest):
+
+ def test_get_scheduler(self):
+ """Tests successful execution of the get_scheduler command."""
+ mock_options = self.setup_mock_options()
+ mock_proxy = create_autospec(spec=SchedulerProxy, instance=True)
+ mock_scheduler_client = create_autospec(spec=SchedulerClient, instance=True)
+ mock_raw_url = PropertyMock(return_value="url")
+ mock_proxy.scheduler_client.return_value = mock_scheduler_client
+ mock_scheduler_client.raw_url = mock_raw_url
+
+ with contextlib.nested(
+ patch('twitter.common.app.get_options', return_value=mock_options),
+ patch('apache.aurora.admin.admin.make_admin_client',
+ return_value=create_autospec(spec=AuroraClientAPI)),
+ patch('apache.aurora.admin.admin.CLUSTERS', new=self.TEST_CLUSTERS),
+ ) as (_, mock_make_admin_client, _):
+
+ api = mock_make_admin_client.return_value
+ api.scheduler_proxy = PropertyMock(return_value=mock_proxy)
+
+ get_scheduler([self.TEST_CLUSTER])
+
+ mock_raw_url.assert_called_once()