Statistics
| Branch: | Tag: | Revision:

root / lib / server / noded.py @ 3a9fe2bc

History | View | Annotate | Download (32.1 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2010, 2011, 2012 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21

    
22
"""Ganeti node daemon"""
23

    
24
# pylint: disable=C0103,W0142
25

    
26
# C0103: Functions in this module need to have a given name structure,
27
# and the name of the daemon doesn't match
28

    
29
# W0142: Used * or ** magic, since we do use it extensively in this
30
# module
31

    
32
import os
33
import sys
34
import logging
35
import signal
36
import codecs
37

    
38
from optparse import OptionParser
39

    
40
from ganeti import backend
41
from ganeti import constants
42
from ganeti import objects
43
from ganeti import errors
44
from ganeti import jstore
45
from ganeti import daemon
46
from ganeti import http
47
from ganeti import utils
48
from ganeti import storage
49
from ganeti import serializer
50
from ganeti import netutils
51
from ganeti import pathutils
52
from ganeti import ssconf
53

    
54
import ganeti.http.server # pylint: disable=W0611
55

    
56

    
57
queue_lock = None
58

    
59

    
60
def _extendReasonTrail(trail, source, reason=""):
61
  """Extend the reason trail with noded information
62

63
  The trail is extended by appending the name of the noded functionality
64
  """
65
  assert trail is not None
66
  trail_source = "%s:%s" % (constants.OPCODE_REASON_SRC_NODED, source)
67
  trail.append((trail_source, reason, utils.EpochNano()))
68

    
69

    
70
def _PrepareQueueLock():
71
  """Try to prepare the queue lock.
72

73
  @return: None for success, otherwise an exception object
74

75
  """
76
  global queue_lock # pylint: disable=W0603
77

    
78
  if queue_lock is not None:
79
    return None
80

    
81
  # Prepare job queue
82
  try:
83
    queue_lock = jstore.InitAndVerifyQueue(must_lock=False)
84
    return None
85
  except EnvironmentError, err:
86
    return err
87

    
88

    
89
def _RequireJobQueueLock(fn):
90
  """Decorator for job queue manipulating functions.
91

92
  """
93
  QUEUE_LOCK_TIMEOUT = 10
94

    
95
  def wrapper(*args, **kwargs):
96
    # Locking in exclusive, blocking mode because there could be several
97
    # children running at the same time. Waiting up to 10 seconds.
98
    if _PrepareQueueLock() is not None:
99
      raise errors.JobQueueError("Job queue failed initialization,"
100
                                 " cannot update jobs")
101
    queue_lock.Exclusive(blocking=True, timeout=QUEUE_LOCK_TIMEOUT)
102
    try:
103
      return fn(*args, **kwargs)
104
    finally:
105
      queue_lock.Unlock()
106

    
107
  return wrapper
108

    
109

    
110
def _DecodeImportExportIO(ieio, ieioargs):
111
  """Decodes import/export I/O information.
112

113
  """
114
  if ieio == constants.IEIO_RAW_DISK:
115
    assert len(ieioargs) == 1
116
    return (objects.Disk.FromDict(ieioargs[0]), )
117

    
118
  if ieio == constants.IEIO_SCRIPT:
119
    assert len(ieioargs) == 2
120
    return (objects.Disk.FromDict(ieioargs[0]), ieioargs[1])
121

    
122
  return ieioargs
123

    
124

    
125
def _DefaultAlternative(value, default):
126
  """Returns value or, if evaluating to False, a default value.
127

128
  Returns the given value, unless it evaluates to False. In the latter case the
129
  default value is returned.
130

131
  @param value: Value to return if it doesn't evaluate to False
132
  @param default: Default value
133
  @return: Given value or the default
134

135
  """
136
  if value:
137
    return value
138

    
139
  return default
140

    
141

    
142
class MlockallRequestExecutor(http.server.HttpServerRequestExecutor):
143
  """Subclass ensuring request handlers are locked in RAM.
144

145
  """
146
  def __init__(self, *args, **kwargs):
147
    utils.Mlockall()
148

    
149
    http.server.HttpServerRequestExecutor.__init__(self, *args, **kwargs)
150

    
151

    
152
class NodeRequestHandler(http.server.HttpServerHandler):
153
  """The server implementation.
154

155
  This class holds all methods exposed over the RPC interface.
156

157
  """
158
  # too many public methods, and unused args - all methods get params
159
  # due to the API
160
  # pylint: disable=R0904,W0613
161
  def __init__(self):
162
    http.server.HttpServerHandler.__init__(self)
163
    self.noded_pid = os.getpid()
164

    
165
  def HandleRequest(self, req):
166
    """Handle a request.
167

168
    """
169
    if req.request_method.upper() != http.HTTP_POST:
170
      raise http.HttpBadRequest("Only the POST method is supported")
171

    
172
    path = req.request_path
173
    if path.startswith("/"):
174
      path = path[1:]
175

    
176
    method = getattr(self, "perspective_%s" % path, None)
177
    if method is None:
178
      raise http.HttpNotFound()
179

    
180
    try:
181
      result = (True, method(serializer.LoadJson(req.request_body)))
182

    
183
    except backend.RPCFail, err:
184
      # our custom failure exception; str(err) works fine if the
185
      # exception was constructed with a single argument, and in
186
      # this case, err.message == err.args[0] == str(err)
187
      result = (False, str(err))
188
    except errors.QuitGanetiException, err:
189
      # Tell parent to quit
190
      logging.info("Shutting down the node daemon, arguments: %s",
191
                   str(err.args))
192
      os.kill(self.noded_pid, signal.SIGTERM)
193
      # And return the error's arguments, which must be already in
194
      # correct tuple format
195
      result = err.args
196
    except Exception, err:
197
      logging.exception("Error in RPC call")
198
      result = (False, "Error while executing backend function: %s" % str(err))
199

    
200
    return serializer.DumpJson(result)
201

    
202
  # the new block devices  --------------------------
203

    
204
  @staticmethod
205
  def perspective_blockdev_create(params):
206
    """Create a block device.
207

208
    """
209
    (bdev_s, size, owner, on_primary, info, excl_stor) = params
210
    bdev = objects.Disk.FromDict(bdev_s)
211
    if bdev is None:
212
      raise ValueError("can't unserialize data!")
213
    return backend.BlockdevCreate(bdev, size, owner, on_primary, info,
214
                                  excl_stor)
215

    
216
  @staticmethod
217
  def perspective_blockdev_pause_resume_sync(params):
218
    """Pause/resume sync of a block device.
219

220
    """
221
    disks_s, pause = params
222
    disks = [objects.Disk.FromDict(bdev_s) for bdev_s in disks_s]
223
    return backend.BlockdevPauseResumeSync(disks, pause)
224

    
225
  @staticmethod
226
  def perspective_blockdev_wipe(params):
227
    """Wipe a block device.
228

229
    """
230
    bdev_s, offset, size = params
231
    bdev = objects.Disk.FromDict(bdev_s)
232
    return backend.BlockdevWipe(bdev, offset, size)
233

    
234
  @staticmethod
235
  def perspective_blockdev_remove(params):
236
    """Remove a block device.
237

238
    """
239
    bdev_s = params[0]
240
    bdev = objects.Disk.FromDict(bdev_s)
241
    return backend.BlockdevRemove(bdev)
242

    
243
  @staticmethod
244
  def perspective_blockdev_rename(params):
245
    """Remove a block device.
246

247
    """
248
    devlist = [(objects.Disk.FromDict(ds), uid) for ds, uid in params[0]]
249
    return backend.BlockdevRename(devlist)
250

    
251
  @staticmethod
252
  def perspective_blockdev_assemble(params):
253
    """Assemble a block device.
254

255
    """
256
    bdev_s, owner, on_primary, idx = params
257
    bdev = objects.Disk.FromDict(bdev_s)
258
    if bdev is None:
259
      raise ValueError("can't unserialize data!")
260
    return backend.BlockdevAssemble(bdev, owner, on_primary, idx)
261

    
262
  @staticmethod
263
  def perspective_blockdev_shutdown(params):
264
    """Shutdown a block device.
265

266
    """
267
    bdev_s = params[0]
268
    bdev = objects.Disk.FromDict(bdev_s)
269
    if bdev is None:
270
      raise ValueError("can't unserialize data!")
271
    return backend.BlockdevShutdown(bdev)
272

    
273
  @staticmethod
274
  def perspective_blockdev_addchildren(params):
275
    """Add a child to a mirror device.
276

277
    Note: this is only valid for mirror devices. It's the caller's duty
278
    to send a correct disk, otherwise we raise an error.
279

280
    """
281
    bdev_s, ndev_s = params
282
    bdev = objects.Disk.FromDict(bdev_s)
283
    ndevs = [objects.Disk.FromDict(disk_s) for disk_s in ndev_s]
284
    if bdev is None or ndevs.count(None) > 0:
285
      raise ValueError("can't unserialize data!")
286
    return backend.BlockdevAddchildren(bdev, ndevs)
287

    
288
  @staticmethod
289
  def perspective_blockdev_removechildren(params):
290
    """Remove a child from a mirror device.
291

292
    This is only valid for mirror devices, of course. It's the callers
293
    duty to send a correct disk, otherwise we raise an error.
294

295
    """
296
    bdev_s, ndev_s = params
297
    bdev = objects.Disk.FromDict(bdev_s)
298
    ndevs = [objects.Disk.FromDict(disk_s) for disk_s in ndev_s]
299
    if bdev is None or ndevs.count(None) > 0:
300
      raise ValueError("can't unserialize data!")
301
    return backend.BlockdevRemovechildren(bdev, ndevs)
302

    
303
  @staticmethod
304
  def perspective_blockdev_getmirrorstatus(params):
305
    """Return the mirror status for a list of disks.
306

307
    """
308
    disks = [objects.Disk.FromDict(dsk_s)
309
             for dsk_s in params[0]]
310
    return [status.ToDict()
311
            for status in backend.BlockdevGetmirrorstatus(disks)]
312

    
313
  @staticmethod
314
  def perspective_blockdev_getmirrorstatus_multi(params):
315
    """Return the mirror status for a list of disks.
316

317
    """
318
    (node_disks, ) = params
319

    
320
    disks = [objects.Disk.FromDict(dsk_s) for dsk_s in node_disks]
321

    
322
    result = []
323

    
324
    for (success, status) in backend.BlockdevGetmirrorstatusMulti(disks):
325
      if success:
326
        result.append((success, status.ToDict()))
327
      else:
328
        result.append((success, status))
329

    
330
    return result
331

    
332
  @staticmethod
333
  def perspective_blockdev_find(params):
334
    """Expose the FindBlockDevice functionality for a disk.
335

336
    This will try to find but not activate a disk.
337

338
    """
339
    disk = objects.Disk.FromDict(params[0])
340

    
341
    result = backend.BlockdevFind(disk)
342
    if result is None:
343
      return None
344

    
345
    return result.ToDict()
346

    
347
  @staticmethod
348
  def perspective_blockdev_snapshot(params):
349
    """Create a snapshot device.
350

351
    Note that this is only valid for LVM disks, if we get passed
352
    something else we raise an exception. The snapshot device can be
353
    remove by calling the generic block device remove call.
354

355
    """
356
    (disk, snapshot_name) = params
357
    cfbd = objects.Disk.FromDict(disk)
358
    return backend.BlockdevSnapshot(cfbd, snapshot_name)
359

    
360
  @staticmethod
361
  def perspective_blockdev_grow(params):
362
    """Grow a stack of devices.
363

364
    """
365
    if len(params) < 4:
366
      raise ValueError("Received only 3 parameters in blockdev_grow,"
367
                       " old master?")
368
    cfbd = objects.Disk.FromDict(params[0])
369
    amount = params[1]
370
    dryrun = params[2]
371
    backingstore = params[3]
372
    return backend.BlockdevGrow(cfbd, amount, dryrun, backingstore)
373

    
374
  @staticmethod
375
  def perspective_blockdev_close(params):
376
    """Closes the given block devices.
377

378
    """
379
    disks = [objects.Disk.FromDict(cf) for cf in params[1]]
380
    return backend.BlockdevClose(params[0], disks)
381

    
382
  @staticmethod
383
  def perspective_blockdev_getsize(params):
384
    """Compute the sizes of the given block devices.
385

386
    """
387
    disks = [objects.Disk.FromDict(cf) for cf in params[0]]
388
    return backend.BlockdevGetsize(disks)
389

    
390
  @staticmethod
391
  def perspective_blockdev_export(params):
392
    """Compute the sizes of the given block devices.
393

394
    """
395
    disk = objects.Disk.FromDict(params[0])
396
    dest_node, dest_path, cluster_name = params[1:]
397
    return backend.BlockdevExport(disk, dest_node, dest_path, cluster_name)
398

    
399
  @staticmethod
400
  def perspective_blockdev_setinfo(params):
401
    """Sets metadata information on the given block device.
402

403
    """
404
    (disk, info) = params
405
    disk = objects.Disk.FromDict(disk)
406
    return backend.BlockdevSetInfo(disk, info)
407

    
408
  # blockdev/drbd specific methods ----------
409

    
410
  @staticmethod
411
  def perspective_drbd_disconnect_net(params):
412
    """Disconnects the network connection of drbd disks.
413

414
    Note that this is only valid for drbd disks, so the members of the
415
    disk list must all be drbd devices.
416

417
    """
418
    nodes_ip, disks = params
419
    disks = [objects.Disk.FromDict(cf) for cf in disks]
420
    return backend.DrbdDisconnectNet(nodes_ip, disks)
421

    
422
  @staticmethod
423
  def perspective_drbd_attach_net(params):
424
    """Attaches the network connection of drbd disks.
425

426
    Note that this is only valid for drbd disks, so the members of the
427
    disk list must all be drbd devices.
428

429
    """
430
    nodes_ip, disks, instance_name, multimaster = params
431
    disks = [objects.Disk.FromDict(cf) for cf in disks]
432
    return backend.DrbdAttachNet(nodes_ip, disks,
433
                                     instance_name, multimaster)
434

    
435
  @staticmethod
436
  def perspective_drbd_wait_sync(params):
437
    """Wait until DRBD disks are synched.
438

439
    Note that this is only valid for drbd disks, so the members of the
440
    disk list must all be drbd devices.
441

442
    """
443
    nodes_ip, disks = params
444
    disks = [objects.Disk.FromDict(cf) for cf in disks]
445
    return backend.DrbdWaitSync(nodes_ip, disks)
446

    
447
  @staticmethod
448
  def perspective_drbd_helper(params):
449
    """Query drbd helper.
450

451
    """
452
    return backend.GetDrbdUsermodeHelper()
453

    
454
  # export/import  --------------------------
455

    
456
  @staticmethod
457
  def perspective_finalize_export(params):
458
    """Expose the finalize export functionality.
459

460
    """
461
    instance = objects.Instance.FromDict(params[0])
462

    
463
    snap_disks = []
464
    for disk in params[1]:
465
      if isinstance(disk, bool):
466
        snap_disks.append(disk)
467
      else:
468
        snap_disks.append(objects.Disk.FromDict(disk))
469

    
470
    return backend.FinalizeExport(instance, snap_disks)
471

    
472
  @staticmethod
473
  def perspective_export_info(params):
474
    """Query information about an existing export on this node.
475

476
    The given path may not contain an export, in which case we return
477
    None.
478

479
    """
480
    path = params[0]
481
    return backend.ExportInfo(path)
482

    
483
  @staticmethod
484
  def perspective_export_list(params):
485
    """List the available exports on this node.
486

487
    Note that as opposed to export_info, which may query data about an
488
    export in any path, this only queries the standard Ganeti path
489
    (pathutils.EXPORT_DIR).
490

491
    """
492
    return backend.ListExports()
493

    
494
  @staticmethod
495
  def perspective_export_remove(params):
496
    """Remove an export.
497

498
    """
499
    export = params[0]
500
    return backend.RemoveExport(export)
501

    
502
  # block device ---------------------
503
  @staticmethod
504
  def perspective_bdev_sizes(params):
505
    """Query the list of block devices
506

507
    """
508
    devices = params[0]
509
    return backend.GetBlockDevSizes(devices)
510

    
511
  # volume  --------------------------
512

    
513
  @staticmethod
514
  def perspective_lv_list(params):
515
    """Query the list of logical volumes in a given volume group.
516

517
    """
518
    vgname = params[0]
519
    return backend.GetVolumeList(vgname)
520

    
521
  @staticmethod
522
  def perspective_vg_list(params):
523
    """Query the list of volume groups.
524

525
    """
526
    return backend.ListVolumeGroups()
527

    
528
  # Storage --------------------------
529

    
530
  @staticmethod
531
  def perspective_storage_list(params):
532
    """Get list of storage units.
533

534
    """
535
    (su_name, su_args, name, fields) = params
536
    return storage.GetStorage(su_name, *su_args).List(name, fields)
537

    
538
  @staticmethod
539
  def perspective_storage_modify(params):
540
    """Modify a storage unit.
541

542
    """
543
    (su_name, su_args, name, changes) = params
544
    return storage.GetStorage(su_name, *su_args).Modify(name, changes)
545

    
546
  @staticmethod
547
  def perspective_storage_execute(params):
548
    """Execute an operation on a storage unit.
549

550
    """
551
    (su_name, su_args, name, op) = params
552
    return storage.GetStorage(su_name, *su_args).Execute(name, op)
553

    
554
  # bridge  --------------------------
555

    
556
  @staticmethod
557
  def perspective_bridges_exist(params):
558
    """Check if all bridges given exist on this node.
559

560
    """
561
    bridges_list = params[0]
562
    return backend.BridgesExist(bridges_list)
563

    
564
  # instance  --------------------------
565

    
566
  @staticmethod
567
  def perspective_instance_os_add(params):
568
    """Install an OS on a given instance.
569

570
    """
571
    inst_s = params[0]
572
    inst = objects.Instance.FromDict(inst_s)
573
    reinstall = params[1]
574
    debug = params[2]
575
    return backend.InstanceOsAdd(inst, reinstall, debug)
576

    
577
  @staticmethod
578
  def perspective_instance_run_rename(params):
579
    """Runs the OS rename script for an instance.
580

581
    """
582
    inst_s, old_name, debug = params
583
    inst = objects.Instance.FromDict(inst_s)
584
    return backend.RunRenameInstance(inst, old_name, debug)
585

    
586
  @staticmethod
587
  def perspective_instance_shutdown(params):
588
    """Shutdown an instance.
589

590
    """
591
    instance = objects.Instance.FromDict(params[0])
592
    timeout = params[1]
593
    trail = params[2]
594
    _extendReasonTrail(trail, "shutdown")
595
    return backend.InstanceShutdown(instance, timeout, trail)
596

    
597
  @staticmethod
598
  def perspective_instance_start(params):
599
    """Start an instance.
600

601
    """
602
    (instance_name, startup_paused, trail) = params
603
    instance = objects.Instance.FromDict(instance_name)
604
    _extendReasonTrail(trail, "start")
605
    return backend.StartInstance(instance, startup_paused, trail)
606

    
607
  @staticmethod
608
  def perspective_hotplug_device(params):
609
    """Hotplugs device to a running instance.
610

611
    """
612
    (idict, action, dev_type, ddict, extra, seq) = params
613
    instance = objects.Instance.FromDict(idict)
614
    if dev_type == constants.HOTPLUG_TARGET_DISK:
615
      device = objects.Disk.FromDict(ddict)
616
    elif dev_type == constants.HOTPLUG_TARGET_NIC:
617
      device = objects.NIC.FromDict(ddict)
618
    else:
619
      assert dev_type in constants.HOTPLUG_ALL_TARGETS
620
    return backend.HotplugDevice(instance, action, dev_type, device, extra, seq)
621

    
622
  @staticmethod
623
  def perspective_migration_info(params):
624
    """Gather information about an instance to be migrated.
625

626
    """
627
    instance = objects.Instance.FromDict(params[0])
628
    return backend.MigrationInfo(instance)
629

    
630
  @staticmethod
631
  def perspective_accept_instance(params):
632
    """Prepare the node to accept an instance.
633

634
    """
635
    instance, info, target = params
636
    instance = objects.Instance.FromDict(instance)
637
    return backend.AcceptInstance(instance, info, target)
638

    
639
  @staticmethod
640
  def perspective_instance_finalize_migration_dst(params):
641
    """Finalize the instance migration on the destination node.
642

643
    """
644
    instance, info, success = params
645
    instance = objects.Instance.FromDict(instance)
646
    return backend.FinalizeMigrationDst(instance, info, success)
647

    
648
  @staticmethod
649
  def perspective_instance_migrate(params):
650
    """Migrates an instance.
651

652
    """
653
    instance, target, live = params
654
    instance = objects.Instance.FromDict(instance)
655
    return backend.MigrateInstance(instance, target, live)
656

    
657
  @staticmethod
658
  def perspective_instance_finalize_migration_src(params):
659
    """Finalize the instance migration on the source node.
660

661
    """
662
    instance, success, live = params
663
    instance = objects.Instance.FromDict(instance)
664
    return backend.FinalizeMigrationSource(instance, success, live)
665

    
666
  @staticmethod
667
  def perspective_instance_get_migration_status(params):
668
    """Reports migration status.
669

670
    """
671
    instance = objects.Instance.FromDict(params[0])
672
    return backend.GetMigrationStatus(instance).ToDict()
673

    
674
  @staticmethod
675
  def perspective_instance_reboot(params):
676
    """Reboot an instance.
677

678
    """
679
    instance = objects.Instance.FromDict(params[0])
680
    reboot_type = params[1]
681
    shutdown_timeout = params[2]
682
    trail = params[3]
683
    _extendReasonTrail(trail, "reboot")
684
    return backend.InstanceReboot(instance, reboot_type, shutdown_timeout,
685
                                  trail)
686

    
687
  @staticmethod
688
  def perspective_instance_balloon_memory(params):
689
    """Modify instance runtime memory.
690

691
    """
692
    instance_dict, memory = params
693
    instance = objects.Instance.FromDict(instance_dict)
694
    return backend.InstanceBalloonMemory(instance, memory)
695

    
696
  @staticmethod
697
  def perspective_instance_info(params):
698
    """Query instance information.
699

700
    """
701
    return backend.GetInstanceInfo(params[0], params[1])
702

    
703
  @staticmethod
704
  def perspective_instance_migratable(params):
705
    """Query whether the specified instance can be migrated.
706

707
    """
708
    instance = objects.Instance.FromDict(params[0])
709
    return backend.GetInstanceMigratable(instance)
710

    
711
  @staticmethod
712
  def perspective_all_instances_info(params):
713
    """Query information about all instances.
714

715
    """
716
    return backend.GetAllInstancesInfo(params[0])
717

    
718
  @staticmethod
719
  def perspective_instance_list(params):
720
    """Query the list of running instances.
721

722
    """
723
    return backend.GetInstanceList(params[0])
724

    
725
  # node --------------------------
726

    
727
  @staticmethod
728
  def perspective_node_has_ip_address(params):
729
    """Checks if a node has the given ip address.
730

731
    """
732
    return netutils.IPAddress.Own(params[0])
733

    
734
  @staticmethod
735
  def perspective_node_info(params):
736
    """Query node information.
737

738
    """
739
    (vg_names, hv_names, excl_stor) = params
740
    return backend.GetNodeInfo(vg_names, hv_names, excl_stor)
741

    
742
  @staticmethod
743
  def perspective_etc_hosts_modify(params):
744
    """Modify a node entry in /etc/hosts.
745

746
    """
747
    backend.EtcHostsModify(params[0], params[1], params[2])
748

    
749
    return True
750

    
751
  @staticmethod
752
  def perspective_node_verify(params):
753
    """Run a verify sequence on this node.
754

755
    """
756
    return backend.VerifyNode(params[0], params[1])
757

    
758
  @classmethod
759
  def perspective_node_verify_light(cls, params):
760
    """Run a light verify sequence on this node.
761

762
    """
763
    # So far it's the same as the normal node_verify
764
    return cls.perspective_node_verify(params)
765

    
766
  @staticmethod
767
  def perspective_node_start_master_daemons(params):
768
    """Start the master daemons on this node.
769

770
    """
771
    return backend.StartMasterDaemons(params[0])
772

    
773
  @staticmethod
774
  def perspective_node_activate_master_ip(params):
775
    """Activate the master IP on this node.
776

777
    """
778
    master_params = objects.MasterNetworkParameters.FromDict(params[0])
779
    return backend.ActivateMasterIp(master_params, params[1])
780

    
781
  @staticmethod
782
  def perspective_node_deactivate_master_ip(params):
783
    """Deactivate the master IP on this node.
784

785
    """
786
    master_params = objects.MasterNetworkParameters.FromDict(params[0])
787
    return backend.DeactivateMasterIp(master_params, params[1])
788

    
789
  @staticmethod
790
  def perspective_node_stop_master(params):
791
    """Stops master daemons on this node.
792

793
    """
794
    return backend.StopMasterDaemons()
795

    
796
  @staticmethod
797
  def perspective_node_change_master_netmask(params):
798
    """Change the master IP netmask.
799

800
    """
801
    return backend.ChangeMasterNetmask(params[0], params[1], params[2],
802
                                       params[3])
803

    
804
  @staticmethod
805
  def perspective_node_leave_cluster(params):
806
    """Cleanup after leaving a cluster.
807

808
    """
809
    return backend.LeaveCluster(params[0])
810

    
811
  @staticmethod
812
  def perspective_node_volumes(params):
813
    """Query the list of all logical volume groups.
814

815
    """
816
    return backend.NodeVolumes()
817

    
818
  @staticmethod
819
  def perspective_node_demote_from_mc(params):
820
    """Demote a node from the master candidate role.
821

822
    """
823
    return backend.DemoteFromMC()
824

    
825
  @staticmethod
826
  def perspective_node_powercycle(params):
827
    """Tries to powercycle the nod.
828

829
    """
830
    hypervisor_type = params[0]
831
    return backend.PowercycleNode(hypervisor_type)
832

    
833
  # cluster --------------------------
834

    
835
  @staticmethod
836
  def perspective_version(params):
837
    """Query version information.
838

839
    """
840
    return constants.PROTOCOL_VERSION
841

    
842
  @staticmethod
843
  def perspective_upload_file(params):
844
    """Upload a file.
845

846
    Note that the backend implementation imposes strict rules on which
847
    files are accepted.
848

849
    """
850
    return backend.UploadFile(*(params[0]))
851

    
852
  @staticmethod
853
  def perspective_master_info(params):
854
    """Query master information.
855

856
    """
857
    return backend.GetMasterInfo()
858

    
859
  @staticmethod
860
  def perspective_run_oob(params):
861
    """Runs oob on node.
862

863
    """
864
    output = backend.RunOob(params[0], params[1], params[2], params[3])
865
    if output:
866
      result = serializer.LoadJson(output)
867
    else:
868
      result = None
869
    return result
870

    
871
  @staticmethod
872
  def perspective_restricted_command(params):
873
    """Runs a restricted command.
874

875
    """
876
    (cmd, ) = params
877

    
878
    return backend.RunRestrictedCmd(cmd)
879

    
880
  @staticmethod
881
  def perspective_write_ssconf_files(params):
882
    """Write ssconf files.
883

884
    """
885
    (values,) = params
886
    return ssconf.WriteSsconfFiles(values)
887

    
888
  @staticmethod
889
  def perspective_get_watcher_pause(params):
890
    """Get watcher pause end.
891

892
    """
893
    return utils.ReadWatcherPauseFile(pathutils.WATCHER_PAUSEFILE)
894

    
895
  @staticmethod
896
  def perspective_set_watcher_pause(params):
897
    """Set watcher pause.
898

899
    """
900
    (until, ) = params
901
    return backend.SetWatcherPause(until)
902

    
903
  # os -----------------------
904

    
905
  @staticmethod
906
  def perspective_os_diagnose(params):
907
    """Query detailed information about existing OSes.
908

909
    """
910
    return backend.DiagnoseOS()
911

    
912
  @staticmethod
913
  def perspective_os_get(params):
914
    """Query information about a given OS.
915

916
    """
917
    name = params[0]
918
    os_obj = backend.OSFromDisk(name)
919
    return os_obj.ToDict()
920

    
921
  @staticmethod
922
  def perspective_os_validate(params):
923
    """Run a given OS' validation routine.
924

925
    """
926
    required, name, checks, params = params
927
    return backend.ValidateOS(required, name, checks, params)
928

    
929
  # extstorage -----------------------
930

    
931
  @staticmethod
932
  def perspective_extstorage_diagnose(params):
933
    """Query detailed information about existing extstorage providers.
934

935
    """
936
    return backend.DiagnoseExtStorage()
937

    
938
  # hooks -----------------------
939

    
940
  @staticmethod
941
  def perspective_hooks_runner(params):
942
    """Run hook scripts.
943

944
    """
945
    hpath, phase, env = params
946
    hr = backend.HooksRunner()
947
    return hr.RunHooks(hpath, phase, env)
948

    
949
  # iallocator -----------------
950

    
951
  @staticmethod
952
  def perspective_iallocator_runner(params):
953
    """Run an iallocator script.
954

955
    """
956
    name, idata = params
957
    iar = backend.IAllocatorRunner()
958
    return iar.Run(name, idata)
959

    
960
  # test -----------------------
961

    
962
  @staticmethod
963
  def perspective_test_delay(params):
964
    """Run test delay.
965

966
    """
967
    duration = params[0]
968
    status, rval = utils.TestDelay(duration)
969
    if not status:
970
      raise backend.RPCFail(rval)
971
    return rval
972

    
973
  # file storage ---------------
974

    
975
  @staticmethod
976
  def perspective_file_storage_dir_create(params):
977
    """Create the file storage directory.
978

979
    """
980
    file_storage_dir = params[0]
981
    return backend.CreateFileStorageDir(file_storage_dir)
982

    
983
  @staticmethod
984
  def perspective_file_storage_dir_remove(params):
985
    """Remove the file storage directory.
986

987
    """
988
    file_storage_dir = params[0]
989
    return backend.RemoveFileStorageDir(file_storage_dir)
990

    
991
  @staticmethod
992
  def perspective_file_storage_dir_rename(params):
993
    """Rename the file storage directory.
994

995
    """
996
    old_file_storage_dir = params[0]
997
    new_file_storage_dir = params[1]
998
    return backend.RenameFileStorageDir(old_file_storage_dir,
999
                                        new_file_storage_dir)
1000

    
1001
  # jobs ------------------------
1002

    
1003
  @staticmethod
1004
  @_RequireJobQueueLock
1005
  def perspective_jobqueue_update(params):
1006
    """Update job queue.
1007

1008
    """
1009
    (file_name, content) = params
1010
    return backend.JobQueueUpdate(file_name, content)
1011

    
1012
  @staticmethod
1013
  @_RequireJobQueueLock
1014
  def perspective_jobqueue_purge(params):
1015
    """Purge job queue.
1016

1017
    """
1018
    return backend.JobQueuePurge()
1019

    
1020
  @staticmethod
1021
  @_RequireJobQueueLock
1022
  def perspective_jobqueue_rename(params):
1023
    """Rename a job queue file.
1024

1025
    """
1026
    # TODO: What if a file fails to rename?
1027
    return [backend.JobQueueRename(old, new) for old, new in params[0]]
1028

    
1029
  @staticmethod
1030
  @_RequireJobQueueLock
1031
  def perspective_jobqueue_set_drain_flag(params):
1032
    """Set job queue's drain flag.
1033

1034
    """
1035
    (flag, ) = params
1036

    
1037
    return jstore.SetDrainFlag(flag)
1038

    
1039
  # hypervisor ---------------
1040

    
1041
  @staticmethod
1042
  def perspective_hypervisor_validate_params(params):
1043
    """Validate the hypervisor parameters.
1044

1045
    """
1046
    (hvname, hvparams) = params
1047
    return backend.ValidateHVParams(hvname, hvparams)
1048

    
1049
  # Crypto
1050

    
1051
  @staticmethod
1052
  def perspective_x509_cert_create(params):
1053
    """Creates a new X509 certificate for SSL/TLS.
1054

1055
    """
1056
    (validity, ) = params
1057
    return backend.CreateX509Certificate(validity)
1058

    
1059
  @staticmethod
1060
  def perspective_x509_cert_remove(params):
1061
    """Removes a X509 certificate.
1062

1063
    """
1064
    (name, ) = params
1065
    return backend.RemoveX509Certificate(name)
1066

    
1067
  # Import and export
1068

    
1069
  @staticmethod
1070
  def perspective_import_start(params):
1071
    """Starts an import daemon.
1072

1073
    """
1074
    (opts_s, instance, component, (dest, dest_args)) = params
1075

    
1076
    opts = objects.ImportExportOptions.FromDict(opts_s)
1077

    
1078
    return backend.StartImportExportDaemon(constants.IEM_IMPORT, opts,
1079
                                           None, None,
1080
                                           objects.Instance.FromDict(instance),
1081
                                           component, dest,
1082
                                           _DecodeImportExportIO(dest,
1083
                                                                 dest_args))
1084

    
1085
  @staticmethod
1086
  def perspective_export_start(params):
1087
    """Starts an export daemon.
1088

1089
    """
1090
    (opts_s, host, port, instance, component, (source, source_args)) = params
1091

    
1092
    opts = objects.ImportExportOptions.FromDict(opts_s)
1093

    
1094
    return backend.StartImportExportDaemon(constants.IEM_EXPORT, opts,
1095
                                           host, port,
1096
                                           objects.Instance.FromDict(instance),
1097
                                           component, source,
1098
                                           _DecodeImportExportIO(source,
1099
                                                                 source_args))
1100

    
1101
  @staticmethod
1102
  def perspective_impexp_status(params):
1103
    """Retrieves the status of an import or export daemon.
1104

1105
    """
1106
    return backend.GetImportExportStatus(params[0])
1107

    
1108
  @staticmethod
1109
  def perspective_impexp_abort(params):
1110
    """Aborts an import or export.
1111

1112
    """
1113
    return backend.AbortImportExport(params[0])
1114

    
1115
  @staticmethod
1116
  def perspective_impexp_cleanup(params):
1117
    """Cleans up after an import or export.
1118

1119
    """
1120
    return backend.CleanupImportExport(params[0])
1121

    
1122

    
1123
def CheckNoded(_, args):
1124
  """Initial checks whether to run or exit with a failure.
1125

1126
  """
1127
  if args: # noded doesn't take any arguments
1128
    print >> sys.stderr, ("Usage: %s [-f] [-d] [-p port] [-b ADDRESS]" %
1129
                          sys.argv[0])
1130
    sys.exit(constants.EXIT_FAILURE)
1131
  try:
1132
    codecs.lookup("string-escape")
1133
  except LookupError:
1134
    print >> sys.stderr, ("Can't load the string-escape code which is part"
1135
                          " of the Python installation. Is your installation"
1136
                          " complete/correct? Aborting.")
1137
    sys.exit(constants.EXIT_FAILURE)
1138

    
1139

    
1140
def PrepNoded(options, _):
1141
  """Preparation node daemon function, executed with the PID file held.
1142

1143
  """
1144
  if options.mlock:
1145
    request_executor_class = MlockallRequestExecutor
1146
    try:
1147
      utils.Mlockall()
1148
    except errors.NoCtypesError:
1149
      logging.warning("Cannot set memory lock, ctypes module not found")
1150
      request_executor_class = http.server.HttpServerRequestExecutor
1151
  else:
1152
    request_executor_class = http.server.HttpServerRequestExecutor
1153

    
1154
  # Read SSL certificate
1155
  if options.ssl:
1156
    ssl_params = http.HttpSslParams(ssl_key_path=options.ssl_key,
1157
                                    ssl_cert_path=options.ssl_cert)
1158
  else:
1159
    ssl_params = None
1160

    
1161
  err = _PrepareQueueLock()
1162
  if err is not None:
1163
    # this might be some kind of file-system/permission error; while
1164
    # this breaks the job queue functionality, we shouldn't prevent
1165
    # startup of the whole node daemon because of this
1166
    logging.critical("Can't init/verify the queue, proceeding anyway: %s", err)
1167

    
1168
  handler = NodeRequestHandler()
1169

    
1170
  mainloop = daemon.Mainloop()
1171
  server = \
1172
    http.server.HttpServer(mainloop, options.bind_address, options.port,
1173
                           handler, ssl_params=ssl_params, ssl_verify_peer=True,
1174
                           request_executor_class=request_executor_class)
1175
  server.Start()
1176

    
1177
  return (mainloop, server)
1178

    
1179

    
1180
def ExecNoded(options, args, prep_data): # pylint: disable=W0613
1181
  """Main node daemon function, executed with the PID file held.
1182

1183
  """
1184
  (mainloop, server) = prep_data
1185
  try:
1186
    mainloop.Run()
1187
  finally:
1188
    server.Stop()
1189

    
1190

    
1191
def Main():
1192
  """Main function for the node daemon.
1193

1194
  """
1195
  parser = OptionParser(description="Ganeti node daemon",
1196
                        usage="%prog [-f] [-d] [-p port] [-b ADDRESS]",
1197
                        version="%%prog (ganeti) %s" %
1198
                        constants.RELEASE_VERSION)
1199
  parser.add_option("--no-mlock", dest="mlock",
1200
                    help="Do not mlock the node memory in ram",
1201
                    default=True, action="store_false")
1202

    
1203
  daemon.GenericMain(constants.NODED, parser, CheckNoded, PrepNoded, ExecNoded,
1204
                     default_ssl_cert=pathutils.NODED_CERT_FILE,
1205
                     default_ssl_key=pathutils.NODED_CERT_FILE,
1206
                     console_logging=True)