rlib2.py 20.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#
#

# Copyright (C) 2006, 2007, 2008 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
# 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.

"""

Iustin Pop's avatar
Iustin Pop committed
26
27
28
29
# pylint: disable-msg=C0103

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

Iustin Pop's avatar
Iustin Pop committed
30
from ganeti import opcodes
31
32
from ganeti import http
from ganeti import constants
Iustin Pop's avatar
Iustin Pop committed
33
from ganeti import cli
Michael Hanselmann's avatar
Michael Hanselmann committed
34
from ganeti import rapi
Iustin Pop's avatar
Iustin Pop committed
35
from ganeti.rapi import baserlib
36

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
37

Iustin Pop's avatar
Iustin Pop committed
38
_COMMON_FIELDS = ["ctime", "mtime", "uuid", "serial_no", "tags"]
39
40
41
I_FIELDS = ["name", "admin_state", "os",
            "pnode", "snodes",
            "disk_template",
42
            "nic.ips", "nic.macs", "nic.modes", "nic.links", "nic.bridges",
43
            "network_port",
44
            "disk.sizes", "disk_usage",
45
            "beparams", "hvparams",
46
            "oper_state", "oper_ram", "status",
Iustin Pop's avatar
Iustin Pop committed
47
            ] + _COMMON_FIELDS
48

49
N_FIELDS = ["name", "offline", "master_candidate", "drained",
50
            "dtotal", "dfree",
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
51
            "mtotal", "mnode", "mfree",
Iustin Pop's avatar
Iustin Pop committed
52
            "pinst_cnt", "sinst_cnt",
53
            "ctotal", "cnodes", "csockets",
Iustin Pop's avatar
Iustin Pop committed
54
            "pip", "sip", "role",
55
            "pinst_list", "sinst_list",
Iustin Pop's avatar
Iustin Pop committed
56
            ] + _COMMON_FIELDS
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
57

58
59
60
61
62
63
64
65
66
67
68
69
70
71
_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,
  }

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
72
73
74
75
76
77
78
79

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

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

  """
80
81
  @staticmethod
  def GET():
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
82
83
84
85
86
87
88
89
90
91
    """Returns the remote API version.

    """
    return constants.RAPI_VERSION


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

  """
92
93
  @staticmethod
  def GET():
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
94
95
96
    """Returns cluster information.

    """
Iustin Pop's avatar
Iustin Pop committed
97
    client = baserlib.GetClient()
98
    return client.QueryClusterInfo()
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
99
100
101
102
103
104


class R_2_os(baserlib.R_Generic):
  """/2/os resource.

  """
105
106
  @staticmethod
  def GET():
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
107
108
109
110
111
112
113
    """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
114
    cl = baserlib.GetClient()
115
116
    op = opcodes.OpDiagnoseOS(output_fields=["name", "valid", "variants"],
                              names=[])
Iustin Pop's avatar
Iustin Pop committed
117
118
119
120
    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
121
122

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

125
126
127
128
129
130
    os_names = []
    for (name, valid, variants) in diagnose_data:
      if valid:
        os_names.extend(cli.CalculateOSNames(name, variants))

    return os_names
131

132

133
134
135
136
class R_2_redist_config(baserlib.R_Generic):
  """/2/redistribute-config resource.

  """
137
138
  @staticmethod
  def PUT():
139
140
141
142
143
144
    """Redistribute configuration to all nodes.

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


145
146
147
148
class R_2_jobs(baserlib.R_Generic):
  """/2/jobs resource.

  """
149
150
  @staticmethod
  def GET():
151
152
    """Returns a dictionary of jobs.

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

155
156
    """
    fields = ["id"]
Iustin Pop's avatar
Iustin Pop committed
157
    cl = baserlib.GetClient()
158
    # Convert the list of lists to the list of ids
Iustin Pop's avatar
Iustin Pop committed
159
    result = [job_id for [job_id] in cl.QueryJobs(None, fields)]
160
161
    return baserlib.BuildUriList(result, "/2/jobs/%s",
                                 uri_fields=("id", "uri"))
162
163
164
165
166
167
168
169
170


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
171
172
173
174
175
176
177
178
    @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
179

180
    """
Iustin Pop's avatar
Iustin Pop committed
181
182
183
184
    fields = ["id", "ops", "status", "summary",
              "opstatus", "opresult", "oplog",
              "received_ts", "start_ts", "end_ts",
              ]
185
    job_id = self.items[0]
Iustin Pop's avatar
Iustin Pop committed
186
    result = baserlib.GetClient().QueryJobs([job_id, ], fields)[0]
Iustin Pop's avatar
Iustin Pop committed
187
188
    if result is None:
      raise http.HttpNotFound()
189
190
    return baserlib.MapFields(fields, result)

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
191
192
193
194
195
  def DELETE(self):
    """Cancel not-yet-started job.

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

199
200
201
202
203
204
205

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
206

207
    """
Iustin Pop's avatar
Iustin Pop committed
208
    client = baserlib.GetClient()
Iustin Pop's avatar
Iustin Pop committed
209

210
    if self.useBulk():
211
      bulkdata = client.QueryNodes([], N_FIELDS, False)
212
      return baserlib.MapBulkFields(bulkdata, N_FIELDS)
213
214
215
216
217
    else:
      nodesdata = client.QueryNodes([], ["name"], False)
      nodeslist = [row[0] for row in nodesdata]
      return baserlib.BuildUriList(nodeslist, "/2/nodes/%s",
                                   uri_fields=("id", "uri"))
218
219


Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
220
221
class R_2_nodes_name(baserlib.R_Generic):
  """/2/nodes/[node_name] resources.
222
223

  """
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
224
225
226
227
228
  def GET(self):
    """Send information about a node.

    """
    node_name = self.items[0]
Iustin Pop's avatar
Iustin Pop committed
229
    client = baserlib.GetClient()
230
    result = client.QueryNodes(names=[node_name], fields=N_FIELDS,
231
                               use_locking=self.useLocking())
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
232
233

    return baserlib.MapFields(N_FIELDS, result[0])
234
235


236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
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
293
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

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

    node_name = self.items[0]
    role = self.req.request_body

    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])


294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
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)

    op = opcodes.OpEvacuateNode(node_name=node_name,
                                remote_node=remote_node,
                                iallocator=iallocator)

    return baserlib.SubmitJob([op])


313
class R_2_nodes_name_migrate(baserlib.R_Generic):
314
  """/2/nodes/[node_name]/migrate resource.
315
316
317
318
319
320
321
322
323
324
325
326
327
328

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

    """
    node_name = self.items[0]
    live = bool(self._checkIntVariable("live", default=1))

    op = opcodes.OpMigrateNode(node_name=node_name, live=live)

    return baserlib.SubmitJob([op])


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
354
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])


355
356
357
358
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
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])


385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
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])


408
409
410
411
412
413
414
415
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
416
    client = baserlib.GetClient()
417

418
419
420
    use_locking = self.useLocking()
    if self.useBulk():
      bulkdata = client.QueryInstances([], I_FIELDS, use_locking)
421
      return baserlib.MapBulkFields(bulkdata, I_FIELDS)
422
    else:
423
      instancesdata = client.QueryInstances([], ["name"], use_locking)
424
      instanceslist = [row[0] for row in instancesdata]
425
426
427
      return baserlib.BuildUriList(instanceslist, "/2/instances/%s",
                                   uri_fields=("id", "uri"))

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
428
  def POST(self):
429
430
    """Create an instance.

Iustin Pop's avatar
Iustin Pop committed
431
    @return: a job id
432
433

    """
Iustin Pop's avatar
Iustin Pop committed
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
    if not isinstance(self.req.request_body, dict):
      raise http.HttpBadRequest("Invalid body contents, not a dictionary")

    beparams = baserlib.MakeParamsDict(self.req.request_body,
                                       constants.BES_PARAMETERS)
    hvparams = baserlib.MakeParamsDict(self.req.request_body,
                                       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"
451
                                  " be an integer" % idx)
Iustin Pop's avatar
Iustin Pop committed
452
453
      disks.append({"size": d})
    # nic processing (one nic only)
Guido Trotter's avatar
Guido Trotter committed
454
455
456
457
458
459
460
461
    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:
462
      nics[0]["bridge"] = fn("bridge")
463

Iustin Pop's avatar
Iustin Pop committed
464
465
466
467
468
469
470
471
472
473
474
475
    op = opcodes.OpCreateInstance(
      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),
476
      name_check=fn('name_check', True),
Iustin Pop's avatar
Iustin Pop committed
477
478
479
480
481
482
      wait_for_sync=True,
      hypervisor=fn('hypervisor', None),
      hvparams=hvparams,
      beparams=beparams,
      file_storage_dir=fn('file_storage_dir', None),
      file_driver=fn('file_driver', 'loop'),
Iustin Pop's avatar
Iustin Pop committed
483
      dry_run=bool(self.dryRun()),
Iustin Pop's avatar
Iustin Pop committed
484
485
486
      )

    return baserlib.SubmitJob([op])
487

488

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
489
490
class R_2_instances_name(baserlib.R_Generic):
  """/2/instances/[instance_name] resources.
491
492

  """
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
493
494
495
496
  def GET(self):
    """Send information about an instance.

    """
Iustin Pop's avatar
Iustin Pop committed
497
    client = baserlib.GetClient()
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
498
    instance_name = self.items[0]
499
    result = client.QueryInstances(names=[instance_name], fields=I_FIELDS,
500
                                   use_locking=self.useLocking())
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
501
502

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

Iustin Pop's avatar
Iustin Pop committed
504
505
506
507
  def DELETE(self):
    """Delete an instance.

    """
Iustin Pop's avatar
Iustin Pop committed
508
    op = opcodes.OpRemoveInstance(instance_name=self.items[0],
Iustin Pop's avatar
Iustin Pop committed
509
510
                                  ignore_failures=False,
                                  dry_run=bool(self.dryRun()))
Iustin Pop's avatar
Iustin Pop committed
511
    return baserlib.SubmitJob([op])
Iustin Pop's avatar
Iustin Pop committed
512

513

514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
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])


530
531
532
533
534
535
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
536
  def POST(self):
537
538
    """Reboot an instance.

539
540
541
    The URI takes type=[hard|soft|full] and
    ignore_secondaries=[False|True] parameters.

542
543
    """
    instance_name = self.items[0]
544
545
    reboot_type = self.queryargs.get('type',
                                     [constants.INSTANCE_REBOOT_HARD])[0]
546
    ignore_secondaries = bool(self._checkIntVariable('ignore_secondaries'))
Iustin Pop's avatar
Iustin Pop committed
547
548
    op = opcodes.OpRebootInstance(instance_name=instance_name,
                                  reboot_type=reboot_type,
Iustin Pop's avatar
Iustin Pop committed
549
550
                                  ignore_secondaries=ignore_secondaries,
                                  dry_run=bool(self.dryRun()))
551

Iustin Pop's avatar
Iustin Pop committed
552
    return baserlib.SubmitJob([op])
553
554


555
556
557
558
559
560
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
561
  def PUT(self):
562
563
    """Startup an instance.

Iustin Pop's avatar
Iustin Pop committed
564
565
    The URI takes force=[False|True] parameter to start the instance
    if even if secondary disks are failing.
566
567
568

    """
    instance_name = self.items[0]
569
    force_startup = bool(self._checkIntVariable('force'))
Iustin Pop's avatar
Iustin Pop committed
570
    op = opcodes.OpStartupInstance(instance_name=instance_name,
Iustin Pop's avatar
Iustin Pop committed
571
572
                                   force=force_startup,
                                   dry_run=bool(self.dryRun()))
573

Iustin Pop's avatar
Iustin Pop committed
574
    return baserlib.SubmitJob([op])
575
576
577
578
579
580
581
582


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
583
  def PUT(self):
584
585
586
587
    """Shutdown an instance.

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

Iustin Pop's avatar
Iustin Pop committed
591
    return baserlib.SubmitJob([op])
592
593


594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
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.

    """
    instance_name = self.items[0]
    ostype = self._checkStringVariable('os')
    nostartup = self._checkIntVariable('nostartup')
    ops = [
      opcodes.OpShutdownInstance(instance_name=instance_name),
      opcodes.OpReinstallInstance(instance_name=instance_name, os_type=ostype),
      ]
    if not nostartup:
      ops.append(opcodes.OpStartupInstance(instance_name=instance_name,
                                           force=False))
    return baserlib.SubmitJob(ops)


621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
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])


652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
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])


Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
671
672
class _R_Tags(baserlib.R_Generic):
  """ Quasiclass for tagging resources
673

Iustin Pop's avatar
Iustin Pop committed
674
  Manages tags. When inheriting this class you must define the
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
675
  TAG_LEVEL for it.
676
677

  """
Iustin Pop's avatar
Iustin Pop committed
678
  TAG_LEVEL = None
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
679
680
681
682
683
684
685
686
687
688
689
690
691

  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)

    if self.TAG_LEVEL != constants.TAG_CLUSTER:
      self.name = items[0]
    else:
      self.name = ""
692
693

  def GET(self):
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
694
    """Returns a list of tags.
695
696
697
698

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

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

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
702
  def PUT(self):
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
703
    """Add a set of tags.
704

Iustin Pop's avatar
Iustin Pop committed
705
706
    The request as a list of strings should be PUT to this URI. And
    you'll have back a job id.
707
708

    """
Iustin Pop's avatar
Iustin Pop committed
709
    # pylint: disable-msg=W0212
Iustin Pop's avatar
Iustin Pop committed
710
711
712
    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
713
    return baserlib._Tags_PUT(self.TAG_LEVEL,
Iustin Pop's avatar
Iustin Pop committed
714
715
                              self.queryargs['tag'], name=self.name,
                              dry_run=bool(self.dryRun()))
716
717
718
719

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

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
720
    In order to delete a set of tags, the DELETE
Iustin Pop's avatar
Iustin Pop committed
721
    request should be addressed to URI like:
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
722
    /tags?tag=[tag]&tag=[tag]
723
724

    """
Iustin Pop's avatar
Iustin Pop committed
725
    # pylint: disable-msg=W0212
726
    if 'tag' not in self.queryargs:
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
727
      # no we not gonna delete all tags
Iustin Pop's avatar
Iustin Pop committed
728
729
      raise http.HttpBadRequest("Cannot delete all tags - please specify"
                                " tag(s) using the 'tag' parameter")
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
730
    return baserlib._Tags_DELETE(self.TAG_LEVEL,
731
                                 self.queryargs['tag'],
Iustin Pop's avatar
Iustin Pop committed
732
733
                                 name=self.name,
                                 dry_run=bool(self.dryRun()))
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760


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