Statistics
| Branch: | Tag: | Revision:

root / lib / server / noded.py @ 4a90bd4f

History | View | Annotate | Download (31.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 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 _PrepareQueueLock():
61
  """Try to prepare the queue lock.
62

63
  @return: None for success, otherwise an exception object
64

65
  """
66
  global queue_lock # pylint: disable=W0603
67

    
68
  if queue_lock is not None:
69
    return None
70

    
71
  # Prepare job queue
72
  try:
73
    queue_lock = jstore.InitAndVerifyQueue(must_lock=False)
74
    return None
75
  except EnvironmentError, err:
76
    return err
77

    
78

    
79
def _RequireJobQueueLock(fn):
80
  """Decorator for job queue manipulating functions.
81

82
  """
83
  QUEUE_LOCK_TIMEOUT = 10
84

    
85
  def wrapper(*args, **kwargs):
86
    # Locking in exclusive, blocking mode because there could be several
87
    # children running at the same time. Waiting up to 10 seconds.
88
    if _PrepareQueueLock() is not None:
89
      raise errors.JobQueueError("Job queue failed initialization,"
90
                                 " cannot update jobs")
91
    queue_lock.Exclusive(blocking=True, timeout=QUEUE_LOCK_TIMEOUT)
92
    try:
93
      return fn(*args, **kwargs)
94
    finally:
95
      queue_lock.Unlock()
96

    
97
  return wrapper
98

    
99

    
100
def _DecodeImportExportIO(ieio, ieioargs):
101
  """Decodes import/export I/O information.
102

103
  """
104
  if ieio == constants.IEIO_RAW_DISK:
105
    assert len(ieioargs) == 1
106
    return (objects.Disk.FromDict(ieioargs[0]), )
107

    
108
  if ieio == constants.IEIO_SCRIPT:
109
    assert len(ieioargs) == 2
110
    return (objects.Disk.FromDict(ieioargs[0]), ieioargs[1])
111

    
112
  return ieioargs
113

    
114

    
115
def _DefaultAlternative(value, default):
116
  """Returns the given value, unless it is None. In that case, returns a
117
  default alternative.
118

119
  @param value: The value to return if it is not None.
120
  @param default: The value to return as a default alternative.
121
  @return: The given value or the default alternative.\
122

123
  """
124
  if value:
125
    return value
126

    
127
  return default
128

    
129

    
130
class MlockallRequestExecutor(http.server.HttpServerRequestExecutor):
131
  """Subclass ensuring request handlers are locked in RAM.
132

133
  """
134
  def __init__(self, *args, **kwargs):
135
    utils.Mlockall()
136

    
137
    http.server.HttpServerRequestExecutor.__init__(self, *args, **kwargs)
138

    
139

    
140
class NodeRequestHandler(http.server.HttpServerHandler):
141
  """The server implementation.
142

143
  This class holds all methods exposed over the RPC interface.
144

145
  """
146
  # too many public methods, and unused args - all methods get params
147
  # due to the API
148
  # pylint: disable=R0904,W0613
149
  def __init__(self):
150
    http.server.HttpServerHandler.__init__(self)
151
    self.noded_pid = os.getpid()
152

    
153
  def HandleRequest(self, req):
154
    """Handle a request.
155

156
    """
157
    if req.request_method.upper() != http.HTTP_POST:
158
      raise http.HttpBadRequest("Only the POST method is supported")
159

    
160
    path = req.request_path
161
    if path.startswith("/"):
162
      path = path[1:]
163

    
164
    method = getattr(self, "perspective_%s" % path, None)
165
    if method is None:
166
      raise http.HttpNotFound()
167

    
168
    try:
169
      result = (True, method(serializer.LoadJson(req.request_body)))
170

    
171
    except backend.RPCFail, err:
172
      # our custom failure exception; str(err) works fine if the
173
      # exception was constructed with a single argument, and in
174
      # this case, err.message == err.args[0] == str(err)
175
      result = (False, str(err))
176
    except errors.QuitGanetiException, err:
177
      # Tell parent to quit
178
      logging.info("Shutting down the node daemon, arguments: %s",
179
                   str(err.args))
180
      os.kill(self.noded_pid, signal.SIGTERM)
181
      # And return the error's arguments, which must be already in
182
      # correct tuple format
183
      result = err.args
184
    except Exception, err:
185
      logging.exception("Error in RPC call")
186
      result = (False, "Error while executing backend function: %s" % str(err))
187

    
188
    return serializer.DumpJson(result)
189

    
190
  # the new block devices  --------------------------
191

    
192
  @staticmethod
193
  def perspective_blockdev_create(params):
194
    """Create a block device.
195

196
    """
197
    (bdev_s, size, owner, on_primary, info, excl_stor) = params
198
    bdev = objects.Disk.FromDict(bdev_s)
199
    if bdev is None:
200
      raise ValueError("can't unserialize data!")
201
    return backend.BlockdevCreate(bdev, size, owner, on_primary, info,
202
                                  excl_stor)
203

    
204
  @staticmethod
205
  def perspective_blockdev_pause_resume_sync(params):
206
    """Pause/resume sync of a block device.
207

208
    """
209
    disks_s, pause = params
210
    disks = [objects.Disk.FromDict(bdev_s) for bdev_s in disks_s]
211
    return backend.BlockdevPauseResumeSync(disks, pause)
212

    
213
  @staticmethod
214
  def perspective_blockdev_wipe(params):
215
    """Wipe a block device.
216

217
    """
218
    bdev_s, offset, size = params
219
    bdev = objects.Disk.FromDict(bdev_s)
220
    return backend.BlockdevWipe(bdev, offset, size)
221

    
222
  @staticmethod
223
  def perspective_blockdev_remove(params):
224
    """Remove a block device.
225

226
    """
227
    bdev_s = params[0]
228
    bdev = objects.Disk.FromDict(bdev_s)
229
    return backend.BlockdevRemove(bdev)
230

    
231
  @staticmethod
232
  def perspective_blockdev_rename(params):
233
    """Remove a block device.
234

235
    """
236
    devlist = [(objects.Disk.FromDict(ds), uid) for ds, uid in params[0]]
237
    return backend.BlockdevRename(devlist)
238

    
239
  @staticmethod
240
  def perspective_blockdev_assemble(params):
241
    """Assemble a block device.
242

243
    """
244
    bdev_s, owner, on_primary, idx = params
245
    bdev = objects.Disk.FromDict(bdev_s)
246
    if bdev is None:
247
      raise ValueError("can't unserialize data!")
248
    return backend.BlockdevAssemble(bdev, owner, on_primary, idx)
249

    
250
  @staticmethod
251
  def perspective_blockdev_shutdown(params):
252
    """Shutdown a block device.
253

254
    """
255
    bdev_s = params[0]
256
    bdev = objects.Disk.FromDict(bdev_s)
257
    if bdev is None:
258
      raise ValueError("can't unserialize data!")
259
    return backend.BlockdevShutdown(bdev)
260

    
261
  @staticmethod
262
  def perspective_blockdev_addchildren(params):
263
    """Add a child to a mirror device.
264

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

268
    """
269
    bdev_s, ndev_s = params
270
    bdev = objects.Disk.FromDict(bdev_s)
271
    ndevs = [objects.Disk.FromDict(disk_s) for disk_s in ndev_s]
272
    if bdev is None or ndevs.count(None) > 0:
273
      raise ValueError("can't unserialize data!")
274
    return backend.BlockdevAddchildren(bdev, ndevs)
275

    
276
  @staticmethod
277
  def perspective_blockdev_removechildren(params):
278
    """Remove a child from a mirror device.
279

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

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

    
291
  @staticmethod
292
  def perspective_blockdev_getmirrorstatus(params):
293
    """Return the mirror status for a list of disks.
294

295
    """
296
    disks = [objects.Disk.FromDict(dsk_s)
297
             for dsk_s in params[0]]
298
    return [status.ToDict()
299
            for status in backend.BlockdevGetmirrorstatus(disks)]
300

    
301
  @staticmethod
302
  def perspective_blockdev_getmirrorstatus_multi(params):
303
    """Return the mirror status for a list of disks.
304

305
    """
306
    (node_disks, ) = params
307

    
308
    disks = [objects.Disk.FromDict(dsk_s) for dsk_s in node_disks]
309

    
310
    result = []
311

    
312
    for (success, status) in backend.BlockdevGetmirrorstatusMulti(disks):
313
      if success:
314
        result.append((success, status.ToDict()))
315
      else:
316
        result.append((success, status))
317

    
318
    return result
319

    
320
  @staticmethod
321
  def perspective_blockdev_find(params):
322
    """Expose the FindBlockDevice functionality for a disk.
323

324
    This will try to find but not activate a disk.
325

326
    """
327
    disk = objects.Disk.FromDict(params[0])
328

    
329
    result = backend.BlockdevFind(disk)
330
    if result is None:
331
      return None
332

    
333
    return result.ToDict()
334

    
335
  @staticmethod
336
  def perspective_blockdev_snapshot(params):
337
    """Create a snapshot device.
338

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

343
    """
344
    cfbd = objects.Disk.FromDict(params[0])
345
    return backend.BlockdevSnapshot(cfbd)
346

    
347
  @staticmethod
348
  def perspective_blockdev_grow(params):
349
    """Grow a stack of devices.
350

351
    """
352
    if len(params) < 4:
353
      raise ValueError("Received only 3 parameters in blockdev_grow,"
354
                       " old master?")
355
    cfbd = objects.Disk.FromDict(params[0])
356
    amount = params[1]
357
    dryrun = params[2]
358
    backingstore = params[3]
359
    return backend.BlockdevGrow(cfbd, amount, dryrun, backingstore)
360

    
361
  @staticmethod
362
  def perspective_blockdev_close(params):
363
    """Closes the given block devices.
364

365
    """
366
    disks = [objects.Disk.FromDict(cf) for cf in params[1]]
367
    return backend.BlockdevClose(params[0], disks)
368

    
369
  @staticmethod
370
  def perspective_blockdev_getsize(params):
371
    """Compute the sizes of the given block devices.
372

373
    """
374
    disks = [objects.Disk.FromDict(cf) for cf in params[0]]
375
    return backend.BlockdevGetsize(disks)
376

    
377
  @staticmethod
378
  def perspective_blockdev_export(params):
379
    """Compute the sizes of the given block devices.
380

381
    """
382
    disk = objects.Disk.FromDict(params[0])
383
    dest_node, dest_path, cluster_name = params[1:]
384
    return backend.BlockdevExport(disk, dest_node, dest_path, cluster_name)
385

    
386
  @staticmethod
387
  def perspective_blockdev_setinfo(params):
388
    """Sets metadata information on the given block device.
389

390
    """
391
    (disk, info) = params
392
    disk = objects.Disk.FromDict(disk)
393
    return backend.BlockdevSetInfo(disk, info)
394

    
395
  # blockdev/drbd specific methods ----------
396

    
397
  @staticmethod
398
  def perspective_drbd_disconnect_net(params):
399
    """Disconnects the network connection of drbd disks.
400

401
    Note that this is only valid for drbd disks, so the members of the
402
    disk list must all be drbd devices.
403

404
    """
405
    nodes_ip, disks = params
406
    disks = [objects.Disk.FromDict(cf) for cf in disks]
407
    return backend.DrbdDisconnectNet(nodes_ip, disks)
408

    
409
  @staticmethod
410
  def perspective_drbd_attach_net(params):
411
    """Attaches 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, instance_name, multimaster = params
418
    disks = [objects.Disk.FromDict(cf) for cf in disks]
419
    return backend.DrbdAttachNet(nodes_ip, disks,
420
                                     instance_name, multimaster)
421

    
422
  @staticmethod
423
  def perspective_drbd_wait_sync(params):
424
    """Wait until DRBD disks are synched.
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 = params
431
    disks = [objects.Disk.FromDict(cf) for cf in disks]
432
    return backend.DrbdWaitSync(nodes_ip, disks)
433

    
434
  @staticmethod
435
  def perspective_drbd_helper(params):
436
    """Query drbd helper.
437

438
    """
439
    return backend.GetDrbdUsermodeHelper()
440

    
441
  # export/import  --------------------------
442

    
443
  @staticmethod
444
  def perspective_finalize_export(params):
445
    """Expose the finalize export functionality.
446

447
    """
448
    instance = objects.Instance.FromDict(params[0])
449

    
450
    snap_disks = []
451
    for disk in params[1]:
452
      if isinstance(disk, bool):
453
        snap_disks.append(disk)
454
      else:
455
        snap_disks.append(objects.Disk.FromDict(disk))
456

    
457
    return backend.FinalizeExport(instance, snap_disks)
458

    
459
  @staticmethod
460
  def perspective_export_info(params):
461
    """Query information about an existing export on this node.
462

463
    The given path may not contain an export, in which case we return
464
    None.
465

466
    """
467
    path = params[0]
468
    return backend.ExportInfo(path)
469

    
470
  @staticmethod
471
  def perspective_export_list(params):
472
    """List the available exports on this node.
473

474
    Note that as opposed to export_info, which may query data about an
475
    export in any path, this only queries the standard Ganeti path
476
    (pathutils.EXPORT_DIR).
477

478
    """
479
    return backend.ListExports()
480

    
481
  @staticmethod
482
  def perspective_export_remove(params):
483
    """Remove an export.
484

485
    """
486
    export = params[0]
487
    return backend.RemoveExport(export)
488

    
489
  # block device ---------------------
490
  @staticmethod
491
  def perspective_bdev_sizes(params):
492
    """Query the list of block devices
493

494
    """
495
    devices = params[0]
496
    return backend.GetBlockDevSizes(devices)
497

    
498
  # volume  --------------------------
499

    
500
  @staticmethod
501
  def perspective_lv_list(params):
502
    """Query the list of logical volumes in a given volume group.
503

504
    """
505
    vgname = params[0]
506
    return backend.GetVolumeList(vgname)
507

    
508
  @staticmethod
509
  def perspective_vg_list(params):
510
    """Query the list of volume groups.
511

512
    """
513
    return backend.ListVolumeGroups()
514

    
515
  # Storage --------------------------
516

    
517
  @staticmethod
518
  def perspective_storage_list(params):
519
    """Get list of storage units.
520

521
    """
522
    (su_name, su_args, name, fields) = params
523
    return storage.GetStorage(su_name, *su_args).List(name, fields)
524

    
525
  @staticmethod
526
  def perspective_storage_modify(params):
527
    """Modify a storage unit.
528

529
    """
530
    (su_name, su_args, name, changes) = params
531
    return storage.GetStorage(su_name, *su_args).Modify(name, changes)
532

    
533
  @staticmethod
534
  def perspective_storage_execute(params):
535
    """Execute an operation on a storage unit.
536

537
    """
538
    (su_name, su_args, name, op) = params
539
    return storage.GetStorage(su_name, *su_args).Execute(name, op)
540

    
541
  # bridge  --------------------------
542

    
543
  @staticmethod
544
  def perspective_bridges_exist(params):
545
    """Check if all bridges given exist on this node.
546

547
    """
548
    bridges_list = params[0]
549
    return backend.BridgesExist(bridges_list)
550

    
551
  # instance  --------------------------
552

    
553
  @staticmethod
554
  def perspective_instance_os_add(params):
555
    """Install an OS on a given instance.
556

557
    """
558
    inst_s = params[0]
559
    inst = objects.Instance.FromDict(inst_s)
560
    reinstall = params[1]
561
    debug = params[2]
562
    return backend.InstanceOsAdd(inst, reinstall, debug)
563

    
564
  @staticmethod
565
  def perspective_instance_run_rename(params):
566
    """Runs the OS rename script for an instance.
567

568
    """
569
    inst_s, old_name, debug = params
570
    inst = objects.Instance.FromDict(inst_s)
571
    return backend.RunRenameInstance(inst, old_name, debug)
572

    
573
  @staticmethod
574
  def perspective_instance_shutdown(params):
575
    """Shutdown an instance.
576

577
    """
578
    instance = objects.Instance.FromDict(params[0])
579
    timeout = params[1]
580
    return backend.InstanceShutdown(instance, timeout)
581

    
582
  @staticmethod
583
  def perspective_instance_start(params):
584
    """Start an instance.
585

586
    """
587
    (instance_name, startup_paused) = params
588
    instance = objects.Instance.FromDict(instance_name)
589
    return backend.StartInstance(instance, startup_paused)
590

    
591
  @staticmethod
592
  def perspective_migration_info(params):
593
    """Gather information about an instance to be migrated.
594

595
    """
596
    instance = objects.Instance.FromDict(params[0])
597
    return backend.MigrationInfo(instance)
598

    
599
  @staticmethod
600
  def perspective_accept_instance(params):
601
    """Prepare the node to accept an instance.
602

603
    """
604
    instance, info, target = params
605
    instance = objects.Instance.FromDict(instance)
606
    return backend.AcceptInstance(instance, info, target)
607

    
608
  @staticmethod
609
  def perspective_instance_finalize_migration_dst(params):
610
    """Finalize the instance migration on the destination node.
611

612
    """
613
    instance, info, success = params
614
    instance = objects.Instance.FromDict(instance)
615
    return backend.FinalizeMigrationDst(instance, info, success)
616

    
617
  @staticmethod
618
  def perspective_instance_migrate(params):
619
    """Migrates an instance.
620

621
    """
622
    instance, target, live = params
623
    instance = objects.Instance.FromDict(instance)
624
    return backend.MigrateInstance(instance, target, live)
625

    
626
  @staticmethod
627
  def perspective_instance_finalize_migration_src(params):
628
    """Finalize the instance migration on the source node.
629

630
    """
631
    instance, success, live = params
632
    instance = objects.Instance.FromDict(instance)
633
    return backend.FinalizeMigrationSource(instance, success, live)
634

    
635
  @staticmethod
636
  def perspective_instance_get_migration_status(params):
637
    """Reports migration status.
638

639
    """
640
    instance = objects.Instance.FromDict(params[0])
641
    return backend.GetMigrationStatus(instance).ToDict()
642

    
643
  @staticmethod
644
  def perspective_instance_reboot(params):
645
    """Reboot an instance.
646

647
    """
648
    instance = objects.Instance.FromDict(params[0])
649
    reboot_type = params[1]
650
    shutdown_timeout = params[2]
651
    (reason_source, reason_text) = params[3]
652
    reason_text = _DefaultAlternative(reason_text,
653
                                      constants.INSTANCE_REASON_REBOOT)
654
    reason = backend.InstReason(reason_source, reason_text)
655
    return backend.InstanceReboot(instance, reboot_type, shutdown_timeout,
656
                                  reason)
657

    
658
  @staticmethod
659
  def perspective_instance_balloon_memory(params):
660
    """Modify instance runtime memory.
661

662
    """
663
    instance_dict, memory = params
664
    instance = objects.Instance.FromDict(instance_dict)
665
    return backend.InstanceBalloonMemory(instance, memory)
666

    
667
  @staticmethod
668
  def perspective_instance_info(params):
669
    """Query instance information.
670

671
    """
672
    return backend.GetInstanceInfo(params[0], params[1])
673

    
674
  @staticmethod
675
  def perspective_instance_migratable(params):
676
    """Query whether the specified instance can be migrated.
677

678
    """
679
    instance = objects.Instance.FromDict(params[0])
680
    return backend.GetInstanceMigratable(instance)
681

    
682
  @staticmethod
683
  def perspective_all_instances_info(params):
684
    """Query information about all instances.
685

686
    """
687
    return backend.GetAllInstancesInfo(params[0])
688

    
689
  @staticmethod
690
  def perspective_instance_list(params):
691
    """Query the list of running instances.
692

693
    """
694
    return backend.GetInstanceList(params[0])
695

    
696
  # node --------------------------
697

    
698
  @staticmethod
699
  def perspective_node_has_ip_address(params):
700
    """Checks if a node has the given ip address.
701

702
    """
703
    return netutils.IPAddress.Own(params[0])
704

    
705
  @staticmethod
706
  def perspective_node_info(params):
707
    """Query node information.
708

709
    """
710
    (vg_names, hv_names, excl_stor) = params
711
    return backend.GetNodeInfo(vg_names, hv_names, excl_stor)
712

    
713
  @staticmethod
714
  def perspective_etc_hosts_modify(params):
715
    """Modify a node entry in /etc/hosts.
716

717
    """
718
    backend.EtcHostsModify(params[0], params[1], params[2])
719

    
720
    return True
721

    
722
  @staticmethod
723
  def perspective_node_verify(params):
724
    """Run a verify sequence on this node.
725

726
    """
727
    return backend.VerifyNode(params[0], params[1])
728

    
729
  @classmethod
730
  def perspective_node_verify_light(cls, params):
731
    """Run a light verify sequence on this node.
732

733
    """
734
    # So far it's the same as the normal node_verify
735
    return cls.perspective_node_verify(params)
736

    
737
  @staticmethod
738
  def perspective_node_start_master_daemons(params):
739
    """Start the master daemons on this node.
740

741
    """
742
    return backend.StartMasterDaemons(params[0])
743

    
744
  @staticmethod
745
  def perspective_node_activate_master_ip(params):
746
    """Activate the master IP on this node.
747

748
    """
749
    master_params = objects.MasterNetworkParameters.FromDict(params[0])
750
    return backend.ActivateMasterIp(master_params, params[1])
751

    
752
  @staticmethod
753
  def perspective_node_deactivate_master_ip(params):
754
    """Deactivate the master IP on this node.
755

756
    """
757
    master_params = objects.MasterNetworkParameters.FromDict(params[0])
758
    return backend.DeactivateMasterIp(master_params, params[1])
759

    
760
  @staticmethod
761
  def perspective_node_stop_master(params):
762
    """Stops master daemons on this node.
763

764
    """
765
    return backend.StopMasterDaemons()
766

    
767
  @staticmethod
768
  def perspective_node_change_master_netmask(params):
769
    """Change the master IP netmask.
770

771
    """
772
    return backend.ChangeMasterNetmask(params[0], params[1], params[2],
773
                                       params[3])
774

    
775
  @staticmethod
776
  def perspective_node_leave_cluster(params):
777
    """Cleanup after leaving a cluster.
778

779
    """
780
    return backend.LeaveCluster(params[0])
781

    
782
  @staticmethod
783
  def perspective_node_volumes(params):
784
    """Query the list of all logical volume groups.
785

786
    """
787
    return backend.NodeVolumes()
788

    
789
  @staticmethod
790
  def perspective_node_demote_from_mc(params):
791
    """Demote a node from the master candidate role.
792

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

    
796
  @staticmethod
797
  def perspective_node_powercycle(params):
798
    """Tries to powercycle the nod.
799

800
    """
801
    hypervisor_type = params[0]
802
    return backend.PowercycleNode(hypervisor_type)
803

    
804
  # cluster --------------------------
805

    
806
  @staticmethod
807
  def perspective_version(params):
808
    """Query version information.
809

810
    """
811
    return constants.PROTOCOL_VERSION
812

    
813
  @staticmethod
814
  def perspective_upload_file(params):
815
    """Upload a file.
816

817
    Note that the backend implementation imposes strict rules on which
818
    files are accepted.
819

820
    """
821
    return backend.UploadFile(*(params[0]))
822

    
823
  @staticmethod
824
  def perspective_master_info(params):
825
    """Query master information.
826

827
    """
828
    return backend.GetMasterInfo()
829

    
830
  @staticmethod
831
  def perspective_run_oob(params):
832
    """Runs oob on node.
833

834
    """
835
    output = backend.RunOob(params[0], params[1], params[2], params[3])
836
    if output:
837
      result = serializer.LoadJson(output)
838
    else:
839
      result = None
840
    return result
841

    
842
  @staticmethod
843
  def perspective_restricted_command(params):
844
    """Runs a restricted command.
845

846
    """
847
    (cmd, ) = params
848

    
849
    return backend.RunRestrictedCmd(cmd)
850

    
851
  @staticmethod
852
  def perspective_write_ssconf_files(params):
853
    """Write ssconf files.
854

855
    """
856
    (values,) = params
857
    return ssconf.WriteSsconfFiles(values)
858

    
859
  @staticmethod
860
  def perspective_get_watcher_pause(params):
861
    """Get watcher pause end.
862

863
    """
864
    return utils.ReadWatcherPauseFile(pathutils.WATCHER_PAUSEFILE)
865

    
866
  @staticmethod
867
  def perspective_set_watcher_pause(params):
868
    """Set watcher pause.
869

870
    """
871
    (until, ) = params
872
    return backend.SetWatcherPause(until)
873

    
874
  # os -----------------------
875

    
876
  @staticmethod
877
  def perspective_os_diagnose(params):
878
    """Query detailed information about existing OSes.
879

880
    """
881
    return backend.DiagnoseOS()
882

    
883
  @staticmethod
884
  def perspective_os_get(params):
885
    """Query information about a given OS.
886

887
    """
888
    name = params[0]
889
    os_obj = backend.OSFromDisk(name)
890
    return os_obj.ToDict()
891

    
892
  @staticmethod
893
  def perspective_os_validate(params):
894
    """Run a given OS' validation routine.
895

896
    """
897
    required, name, checks, params = params
898
    return backend.ValidateOS(required, name, checks, params)
899

    
900
  # extstorage -----------------------
901

    
902
  @staticmethod
903
  def perspective_extstorage_diagnose(params):
904
    """Query detailed information about existing extstorage providers.
905

906
    """
907
    return backend.DiagnoseExtStorage()
908

    
909
  # hooks -----------------------
910

    
911
  @staticmethod
912
  def perspective_hooks_runner(params):
913
    """Run hook scripts.
914

915
    """
916
    hpath, phase, env = params
917
    hr = backend.HooksRunner()
918
    return hr.RunHooks(hpath, phase, env)
919

    
920
  # iallocator -----------------
921

    
922
  @staticmethod
923
  def perspective_iallocator_runner(params):
924
    """Run an iallocator script.
925

926
    """
927
    name, idata = params
928
    iar = backend.IAllocatorRunner()
929
    return iar.Run(name, idata)
930

    
931
  # test -----------------------
932

    
933
  @staticmethod
934
  def perspective_test_delay(params):
935
    """Run test delay.
936

937
    """
938
    duration = params[0]
939
    status, rval = utils.TestDelay(duration)
940
    if not status:
941
      raise backend.RPCFail(rval)
942
    return rval
943

    
944
  # file storage ---------------
945

    
946
  @staticmethod
947
  def perspective_file_storage_dir_create(params):
948
    """Create the file storage directory.
949

950
    """
951
    file_storage_dir = params[0]
952
    return backend.CreateFileStorageDir(file_storage_dir)
953

    
954
  @staticmethod
955
  def perspective_file_storage_dir_remove(params):
956
    """Remove the file storage directory.
957

958
    """
959
    file_storage_dir = params[0]
960
    return backend.RemoveFileStorageDir(file_storage_dir)
961

    
962
  @staticmethod
963
  def perspective_file_storage_dir_rename(params):
964
    """Rename the file storage directory.
965

966
    """
967
    old_file_storage_dir = params[0]
968
    new_file_storage_dir = params[1]
969
    return backend.RenameFileStorageDir(old_file_storage_dir,
970
                                        new_file_storage_dir)
971

    
972
  # jobs ------------------------
973

    
974
  @staticmethod
975
  @_RequireJobQueueLock
976
  def perspective_jobqueue_update(params):
977
    """Update job queue.
978

979
    """
980
    (file_name, content) = params
981
    return backend.JobQueueUpdate(file_name, content)
982

    
983
  @staticmethod
984
  @_RequireJobQueueLock
985
  def perspective_jobqueue_purge(params):
986
    """Purge job queue.
987

988
    """
989
    return backend.JobQueuePurge()
990

    
991
  @staticmethod
992
  @_RequireJobQueueLock
993
  def perspective_jobqueue_rename(params):
994
    """Rename a job queue file.
995

996
    """
997
    # TODO: What if a file fails to rename?
998
    return [backend.JobQueueRename(old, new) for old, new in params[0]]
999

    
1000
  @staticmethod
1001
  @_RequireJobQueueLock
1002
  def perspective_jobqueue_set_drain_flag(params):
1003
    """Set job queue's drain flag.
1004

1005
    """
1006
    (flag, ) = params
1007

    
1008
    return jstore.SetDrainFlag(flag)
1009

    
1010
  # hypervisor ---------------
1011

    
1012
  @staticmethod
1013
  def perspective_hypervisor_validate_params(params):
1014
    """Validate the hypervisor parameters.
1015

1016
    """
1017
    (hvname, hvparams) = params
1018
    return backend.ValidateHVParams(hvname, hvparams)
1019

    
1020
  # Crypto
1021

    
1022
  @staticmethod
1023
  def perspective_x509_cert_create(params):
1024
    """Creates a new X509 certificate for SSL/TLS.
1025

1026
    """
1027
    (validity, ) = params
1028
    return backend.CreateX509Certificate(validity)
1029

    
1030
  @staticmethod
1031
  def perspective_x509_cert_remove(params):
1032
    """Removes a X509 certificate.
1033

1034
    """
1035
    (name, ) = params
1036
    return backend.RemoveX509Certificate(name)
1037

    
1038
  # Import and export
1039

    
1040
  @staticmethod
1041
  def perspective_import_start(params):
1042
    """Starts an import daemon.
1043

1044
    """
1045
    (opts_s, instance, component, (dest, dest_args)) = params
1046

    
1047
    opts = objects.ImportExportOptions.FromDict(opts_s)
1048

    
1049
    return backend.StartImportExportDaemon(constants.IEM_IMPORT, opts,
1050
                                           None, None,
1051
                                           objects.Instance.FromDict(instance),
1052
                                           component, dest,
1053
                                           _DecodeImportExportIO(dest,
1054
                                                                 dest_args))
1055

    
1056
  @staticmethod
1057
  def perspective_export_start(params):
1058
    """Starts an export daemon.
1059

1060
    """
1061
    (opts_s, host, port, instance, component, (source, source_args)) = params
1062

    
1063
    opts = objects.ImportExportOptions.FromDict(opts_s)
1064

    
1065
    return backend.StartImportExportDaemon(constants.IEM_EXPORT, opts,
1066
                                           host, port,
1067
                                           objects.Instance.FromDict(instance),
1068
                                           component, source,
1069
                                           _DecodeImportExportIO(source,
1070
                                                                 source_args))
1071

    
1072
  @staticmethod
1073
  def perspective_impexp_status(params):
1074
    """Retrieves the status of an import or export daemon.
1075

1076
    """
1077
    return backend.GetImportExportStatus(params[0])
1078

    
1079
  @staticmethod
1080
  def perspective_impexp_abort(params):
1081
    """Aborts an import or export.
1082

1083
    """
1084
    return backend.AbortImportExport(params[0])
1085

    
1086
  @staticmethod
1087
  def perspective_impexp_cleanup(params):
1088
    """Cleans up after an import or export.
1089

1090
    """
1091
    return backend.CleanupImportExport(params[0])
1092

    
1093

    
1094
def CheckNoded(_, args):
1095
  """Initial checks whether to run or exit with a failure.
1096

1097
  """
1098
  if args: # noded doesn't take any arguments
1099
    print >> sys.stderr, ("Usage: %s [-f] [-d] [-p port] [-b ADDRESS]" %
1100
                          sys.argv[0])
1101
    sys.exit(constants.EXIT_FAILURE)
1102
  try:
1103
    codecs.lookup("string-escape")
1104
  except LookupError:
1105
    print >> sys.stderr, ("Can't load the string-escape code which is part"
1106
                          " of the Python installation. Is your installation"
1107
                          " complete/correct? Aborting.")
1108
    sys.exit(constants.EXIT_FAILURE)
1109

    
1110

    
1111
def PrepNoded(options, _):
1112
  """Preparation node daemon function, executed with the PID file held.
1113

1114
  """
1115
  if options.mlock:
1116
    request_executor_class = MlockallRequestExecutor
1117
    try:
1118
      utils.Mlockall()
1119
    except errors.NoCtypesError:
1120
      logging.warning("Cannot set memory lock, ctypes module not found")
1121
      request_executor_class = http.server.HttpServerRequestExecutor
1122
  else:
1123
    request_executor_class = http.server.HttpServerRequestExecutor
1124

    
1125
  # Read SSL certificate
1126
  if options.ssl:
1127
    ssl_params = http.HttpSslParams(ssl_key_path=options.ssl_key,
1128
                                    ssl_cert_path=options.ssl_cert)
1129
  else:
1130
    ssl_params = None
1131

    
1132
  err = _PrepareQueueLock()
1133
  if err is not None:
1134
    # this might be some kind of file-system/permission error; while
1135
    # this breaks the job queue functionality, we shouldn't prevent
1136
    # startup of the whole node daemon because of this
1137
    logging.critical("Can't init/verify the queue, proceeding anyway: %s", err)
1138

    
1139
  handler = NodeRequestHandler()
1140

    
1141
  mainloop = daemon.Mainloop()
1142
  server = \
1143
    http.server.HttpServer(mainloop, options.bind_address, options.port,
1144
                           handler, ssl_params=ssl_params, ssl_verify_peer=True,
1145
                           request_executor_class=request_executor_class)
1146
  server.Start()
1147

    
1148
  return (mainloop, server)
1149

    
1150

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

1154
  """
1155
  (mainloop, server) = prep_data
1156
  try:
1157
    mainloop.Run()
1158
  finally:
1159
    server.Stop()
1160

    
1161

    
1162
def Main():
1163
  """Main function for the node daemon.
1164

1165
  """
1166
  parser = OptionParser(description="Ganeti node daemon",
1167
                        usage="%prog [-f] [-d] [-p port] [-b ADDRESS]",
1168
                        version="%%prog (ganeti) %s" %
1169
                        constants.RELEASE_VERSION)
1170
  parser.add_option("--no-mlock", dest="mlock",
1171
                    help="Do not mlock the node memory in ram",
1172
                    default=True, action="store_false")
1173

    
1174
  daemon.GenericMain(constants.NODED, parser, CheckNoded, PrepNoded, ExecNoded,
1175
                     default_ssl_cert=pathutils.NODED_CERT_FILE,
1176
                     default_ssl_key=pathutils.NODED_CERT_FILE,
1177
                     console_logging=True)