Commit 01ab7ec9 authored by Niklas Hambuechen's avatar Niklas Hambuechen

QA for job filtering

Includes QA for RAPI filter management and gnt_filter.

System tests (adding/removing filters, observing their effects)
are done with gnt_filter.
Signed-off-by: default avatarNiklas Hambuechen <niklash@google.com>
Reviewed-by: default avatarKlaus Aehlig <aehlig@google.com>
parent 226455df
......@@ -1193,6 +1193,7 @@ qa_scripts = \
qa/qa_daemon.py \
qa/qa_env.py \
qa/qa_error.py \
qa/qa_filters.py \
qa/qa_group.py \
qa/qa_instance.py \
qa/qa_instance_utils.py \
......
......@@ -46,6 +46,7 @@ import qa_config
import qa_daemon
import qa_env
import qa_error
import qa_filters
import qa_group
import qa_instance
import qa_iptables
......@@ -429,6 +430,23 @@ def RunNetworkTests():
RunTestIf(["network", "tags"], qa_network.TestNetworkTags)
def RunFilterTests():
"""Run tests for job filter management.
"""
RunTestIf("filters", qa_filters.TestFilterList)
RunTestIf("filters", qa_filters.TestFilterListFields)
RunTestIf("filters", qa_filters.TestFilterAddRemove)
RunTestIf("filters", qa_filters.TestFilterReject)
RunTestIf("filters", qa_filters.TestFilterOpCode)
RunTestIf("filters", qa_filters.TestFilterReasonChain)
RunTestIf("filters", qa_filters.TestFilterContinue)
RunTestIf("filters", qa_filters.TestFilterAcceptPause)
RunTestIf("filters", qa_filters.TestFilterWatermark)
RunTestIf("filters", qa_filters.TestFilterRateLimit)
RunTestIf("filters", qa_filters.TestAdHocReasonRateLimit)
def RunGroupRwTests():
"""Run tests for adding/removing/renaming groups.
......@@ -948,6 +966,7 @@ def RunQa():
RunTestBlock(RunGroupListTests)
RunTestBlock(RunGroupRwTests)
RunTestBlock(RunNetworkTests)
RunTestBlock(RunFilterTests)
# The master shouldn't be readded or put offline; "delay" needs a non-master
# node to test
......@@ -1032,6 +1051,9 @@ def RunQa():
finally:
pnode.Release()
if qa_rapi.Enabled():
RunTestIf("filters", qa_rapi.TestFilters)
RunTestIf("cluster-upgrade", qa_cluster.TestUpgrade)
RunTestBlock(RunExclusiveStorageTests)
......
......@@ -60,6 +60,7 @@ def TestGanetiCommands():
["gnt-node", "--version"],
["gnt-os", "--version"],
["gnt-storage", "--version"],
["gnt-filter", "--version"],
["ganeti-noded", "--version"],
["ganeti-rapi", "--version"],
["ganeti-watcher", "--version"],
......
#
#
# 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
import qa_utils
from qa_utils import AssertCommand, AssertEqual, AssertIn
def stdout_of(cmd):
"""Small helper to run a stdout_of.
Makes sure the stdout_of returns exit code 0.
@type cmd: list of strings
@param cmd: the stdout_of to run
@return: Captured, stripped stdout.
"""
_, out, _ = AssertCommand(cmd)
return out.strip()
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)
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.
"""
# 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",
]))
time.sleep(0.5) # give some time to finish
AssertEqual(GetJobStatus(jid1), "queued", msg="Job should be paused")
AssertEqual(GetJobStatus(jid2), "success", msg="Job should not be paused")
# Delete the filters.
AssertCommand(["gnt-filter", "delete", uuid1])
AssertCommand(["gnt-filter", "delete", uuid2])
# Now the second job should run through
time.sleep(0.5)
AssertEqual(GetJobStatus(jid1), "success",
msg="Deleting PAUSE filter did not let job run through")
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"])
# 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([
"gnt-debug", "delay", "--print-jobid", "--submit", "20"
]))
jid2 = int(stdout_of([
"gnt-debug", "delay", "--print-jobid", "--submit", "20"
]))
jid3 = int(stdout_of([
"gnt-debug", "delay", "--print-jobid", "--submit", "20"
]))
time.sleep(0.1) # give the scheduler some time to notice
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])
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",
"--reason=rate-limit:2:hello", "20",
]))
jid2 = int(stdout_of([
"gnt-debug", "delay", "--print-jobid", "--submit",
"--reason=rate-limit:2:hello", "20",
]))
jid3 = int(stdout_of([
"gnt-debug", "delay", "--print-jobid", "--submit",
"--reason=rate-limit:2:hello", "20",
]))
time.sleep(0.1) # give the scheduler some time to notice
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])
......@@ -32,11 +32,13 @@
"""
import copy
import functools
import itertools
import random
import re
import tempfile
import uuid as uuid_module
from ganeti import cli
from ganeti import compat
......@@ -168,6 +170,15 @@ JOB_FIELDS = compat.UniqueFrozenset([
"received_ts", "start_ts", "end_ts",
])
FILTER_FIELDS = compat.UniqueFrozenset([
"watermark",
"priority",
"predicates",
"action",
"reason_trail",
"uuid",
])
LIST_FIELDS = ("id", "uri")
......@@ -320,6 +331,11 @@ def TestEmptyCluster():
for field in GROUP_FIELDS:
AssertIn(field, group)
def _VerifyFiltersBulk(data):
for group in data:
for field in FILTER_FIELDS:
AssertIn(field, group)
_DoTests([
("/", None, "GET", None),
("/2/info", _VerifyInfo, "GET", None),
......@@ -331,6 +347,8 @@ def TestEmptyCluster():
("/2/instances", [], "GET", None),
("/2/instances?bulk=1", [], "GET", None),
("/2/os", None, "GET", None),
("/2/filters", [], "GET", None),
("/2/filters?bulk=1", _VerifyFiltersBulk, "GET", None),
])
# Test HTTP Not Found
......@@ -1097,3 +1115,51 @@ def TestInterClusterInstanceMove(src_instance, dest_instance,
_InvokeMoveInstance(src_instance.name, dest_instance.name, rapi_pw_file.name,
master.primary, perform_checks,
target_nodes=(pnode.primary, snode.primary))
def TestFilters():
"""Testing filter management via the remote API.
"""
body = {
"priority": 10,
"predicates": [],
"action": "CONTINUE",
"reason": [(constants.OPCODE_REASON_SRC_USER,
"reason1",
utils.EpochNano())],
}
body1 = copy.deepcopy(body)
body1["priority"] = 20
# Query filters
_DoTests([("/2/filters", [], "GET", None)])
# Add a filter via POST and delete it again
uuid = _DoTests([("/2/filters", None, "POST", body)])[0]
uuid_module.UUID(uuid) # Check if uuid is a valid UUID
_DoTests([("/2/filters/%s" % uuid, lambda r: r is None, "DELETE", None)])
_DoTests([
# Check PUT-inserting a nonexistent filter with given UUID
("/2/filters/%s" % uuid, lambda u: u == uuid, "PUT", body),
# Check PUT-inserting an existent filter with given UUID
("/2/filters/%s" % uuid, lambda u: u == uuid, "PUT", body1),
# Check that the update changed the filter
("/2/filters/%s" % uuid, lambda f: f["priority"] == 20, "GET", None),
# Delete it again
("/2/filters/%s" % uuid, lambda r: r is None, "DELETE", None),
])
# Add multiple filters, query and delete them
uuids = _DoTests([
("/2/filters", None, "POST", body),
("/2/filters", None, "POST", body),
("/2/filters", None, "POST", body),
])
_DoTests([("/2/filters", lambda rs: [r["uuid"] for r in rs] == uuids,
"GET", None)])
for u in uuids:
_DoTests([("/2/filters/%s" % u, lambda r: r is None, "DELETE", None)])
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment