Statistics
| Branch: | Tag: | Revision:

root / lib / server / noded.py @ 1f350e0f

History | View | Annotate | Download (31.5 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
    cfbd = objects.Disk.FromDict(params[0])
357
    return backend.BlockdevSnapshot(cfbd)
358

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
453
  # export/import  --------------------------
454

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

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

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

    
469
    return backend.FinalizeExport(instance, snap_disks)
470

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

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

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

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

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

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

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

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

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

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

    
510
  # volume  --------------------------
511

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

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

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

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

    
527
  # Storage --------------------------
528

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

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

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

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

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

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

    
553
  # bridge  --------------------------
554

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

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

    
563
  # instance  --------------------------
564

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

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

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

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

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

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

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

600
    """
601
    (instance_name, startup_paused) = params
602
    instance = objects.Instance.FromDict(instance_name)
603
    return backend.StartInstance(instance, startup_paused)
604

    
605
  @staticmethod
606
  def perspective_migration_info(params):
607
    """Gather information about an instance to be migrated.
608

609
    """
610
    instance = objects.Instance.FromDict(params[0])
611
    return backend.MigrationInfo(instance)
612

    
613
  @staticmethod
614
  def perspective_accept_instance(params):
615
    """Prepare the node to accept an instance.
616

617
    """
618
    instance, info, target = params
619
    instance = objects.Instance.FromDict(instance)
620
    return backend.AcceptInstance(instance, info, target)
621

    
622
  @staticmethod
623
  def perspective_instance_finalize_migration_dst(params):
624
    """Finalize the instance migration on the destination node.
625

626
    """
627
    instance, info, success = params
628
    instance = objects.Instance.FromDict(instance)
629
    return backend.FinalizeMigrationDst(instance, info, success)
630

    
631
  @staticmethod
632
  def perspective_instance_migrate(params):
633
    """Migrates an instance.
634

635
    """
636
    instance, target, live = params
637
    instance = objects.Instance.FromDict(instance)
638
    return backend.MigrateInstance(instance, target, live)
639

    
640
  @staticmethod
641
  def perspective_instance_finalize_migration_src(params):
642
    """Finalize the instance migration on the source node.
643

644
    """
645
    instance, success, live = params
646
    instance = objects.Instance.FromDict(instance)
647
    return backend.FinalizeMigrationSource(instance, success, live)
648

    
649
  @staticmethod
650
  def perspective_instance_get_migration_status(params):
651
    """Reports migration status.
652

653
    """
654
    instance = objects.Instance.FromDict(params[0])
655
    return backend.GetMigrationStatus(instance).ToDict()
656

    
657
  @staticmethod
658
  def perspective_instance_reboot(params):
659
    """Reboot an instance.
660

661
    """
662
    instance = objects.Instance.FromDict(params[0])
663
    reboot_type = params[1]
664
    shutdown_timeout = params[2]
665
    trail = params[3]
666
    _extendReasonTrail(trail, "reboot")
667
    return backend.InstanceReboot(instance, reboot_type, shutdown_timeout,
668
                                  trail)
669

    
670
  @staticmethod
671
  def perspective_instance_balloon_memory(params):
672
    """Modify instance runtime memory.
673

674
    """
675
    instance_dict, memory = params
676
    instance = objects.Instance.FromDict(instance_dict)
677
    return backend.InstanceBalloonMemory(instance, memory)
678

    
679
  @staticmethod
680
  def perspective_instance_info(params):
681
    """Query instance information.
682

683
    """
684
    return backend.GetInstanceInfo(params[0], params[1])
685

    
686
  @staticmethod
687
  def perspective_instance_migratable(params):
688
    """Query whether the specified instance can be migrated.
689

690
    """
691
    instance = objects.Instance.FromDict(params[0])
692
    return backend.GetInstanceMigratable(instance)
693

    
694
  @staticmethod
695
  def perspective_all_instances_info(params):
696
    """Query information about all instances.
697

698
    """
699
    return backend.GetAllInstancesInfo(params[0])
700

    
701
  @staticmethod
702
  def perspective_instance_list(params):
703
    """Query the list of running instances.
704

705
    """
706
    return backend.GetInstanceList(params[0])
707

    
708
  # node --------------------------
709

    
710
  @staticmethod
711
  def perspective_node_has_ip_address(params):
712
    """Checks if a node has the given ip address.
713

714
    """
715
    return netutils.IPAddress.Own(params[0])
716

    
717
  @staticmethod
718
  def perspective_node_info(params):
719
    """Query node information.
720

721
    """
722
    (vg_names, hv_names, excl_stor) = params
723
    return backend.GetNodeInfo(vg_names, hv_names, excl_stor)
724

    
725
  @staticmethod
726
  def perspective_etc_hosts_modify(params):
727
    """Modify a node entry in /etc/hosts.
728

729
    """
730
    backend.EtcHostsModify(params[0], params[1], params[2])
731

    
732
    return True
733

    
734
  @staticmethod
735
  def perspective_node_verify(params):
736
    """Run a verify sequence on this node.
737

738
    """
739
    return backend.VerifyNode(params[0], params[1])
740

    
741
  @classmethod
742
  def perspective_node_verify_light(cls, params):
743
    """Run a light verify sequence on this node.
744

745
    """
746
    # So far it's the same as the normal node_verify
747
    return cls.perspective_node_verify(params)
748

    
749
  @staticmethod
750
  def perspective_node_start_master_daemons(params):
751
    """Start the master daemons on this node.
752

753
    """
754
    return backend.StartMasterDaemons(params[0])
755

    
756
  @staticmethod
757
  def perspective_node_activate_master_ip(params):
758
    """Activate the master IP on this node.
759

760
    """
761
    master_params = objects.MasterNetworkParameters.FromDict(params[0])
762
    return backend.ActivateMasterIp(master_params, params[1])
763

    
764
  @staticmethod
765
  def perspective_node_deactivate_master_ip(params):
766
    """Deactivate the master IP on this node.
767

768
    """
769
    master_params = objects.MasterNetworkParameters.FromDict(params[0])
770
    return backend.DeactivateMasterIp(master_params, params[1])
771

    
772
  @staticmethod
773
  def perspective_node_stop_master(params):
774
    """Stops master daemons on this node.
775

776
    """
777
    return backend.StopMasterDaemons()
778

    
779
  @staticmethod
780
  def perspective_node_change_master_netmask(params):
781
    """Change the master IP netmask.
782

783
    """
784
    return backend.ChangeMasterNetmask(params[0], params[1], params[2],
785
                                       params[3])
786

    
787
  @staticmethod
788
  def perspective_node_leave_cluster(params):
789
    """Cleanup after leaving a cluster.
790

791
    """
792
    return backend.LeaveCluster(params[0])
793

    
794
  @staticmethod
795
  def perspective_node_volumes(params):
796
    """Query the list of all logical volume groups.
797

798
    """
799
    return backend.NodeVolumes()
800

    
801
  @staticmethod
802
  def perspective_node_demote_from_mc(params):
803
    """Demote a node from the master candidate role.
804

805
    """
806
    return backend.DemoteFromMC()
807

    
808
  @staticmethod
809
  def perspective_node_powercycle(params):
810
    """Tries to powercycle the nod.
811

812
    """
813
    hypervisor_type = params[0]
814
    return backend.PowercycleNode(hypervisor_type)
815

    
816
  # cluster --------------------------
817

    
818
  @staticmethod
819
  def perspective_version(params):
820
    """Query version information.
821

822
    """
823
    return constants.PROTOCOL_VERSION
824

    
825
  @staticmethod
826
  def perspective_upload_file(params):
827
    """Upload a file.
828

829
    Note that the backend implementation imposes strict rules on which
830
    files are accepted.
831

832
    """
833
    return backend.UploadFile(*(params[0]))
834

    
835
  @staticmethod
836
  def perspective_master_info(params):
837
    """Query master information.
838

839
    """
840
    return backend.GetMasterInfo()
841

    
842
  @staticmethod
843
  def perspective_run_oob(params):
844
    """Runs oob on node.
845

846
    """
847
    output = backend.RunOob(params[0], params[1], params[2], params[3])
848
    if output:
849
      result = serializer.LoadJson(output)
850
    else:
851
      result = None
852
    return result
853

    
854
  @staticmethod
855
  def perspective_restricted_command(params):
856
    """Runs a restricted command.
857

858
    """
859
    (cmd, ) = params
860

    
861
    return backend.RunRestrictedCmd(cmd)
862

    
863
  @staticmethod
864
  def perspective_write_ssconf_files(params):
865
    """Write ssconf files.
866

867
    """
868
    (values,) = params
869
    return ssconf.WriteSsconfFiles(values)
870

    
871
  @staticmethod
872
  def perspective_get_watcher_pause(params):
873
    """Get watcher pause end.
874

875
    """
876
    return utils.ReadWatcherPauseFile(pathutils.WATCHER_PAUSEFILE)
877

    
878
  @staticmethod
879
  def perspective_set_watcher_pause(params):
880
    """Set watcher pause.
881

882
    """
883
    (until, ) = params
884
    return backend.SetWatcherPause(until)
885

    
886
  # os -----------------------
887

    
888
  @staticmethod
889
  def perspective_os_diagnose(params):
890
    """Query detailed information about existing OSes.
891

892
    """
893
    return backend.DiagnoseOS()
894

    
895
  @staticmethod
896
  def perspective_os_get(params):
897
    """Query information about a given OS.
898

899
    """
900
    name = params[0]
901
    os_obj = backend.OSFromDisk(name)
902
    return os_obj.ToDict()
903

    
904
  @staticmethod
905
  def perspective_os_validate(params):
906
    """Run a given OS' validation routine.
907

908
    """
909
    required, name, checks, params = params
910
    return backend.ValidateOS(required, name, checks, params)
911

    
912
  # extstorage -----------------------
913

    
914
  @staticmethod
915
  def perspective_extstorage_diagnose(params):
916
    """Query detailed information about existing extstorage providers.
917

918
    """
919
    return backend.DiagnoseExtStorage()
920

    
921
  # hooks -----------------------
922

    
923
  @staticmethod
924
  def perspective_hooks_runner(params):
925
    """Run hook scripts.
926

927
    """
928
    hpath, phase, env = params
929
    hr = backend.HooksRunner()
930
    return hr.RunHooks(hpath, phase, env)
931

    
932
  # iallocator -----------------
933

    
934
  @staticmethod
935
  def perspective_iallocator_runner(params):
936
    """Run an iallocator script.
937

938
    """
939
    name, idata = params
940
    iar = backend.IAllocatorRunner()
941
    return iar.Run(name, idata)
942

    
943
  # test -----------------------
944

    
945
  @staticmethod
946
  def perspective_test_delay(params):
947
    """Run test delay.
948

949
    """
950
    duration = params[0]
951
    status, rval = utils.TestDelay(duration)
952
    if not status:
953
      raise backend.RPCFail(rval)
954
    return rval
955

    
956
  # file storage ---------------
957

    
958
  @staticmethod
959
  def perspective_file_storage_dir_create(params):
960
    """Create the file storage directory.
961

962
    """
963
    file_storage_dir = params[0]
964
    return backend.CreateFileStorageDir(file_storage_dir)
965

    
966
  @staticmethod
967
  def perspective_file_storage_dir_remove(params):
968
    """Remove the file storage directory.
969

970
    """
971
    file_storage_dir = params[0]
972
    return backend.RemoveFileStorageDir(file_storage_dir)
973

    
974
  @staticmethod
975
  def perspective_file_storage_dir_rename(params):
976
    """Rename the file storage directory.
977

978
    """
979
    old_file_storage_dir = params[0]
980
    new_file_storage_dir = params[1]
981
    return backend.RenameFileStorageDir(old_file_storage_dir,
982
                                        new_file_storage_dir)
983

    
984
  # jobs ------------------------
985

    
986
  @staticmethod
987
  @_RequireJobQueueLock
988
  def perspective_jobqueue_update(params):
989
    """Update job queue.
990

991
    """
992
    (file_name, content) = params
993
    return backend.JobQueueUpdate(file_name, content)
994

    
995
  @staticmethod
996
  @_RequireJobQueueLock
997
  def perspective_jobqueue_purge(params):
998
    """Purge job queue.
999

1000
    """
1001
    return backend.JobQueuePurge()
1002

    
1003
  @staticmethod
1004
  @_RequireJobQueueLock
1005
  def perspective_jobqueue_rename(params):
1006
    """Rename a job queue file.
1007

1008
    """
1009
    # TODO: What if a file fails to rename?
1010
    return [backend.JobQueueRename(old, new) for old, new in params[0]]
1011

    
1012
  @staticmethod
1013
  @_RequireJobQueueLock
1014
  def perspective_jobqueue_set_drain_flag(params):
1015
    """Set job queue's drain flag.
1016

1017
    """
1018
    (flag, ) = params
1019

    
1020
    return jstore.SetDrainFlag(flag)
1021

    
1022
  # hypervisor ---------------
1023

    
1024
  @staticmethod
1025
  def perspective_hypervisor_validate_params(params):
1026
    """Validate the hypervisor parameters.
1027

1028
    """
1029
    (hvname, hvparams) = params
1030
    return backend.ValidateHVParams(hvname, hvparams)
1031

    
1032
  # Crypto
1033

    
1034
  @staticmethod
1035
  def perspective_x509_cert_create(params):
1036
    """Creates a new X509 certificate for SSL/TLS.
1037

1038
    """
1039
    (validity, ) = params
1040
    return backend.CreateX509Certificate(validity)
1041

    
1042
  @staticmethod
1043
  def perspective_x509_cert_remove(params):
1044
    """Removes a X509 certificate.
1045

1046
    """
1047
    (name, ) = params
1048
    return backend.RemoveX509Certificate(name)
1049

    
1050
  # Import and export
1051

    
1052
  @staticmethod
1053
  def perspective_import_start(params):
1054
    """Starts an import daemon.
1055

1056
    """
1057
    (opts_s, instance, component, (dest, dest_args)) = params
1058

    
1059
    opts = objects.ImportExportOptions.FromDict(opts_s)
1060

    
1061
    return backend.StartImportExportDaemon(constants.IEM_IMPORT, opts,
1062
                                           None, None,
1063
                                           objects.Instance.FromDict(instance),
1064
                                           component, dest,
1065
                                           _DecodeImportExportIO(dest,
1066
                                                                 dest_args))
1067

    
1068
  @staticmethod
1069
  def perspective_export_start(params):
1070
    """Starts an export daemon.
1071

1072
    """
1073
    (opts_s, host, port, instance, component, (source, source_args)) = params
1074

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

    
1077
    return backend.StartImportExportDaemon(constants.IEM_EXPORT, opts,
1078
                                           host, port,
1079
                                           objects.Instance.FromDict(instance),
1080
                                           component, source,
1081
                                           _DecodeImportExportIO(source,
1082
                                                                 source_args))
1083

    
1084
  @staticmethod
1085
  def perspective_impexp_status(params):
1086
    """Retrieves the status of an import or export daemon.
1087

1088
    """
1089
    return backend.GetImportExportStatus(params[0])
1090

    
1091
  @staticmethod
1092
  def perspective_impexp_abort(params):
1093
    """Aborts an import or export.
1094

1095
    """
1096
    return backend.AbortImportExport(params[0])
1097

    
1098
  @staticmethod
1099
  def perspective_impexp_cleanup(params):
1100
    """Cleans up after an import or export.
1101

1102
    """
1103
    return backend.CleanupImportExport(params[0])
1104

    
1105

    
1106
def CheckNoded(_, args):
1107
  """Initial checks whether to run or exit with a failure.
1108

1109
  """
1110
  if args: # noded doesn't take any arguments
1111
    print >> sys.stderr, ("Usage: %s [-f] [-d] [-p port] [-b ADDRESS]" %
1112
                          sys.argv[0])
1113
    sys.exit(constants.EXIT_FAILURE)
1114
  try:
1115
    codecs.lookup("string-escape")
1116
  except LookupError:
1117
    print >> sys.stderr, ("Can't load the string-escape code which is part"
1118
                          " of the Python installation. Is your installation"
1119
                          " complete/correct? Aborting.")
1120
    sys.exit(constants.EXIT_FAILURE)
1121

    
1122

    
1123
def PrepNoded(options, _):
1124
  """Preparation node daemon function, executed with the PID file held.
1125

1126
  """
1127
  if options.mlock:
1128
    request_executor_class = MlockallRequestExecutor
1129
    try:
1130
      utils.Mlockall()
1131
    except errors.NoCtypesError:
1132
      logging.warning("Cannot set memory lock, ctypes module not found")
1133
      request_executor_class = http.server.HttpServerRequestExecutor
1134
  else:
1135
    request_executor_class = http.server.HttpServerRequestExecutor
1136

    
1137
  # Read SSL certificate
1138
  if options.ssl:
1139
    ssl_params = http.HttpSslParams(ssl_key_path=options.ssl_key,
1140
                                    ssl_cert_path=options.ssl_cert)
1141
  else:
1142
    ssl_params = None
1143

    
1144
  err = _PrepareQueueLock()
1145
  if err is not None:
1146
    # this might be some kind of file-system/permission error; while
1147
    # this breaks the job queue functionality, we shouldn't prevent
1148
    # startup of the whole node daemon because of this
1149
    logging.critical("Can't init/verify the queue, proceeding anyway: %s", err)
1150

    
1151
  handler = NodeRequestHandler()
1152

    
1153
  mainloop = daemon.Mainloop()
1154
  server = \
1155
    http.server.HttpServer(mainloop, options.bind_address, options.port,
1156
                           handler, ssl_params=ssl_params, ssl_verify_peer=True,
1157
                           request_executor_class=request_executor_class)
1158
  server.Start()
1159

    
1160
  return (mainloop, server)
1161

    
1162

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

1166
  """
1167
  (mainloop, server) = prep_data
1168
  try:
1169
    mainloop.Run()
1170
  finally:
1171
    server.Stop()
1172

    
1173

    
1174
def Main():
1175
  """Main function for the node daemon.
1176

1177
  """
1178
  parser = OptionParser(description="Ganeti node daemon",
1179
                        usage="%prog [-f] [-d] [-p port] [-b ADDRESS]",
1180
                        version="%%prog (ganeti) %s" %
1181
                        constants.RELEASE_VERSION)
1182
  parser.add_option("--no-mlock", dest="mlock",
1183
                    help="Do not mlock the node memory in ram",
1184
                    default=True, action="store_false")
1185

    
1186
  daemon.GenericMain(constants.NODED, parser, CheckNoded, PrepNoded, ExecNoded,
1187
                     default_ssl_cert=pathutils.NODED_CERT_FILE,
1188
                     default_ssl_key=pathutils.NODED_CERT_FILE,
1189
                     console_logging=True)