rlib2.py 15.6 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
from ganeti import opcodes
27
28
from ganeti import http
from ganeti import constants
Iustin Pop's avatar
Iustin Pop committed
29
from ganeti import cli
Iustin Pop's avatar
Iustin Pop committed
30
from ganeti.rapi import baserlib
31

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
32

Iustin Pop's avatar
Iustin Pop committed
33

34
35
36
37
I_FIELDS = ["name", "admin_state", "os",
            "pnode", "snodes",
            "disk_template",
            "nic.ips", "nic.macs", "nic.bridges",
38
            "network_port",
39
            "disk.sizes", "disk_usage",
40
            "beparams", "hvparams",
41
42
43
            "oper_state", "oper_ram", "status",
            "tags"]

44
N_FIELDS = ["name", "offline", "master_candidate", "drained",
45
            "dtotal", "dfree",
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
46
            "mtotal", "mnode", "mfree",
47
48
            "pinst_cnt", "sinst_cnt", "tags",
            "ctotal", "cnodes", "csockets",
49
50
            "pip", "sip", "serial_no", "role",
            "pinst_list", "sinst_list",
51
            ]
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80


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

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

  """
  DOC_URI = "/version"

  def GET(self):
    """Returns the remote API version.

    """
    return constants.RAPI_VERSION


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

  """
  DOC_URI = "/2/info"

  def GET(self):
    """Returns cluster information.

    Example::

Iustin Pop's avatar
Iustin Pop committed
81
82
83
    {
      "config_version": 2000000,
      "name": "cluster",
Iustin Pop's avatar
Iustin Pop committed
84
      "software_version": "2.0.0~beta2",
Iustin Pop's avatar
Iustin Pop committed
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
      "os_api_version": 10,
      "export_version": 0,
      "candidate_pool_size": 10,
      "enabled_hypervisors": [
        "fake"
      ],
      "hvparams": {
        "fake": {}
       },
      "default_hypervisor": "fake",
      "master": "node1.example.com",
      "architecture": [
        "64bit",
        "x86_64"
      ],
      "protocol_version": 20,
      "beparams": {
        "default": {
          "auto_balance": true,
          "vcpus": 1,
          "memory": 128
         }
        }
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
108
109
110
      }

    """
Iustin Pop's avatar
Iustin Pop committed
111
    client = baserlib.GetClient()
112
    return client.QueryClusterInfo()
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128


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

  """
  DOC_URI = "/2/os"

  def GET(self):
    """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
129
130
131
132
133
134
    cl = baserlib.GetClient()
    op = opcodes.OpDiagnoseOS(output_fields=["name", "valid"], names=[])
    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
135
136

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

    return [row[0] for row in diagnose_data if row[1]]
140

141
142
143
144
145
146
147
148
149
150

class R_2_jobs(baserlib.R_Generic):
  """/2/jobs resource.

  """
  DOC_URI = "/2/jobs"

  def GET(self):
    """Returns a dictionary of jobs.

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

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


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

  """
  DOC_URI = "/2/jobs/[job_id]"

  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

class R_2_nodes(baserlib.R_Generic):
  """/2/nodes resource.

  """
  DOC_URI = "/2/nodes"
Iustin Pop's avatar
Iustin Pop committed
205

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

Iustin Pop's avatar
Iustin Pop committed
209
    Example::
210

Iustin Pop's avatar
Iustin Pop committed
211
      [
212
213
214
215
216
217
218
        {
          "id": "node1.example.com",
          "uri": "\/instances\/node1.example.com"
        },
        {
          "id": "node2.example.com",
          "uri": "\/instances\/node2.example.com"
Iustin Pop's avatar
Iustin Pop committed
219
220
        }
      ]
221

Iustin Pop's avatar
Iustin Pop committed
222
    If the optional 'bulk' argument is provided and set to 'true'
223
224
225
    value (i.e '?bulk=1'), the output contains detailed
    information about nodes as a list.

Iustin Pop's avatar
Iustin Pop committed
226
227
228
    Example::

      [
229
230
231
232
233
234
235
236
237
        {
          "pinst_cnt": 1,
          "mfree": 31280,
          "mtotal": 32763,
          "name": "www.example.com",
          "tags": [],
          "mnode": 512,
          "dtotal": 5246208,
          "sinst_cnt": 2,
238
239
          "dfree": 5171712,
          "offline": false
240
241
        },
        ...
Iustin Pop's avatar
Iustin Pop committed
242
243
244
      ]

    @return: a dictionary with 'name' and 'uri' keys for each of them
245
246

    """
Iustin Pop's avatar
Iustin Pop committed
247
    client = baserlib.GetClient()
Iustin Pop's avatar
Iustin Pop committed
248

249
    if self.useBulk():
250
      bulkdata = client.QueryNodes([], N_FIELDS, False)
251
      return baserlib.MapBulkFields(bulkdata, N_FIELDS)
252
253
254
255
256
    else:
      nodesdata = client.QueryNodes([], ["name"], False)
      nodeslist = [row[0] for row in nodesdata]
      return baserlib.BuildUriList(nodeslist, "/2/nodes/%s",
                                   uri_fields=("id", "uri"))
257
258


Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
259
260
class R_2_nodes_name(baserlib.R_Generic):
  """/2/nodes/[node_name] resources.
261
262

  """
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
263
264
265
266
267
268
269
  DOC_URI = "/nodes/[node_name]"

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

    """
    node_name = self.items[0]
Iustin Pop's avatar
Iustin Pop committed
270
    client = baserlib.GetClient()
271
    result = client.QueryNodes(names=[node_name], fields=N_FIELDS,
272
                               use_locking=self.useLocking())
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
273
274

    return baserlib.MapFields(N_FIELDS, result[0])
275
276


277
278
279
280
281
282
283
284
285
286
class R_2_instances(baserlib.R_Generic):
  """/2/instances resource.

  """
  DOC_URI = "/2/instances"

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


Iustin Pop's avatar
Iustin Pop committed
287
288
289
    Example::

      [
290
291
292
293
294
295
296
        {
          "name": "web.example.com",
          "uri": "\/instances\/web.example.com"
        },
        {
          "name": "mail.example.com",
          "uri": "\/instances\/mail.example.com"
Iustin Pop's avatar
Iustin Pop committed
297
298
        }
      ]
299
300
301
302
303

    If the optional 'bulk' argument is provided and set to 'true'
    value (i.e '?bulk=1'), the output contains detailed
    information about instances as a list.

Iustin Pop's avatar
Iustin Pop committed
304
305
306
    Example::

      [
307
308
        {
           "status": "running",
Iustin Pop's avatar
Iustin Pop committed
309
310
311
312
           "disk_usage": 20480,
           "nic.bridges": [
             "xen-br0"
            ],
313
314
           "name": "web.example.com",
           "tags": ["tag1", "tag2"],
Iustin Pop's avatar
Iustin Pop committed
315
316
317
318
319
320
321
           "beparams": {
             "vcpus": 2,
             "memory": 512
           },
           "disk.sizes": [
               20480
           ],
322
           "pnode": "node1.example.com",
Iustin Pop's avatar
Iustin Pop committed
323
           "nic.macs": ["01:23:45:67:89:01"],
324
325
326
327
328
329
330
           "snodes": ["node2.example.com"],
           "disk_template": "drbd",
           "admin_state": true,
           "os": "debian-etch",
           "oper_state": true
        },
        ...
Iustin Pop's avatar
Iustin Pop committed
331
332
      ]

Iustin Pop's avatar
Iustin Pop committed
333
    @return: a dictionary with 'name' and 'uri' keys for each of them.
334
335

    """
Iustin Pop's avatar
Iustin Pop committed
336
    client = baserlib.GetClient()
337

338
339
340
    use_locking = self.useLocking()
    if self.useBulk():
      bulkdata = client.QueryInstances([], I_FIELDS, use_locking)
341
      return baserlib.MapBulkFields(bulkdata, I_FIELDS)
342
    else:
343
      instancesdata = client.QueryInstances([], ["name"], use_locking)
344
      instanceslist = [row[0] for row in instancesdata]
345
346
347
      return baserlib.BuildUriList(instanceslist, "/2/instances/%s",
                                   uri_fields=("id", "uri"))

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
348
  def POST(self):
349
350
    """Create an instance.

Iustin Pop's avatar
Iustin Pop committed
351
    @return: a job id
352
353

    """
Iustin Pop's avatar
Iustin Pop committed
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
    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"
                                  " be an integer")
      disks.append({"size": d})
    # nic processing (one nic only)
    nics = [{"mac": fn("mac", constants.VALUE_AUTO),
             "ip": fn("ip", None),
             "bridge": fn("bridge", None)}]
377

Iustin Pop's avatar
Iustin Pop committed
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
    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),
      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'),
      )

    return baserlib.SubmitJob([op])
399

400

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
401
402
class R_2_instances_name(baserlib.R_Generic):
  """/2/instances/[instance_name] resources.
403
404

  """
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
405
406
407
408
409
410
  DOC_URI = "/2/instances/[instance_name]"

  def GET(self):
    """Send information about an instance.

    """
Iustin Pop's avatar
Iustin Pop committed
411
    client = baserlib.GetClient()
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
412
    instance_name = self.items[0]
413
    result = client.QueryInstances(names=[instance_name], fields=I_FIELDS,
414
                                   use_locking=self.useLocking())
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
415
416

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

Iustin Pop's avatar
Iustin Pop committed
418
419
420
421
  def DELETE(self):
    """Delete an instance.

    """
Iustin Pop's avatar
Iustin Pop committed
422
423
424
    op = opcodes.OpRemoveInstance(instance_name=self.items[0],
                                  ignore_failures=False)
    return baserlib.SubmitJob([op])
Iustin Pop's avatar
Iustin Pop committed
425

426

427
428
429
430
431
432
433
434
435
class R_2_instances_name_reboot(baserlib.R_Generic):
  """/2/instances/[instance_name]/reboot resource.

  Implements an instance reboot.

  """

  DOC_URI = "/2/instances/[instance_name]/reboot"

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
436
  def POST(self):
437
438
    """Reboot an instance.

439
440
441
    The URI takes type=[hard|soft|full] and
    ignore_secondaries=[False|True] parameters.

442
443
    """
    instance_name = self.items[0]
444
445
    reboot_type = self.queryargs.get('type',
                                     [constants.INSTANCE_REBOOT_HARD])[0]
446
    ignore_secondaries = bool(self._checkIntVariable('ignore_secondaries'))
Iustin Pop's avatar
Iustin Pop committed
447
448
449
    op = opcodes.OpRebootInstance(instance_name=instance_name,
                                  reboot_type=reboot_type,
                                  ignore_secondaries=ignore_secondaries)
450

Iustin Pop's avatar
Iustin Pop committed
451
    return baserlib.SubmitJob([op])
452
453


454
455
456
457
458
459
460
461
462
class R_2_instances_name_startup(baserlib.R_Generic):
  """/2/instances/[instance_name]/startup resource.

  Implements an instance startup.

  """

  DOC_URI = "/2/instances/[instance_name]/startup"

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
463
  def PUT(self):
464
465
    """Startup an instance.

Iustin Pop's avatar
Iustin Pop committed
466
467
    The URI takes force=[False|True] parameter to start the instance
    if even if secondary disks are failing.
468
469
470

    """
    instance_name = self.items[0]
471
    force_startup = bool(self._checkIntVariable('force'))
Iustin Pop's avatar
Iustin Pop committed
472
473
    op = opcodes.OpStartupInstance(instance_name=instance_name,
                                   force=force_startup)
474

Iustin Pop's avatar
Iustin Pop committed
475
    return baserlib.SubmitJob([op])
476
477
478
479
480
481
482
483
484
485
486


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

  Implements an instance shutdown.

  """

  DOC_URI = "/2/instances/[instance_name]/shutdown"

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
487
  def PUT(self):
488
489
490
491
    """Shutdown an instance.

    """
    instance_name = self.items[0]
Iustin Pop's avatar
Iustin Pop committed
492
    op = opcodes.OpShutdownInstance(instance_name=instance_name)
493

Iustin Pop's avatar
Iustin Pop committed
494
    return baserlib.SubmitJob([op])
495
496


497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
class R_2_instances_name_reinstall(baserlib.R_Generic):
  """/2/instances/[instance_name]/reinstall resource.

  Implements an instance reinstall.

  """

  DOC_URI = "/2/instances/[instance_name]/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)


Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
527
528
class _R_Tags(baserlib.R_Generic):
  """ Quasiclass for tagging resources
529

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
530
531
  Manages tags. Inheriting this class you suppose to define DOC_URI and
  TAG_LEVEL for it.
532
533

  """
Iustin Pop's avatar
Iustin Pop committed
534
  TAG_LEVEL = None
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
535
536
537
538
539
540
541
542
543
544
545
546
547

  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 = ""
548
549

  def GET(self):
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
550
    """Returns a list of tags.
551
552
553
554

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

    """
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
555
    return baserlib._Tags_GET(self.TAG_LEVEL, name=self.name)
556

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
557
  def PUT(self):
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
558
    """Add a set of tags.
559

Iustin Pop's avatar
Iustin Pop committed
560
561
    The request as a list of strings should be PUT to this URI. And
    you'll have back a job id.
562
563

    """
Iustin Pop's avatar
Iustin Pop committed
564
565
566
    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
567
    return baserlib._Tags_PUT(self.TAG_LEVEL,
Iustin Pop's avatar
Iustin Pop committed
568
                              self.queryargs['tag'], name=self.name)
569
570
571
572

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

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
573
    In order to delete a set of tags, the DELETE
Iustin Pop's avatar
Iustin Pop committed
574
    request should be addressed to URI like:
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
575
    /tags?tag=[tag]&tag=[tag]
576
577
578

    """
    if 'tag' not in self.queryargs:
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
579
      # no we not gonna delete all tags
Iustin Pop's avatar
Iustin Pop committed
580
581
      raise http.HttpBadRequest("Cannot delete all tags - please specify"
                                " tag(s) using the 'tag' parameter")
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
582
    return baserlib._Tags_DELETE(self.TAG_LEVEL,
583
                                 self.queryargs['tag'],
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
                                 name=self.name)


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

  Manages per-instance tags.

  """
  DOC_URI = "/2/instances/[instance_name]/tags"
  TAG_LEVEL = constants.TAG_INSTANCE


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

  Manages per-node tags.

  """
  DOC_URI = "/2/nodes/[node_name]/tags"
  TAG_LEVEL = constants.TAG_NODE


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

  Manages cluster tags.

  """
  DOC_URI = "/2/tags"
  TAG_LEVEL = constants.TAG_CLUSTER