ConfigWriter: handle the drained node flag
[ganeti-local] / lib / rapi / baserlib.py
index 099fab1..9d0935d 100644 (file)
 import ganeti.cli
 import ganeti.opcodes
 
+from ganeti import luxi
+from ganeti import rapi
+from ganeti import http
+
 
 def BuildUriList(ids, uri_format, uri_fields=("name", "uri")):
   """Builds a URI list as used by index resources.
 
-  Args:
-  - ids: List of ids as strings
-  - uri_format: Format to be applied for URI
-  - uri_fields: Optional parameter for field ids
+  @param ids: list of ids as strings
+  @param uri_format: format to be applied for URI
+  @param uri_fields: optional parameter for field IDs
 
   """
   (field_id, field_uri) = uri_fields
@@ -51,9 +54,8 @@ def BuildUriList(ids, uri_format, uri_fields=("name", "uri")):
 def ExtractField(sequence, index):
   """Creates a list containing one column out of a list of lists.
 
-  Args:
-  - sequence: Sequence of lists
-  - index: Index of field
+  @param sequence: sequence of lists
+  @param index: index of field
 
   """
   return map(lambda item: item[index], sequence)
@@ -62,13 +64,12 @@ def ExtractField(sequence, index):
 def MapFields(names, data):
   """Maps two lists into one dictionary.
 
-  Args:
-  - names: Field names (list of strings)
-  - data: Field data (list)
+  Example::
+      >>> MapFields(["a", "b"], ["foo", 123])
+      {'a': 'foo', 'b': 123}
 
-  Example:
-  >>> MapFields(["a", "b"], ["foo", 123])
-  {'a': 'foo', 'b': 123}
+  @param names: field names (list of strings)
+  @param data: field data (list)
 
   """
   if len(names) != len(data):
@@ -76,32 +77,129 @@ def MapFields(names, data):
   return dict(zip(names, data))
 
 
-def _Tags_GET(kind, name=None):
+def _Tags_GET(kind, name=""):
   """Helper function to retrieve tags.
 
   """
-  if name is None:
-    # Do not cause "missing parameter" error, which happens if a parameter
-    # is None.
-    name = ""
   op = ganeti.opcodes.OpGetTags(kind=kind, name=name)
   tags = ganeti.cli.SubmitOpCode(op)
   return list(tags)
 
 
+def _Tags_PUT(kind, tags, name=""):
+  """Helper function to set tags.
+
+  """
+  cl = luxi.Client()
+  return cl.SubmitJob([ganeti.opcodes.OpAddTags(kind=kind, name=name,
+                                                tags=tags)])
+
+
+def _Tags_DELETE(kind, tags, name=""):
+  """Helper function to delete tags.
+
+  """
+  cl = luxi.Client()
+  return cl.SubmitJob([ganeti.opcodes.OpDelTags(kind=kind, name=name,
+                                                tags=tags)])
+
+
+def MapBulkFields(itemslist, fields):
+  """Map value to field name in to one dictionary.
+
+  @param itemslist: a list of items values
+  @param fields: a list of items names
+
+  @return: a list of mapped dictionaries
+
+  """
+  items_details = []
+  for item in itemslist:
+    mapped = MapFields(fields, item)
+    items_details.append(mapped)
+  return items_details
+
+
+def MakeParamsDict(opts, params):
+  """Makes params dictionary out of a option set.
+
+  This function returns a dictionary needed for hv or be parameters. But only
+  those fields which provided in the option set. Takes parameters frozensets
+  from constants.
+
+  @type opts: dict
+  @param opts: selected options
+  @type params: frozenset
+  @param params: subset of options
+  @rtype: dict
+  @return: dictionary of options, filtered by given subset.
+
+  """
+  result = {}
+
+  for p in params:
+    try:
+      value = opts[p]
+    except KeyError:
+      continue
+    result[p] = value
+
+  return result
+
+
 class R_Generic(object):
   """Generic class for resources.
 
   """
-  def __init__(self, request, items, queryargs):
+  # Default permission requirements
+  GET_ACCESS = []
+  PUT_ACCESS = [rapi.RAPI_ACCESS_WRITE]
+  POST_ACCESS = [rapi.RAPI_ACCESS_WRITE]
+  DELETE_ACCESS = [rapi.RAPI_ACCESS_WRITE]
+
+  def __init__(self, items, queryargs, req):
     """Generic resource constructor.
 
-    Args:
-      request: HTTPRequestHandler object
-      items: a list with variables encoded in the URL
-      queryargs: a dictionary with additional options from URL
+    @param items: a list with variables encoded in the URL
+    @param queryargs: a dictionary with additional options from URL
 
     """
-    self.request = request
     self.items = items
     self.queryargs = queryargs
+    self.req = req
+    self.sn = None
+
+  def getSerialNumber(self):
+    """Get Serial Number.
+
+    """
+    return self.sn
+
+  def _checkIntVariable(self, name):
+    """Return the parsed value of an int argument.
+
+    """
+    val = self.queryargs.get(name, 0)
+    if isinstance(val, list):
+      if val:
+        val = val[0]
+      else:
+        val = 0
+    try:
+      val = int(val)
+    except (ValueError, TypeError), err:
+      raise http.HttpBadRequest(message="Invalid value for the"
+                                " '%s' parameter" % (name,))
+    return val
+
+  def useLocking(self):
+    """Check if the request specifies locking.
+
+    """
+    return self._checkIntVariable('lock')
+
+  def useBulk(self):
+    """Check if the request specifies bulk querying.
+
+    """
+    return self._checkIntVariable('bulk')