Statistics
| Branch: | Tag: | Revision:

root / lib / server / noded.py @ 0e79564a

History | View | Annotate | Download (31.3 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 value or, if evaluating to False, a default value.
117

118
  Returns the given value, unless it evaluates to False. In the latter case the
119
  default value is returned.
120

121
  @param value: Value to return if it doesn't evaluate to False
122
  @param default: Default value
123
  @return: Given value or the default
124

125
  """
126
  if value:
127
    return value
128

    
129
  return default
130

    
131

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

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

    
139
    http.server.HttpServerRequestExecutor.__init__(self, *args, **kwargs)
140

    
141

    
142
class NodeRequestHandler(http.server.HttpServerHandler):
143
  """The server implementation.
144

145
  This class holds all methods exposed over the RPC interface.
146

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

    
155
  def HandleRequest(self, req):
156
    """Handle a request.
157

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

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

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

    
170
    try:
171
      result = (True, method(serializer.LoadJson(req.request_body)))
172

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

    
190
    return serializer.DumpJson(result)
191

    
192
  # the new block devices  --------------------------
193

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

307
    """
308
    (node_disks, ) = params
309

    
310
    disks = [objects.Disk.FromDict(dsk_s) for dsk_s in node_disks]
311

    
312
    result = []
313

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

    
320
    return result
321

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

326
    This will try to find but not activate a disk.
327

328
    """
329
    disk = objects.Disk.FromDict(params[0])
330

    
331
    result = backend.BlockdevFind(disk)
332
    if result is None:
333
      return None
334

    
335
    return result.ToDict()
336

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

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

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

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

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

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

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

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

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

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

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

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

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

    
397
  # blockdev/drbd specific methods ----------
398

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

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

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

    
411
  @staticmethod
412
  def perspective_drbd_attach_net(params):
413
    """Attaches the network connection of drbd disks.
414

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

418
    """
419
    nodes_ip, disks, instance_name, multimaster = params
420
    disks = [objects.Disk.FromDict(cf) for cf in disks]
421
    return backend.DrbdAttachNet(nodes_ip, disks,
422
                                     instance_name, multimaster)
423

    
424
  @staticmethod
425
  def perspective_drbd_wait_sync(params):
426
    """Wait until DRBD disks are synched.
427

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

431
    """
432
    nodes_ip, disks = params
433
    disks = [objects.Disk.FromDict(cf) for cf in disks]
434
    return backend.DrbdWaitSync(nodes_ip, disks)
435

    
436
  @staticmethod
437
  def perspective_drbd_helper(params):
438
    """Query drbd helper.
439

440
    """
441
    return backend.GetDrbdUsermodeHelper()
442

    
443
  # export/import  --------------------------
444

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

449
    """
450
    instance = objects.Instance.FromDict(params[0])
451

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

    
459
    return backend.FinalizeExport(instance, snap_disks)
460

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

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

468
    """
469
    path = params[0]
470
    return backend.ExportInfo(path)
471

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

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

480
    """
481
    return backend.ListExports()
482

    
483
  @staticmethod
484
  def perspective_export_remove(params):
485
    """Remove an export.
486

487
    """
488
    export = params[0]
489
    return backend.RemoveExport(export)
490

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

496
    """
497
    devices = params[0]
498
    return backend.GetBlockDevSizes(devices)
499

    
500
  # volume  --------------------------
501

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

506
    """
507
    vgname = params[0]
508
    return backend.GetVolumeList(vgname)
509

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

514
    """
515
    return backend.ListVolumeGroups()
516

    
517
  # Storage --------------------------
518

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

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

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

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

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

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

    
543
  # bridge  --------------------------
544

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

549
    """
550
    bridges_list = params[0]
551
    return backend.BridgesExist(bridges_list)
552

    
553
  # instance  --------------------------
554

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

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

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

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

    
575
  @staticmethod
576
  def perspective_instance_shutdown(params):
577
    """Shutdown an instance.
578

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

    
584
  @staticmethod
585
  def perspective_instance_start(params):
586
    """Start an instance.
587

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

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

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

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

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

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

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

    
619
  @staticmethod
620
  def perspective_instance_migrate(params):
621
    """Migrates an instance.
622

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

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

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

    
637
  @staticmethod
638
  def perspective_instance_get_migration_status(params):
639
    """Reports migration status.
640

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

    
645
  @staticmethod
646
  def perspective_instance_reboot(params):
647
    """Reboot an instance.
648

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

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

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

    
669
  @staticmethod
670
  def perspective_instance_info(params):
671
    """Query instance information.
672

673
    """
674
    return backend.GetInstanceInfo(params[0], params[1])
675

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

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

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

688
    """
689
    return backend.GetAllInstancesInfo(params[0])
690

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

695
    """
696
    return backend.GetInstanceList(params[0])
697

    
698
  # node --------------------------
699

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

704
    """
705
    return netutils.IPAddress.Own(params[0])
706

    
707
  @staticmethod
708
  def perspective_node_info(params):
709
    """Query node information.
710

711
    """
712
    (vg_names, hv_names, excl_stor) = params
713
    return backend.GetNodeInfo(vg_names, hv_names, excl_stor)
714

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

719
    """
720
    backend.EtcHostsModify(params[0], params[1], params[2])
721

    
722
    return True
723

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

728
    """
729
    return backend.VerifyNode(params[0], params[1])
730

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

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

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

743
    """
744
    return backend.StartMasterDaemons(params[0])
745

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

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

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

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

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

766
    """
767
    return backend.StopMasterDaemons()
768

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

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

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

781
    """
782
    return backend.LeaveCluster(params[0])
783

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

788
    """
789
    return backend.NodeVolumes()
790

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

795
    """
796
    return backend.DemoteFromMC()
797

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

802
    """
803
    hypervisor_type = params[0]
804
    return backend.PowercycleNode(hypervisor_type)
805

    
806
  # cluster --------------------------
807

    
808
  @staticmethod
809
  def perspective_version(params):
810
    """Query version information.
811

812
    """
813
    return constants.PROTOCOL_VERSION
814

    
815
  @staticmethod
816
  def perspective_upload_file(params):
817
    """Upload a file.
818

819
    Note that the backend implementation imposes strict rules on which
820
    files are accepted.
821

822
    """
823
    return backend.UploadFile(*(params[0]))
824

    
825
  @staticmethod
826
  def perspective_master_info(params):
827
    """Query master information.
828

829
    """
830
    return backend.GetMasterInfo()
831

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

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

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

848
    """
849
    (cmd, ) = params
850

    
851
    return backend.RunRestrictedCmd(cmd)
852

    
853
  @staticmethod
854
  def perspective_write_ssconf_files(params):
855
    """Write ssconf files.
856

857
    """
858
    (values,) = params
859
    return ssconf.WriteSsconfFiles(values)
860

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

865
    """
866
    return utils.ReadWatcherPauseFile(pathutils.WATCHER_PAUSEFILE)
867

    
868
  @staticmethod
869
  def perspective_set_watcher_pause(params):
870
    """Set watcher pause.
871

872
    """
873
    (until, ) = params
874
    return backend.SetWatcherPause(until)
875

    
876
  # os -----------------------
877

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

882
    """
883
    return backend.DiagnoseOS()
884

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

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

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

898
    """
899
    required, name, checks, params = params
900
    return backend.ValidateOS(required, name, checks, params)
901

    
902
  # extstorage -----------------------
903

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

908
    """
909
    return backend.DiagnoseExtStorage()
910

    
911
  # hooks -----------------------
912

    
913
  @staticmethod
914
  def perspective_hooks_runner(params):
915
    """Run hook scripts.
916

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

    
922
  # iallocator -----------------
923

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

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

    
933
  # test -----------------------
934

    
935
  @staticmethod
936
  def perspective_test_delay(params):
937
    """Run test delay.
938

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

    
946
  # file storage ---------------
947

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

952
    """
953
    file_storage_dir = params[0]
954
    return backend.CreateFileStorageDir(file_storage_dir)
955

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

960
    """
961
    file_storage_dir = params[0]
962
    return backend.RemoveFileStorageDir(file_storage_dir)
963

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

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

    
974
  # jobs ------------------------
975

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

981
    """
982
    (file_name, content) = params
983
    return backend.JobQueueUpdate(file_name, content)
984

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

990
    """
991
    return backend.JobQueuePurge()
992

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

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

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

1007
    """
1008
    (flag, ) = params
1009

    
1010
    return jstore.SetDrainFlag(flag)
1011

    
1012
  # hypervisor ---------------
1013

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

1018
    """
1019
    (hvname, hvparams) = params
1020
    return backend.ValidateHVParams(hvname, hvparams)
1021

    
1022
  # Crypto
1023

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

1028
    """
1029
    (validity, ) = params
1030
    return backend.CreateX509Certificate(validity)
1031

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

1036
    """
1037
    (name, ) = params
1038
    return backend.RemoveX509Certificate(name)
1039

    
1040
  # Import and export
1041

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

1046
    """
1047
    (opts_s, instance, component, (dest, dest_args)) = params
1048

    
1049
    opts = objects.ImportExportOptions.FromDict(opts_s)
1050

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

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

1062
    """
1063
    (opts_s, host, port, instance, component, (source, source_args)) = params
1064

    
1065
    opts = objects.ImportExportOptions.FromDict(opts_s)
1066

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

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

1078
    """
1079
    return backend.GetImportExportStatus(params[0])
1080

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

1085
    """
1086
    return backend.AbortImportExport(params[0])
1087

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

1092
    """
1093
    return backend.CleanupImportExport(params[0])
1094

    
1095

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

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

    
1112

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

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

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

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

    
1141
  handler = NodeRequestHandler()
1142

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

    
1150
  return (mainloop, server)
1151

    
1152

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

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

    
1163

    
1164
def Main():
1165
  """Main function for the node daemon.
1166

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

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