コード例 #1
0
ファイル: test_status.py プロジェクト: kevints/aurora
 def test_successful_status_output_no_metadata(self):
   """Test the status command more deeply: in a request with a fully specified
   job, it should end up doing a query using getTasksWithoutConfigs."""
   mock_context = FakeAuroraCommandContext()
   mock_context.add_expected_status_query_result(self.create_status_null_metadata())
   with contextlib.nested(
       patch('apache.aurora.client.cli.jobs.Job.create_context', return_value=mock_context),
       patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS)):
     cmd = AuroraCommandLine()
     cmd.execute(['job', 'status', 'west/bozo/test/hello'])
     actual = re.sub("\\d\\d:\\d\\d:\\d\\d", "##:##:##", '\n'.join(mock_context.get_out()))
     expected = textwrap.dedent("""\
         Active tasks (3):
         \tTask role: bozo, env: test, name: woops, instance: 1, status: RUNNING on slavehost
         \t  cpus: 2, ram: 2 MB, disk: 2 MB
         \t  events:
         \t   1970-11-23 ##:##:## RUNNING: Hi there
         \tTask role: bozo, env: test, name: woops, instance: 2, status: RUNNING on slavehost
         \t  cpus: 2, ram: 2 MB, disk: 2 MB
         \t  events:
         \t   1970-11-23 ##:##:## RUNNING: Hi there
         \tTask role: bozo, env: test, name: woops, instance: 3, status: RUNNING on slavehost
         \t  cpus: 2, ram: 2 MB, disk: 2 MB
         \t  events:
         \t   1970-11-23 ##:##:## RUNNING: Hi there
         Inactive tasks (0):
         """)
     assert actual == expected
コード例 #2
0
  def test_killall_job(self):
    """Test kill client-side API logic."""
    mock_context = FakeAuroraCommandContext()
    mock_scheduler_proxy = create_autospec(spec=SchedulerThriftApiSpec, instance=True)
    with contextlib.nested(
        patch('threading._Event.wait'),
        patch('apache.aurora.client.cli.jobs.Job.create_context', return_value=mock_context),
        patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS)):

      api = mock_context.get_api('west')
      mock_scheduler_proxy.getTasksWithoutConfigs.return_value = self.create_status_call_result()
      api.kill_job.return_value = self.get_kill_job_response()
      mock_scheduler_proxy.killTasks.return_value = self.get_kill_job_response()
      mock_context.add_expected_status_query_result(self.create_status_call_result(
          self.create_mock_task(ScheduleStatus.KILLED)))
      with temporary_file() as fp:
        fp.write(self.get_valid_config())
        fp.flush()
        cmd = AuroraCommandLine()
        cmd.execute(['job', 'killall', '--no-batching', '--config=%s' % fp.name,
            'west/bozo/test/hello'])

      # Now check that the right API calls got made.
      assert api.kill_job.call_count == 1
      api.kill_job.assert_called_with(AuroraJobKey.from_path('west/bozo/test/hello'), None)
      self.assert_scheduler_called(api, self.get_expected_task_query(), 2)
コード例 #3
0
ファイル: test_status.py プロジェクト: kevints/aurora
  def test_status_wildcard(self):
    """Test status using a wildcard. It should first call api.get_jobs, and then do a
    getTasksWithoutConfigs on each job."""
    mock_context = FakeAuroraCommandContext()
    mock_api = mock_context.get_api('west')
    mock_api.check_status.return_value = self.create_status_response()
    mock_api.get_jobs.return_value = self.create_getjobs_response()
    with contextlib.nested(
        patch('apache.aurora.client.cli.jobs.Job.create_context', return_value=mock_context),
        patch('apache.aurora.client.cli.context.CLUSTERS', new=self.TEST_CLUSTERS)):
      cmd = AuroraCommandLine()
      cmd.execute(['job', 'status', '*'])

    # Wildcard should have expanded to two jobs, so there should be two calls
    # to check_status.
    assert mock_api.check_status.call_count == 2

    assert mock_api.check_status.call_args_list[0][0][0].cluster == 'west'
    assert mock_api.check_status.call_args_list[0][0][0].role == 'RoleA'
    assert mock_api.check_status.call_args_list[0][0][0].env == 'test'
    assert mock_api.check_status.call_args_list[0][0][0].name == 'hithere'

    assert mock_api.check_status.call_args_list[1][0][0].cluster == 'west'
    assert mock_api.check_status.call_args_list[1][0][0].role == 'bozo'
    assert mock_api.check_status.call_args_list[1][0][0].env == 'test'
    assert mock_api.check_status.call_args_list[1][0][0].name == 'hello'
コード例 #4
0
ファイル: test_diff.py プロジェクト: bhuvan/incubator-aurora
  def test_successful_diff(self):
    """Test the diff command."""
    (mock_api, mock_scheduler_proxy) = self.create_mock_api()
    with contextlib.nested(
        patch('apache.aurora.client.api.SchedulerProxy', return_value=mock_scheduler_proxy),
        patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS),
        patch('subprocess.call', return_value=0),
        patch('json.loads', return_value=Mock())) as (_, _, subprocess_patch, _):
      mock_scheduler_proxy.getTasksStatus.return_value = self.create_status_response()
      self.setup_populate_job_config(mock_scheduler_proxy)
      with temporary_file() as fp:
        fp.write(self.get_valid_config())
        fp.flush()
        cmd = AuroraCommandLine()
        cmd.execute(['job', 'diff', 'west/bozo/test/hello', fp.name])

        # Diff should get the task status, populate a config, and run diff.
        mock_scheduler_proxy.getTasksStatus.assert_called_with(
            TaskQuery(jobName='hello', environment='test', owner=Identity(role='bozo'),
                statuses=ACTIVE_STATES))
        assert mock_scheduler_proxy.populateJobConfig.call_count == 1
        assert isinstance(mock_scheduler_proxy.populateJobConfig.call_args[0][0], JobConfiguration)
        assert (mock_scheduler_proxy.populateJobConfig.call_args[0][0].key ==
            JobKey(environment=u'test', role=u'bozo', name=u'hello'))
        # Subprocess should have been used to invoke diff with two parameters.
        assert subprocess_patch.call_count == 1
        assert len(subprocess_patch.call_args[0][0]) == 3
        assert subprocess_patch.call_args[0][0][0] == os.environ.get('DIFF_VIEWER', 'diff')
コード例 #5
0
 def test_restart_failed_restart_output(self):
   self.reset_mock_io()
   (mock_api, mock_scheduler_proxy) = self.create_mock_api()
   mock_health_check = self.setup_health_checks(mock_api)
   self.setup_mock_scheduler_for_simple_restart(mock_api)
   mock_scheduler_proxy.restartShards.return_value = self.create_error_response()
   with contextlib.nested(
       patch('apache.aurora.client.api.SchedulerProxy', return_value=mock_scheduler_proxy),
       patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS),
       patch('apache.aurora.client.api.instance_watcher.StatusHealthCheck',
           return_value=mock_health_check),
       patch('time.time', side_effect=functools.partial(self.fake_time, self)),
       patch('apache.aurora.client.cli.context.AuroraCommandContext.print_out',
           side_effect=self.mock_print_out),
       patch('apache.aurora.client.cli.context.AuroraCommandContext.print_err',
           side_effect=self.mock_print_err),
       patch('threading._Event.wait')):
     with temporary_file() as fp:
       fp.write(self.get_valid_config())
       fp.flush()
       cmd = AuroraCommandLine()
       cmd.execute(['job', 'restart', '--batch-size=5', 'west/bozo/test/hello',
           '--config', fp.name])
     assert self.MOCK_OUT == []
     assert "Error restarting job west/bozo/test/hello:" in self.MOCK_ERR
コード例 #6
0
  def test_kill_job_with_instances_batched_large(self):
    """Test kill client-side API logic."""
    mock_context = FakeAuroraCommandContext()
    with contextlib.nested(
        patch('threading._Event.wait'),
        patch('apache.aurora.client.cli.jobs.Job.create_context', return_value=mock_context),
        patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS)):
      api = mock_context.get_api('west')
      status_result = self.create_status_call_result()
      mock_context.add_expected_status_query_result(status_result)
      api.kill_job.return_value = self.get_kill_job_response()
      mock_context.add_expected_status_query_result(self.create_status_call_result(
          self.create_mock_task(ScheduleStatus.KILLED)))

      with temporary_file() as fp:
        fp.write(self.get_valid_config())
        fp.flush()
        cmd = AuroraCommandLine()
        cmd.execute(['job', 'kill', '--config=%s' % fp.name, 'west/bozo/test/hello/0,2,4-13'])

      # Now check that the right API calls got made.
      assert api.kill_job.call_count == 3
      api.kill_job.assert_called_with(AuroraJobKey.from_path('west/bozo/test/hello'),
          [12, 13])
      # Expect total 5 calls (3 from JobMonitor).
      self.assert_scheduler_called(api, self.get_expected_task_query([12, 13]), 5)
コード例 #7
0
ファイル: test_update.py プロジェクト: rowoot/aurora
 def test_updater_simple_small_doesnt_warn(self):
     mock_out = IOMock()
     mock_err = IOMock()
     (mock_api, mock_scheduler_proxy) = self.create_mock_api()
     mock_health_check = self.setup_health_checks(mock_api)
     mock_quota_check = self.setup_quota_check()
     mock_job_monitor = self.setup_job_monitor()
     fake_mux = self.FakeSchedulerMux()
     self.setup_mock_scheduler_for_simple_update(mock_api)
     with contextlib.nested(
         patch("apache.aurora.client.cli.jobs.AuroraCommandContext.print_out", side_effect=mock_out.put),
         patch("apache.aurora.client.cli.jobs.AuroraCommandContext.print_err", side_effect=mock_err.put),
         patch("apache.aurora.client.api.SchedulerProxy", return_value=mock_scheduler_proxy),
         patch("apache.aurora.client.api.instance_watcher.StatusHealthCheck", return_value=mock_health_check),
         patch("apache.aurora.client.api.updater.JobMonitor", return_value=mock_job_monitor),
         patch("apache.aurora.client.api.updater.QuotaCheck", return_value=mock_quota_check),
         patch("apache.aurora.client.api.updater.SchedulerMux", return_value=fake_mux),
         patch("time.time", side_effect=functools.partial(self.fake_time, self)),
         patch("time.sleep", return_value=None),
         patch("threading._Event.wait"),
     ):
         with temporary_file() as fp:
             fp.write(self.get_service_config())
             fp.flush()
             cmd = AuroraCommandLine()
             cmd.execute(["job", "update", "west/bozo/test/hello", fp.name])
         assert mock_out.get() == ["Update completed successfully"]
         assert mock_err.get() == [CLIENT_UPDATER_DEPRECATION]
コード例 #8
0
ファイル: test_status.py プロジェクト: bmhatfield/aurora
 def test_successful_status_output_no_metadata(self):
     """Test the status command more deeply: in a request with a fully specified
 job, it should end up doing a query using getTasksWithoutConfigs."""
     mock_context = FakeAuroraCommandContext()
     mock_context.add_expected_status_query_result(self.create_status_null_metadata())
     with patch("apache.aurora.client.cli.jobs.Job.create_context", return_value=mock_context):
         cmd = AuroraCommandLine()
         cmd.execute(["job", "status", "west/bozo/test/hello"])
         actual = re.sub("\\d\\d:\\d\\d:\\d\\d", "##:##:##", "\n".join(mock_context.get_out()))
         expected = textwrap.dedent(
             """\
       Active tasks (3):
       \tTask role: bozo, env: test, name: woops, instance: 1, status: RUNNING on slavehost
       \t  CPU: 2 core(s), RAM: 2 MB, Disk: 2 MB
       \t  events:
       \t   1970-11-23 ##:##:## RUNNING: Hi there
       \tTask role: bozo, env: test, name: woops, instance: 2, status: RUNNING on slavehost
       \t  CPU: 2 core(s), RAM: 2 MB, Disk: 2 MB
       \t  events:
       \t   1970-11-23 ##:##:## RUNNING: Hi there
       \tTask role: bozo, env: test, name: woops, instance: 3, status: RUNNING on slavehost
       \t  CPU: 2 core(s), RAM: 2 MB, Disk: 2 MB
       \t  events:
       \t   1970-11-23 ##:##:## RUNNING: Hi there
       Inactive tasks (0):
       """
         )
         assert actual == expected
コード例 #9
0
ファイル: test_restart.py プロジェクト: abdasgupta/aurora
 def test_restart_simple_output(self):
   self.reset_mock_io()
   # Test the client-side restart logic in its simplest case: everything succeeds
   (mock_api, mock_scheduler_proxy) = self.create_mock_api()
   mock_health_check = self.setup_health_checks(mock_api)
   self.setup_mock_scheduler_for_simple_restart(mock_api)
   with contextlib.nested(
       patch('apache.aurora.client.api.SchedulerProxy', return_value=mock_scheduler_proxy),
       patch('apache.aurora.client.api.instance_watcher.StatusHealthCheck',
           return_value=mock_health_check),
       patch('time.time', side_effect=functools.partial(self.fake_time, self)),
       patch('threading._Event.wait'),
       patch('apache.aurora.client.cli.context.AuroraCommandContext.print_out',
           side_effect=self.mock_print_out),
       patch('apache.aurora.client.cli.context.AuroraCommandContext.print_err',
           side_effect=self.mock_print_err)
   ):
     with temporary_file() as fp:
       fp.write(self.get_valid_config())
       fp.flush()
       cmd = AuroraCommandLine()
       cmd.execute(['job', 'restart', '--batch-size=5', 'west/bozo/test/hello',
           '--config', fp.name])
       assert self.MOCK_OUT == ['Job west/bozo/test/hello restarted successfully']
       assert self.MOCK_ERR == []
コード例 #10
0
  def test_plugin_runs_in_create_job(self):
    """Run a test of the "create" command against a mocked-out API:
    Verifies that the creation command sends the right API RPCs, and performs the correct
    tests on the result."""

    # We'll patch out create_context, which will give us a fake context
    # object, and everything can be stubbed through that.
    mock_context = FakeAuroraCommandContext()
    with patch('apache.aurora.client.cli.jobs.Job.create_context', return_value=mock_context):
      # After making the client, create sets up a job monitor.
      # The monitor uses TaskQuery to get the tasks. It's called at least twice:once before
      # the job is created, and once after. So we need to set up mocks for the query results.
      mock_query = self.create_mock_query()
      mock_context.add_expected_status_query_result(
        self.create_mock_status_query_result(ScheduleStatus.INIT))
      mock_context.add_expected_status_query_result(
        self.create_mock_status_query_result(ScheduleStatus.RUNNING))
      api = mock_context.get_api('west')
      api.create_job.return_value = self.get_createjob_response()

      # This is the real test: invoke create as if it had been called by the command line.
      with temporary_file() as fp:
        fp.write(self.get_valid_config())
        fp.flush()
        cmd = AuroraCommandLine()
        cmd.register_plugin(BogusPlugin())
        cmd.execute(['job', 'create', '--bogosity=maximum', '--wait_until=RUNNING',
            'west/bozo/test/hello', fp.name])

      # Now check that the right API calls got made.
      # Check that create_job was called exactly once, with an AuroraConfig parameter.
      self.assert_create_job_called(api)
      self.assert_scheduler_called(api, mock_query, 2)
      # Check that the plugin did its job.
      assert mock_context.bogosity == "maximum"
コード例 #11
0
ファイル: test_task.py プロジェクト: rowhit/aurora
  def test_successful_ssh(self):
    """Test the ssh command."""
    (mock_api, mock_scheduler_proxy) = self.create_mock_api()
    mock_scheduler_proxy.getTasksStatus.return_value = self.create_status_response()
    sandbox_args = {'slave_root': '/slaveroot', 'slave_run_directory': 'slaverun'}
    with contextlib.nested(
        patch('apache.aurora.client.api.SchedulerProxy', return_value=mock_scheduler_proxy),
        patch('apache.aurora.client.api.command_runner.DistributedCommandRunner.sandbox_args',
            return_value=sandbox_args),
        patch('subprocess.call', return_value=0)) as (
            mock_scheduler_proxy_class,
            mock_runner_args_patch,
            mock_subprocess):
      cmd = AuroraCommandLine()
      cmd.execute(['task', 'ssh', '--ssh-options=-v', 'west/bozo/test/hello/1', '--command=ls'])

      # The status command sends a getTasksStatus query to the scheduler,
      # and then prints the result.
      mock_scheduler_proxy.getTasksStatus.assert_called_with(TaskQuery(
          jobKeys=[JobKey(role='bozo', environment='test', name='hello')],
          instanceIds=set([1]),
          statuses=set([ScheduleStatus.RUNNING, ScheduleStatus.KILLING, ScheduleStatus.RESTARTING,
              ScheduleStatus.PREEMPTING, ScheduleStatus.DRAINING
              ])))
      mock_subprocess.assert_called_with(['ssh', '-t', '-v', 'bozo@slavehost',
          'cd /slaveroot/slaves/*/frameworks/*/executors/thermos-1287391823/runs/'
          'slaverun/sandbox;ls'])
コード例 #12
0
ファイル: test_command_hooks.py プロジェクト: apache/aurora
  def test_create_job_with_successful_hook(self):
    GlobalCommandHookRegistry.reset()
    command_hook = HookForTesting(True)
    GlobalCommandHookRegistry.register_command_hook(command_hook)
    mock_context = FakeAuroraCommandContext()
    with patch("apache.aurora.client.cli.jobs.Job.create_context", return_value=mock_context):
      mock_query = self.create_query()
      mock_context.add_expected_status_query_result(
          self.create_mock_status_query_result(ScheduleStatus.INIT))
      mock_context.add_expected_status_query_result(
          self.create_mock_status_query_result(ScheduleStatus.RUNNING))
      mock_context.add_expected_status_query_result(
          self.create_mock_status_query_result(ScheduleStatus.RUNNING))
      mock_context.get_api("west").check_status.side_effect = (
        lambda x: self.create_mock_status_query_result(ScheduleStatus.RUNNING))
      api = mock_context.get_api("west")
      api.create_job.return_value = self.get_createjob_response()
      api.get_tier_configs.return_value = self.get_mock_tier_configurations()

      with temporary_file() as fp:
        fp.write(self.get_valid_config())
        fp.flush()
        cmd = AuroraCommandLine()
        cmd.execute(["job", "create", "--wait-until=RUNNING", "west/bozo/test/hello",
            fp.name])

      self.assert_create_job_called(api)
      self.assert_scheduler_called(api, mock_query, 1)
      assert command_hook.ran_pre
      assert command_hook.ran_post
コード例 #13
0
ファイル: test_update.py プロジェクト: ruo91/incubator-aurora
 def test_updater_simple_small_doesnt_warn(self):
   mock_out = IOMock()
   mock_err = IOMock()
   (mock_api, mock_scheduler_proxy) = self.create_mock_api()
   mock_health_check = self.setup_health_checks(mock_api)
   mock_quota_check = self.setup_quota_check()
   mock_job_monitor = self.setup_job_monitor()
   fake_mux = self.FakeSchedulerMux()
   self.setup_mock_scheduler_for_simple_update(mock_api)
   # This doesn't work, because:
   # - The mock_context stubs out the API.
   # - the test relies on using live code in the API.
   with contextlib.nested(
       patch('apache.aurora.client.cli.jobs.AuroraCommandContext.print_out',
           side_effect=mock_out.put),
       patch('apache.aurora.client.cli.jobs.AuroraCommandContext.print_err',
           side_effect=mock_err.put),
       patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS),
       patch('apache.aurora.client.api.SchedulerProxy', return_value=mock_scheduler_proxy),
       patch('apache.aurora.client.api.instance_watcher.StatusHealthCheck',
           return_value=mock_health_check),
       patch('apache.aurora.client.api.updater.JobMonitor', return_value=mock_job_monitor),
       patch('apache.aurora.client.api.updater.QuotaCheck', return_value=mock_quota_check),
       patch('apache.aurora.client.api.updater.SchedulerMux', return_value=fake_mux),
       patch('time.time', side_effect=functools.partial(self.fake_time, self)),
       patch('time.sleep', return_value=None),
       patch('threading._Event.wait')):
     with temporary_file() as fp:
       fp.write(self.get_valid_config())
       fp.flush()
       cmd = AuroraCommandLine()
       cmd.execute(['job', 'update', 'west/bozo/test/hello', fp.name])
     assert mock_out.get() == ['Update completed successfully']
     assert mock_err.get() == []
コード例 #14
0
  def test_simple_successful_create_job_with_bindings(self):
    """Run a test of the "create" command against a mocked-out API:
    Verifies that the creation command sends the right API RPCs, and performs the correct
    tests on the result."""

    mock_context = FakeAuroraCommandContext()
    with contextlib.nested(
        patch('threading._Event.wait'),
        patch('apache.aurora.client.cli.jobs.Job.create_context', return_value=mock_context)):
      mock_query = self.create_query()
      mock_context.add_expected_status_query_result(
        self.create_mock_status_query_result(ScheduleStatus.PENDING))
      mock_context.add_expected_status_query_result(
        self.create_mock_status_query_result(ScheduleStatus.RUNNING))
      api = mock_context.get_api('west')
      api.create_job.return_value = self.get_createjob_response()

      # This is the real test: invoke create as if it had been called by the command line.
      with temporary_file() as fp:
        fp.write(self.get_unbound_test_config())
        fp.flush()
        cmd = AuroraCommandLine()
        cmd.execute(['job', 'create', '--wait-until=RUNNING', '--bind', 'cluster_binding=west',
            '--bind', 'instances_binding=20', '--bind', 'TEST_BATCH=1',
            'west/bozo/test/hello',
            fp.name])

      # Now check that the right API calls got made.
      # Check that create_job was called exactly once, with an AuroraConfig parameter.
      self.assert_create_job_called(api)
      self.assert_scheduler_called(api, mock_query, 2)
コード例 #15
0
ファイル: test_update.py プロジェクト: rowoot/aurora
 def test_large_with_instances_doesnt_warn(self):
     (mock_api, mock_scheduler_proxy) = self.create_mock_api()
     mock_health_check = self.setup_health_checks(mock_api)
     mock_quota_check = self.setup_quota_check()
     mock_job_monitor = self.setup_job_monitor()
     fake_mux = self.FakeSchedulerMux()
     self.setup_mock_scheduler_for_simple_update(mock_api, count=20)
     config = self.get_valid_config()
     config = config.replace("instances = 20", "instances = 200")
     with contextlib.nested(
         patch("apache.aurora.client.api.SchedulerProxy", return_value=mock_scheduler_proxy),
         patch("apache.aurora.client.api.instance_watcher.StatusHealthCheck", return_value=mock_health_check),
         patch("apache.aurora.client.api.updater.JobMonitor", return_value=mock_job_monitor),
         patch("apache.aurora.client.api.updater.QuotaCheck", return_value=mock_quota_check),
         patch("apache.aurora.client.api.updater.SchedulerMux", return_value=fake_mux),
         patch("time.time", side_effect=functools.partial(self.fake_time, self)),
         patch("threading._Event.wait"),
     ):
         with patch("time.sleep") as sleep:
             with temporary_file() as fp:
                 fp.write(config)
                 fp.flush()
                 cmd = AuroraCommandLine()
                 cmd.execute(["job", "update", "west/bozo/test/hello/1,3", fp.name])
                 assert sleep.call_count == 0
コード例 #16
0
  def test_restart_simple(self):
    # Test the client-side restart logic in its simplest case: everything succeeds
    (mock_api, mock_scheduler_proxy) = self.create_mock_api()
    mock_health_check = self.setup_health_checks(mock_api)
    self.setup_mock_scheduler_for_simple_restart(mock_api)
    with contextlib.nested(
        patch('apache.aurora.client.api.SchedulerProxy', return_value=mock_scheduler_proxy),
        patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS),
        patch('apache.aurora.client.api.instance_watcher.StatusHealthCheck',
            return_value=mock_health_check),
        patch('time.time', side_effect=functools.partial(self.fake_time, self)),
        patch('threading._Event.wait')
    ):
      with temporary_file() as fp:
        fp.write(self.get_valid_config())
        fp.flush()
        cmd = AuroraCommandLine()
        cmd.execute(['job', 'restart', '--batch-size=5', 'west/bozo/test/hello', fp.name])

        # Like the update test, the exact number of calls here doesn't matter.
        # what matters is that it must have been called once before batching, plus
        # at least once per batch, and there are 4 batches.
        assert mock_scheduler_proxy.getTasksWithoutConfigs.call_count >= 4
        # called once per batch
        assert mock_scheduler_proxy.restartShards.call_count == 4
        # parameters for all calls are generated by the same code, so we just check one
        mock_scheduler_proxy.restartShards.assert_called_with(JobKey(environment=self.TEST_ENV,
            role=self.TEST_ROLE, name=self.TEST_JOB), [15, 16, 17, 18, 19], None)
コード例 #17
0
  def test_updater_simple_with_instances(self):
    (mock_api, mock_scheduler_proxy) = self.create_mock_api()
    mock_health_check = self.setup_health_checks(mock_api)
    mock_quota_check = self.setup_quota_check()
    mock_job_monitor = self.setup_job_monitor()
    fake_mux = self.FakeSchedulerMux()
    self.setup_mock_scheduler_for_simple_update(mock_api)
    with contextlib.nested(
        patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS),
        patch('apache.aurora.client.api.SchedulerProxy', return_value=mock_scheduler_proxy),
        patch('apache.aurora.client.api.instance_watcher.StatusHealthCheck',
            return_value=mock_health_check),
        patch('apache.aurora.client.api.updater.JobMonitor', return_value=mock_job_monitor),
        patch('apache.aurora.client.api.updater.QuotaCheck', return_value=mock_quota_check),
        patch('apache.aurora.client.api.updater.SchedulerMux', return_value=fake_mux),
        patch('time.time', side_effect=functools.partial(self.fake_time, self)),
        patch('time.sleep', return_value=None),
        patch('threading._Event.wait')):
      with temporary_file() as fp:
        fp.write(self.get_valid_config())
        fp.flush()
        cmd = AuroraCommandLine()
        cmd.execute(['job', 'update', 'west/bozo/test/hello/1', fp.name])

      mock_scheduler_proxy = mock_api.scheduler_proxy
      assert mock_scheduler_proxy.acquireLock.call_count == 1
      assert mock_scheduler_proxy.addInstances.call_count == 1
      assert mock_scheduler_proxy.killTasks.call_count == 1
      self.assert_correct_status_calls(mock_scheduler_proxy)
      assert mock_scheduler_proxy.releaseLock.call_count == 1
コード例 #18
0
  def test_killall_job_something_else(self):
    """Test kill client-side API logic."""
    mock_context = FakeAuroraCommandContext()
    mock_scheduler_proxy = Mock()
    with contextlib.nested(
        patch('time.sleep'),
        patch('apache.aurora.client.cli.jobs.Job.create_context', return_value=mock_context),
        patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS)):

      api = mock_context.get_api('west')
      api.kill_job.return_value = self.get_kill_job_response()
      mock_context.add_expected_status_query_result(self.create_status_call_result())
      mock_scheduler_proxy.killTasks.return_value = self.get_kill_job_response()
      mock_context.add_expected_status_query_result(self.create_status_call_result(
          self.create_mock_task(ScheduleStatus.KILLED)))
      with temporary_file() as fp:
        fp.write(self.get_valid_config())
        fp.flush()
        cmd = AuroraCommandLine()
        cmd.execute(['job', 'killall', '--config=%s' % fp.name, 'west/bozo/test/hello'])

      # Now check that the right API calls got made.
      assert api.kill_job.call_count == 4
      instances = [15, 16, 17, 18, 19]
      api.kill_job.assert_called_with(AuroraJobKey.from_path('west/bozo/test/hello'), instances)
      self.assert_scheduler_called(api, self.get_expected_task_query(instances), 6)
コード例 #19
0
 def test_large_with_instances_doesnt_warn(self):
   (mock_api, mock_scheduler_proxy) = self.create_mock_api()
   mock_health_check = self.setup_health_checks(mock_api)
   mock_quota_check = self.setup_quota_check()
   mock_job_monitor = self.setup_job_monitor()
   fake_mux = self.FakeSchedulerMux()
   self.setup_mock_scheduler_for_simple_update(mock_api, count=20)
   config = self.get_valid_config()
   config = config.replace("instances = 20", "instances = 200")
   with contextlib.nested(
       patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS),
       patch('apache.aurora.client.api.SchedulerProxy', return_value=mock_scheduler_proxy),
       patch('apache.aurora.client.api.instance_watcher.StatusHealthCheck',
           return_value=mock_health_check),
       patch('apache.aurora.client.api.updater.JobMonitor', return_value=mock_job_monitor),
       patch('apache.aurora.client.api.updater.QuotaCheck', return_value=mock_quota_check),
       patch('apache.aurora.client.api.updater.SchedulerMux', return_value=fake_mux),
       patch('time.time', side_effect=functools.partial(self.fake_time, self)),
       patch('threading._Event.wait')):
     with patch('apache.aurora.client.cli.context.AuroraCommandContext.warn_and_pause') as pause:
       with temporary_file() as fp:
         fp.write(config)
         fp.flush()
         cmd = AuroraCommandLine()
         cmd.execute(['job', 'update', 'west/bozo/test/hello/1,3', fp.name])
         assert pause.call_count == 0
コード例 #20
0
ファイル: test_diff.py プロジェクト: kpeterson1/aurora
    def test_successful_diff(self):
        """Test the diff command."""
        (mock_api, mock_scheduler_proxy) = self.create_mock_api()
        with contextlib.nested(
            patch("apache.aurora.client.api.SchedulerProxy", return_value=mock_scheduler_proxy),
            patch("subprocess.call", return_value=0),
            patch("json.loads", return_value=Mock()),
        ) as (_, subprocess_patch, _):

            mock_scheduler_proxy.getTasksStatus.return_value = self.create_status_response()
            self.setup_populate_job_config(mock_scheduler_proxy)
            with temporary_file() as fp:
                fp.write(self.get_valid_config())
                fp.flush()
                cmd = AuroraCommandLine()
                cmd.execute(["job", "diff", "west/bozo/test/hello", fp.name])

                # Diff should get the task status, populate a config, and run diff.
                mock_scheduler_proxy.getTasksStatus.assert_called_with(
                    TaskQuery(jobKeys=[JobKey(role="bozo", environment="test", name="hello")], statuses=ACTIVE_STATES)
                )
                assert mock_scheduler_proxy.populateJobConfig.call_count == 1
                assert isinstance(mock_scheduler_proxy.populateJobConfig.call_args[0][0], JobConfiguration)
                assert mock_scheduler_proxy.populateJobConfig.call_args[0][0].key == JobKey(
                    environment=u"test", role=u"bozo", name=u"hello"
                )
                # Subprocess should have been used to invoke diff with two parameters.
                assert subprocess_patch.call_count == 1
                assert len(subprocess_patch.call_args[0][0]) == 3
                assert subprocess_patch.call_args[0][0][0] == os.environ.get("DIFF_VIEWER", "diff")
コード例 #21
0
  def test_successful_run(self):
    """Test the run command."""
    # Calls api.check_status, which calls scheduler_proxy.getJobs
    (mock_api, mock_scheduler_proxy) = self.create_mock_api()
    mock_scheduler_proxy.getTasksStatus.return_value = self.create_status_response()
    sandbox_args = {'slave_root': '/slaveroot', 'slave_run_directory': 'slaverun'}
    with contextlib.nested(
        patch('apache.aurora.client.api.SchedulerProxy', return_value=mock_scheduler_proxy),
        patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS),
        patch('apache.aurora.client.cli.task.CLUSTERS', new=self.TEST_CLUSTERS),
        patch('apache.aurora.client.api.command_runner.DistributedCommandRunner.sandbox_args',
            return_value=sandbox_args),
        patch('subprocess.Popen', return_value=self.create_mock_process())) as (
            mock_scheduler_proxy_class,
            mock_clusters,
            mock_clusters_cli,
            mock_runner_args_patch,
            mock_subprocess):
      cmd = AuroraCommandLine()
      cmd.execute(['task', 'run', 'west/bozo/test/hello', 'ls'])
      # The status command sends a getTasksStatus query to the scheduler,
      # and then prints the result.
      mock_scheduler_proxy.getTasksStatus.assert_called_with(TaskQuery(jobName='hello',
          environment='test', owner=Identity(role='bozo'),
          statuses=set([ScheduleStatus.RUNNING, ScheduleStatus.KILLING, ScheduleStatus.RESTARTING,
              ScheduleStatus.PREEMPTING, ScheduleStatus.DRAINING])))

      # The mock status call returns 3 three ScheduledTasks, so three commands should have been run
      assert mock_subprocess.call_count == 3
      mock_subprocess.assert_called_with(['ssh', '-n', '-q', 'bozo@slavehost',
          'cd /slaveroot/slaves/*/frameworks/*/executors/thermos-1287391823/runs/'
          'slaverun/sandbox;ls'],
          stderr=-2, stdout=-1)
コード例 #22
0
ファイル: test_quota.py プロジェクト: KancerEzeroglu/aurora
 def _call_get_quota(self, mock_context, command_args):
   with contextlib.nested(
       patch('apache.aurora.client.cli.quota.Quota.create_context', return_value=mock_context),
       patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS)):
     cmd = AuroraCommandLine()
     cmd.execute(command_args)
     out = '\n'.join(mock_context.get_out())
     return out
コード例 #23
0
ファイル: test_sla.py プロジェクト: wickman/incubator-aurora
 def test_invalid_percentile(self):
   cmd = AuroraCommandLine()
   try:
     cmd.execute(['sla', 'get-job-uptime', 'west/role/env/test', '--percentiles=100'])
   except SystemExit:
     pass
   else:
     assert 'Expected error is not raised.'
コード例 #24
0
ファイル: test_status.py プロジェクト: benley/aurora
 def test_successful_status_deep_null_metadata(self):
   (mock_api, mock_scheduler_proxy) = self.create_mock_api()
   mock_scheduler_proxy.getTasksWithoutConfigs.return_value = self.create_status_null_metadata()
   with patch('apache.aurora.client.api.SchedulerProxy', return_value=mock_scheduler_proxy):
     cmd = AuroraCommandLine()
     cmd.execute(['job', 'status', 'west/bozo/test/hello'])
     mock_scheduler_proxy.getTasksWithoutConfigs.assert_called_with(
         TaskQuery(jobKeys=[JobKey(role='bozo', environment='test', name='hello')]))
コード例 #25
0
ファイル: test_status.py プロジェクト: bmhatfield/aurora
 def test_successful_status_deep_null_metadata(self):
     (mock_api, mock_scheduler_proxy) = self.create_mock_api()
     mock_scheduler_proxy.getTasksWithoutConfigs.return_value = self.create_status_null_metadata()
     with patch("apache.aurora.client.api.SchedulerProxy", return_value=mock_scheduler_proxy):
         cmd = AuroraCommandLine()
         cmd.execute(["job", "status", "west/bozo/test/hello"])
         mock_scheduler_proxy.getTasksWithoutConfigs.assert_called_with(
             TaskQuery(jobKeys=[JobKey(role="bozo", environment="test", name="hello")])
         )
コード例 #26
0
ファイル: test_sla.py プロジェクト: AltanAlpay/aurora
 def test_get_job_uptime_with_percentiles(self):
   mock_context = FakeAuroraCommandContext()
   self.setup_mock_sla_uptime_vector(mock_context, 915)
   with patch('apache.aurora.client.cli.sla.Sla.create_context', return_value=mock_context):
     cmd = AuroraCommandLine()
     cmd.execute(['sla', 'get-job-uptime', 'west/role/env/test', '--percentiles=99.9,85.5'])
     out = '\n'.join(mock_context.get_out())
     assert '99.9 percentile\t- 915 seconds' in out
     assert '85.5 percentile\t- 915 seconds' in out
コード例 #27
0
ファイル: test_sla.py プロジェクト: AltanAlpay/aurora
 def test_get_task_up_count_with_durations(self):
   mock_context = FakeAuroraCommandContext()
   self.setup_mock_sla_uptime_vector(mock_context, 95.3577434734)
   with patch('apache.aurora.client.cli.sla.Sla.create_context', return_value=mock_context):
     cmd = AuroraCommandLine()
     cmd.execute(['sla', 'get-task-up-count', 'west/role/env/test', '--durations=3m,2d6h,3h'])
     out = '\n'.join(mock_context.get_out())
     assert '3 mins\t- 95.36 %' in out
     assert '54 hrs\t- 95.36 %' in out
     assert '3 hrs\t- 95.36 %' in out
コード例 #28
0
ファイル: test_status.py プロジェクト: bmhatfield/aurora
    def test_successful_status_shallow_nometadata(self):
        """Regression test: there was a crasher bug when metadata was None."""

        mock_context = FakeAuroraCommandContext()
        mock_api = mock_context.get_api("west")
        mock_api.check_status.return_value = self.create_status_null_metadata()
        with contextlib.nested(patch("apache.aurora.client.cli.jobs.Job.create_context", return_value=mock_context)):
            cmd = AuroraCommandLine()
            cmd.execute(["job", "status", "west/bozo/test/hello"])
            mock_api.check_status.assert_called_with(AuroraJobKey("west", "bozo", "test", "hello"))
コード例 #29
0
ファイル: test_status.py プロジェクト: bmhatfield/aurora
 def test_successful_status_shallow(self):
     """Test the status command at the shallowest level: calling status should end up invoking
 the local APIs get_status method."""
     mock_context = FakeAuroraCommandContext()
     mock_api = mock_context.get_api("west")
     mock_api.check_status.return_value = self.create_status_response()
     with contextlib.nested(patch("apache.aurora.client.cli.jobs.Job.create_context", return_value=mock_context)):
         cmd = AuroraCommandLine()
         cmd.execute(["job", "status", "west/bozo/test/hello"])
         mock_api.check_status.assert_called_with(AuroraJobKey("west", "bozo", "test", "hello"))
コード例 #30
0
 def test_successful_status_deep_null_packages(self):
   (mock_api, mock_scheduler_proxy) = self.create_mock_api()
   mock_scheduler_proxy.query.return_value = self.create_status_response_null_package()
   with contextlib.nested(
       patch('apache.aurora.client.api.SchedulerProxy', return_value=mock_scheduler_proxy),
       patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS)):
     cmd = AuroraCommandLine()
     cmd.execute(['job', 'status', 'west/bozo/test/hello'])
     mock_scheduler_proxy.getTasksStatus.assert_called_with(TaskQuery(jobName='hello',
         environment='test', owner=Identity(role='bozo')))
コード例 #31
0
  def test_resume_update_command_line_succeeds(self):
    mock_context = FakeAuroraCommandContext()
    with contextlib.nested(
        patch('apache.aurora.client.cli.update.Update.create_context', return_value=mock_context),
        patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS)):
      mock_api = mock_context.get_api(self.TEST_CLUSTER)
      mock_api.resume_job_update.return_value = self.create_simple_success_response()
      with temporary_file() as fp:
        fp.write(self.get_valid_config())
        fp.flush()
        cmd = AuroraCommandLine()
        result = cmd.execute(['beta-update', 'resume', self.TEST_JOBSPEC])
        assert result == EXIT_OK

      mock_api.resume_job_update.assert_called_with(self.TEST_JOBKEY)
      assert mock_context.get_out() == ["Update has been resumed."]
コード例 #32
0
 def test_update_invalid_config(self):
     mock_context = FakeAuroraCommandContext()
     with contextlib.nested(
             patch('apache.aurora.client.cli.jobs.Job.create_context',
                   return_value=mock_context),
             patch('apache.aurora.client.factory.CLUSTERS',
                   new=self.TEST_CLUSTERS)):
         mock_api = mock_context.get_api('west')
         with temporary_file() as fp:
             fp.write(self.get_invalid_config('invalid_field=False,'))
             fp.flush()
             cmd = AuroraCommandLine()
             result = cmd.execute(
                 ['job', 'update', '--force', self.TEST_JOBSPEC, fp.name])
             assert result == EXIT_INVALID_CONFIGURATION
             assert mock_api.update_job.call_count == 0
コード例 #33
0
 def test_ssh_no_instance_command(self):
     """Test the ssh command when the jobkey parameter doesn't specify an instance."""
     (mock_api, mock_scheduler_proxy) = self.create_mock_api()
     mock_scheduler_proxy.getTasksStatus.return_value = self.create_nojob_status_response(
     )
     with contextlib.nested(
             patch('apache.aurora.client.api.SchedulerProxy',
                   return_value=mock_scheduler_proxy),
             patch('subprocess.Popen',
                   return_value=self.create_mock_process())) as (
                       mock_scheduler_proxy_class, mock_subprocess):
         cmd = AuroraCommandLine()
         result = cmd.execute(
             ['task', 'ssh', 'west/bozo/test/hello', '--command=ls'])
         assert result == EXIT_INVALID_PARAMETER
         assert mock_subprocess.call_count == 0
コード例 #34
0
ファイル: test_status.py プロジェクト: KancerEzeroglu/aurora
 def test_no_jobs_found_status_shallow(self):
     # Calls api.check_status, which calls scheduler_proxy.getJobs
     mock_context = FakeAuroraCommandContext()
     mock_api = mock_context.get_api('west')
     mock_api.check_status.return_value = self.create_nojobs_status_response(
     )
     with contextlib.nested(
             patch('apache.aurora.client.cli.jobs.Job.create_context',
                   return_value=mock_context)):
         cmd = AuroraCommandLine()
         result = cmd.execute(
             ['job', 'status', '--write-json', 'west/bozo/test/hello'])
         assert mock_context.get_out() == [
             '{"jobspec":"west/bozo/test/hello","error":"No matching jobs found"}'
         ]
         assert result == EXIT_OK
コード例 #35
0
    def test_schedule_cron_failed_invalid_config(self):
        mock_context = FakeAuroraCommandContext()
        with patch('apache.aurora.client.cli.cron.CronNoun.create_context',
                   return_value=mock_context):
            with temporary_file() as fp:
                fp.write(self.get_invalid_cron_config('invalid_clause=oops'))
                fp.flush()
                cmd = AuroraCommandLine()
                result = cmd.execute(
                    ['cron', 'schedule', 'west/bozo/test/hello', fp.name])
                assert result == EXIT_INVALID_CONFIGURATION

            # Now check that the right API calls got made.
            # Check that create_job was not called.
            api = mock_context.get_api('west')
            assert api.schedule_cron.call_count == 0
コード例 #36
0
 def test_start_cron_open_browser(self):
     mock_context = FakeAuroraCommandContext()
     with patch('apache.aurora.client.cli.cron.CronNoun.create_context',
                return_value=mock_context):
         api = mock_context.get_api("west")
         api.start_cronjob.return_value = self.create_simple_success_response(
         )
         cmd = AuroraCommandLine()
         result = cmd.execute(
             ['cron', 'start', self.TEST_JOBSPEC, '--open-browser'])
         assert result == EXIT_OK
         api.start_cronjob.assert_called_once_with(self.TEST_JOBKEY,
                                                   config=None)
         assert self.mock_webbrowser.mock_calls == [
             call("http://something_or_other/scheduler/bozo/test/hello")
         ]
コード例 #37
0
ファイル: test_create.py プロジェクト: zhiqinghuang/aurora
 def test_create_cron_job_fails(self):
     """Test a cron job is not accepted."""
     mock_context = FakeAuroraCommandContext()
     api = mock_context.get_api('west')
     api.get_tier_configs.return_value = self.get_mock_tier_configurations()
     with patch('apache.aurora.client.cli.jobs.Job.create_context',
                return_value=mock_context):
         with temporary_file() as fp:
             fp.write(self.get_valid_cron_config())
             fp.flush()
             cmd = AuroraCommandLine()
             result = cmd.execute([
                 'job', 'create', '--wait-until=RUNNING',
                 'west/bozo/test/hello', fp.name
             ])
             assert result == EXIT_COMMAND_FAILURE
コード例 #38
0
 def test_list_updates_command(self):
   mock_context = FakeAuroraCommandContext()
   mock_context.get_api('west').query_job_updates.return_value = self.get_status_query_response()
   with contextlib.nested(
       patch('apache.aurora.client.cli.update.Update.create_context', return_value=mock_context),
       patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS)):
     cmd = AuroraCommandLine()
     result = cmd.execute(["beta-update", "list", self.TEST_CLUSTER, "--user=me"])
     assert result == EXIT_OK
     assert mock_context.get_out_str() == textwrap.dedent("""\
         Job: west/bozo/test/hello, Id: 0, User: me, Status: ROLLED_FORWARD
           Created: 1411404927, Last Modified 14114056030
         Job: west/bozo/test/hello, Id: 1, User: me, Status: ROLLED_FORWARD
           Created: 1411404927, Last Modified 14114056030
         Job: west/bozo/test/hello, Id: 2, User: me, Status: ROLLED_FORWARD
           Created: 1411404927, Last Modified 14114056030""")
コード例 #39
0
ファイル: test_cron.py プロジェクト: xuchenw/incubator-aurora
 def test_schedule_cron_deep_api(self):
   (mock_api, mock_scheduler_proxy) = self.create_mock_api()
   with contextlib.nested(
       patch('time.sleep'),
       patch('apache.aurora.client.api.SchedulerProxy', return_value=mock_scheduler_proxy),
       patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS)):
     mock_scheduler_proxy.scheduleCronJob.return_value = self.create_simple_success_response()
     with temporary_file() as fp:
       fp.write(self.get_valid_cron_config())
       fp.flush()
       cmd = AuroraCommandLine()
       result = cmd.execute(['cron', 'schedule', 'west/bozo/test/hello', fp.name])
       assert result == EXIT_OK
       assert mock_scheduler_proxy.scheduleCronJob.call_count == 1
       job = mock_scheduler_proxy.scheduleCronJob.call_args[0][0]
       assert job.key == JobKey("bozo", "test", "hello")
コード例 #40
0
 def test_unknown_error(self):
   mock_context = FakeAuroraCommandContext(reveal=False)
   with contextlib.nested(
       patch('time.sleep'),
       patch('apache.aurora.client.cli.jobs.Job.create_context',
           side_effect=Exception("Argh"))):
     api = mock_context.get_api('west')
     api.create_job.return_value = self.get_createjob_response()
     with temporary_file() as fp:
       fp.write(self.get_valid_config())
       fp.flush()
       cmd = AuroraCommandLine()
       result = cmd.execute(['job', 'create', '--wait-until=RUNNING', 'west/bozo/test/hello',
           fp.name])
       assert result == EXIT_UNKNOWN_ERROR
       assert api.create_job.call_count == 0
コード例 #41
0
  def test_interrupt(self):
    mock_context = FakeAuroraCommandContext()
    with contextlib.nested(
        patch('time.sleep'),
        patch('apache.aurora.client.cli.jobs.Job.create_context',
            side_effect=KeyboardInterrupt())):
      api = mock_context.get_api('west')
      api.create_job.return_value = self.get_createjob_response()

      with temporary_file() as fp:
        fp.write(self.get_valid_config())
        fp.flush()
        cmd = AuroraCommandLine()
        result = cmd.execute(['job', 'create', '--wait-until=RUNNING', 'west/bozo/test/hello',
            fp.name])
        assert result == EXIT_INTERRUPTED
        assert api.create_job.call_count == 0
コード例 #42
0
  def test_create_job_failed_invalid_config(self):
    """Run a test of the "create" command against a mocked-out API, with a configuration
    containing a syntax error"""
    mock_context = FakeAuroraCommandContext()
    with patch('apache.aurora.client.cli.jobs.Job.create_context', return_value=mock_context):
      with temporary_file() as fp:
        fp.write(self.get_invalid_config('invalid_clause=oops'))
        fp.flush()
        cmd = AuroraCommandLine()
        result = cmd.execute(['job', 'create', '--wait-until=RUNNING',
            'west/bozo/test/hello', fp.name])
        assert result == EXIT_INVALID_CONFIGURATION

      # Now check that the right API calls got made.
      # Check that create_job was not called.
      api = mock_context.get_api('west')
      assert api.create_job.call_count == 0
コード例 #43
0
  def test_pause_update_command_line_error(self):
    mock_context = FakeAuroraCommandContext()
    with contextlib.nested(
        patch('apache.aurora.client.cli.update.Update.create_context', return_value=mock_context),
        patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS)):
      mock_api = mock_context.get_api(self.TEST_CLUSTER)
      mock_api.pause_job_update.return_value = self.create_error_response()
      with temporary_file() as fp:
        fp.write(self.get_valid_config())
        fp.flush()
        cmd = AuroraCommandLine()
        result = cmd.execute(['beta-update', 'pause', self.TEST_JOBSPEC])
        assert result == EXIT_API_ERROR

      mock_api.pause_job_update.assert_called_with(self.TEST_JOBKEY)
      assert mock_context.get_out() == []
      assert mock_context.get_err() == ["Failed to pause update due to error:", "\tDamn"]
コード例 #44
0
 def test_deschedule_cron_deep_api(self):
     (mock_api, mock_scheduler_proxy) = self.create_mock_api()
     with contextlib.nested(
             patch('time.sleep'),
             patch('apache.aurora.client.api.SchedulerProxy',
                   return_value=mock_scheduler_proxy),
             patch('apache.aurora.client.factory.CLUSTERS',
                   new=self.TEST_CLUSTERS)):
         mock_scheduler_proxy.descheduleCronJob.return_value = self.create_simple_success_response(
         )
         cmd = AuroraCommandLine()
         result = cmd.execute(
             ['cron', 'deschedule', 'west/bozo/test/hello'])
         assert result == EXIT_OK
         assert mock_scheduler_proxy.descheduleCronJob.call_count == 1
         mock_scheduler_proxy.descheduleCronJob.assert_called_with(
             JobKey(environment='test', role='bozo', name='hello'), None)
コード例 #45
0
    def test_schedule_failed(self):
        mock_context = FakeAuroraCommandContext()
        with patch('apache.aurora.client.cli.cron.CronNoun.create_context',
                   return_value=mock_context):
            api = mock_context.get_api('west')
            api.schedule_cron.return_value = self.create_error_response()
            with temporary_file() as fp:
                fp.write(self.get_valid_config())
                fp.flush()
                cmd = AuroraCommandLine()
                result = cmd.execute(
                    ['cron', 'schedule', 'west/bozo/test/hello', fp.name])
                assert result == EXIT_API_ERROR

            # Now check that the right API calls got made.
            # Check that create_job was called exactly once, with an AuroraConfig parameter.
            assert api.schedule_cron.call_count == 1
コード例 #46
0
ファイル: test_task.py プロジェクト: KancerEzeroglu/aurora
 def test_ssh_job_not_found(self):
     """Test the ssh command when the jobkey parameter specifies a job that isn't running."""
     (mock_api, mock_scheduler_proxy) = self.create_mock_api()
     mock_scheduler_proxy.getTasksStatus.return_value = self.create_nojob_status_response(
     )
     with contextlib.nested(
             patch('apache.aurora.client.api.SchedulerProxy',
                   return_value=mock_scheduler_proxy),
             patch('apache.aurora.client.factory.CLUSTERS',
                   new=self.TEST_CLUSTERS),
             patch('subprocess.call',
                   return_value=0)) as (mock_scheduler_proxy_class,
                                        mock_clusters, mock_subprocess):
         cmd = AuroraCommandLine()
         result = cmd.execute(
             ['task', 'ssh', 'west/bozo/test/hello/1', '--command=ls'])
         assert result == EXIT_INVALID_PARAMETER
         assert mock_subprocess.call_count == 0
コード例 #47
0
ファイル: test_inspect.py プロジェクト: isabella232/client-3
 def test_inspect_job_raw(self):
   mock_stdout = []
   def mock_print_out(msg, indent=0):
     indent_str = " " * indent
     mock_stdout.append("%s%s" % (indent_str, msg))
   job_config = self.get_job_config()
   with contextlib.nested(
       patch('apache.aurora.client.cli.context.AuroraCommandContext.print_out',
           side_effect=mock_print_out),
       patch('apache.aurora.client.cli.context.AuroraCommandContext.get_job_config',
           return_value=job_config)):
     cmd = AuroraCommandLine()
     assert cmd.execute(['job', 'inspect', '--raw', 'west/bozo/test/hello', 'config.aurora']) == 0
     output = '\n'.join(mock_stdout)
     # It's impossible to assert string equivalence of two objects with nested un-hashable types.
     # Given that the only product of --raw flag is the thrift representation of AuroraConfig
     # it's enough to do a spot check here and let thrift.py tests validate the structure.
     assert 'TaskConfig' in output
コード例 #48
0
 def test_schedule_cron_deep_api(self):
     mock_context = FakeAuroraCommandContext()
     with patch('apache.aurora.client.cli.cron.CronNoun.create_context',
                return_value=mock_context):
         api = mock_context.get_api("west")
         api.schedule_cron.return_value = self.create_simple_success_response(
         )
         with temporary_file() as fp:
             fp.write(self.get_valid_cron_config())
             fp.flush()
             cmd = AuroraCommandLine()
             result = cmd.execute(
                 ['cron', 'schedule', 'west/bozo/test/hello', fp.name])
             assert result == EXIT_OK
             assert api.schedule_cron.call_count == 1
             config = api.schedule_cron.call_args[0][0]
             assert config.role() == "bozo"
             assert config.environment() == "test"
             assert config.name() == "hello"
コード例 #49
0
    def test_cron_status(self):
        (mock_api, mock_scheduler_proxy) = self.create_mock_api()
        with contextlib.nested(
                patch('time.sleep'),
                patch('apache.aurora.client.api.SchedulerProxy',
                      return_value=mock_scheduler_proxy),
                patch('apache.aurora.client.factory.CLUSTERS',
                      new=self.TEST_CLUSTERS),
                patch(
                    'apache.aurora.client.cli.context.AuroraCommandContext.print_out'
                )) as (_, _, _, mock_print):
            mock_scheduler_proxy.getJobs.return_value = self._create_getjobs_response(
            )
            cmd = AuroraCommandLine()
            result = cmd.execute(['cron', 'show', 'west/bozo/test/hello'])

            assert result == EXIT_OK
            mock_scheduler_proxy.getJobs.assert_called_once_with("bozo")
            mock_print.assert_called_with("west/bozo/test/hello\t * * * * *")
コード例 #50
0
 def test_restart_no_such_job_with_instances(self):
     (mock_api, mock_scheduler_proxy) = self.create_mock_api()
     mock_health_check = self.setup_health_checks()
     mock_io = IOMock()
     self.setup_mock_scheduler_for_simple_restart(mock_api)
     # Make getTasksWithoutConfigs return an error, which is what happens when a job is not found.
     mock_scheduler_proxy.getTasksWithoutConfigs.return_value = self.create_error_response(
     )
     mock_scheduler_proxy.getTierConfigs.return_value = self.get_mock_tier_configurations(
     )
     with contextlib.nested(
             patch(
                 'apache.aurora.client.cli.context.AuroraCommandContext.print_err',
                 side_effect=mock_io.put),
             patch('apache.aurora.client.api.SchedulerProxy',
                   return_value=mock_scheduler_proxy),
             patch(
                 'apache.aurora.client.api.instance_watcher.StatusHealthCheck',
                 return_value=mock_health_check),
             patch('time.time',
                   side_effect=functools.partial(self.fake_time, self)),
             patch('threading._Event.wait')):
         with temporary_file() as fp:
             fp.write(self.get_valid_config())
             fp.flush()
             cmd = AuroraCommandLine()
             result = cmd.execute([
                 'job', 'restart', '--batch-size=5',
                 'west/bozo/test/hello/1-3', '--config', fp.name
             ])
             # We need to check tat getTasksWithoutConfigs was called, but that restartShards wasn't.
             # In older versions of the client, if shards were specified, but the job didn't
             # exist, the error wouldn't be detected unti0 restartShards was called, which generated
             # the wrong error message.
             assert mock_scheduler_proxy.getTasksWithoutConfigs.call_count == 1
             assert mock_scheduler_proxy.restartShards.call_count == 0
             assert result == EXIT_API_ERROR
             # Error message should be written to log, and it should be what was returned
             # by the getTasksWithoutConfigs call.
             assert mock_io.get() == [
                 "Error restarting job west/bozo/test/hello:", "\tWhoops"
             ]
コード例 #51
0
  def test_create_job_failed(self):
    """Run a test of the "create" command against a mocked-out API:
    this time, make the monitor check status several times before successful completion.
    """
    mock_context = FakeAuroraCommandContext()
    with patch('apache.aurora.client.cli.jobs.Job.create_context', return_value=mock_context):
      mock_context.add_expected_status_query_result(
          self.create_mock_status_query_result(ScheduleStatus.INIT))
      api = mock_context.get_api('west')
      api.create_job.return_value = self.get_failed_createjob_response()
      with temporary_file() as fp:
        fp.write(self.get_valid_config())
        fp.flush()
        cmd = AuroraCommandLine()
        result = cmd.execute(['job', 'create', '--wait-until=RUNNING',
            'west/bozo/test/hello', fp.name])
        assert result == EXIT_COMMAND_FAILURE

      # Check that create_job was called exactly once, with an AuroraConfig parameter.
      self.assert_create_job_called(api)
コード例 #52
0
  def test_create_job_failed_output(self):
    """Test that a failed create generates the correct error messages"""
    mock_context = FakeAuroraCommandContext()
    with patch('apache.aurora.client.cli.jobs.Job.create_context', return_value=mock_context):
      mock_context.add_expected_status_query_result(
          self.create_mock_status_query_result(ScheduleStatus.INIT))
      api = mock_context.get_api('west')
      api.create_job.return_value = self.get_failed_createjob_response()
      with temporary_file() as fp:
        fp.write(self.get_valid_config())
        fp.flush()
        cmd = AuroraCommandLine()
        result = cmd.execute(['job', 'create', '--wait-until=RUNNING',
            'west/bozo/test/hello', fp.name])
        assert result == EXIT_COMMAND_FAILURE

      # Check that create_job was called exactly once, with an AuroraConfig parameter.
      print("Out=%s\nErr=%s" % (mock_context.get_out(), mock_context.get_err()))
      assert mock_context.get_out() == []
      assert mock_context.get_err() == ["job create failed because of scheduler error"]
コード例 #53
0
    def test_status_api_failure(self):
        # Following should use spec=SchedulerClient, but due to introspection for the RPC calls,
        # the necessary methods aren't in that spec.
        mock_scheduler_client = Mock()
        mock_scheduler_client.getTasksWithoutConfigs.side_effect = IOError(
            "Uh-Oh")
        with contextlib.nested(
                patch(
                    'apache.aurora.client.api.scheduler_client.SchedulerClient.get',
                    return_value=mock_scheduler_client),
                patch('apache.aurora.client.factory.CLUSTERS',
                      new=self.TEST_CLUSTERS)):

            cmd = AuroraCommandLine()
            # This should create a scheduler client, set everything up, and then issue a
            # getTasksWithoutConfigs call against the mock_scheduler_client. That should raise an
            # exception, which results in the command failing with an error code.
            result = cmd.execute(['job', 'status', 'west/bozo/test/hello'])
            assert result == EXIT_API_ERROR
            mock_scheduler_client.getTasksWithoutConfigs.assert_call_count == 1
コード例 #54
0
 def test_list_updates_command(self):
     mock_context = FakeAuroraCommandContext()
     mock_context.get_api(
         'west'
     ).query_job_updates.return_value = self.get_status_query_response()
     with contextlib.nested(
             patch('apache.aurora.client.cli.update.Update.create_context',
                   return_value=mock_context),
             patch('apache.aurora.client.factory.CLUSTERS',
                   new=self.TEST_CLUSTERS)):
         cmd = AuroraCommandLine()
         result = cmd.execute(["beta-update", "list", "west", "--user=me"])
         assert result == EXIT_OK
         assert mock_context.get_out_str() == textwrap.dedent("""\
       Job: west/mcc/test/hello, Id: hello, User: me, Status: ROLLING_FORWARD
         Created: 1411404927, Last Modified 14114056030
       Job: west/mch/prod/goodbye, Id: goodbye, User: me, Status: ROLLING_BACK
         Created: 1411300632, Last Modified 14114092632
       Job: west/mcq/devel/gasp, Id: gasp, User: me, Status: ROLL_FORWARD_PAUSED
         Created: 1411600891, Last Modified 1411800891""")
コード例 #55
0
 def test_restart_failed_status(self):
   (mock_api, mock_scheduler_proxy) = self.create_mock_api()
   mock_health_check = self.setup_health_checks(mock_api)
   self.setup_mock_scheduler_for_simple_restart(mock_api)
   mock_scheduler_proxy.getTasksWithoutConfigs.return_value = self.create_error_response()
   with contextlib.nested(
       patch('apache.aurora.client.api.SchedulerProxy', return_value=mock_scheduler_proxy),
       patch('apache.aurora.client.api.instance_watcher.StatusHealthCheck',
           return_value=mock_health_check),
       patch('time.time', side_effect=functools.partial(self.fake_time, self)),
       patch('threading._Event.wait')):
     with temporary_file() as fp:
       fp.write(self.get_valid_config())
       fp.flush()
       cmd = AuroraCommandLine()
       result = cmd.execute(['job', 'restart', '--batch-size=5', 'west/bozo/test/hello',
           '--config', fp.name])
       assert mock_scheduler_proxy.getTasksWithoutConfigs.call_count == 1
       assert mock_scheduler_proxy.restartShards.call_count == 0
       assert result == EXIT_API_ERROR
コード例 #56
0
    def test_inspect_job(self):
        mock_stdout = []

        def mock_print_out(msg, indent=0):
            indent_str = " " * indent
            mock_stdout.append("%s%s" % (indent_str, msg))

        with contextlib.nested(
                patch(
                    'apache.aurora.client.cli.context.AuroraCommandContext.print_out',
                    side_effect=mock_print_out),
                patch(
                    'apache.aurora.client.cli.context.AuroraCommandContext.get_job_config',
                    return_value=self.get_job_config())):
            cmd = AuroraCommandLine()
            assert cmd.execute(
                ['job', 'inspect', 'west/bozo/test/hello',
                 'config.aurora']) == 0
            output = '\n'.join(mock_stdout)
            assert output == '''Job level information
コード例 #57
0
    def test_inspect_job(self):
        (mock_api, mock_scheduler_proxy) = self.create_mock_api()
        AuroraCommandContext.enable_reveal_errors()
        mock_transcript = []

        def mock_print_out(msg, indent=0):
            indent_str = " " * indent
            mock_transcript.append("%s%s" % (indent_str, msg))

        with contextlib.nested(
                patch('threading._Event.wait'),
                patch('apache.aurora.client.api.SchedulerProxy',
                      return_value=mock_scheduler_proxy),
                patch('apache.aurora.client.factory.CLUSTERS',
                      new=self.TEST_CLUSTERS),
                patch(
                    'apache.aurora.client.cli.context.AuroraCommandContext.print_out',
                    side_effect=mock_print_out),
                patch('apache.aurora.client.cli.context.get_config',
                      return_value=self.get_mock_config())):
            with temporary_file() as fp:
                fp.write(self.get_valid_config())
                fp.flush()
                cmd = AuroraCommandLine()
                result = cmd.execute([
                    'job', 'inspect', '--reveal-errors',
                    'west/bozo/test/hello', fp.name
                ])
                # inspect command should run without errors, and return 0.
                assert result == 0
                # The command output for the mock should look right.
                print(mock_transcript)
                assert mock_transcript == [
                    "Job level information", "  name:       'the_job'",
                    "  role:       'bozo'", "  contact:    '*****@*****.**'",
                    "  cluster:    'west'", "  instances:  '3'", "  cron:",
                    "    schedule: '* * * * *'", "    policy:   '0'",
                    "  service:    False", "  production: False", "",
                    "Task level information", "  name: 'task'", "",
                    "Process 'process':", "  cmdline:", "    ls -la", ""
                ]
コード例 #58
0
 def test_list_updates_command_json(self):
     mock_context = FakeAuroraCommandContext()
     mock_context.get_api(
         'west'
     ).query_job_updates.return_value = self.get_status_query_response()
     with contextlib.nested(
             patch('apache.aurora.client.cli.update.Update.create_context',
                   return_value=mock_context),
             patch('apache.aurora.client.factory.CLUSTERS',
                   new=self.TEST_CLUSTERS)):
         cmd = AuroraCommandLine()
         result = cmd.execute(
             ["beta-update", "list", "west", "--user=me", '--write-json'])
         assert result == EXIT_OK
         assert mock_context.get_out_str() == textwrap.dedent("""\
       [
         {
           "status": "ROLLING_FORWARD",
           "started": 1411404927,
           "lastModified": 14114056030,
           "user": "******",
           "jobkey": "west/mcc/test/hello",
           "id": "hello"
         },
         {
           "status": "ROLLING_BACK",
           "started": 1411300632,
           "lastModified": 14114092632,
           "user": "******",
           "jobkey": "west/mch/prod/goodbye",
           "id": "goodbye"
         },
         {
           "status": "ROLL_FORWARD_PAUSED",
           "started": 1411600891,
           "lastModified": 1411800891,
           "user": "******",
           "jobkey": "west/mcq/devel/gasp",
           "id": "gasp"
         }
       ]""")
コード例 #59
0
  def generic_test_successful_run(self, cmd_args, instances):
    """Common structure of all successful run tests.
    Params:
      cmd_args: the arguments to pass to the aurora command line to run this test.
      instances: the list of instances that should be passed to a status query.
         (The status query is the only visible difference between a sharded
         run, and an all-instances run in the test.)
    """
    # Calls api.check_status, which calls scheduler_proxy.getJobs
    (mock_api, mock_scheduler_proxy) = self.create_mock_api()
    mock_scheduler_proxy.getTasksStatus.return_value = self.create_status_response()
    sandbox_args = {'slave_root': '/slaveroot', 'slave_run_directory': 'slaverun'}
    with contextlib.nested(
        patch('apache.aurora.client.api.SchedulerProxy', return_value=mock_scheduler_proxy),
        patch('apache.aurora.client.api.command_runner.'
              'InstanceDistributedCommandRunner.sandbox_args',
            return_value=sandbox_args),
        patch('subprocess.Popen', return_value=self.create_mock_process())) as (
            mock_scheduler_proxy_class,
            mock_clusters,
            mock_clusters_cli,
            mock_runner_args_patch,
            mock_subprocess):
      cmd = AuroraCommandLine()
      assert cmd.execute(cmd_args) == EXIT_OK
      # The status command sends a getTasksStatus query to the scheduler,
      # and then prints the result. The use of shards, above, should change
      # this query - that's the focus of the instances test.
      mock_scheduler_proxy.getTasksStatus.assert_called_with(TaskQuery(
          jobKeys=[JobKey(role='bozo', environment='test', name='hello')],
          statuses=set([ScheduleStatus.RUNNING, ScheduleStatus.KILLING, ScheduleStatus.RESTARTING,
              ScheduleStatus.PREEMPTING, ScheduleStatus.DRAINING]),
          instanceIds=instances))

      # The mock status call returns 3 three ScheduledTasks, so three commands should have been run
      assert mock_subprocess.call_count == 3
      mock_subprocess.assert_called_with(['ssh', '-n', '-q', 'bozo@slavehost',
          'cd /slaveroot/slaves/*/frameworks/*/executors/thermos-1287391823/runs/'
          'slaverun/sandbox;ls'],
          stderr=-2, stdout=-1)
コード例 #60
0
  def test_start_update_command_line_succeeds_noop_update(self):
    mock_context = FakeAuroraCommandContext()
    resp = self.create_simple_success_response()
    resp.details = [ResponseDetail(message="Noop update.")]
    with contextlib.nested(
        patch('apache.aurora.client.cli.update.Update.create_context', return_value=mock_context),
        patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS)):
      mock_api = mock_context.get_api(self.TEST_CLUSTER)
      mock_api.start_job_update.return_value = resp
      with temporary_file() as fp:
        fp.write(self.get_valid_config())
        fp.flush()
        cmd = AuroraCommandLine()
        result = cmd.execute(['beta-update', 'start', self.TEST_JOBSPEC, fp.name])
        assert result == EXIT_OK

      assert mock_api.start_job_update.call_count == 1
      args, kwargs = mock_api.start_job_update.call_args
      assert isinstance(args[0], AuroraConfig)
      assert args[1] is None
      assert mock_context.get_out() == ["Noop update."]
      assert mock_context.get_err() == []