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 2014/02/19 19:08:37 UTC

git commit: Added "sla get_job_uptime" command.

Repository: incubator-aurora
Updated Branches:
  refs/heads/master d3c61cf1f -> dadb6509a


Added "sla get_job_uptime" command.

Bugs closed: AURORA-207

Reviewed at https://reviews.apache.org/r/18153/


Project: http://git-wip-us.apache.org/repos/asf/incubator-aurora/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-aurora/commit/dadb6509
Tree: http://git-wip-us.apache.org/repos/asf/incubator-aurora/tree/dadb6509
Diff: http://git-wip-us.apache.org/repos/asf/incubator-aurora/diff/dadb6509

Branch: refs/heads/master
Commit: dadb6509a5ba65f897cc7d6948c062445ac81f7f
Parents: d3c61cf
Author: Maxim Khutornenko <ma...@apache.org>
Authored: Wed Feb 19 10:02:46 2014 -0800
Committer: Maxim Khutornenko <ma...@apache.org>
Committed: Wed Feb 19 10:02:46 2014 -0800

----------------------------------------------------------------------
 src/main/python/apache/aurora/client/api/sla.py | 16 ++++-
 .../python/apache/aurora/client/cli/options.py  | 31 ++++++++--
 src/main/python/apache/aurora/client/cli/sla.py | 51 ++++++++++++---
 .../python/apache/aurora/client/api/test_sla.py | 44 ++++++++++++-
 .../python/apache/aurora/client/cli/test_sla.py | 65 +++++++++++++++++---
 5 files changed, 183 insertions(+), 24 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-aurora/blob/dadb6509/src/main/python/apache/aurora/client/api/sla.py
----------------------------------------------------------------------
diff --git a/src/main/python/apache/aurora/client/api/sla.py b/src/main/python/apache/aurora/client/api/sla.py
index b69d208..b0b2b24 100644
--- a/src/main/python/apache/aurora/client/api/sla.py
+++ b/src/main/python/apache/aurora/client/api/sla.py
@@ -51,12 +51,26 @@ class JobUpTimeSlaVector(object):
     above = len([uptime for uptime in self._uptime_map.values() if uptime >= duration])
     return 0 if not total else 100.0 * above / total
 
+  def get_job_uptime(self, percentile):
+    """Returns the uptime (in seconds) of the job at the specified percentile.
+
+    Arguments:
+    percentile -- percentile to report uptime for.
+    """
+    if percentile <= 0 or percentile >= 100:
+      raise ValueError('Percentile must be within (0, 100), got %r instead.' % percentile)
+
+    total = len(self._uptime_map)
+    value = math.floor(percentile / 100.0 * total)
+    index = total - int(value) - 1
+    return sorted(self._uptime_map.values())[index] if 0 <= index < total else 0
+
   def _instance_uptime(self):
     instance_map = {}
     for task in self._tasks:
       for event in task.taskEvents:
         if event.status == ScheduleStatus.STARTING:
-          instance_map[task.assignedTask.instanceId] = self._now - event.timestamp / 1000
+          instance_map[task.assignedTask.instanceId] = math.floor(self._now - event.timestamp / 1000)
           break
     return instance_map
 

http://git-wip-us.apache.org/repos/asf/incubator-aurora/blob/dadb6509/src/main/python/apache/aurora/client/cli/options.py
----------------------------------------------------------------------
diff --git a/src/main/python/apache/aurora/client/cli/options.py b/src/main/python/apache/aurora/client/cli/options.py
index 1cbde5e..2f37372 100644
--- a/src/main/python/apache/aurora/client/cli/options.py
+++ b/src/main/python/apache/aurora/client/cli/options.py
@@ -20,6 +20,7 @@ from types import IntType, StringType
 from apache.aurora.common.aurora_job_key import AuroraJobKey
 
 from twitter.common.quantity.parse_simple import parse_time
+from argparse import ArgumentTypeError
 
 
 class CommandOption(object):
@@ -83,13 +84,12 @@ class CommandOption(object):
 
 def parse_qualified_role(rolestr):
   if rolestr is None:
-    raise ValueError('Role argument cannot be empty!')
+    raise ArgumentTypeError('Role argument cannot be empty!')
   role_parts = rolestr.split('/')
   if len(role_parts) != 2:
-    raise ValueError('Role argument must be a CLUSTER/NAME pair')
+    raise ArgumentTypeError('Role argument must be a CLUSTER/NAME pair')
   return role_parts
 
-
 def parse_instances(instances):
   """Parse lists of instances or instance ranges into a set().
      Examples:
@@ -111,9 +111,28 @@ def parse_time_values(time_values):
        15m
        1m,1d,3h25m,2h4m15s
   """
-  if time_values is None or time_values == '':
-    return None
-  return sorted(map(parse_time, time_values.split(',')))
+  try:
+    return sorted(map(parse_time, time_values.split(','))) if time_values else None
+  except ValueError as e:
+    raise ArgumentTypeError(e)
+
+def parse_percentiles(percentiles):
+  """Parse lists of percentile values in (0,100) range.
+     Examples:
+       .2
+       10,15,99.9
+  """
+  def parse_percentile(val):
+    try:
+      result = float(val)
+      if result <= 0 or result >= 100:
+        raise ValueError()
+    except ValueError:
+      raise ArgumentTypeError('Invalid percentile value:%s. '
+                              'Must be between 0.0 and 100.0 exclusive.' % val)
+    return result
+
+  return sorted(map(parse_percentile, percentiles.split(','))) if percentiles else None
 
 
 TaskInstanceKey = namedtuple('TaskInstanceKey', [ 'jobkey', 'instance' ])

http://git-wip-us.apache.org/repos/asf/incubator-aurora/blob/dadb6509/src/main/python/apache/aurora/client/cli/sla.py
----------------------------------------------------------------------
diff --git a/src/main/python/apache/aurora/client/cli/sla.py b/src/main/python/apache/aurora/client/cli/sla.py
index 0200270..9dd766b 100644
--- a/src/main/python/apache/aurora/client/cli/sla.py
+++ b/src/main/python/apache/aurora/client/cli/sla.py
@@ -20,7 +20,12 @@ from apache.aurora.client.cli import (
     Verb,
 )
 from apache.aurora.client.cli.context import AuroraCommandContext
-from apache.aurora.client.cli.options import CommandOption, JOBSPEC_ARGUMENT, parse_time_values
+from apache.aurora.client.cli.options import (
+    CommandOption, 
+    JOBSPEC_ARGUMENT, 
+    parse_percentiles, 
+    parse_time_values
+)
 
 from twitter.common.quantity import Time
 
@@ -36,25 +41,22 @@ class GetTaskUpCountCmd(Verb):
 If duration is not specified prints a histogram-like log-scale distribution
 of task uptime percentages.
 """
-
+  
   @classmethod
   def render_get_task_up_count(cls, context, vector):
     def format_output(durations):
-      return ['%s\t- %.2f%%' % (duration, vector.get_task_up_count(duration.as_(Time.SECONDS)))
+      return ['%s\t- %.2f %%' % (duration, vector.get_task_up_count(duration.as_(Time.SECONDS)))
           for duration in durations]
 
     durations = context.options.durations or parse_time_values('1m,10m,1h,12h,7d')
     return '\n'.join(format_output(durations))
 
-
   def get_options(self):
     return [
         CommandOption('--durations', type=parse_time_values, default=None,
             help="""Durations to report uptime for.
 Format: XdYhZmWs (each field optional but must be in that order.)
-Examples:
- --durations=1d'
-  --durations=3m,10s,1h3m10s"""),
+Example: --durations=3m,10s,1h3m10s"""),
         JOBSPEC_ARGUMENT]
 
   def execute(self, context):
@@ -64,6 +66,40 @@ Examples:
     return EXIT_OK
 
 
+class GetJobUptimeCmd(Verb):
+  @property
+  def name(self):
+    return 'get_job_uptime'
+
+  @property
+  def help(self):
+    return """Prints the job uptime at the specified percentile. If the percentile
+is not specified prints a histogram-like distribution of uptime percentiles.
+"""
+
+  @classmethod
+  def render_get_job_uptime(cls, context, vector):
+    def format_output(percentiles):
+      return ['%s percentile\t- %s seconds' % (percentile, vector.get_job_uptime(percentile))
+              for percentile in sorted(percentiles, reverse=True)]
+
+    percentiles = context.options.percentiles or parse_percentiles('99,95,90,85,75,60,50,30,10')
+    return '\n'.join(format_output(percentiles))
+
+  def get_options(self):
+    return [
+        CommandOption('--percentiles', type=parse_percentiles, default=None,
+            help="""Percentiles to report uptime for. Format: values within (0.0, 100.0).
+Example: --percentiles=50,75,95.5"""),
+        JOBSPEC_ARGUMENT]
+
+  def execute(self, context):
+    api = context.get_api(context.options.jobspec.cluster)
+    vector = api.sla_get_job_uptime_vector(context.options.jobspec)
+    context.print_out(self.render_get_job_uptime(context, vector))
+    return EXIT_OK
+
+
 class Sla(Noun):
   @property
   def name(self):
@@ -80,3 +116,4 @@ class Sla(Noun):
   def __init__(self):
     super(Sla, self).__init__()
     self.register_verb(GetTaskUpCountCmd())
+    self.register_verb(GetJobUptimeCmd())

http://git-wip-us.apache.org/repos/asf/incubator-aurora/blob/dadb6509/src/test/python/apache/aurora/client/api/test_sla.py
----------------------------------------------------------------------
diff --git a/src/test/python/apache/aurora/client/api/test_sla.py b/src/test/python/apache/aurora/client/api/test_sla.py
index 54f904c..2e6c8fa 100644
--- a/src/test/python/apache/aurora/client/api/test_sla.py
+++ b/src/test/python/apache/aurora/client/api/test_sla.py
@@ -67,20 +67,36 @@ class SlaTest(unittest.TestCase):
   def create_tasks(self, durations):
     return [self.create_task(duration, index) for index, duration in enumerate(durations)]
 
-
   def assert_count_result(self, percentage, duration):
     vector = self._sla.get_job_uptime_vector(self._job_key)
     actual = vector.get_task_up_count(duration)
     assert percentage == actual, (
         'Expected percentage:%s Actual percentage:%s' % (percentage, actual)
     )
+    self.expect_task_status_call()
+
+  def assert_uptime_result(self, expected, percentile):
+    vector = self._sla.get_job_uptime_vector(self._job_key)
+    try:
+      actual = vector.get_job_uptime(percentile)
+    except ValueError:
+      assert expected is None, 'Unexpected error raised.'
+    else:
+      assert expected is not None, 'Expected error not raised.'
+      assert expected == actual, (
+          'Expected uptime:%s Actual uptime:%s' % (expected, actual)
+      )
+      self.expect_task_status_call()
 
+  def expect_task_status_call(self):
     self._scheduler.getTasksStatus.assert_called_once_with(
         TaskQuery(
             owner=Identity(role=self._role),
             environment=self._env,
             jobName=self._name,
-            statuses=ACTIVE_STATES))
+            statuses=ACTIVE_STATES)
+    )
+
 
   def test_count_0(self):
     self.mock_get_tasks([])
@@ -93,3 +109,27 @@ class SlaTest(unittest.TestCase):
   def test_count_100(self):
     self.mock_get_tasks(self.create_tasks([100, 200, 300, 400, 500]))
     self.assert_count_result(100, 50)
+
+  def test_uptime_empty(self):
+    self.mock_get_tasks([])
+    self.assert_uptime_result(0, 50)
+
+  def test_uptime_0(self):
+    self.mock_get_tasks(self.create_tasks([100, 200, 300, 400]))
+    self.assert_uptime_result(None, 0)
+
+  def test_uptime_10(self):
+    self.mock_get_tasks(self.create_tasks([100, 200, 300, 400]))
+    self.assert_uptime_result(400, 10)
+
+  def test_uptime_50(self):
+    self.mock_get_tasks(self.create_tasks([100, 200, 300, 400]))
+    self.assert_uptime_result(200, 50)
+
+  def test_uptime_99(self):
+    self.mock_get_tasks(self.create_tasks([100, 200, 300, 400]))
+    self.assert_uptime_result(100, 99)
+
+  def test_uptime_100(self):
+    self.mock_get_tasks(self.create_tasks([100, 200, 300, 400]))
+    self.assert_uptime_result(None, 100)

http://git-wip-us.apache.org/repos/asf/incubator-aurora/blob/dadb6509/src/test/python/apache/aurora/client/cli/test_sla.py
----------------------------------------------------------------------
diff --git a/src/test/python/apache/aurora/client/cli/test_sla.py b/src/test/python/apache/aurora/client/cli/test_sla.py
index 703d39e..46f3e8d 100644
--- a/src/test/python/apache/aurora/client/cli/test_sla.py
+++ b/src/test/python/apache/aurora/client/cli/test_sla.py
@@ -39,11 +39,11 @@ class TestGetTaskUpCountCommand(AuroraClientCommandTest):
       cmd = AuroraCommandLine()
       cmd.execute(['sla', 'get_task_up_count', 'west/role/env/test'])
       out = '\n'.join(mock_context.get_out())
-      assert '1 mins\t- 10.65%\n' in out
-      assert '10 mins\t- 10.65%\n' in out
-      assert '1 hrs\t- 10.65%\n' in out
-      assert '12 hrs\t- 10.65%\n' in out
-      assert '7 days\t- 10.65%' in out
+      assert '1 mins\t- 10.65 %\n' in out
+      assert '10 mins\t- 10.65 %\n' in out
+      assert '1 hrs\t- 10.65 %\n' in out
+      assert '12 hrs\t- 10.65 %\n' in out
+      assert '7 days\t- 10.65 %' in out
 
   def test_get_task_up_count_with_durations(self):
     mock_context = FakeAuroraCommandContext()
@@ -54,6 +54,55 @@ class TestGetTaskUpCountCommand(AuroraClientCommandTest):
       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
+      assert '3 mins\t- 95.36 %' in out
+      assert '54 hrs\t- 95.36 %' in out
+      assert '3 hrs\t- 95.36 %' in out
+
+
+class TestGetJobUptimeCommand(AuroraClientCommandTest):
+  @classmethod
+  def setup_mock_sla_uptime_vector(cls, mock_context, uptime):
+    api = mock_context.get_api('west')
+    response = Mock()
+    response.get_job_uptime.return_value = uptime
+    api.sla_get_job_uptime_vector.return_value = response
+
+  def test_get_job_uptime_no_percentile(self):
+    mock_context = FakeAuroraCommandContext()
+    self.setup_mock_sla_uptime_vector(mock_context, 915)
+    with contextlib.nested(
+        patch('apache.aurora.client.cli.sla.Sla.create_context', return_value=mock_context),
+        patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS)):
+      cmd = AuroraCommandLine()
+      cmd.execute(['sla', 'get_job_uptime', 'west/role/env/test'])
+      out = '\n'.join(mock_context.get_out())
+      assert '99.0 percentile\t- 915 seconds' in out
+      assert '95.0 percentile\t- 915 seconds' in out
+      assert '90.0 percentile\t- 915 seconds' in out
+      assert '85.0 percentile\t- 915 seconds' in out
+      assert '75.0 percentile\t- 915 seconds' in out
+      assert '60.0 percentile\t- 915 seconds' in out
+      assert '50.0 percentile\t- 915 seconds' in out
+      assert '30.0 percentile\t- 915 seconds' in out
+      assert '10.0 percentile\t- 915 seconds' in out
+
+  def test_get_job_uptime_with_percentiles(self):
+    mock_context = FakeAuroraCommandContext()
+    self.setup_mock_sla_uptime_vector(mock_context, 915)
+    with contextlib.nested(
+        patch('apache.aurora.client.cli.sla.Sla.create_context', return_value=mock_context),
+        patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS)):
+      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
+
+  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.'