rlib2.py 37.1 KB
Newer Older
1
2
3
#
#

4
# Copyright (C) 2006, 2007, 2008, 2009, 2010 Google Inc.
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#
# 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
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Remote API version 2 baserlib.library.

24
  PUT or POST?
25
  ============
26
27
28
29
30
31
32
33
34
35
36
37

  According to RFC2616 the main difference between PUT and POST is that
  POST can create new resources but PUT can only create the resource the
  URI was pointing to on the PUT request.

  To be in context of this module for instance creation POST on
  /2/instances is legitim while PUT would be not, due to it does create a
  new entity and not just replace /2/instances with it.

  So when adding new methods, if they are operating on the URI entity itself,
  PUT should be prefered over POST.

38
39
"""

Iustin Pop's avatar
Iustin Pop committed
40
41
42
43
# pylint: disable-msg=C0103

# C0103: Invalid name, since the R_* names are not conforming

Iustin Pop's avatar
Iustin Pop committed
44
from ganeti import opcodes
45
46
from ganeti import http
from ganeti import constants
Iustin Pop's avatar
Iustin Pop committed
47
from ganeti import cli
48
from ganeti import utils
Michael Hanselmann's avatar
Michael Hanselmann committed
49
from ganeti import rapi
Iustin Pop's avatar
Iustin Pop committed
50
from ganeti.rapi import baserlib
51

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
52

Iustin Pop's avatar
Iustin Pop committed
53
_COMMON_FIELDS = ["ctime", "mtime", "uuid", "serial_no", "tags"]
54
55
56
I_FIELDS = ["name", "admin_state", "os",
            "pnode", "snodes",
            "disk_template",
57
            "nic.ips", "nic.macs", "nic.modes", "nic.links", "nic.bridges",
58
            "network_port",
59
            "disk.sizes", "disk_usage",
60
            "beparams", "hvparams",
61
            "oper_state", "oper_ram", "oper_vcpus", "status",
62
            "custom_hvparams", "custom_beparams", "custom_nicparams",
Iustin Pop's avatar
Iustin Pop committed
63
            ] + _COMMON_FIELDS
64

65
N_FIELDS = ["name", "offline", "master_candidate", "drained",
66
            "dtotal", "dfree",
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
67
            "mtotal", "mnode", "mfree",
Iustin Pop's avatar
Iustin Pop committed
68
            "pinst_cnt", "sinst_cnt",
69
            "ctotal", "cnodes", "csockets",
Iustin Pop's avatar
Iustin Pop committed
70
            "pip", "sip", "role",
71
            "pinst_list", "sinst_list",
72
            "master_capable", "vm_capable",
73
            "group.uuid",
Iustin Pop's avatar
Iustin Pop committed
74
            ] + _COMMON_FIELDS
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
75

76
77
78
79
G_FIELDS = ["name", "uuid",
            "node_cnt", "node_list",
            ]

80
81
82
83
84
85
86
87
88
89
90
91
92
93
_NR_DRAINED = "drained"
_NR_MASTER_CANDIATE = "master-candidate"
_NR_MASTER = "master"
_NR_OFFLINE = "offline"
_NR_REGULAR = "regular"

_NR_MAP = {
  "M": _NR_MASTER,
  "C": _NR_MASTER_CANDIATE,
  "D": _NR_DRAINED,
  "O": _NR_OFFLINE,
  "R": _NR_REGULAR,
  }

94
95
96
# Request data version field
_REQ_DATA_VERSION = "__version__"

97
98
99
# Feature string for instance creation request data version 1
_INST_CREATE_REQV1 = "instance-create-reqv1"

100
101
102
# Feature string for instance reinstall request version 1
_INST_REINSTALL_REQV1 = "instance-reinstall-reqv1"

103
104
105
# Timeout for /2/jobs/[job_id]/wait. Gives job up to 10 seconds to change.
_WFJC_TIMEOUT = 10

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
106
107
108
109
110
111
112
113

class R_version(baserlib.R_Generic):
  """/version resource.

  This resource should be used to determine the remote API version and
  to adapt clients accordingly.

  """
114
115
  @staticmethod
  def GET():
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
116
117
118
119
120
121
122
123
124
125
    """Returns the remote API version.

    """
    return constants.RAPI_VERSION


class R_2_info(baserlib.R_Generic):
  """Cluster info.

  """
126
127
  @staticmethod
  def GET():
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
128
129
130
    """Returns cluster information.

    """
Iustin Pop's avatar
Iustin Pop committed
131
    client = baserlib.GetClient()
132
    return client.QueryClusterInfo()
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
133
134


135
136
137
138
139
140
141
142
143
class R_2_features(baserlib.R_Generic):
  """/2/features resource.

  """
  @staticmethod
  def GET():
    """Returns list of optional RAPI features implemented.

    """
144
    return [_INST_CREATE_REQV1, _INST_REINSTALL_REQV1]
145
146


Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
147
148
149
150
class R_2_os(baserlib.R_Generic):
  """/2/os resource.

  """
151
152
  @staticmethod
  def GET():
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
153
154
155
156
157
158
159
    """Return a list of all OSes.

    Can return error 500 in case of a problem.

    Example: ["debian-etch"]

    """
Iustin Pop's avatar
Iustin Pop committed
160
    cl = baserlib.GetClient()
161
    op = opcodes.OpDiagnoseOS(output_fields=["name", "variants"], names=[])
Iustin Pop's avatar
Iustin Pop committed
162
163
164
165
    job_id = baserlib.SubmitJob([op], cl)
    # we use custom feedback function, instead of print we log the status
    result = cli.PollJob(job_id, cl, feedback_fn=baserlib.FeedbackFn)
    diagnose_data = result[0]
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
166
167

    if not isinstance(diagnose_data, list):
Iustin Pop's avatar
Iustin Pop committed
168
      raise http.HttpBadGateway(message="Can't get OS list")
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
169

170
    os_names = []
171
172
    for (name, variants) in diagnose_data:
      os_names.extend(cli.CalculateOSNames(name, variants))
173
174

    return os_names
175

176

177
178
179
180
class R_2_redist_config(baserlib.R_Generic):
  """/2/redistribute-config resource.

  """
181
182
  @staticmethod
  def PUT():
183
184
185
186
187
188
    """Redistribute configuration to all nodes.

    """
    return baserlib.SubmitJob([opcodes.OpRedistributeConfig()])


189
190
191
192
class R_2_jobs(baserlib.R_Generic):
  """/2/jobs resource.

  """
193
194
  @staticmethod
  def GET():
195
196
    """Returns a dictionary of jobs.

Iustin Pop's avatar
Iustin Pop committed
197
    @return: a dictionary with jobs id and uri.
Iustin Pop's avatar
Iustin Pop committed
198

199
200
    """
    fields = ["id"]
Iustin Pop's avatar
Iustin Pop committed
201
    cl = baserlib.GetClient()
202
    # Convert the list of lists to the list of ids
Iustin Pop's avatar
Iustin Pop committed
203
    result = [job_id for [job_id] in cl.QueryJobs(None, fields)]
204
205
    return baserlib.BuildUriList(result, "/2/jobs/%s",
                                 uri_fields=("id", "uri"))
206
207
208
209
210
211
212
213
214


class R_2_jobs_id(baserlib.R_Generic):
  """/2/jobs/[job_id] resource.

  """
  def GET(self):
    """Returns a job status.

Iustin Pop's avatar
Iustin Pop committed
215
216
217
218
219
220
221
222
    @return: a dictionary with job parameters.
        The result includes:
            - id: job ID as a number
            - status: current job status as a string
            - ops: involved OpCodes as a list of dictionaries for each
              opcodes in the job
            - opstatus: OpCodes status as a list
            - opresult: OpCodes results as a list of lists
Iustin Pop's avatar
Iustin Pop committed
223

224
    """
Iustin Pop's avatar
Iustin Pop committed
225
226
227
228
    fields = ["id", "ops", "status", "summary",
              "opstatus", "opresult", "oplog",
              "received_ts", "start_ts", "end_ts",
              ]
229
    job_id = self.items[0]
Iustin Pop's avatar
Iustin Pop committed
230
    result = baserlib.GetClient().QueryJobs([job_id, ], fields)[0]
Iustin Pop's avatar
Iustin Pop committed
231
232
    if result is None:
      raise http.HttpNotFound()
233
234
    return baserlib.MapFields(fields, result)

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
235
236
237
238
239
  def DELETE(self):
    """Cancel not-yet-started job.

    """
    job_id = self.items[0]
Iustin Pop's avatar
Iustin Pop committed
240
    result = baserlib.GetClient().CancelJob(job_id)
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
241
242
    return result

243

244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
class R_2_jobs_id_wait(baserlib.R_Generic):
  """/2/jobs/[job_id]/wait resource.

  """
  # WaitForJobChange provides access to sensitive information and blocks
  # machine resources (it's a blocking RAPI call), hence restricting access.
  GET_ACCESS = [rapi.RAPI_ACCESS_WRITE]

  def GET(self):
    """Waits for job changes.

    """
    job_id = self.items[0]

    fields = self.getBodyParameter("fields")
    prev_job_info = self.getBodyParameter("previous_job_info", None)
    prev_log_serial = self.getBodyParameter("previous_log_serial", None)

    if not isinstance(fields, list):
      raise http.HttpBadRequest("The 'fields' parameter should be a list")

    if not (prev_job_info is None or isinstance(prev_job_info, list)):
      raise http.HttpBadRequest("The 'previous_job_info' parameter should"
                                " be a list")

    if not (prev_log_serial is None or
            isinstance(prev_log_serial, (int, long))):
      raise http.HttpBadRequest("The 'previous_log_serial' parameter should"
                                " be a number")

    client = baserlib.GetClient()
    result = client.WaitForJobChangeOnce(job_id, fields,
                                         prev_job_info, prev_log_serial,
                                         timeout=_WFJC_TIMEOUT)
    if not result:
      raise http.HttpNotFound()

    if result == constants.JOB_NOTCHANGED:
      # No changes
      return None

    (job_info, log_entries) = result

    return {
      "job_info": job_info,
      "log_entries": log_entries,
      }


293
294
295
296
297
298
class R_2_nodes(baserlib.R_Generic):
  """/2/nodes resource.

  """
  def GET(self):
    """Returns a list of all nodes.
Iustin Pop's avatar
Iustin Pop committed
299

300
    """
Iustin Pop's avatar
Iustin Pop committed
301
    client = baserlib.GetClient()
Iustin Pop's avatar
Iustin Pop committed
302

303
    if self.useBulk():
304
      bulkdata = client.QueryNodes([], N_FIELDS, False)
305
      return baserlib.MapBulkFields(bulkdata, N_FIELDS)
306
307
308
309
310
    else:
      nodesdata = client.QueryNodes([], ["name"], False)
      nodeslist = [row[0] for row in nodesdata]
      return baserlib.BuildUriList(nodeslist, "/2/nodes/%s",
                                   uri_fields=("id", "uri"))
311
312


Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
313
314
class R_2_nodes_name(baserlib.R_Generic):
  """/2/nodes/[node_name] resources.
315
316

  """
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
317
318
319
320
321
  def GET(self):
    """Send information about a node.

    """
    node_name = self.items[0]
Iustin Pop's avatar
Iustin Pop committed
322
    client = baserlib.GetClient()
323
324
325
326

    result = baserlib.HandleItemQueryErrors(client.QueryNodes,
                                            names=[node_name], fields=N_FIELDS,
                                            use_locking=self.useLocking())
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
327
328

    return baserlib.MapFields(N_FIELDS, result[0])
329
330


331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
class R_2_nodes_name_role(baserlib.R_Generic):
  """ /2/nodes/[node_name]/role resource.

  """
  def GET(self):
    """Returns the current node role.

    @return: Node role

    """
    node_name = self.items[0]
    client = baserlib.GetClient()
    result = client.QueryNodes(names=[node_name], fields=["role"],
                               use_locking=self.useLocking())

    return _NR_MAP[result[0][0]]

  def PUT(self):
    """Sets the node role.

    @return: a job id

    """
354
    if not isinstance(self.request_body, basestring):
355
356
357
      raise http.HttpBadRequest("Invalid body contents, not a string")

    node_name = self.items[0]
358
    role = self.request_body
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388

    if role == _NR_REGULAR:
      candidate = False
      offline = False
      drained = False

    elif role == _NR_MASTER_CANDIATE:
      candidate = True
      offline = drained = None

    elif role == _NR_DRAINED:
      drained = True
      candidate = offline = None

    elif role == _NR_OFFLINE:
      offline = True
      candidate = drained = None

    else:
      raise http.HttpBadRequest("Can't set '%s' role" % role)

    op = opcodes.OpSetNodeParams(node_name=node_name,
                                 master_candidate=candidate,
                                 offline=offline,
                                 drained=drained,
                                 force=bool(self.useForce()))

    return baserlib.SubmitJob([op])


389
390
391
392
393
394
395
396
397
398
399
class R_2_nodes_name_evacuate(baserlib.R_Generic):
  """/2/nodes/[node_name]/evacuate resource.

  """
  def POST(self):
    """Evacuate all secondary instances off a node.

    """
    node_name = self.items[0]
    remote_node = self._checkStringVariable("remote_node", default=None)
    iallocator = self._checkStringVariable("iallocator", default=None)
400
401
    early_r = bool(self._checkIntVariable("early_release", default=0))
    dry_run = bool(self.dryRun())
402

403
    cl = baserlib.GetClient()
404

405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
    op = opcodes.OpNodeEvacuationStrategy(nodes=[node_name],
                                          iallocator=iallocator,
                                          remote_node=remote_node)

    job_id = baserlib.SubmitJob([op], cl)
    # we use custom feedback function, instead of print we log the status
    result = cli.PollJob(job_id, cl, feedback_fn=baserlib.FeedbackFn)

    jobs = []
    for iname, node in result:
      if dry_run:
        jid = None
      else:
        op = opcodes.OpReplaceDisks(instance_name=iname,
                                    remote_node=node, disks=[],
                                    mode=constants.REPLACE_DISK_CHG,
                                    early_release=early_r)
        jid = baserlib.SubmitJob([op])
      jobs.append((jid, iname, node))

    return jobs
426
427


428
class R_2_nodes_name_migrate(baserlib.R_Generic):
429
  """/2/nodes/[node_name]/migrate resource.
430
431
432
433
434
435
436
437

  """
  def POST(self):
    """Migrate all primary instances from a node.

    """
    node_name = self.items[0]

438
439
440
441
442
443
444
445
446
447
448
449
    if "live" in self.queryargs and "mode" in self.queryargs:
      raise http.HttpBadRequest("Only one of 'live' and 'mode' should"
                                " be passed")
    elif "live" in self.queryargs:
      if self._checkIntVariable("live", default=1):
        mode = constants.HT_MIGRATION_LIVE
      else:
        mode = constants.HT_MIGRATION_NONLIVE
    else:
      mode = self._checkStringVariable("mode", default=None)

    op = opcodes.OpMigrateNode(node_name=node_name, mode=mode)
450
451
452
453

    return baserlib.SubmitJob([op])


454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
class R_2_nodes_name_storage(baserlib.R_Generic):
  """/2/nodes/[node_name]/storage ressource.

  """
  # LUQueryNodeStorage acquires locks, hence restricting access to GET
  GET_ACCESS = [rapi.RAPI_ACCESS_WRITE]

  def GET(self):
    node_name = self.items[0]

    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.OpQueryNodeStorage(nodes=[node_name],
                                    storage_type=storage_type,
                                    output_fields=output_fields.split(","))
    return baserlib.SubmitJob([op])


480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
class R_2_nodes_name_storage_modify(baserlib.R_Generic):
  """/2/nodes/[node_name]/storage/modify ressource.

  """
  def PUT(self):
    node_name = self.items[0]

    storage_type = self._checkStringVariable("storage_type", None)
    if not storage_type:
      raise http.HttpBadRequest("Missing the required 'storage_type'"
                                " parameter")

    name = self._checkStringVariable("name", None)
    if not name:
      raise http.HttpBadRequest("Missing the required 'name'"
                                " parameter")

    changes = {}

    if "allocatable" in self.queryargs:
      changes[constants.SF_ALLOCATABLE] = \
        bool(self._checkIntVariable("allocatable", default=1))

    op = opcodes.OpModifyNodeStorage(node_name=node_name,
                                     storage_type=storage_type,
                                     name=name,
                                     changes=changes)
    return baserlib.SubmitJob([op])


510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
class R_2_nodes_name_storage_repair(baserlib.R_Generic):
  """/2/nodes/[node_name]/storage/repair ressource.

  """
  def PUT(self):
    node_name = self.items[0]

    storage_type = self._checkStringVariable("storage_type", None)
    if not storage_type:
      raise http.HttpBadRequest("Missing the required 'storage_type'"
                                " parameter")

    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 baserlib.SubmitJob([op])


533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
class R_2_groups(baserlib.R_Generic):
  """/2/groups resource.

  """
  def GET(self):
    """Returns a list of all node groups.

    """
    client = baserlib.GetClient()

    if self.useBulk():
      bulkdata = client.QueryGroups([], G_FIELDS, False)
      return baserlib.MapBulkFields(bulkdata, G_FIELDS)
    else:
      data = client.QueryGroups([], ["name"], False)
      groupnames = [row[0] for row in data]
      return baserlib.BuildUriList(groupnames, "/2/groups/%s",
                                   uri_fields=("name", "uri"))


class R_2_groups_name(baserlib.R_Generic):
  """/2/groups/[group_name] resources.

  """
  def GET(self):
    """Send information about a node group.

    """
    group_name = self.items[0]
    client = baserlib.GetClient()

    result = baserlib.HandleItemQueryErrors(client.QueryGroups,
                                            names=[group_name], fields=G_FIELDS,
                                            use_locking=self.useLocking())

    return baserlib.MapFields(G_FIELDS, result[0])



572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
def _ParseInstanceCreateRequestVersion1(data, dry_run):
  """Parses an instance creation request version 1.

  @rtype: L{opcodes.OpCreateInstance}
  @return: Instance creation opcode

  """
  # Disks
  disks_input = baserlib.CheckParameter(data, "disks", exptype=list)

  disks = []
  for idx, i in enumerate(disks_input):
    baserlib.CheckType(i, dict, "Disk %d specification" % idx)

    # Size is mandatory
    try:
588
      size = i[constants.IDISK_SIZE]
589
590
591
592
593
    except KeyError:
      raise http.HttpBadRequest("Disk %d specification wrong: missing disk"
                                " size" % idx)

    disk = {
594
      constants.IDISK_SIZE: size,
595
596
597
598
      }

    # Optional disk access mode
    try:
599
      disk_access = i[constants.IDISK_MODE]
600
601
602
    except KeyError:
      pass
    else:
603
      disk[constants.IDISK_MODE] = disk_access
604
605
606
607
608
609
610
611
612
613
614
615
616
617

    disks.append(disk)

  assert len(disks_input) == len(disks)

  # Network interfaces
  nics_input = baserlib.CheckParameter(data, "nics", exptype=list)

  nics = []
  for idx, i in enumerate(nics_input):
    baserlib.CheckType(i, dict, "NIC %d specification" % idx)

    nic = {}

618
    for field in constants.INIC_PARAMS:
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
      try:
        value = i[field]
      except KeyError:
        continue

      nic[field] = value

    nics.append(nic)

  assert len(nics_input) == len(nics)

  # HV/BE parameters
  hvparams = baserlib.CheckParameter(data, "hvparams", default={})
  utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)

  beparams = baserlib.CheckParameter(data, "beparams", default={})
  utils.ForceDictType(beparams, constants.BES_PARAMETER_TYPES)

  return opcodes.OpCreateInstance(
    mode=baserlib.CheckParameter(data, "mode"),
    instance_name=baserlib.CheckParameter(data, "name"),
640
641
    os_type=baserlib.CheckParameter(data, "os"),
    osparams=baserlib.CheckParameter(data, "osparams", default={}),
642
643
    force_variant=baserlib.CheckParameter(data, "force_variant",
                                          default=False),
644
    no_install=baserlib.CheckParameter(data, "no_install", default=False),
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
    pnode=baserlib.CheckParameter(data, "pnode", default=None),
    snode=baserlib.CheckParameter(data, "snode", default=None),
    disk_template=baserlib.CheckParameter(data, "disk_template"),
    disks=disks,
    nics=nics,
    src_node=baserlib.CheckParameter(data, "src_node", default=None),
    src_path=baserlib.CheckParameter(data, "src_path", default=None),
    start=baserlib.CheckParameter(data, "start", default=True),
    wait_for_sync=True,
    ip_check=baserlib.CheckParameter(data, "ip_check", default=True),
    name_check=baserlib.CheckParameter(data, "name_check", default=True),
    file_storage_dir=baserlib.CheckParameter(data, "file_storage_dir",
                                             default=None),
    file_driver=baserlib.CheckParameter(data, "file_driver",
                                        default=constants.FD_LOOP),
660
661
662
663
664
665
    source_handshake=baserlib.CheckParameter(data, "source_handshake",
                                             default=None),
    source_x509_ca=baserlib.CheckParameter(data, "source_x509_ca",
                                           default=None),
    source_instance_name=baserlib.CheckParameter(data, "source_instance_name",
                                                 default=None),
666
667
668
669
670
671
672
673
    iallocator=baserlib.CheckParameter(data, "iallocator", default=None),
    hypervisor=baserlib.CheckParameter(data, "hypervisor", default=None),
    hvparams=hvparams,
    beparams=beparams,
    dry_run=dry_run,
    )


674
675
676
677
678
679
680
681
class R_2_instances(baserlib.R_Generic):
  """/2/instances resource.

  """
  def GET(self):
    """Returns a list of all available instances.

    """
Iustin Pop's avatar
Iustin Pop committed
682
    client = baserlib.GetClient()
683

684
685
686
    use_locking = self.useLocking()
    if self.useBulk():
      bulkdata = client.QueryInstances([], I_FIELDS, use_locking)
687
      return baserlib.MapBulkFields(bulkdata, I_FIELDS)
688
    else:
689
      instancesdata = client.QueryInstances([], ["name"], use_locking)
690
      instanceslist = [row[0] for row in instancesdata]
691
692
693
      return baserlib.BuildUriList(instanceslist, "/2/instances/%s",
                                   uri_fields=("id", "uri"))

694
695
  def _ParseVersion0CreateRequest(self):
    """Parses an instance creation request version 0.
696

697
    Request data version 0 is deprecated and should not be used anymore.
698

699
700
    @rtype: L{opcodes.OpCreateInstance}
    @return: Instance creation opcode
Iustin Pop's avatar
Iustin Pop committed
701

702
    """
703
    # Do not modify anymore, request data version 0 is deprecated
704
    beparams = baserlib.MakeParamsDict(self.request_body,
Iustin Pop's avatar
Iustin Pop committed
705
                                       constants.BES_PARAMETERS)
706
    hvparams = baserlib.MakeParamsDict(self.request_body,
Iustin Pop's avatar
Iustin Pop committed
707
708
709
710
711
712
713
714
715
716
717
                                       constants.HVS_PARAMETERS)
    fn = self.getBodyParameter

    # disk processing
    disk_data = fn('disks')
    if not isinstance(disk_data, list):
      raise http.HttpBadRequest("The 'disks' parameter should be a list")
    disks = []
    for idx, d in enumerate(disk_data):
      if not isinstance(d, int):
        raise http.HttpBadRequest("Disk %d specification wrong: should"
718
                                  " be an integer" % idx)
Iustin Pop's avatar
Iustin Pop committed
719
      disks.append({"size": d})
720

Iustin Pop's avatar
Iustin Pop committed
721
    # nic processing (one nic only)
Guido Trotter's avatar
Guido Trotter committed
722
723
724
725
726
727
728
729
    nics = [{"mac": fn("mac", constants.VALUE_AUTO)}]
    if fn("ip", None) is not None:
      nics[0]["ip"] = fn("ip")
    if fn("mode", None) is not None:
      nics[0]["mode"] = fn("mode")
    if fn("link", None) is not None:
      nics[0]["link"] = fn("link")
    if fn("bridge", None) is not None:
730
      nics[0]["bridge"] = fn("bridge")
731

732
    # Do not modify anymore, request data version 0 is deprecated
733
    return opcodes.OpCreateInstance(
Iustin Pop's avatar
Iustin Pop committed
734
735
736
737
738
739
740
741
742
743
744
      mode=constants.INSTANCE_CREATE,
      instance_name=fn('name'),
      disks=disks,
      disk_template=fn('disk_template'),
      os_type=fn('os'),
      pnode=fn('pnode', None),
      snode=fn('snode', None),
      iallocator=fn('iallocator', None),
      nics=nics,
      start=fn('start', True),
      ip_check=fn('ip_check', True),
745
      name_check=fn('name_check', True),
Iustin Pop's avatar
Iustin Pop committed
746
747
748
749
750
      wait_for_sync=True,
      hypervisor=fn('hypervisor', None),
      hvparams=hvparams,
      beparams=beparams,
      file_storage_dir=fn('file_storage_dir', None),
751
      file_driver=fn('file_driver', constants.FD_LOOP),
Iustin Pop's avatar
Iustin Pop committed
752
      dry_run=bool(self.dryRun()),
Iustin Pop's avatar
Iustin Pop committed
753
754
      )

755
756
757
758
759
760
  def POST(self):
    """Create an instance.

    @return: a job id

    """
Luca Bigliardi's avatar
Luca Bigliardi committed
761
    if not isinstance(self.request_body, dict):
762
763
764
765
766
767
768
      raise http.HttpBadRequest("Invalid body contents, not a dictionary")

    # Default to request data version 0
    data_version = self.getBodyParameter(_REQ_DATA_VERSION, 0)

    if data_version == 0:
      op = self._ParseVersion0CreateRequest()
769
    elif data_version == 1:
Luca Bigliardi's avatar
Luca Bigliardi committed
770
      op = _ParseInstanceCreateRequestVersion1(self.request_body,
771
                                               self.dryRun())
772
773
    else:
      raise http.HttpBadRequest("Unsupported request data version %s" %
774
                                data_version)
775

Iustin Pop's avatar
Iustin Pop committed
776
    return baserlib.SubmitJob([op])
777

778

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
779
780
class R_2_instances_name(baserlib.R_Generic):
  """/2/instances/[instance_name] resources.
781
782

  """
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
783
784
785
786
  def GET(self):
    """Send information about an instance.

    """
Iustin Pop's avatar
Iustin Pop committed
787
    client = baserlib.GetClient()
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
788
    instance_name = self.items[0]
789
790
791
792
793

    result = baserlib.HandleItemQueryErrors(client.QueryInstances,
                                            names=[instance_name],
                                            fields=I_FIELDS,
                                            use_locking=self.useLocking())
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
794
795

    return baserlib.MapFields(I_FIELDS, result[0])
796

Iustin Pop's avatar
Iustin Pop committed
797
798
799
800
  def DELETE(self):
    """Delete an instance.

    """
Iustin Pop's avatar
Iustin Pop committed
801
    op = opcodes.OpRemoveInstance(instance_name=self.items[0],
Iustin Pop's avatar
Iustin Pop committed
802
803
                                  ignore_failures=False,
                                  dry_run=bool(self.dryRun()))
Iustin Pop's avatar
Iustin Pop committed
804
    return baserlib.SubmitJob([op])
Iustin Pop's avatar
Iustin Pop committed
805

806

807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
class R_2_instances_name_info(baserlib.R_Generic):
  """/2/instances/[instance_name]/info resource.

  """
  def GET(self):
    """Request detailed instance information.

    """
    instance_name = self.items[0]
    static = bool(self._checkIntVariable("static", default=0))

    op = opcodes.OpQueryInstanceData(instances=[instance_name],
                                     static=static)
    return baserlib.SubmitJob([op])


823
824
825
826
827
828
class R_2_instances_name_reboot(baserlib.R_Generic):
  """/2/instances/[instance_name]/reboot resource.

  Implements an instance reboot.

  """
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
829
  def POST(self):
830
831
    """Reboot an instance.

832
833
834
    The URI takes type=[hard|soft|full] and
    ignore_secondaries=[False|True] parameters.

835
836
    """
    instance_name = self.items[0]
837
838
    reboot_type = self.queryargs.get('type',
                                     [constants.INSTANCE_REBOOT_HARD])[0]
839
    ignore_secondaries = bool(self._checkIntVariable('ignore_secondaries'))
Iustin Pop's avatar
Iustin Pop committed
840
841
    op = opcodes.OpRebootInstance(instance_name=instance_name,
                                  reboot_type=reboot_type,
Iustin Pop's avatar
Iustin Pop committed
842
843
                                  ignore_secondaries=ignore_secondaries,
                                  dry_run=bool(self.dryRun()))
844

Iustin Pop's avatar
Iustin Pop committed
845
    return baserlib.SubmitJob([op])
846
847


848
849
850
851
852
853
class R_2_instances_name_startup(baserlib.R_Generic):
  """/2/instances/[instance_name]/startup resource.

  Implements an instance startup.

  """
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
854
  def PUT(self):
855
856
    """Startup an instance.

Iustin Pop's avatar
Iustin Pop committed
857
858
    The URI takes force=[False|True] parameter to start the instance
    if even if secondary disks are failing.
859
860
861

    """
    instance_name = self.items[0]
862
    force_startup = bool(self._checkIntVariable('force'))
Iustin Pop's avatar
Iustin Pop committed
863
    op = opcodes.OpStartupInstance(instance_name=instance_name,
Iustin Pop's avatar
Iustin Pop committed
864
865
                                   force=force_startup,
                                   dry_run=bool(self.dryRun()))
866

Iustin Pop's avatar
Iustin Pop committed
867
    return baserlib.SubmitJob([op])
868
869
870
871
872
873
874
875


class R_2_instances_name_shutdown(baserlib.R_Generic):
  """/2/instances/[instance_name]/shutdown resource.

  Implements an instance shutdown.

  """
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
876
  def PUT(self):
877
878
879
880
    """Shutdown an instance.

    """
    instance_name = self.items[0]
Iustin Pop's avatar
Iustin Pop committed
881
882
    op = opcodes.OpShutdownInstance(instance_name=instance_name,
                                    dry_run=bool(self.dryRun()))
883

Iustin Pop's avatar
Iustin Pop committed
884
    return baserlib.SubmitJob([op])
885
886


887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
def _ParseInstanceReinstallRequest(name, data):
  """Parses a request for reinstalling an instance.

  """
  if not isinstance(data, dict):
    raise http.HttpBadRequest("Invalid body contents, not a dictionary")

  ostype = baserlib.CheckParameter(data, "os")
  start = baserlib.CheckParameter(data, "start", exptype=bool,
                                  default=True)
  osparams = baserlib.CheckParameter(data, "osparams", default=None)

  ops = [
    opcodes.OpShutdownInstance(instance_name=name),
    opcodes.OpReinstallInstance(instance_name=name, os_type=ostype,
                                osparams=osparams),
    ]

  if start:
    ops.append(opcodes.OpStartupInstance(instance_name=name, force=False))

  return ops


911
912
913
914
915
916
917
918
919
920
921
922
923
924
class R_2_instances_name_reinstall(baserlib.R_Generic):
  """/2/instances/[instance_name]/reinstall resource.

  Implements an instance reinstall.

  """
  def POST(self):
    """Reinstall an instance.

    The URI takes os=name and nostartup=[0|1] optional
    parameters. By default, the instance will be started
    automatically.

    """
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
    if self.request_body:
      if self.queryargs:
        raise http.HttpBadRequest("Can't combine query and body parameters")

      body = self.request_body
    else:
      if not self.queryargs:
        raise http.HttpBadRequest("Missing query parameters")
      # Legacy interface, do not modify/extend
      body = {
        "os": self._checkStringVariable("os"),
        "start": not self._checkIntVariable("nostartup"),
        }

    ops = _ParseInstanceReinstallRequest(self.items[0], body)

941
942
943
    return baserlib.SubmitJob(ops)


944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
class R_2_instances_name_replace_disks(baserlib.R_Generic):
  """/2/instances/[instance_name]/replace-disks resource.

  """
  def POST(self):
    """Replaces disks on an instance.

    """
    instance_name = self.items[0]
    remote_node = self._checkStringVariable("remote_node", default=None)
    mode = self._checkStringVariable("mode", default=None)
    raw_disks = self._checkStringVariable("disks", default=None)
    iallocator = self._checkStringVariable("iallocator", default=None)

    if raw_disks:
      try:
        disks = [int(part) for part in raw_disks.split(",")]
      except ValueError, err:
        raise http.HttpBadRequest("Invalid disk index passed: %s" % str(err))
    else:
      disks = []

    op = opcodes.OpReplaceDisks(instance_name=instance_name,
                                remote_node=remote_node,
                                mode=mode,
                                disks=disks,
                                iallocator=iallocator)

    return baserlib.SubmitJob([op])


975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
class R_2_instances_name_activate_disks(baserlib.R_Generic):
  """/2/instances/[instance_name]/activate-disks resource.

  """
  def PUT(self):
    """Activate disks for an instance.

    The URI might contain ignore_size to ignore current recorded size.

    """
    instance_name = self.items[0]
    ignore_size = bool(self._checkIntVariable('ignore_size'))

    op = opcodes.OpActivateInstanceDisks(instance_name=instance_name,
                                         ignore_size=ignore_size)

    return baserlib.SubmitJob([op])


994
995
996
997
998
999
1000
1001
1002
1003
class R_2_instances_name_deactivate_disks(baserlib.R_Generic):
  """/2/instances/[instance_name]/deactivate-disks resource.

  """
  def PUT(self):
    """Deactivate disks for an instance.

    """
    instance_name = self.items[0]

1004
    op = opcodes.OpDeactivateInstanceDisks(instance_name=instance_name)
1005
1006
1007
1008

    return baserlib.SubmitJob([op])


1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
class R_2_instances_name_prepare_export(baserlib.R_Generic):
  """/2/instances/[instance_name]/prepare-export resource.

  """
  def PUT(self):
    """Prepares an export for an instance.

    @return: a job id

    """
    instance_name = self.items[0]
    mode = self._checkStringVariable("mode")

    op = opcodes.OpPrepareExport(instance_name=instance_name,
                                 mode=mode)

    return baserlib.SubmitJob([op])


def _ParseExportInstanceRequest(name, data):
  """Parses a request for an instance export.

  @rtype: L{opcodes.OpExportInstance}
  @return: Instance export opcode

  """
  mode = baserlib.CheckParameter(data, "mode",
                                 default=constants.EXPORT_MODE_LOCAL)
  target_node = baserlib.CheckParameter(data, "destination")
  shutdown = baserlib.CheckParameter(data, "shutdown", exptype=bool)
  remove_instance = baserlib.CheckParameter(data, "remove_instance",
                                            exptype=bool, default=False)
  x509_key_name = baserlib.CheckParameter(data, "x509_key_name", default=None)
  destination_x509_ca = baserlib.CheckParameter(data, "destination_x509_ca",
                                                default=None)

  return opcodes.OpExportInstance(instance_name=name,
                                  mode=mode,
                                  target_node=target_node,
                                  shutdown=shutdown,
                                  remove_instance=remove_instance,
                                  x509_key_name=x509_key_name,
                                  destination_x509_ca=destination_x509_ca)


class R_2_instances_name_export(baserlib.R_Generic):
  """/2/instances/[instance_name]/export resource.

  """
  def PUT(self):
    """Exports an instance.

    @return: a job id

    """
    if not isinstance(self.request_body, dict):
      raise http.HttpBadRequest("Invalid body contents, not a dictionary")

    op = _ParseExportInstanceRequest(self.items[0], self.request_body)

    return baserlib.SubmitJob([op])


1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
def _ParseMigrateInstanceRequest(name, data):
  """Parses a request for an instance migration.

  @rtype: L{opcodes.OpMigrateInstance}
  @return: Instance migration opcode

  """
  mode = baserlib.CheckParameter(data, "mode", default=None)
  cleanup = baserlib.CheckParameter(data, "cleanup", exptype=bool,
                                    default=False)

  return opcodes.OpMigrateInstance(instance_name=name, mode=mode,
                                   cleanup=cleanup)


class R_2_instances_name_migrate(baserlib.R_Generic):
  """/2/instances/[instance_name]/migrate resource.

  """
  def PUT(self):
    """Migrates an instance.

    @return: a job id

    """
    baserlib.CheckType(self.request_body, dict, "Body contents")

    op = _ParseMigrateInstanceRequest(self.items[0], self.request_body)

    return baserlib.SubmitJob([op])


1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
def _ParseRenameInstanceRequest(name, data):
  """Parses a request for renaming an instance.

  @rtype: L{opcodes.OpRenameInstance}
  @return: Instance rename opcode

  """
  new_name = baserlib.CheckParameter(data, "new_name")
  ip_check = baserlib.CheckParameter(data, "ip_check", default=True)
  name_check = baserlib.CheckParameter(data, "name_check", default=True)

  return opcodes.OpRenameInstance(instance_name=name, new_name=new_name,
                                  name_check=name_check, ip_check=ip_check)


class R_2_instances_name_rename(baserlib.R_Generic):
  """/2/instances/[instance_name]/rename resource.

  """
  def PUT(self):
    """Changes the name of an instance.

    @return: a job id

    """
    baserlib.CheckType(self.request_body, dict, "Body contents")

    op = _ParseRenameInstanceRequest(self.items[0], self.request_body)

    return baserlib.SubmitJob([op])


1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
def _ParseModifyInstanceRequest(name, data):
  """Parses a request for modifying an instance.

  @rtype: L{opcodes.OpSetInstanceParams}
  @return: Instance modify opcode

  """
  osparams = baserlib.CheckParameter(data, "osparams", default={})
  force = baserlib.CheckParameter(data, "force", default=False)
  nics = baserlib.CheckParameter(data, "nics", default=[])
  disks = baserlib.CheckParameter(data, "disks", default=[])
  disk_template = baserlib.CheckParameter(data, "disk_template", default=None)
  remote_node = baserlib.CheckParameter(data, "remote_node", default=None)
  os_name = baserlib.CheckParameter(data, "os_name", default=None)
  force_variant = baserlib.CheckParameter(data, "force_variant", default=False)

  # HV/BE parameters
  hvparams = baserlib.CheckParameter(data, "hvparams", default={})
  utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES,
                      allowed_values=[constants.VALUE_DEFAULT])

  beparams = baserlib.CheckParameter(data, "beparams", default={})
  utils.ForceDictType(beparams, constants.BES_PARAMETER_TYPES,
                      allowed_values=[constants.VALUE_DEFAULT])

  return opcodes.OpSetInstanceParams(instance_name=name, hvparams=hvparams,
                                     beparams=beparams, osparams=osparams,
                                     force=force, nics=nics, disks=disks,
                                     disk_template=disk_template,
                                     remote_node=remote_node, os_name=os_name,
                                     force_variant=force_variant)


class R_2_instances_name_modify(baserlib.R_Generic):
  """/2/instances/[instance_name]/modify resource.

  """
  def PUT(self):
    """Changes some parameters of an instance.

    @return: a job id

    """
    baserlib.CheckType(self.request_body, dict, "Body contents")

    op = _ParseModifyInstanceRequest(self.items[0], self.request_body)

    return baserlib.SubmitJob([op])


Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
1186
1187
class _R_Tags(baserlib.R_Generic):
  """ Quasiclass for tagging resources
1188

Iustin Pop's avatar
Iustin Pop committed
1189
  Manages tags. When inheriting this class you must define the
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
1190
  TAG_LEVEL for it.
1191
1192

  """
Iustin Pop's avatar
Iustin Pop committed
1193
  TAG_LEVEL = None
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
1194
1195
1196
1197
1198
1199
1200
1201
1202

  def __init__(self, items, queryargs, req):
    """A tag resource constructor.

    We have to override the default to sort out cluster naming case.

    """
    baserlib.R_Generic.__init__(self, items, queryargs, req)

1203
1204
    if self.TAG_LEVEL == constants.TAG_CLUSTER:
      self.name = None
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
1205
    else:
1206
      self.name = items[0]
1207
1208

  def GET(self):
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
1209
    """Returns a list of tags.
1210
1211
1212
1213

    Example: ["tag1", "tag2", "tag3"]

    """
Iustin Pop's avatar
Iustin Pop committed
1214
    # pylint: disable-msg=W0212
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
1215
    return baserlib._Tags_GET(self.TAG_LEVEL, name=self.name)
1216

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
1217
  def PUT(self):
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
1218
    """Add a set of tags.
1219

Iustin Pop's avatar
Iustin Pop committed
1220
1221
    The request as a list of strings should be PUT to this URI. And
    you'll have back a job id.
1222
1223

    """
Iustin Pop's avatar
Iustin Pop committed
1224
    # pylint: disable-msg=W0212
Iustin Pop's avatar
Iustin Pop committed
1225
1226
1227
    if 'tag' not in self.queryargs:
      raise http.HttpBadRequest("Please specify tag(s) to add using the"
                                " the 'tag' parameter")
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
1228
    return baserlib._Tags_PUT(self.TAG_LEVEL,
Iustin Pop's avatar
Iustin Pop committed
1229
1230
                              self.queryargs['tag'], name=self.name,
                              dry_run=bool(self.dryRun()))
1231
1232
1233
1234

  def DELETE(self):
    """Delete a tag.

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
1235
    In order to delete a set of tags, the DELETE
Iustin Pop's avatar
Iustin Pop committed
1236
    request should be addressed to URI like:
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
1237
    /tags?tag=[tag]&tag=[tag]
1238
1239

    """
Iustin Pop's avatar
Iustin Pop committed
1240
    # pylint: disable-msg=W0212
1241
    if 'tag' not in self.queryargs:
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
1242
      # no we not gonna delete all tags
Iustin Pop's avatar
Iustin Pop committed
1243
1244
      raise http.HttpBadRequest("Cannot delete all tags - please specify"
                                " tag(s) using the 'tag' parameter")
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
1245
    return baserlib._Tags_DELETE(self.TAG_LEVEL,
1246
                                 self.queryargs['tag'],
Iustin Pop's avatar
Iustin Pop committed
1247
1248
                                 name=self.name,
                                 dry_run=bool(self.dryRun()))
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275


class R_2_instances_name_tags(_R_Tags):
  """ /2/instances/[instance_name]/tags resource.

  Manages per-instance tags.

  """
  TAG_LEVEL = constants.TAG_INSTANCE


class R_2_nodes_name_tags(_R_Tags):
  """ /2/nodes/[node_name]/tags resource.

  Manages per-node tags.

  """
  TAG_LEVEL = constants.TAG_NODE


class R_2_tags(_R_Tags):
  """ /2/instances/tags resource.

  Manages cluster tags.

  """
  TAG_LEVEL = constants.TAG_CLUSTER