Statistics
| Branch: | Tag: | Revision:

root / lib / server / noded.py @ a5ce2ea2

History | View | Annotate | Download (29.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

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

    
55

    
56
queue_lock = None
57

    
58

    
59
def _PrepareQueueLock():
60
  """Try to prepare the queue lock.
61

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

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

    
67
  if queue_lock is not None:
68
    return None
69

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

    
77

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

81
  """
82
  QUEUE_LOCK_TIMEOUT = 10
83

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

    
96
  return wrapper
97

    
98

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

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

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

    
111
  return ieioargs
112

    
113

    
114
class MlockallRequestExecutor(http.server.HttpServerRequestExecutor):
115
  """Subclass ensuring request handlers are locked in RAM.
116

117
  """
118
  def __init__(self, *args, **kwargs):
119
    utils.Mlockall()
120

    
121
    http.server.HttpServerRequestExecutor.__init__(self, *args, **kwargs)
122

    
123

    
124
class NodeRequestHandler(http.server.HttpServerHandler):
125
  """The server implementation.
126

127
  This class holds all methods exposed over the RPC interface.
128

129
  """
130
  # too many public methods, and unused args - all methods get params
131
  # due to the API
132
  # pylint: disable=R0904,W0613
133
  def __init__(self):
134
    http.server.HttpServerHandler.__init__(self)
135
    self.noded_pid = os.getpid()
136

    
137
  def HandleRequest(self, req):
138
    """Handle a request.
139

140
    """
141
    # FIXME: Remove HTTP_PUT in Ganeti 2.7
142
    if req.request_method.upper() not in (http.HTTP_PUT, http.HTTP_POST):
143
      raise http.HttpBadRequest("Only PUT and POST methods are supported")
144

    
145
    path = req.request_path
146
    if path.startswith("/"):
147
      path = path[1:]
148

    
149
    method = getattr(self, "perspective_%s" % path, None)
150
    if method is None:
151
      raise http.HttpNotFound()
152

    
153
    try:
154
      result = (True, method(serializer.LoadJson(req.request_body)))
155

    
156
    except backend.RPCFail, err:
157
      # our custom failure exception; str(err) works fine if the
158
      # exception was constructed with a single argument, and in
159
      # this case, err.message == err.args[0] == str(err)
160
      result = (False, str(err))
161
    except errors.QuitGanetiException, err:
162
      # Tell parent to quit
163
      logging.info("Shutting down the node daemon, arguments: %s",
164
                   str(err.args))
165
      os.kill(self.noded_pid, signal.SIGTERM)
166
      # And return the error's arguments, which must be already in
167
      # correct tuple format
168
      result = err.args
169
    except Exception, err:
170
      logging.exception("Error in RPC call")
171
      result = (False, "Error while executing backend function: %s" % str(err))
172

    
173
    return serializer.DumpJson(result)
174

    
175
  # the new block devices  --------------------------
176

    
177
  @staticmethod
178
  def perspective_blockdev_create(params):
179
    """Create a block device.
180

181
    """
182
    bdev_s, size, owner, on_primary, info = params
183
    bdev = objects.Disk.FromDict(bdev_s)
184
    if bdev is None:
185
      raise ValueError("can't unserialize data!")
186
    return backend.BlockdevCreate(bdev, size, owner, on_primary, info)
187

    
188
  @staticmethod
189
  def perspective_blockdev_pause_resume_sync(params):
190
    """Pause/resume sync of a block device.
191

192
    """
193
    disks_s, pause = params
194
    disks = [objects.Disk.FromDict(bdev_s) for bdev_s in disks_s]
195
    return backend.BlockdevPauseResumeSync(disks, pause)
196

    
197
  @staticmethod
198
  def perspective_blockdev_wipe(params):
199
    """Wipe a block device.
200

201
    """
202
    bdev_s, offset, size = params
203
    bdev = objects.Disk.FromDict(bdev_s)
204
    return backend.BlockdevWipe(bdev, offset, size)
205

    
206
  @staticmethod
207
  def perspective_blockdev_remove(params):
208
    """Remove a block device.
209

210
    """
211
    bdev_s = params[0]
212
    bdev = objects.Disk.FromDict(bdev_s)
213
    return backend.BlockdevRemove(bdev)
214

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

219
    """
220
    devlist = [(objects.Disk.FromDict(ds), uid) for ds, uid in params[0]]
221
    return backend.BlockdevRename(devlist)
222

    
223
  @staticmethod
224
  def perspective_blockdev_assemble(params):
225
    """Assemble a block device.
226

227
    """
228
    bdev_s, owner, on_primary, idx = params
229
    bdev = objects.Disk.FromDict(bdev_s)
230
    if bdev is None:
231
      raise ValueError("can't unserialize data!")
232
    return backend.BlockdevAssemble(bdev, owner, on_primary, idx)
233

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

238
    """
239
    bdev_s = params[0]
240
    bdev = objects.Disk.FromDict(bdev_s)
241
    if bdev is None:
242
      raise ValueError("can't unserialize data!")
243
    return backend.BlockdevShutdown(bdev)
244

    
245
  @staticmethod
246
  def perspective_blockdev_addchildren(params):
247
    """Add a child to a mirror device.
248

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

252
    """
253
    bdev_s, ndev_s = params
254
    bdev = objects.Disk.FromDict(bdev_s)
255
    ndevs = [objects.Disk.FromDict(disk_s) for disk_s in ndev_s]
256
    if bdev is None or ndevs.count(None) > 0:
257
      raise ValueError("can't unserialize data!")
258
    return backend.BlockdevAddchildren(bdev, ndevs)
259

    
260
  @staticmethod
261
  def perspective_blockdev_removechildren(params):
262
    """Remove a child from a mirror device.
263

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

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

    
275
  @staticmethod
276
  def perspective_blockdev_getmirrorstatus(params):
277
    """Return the mirror status for a list of disks.
278

279
    """
280
    disks = [objects.Disk.FromDict(dsk_s)
281
             for dsk_s in params[0]]
282
    return [status.ToDict()
283
            for status in backend.BlockdevGetmirrorstatus(disks)]
284

    
285
  @staticmethod
286
  def perspective_blockdev_getmirrorstatus_multi(params):
287
    """Return the mirror status for a list of disks.
288

289
    """
290
    (node_disks, ) = params
291

    
292
    disks = [objects.Disk.FromDict(dsk_s) for dsk_s in node_disks]
293

    
294
    result = []
295

    
296
    for (success, status) in backend.BlockdevGetmirrorstatusMulti(disks):
297
      if success:
298
        result.append((success, status.ToDict()))
299
      else:
300
        result.append((success, status))
301

    
302
    return result
303

    
304
  @staticmethod
305
  def perspective_blockdev_find(params):
306
    """Expose the FindBlockDevice functionality for a disk.
307

308
    This will try to find but not activate a disk.
309

310
    """
311
    disk = objects.Disk.FromDict(params[0])
312

    
313
    result = backend.BlockdevFind(disk)
314
    if result is None:
315
      return None
316

    
317
    return result.ToDict()
318

    
319
  @staticmethod
320
  def perspective_blockdev_snapshot(params):
321
    """Create a snapshot device.
322

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

327
    """
328
    cfbd = objects.Disk.FromDict(params[0])
329
    return backend.BlockdevSnapshot(cfbd)
330

    
331
  @staticmethod
332
  def perspective_blockdev_grow(params):
333
    """Grow a stack of devices.
334

335
    """
336
    if len(params) < 4:
337
      raise ValueError("Received only 3 parameters in blockdev_grow,"
338
                       " old master?")
339
    cfbd = objects.Disk.FromDict(params[0])
340
    amount = params[1]
341
    dryrun = params[2]
342
    backingstore = params[3]
343
    return backend.BlockdevGrow(cfbd, amount, dryrun, backingstore)
344

    
345
  @staticmethod
346
  def perspective_blockdev_close(params):
347
    """Closes the given block devices.
348

349
    """
350
    disks = [objects.Disk.FromDict(cf) for cf in params[1]]
351
    return backend.BlockdevClose(params[0], disks)
352

    
353
  @staticmethod
354
  def perspective_blockdev_getsize(params):
355
    """Compute the sizes of the given block devices.
356

357
    """
358
    disks = [objects.Disk.FromDict(cf) for cf in params[0]]
359
    return backend.BlockdevGetsize(disks)
360

    
361
  @staticmethod
362
  def perspective_blockdev_export(params):
363
    """Compute the sizes of the given block devices.
364

365
    """
366
    disk = objects.Disk.FromDict(params[0])
367
    dest_node, dest_path, cluster_name = params[1:]
368
    return backend.BlockdevExport(disk, dest_node, dest_path, cluster_name)
369

    
370
  # blockdev/drbd specific methods ----------
371

    
372
  @staticmethod
373
  def perspective_drbd_disconnect_net(params):
374
    """Disconnects the network connection of drbd disks.
375

376
    Note that this is only valid for drbd disks, so the members of the
377
    disk list must all be drbd devices.
378

379
    """
380
    nodes_ip, disks = params
381
    disks = [objects.Disk.FromDict(cf) for cf in disks]
382
    return backend.DrbdDisconnectNet(nodes_ip, disks)
383

    
384
  @staticmethod
385
  def perspective_drbd_attach_net(params):
386
    """Attaches the network connection of drbd disks.
387

388
    Note that this is only valid for drbd disks, so the members of the
389
    disk list must all be drbd devices.
390

391
    """
392
    nodes_ip, disks, instance_name, multimaster = params
393
    disks = [objects.Disk.FromDict(cf) for cf in disks]
394
    return backend.DrbdAttachNet(nodes_ip, disks,
395
                                     instance_name, multimaster)
396

    
397
  @staticmethod
398
  def perspective_drbd_wait_sync(params):
399
    """Wait until DRBD disks are synched.
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.DrbdWaitSync(nodes_ip, disks)
408

    
409
  @staticmethod
410
  def perspective_drbd_helper(params):
411
    """Query drbd helper.
412

413
    """
414
    return backend.GetDrbdUsermodeHelper()
415

    
416
  # export/import  --------------------------
417

    
418
  @staticmethod
419
  def perspective_finalize_export(params):
420
    """Expose the finalize export functionality.
421

422
    """
423
    instance = objects.Instance.FromDict(params[0])
424

    
425
    snap_disks = []
426
    for disk in params[1]:
427
      if isinstance(disk, bool):
428
        snap_disks.append(disk)
429
      else:
430
        snap_disks.append(objects.Disk.FromDict(disk))
431

    
432
    return backend.FinalizeExport(instance, snap_disks)
433

    
434
  @staticmethod
435
  def perspective_export_info(params):
436
    """Query information about an existing export on this node.
437

438
    The given path may not contain an export, in which case we return
439
    None.
440

441
    """
442
    path = params[0]
443
    return backend.ExportInfo(path)
444

    
445
  @staticmethod
446
  def perspective_export_list(params):
447
    """List the available exports on this node.
448

449
    Note that as opposed to export_info, which may query data about an
450
    export in any path, this only queries the standard Ganeti path
451
    (pathutils.EXPORT_DIR).
452

453
    """
454
    return backend.ListExports()
455

    
456
  @staticmethod
457
  def perspective_export_remove(params):
458
    """Remove an export.
459

460
    """
461
    export = params[0]
462
    return backend.RemoveExport(export)
463

    
464
  # block device ---------------------
465
  @staticmethod
466
  def perspective_bdev_sizes(params):
467
    """Query the list of block devices
468

469
    """
470
    devices = params[0]
471
    return backend.GetBlockDevSizes(devices)
472

    
473
  # volume  --------------------------
474

    
475
  @staticmethod
476
  def perspective_lv_list(params):
477
    """Query the list of logical volumes in a given volume group.
478

479
    """
480
    vgname = params[0]
481
    return backend.GetVolumeList(vgname)
482

    
483
  @staticmethod
484
  def perspective_vg_list(params):
485
    """Query the list of volume groups.
486

487
    """
488
    return backend.ListVolumeGroups()
489

    
490
  # Storage --------------------------
491

    
492
  @staticmethod
493
  def perspective_storage_list(params):
494
    """Get list of storage units.
495

496
    """
497
    (su_name, su_args, name, fields) = params
498
    return storage.GetStorage(su_name, *su_args).List(name, fields)
499

    
500
  @staticmethod
501
  def perspective_storage_modify(params):
502
    """Modify a storage unit.
503

504
    """
505
    (su_name, su_args, name, changes) = params
506
    return storage.GetStorage(su_name, *su_args).Modify(name, changes)
507

    
508
  @staticmethod
509
  def perspective_storage_execute(params):
510
    """Execute an operation on a storage unit.
511

512
    """
513
    (su_name, su_args, name, op) = params
514
    return storage.GetStorage(su_name, *su_args).Execute(name, op)
515

    
516
  # bridge  --------------------------
517

    
518
  @staticmethod
519
  def perspective_bridges_exist(params):
520
    """Check if all bridges given exist on this node.
521

522
    """
523
    bridges_list = params[0]
524
    return backend.BridgesExist(bridges_list)
525

    
526
  # instance  --------------------------
527

    
528
  @staticmethod
529
  def perspective_instance_os_add(params):
530
    """Install an OS on a given instance.
531

532
    """
533
    inst_s = params[0]
534
    inst = objects.Instance.FromDict(inst_s)
535
    reinstall = params[1]
536
    debug = params[2]
537
    return backend.InstanceOsAdd(inst, reinstall, debug)
538

    
539
  @staticmethod
540
  def perspective_instance_run_rename(params):
541
    """Runs the OS rename script for an instance.
542

543
    """
544
    inst_s, old_name, debug = params
545
    inst = objects.Instance.FromDict(inst_s)
546
    return backend.RunRenameInstance(inst, old_name, debug)
547

    
548
  @staticmethod
549
  def perspective_instance_shutdown(params):
550
    """Shutdown an instance.
551

552
    """
553
    instance = objects.Instance.FromDict(params[0])
554
    timeout = params[1]
555
    return backend.InstanceShutdown(instance, timeout)
556

    
557
  @staticmethod
558
  def perspective_instance_start(params):
559
    """Start an instance.
560

561
    """
562
    (instance_name, startup_paused) = params
563
    instance = objects.Instance.FromDict(instance_name)
564
    return backend.StartInstance(instance, startup_paused)
565

    
566
  @staticmethod
567
  def perspective_migration_info(params):
568
    """Gather information about an instance to be migrated.
569

570
    """
571
    instance = objects.Instance.FromDict(params[0])
572
    return backend.MigrationInfo(instance)
573

    
574
  @staticmethod
575
  def perspective_accept_instance(params):
576
    """Prepare the node to accept an instance.
577

578
    """
579
    instance, info, target = params
580
    instance = objects.Instance.FromDict(instance)
581
    return backend.AcceptInstance(instance, info, target)
582

    
583
  @staticmethod
584
  def perspective_instance_finalize_migration_dst(params):
585
    """Finalize the instance migration on the destination node.
586

587
    """
588
    instance, info, success = params
589
    instance = objects.Instance.FromDict(instance)
590
    return backend.FinalizeMigrationDst(instance, info, success)
591

    
592
  @staticmethod
593
  def perspective_instance_migrate(params):
594
    """Migrates an instance.
595

596
    """
597
    instance, target, live = params
598
    instance = objects.Instance.FromDict(instance)
599
    return backend.MigrateInstance(instance, target, live)
600

    
601
  @staticmethod
602
  def perspective_instance_finalize_migration_src(params):
603
    """Finalize the instance migration on the source node.
604

605
    """
606
    instance, success, live = params
607
    instance = objects.Instance.FromDict(instance)
608
    return backend.FinalizeMigrationSource(instance, success, live)
609

    
610
  @staticmethod
611
  def perspective_instance_get_migration_status(params):
612
    """Reports migration status.
613

614
    """
615
    instance = objects.Instance.FromDict(params[0])
616
    return backend.GetMigrationStatus(instance).ToDict()
617

    
618
  @staticmethod
619
  def perspective_instance_reboot(params):
620
    """Reboot an instance.
621

622
    """
623
    instance = objects.Instance.FromDict(params[0])
624
    reboot_type = params[1]
625
    shutdown_timeout = params[2]
626
    return backend.InstanceReboot(instance, reboot_type, shutdown_timeout)
627

    
628
  @staticmethod
629
  def perspective_instance_balloon_memory(params):
630
    """Modify instance runtime memory.
631

632
    """
633
    instance_dict, memory = params
634
    instance = objects.Instance.FromDict(instance_dict)
635
    return backend.InstanceBalloonMemory(instance, memory)
636

    
637
  @staticmethod
638
  def perspective_instance_info(params):
639
    """Query instance information.
640

641
    """
642
    return backend.GetInstanceInfo(params[0], params[1])
643

    
644
  @staticmethod
645
  def perspective_instance_migratable(params):
646
    """Query whether the specified instance can be migrated.
647

648
    """
649
    instance = objects.Instance.FromDict(params[0])
650
    return backend.GetInstanceMigratable(instance)
651

    
652
  @staticmethod
653
  def perspective_all_instances_info(params):
654
    """Query information about all instances.
655

656
    """
657
    return backend.GetAllInstancesInfo(params[0])
658

    
659
  @staticmethod
660
  def perspective_instance_list(params):
661
    """Query the list of running instances.
662

663
    """
664
    return backend.GetInstanceList(params[0])
665

    
666
  # node --------------------------
667

    
668
  @staticmethod
669
  def perspective_node_has_ip_address(params):
670
    """Checks if a node has the given ip address.
671

672
    """
673
    return netutils.IPAddress.Own(params[0])
674

    
675
  @staticmethod
676
  def perspective_node_info(params):
677
    """Query node information.
678

679
    """
680
    (vg_names, hv_names) = params
681
    return backend.GetNodeInfo(vg_names, hv_names)
682

    
683
  @staticmethod
684
  def perspective_etc_hosts_modify(params):
685
    """Modify a node entry in /etc/hosts.
686

687
    """
688
    backend.EtcHostsModify(params[0], params[1], params[2])
689

    
690
    return True
691

    
692
  @staticmethod
693
  def perspective_node_verify(params):
694
    """Run a verify sequence on this node.
695

696
    """
697
    return backend.VerifyNode(params[0], params[1])
698

    
699
  @staticmethod
700
  def perspective_node_start_master_daemons(params):
701
    """Start the master daemons on this node.
702

703
    """
704
    return backend.StartMasterDaemons(params[0])
705

    
706
  @staticmethod
707
  def perspective_node_activate_master_ip(params):
708
    """Activate the master IP on this node.
709

710
    """
711
    master_params = objects.MasterNetworkParameters.FromDict(params[0])
712
    return backend.ActivateMasterIp(master_params, params[1])
713

    
714
  @staticmethod
715
  def perspective_node_deactivate_master_ip(params):
716
    """Deactivate the master IP on this node.
717

718
    """
719
    master_params = objects.MasterNetworkParameters.FromDict(params[0])
720
    return backend.DeactivateMasterIp(master_params, params[1])
721

    
722
  @staticmethod
723
  def perspective_node_stop_master(params):
724
    """Stops master daemons on this node.
725

726
    """
727
    return backend.StopMasterDaemons()
728

    
729
  @staticmethod
730
  def perspective_node_change_master_netmask(params):
731
    """Change the master IP netmask.
732

733
    """
734
    return backend.ChangeMasterNetmask(params[0], params[1], params[2],
735
                                       params[3])
736

    
737
  @staticmethod
738
  def perspective_node_leave_cluster(params):
739
    """Cleanup after leaving a cluster.
740

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

    
744
  @staticmethod
745
  def perspective_node_volumes(params):
746
    """Query the list of all logical volume groups.
747

748
    """
749
    return backend.NodeVolumes()
750

    
751
  @staticmethod
752
  def perspective_node_demote_from_mc(params):
753
    """Demote a node from the master candidate role.
754

755
    """
756
    return backend.DemoteFromMC()
757

    
758
  @staticmethod
759
  def perspective_node_powercycle(params):
760
    """Tries to powercycle the nod.
761

762
    """
763
    hypervisor_type = params[0]
764
    return backend.PowercycleNode(hypervisor_type)
765

    
766
  # cluster --------------------------
767

    
768
  @staticmethod
769
  def perspective_version(params):
770
    """Query version information.
771

772
    """
773
    return constants.PROTOCOL_VERSION
774

    
775
  @staticmethod
776
  def perspective_upload_file(params):
777
    """Upload a file.
778

779
    Note that the backend implementation imposes strict rules on which
780
    files are accepted.
781

782
    """
783
    return backend.UploadFile(*(params[0]))
784

    
785
  @staticmethod
786
  def perspective_master_info(params):
787
    """Query master information.
788

789
    """
790
    return backend.GetMasterInfo()
791

    
792
  @staticmethod
793
  def perspective_run_oob(params):
794
    """Runs oob on node.
795

796
    """
797
    output = backend.RunOob(params[0], params[1], params[2], params[3])
798
    if output:
799
      result = serializer.LoadJson(output)
800
    else:
801
      result = None
802
    return result
803

    
804
  @staticmethod
805
  def perspective_write_ssconf_files(params):
806
    """Write ssconf files.
807

808
    """
809
    (values,) = params
810
    return backend.WriteSsconfFiles(values)
811

    
812
  # os -----------------------
813

    
814
  @staticmethod
815
  def perspective_os_diagnose(params):
816
    """Query detailed information about existing OSes.
817

818
    """
819
    return backend.DiagnoseOS()
820

    
821
  @staticmethod
822
  def perspective_os_get(params):
823
    """Query information about a given OS.
824

825
    """
826
    name = params[0]
827
    os_obj = backend.OSFromDisk(name)
828
    return os_obj.ToDict()
829

    
830
  @staticmethod
831
  def perspective_os_validate(params):
832
    """Run a given OS' validation routine.
833

834
    """
835
    required, name, checks, params = params
836
    return backend.ValidateOS(required, name, checks, params)
837

    
838
  # hooks -----------------------
839

    
840
  @staticmethod
841
  def perspective_hooks_runner(params):
842
    """Run hook scripts.
843

844
    """
845
    hpath, phase, env = params
846
    hr = backend.HooksRunner()
847
    return hr.RunHooks(hpath, phase, env)
848

    
849
  # iallocator -----------------
850

    
851
  @staticmethod
852
  def perspective_iallocator_runner(params):
853
    """Run an iallocator script.
854

855
    """
856
    name, idata = params
857
    iar = backend.IAllocatorRunner()
858
    return iar.Run(name, idata)
859

    
860
  # test -----------------------
861

    
862
  @staticmethod
863
  def perspective_test_delay(params):
864
    """Run test delay.
865

866
    """
867
    duration = params[0]
868
    status, rval = utils.TestDelay(duration)
869
    if not status:
870
      raise backend.RPCFail(rval)
871
    return rval
872

    
873
  # file storage ---------------
874

    
875
  @staticmethod
876
  def perspective_file_storage_dir_create(params):
877
    """Create the file storage directory.
878

879
    """
880
    file_storage_dir = params[0]
881
    return backend.CreateFileStorageDir(file_storage_dir)
882

    
883
  @staticmethod
884
  def perspective_file_storage_dir_remove(params):
885
    """Remove the file storage directory.
886

887
    """
888
    file_storage_dir = params[0]
889
    return backend.RemoveFileStorageDir(file_storage_dir)
890

    
891
  @staticmethod
892
  def perspective_file_storage_dir_rename(params):
893
    """Rename the file storage directory.
894

895
    """
896
    old_file_storage_dir = params[0]
897
    new_file_storage_dir = params[1]
898
    return backend.RenameFileStorageDir(old_file_storage_dir,
899
                                        new_file_storage_dir)
900

    
901
  # jobs ------------------------
902

    
903
  @staticmethod
904
  @_RequireJobQueueLock
905
  def perspective_jobqueue_update(params):
906
    """Update job queue.
907

908
    """
909
    (file_name, content) = params
910
    return backend.JobQueueUpdate(file_name, content)
911

    
912
  @staticmethod
913
  @_RequireJobQueueLock
914
  def perspective_jobqueue_purge(params):
915
    """Purge job queue.
916

917
    """
918
    return backend.JobQueuePurge()
919

    
920
  @staticmethod
921
  @_RequireJobQueueLock
922
  def perspective_jobqueue_rename(params):
923
    """Rename a job queue file.
924

925
    """
926
    # TODO: What if a file fails to rename?
927
    return [backend.JobQueueRename(old, new) for old, new in params[0]]
928

    
929
  # hypervisor ---------------
930

    
931
  @staticmethod
932
  def perspective_hypervisor_validate_params(params):
933
    """Validate the hypervisor parameters.
934

935
    """
936
    (hvname, hvparams) = params
937
    return backend.ValidateHVParams(hvname, hvparams)
938

    
939
  # Crypto
940

    
941
  @staticmethod
942
  def perspective_x509_cert_create(params):
943
    """Creates a new X509 certificate for SSL/TLS.
944

945
    """
946
    (validity, ) = params
947
    return backend.CreateX509Certificate(validity)
948

    
949
  @staticmethod
950
  def perspective_x509_cert_remove(params):
951
    """Removes a X509 certificate.
952

953
    """
954
    (name, ) = params
955
    return backend.RemoveX509Certificate(name)
956

    
957
  # Import and export
958

    
959
  @staticmethod
960
  def perspective_import_start(params):
961
    """Starts an import daemon.
962

963
    """
964
    (opts_s, instance, component, (dest, dest_args)) = params
965

    
966
    opts = objects.ImportExportOptions.FromDict(opts_s)
967

    
968
    return backend.StartImportExportDaemon(constants.IEM_IMPORT, opts,
969
                                           None, None,
970
                                           objects.Instance.FromDict(instance),
971
                                           component, dest,
972
                                           _DecodeImportExportIO(dest,
973
                                                                 dest_args))
974

    
975
  @staticmethod
976
  def perspective_export_start(params):
977
    """Starts an export daemon.
978

979
    """
980
    (opts_s, host, port, instance, component, (source, source_args)) = params
981

    
982
    opts = objects.ImportExportOptions.FromDict(opts_s)
983

    
984
    return backend.StartImportExportDaemon(constants.IEM_EXPORT, opts,
985
                                           host, port,
986
                                           objects.Instance.FromDict(instance),
987
                                           component, source,
988
                                           _DecodeImportExportIO(source,
989
                                                                 source_args))
990

    
991
  @staticmethod
992
  def perspective_impexp_status(params):
993
    """Retrieves the status of an import or export daemon.
994

995
    """
996
    return backend.GetImportExportStatus(params[0])
997

    
998
  @staticmethod
999
  def perspective_impexp_abort(params):
1000
    """Aborts an import or export.
1001

1002
    """
1003
    return backend.AbortImportExport(params[0])
1004

    
1005
  @staticmethod
1006
  def perspective_impexp_cleanup(params):
1007
    """Cleans up after an import or export.
1008

1009
    """
1010
    return backend.CleanupImportExport(params[0])
1011

    
1012

    
1013
def CheckNoded(_, args):
1014
  """Initial checks whether to run or exit with a failure.
1015

1016
  """
1017
  if args: # noded doesn't take any arguments
1018
    print >> sys.stderr, ("Usage: %s [-f] [-d] [-p port] [-b ADDRESS]" %
1019
                          sys.argv[0])
1020
    sys.exit(constants.EXIT_FAILURE)
1021
  try:
1022
    codecs.lookup("string-escape")
1023
  except LookupError:
1024
    print >> sys.stderr, ("Can't load the string-escape code which is part"
1025
                          " of the Python installation. Is your installation"
1026
                          " complete/correct? Aborting.")
1027
    sys.exit(constants.EXIT_FAILURE)
1028

    
1029

    
1030
def PrepNoded(options, _):
1031
  """Preparation node daemon function, executed with the PID file held.
1032

1033
  """
1034
  if options.mlock:
1035
    request_executor_class = MlockallRequestExecutor
1036
    try:
1037
      utils.Mlockall()
1038
    except errors.NoCtypesError:
1039
      logging.warning("Cannot set memory lock, ctypes module not found")
1040
      request_executor_class = http.server.HttpServerRequestExecutor
1041
  else:
1042
    request_executor_class = http.server.HttpServerRequestExecutor
1043

    
1044
  # Read SSL certificate
1045
  if options.ssl:
1046
    ssl_params = http.HttpSslParams(ssl_key_path=options.ssl_key,
1047
                                    ssl_cert_path=options.ssl_cert)
1048
  else:
1049
    ssl_params = None
1050

    
1051
  err = _PrepareQueueLock()
1052
  if err is not None:
1053
    # this might be some kind of file-system/permission error; while
1054
    # this breaks the job queue functionality, we shouldn't prevent
1055
    # startup of the whole node daemon because of this
1056
    logging.critical("Can't init/verify the queue, proceeding anyway: %s", err)
1057

    
1058
  handler = NodeRequestHandler()
1059

    
1060
  mainloop = daemon.Mainloop()
1061
  server = \
1062
    http.server.HttpServer(mainloop, options.bind_address, options.port,
1063
                           handler, ssl_params=ssl_params, ssl_verify_peer=True,
1064
                           request_executor_class=request_executor_class)
1065
  server.Start()
1066

    
1067
  return (mainloop, server)
1068

    
1069

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

1073
  """
1074
  (mainloop, server) = prep_data
1075
  try:
1076
    mainloop.Run()
1077
  finally:
1078
    server.Stop()
1079

    
1080

    
1081
def Main():
1082
  """Main function for the node daemon.
1083

1084
  """
1085
  parser = OptionParser(description="Ganeti node daemon",
1086
                        usage="%prog [-f] [-d] [-p port] [-b ADDRESS]",
1087
                        version="%%prog (ganeti) %s" %
1088
                        constants.RELEASE_VERSION)
1089
  parser.add_option("--no-mlock", dest="mlock",
1090
                    help="Do not mlock the node memory in ram",
1091
                    default=True, action="store_false")
1092

    
1093
  daemon.GenericMain(constants.NODED, parser, CheckNoded, PrepNoded, ExecNoded,
1094
                     default_ssl_cert=pathutils.NODED_CERT_FILE,
1095
                     default_ssl_key=pathutils.NODED_CERT_FILE,
1096
                     console_logging=True)