Statistics
| Branch: | Tag: | Revision:

root / lib / server / noded.py @ 24711492

History | View | Annotate | Download (33.2 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.storage import container
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) < 5:
365
      raise ValueError("Received only %s parameters in blockdev_grow,"
366
                       " old master?" % len(params))
367
    cfbd = objects.Disk.FromDict(params[0])
368
    amount = params[1]
369
    dryrun = params[2]
370
    backingstore = params[3]
371
    excl_stor = params[4]
372
    return backend.BlockdevGrow(cfbd, amount, dryrun, backingstore, excl_stor)
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_getdimensions(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.BlockdevGetdimensions(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_ip, dest_path, cluster_name = params[1:]
397
    return backend.BlockdevExport(disk, dest_node_ip, 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
    (disks,) = params
419
    disks = [objects.Disk.FromDict(disk) for disk in disks]
420
    return backend.DrbdDisconnectNet(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
    disks, instance_name, multimaster = params
431
    disks = [objects.Disk.FromDict(disk) for disk in disks]
432
    return backend.DrbdAttachNet(disks, 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
    (disks,) = params
443
    disks = [objects.Disk.FromDict(disk) for disk in disks]
444
    return backend.DrbdWaitSync(disks)
445

    
446
  @staticmethod
447
  def perspective_drbd_needs_activation(params):
448
    """Checks if the drbd devices need activation
449

450
    Note that this is only valid for drbd disks, so the members of the
451
    disk list must all be drbd devices.
452

453
    """
454
    (disks,) = params
455
    disks = [objects.Disk.FromDict(disk) for disk in disks]
456
    return backend.DrbdNeedsActivation(disks)
457

    
458
  @staticmethod
459
  def perspective_drbd_helper(_):
460
    """Query drbd helper.
461

462
    """
463
    return backend.GetDrbdUsermodeHelper()
464

    
465
  # export/import  --------------------------
466

    
467
  @staticmethod
468
  def perspective_finalize_export(params):
469
    """Expose the finalize export functionality.
470

471
    """
472
    instance = objects.Instance.FromDict(params[0])
473

    
474
    snap_disks = []
475
    for disk in params[1]:
476
      if isinstance(disk, bool):
477
        snap_disks.append(disk)
478
      else:
479
        snap_disks.append(objects.Disk.FromDict(disk))
480

    
481
    return backend.FinalizeExport(instance, snap_disks)
482

    
483
  @staticmethod
484
  def perspective_export_info(params):
485
    """Query information about an existing export on this node.
486

487
    The given path may not contain an export, in which case we return
488
    None.
489

490
    """
491
    path = params[0]
492
    return backend.ExportInfo(path)
493

    
494
  @staticmethod
495
  def perspective_export_list(params):
496
    """List the available exports on this node.
497

498
    Note that as opposed to export_info, which may query data about an
499
    export in any path, this only queries the standard Ganeti path
500
    (pathutils.EXPORT_DIR).
501

502
    """
503
    return backend.ListExports()
504

    
505
  @staticmethod
506
  def perspective_export_remove(params):
507
    """Remove an export.
508

509
    """
510
    export = params[0]
511
    return backend.RemoveExport(export)
512

    
513
  # block device ---------------------
514
  @staticmethod
515
  def perspective_bdev_sizes(params):
516
    """Query the list of block devices
517

518
    """
519
    devices = params[0]
520
    return backend.GetBlockDevSizes(devices)
521

    
522
  # volume  --------------------------
523

    
524
  @staticmethod
525
  def perspective_lv_list(params):
526
    """Query the list of logical volumes in a given volume group.
527

528
    """
529
    vgname = params[0]
530
    return backend.GetVolumeList(vgname)
531

    
532
  @staticmethod
533
  def perspective_vg_list(params):
534
    """Query the list of volume groups.
535

536
    """
537
    return backend.ListVolumeGroups()
538

    
539
  # Storage --------------------------
540

    
541
  @staticmethod
542
  def perspective_storage_list(params):
543
    """Get list of storage units.
544

545
    """
546
    (su_name, su_args, name, fields) = params
547
    return container.GetStorage(su_name, *su_args).List(name, fields)
548

    
549
  @staticmethod
550
  def perspective_storage_modify(params):
551
    """Modify a storage unit.
552

553
    """
554
    (su_name, su_args, name, changes) = params
555
    return container.GetStorage(su_name, *su_args).Modify(name, changes)
556

    
557
  @staticmethod
558
  def perspective_storage_execute(params):
559
    """Execute an operation on a storage unit.
560

561
    """
562
    (su_name, su_args, name, op) = params
563
    return container.GetStorage(su_name, *su_args).Execute(name, op)
564

    
565
  # bridge  --------------------------
566

    
567
  @staticmethod
568
  def perspective_bridges_exist(params):
569
    """Check if all bridges given exist on this node.
570

571
    """
572
    bridges_list = params[0]
573
    return backend.BridgesExist(bridges_list)
574

    
575
  # instance  --------------------------
576

    
577
  @staticmethod
578
  def perspective_instance_os_add(params):
579
    """Install an OS on a given instance.
580

581
    """
582
    inst_s = params[0]
583
    inst = objects.Instance.FromDict(inst_s)
584
    reinstall = params[1]
585
    debug = params[2]
586
    return backend.InstanceOsAdd(inst, reinstall, debug)
587

    
588
  @staticmethod
589
  def perspective_instance_run_rename(params):
590
    """Runs the OS rename script for an instance.
591

592
    """
593
    inst_s, old_name, debug = params
594
    inst = objects.Instance.FromDict(inst_s)
595
    return backend.RunRenameInstance(inst, old_name, debug)
596

    
597
  @staticmethod
598
  def perspective_instance_shutdown(params):
599
    """Shutdown an instance.
600

601
    """
602
    instance = objects.Instance.FromDict(params[0])
603
    timeout = params[1]
604
    trail = params[2]
605
    _extendReasonTrail(trail, "shutdown")
606
    return backend.InstanceShutdown(instance, timeout, trail)
607

    
608
  @staticmethod
609
  def perspective_instance_start(params):
610
    """Start an instance.
611

612
    """
613
    (instance_name, startup_paused, trail) = params
614
    instance = objects.Instance.FromDict(instance_name)
615
    _extendReasonTrail(trail, "start")
616
    return backend.StartInstance(instance, startup_paused, trail)
617

    
618
  @staticmethod
619
  def perspective_hotplug_device(params):
620
    """Hotplugs device to a running instance.
621

622
    """
623
    (idict, action, dev_type, ddict, extra, seq) = params
624
    instance = objects.Instance.FromDict(idict)
625
    if dev_type == constants.HOTPLUG_TARGET_DISK:
626
      device = objects.Disk.FromDict(ddict)
627
    elif dev_type == constants.HOTPLUG_TARGET_NIC:
628
      device = objects.NIC.FromDict(ddict)
629
    else:
630
      assert dev_type in constants.HOTPLUG_ALL_TARGETS
631
    return backend.HotplugDevice(instance, action, dev_type, device, extra, seq)
632

    
633
  @staticmethod
634
  def perspective_hotplug_supported(params):
635
    """Checks if hotplug is supported.
636

637
    """
638
    instance = objects.Instance.FromDict(params[0])
639
    return backend.HotplugSupported(instance)
640

    
641
  @staticmethod
642
  def perspective_migration_info(params):
643
    """Gather information about an instance to be migrated.
644

645
    """
646
    instance = objects.Instance.FromDict(params[0])
647
    return backend.MigrationInfo(instance)
648

    
649
  @staticmethod
650
  def perspective_accept_instance(params):
651
    """Prepare the node to accept an instance.
652

653
    """
654
    instance, info, target = params
655
    instance = objects.Instance.FromDict(instance)
656
    return backend.AcceptInstance(instance, info, target)
657

    
658
  @staticmethod
659
  def perspective_instance_finalize_migration_dst(params):
660
    """Finalize the instance migration on the destination node.
661

662
    """
663
    instance, info, success = params
664
    instance = objects.Instance.FromDict(instance)
665
    return backend.FinalizeMigrationDst(instance, info, success)
666

    
667
  @staticmethod
668
  def perspective_instance_migrate(params):
669
    """Migrates an instance.
670

671
    """
672
    cluster_name, instance, target, live = params
673
    instance = objects.Instance.FromDict(instance)
674
    return backend.MigrateInstance(cluster_name, instance, target, live)
675

    
676
  @staticmethod
677
  def perspective_instance_finalize_migration_src(params):
678
    """Finalize the instance migration on the source node.
679

680
    """
681
    instance, success, live = params
682
    instance = objects.Instance.FromDict(instance)
683
    return backend.FinalizeMigrationSource(instance, success, live)
684

    
685
  @staticmethod
686
  def perspective_instance_get_migration_status(params):
687
    """Reports migration status.
688

689
    """
690
    instance = objects.Instance.FromDict(params[0])
691
    return backend.GetMigrationStatus(instance).ToDict()
692

    
693
  @staticmethod
694
  def perspective_instance_reboot(params):
695
    """Reboot an instance.
696

697
    """
698
    instance = objects.Instance.FromDict(params[0])
699
    reboot_type = params[1]
700
    shutdown_timeout = params[2]
701
    trail = params[3]
702
    _extendReasonTrail(trail, "reboot")
703
    return backend.InstanceReboot(instance, reboot_type, shutdown_timeout,
704
                                  trail)
705

    
706
  @staticmethod
707
  def perspective_instance_balloon_memory(params):
708
    """Modify instance runtime memory.
709

710
    """
711
    instance_dict, memory = params
712
    instance = objects.Instance.FromDict(instance_dict)
713
    return backend.InstanceBalloonMemory(instance, memory)
714

    
715
  @staticmethod
716
  def perspective_instance_info(params):
717
    """Query instance information.
718

719
    """
720
    (instance_name, hypervisor_name, hvparams) = params
721
    return backend.GetInstanceInfo(instance_name, hypervisor_name, hvparams)
722

    
723
  @staticmethod
724
  def perspective_instance_migratable(params):
725
    """Query whether the specified instance can be migrated.
726

727
    """
728
    instance = objects.Instance.FromDict(params[0])
729
    return backend.GetInstanceMigratable(instance)
730

    
731
  @staticmethod
732
  def perspective_all_instances_info(params):
733
    """Query information about all instances.
734

735
    """
736
    (hypervisor_list, all_hvparams) = params
737
    return backend.GetAllInstancesInfo(hypervisor_list, all_hvparams)
738

    
739
  @staticmethod
740
  def perspective_instance_list(params):
741
    """Query the list of running instances.
742

743
    """
744
    (hypervisor_list, hvparams) = params
745
    return backend.GetInstanceList(hypervisor_list, hvparams)
746

    
747
  # node --------------------------
748

    
749
  @staticmethod
750
  def perspective_node_has_ip_address(params):
751
    """Checks if a node has the given ip address.
752

753
    """
754
    return netutils.IPAddress.Own(params[0])
755

    
756
  @staticmethod
757
  def perspective_node_info(params):
758
    """Query node information.
759

760
    """
761
    (storage_units, hv_specs) = params
762
    return backend.GetNodeInfo(storage_units, hv_specs)
763

    
764
  @staticmethod
765
  def perspective_etc_hosts_modify(params):
766
    """Modify a node entry in /etc/hosts.
767

768
    """
769
    backend.EtcHostsModify(params[0], params[1], params[2])
770

    
771
    return True
772

    
773
  @staticmethod
774
  def perspective_node_verify(params):
775
    """Run a verify sequence on this node.
776

777
    """
778
    (what, cluster_name, hvparams) = params
779
    return backend.VerifyNode(what, cluster_name, hvparams)
780

    
781
  @classmethod
782
  def perspective_node_verify_light(cls, params):
783
    """Run a light verify sequence on this node.
784

785
    """
786
    # So far it's the same as the normal node_verify
787
    return cls.perspective_node_verify(params)
788

    
789
  @staticmethod
790
  def perspective_node_start_master_daemons(params):
791
    """Start the master daemons on this node.
792

793
    """
794
    return backend.StartMasterDaemons(params[0])
795

    
796
  @staticmethod
797
  def perspective_node_activate_master_ip(params):
798
    """Activate the master IP on this node.
799

800
    """
801
    master_params = objects.MasterNetworkParameters.FromDict(params[0])
802
    return backend.ActivateMasterIp(master_params, params[1])
803

    
804
  @staticmethod
805
  def perspective_node_deactivate_master_ip(params):
806
    """Deactivate the master IP on this node.
807

808
    """
809
    master_params = objects.MasterNetworkParameters.FromDict(params[0])
810
    return backend.DeactivateMasterIp(master_params, params[1])
811

    
812
  @staticmethod
813
  def perspective_node_stop_master(params):
814
    """Stops master daemons on this node.
815

816
    """
817
    return backend.StopMasterDaemons()
818

    
819
  @staticmethod
820
  def perspective_node_change_master_netmask(params):
821
    """Change the master IP netmask.
822

823
    """
824
    return backend.ChangeMasterNetmask(params[0], params[1], params[2],
825
                                       params[3])
826

    
827
  @staticmethod
828
  def perspective_node_leave_cluster(params):
829
    """Cleanup after leaving a cluster.
830

831
    """
832
    return backend.LeaveCluster(params[0])
833

    
834
  @staticmethod
835
  def perspective_node_volumes(params):
836
    """Query the list of all logical volume groups.
837

838
    """
839
    return backend.NodeVolumes()
840

    
841
  @staticmethod
842
  def perspective_node_demote_from_mc(params):
843
    """Demote a node from the master candidate role.
844

845
    """
846
    return backend.DemoteFromMC()
847

    
848
  @staticmethod
849
  def perspective_node_powercycle(params):
850
    """Tries to powercycle the node.
851

852
    """
853
    (hypervisor_type, hvparams) = params
854
    return backend.PowercycleNode(hypervisor_type, hvparams)
855

    
856
  @staticmethod
857
  def perspective_node_configure_ovs(params):
858
    """Sets up OpenvSwitch on the node.
859

860
    """
861
    (ovs_name, ovs_link) = params
862
    return backend.ConfigureOVS(ovs_name, ovs_link)
863

    
864
  # cluster --------------------------
865

    
866
  @staticmethod
867
  def perspective_version(params):
868
    """Query version information.
869

870
    """
871
    return constants.PROTOCOL_VERSION
872

    
873
  @staticmethod
874
  def perspective_upload_file(params):
875
    """Upload a file.
876

877
    Note that the backend implementation imposes strict rules on which
878
    files are accepted.
879

880
    """
881
    return backend.UploadFile(*(params[0]))
882

    
883
  @staticmethod
884
  def perspective_master_info(params):
885
    """Query master information.
886

887
    """
888
    return backend.GetMasterInfo()
889

    
890
  @staticmethod
891
  def perspective_run_oob(params):
892
    """Runs oob on node.
893

894
    """
895
    output = backend.RunOob(params[0], params[1], params[2], params[3])
896
    if output:
897
      result = serializer.LoadJson(output)
898
    else:
899
      result = None
900
    return result
901

    
902
  @staticmethod
903
  def perspective_restricted_command(params):
904
    """Runs a restricted command.
905

906
    """
907
    (cmd, ) = params
908

    
909
    return backend.RunRestrictedCmd(cmd)
910

    
911
  @staticmethod
912
  def perspective_write_ssconf_files(params):
913
    """Write ssconf files.
914

915
    """
916
    (values,) = params
917
    return ssconf.WriteSsconfFiles(values)
918

    
919
  @staticmethod
920
  def perspective_get_watcher_pause(params):
921
    """Get watcher pause end.
922

923
    """
924
    return utils.ReadWatcherPauseFile(pathutils.WATCHER_PAUSEFILE)
925

    
926
  @staticmethod
927
  def perspective_set_watcher_pause(params):
928
    """Set watcher pause.
929

930
    """
931
    (until, ) = params
932
    return backend.SetWatcherPause(until)
933

    
934
  # os -----------------------
935

    
936
  @staticmethod
937
  def perspective_os_diagnose(params):
938
    """Query detailed information about existing OSes.
939

940
    """
941
    return backend.DiagnoseOS()
942

    
943
  @staticmethod
944
  def perspective_os_get(params):
945
    """Query information about a given OS.
946

947
    """
948
    name = params[0]
949
    os_obj = backend.OSFromDisk(name)
950
    return os_obj.ToDict()
951

    
952
  @staticmethod
953
  def perspective_os_validate(params):
954
    """Run a given OS' validation routine.
955

956
    """
957
    required, name, checks, params = params
958
    return backend.ValidateOS(required, name, checks, params)
959

    
960
  # extstorage -----------------------
961

    
962
  @staticmethod
963
  def perspective_extstorage_diagnose(params):
964
    """Query detailed information about existing extstorage providers.
965

966
    """
967
    return backend.DiagnoseExtStorage()
968

    
969
  # hooks -----------------------
970

    
971
  @staticmethod
972
  def perspective_hooks_runner(params):
973
    """Run hook scripts.
974

975
    """
976
    hpath, phase, env = params
977
    hr = backend.HooksRunner()
978
    return hr.RunHooks(hpath, phase, env)
979

    
980
  # iallocator -----------------
981

    
982
  @staticmethod
983
  def perspective_iallocator_runner(params):
984
    """Run an iallocator script.
985

986
    """
987
    name, idata = params
988
    iar = backend.IAllocatorRunner()
989
    return iar.Run(name, idata)
990

    
991
  # test -----------------------
992

    
993
  @staticmethod
994
  def perspective_test_delay(params):
995
    """Run test delay.
996

997
    """
998
    duration = params[0]
999
    status, rval = utils.TestDelay(duration)
1000
    if not status:
1001
      raise backend.RPCFail(rval)
1002
    return rval
1003

    
1004
  # file storage ---------------
1005

    
1006
  @staticmethod
1007
  def perspective_file_storage_dir_create(params):
1008
    """Create the file storage directory.
1009

1010
    """
1011
    file_storage_dir = params[0]
1012
    return backend.CreateFileStorageDir(file_storage_dir)
1013

    
1014
  @staticmethod
1015
  def perspective_file_storage_dir_remove(params):
1016
    """Remove the file storage directory.
1017

1018
    """
1019
    file_storage_dir = params[0]
1020
    return backend.RemoveFileStorageDir(file_storage_dir)
1021

    
1022
  @staticmethod
1023
  def perspective_file_storage_dir_rename(params):
1024
    """Rename the file storage directory.
1025

1026
    """
1027
    old_file_storage_dir = params[0]
1028
    new_file_storage_dir = params[1]
1029
    return backend.RenameFileStorageDir(old_file_storage_dir,
1030
                                        new_file_storage_dir)
1031

    
1032
  # jobs ------------------------
1033

    
1034
  @staticmethod
1035
  @_RequireJobQueueLock
1036
  def perspective_jobqueue_update(params):
1037
    """Update job queue.
1038

1039
    """
1040
    (file_name, content) = params
1041
    return backend.JobQueueUpdate(file_name, content)
1042

    
1043
  @staticmethod
1044
  @_RequireJobQueueLock
1045
  def perspective_jobqueue_purge(params):
1046
    """Purge job queue.
1047

1048
    """
1049
    return backend.JobQueuePurge()
1050

    
1051
  @staticmethod
1052
  @_RequireJobQueueLock
1053
  def perspective_jobqueue_rename(params):
1054
    """Rename a job queue file.
1055

1056
    """
1057
    # TODO: What if a file fails to rename?
1058
    return [backend.JobQueueRename(old, new) for old, new in params[0]]
1059

    
1060
  @staticmethod
1061
  @_RequireJobQueueLock
1062
  def perspective_jobqueue_set_drain_flag(params):
1063
    """Set job queue's drain flag.
1064

1065
    """
1066
    (flag, ) = params
1067

    
1068
    return jstore.SetDrainFlag(flag)
1069

    
1070
  # hypervisor ---------------
1071

    
1072
  @staticmethod
1073
  def perspective_hypervisor_validate_params(params):
1074
    """Validate the hypervisor parameters.
1075

1076
    """
1077
    (hvname, hvparams) = params
1078
    return backend.ValidateHVParams(hvname, hvparams)
1079

    
1080
  # Crypto
1081

    
1082
  @staticmethod
1083
  def perspective_x509_cert_create(params):
1084
    """Creates a new X509 certificate for SSL/TLS.
1085

1086
    """
1087
    (validity, ) = params
1088
    return backend.CreateX509Certificate(validity)
1089

    
1090
  @staticmethod
1091
  def perspective_x509_cert_remove(params):
1092
    """Removes a X509 certificate.
1093

1094
    """
1095
    (name, ) = params
1096
    return backend.RemoveX509Certificate(name)
1097

    
1098
  # Import and export
1099

    
1100
  @staticmethod
1101
  def perspective_import_start(params):
1102
    """Starts an import daemon.
1103

1104
    """
1105
    (opts_s, instance, component, (dest, dest_args)) = params
1106

    
1107
    opts = objects.ImportExportOptions.FromDict(opts_s)
1108

    
1109
    return backend.StartImportExportDaemon(constants.IEM_IMPORT, opts,
1110
                                           None, None,
1111
                                           objects.Instance.FromDict(instance),
1112
                                           component, dest,
1113
                                           _DecodeImportExportIO(dest,
1114
                                                                 dest_args))
1115

    
1116
  @staticmethod
1117
  def perspective_export_start(params):
1118
    """Starts an export daemon.
1119

1120
    """
1121
    (opts_s, host, port, instance, component, (source, source_args)) = params
1122

    
1123
    opts = objects.ImportExportOptions.FromDict(opts_s)
1124

    
1125
    return backend.StartImportExportDaemon(constants.IEM_EXPORT, opts,
1126
                                           host, port,
1127
                                           objects.Instance.FromDict(instance),
1128
                                           component, source,
1129
                                           _DecodeImportExportIO(source,
1130
                                                                 source_args))
1131

    
1132
  @staticmethod
1133
  def perspective_impexp_status(params):
1134
    """Retrieves the status of an import or export daemon.
1135

1136
    """
1137
    return backend.GetImportExportStatus(params[0])
1138

    
1139
  @staticmethod
1140
  def perspective_impexp_abort(params):
1141
    """Aborts an import or export.
1142

1143
    """
1144
    return backend.AbortImportExport(params[0])
1145

    
1146
  @staticmethod
1147
  def perspective_impexp_cleanup(params):
1148
    """Cleans up after an import or export.
1149

1150
    """
1151
    return backend.CleanupImportExport(params[0])
1152

    
1153

    
1154
def CheckNoded(_, args):
1155
  """Initial checks whether to run or exit with a failure.
1156

1157
  """
1158
  if args: # noded doesn't take any arguments
1159
    print >> sys.stderr, ("Usage: %s [-f] [-d] [-p port] [-b ADDRESS]" %
1160
                          sys.argv[0])
1161
    sys.exit(constants.EXIT_FAILURE)
1162
  try:
1163
    codecs.lookup("string-escape")
1164
  except LookupError:
1165
    print >> sys.stderr, ("Can't load the string-escape code which is part"
1166
                          " of the Python installation. Is your installation"
1167
                          " complete/correct? Aborting.")
1168
    sys.exit(constants.EXIT_FAILURE)
1169

    
1170

    
1171
def PrepNoded(options, _):
1172
  """Preparation node daemon function, executed with the PID file held.
1173

1174
  """
1175
  if options.mlock:
1176
    request_executor_class = MlockallRequestExecutor
1177
    try:
1178
      utils.Mlockall()
1179
    except errors.NoCtypesError:
1180
      logging.warning("Cannot set memory lock, ctypes module not found")
1181
      request_executor_class = http.server.HttpServerRequestExecutor
1182
  else:
1183
    request_executor_class = http.server.HttpServerRequestExecutor
1184

    
1185
  # Read SSL certificate
1186
  if options.ssl:
1187
    ssl_params = http.HttpSslParams(ssl_key_path=options.ssl_key,
1188
                                    ssl_cert_path=options.ssl_cert)
1189
  else:
1190
    ssl_params = None
1191

    
1192
  err = _PrepareQueueLock()
1193
  if err is not None:
1194
    # this might be some kind of file-system/permission error; while
1195
    # this breaks the job queue functionality, we shouldn't prevent
1196
    # startup of the whole node daemon because of this
1197
    logging.critical("Can't init/verify the queue, proceeding anyway: %s", err)
1198

    
1199
  handler = NodeRequestHandler()
1200

    
1201
  mainloop = daemon.Mainloop()
1202
  server = \
1203
    http.server.HttpServer(mainloop, options.bind_address, options.port,
1204
                           handler, ssl_params=ssl_params, ssl_verify_peer=True,
1205
                           request_executor_class=request_executor_class)
1206
  server.Start()
1207

    
1208
  return (mainloop, server)
1209

    
1210

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

1214
  """
1215
  (mainloop, server) = prep_data
1216
  try:
1217
    mainloop.Run()
1218
  finally:
1219
    server.Stop()
1220

    
1221

    
1222
def Main():
1223
  """Main function for the node daemon.
1224

1225
  """
1226
  parser = OptionParser(description="Ganeti node daemon",
1227
                        usage=("%prog [-f] [-d] [-p port] [-b ADDRESS]"
1228
                               " [-i INTERFACE]"),
1229
                        version="%%prog (ganeti) %s" %
1230
                        constants.RELEASE_VERSION)
1231
  parser.add_option("--no-mlock", dest="mlock",
1232
                    help="Do not mlock the node memory in ram",
1233
                    default=True, action="store_false")
1234

    
1235
  daemon.GenericMain(constants.NODED, parser, CheckNoded, PrepNoded, ExecNoded,
1236
                     default_ssl_cert=pathutils.NODED_CERT_FILE,
1237
                     default_ssl_key=pathutils.NODED_CERT_FILE,
1238
                     console_logging=True)