#
#
-# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Google Inc.
+# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
"""
-# pylint: disable-msg=C0103
+# pylint: disable=C0103
# C0103: Invalid name, since the R_* names are not conforming
from ganeti import opcodes
+from ganeti import objects
from ganeti import http
from ganeti import constants
from ganeti import cli
I_FIELDS = ["name", "admin_state", "os",
"pnode", "snodes",
"disk_template",
- "nic.ips", "nic.macs", "nic.modes", "nic.links", "nic.bridges",
+ "nic.ips", "nic.macs", "nic.modes", "nic.uuids", "nic.names",
+ "nic.links", "nic.networks", "nic.networks.names", "nic.bridges",
"network_port",
- "disk.sizes", "disk_usage",
+ "disk.sizes", "disk.spindles", "disk_usage", "disk.uuids",
+ "disk.names",
"beparams", "hvparams",
"oper_state", "oper_ram", "oper_vcpus", "status",
"custom_hvparams", "custom_beparams", "custom_nicparams",
] + _COMMON_FIELDS
N_FIELDS = ["name", "offline", "master_candidate", "drained",
- "dtotal", "dfree",
+ "dtotal", "dfree", "sptotal", "spfree",
"mtotal", "mnode", "mfree",
"pinst_cnt", "sinst_cnt",
- "ctotal", "cnodes", "csockets",
+ "ctotal", "cnos", "cnodes", "csockets",
"pip", "sip", "role",
"pinst_list", "sinst_list",
"master_capable", "vm_capable",
+ "ndparams",
"group.uuid",
] + _COMMON_FIELDS
+NET_FIELDS = ["name", "network", "gateway",
+ "network6", "gateway6",
+ "mac_prefix",
+ "free_count", "reserved_count",
+ "map", "group_list", "inst_list",
+ "external_reservations",
+ ] + _COMMON_FIELDS
+
G_FIELDS = [
"alloc_policy",
"name",
"node_cnt",
"node_list",
+ "ipolicy",
+ "custom_ipolicy",
+ "diskparams",
+ "custom_diskparams",
+ "ndparams",
+ "custom_ndparams",
] + _COMMON_FIELDS
J_FIELDS_BULK = [
# Feature string for node evacuation with LU-generated jobs
_NODE_EVAC_RES1 = "node-evac-res1"
-ALL_FEATURES = frozenset([
+ALL_FEATURES = compat.UniqueFrozenset([
_INST_CREATE_REQV1,
_INST_REINSTALL_REQV1,
_NODE_MIGRATE_REQV1,
_WFJC_TIMEOUT = 10
+# FIXME: For compatibility we update the beparams/memory field. Needs to be
+# removed in Ganeti 2.8
+def _UpdateBeparams(inst):
+ """Updates the beparams dict of inst to support the memory field.
+
+ @param inst: Inst dict
+ @return: Updated inst dict
+
+ """
+ beparams = inst["beparams"]
+ beparams[constants.BE_MEMORY] = beparams[constants.BE_MAXMEM]
+
+ return inst
+
+
class R_root(baserlib.ResourceBase):
"""/ resource.
return None
+class R_2(R_root):
+ """/2 resource.
+
+ """
+
+
class R_version(baserlib.ResourceBase):
"""/version resource.
return constants.RAPI_VERSION
-class R_2_info(baserlib.ResourceBase):
+class R_2_info(baserlib.OpcodeResource):
"""/2/info resource.
"""
+ GET_OPCODE = opcodes.OpClusterQuery
+
def GET(self):
"""Returns cluster information.
"""
- client = self.GetClient()
+ client = self.GetClient(query=True)
return client.QueryClusterInfo()
return list(ALL_FEATURES)
-class R_2_os(baserlib.ResourceBase):
+class R_2_os(baserlib.OpcodeResource):
"""/2/os resource.
"""
+ GET_OPCODE = opcodes.OpOsDiagnose
+
def GET(self):
"""Return a list of all OSes.
@return: a dictionary with jobs id and uri.
"""
- client = self.GetClient()
+ client = self.GetClient(query=True)
if self.useBulk():
bulkdata = client.QueryJobs(None, J_FIELDS_BULK)
"""
job_id = self.items[0]
- result = self.GetClient().QueryJobs([job_id, ], J_FIELDS)[0]
+ result = self.GetClient(query=True).QueryJobs([job_id, ], J_FIELDS)[0]
if result is None:
raise http.HttpNotFound()
return baserlib.MapFields(J_FIELDS, result)
}
-class R_2_nodes(baserlib.ResourceBase):
+class R_2_nodes(baserlib.OpcodeResource):
"""/2/nodes resource.
"""
+ GET_OPCODE = opcodes.OpNodeQuery
+
def GET(self):
"""Returns a list of all nodes.
"""
- client = self.GetClient()
+ client = self.GetClient(query=True)
if self.useBulk():
bulkdata = client.QueryNodes([], N_FIELDS, False)
uri_fields=("id", "uri"))
-class R_2_nodes_name(baserlib.ResourceBase):
+class R_2_nodes_name(baserlib.OpcodeResource):
"""/2/nodes/[node_name] resource.
"""
+ GET_OPCODE = opcodes.OpNodeQuery
+
def GET(self):
"""Send information about a node.
"""
node_name = self.items[0]
- client = self.GetClient()
+ client = self.GetClient(query=True)
result = baserlib.HandleItemQueryErrors(client.QueryNodes,
names=[node_name], fields=N_FIELDS,
return baserlib.MapFields(N_FIELDS, result[0])
+class R_2_nodes_name_powercycle(baserlib.OpcodeResource):
+ """/2/nodes/[node_name]/powercycle resource.
+
+ """
+ POST_OPCODE = opcodes.OpNodePowercycle
+
+ def GetPostOpInput(self):
+ """Tries to powercycle a node.
+
+ """
+ return (self.request_body, {
+ "node_name": self.items[0],
+ "force": self.useForce(),
+ })
+
+
class R_2_nodes_name_role(baserlib.OpcodeResource):
"""/2/nodes/[node_name]/role resource.
"""
node_name = self.items[0]
- client = self.GetClient()
+ client = self.GetClient(query=True)
result = client.QueryNodes(names=[node_name], fields=["role"],
use_locking=self.useLocking())
"offline": offline,
"drained": drained,
"force": self.useForce(),
+ "auto_promote": bool(self._checkIntVariable("auto-promote", default=0)),
})
})
-class R_2_nodes_name_storage(baserlib.ResourceBase):
+class R_2_nodes_name_modify(baserlib.OpcodeResource):
+ """/2/nodes/[node_name]/modify resource.
+
+ """
+ POST_OPCODE = opcodes.OpNodeSetParams
+
+ def GetPostOpInput(self):
+ """Changes parameters of a node.
+
+ """
+ assert len(self.items) == 1
+
+ return (self.request_body, {
+ "node_name": self.items[0],
+ })
+
+
+class R_2_nodes_name_storage(baserlib.OpcodeResource):
"""/2/nodes/[node_name]/storage resource.
"""
# LUNodeQueryStorage acquires locks, hence restricting access to GET
GET_ACCESS = [rapi.RAPI_ACCESS_WRITE]
+ GET_OPCODE = opcodes.OpNodeQueryStorage
- def GET(self):
- node_name = self.items[0]
+ def GetGetOpInput(self):
+ """List storage available on a node.
+ """
storage_type = self._checkStringVariable("storage_type", None)
- if not storage_type:
- raise http.HttpBadRequest("Missing the required 'storage_type'"
- " parameter")
-
output_fields = self._checkStringVariable("output_fields", None)
+
if not output_fields:
raise http.HttpBadRequest("Missing the required 'output_fields'"
" parameter")
- op = opcodes.OpNodeQueryStorage(nodes=[node_name],
- storage_type=storage_type,
- output_fields=output_fields.split(","))
- return self.SubmitJob([op])
+ return ({}, {
+ "nodes": [self.items[0]],
+ "storage_type": storage_type,
+ "output_fields": output_fields.split(","),
+ })
-class R_2_nodes_name_storage_modify(baserlib.ResourceBase):
+class R_2_nodes_name_storage_modify(baserlib.OpcodeResource):
"""/2/nodes/[node_name]/storage/modify resource.
"""
- def PUT(self):
- node_name = self.items[0]
+ PUT_OPCODE = opcodes.OpNodeModifyStorage
- storage_type = self._checkStringVariable("storage_type", None)
- if not storage_type:
- raise http.HttpBadRequest("Missing the required 'storage_type'"
- " parameter")
+ def GetPutOpInput(self):
+ """Modifies a storage volume on a node.
+ """
+ storage_type = self._checkStringVariable("storage_type", None)
name = self._checkStringVariable("name", None)
+
if not name:
raise http.HttpBadRequest("Missing the required 'name'"
" parameter")
changes[constants.SF_ALLOCATABLE] = \
bool(self._checkIntVariable("allocatable", default=1))
- op = opcodes.OpNodeModifyStorage(node_name=node_name,
- storage_type=storage_type,
- name=name,
- changes=changes)
- return self.SubmitJob([op])
+ return ({}, {
+ "node_name": self.items[0],
+ "storage_type": storage_type,
+ "name": name,
+ "changes": changes,
+ })
-class R_2_nodes_name_storage_repair(baserlib.ResourceBase):
+class R_2_nodes_name_storage_repair(baserlib.OpcodeResource):
"""/2/nodes/[node_name]/storage/repair resource.
"""
- def PUT(self):
- node_name = self.items[0]
+ PUT_OPCODE = opcodes.OpRepairNodeStorage
- storage_type = self._checkStringVariable("storage_type", None)
- if not storage_type:
- raise http.HttpBadRequest("Missing the required 'storage_type'"
- " parameter")
+ def GetPutOpInput(self):
+ """Repairs a storage volume on a node.
+ """
+ storage_type = self._checkStringVariable("storage_type", None)
name = self._checkStringVariable("name", None)
if not name:
raise http.HttpBadRequest("Missing the required 'name'"
" parameter")
- op = opcodes.OpRepairNodeStorage(node_name=node_name,
- storage_type=storage_type,
- name=name)
- return self.SubmitJob([op])
+ return ({}, {
+ "node_name": self.items[0],
+ "storage_type": storage_type,
+ "name": name,
+ })
+
+
+class R_2_networks(baserlib.OpcodeResource):
+ """/2/networks resource.
+
+ """
+ GET_OPCODE = opcodes.OpNetworkQuery
+ POST_OPCODE = opcodes.OpNetworkAdd
+ POST_RENAME = {
+ "name": "network_name",
+ }
+
+ def GetPostOpInput(self):
+ """Create a network.
+
+ """
+ assert not self.items
+ return (self.request_body, {
+ "dry_run": self.dryRun(),
+ })
+
+ def GET(self):
+ """Returns a list of all networks.
+
+ """
+ client = self.GetClient(query=True)
+
+ if self.useBulk():
+ bulkdata = client.QueryNetworks([], NET_FIELDS, False)
+ return baserlib.MapBulkFields(bulkdata, NET_FIELDS)
+ else:
+ data = client.QueryNetworks([], ["name"], False)
+ networknames = [row[0] for row in data]
+ return baserlib.BuildUriList(networknames, "/2/networks/%s",
+ uri_fields=("name", "uri"))
+
+
+class R_2_networks_name(baserlib.OpcodeResource):
+ """/2/networks/[network_name] resource.
+
+ """
+ DELETE_OPCODE = opcodes.OpNetworkRemove
+
+ def GET(self):
+ """Send information about a network.
+
+ """
+ network_name = self.items[0]
+ client = self.GetClient(query=True)
+
+ result = baserlib.HandleItemQueryErrors(client.QueryNetworks,
+ names=[network_name],
+ fields=NET_FIELDS,
+ use_locking=self.useLocking())
+
+ return baserlib.MapFields(NET_FIELDS, result[0])
+
+ def GetDeleteOpInput(self):
+ """Delete a network.
+
+ """
+ assert len(self.items) == 1
+ return (self.request_body, {
+ "network_name": self.items[0],
+ "dry_run": self.dryRun(),
+ })
+
+
+class R_2_networks_name_connect(baserlib.OpcodeResource):
+ """/2/networks/[network_name]/connect resource.
+
+ """
+ PUT_OPCODE = opcodes.OpNetworkConnect
+
+ def GetPutOpInput(self):
+ """Changes some parameters of node group.
+
+ """
+ assert self.items
+ return (self.request_body, {
+ "network_name": self.items[0],
+ "dry_run": self.dryRun(),
+ })
+
+
+class R_2_networks_name_disconnect(baserlib.OpcodeResource):
+ """/2/networks/[network_name]/disconnect resource.
+
+ """
+ PUT_OPCODE = opcodes.OpNetworkDisconnect
+
+ def GetPutOpInput(self):
+ """Changes some parameters of node group.
+
+ """
+ assert self.items
+ return (self.request_body, {
+ "network_name": self.items[0],
+ "dry_run": self.dryRun(),
+ })
+
+
+class R_2_networks_name_modify(baserlib.OpcodeResource):
+ """/2/networks/[network_name]/modify resource.
+
+ """
+ PUT_OPCODE = opcodes.OpNetworkSetParams
+
+ def GetPutOpInput(self):
+ """Changes some parameters of network.
+
+ """
+ assert self.items
+ return (self.request_body, {
+ "network_name": self.items[0],
+ })
class R_2_groups(baserlib.OpcodeResource):
"""/2/groups resource.
"""
+ GET_OPCODE = opcodes.OpGroupQuery
POST_OPCODE = opcodes.OpGroupAdd
POST_RENAME = {
"name": "group_name",
def GetPostOpInput(self):
"""Create a node group.
+
"""
assert not self.items
return (self.request_body, {
"""Returns a list of all node groups.
"""
- client = self.GetClient()
+ client = self.GetClient(query=True)
if self.useBulk():
bulkdata = client.QueryGroups([], G_FIELDS, False)
uri_fields=("name", "uri"))
-class R_2_groups_name(baserlib.ResourceBase):
+class R_2_groups_name(baserlib.OpcodeResource):
"""/2/groups/[group_name] resource.
"""
+ DELETE_OPCODE = opcodes.OpGroupRemove
+
def GET(self):
"""Send information about a node group.
"""
group_name = self.items[0]
- client = self.GetClient()
+ client = self.GetClient(query=True)
result = baserlib.HandleItemQueryErrors(client.QueryGroups,
names=[group_name], fields=G_FIELDS,
return baserlib.MapFields(G_FIELDS, result[0])
- def DELETE(self):
+ def GetDeleteOpInput(self):
"""Delete a node group.
"""
- op = opcodes.OpGroupRemove(group_name=self.items[0],
- dry_run=bool(self.dryRun()))
-
- return self.SubmitJob([op])
+ assert len(self.items) == 1
+ return ({}, {
+ "group_name": self.items[0],
+ "dry_run": self.dryRun(),
+ })
class R_2_groups_name_modify(baserlib.OpcodeResource):
})
-def _ParseInstanceCreateRequestVersion1(data, dry_run):
- """Parses an instance creation request version 1.
+def _ConvertUsbDevices(data):
+ """Convert in place the usb_devices string to the proper format.
- @rtype: L{opcodes.OpInstanceCreate}
- @return: Instance creation opcode
+ In Ganeti 2.8.4 the separator for the usb_devices hvparam was changed from
+ comma to space because commas cannot be accepted on the command line
+ (they already act as the separator between different hvparams). RAPI
+ should be able to accept commas for backwards compatibility, but we want
+ it to also accept the new space separator. Therefore, we convert
+ spaces into commas here and keep the old parsing logic elsewhere.
"""
- override = {
- "dry_run": dry_run,
- }
-
- rename = {
- "os": "os_type",
- "name": "instance_name",
- }
-
- return baserlib.FillOpcode(opcodes.OpInstanceCreate, data, override,
- rename=rename)
+ try:
+ hvparams = data["hvparams"]
+ usb_devices = hvparams[constants.HV_USB_DEVICES]
+ hvparams[constants.HV_USB_DEVICES] = usb_devices.replace(" ", ",")
+ data["hvparams"] = hvparams
+ except KeyError:
+ #No usb_devices, no modification required
+ pass
-class R_2_instances(baserlib.ResourceBase):
+class R_2_instances(baserlib.OpcodeResource):
"""/2/instances resource.
"""
+ GET_OPCODE = opcodes.OpInstanceQuery
+ POST_OPCODE = opcodes.OpInstanceCreate
+ POST_RENAME = {
+ "os": "os_type",
+ "name": "instance_name",
+ }
+
def GET(self):
"""Returns a list of all available instances.
use_locking = self.useLocking()
if self.useBulk():
bulkdata = client.QueryInstances([], I_FIELDS, use_locking)
- return baserlib.MapBulkFields(bulkdata, I_FIELDS)
+ return map(_UpdateBeparams, baserlib.MapBulkFields(bulkdata, I_FIELDS))
else:
instancesdata = client.QueryInstances([], ["name"], use_locking)
instanceslist = [row[0] for row in instancesdata]
return baserlib.BuildUriList(instanceslist, "/2/instances/%s",
uri_fields=("id", "uri"))
- def POST(self):
+ def GetPostOpInput(self):
"""Create an instance.
@return: a job id
"""
- if not isinstance(self.request_body, dict):
- raise http.HttpBadRequest("Invalid body contents, not a dictionary")
+ baserlib.CheckType(self.request_body, dict, "Body contents")
# Default to request data version 0
data_version = self.getBodyParameter(_REQ_DATA_VERSION, 0)
if data_version == 0:
raise http.HttpBadRequest("Instance creation request version 0 is no"
" longer supported")
- elif data_version == 1:
- data = self.request_body.copy()
- # Remove "__version__"
- data.pop(_REQ_DATA_VERSION, None)
- op = _ParseInstanceCreateRequestVersion1(data, self.dryRun())
- else:
+ elif data_version != 1:
raise http.HttpBadRequest("Unsupported request data version %s" %
data_version)
- return self.SubmitJob([op])
+ data = self.request_body.copy()
+ # Remove "__version__"
+ data.pop(_REQ_DATA_VERSION, None)
+
+ _ConvertUsbDevices(data)
+
+ return (data, {
+ "dry_run": self.dryRun(),
+ })
+
+
+class R_2_instances_multi_alloc(baserlib.OpcodeResource):
+ """/2/instances-multi-alloc resource.
+
+ """
+ POST_OPCODE = opcodes.OpInstanceMultiAlloc
+
+ def GetPostOpInput(self):
+ """Try to allocate multiple instances.
+
+ @return: A dict with submitted jobs, allocatable instances and failed
+ allocations
+
+ """
+ if "instances" not in self.request_body:
+ raise http.HttpBadRequest("Request is missing required 'instances' field"
+ " in body")
+
+ # Unlike most other RAPI calls, this one is composed of individual opcodes,
+ # and we have to do the filling ourselves
+ OPCODE_RENAME = {
+ "os": "os_type",
+ "name": "instance_name",
+ }
+
+ body = objects.FillDict(self.request_body, {
+ "instances": [
+ baserlib.FillOpcode(opcodes.OpInstanceCreate, inst, {},
+ rename=OPCODE_RENAME)
+ for inst in self.request_body["instances"]
+ ],
+ })
+
+ return (body, {
+ "dry_run": self.dryRun(),
+ })
class R_2_instances_name(baserlib.OpcodeResource):
"""/2/instances/[instance_name] resource.
"""
+ GET_OPCODE = opcodes.OpInstanceQuery
DELETE_OPCODE = opcodes.OpInstanceRemove
def GET(self):
fields=I_FIELDS,
use_locking=self.useLocking())
- return baserlib.MapFields(I_FIELDS, result[0])
+ return _UpdateBeparams(baserlib.MapFields(I_FIELDS, result[0]))
def GetDeleteOpInput(self):
"""Delete an instance.
return ops
-class R_2_instances_name_reinstall(baserlib.ResourceBase):
+class R_2_instances_name_reinstall(baserlib.OpcodeResource):
"""/2/instances/[instance_name]/reinstall resource.
Implements an instance reinstall.
"""
+ POST_OPCODE = opcodes.OpInstanceReinstall
+
def POST(self):
"""Reinstall an instance.
"""Replaces disks on an instance.
"""
- data = self.request_body.copy()
static = {
"instance_name": self.items[0],
}
+ if self.request_body:
+ data = self.request_body
+ elif self.queryargs:
+ # Legacy interface, do not modify/extend
+ data = {
+ "remote_node": self._checkStringVariable("remote_node", default=None),
+ "mode": self._checkStringVariable("mode", default=None),
+ "disks": self._checkStringVariable("disks", default=None),
+ "iallocator": self._checkStringVariable("iallocator", default=None),
+ }
+ else:
+ data = {}
+
# Parse disks
try:
- raw_disks = data["disks"]
+ raw_disks = data.pop("disks")
except KeyError:
pass
else:
- if not ht.TListOf(ht.TInt)(raw_disks): # pylint: disable-msg=E1102
- # Backwards compatibility for strings of the format "1, 2, 3"
- try:
- data["disks"] = [int(part) for part in raw_disks.split(",")]
- except (TypeError, ValueError), err:
- raise http.HttpBadRequest("Invalid disk index passed: %s" % err)
+ if raw_disks:
+ if ht.TListOf(ht.TInt)(raw_disks): # pylint: disable=E1102
+ data["disks"] = raw_disks
+ else:
+ # Backwards compatibility for strings of the format "1, 2, 3"
+ try:
+ data["disks"] = [int(part) for part in raw_disks.split(",")]
+ except (TypeError, ValueError), err:
+ raise http.HttpBadRequest("Invalid disk index passed: %s" % err)
return (data, static)
})
+class R_2_instances_name_recreate_disks(baserlib.OpcodeResource):
+ """/2/instances/[instance_name]/recreate-disks resource.
+
+ """
+ POST_OPCODE = opcodes.OpInstanceRecreateDisks
+
+ def GetPostOpInput(self):
+ """Recreate disks for an instance.
+
+ """
+ return ({}, {
+ "instance_name": self.items[0],
+ })
+
+
class R_2_instances_name_prepare_export(baserlib.OpcodeResource):
"""/2/instances/[instance_name]/prepare-export resource.
"""Changes parameters of an instance.
"""
- return (self.request_body, {
+ data = self.request_body.copy()
+ _ConvertUsbDevices(data)
+
+ return (data, {
"instance_name": self.items[0],
})
"""/2/instances/[instance_name]/console resource.
"""
- GET_ACCESS = [rapi.RAPI_ACCESS_WRITE]
+ GET_ACCESS = [rapi.RAPI_ACCESS_WRITE, rapi.RAPI_ACCESS_READ]
+ GET_OPCODE = opcodes.OpInstanceConsole
def GET(self):
"""Request information for connecting to instance's console.
def _GetQueryFields(args):
- """
+ """Tries to extract C{fields} query parameter.
+
+ @type args: dictionary
+ @rtype: list of string
+ @raise http.HttpBadRequest: When parameter can't be found
"""
try:
def _SplitQueryFields(fields):
- """
+ """Splits fields as given for a query request.
+
+ @type fields: string
+ @rtype: list of string
"""
return [i.strip() for i in fields.split(",")]
"""
# Results might contain sensitive information
- GET_ACCESS = [rapi.RAPI_ACCESS_WRITE]
+ GET_ACCESS = [rapi.RAPI_ACCESS_WRITE, rapi.RAPI_ACCESS_READ]
+ PUT_ACCESS = GET_ACCESS
+ GET_OPCODE = opcodes.OpQuery
+ PUT_OPCODE = opcodes.OpQuery
- def _Query(self, fields, filter_):
- return self.GetClient().Query(self.items[0], fields, filter_).ToDict()
+ def _Query(self, fields, qfilter):
+ return self.GetClient().Query(self.items[0], fields, qfilter).ToDict()
def GET(self):
"""Returns resource information.
except KeyError:
fields = _GetQueryFields(self.queryargs)
- return self._Query(fields, self.request_body.get("filter", None))
+ qfilter = body.get("qfilter", None)
+ # TODO: remove this after 2.7
+ if qfilter is None:
+ qfilter = body.get("filter", None)
+
+ return self._Query(fields, qfilter)
class R_2_query_fields(baserlib.ResourceBase):
"""/2/query/[resource]/fields resource.
"""
+ GET_OPCODE = opcodes.OpQueryFields
+
def GET(self):
"""Retrieves list of available fields for a resource.
return self.GetClient().QueryFields(self.items[0], fields).ToDict()
-class _R_Tags(baserlib.ResourceBase):
- """ Quasiclass for tagging resources
+class _R_Tags(baserlib.OpcodeResource):
+ """Quasiclass for tagging resources.
Manages tags. When inheriting this class you must define the
TAG_LEVEL for it.
"""
TAG_LEVEL = None
+ GET_OPCODE = opcodes.OpTagsGet
+ PUT_OPCODE = opcodes.OpTagsSet
+ DELETE_OPCODE = opcodes.OpTagsDel
- def __init__(self, items, queryargs, req):
+ def __init__(self, items, queryargs, req, **kwargs):
"""A tag resource constructor.
We have to override the default to sort out cluster naming case.
"""
- baserlib.ResourceBase.__init__(self, items, queryargs, req)
+ baserlib.OpcodeResource.__init__(self, items, queryargs, req, **kwargs)
if self.TAG_LEVEL == constants.TAG_CLUSTER:
self.name = None
if kind in (constants.TAG_INSTANCE,
constants.TAG_NODEGROUP,
- constants.TAG_NODE):
+ constants.TAG_NODE,
+ constants.TAG_NETWORK):
if not self.name:
raise http.HttpBadRequest("Missing name on tag request")
- cl = self.GetClient()
- if kind == constants.TAG_INSTANCE:
- fn = cl.QueryInstances
- elif kind == constants.TAG_NODEGROUP:
- fn = cl.QueryGroups
- else:
- fn = cl.QueryNodes
- result = fn(names=[self.name], fields=["tags"], use_locking=False)
- if not result or not result[0]:
- raise http.HttpBadGateway("Invalid response from tag query")
- tags = result[0][0]
+ cl = self.GetClient(query=True)
+ tags = list(cl.QueryTags(kind, self.name))
elif kind == constants.TAG_CLUSTER:
assert not self.name
ssc = ssconf.SimpleStore()
tags = ssc.GetClusterTags()
+ else:
+ raise http.HttpBadRequest("Unhandled tag type!")
+
return list(tags)
- def PUT(self):
+ def GetPutOpInput(self):
"""Add a set of tags.
The request as a list of strings should be PUT to this URI. And
you'll have back a job id.
"""
- # pylint: disable-msg=W0212
- if "tag" not in self.queryargs:
- raise http.HttpBadRequest("Please specify tag(s) to add using the"
- " the 'tag' parameter")
- op = opcodes.OpTagsSet(kind=self.TAG_LEVEL, name=self.name,
- tags=self.queryargs["tag"], dry_run=self.dryRun())
- return self.SubmitJob([op])
+ return ({}, {
+ "kind": self.TAG_LEVEL,
+ "name": self.name,
+ "tags": self.queryargs.get("tag", []),
+ "dry_run": self.dryRun(),
+ })
- def DELETE(self):
+ def GetDeleteOpInput(self):
"""Delete a tag.
In order to delete a set of tags, the DELETE
/tags?tag=[tag]&tag=[tag]
"""
- # pylint: disable-msg=W0212
- if "tag" not in self.queryargs:
- # no we not gonna delete all tags
- raise http.HttpBadRequest("Cannot delete all tags - please specify"
- " tag(s) using the 'tag' parameter")
- op = opcodes.OpTagsDel(kind=self.TAG_LEVEL, name=self.name,
- tags=self.queryargs["tag"], dry_run=self.dryRun())
- return self.SubmitJob([op])
+ # Re-use code
+ return self.GetPutOpInput()
class R_2_instances_name_tags(_R_Tags):
TAG_LEVEL = constants.TAG_NODEGROUP
+class R_2_networks_name_tags(_R_Tags):
+ """ /2/networks/[network_name]/tags resource.
+
+ Manages per-network tags.
+
+ """
+ TAG_LEVEL = constants.TAG_NETWORK
+
+
class R_2_tags(_R_Tags):
""" /2/tags resource.