qa_filters.py 11.7 KB
Newer Older
Niklas Hambuechen's avatar
Niklas Hambuechen committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#
#

# Copyright (C) 2014 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


"""QA tests for job filters.

"""

import time

from ganeti import query
38
from ganeti.utils import retry
Niklas Hambuechen's avatar
Niklas Hambuechen committed
39

40
import qa_job_utils
Niklas Hambuechen's avatar
Niklas Hambuechen committed
41
import qa_utils
Klaus Aehlig's avatar
Klaus Aehlig committed
42
from qa_utils import AssertCommand, AssertEqual, AssertIn, stdout_of
Niklas Hambuechen's avatar
Niklas Hambuechen committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76


def GetJobStatus(job_id):
  """Queries the status of the job by parsing output of gnt-job info.

  @type job_id: int
  @param job_id: ID of the job to query
  @return: status of the job as lower-case string

  """
  out = stdout_of(["gnt-job", "info", str(job_id)])
  # The second line of gnt-job info shows the status.
  return out.split('\n')[1].strip().lower().split("status: ")[1]


def KillWaitJobs(job_ids):
  """Kills the lists of jobs, then watches them so that when this function
  returns we can be sure the jobs are all done.

  This should be called at the end of tests that started jobs with --submit
  so that following tests have an empty job queue.

  @type job_ids: list of int
  @param job_ids: the lists of job IDs to kill and wait for
  """
  # We use fail=None to ignore the exit code, since it can be non-zero
  # if the job is already terminated.
  for jid in job_ids:
    AssertCommand(["gnt-job", "cancel", "--kill", "--yes-do-it", str(jid)],
                  fail=None)
  for jid in job_ids:
    AssertCommand(["gnt-job", "watch", str(jid)], fail=None)


77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
def AssertStatusRetry(jid, status, interval=1.0, timeout=20.0):
  """Keeps polling the given job until a given status is reached.

  @type jid: int
  @param jid: job ID of the job to poll
  @type status: string
  @param status: status to wait for
  @type interval: float
  @param interval: polling interval in seconds
  @type timeout: float
  @param timeout: polling timeout in seconds

  @raise retry:RetryTimeout: If the status was not reached within the timeout
  """
  retry_fn = lambda: qa_job_utils.RetryingUntilJobStatus(status, str(jid))
  retry.Retry(retry_fn, interval, timeout)


Niklas Hambuechen's avatar
Niklas Hambuechen committed
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
def TestFilterList():
  """gnt-filter list"""
  qa_utils.GenericQueryTest("gnt-filter", query.FILTER_FIELDS.keys(),
                            namefield="uuid", test_unknown=False)


def TestFilterListFields():
  """gnt-filter list-fields"""
  qa_utils.GenericQueryFieldsTest("gnt-filter", query.FILTER_FIELDS.keys())


def TestFilterAddRemove():
  """gnt-filter add/delete"""

  uuid1 = stdout_of(["gnt-filter", "add", "--reason", "reason1"])

  TestFilterList()
  TestFilterListFields()

  uuid2 = stdout_of(["gnt-filter", "list", "--no-headers", "--output=uuid"])

  AssertEqual(uuid1, uuid2)

  AssertCommand(["gnt-filter", "delete", uuid1])

  TestFilterList()


def TestFilterWatermark():
  """Tests that the filter watermark is set correctly"""

  # Check what the current highest job ID is
  highest_jid1 = int(stdout_of(
    ["gnt-debug", "delay", "--print-jobid", "0.01"]
  ))

  # Add the filter; this sets the watermark
  uuid = stdout_of(["gnt-filter", "add"])

  # Check what the current highest job ID is
  highest_jid2 = int(stdout_of(
    ["gnt-debug", "delay", "--print-jobid", "0.01"]
  ))

  info_out = stdout_of(["gnt-filter", "info", uuid])
  # The second line of gnt-filter info shows the watermark.
  watermark = int(
    info_out.split('\n')[1].strip().lower().split("watermark: ")[1]
  )

  # The atermark must be at least as high as the JID of the job we started
  # just before the creation, and must be lower than the JID of any job
  # created afterwards.
  assert highest_jid1 <= watermark < highest_jid2, \
    "Watermark not in range: %d <= %d < %d" % (highest_jid1, watermark,
                                               highest_jid2)

  # Clean up.
  AssertCommand(["gnt-filter", "delete", uuid])


def TestFilterReject():
  """Tests that the REJECT filter does reject new jobs and that the
  "jobid" predicate works.
  """

  # Add a filter that rejects all new jobs.
  uuid = stdout_of([
    "gnt-filter", "add",
    '--predicates=[["jobid", [">", "id", "watermark"]]]',
    "--action=REJECT",
  ])

  # Newly queued jobs must now fail.
  AssertCommand(["gnt-debug", "delay", "0.01"], fail=True)

  # Clean up.
  AssertCommand(["gnt-filter", "delete", uuid])


def TestFilterOpCode():
  """Tests that filtering with the "opcode" predicate works"""

  # Check that delay jobs work fine.
  AssertCommand(["gnt-debug", "delay", "0.01"])

  # Add a filter that rejects all new delay jobs.
  uuid = stdout_of([
    "gnt-filter", "add",
    '--predicates=[["opcode", ["=", "OP_ID", "OP_TEST_DELAY"]]]',
    "--action=REJECT",
  ])

  # Newly queued delay jobs must now fail.
  AssertCommand(["gnt-debug", "delay", "0.01"], fail=True)

  # Clean up.
  AssertCommand(["gnt-filter", "delete", uuid])


def TestFilterContinue():
  """Tests that the CONTINUE filter has no effect"""

  # Add a filter that just passes to the next filter.
  uuid_cont = stdout_of([
    "gnt-filter", "add",
    '--predicates=[["jobid", [">", "id", "watermark"]]]',
    "--action=CONTINUE",
    "--priority=0",
  ])

  # Add a filter that rejects all new jobs.
  uuid_reject = stdout_of([
    "gnt-filter", "add",
    '--predicates=[["jobid", [">", "id", "watermark"]]]',
    "--action=REJECT",
    "--priority=1",
  ])

  # Newly queued jobs must now fail.
  AssertCommand(["gnt-debug", "delay", "0.01"], fail=True)

  # Delete the rejecting filter.
  AssertCommand(["gnt-filter", "delete", uuid_reject])

  # Newly queued jobs must now succeed.
  AssertCommand(["gnt-debug", "delay", "0.01"])

  # Clean up.
  AssertCommand(["gnt-filter", "delete", uuid_cont])


def TestFilterReasonChain():
  """Tests that filters are processed in the right order and that the
  "reason" predicate works.
  """

  # Add a filter chain that pauses all new jobs apart from those with a
  # specific reason.

  # Accept all jobs that have the "allow this" reason.
  uuid1 = stdout_of([
    "gnt-filter",
    "add",
    '--predicates=[["reason", ["=", "reason", "allow this"]]]',
    "--action=ACCEPT",
    # Default priority 0
  ])

  # Reject those that haven't (but make the one above run first).
  uuid2 = stdout_of([
    "gnt-filter",
    "add",
    '--predicates=[["jobid", [">", "id", "watermark"]]]',
    "--action=REJECT",
    "--priority=1",
  ])

  # This job must now go into queued status.
  AssertCommand(["gnt-debug", "delay", "0.01"], fail=True)
  AssertCommand(["gnt-debug", "delay", "--reason=allow this", "0.01"])

  # Clean up.
  AssertCommand(["gnt-filter", "delete", uuid1])
  AssertCommand(["gnt-filter", "delete", uuid2])


def TestFilterAcceptPause():
  """Tests that the PAUSE filter allows scheduling, but prevents starting,
  and that the ACCEPT filter immediately allows starting.
  """

267 268
  AssertCommand(["gnt-cluster", "watcher", "pause", "600"])

Niklas Hambuechen's avatar
Niklas Hambuechen committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
  # Add a filter chain that pauses all new jobs apart from those with a
  # specific reason.
  # When the pausing filter is deleted, paused jobs must be continued.

  # Accept all jobs that have the "allow this" reason.
  uuid1 = stdout_of([
    "gnt-filter",
    "add",
    '--predicates=[["reason", ["=", "reason", "allow this"]]]',
    "--action=ACCEPT",
    # Default priority 0
  ])

  # Pause those that haven't (but make the one above run first).
  uuid2 = stdout_of([
    "gnt-filter",
    "add",
    '--predicates=[["jobid", [">", "id", "watermark"]]]',
    "--action=PAUSE",
    "--priority=1",
  ])

  # This job must now go into queued status.
  jid1 = int(stdout_of([
    "gnt-debug", "delay", "--submit", "--print-jobid", "0.01",
  ]))

  # This job should run and finish.
  jid2 = int(stdout_of([
    "gnt-debug", "delay", "--submit", "--print-jobid", "--reason=allow this",
    "0.01",
  ]))

302
  time.sleep(5)  # give some time to get queued
Niklas Hambuechen's avatar
Niklas Hambuechen committed
303

304 305
  AssertStatusRetry(jid1, "queued")  # job should be paused
  AssertStatusRetry(jid2, "success")  # job should not be paused
Niklas Hambuechen's avatar
Niklas Hambuechen committed
306 307 308 309 310

  # Delete the filters.
  AssertCommand(["gnt-filter", "delete", uuid1])
  AssertCommand(["gnt-filter", "delete", uuid2])

311
  # Now the paused job should run through.
312
  time.sleep(5)
313
  AssertStatusRetry(jid1, "success")
Niklas Hambuechen's avatar
Niklas Hambuechen committed
314

315 316
  AssertCommand(["gnt-cluster", "watcher", "continue"])

Niklas Hambuechen's avatar
Niklas Hambuechen committed
317 318 319 320 321 322 323 324 325 326

def TestFilterRateLimit():
  """Tests that the RATE_LIMIT filter does reject new jobs when all
  rate-limiting buckets are taken.
  """

  # Make sure our test is not constrained by "max-running-jobs"
  # (simply set it to the default).
  AssertCommand(["gnt-cluster", "modify", "--max-running-jobs=20"])
  AssertCommand(["gnt-cluster", "modify", "--max-tracked-jobs=25"])
327
  AssertCommand(["gnt-cluster", "watcher", "pause", "600"])
Niklas Hambuechen's avatar
Niklas Hambuechen committed
328 329 330 331 332 333 334 335 336 337

  # Add a filter that rejects all new jobs.
  uuid = stdout_of([
    "gnt-filter", "add",
    '--predicates=[["jobid", [">", "id", "watermark"]]]',
    "--action=RATE_LIMIT 2",
  ])

  # Now only the first 2 jobs must be scheduled.
  jid1 = int(stdout_of([
338
    "gnt-debug", "delay", "--print-jobid", "--submit", "200"
Niklas Hambuechen's avatar
Niklas Hambuechen committed
339 340
  ]))
  jid2 = int(stdout_of([
341
    "gnt-debug", "delay", "--print-jobid", "--submit", "200"
Niklas Hambuechen's avatar
Niklas Hambuechen committed
342 343
  ]))
  jid3 = int(stdout_of([
344
    "gnt-debug", "delay", "--print-jobid", "--submit", "200"
Niklas Hambuechen's avatar
Niklas Hambuechen committed
345 346
  ]))

347
  time.sleep(5)  # give the scheduler some time to notice
Niklas Hambuechen's avatar
Niklas Hambuechen committed
348 349 350 351 352 353 354 355 356 357

  AssertIn(GetJobStatus(jid1), ["running", "waiting"],
           msg="Job should not be rate-limited")
  AssertIn(GetJobStatus(jid2), ["running", "waiting"],
           msg="Job should not be rate-limited")
  AssertEqual(GetJobStatus(jid3), "queued", msg="Job should be rate-limited")

  # Clean up.
  AssertCommand(["gnt-filter", "delete", uuid])
  KillWaitJobs([jid1, jid2, jid3])
358
  AssertCommand(["gnt-cluster", "watcher", "continue"])
Niklas Hambuechen's avatar
Niklas Hambuechen committed
359 360 361 362 363 364 365 366 367 368 369 370 371 372


def TestAdHocReasonRateLimit():
  """Tests that ad-hoc rate limiting using --reason="rate-limit:n:..." works.
  """

  # Make sure our test is not constrained by "max-running-jobs"
  # (simply set it to the default).
  AssertCommand(["gnt-cluster", "modify", "--max-running-jobs=20"])
  AssertCommand(["gnt-cluster", "modify", "--max-tracked-jobs=25"])

  # Only the first 2 jobs must be scheduled.
  jid1 = int(stdout_of([
    "gnt-debug", "delay", "--print-jobid", "--submit",
373
    "--reason=rate-limit:2:hello", "200",
Niklas Hambuechen's avatar
Niklas Hambuechen committed
374 375 376
  ]))
  jid2 = int(stdout_of([
    "gnt-debug", "delay", "--print-jobid", "--submit",
377
    "--reason=rate-limit:2:hello", "200",
Niklas Hambuechen's avatar
Niklas Hambuechen committed
378 379 380
  ]))
  jid3 = int(stdout_of([
    "gnt-debug", "delay", "--print-jobid", "--submit",
381
    "--reason=rate-limit:2:hello", "200",
Niklas Hambuechen's avatar
Niklas Hambuechen committed
382 383
  ]))

384
  time.sleep(5)  # give the scheduler some time to notice
Niklas Hambuechen's avatar
Niklas Hambuechen committed
385 386 387 388 389 390 391 392 393

  AssertIn(GetJobStatus(jid1), ["running", "waiting"],
           msg="Job should not be rate-limited")
  AssertIn(GetJobStatus(jid2), ["running", "waiting"],
           msg="Job should not be rate-limited")
  AssertEqual(GetJobStatus(jid3), "queued", msg="Job should be rate-limited")

  # Clean up.
  KillWaitJobs([jid1, jid2, jid3])