Statistics
| Branch: | Tag: | Revision:

root / lib / server / noded.py @ a59faf4b

History | View | Annotate | Download (27.3 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2010, 2011 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-msg=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

    
37
from optparse import OptionParser
38

    
39
from ganeti import backend
40
from ganeti import constants
41
from ganeti import objects
42
from ganeti import errors
43
from ganeti import jstore
44
from ganeti import daemon
45
from ganeti import http
46
from ganeti import utils
47
from ganeti import storage
48
from ganeti import serializer
49
from ganeti import netutils
50

    
51
import ganeti.http.server # pylint: disable-msg=W0611
52

    
53

    
54
queue_lock = None
55

    
56

    
57
def _PrepareQueueLock():
58
  """Try to prepare the queue lock.
59

60
  @return: None for success, otherwise an exception object
61

62
  """
63
  global queue_lock # pylint: disable-msg=W0603
64

    
65
  if queue_lock is not None:
66
    return None
67

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

    
75

    
76
def _RequireJobQueueLock(fn):
77
  """Decorator for job queue manipulating functions.
78

79
  """
80
  QUEUE_LOCK_TIMEOUT = 10
81

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

    
94
  return wrapper
95

    
96

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

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

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

    
109
  return ieioargs
110

    
111

    
112
class MlockallRequestExecutor(http.server.HttpServerRequestExecutor):
113
  """Custom Request Executor class that ensures NodeHttpServer children are
114
  locked in ram.
115

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

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

    
122

    
123
class NodeHttpServer(http.server.HttpServer):
124
  """The server implementation.
125

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

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

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

139
    """
140
    if req.request_method.upper() != http.HTTP_PUT:
141
      raise http.HttpBadRequest()
142

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

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

    
151
    try:
152
      result = (True, method(serializer.LoadJson(req.request_body)))
153

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

    
171
    return serializer.DumpJson(result, indent=False)
172

    
173
  # the new block devices  --------------------------
174

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

287
    """
288
    (node_disks, ) = params
289

    
290
    node_name = netutils.Hostname.GetSysName()
291

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

    
295
    result = []
296

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

    
303
    return result
304

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

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

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

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

    
318
    return result.ToDict()
319

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

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

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

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

336
    """
337
    cfbd = objects.Disk.FromDict(params[0])
338
    amount = params[1]
339
    dryrun = params[2]
340
    return backend.BlockdevGrow(cfbd, amount, dryrun)
341

    
342
  @staticmethod
343
  def perspective_blockdev_close(params):
344
    """Closes the given block devices.
345

346
    """
347
    disks = [objects.Disk.FromDict(cf) for cf in params[1]]
348
    return backend.BlockdevClose(params[0], disks)
349

    
350
  @staticmethod
351
  def perspective_blockdev_getsize(params):
352
    """Compute the sizes of the given block devices.
353

354
    """
355
    disks = [objects.Disk.FromDict(cf) for cf in params[0]]
356
    return backend.BlockdevGetsize(disks)
357

    
358
  @staticmethod
359
  def perspective_blockdev_export(params):
360
    """Compute the sizes of the given block devices.
361

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

    
367
  # blockdev/drbd specific methods ----------
368

    
369
  @staticmethod
370
  def perspective_drbd_disconnect_net(params):
371
    """Disconnects the network connection of drbd disks.
372

373
    Note that this is only valid for drbd disks, so the members of the
374
    disk list must all be drbd devices.
375

376
    """
377
    nodes_ip, disks = params
378
    disks = [objects.Disk.FromDict(cf) for cf in disks]
379
    return backend.DrbdDisconnectNet(nodes_ip, disks)
380

    
381
  @staticmethod
382
  def perspective_drbd_attach_net(params):
383
    """Attaches the network connection of drbd disks.
384

385
    Note that this is only valid for drbd disks, so the members of the
386
    disk list must all be drbd devices.
387

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

    
394
  @staticmethod
395
  def perspective_drbd_wait_sync(params):
396
    """Wait until DRBD disks are synched.
397

398
    Note that this is only valid for drbd disks, so the members of the
399
    disk list must all be drbd devices.
400

401
    """
402
    nodes_ip, disks = params
403
    disks = [objects.Disk.FromDict(cf) for cf in disks]
404
    return backend.DrbdWaitSync(nodes_ip, disks)
405

    
406
  @staticmethod
407
  def perspective_drbd_helper(params):
408
    """Query drbd helper.
409

410
    """
411
    return backend.GetDrbdUsermodeHelper()
412

    
413
  # export/import  --------------------------
414

    
415
  @staticmethod
416
  def perspective_finalize_export(params):
417
    """Expose the finalize export functionality.
418

419
    """
420
    instance = objects.Instance.FromDict(params[0])
421

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

    
429
    return backend.FinalizeExport(instance, snap_disks)
430

    
431
  @staticmethod
432
  def perspective_export_info(params):
433
    """Query information about an existing export on this node.
434

435
    The given path may not contain an export, in which case we return
436
    None.
437

438
    """
439
    path = params[0]
440
    return backend.ExportInfo(path)
441

    
442
  @staticmethod
443
  def perspective_export_list(params):
444
    """List the available exports on this node.
445

446
    Note that as opposed to export_info, which may query data about an
447
    export in any path, this only queries the standard Ganeti path
448
    (constants.EXPORT_DIR).
449

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

    
453
  @staticmethod
454
  def perspective_export_remove(params):
455
    """Remove an export.
456

457
    """
458
    export = params[0]
459
    return backend.RemoveExport(export)
460

    
461
  # block device ---------------------
462
  @staticmethod
463
  def perspective_bdev_sizes(params):
464
    """Query the list of block devices
465

466
    """
467
    devices = params[0]
468
    return backend.GetBlockDevSizes(devices)
469

    
470
  # volume  --------------------------
471

    
472
  @staticmethod
473
  def perspective_lv_list(params):
474
    """Query the list of logical volumes in a given volume group.
475

476
    """
477
    vgname = params[0]
478
    return backend.GetVolumeList(vgname)
479

    
480
  @staticmethod
481
  def perspective_vg_list(params):
482
    """Query the list of volume groups.
483

484
    """
485
    return backend.ListVolumeGroups()
486

    
487
  # Storage --------------------------
488

    
489
  @staticmethod
490
  def perspective_storage_list(params):
491
    """Get list of storage units.
492

493
    """
494
    (su_name, su_args, name, fields) = params
495
    return storage.GetStorage(su_name, *su_args).List(name, fields)
496

    
497
  @staticmethod
498
  def perspective_storage_modify(params):
499
    """Modify a storage unit.
500

501
    """
502
    (su_name, su_args, name, changes) = params
503
    return storage.GetStorage(su_name, *su_args).Modify(name, changes)
504

    
505
  @staticmethod
506
  def perspective_storage_execute(params):
507
    """Execute an operation on a storage unit.
508

509
    """
510
    (su_name, su_args, name, op) = params
511
    return storage.GetStorage(su_name, *su_args).Execute(name, op)
512

    
513
  # bridge  --------------------------
514

    
515
  @staticmethod
516
  def perspective_bridges_exist(params):
517
    """Check if all bridges given exist on this node.
518

519
    """
520
    bridges_list = params[0]
521
    return backend.BridgesExist(bridges_list)
522

    
523
  # instance  --------------------------
524

    
525
  @staticmethod
526
  def perspective_instance_os_add(params):
527
    """Install an OS on a given instance.
528

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

    
536
  @staticmethod
537
  def perspective_instance_run_rename(params):
538
    """Runs the OS rename script for an instance.
539

540
    """
541
    inst_s, old_name, debug = params
542
    inst = objects.Instance.FromDict(inst_s)
543
    return backend.RunRenameInstance(inst, old_name, debug)
544

    
545
  @staticmethod
546
  def perspective_instance_shutdown(params):
547
    """Shutdown an instance.
548

549
    """
550
    instance = objects.Instance.FromDict(params[0])
551
    timeout = params[1]
552
    return backend.InstanceShutdown(instance, timeout)
553

    
554
  @staticmethod
555
  def perspective_instance_start(params):
556
    """Start an instance.
557

558
    """
559
    instance = objects.Instance.FromDict(params[0])
560
    return backend.StartInstance(instance)
561

    
562
  @staticmethod
563
  def perspective_migration_info(params):
564
    """Gather information about an instance to be migrated.
565

566
    """
567
    instance = objects.Instance.FromDict(params[0])
568
    return backend.MigrationInfo(instance)
569

    
570
  @staticmethod
571
  def perspective_accept_instance(params):
572
    """Prepare the node to accept an instance.
573

574
    """
575
    instance, info, target = params
576
    instance = objects.Instance.FromDict(instance)
577
    return backend.AcceptInstance(instance, info, target)
578

    
579
  @staticmethod
580
  def perspective_finalize_migration(params):
581
    """Finalize the instance migration.
582

583
    """
584
    instance, info, success = params
585
    instance = objects.Instance.FromDict(instance)
586
    return backend.FinalizeMigration(instance, info, success)
587

    
588
  @staticmethod
589
  def perspective_instance_migrate(params):
590
    """Migrates an instance.
591

592
    """
593
    instance, target, live = params
594
    instance = objects.Instance.FromDict(instance)
595
    return backend.MigrateInstance(instance, target, live)
596

    
597
  @staticmethod
598
  def perspective_instance_reboot(params):
599
    """Reboot an instance.
600

601
    """
602
    instance = objects.Instance.FromDict(params[0])
603
    reboot_type = params[1]
604
    shutdown_timeout = params[2]
605
    return backend.InstanceReboot(instance, reboot_type, shutdown_timeout)
606

    
607
  @staticmethod
608
  def perspective_instance_info(params):
609
    """Query instance information.
610

611
    """
612
    return backend.GetInstanceInfo(params[0], params[1])
613

    
614
  @staticmethod
615
  def perspective_instance_migratable(params):
616
    """Query whether the specified instance can be migrated.
617

618
    """
619
    instance = objects.Instance.FromDict(params[0])
620
    return backend.GetInstanceMigratable(instance)
621

    
622
  @staticmethod
623
  def perspective_all_instances_info(params):
624
    """Query information about all instances.
625

626
    """
627
    return backend.GetAllInstancesInfo(params[0])
628

    
629
  @staticmethod
630
  def perspective_instance_list(params):
631
    """Query the list of running instances.
632

633
    """
634
    return backend.GetInstanceList(params[0])
635

    
636
  # node --------------------------
637

    
638
  @staticmethod
639
  def perspective_node_tcp_ping(params):
640
    """Do a TcpPing on the remote node.
641

642
    """
643
    return netutils.TcpPing(params[1], params[2], timeout=params[3],
644
                            live_port_needed=params[4], source=params[0])
645

    
646
  @staticmethod
647
  def perspective_node_has_ip_address(params):
648
    """Checks if a node has the given ip address.
649

650
    """
651
    return netutils.IPAddress.Own(params[0])
652

    
653
  @staticmethod
654
  def perspective_node_info(params):
655
    """Query node information.
656

657
    """
658
    vgname, hypervisor_type = params
659
    return backend.GetNodeInfo(vgname, hypervisor_type)
660

    
661
  @staticmethod
662
  def perspective_etc_hosts_modify(params):
663
    """Modify a node entry in /etc/hosts.
664

665
    """
666
    backend.EtcHostsModify(params[0], params[1], params[2])
667

    
668
    return True
669

    
670
  @staticmethod
671
  def perspective_node_verify(params):
672
    """Run a verify sequence on this node.
673

674
    """
675
    return backend.VerifyNode(params[0], params[1])
676

    
677
  @staticmethod
678
  def perspective_node_start_master(params):
679
    """Promote this node to master status.
680

681
    """
682
    return backend.StartMaster(params[0], params[1])
683

    
684
  @staticmethod
685
  def perspective_node_stop_master(params):
686
    """Demote this node from master status.
687

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

    
691
  @staticmethod
692
  def perspective_node_leave_cluster(params):
693
    """Cleanup after leaving a cluster.
694

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

    
698
  @staticmethod
699
  def perspective_node_volumes(params):
700
    """Query the list of all logical volume groups.
701

702
    """
703
    return backend.NodeVolumes()
704

    
705
  @staticmethod
706
  def perspective_node_demote_from_mc(params):
707
    """Demote a node from the master candidate role.
708

709
    """
710
    return backend.DemoteFromMC()
711

    
712

    
713
  @staticmethod
714
  def perspective_node_powercycle(params):
715
    """Tries to powercycle the nod.
716

717
    """
718
    hypervisor_type = params[0]
719
    return backend.PowercycleNode(hypervisor_type)
720

    
721

    
722
  # cluster --------------------------
723

    
724
  @staticmethod
725
  def perspective_version(params):
726
    """Query version information.
727

728
    """
729
    return constants.PROTOCOL_VERSION
730

    
731
  @staticmethod
732
  def perspective_upload_file(params):
733
    """Upload a file.
734

735
    Note that the backend implementation imposes strict rules on which
736
    files are accepted.
737

738
    """
739
    return backend.UploadFile(*params)
740

    
741
  @staticmethod
742
  def perspective_master_info(params):
743
    """Query master information.
744

745
    """
746
    return backend.GetMasterInfo()
747

    
748
  @staticmethod
749
  def perspective_run_oob(params):
750
    """Runs oob on node.
751

752
    """
753
    output = backend.RunOob(params[0], params[1], params[2], params[3])
754
    if output:
755
      result = serializer.LoadJson(output)
756
    else:
757
      result = None
758
    return result
759

    
760
  @staticmethod
761
  def perspective_write_ssconf_files(params):
762
    """Write ssconf files.
763

764
    """
765
    (values,) = params
766
    return backend.WriteSsconfFiles(values)
767

    
768
  # os -----------------------
769

    
770
  @staticmethod
771
  def perspective_os_diagnose(params):
772
    """Query detailed information about existing OSes.
773

774
    """
775
    return backend.DiagnoseOS()
776

    
777
  @staticmethod
778
  def perspective_os_get(params):
779
    """Query information about a given OS.
780

781
    """
782
    name = params[0]
783
    os_obj = backend.OSFromDisk(name)
784
    return os_obj.ToDict()
785

    
786
  @staticmethod
787
  def perspective_os_validate(params):
788
    """Run a given OS' validation routine.
789

790
    """
791
    required, name, checks, params = params
792
    return backend.ValidateOS(required, name, checks, params)
793

    
794
  # hooks -----------------------
795

    
796
  @staticmethod
797
  def perspective_hooks_runner(params):
798
    """Run hook scripts.
799

800
    """
801
    hpath, phase, env = params
802
    hr = backend.HooksRunner()
803
    return hr.RunHooks(hpath, phase, env)
804

    
805
  # iallocator -----------------
806

    
807
  @staticmethod
808
  def perspective_iallocator_runner(params):
809
    """Run an iallocator script.
810

811
    """
812
    name, idata = params
813
    iar = backend.IAllocatorRunner()
814
    return iar.Run(name, idata)
815

    
816
  # test -----------------------
817

    
818
  @staticmethod
819
  def perspective_test_delay(params):
820
    """Run test delay.
821

822
    """
823
    duration = params[0]
824
    status, rval = utils.TestDelay(duration)
825
    if not status:
826
      raise backend.RPCFail(rval)
827
    return rval
828

    
829
  # file storage ---------------
830

    
831
  @staticmethod
832
  def perspective_file_storage_dir_create(params):
833
    """Create the file storage directory.
834

835
    """
836
    file_storage_dir = params[0]
837
    return backend.CreateFileStorageDir(file_storage_dir)
838

    
839
  @staticmethod
840
  def perspective_file_storage_dir_remove(params):
841
    """Remove the file storage directory.
842

843
    """
844
    file_storage_dir = params[0]
845
    return backend.RemoveFileStorageDir(file_storage_dir)
846

    
847
  @staticmethod
848
  def perspective_file_storage_dir_rename(params):
849
    """Rename the file storage directory.
850

851
    """
852
    old_file_storage_dir = params[0]
853
    new_file_storage_dir = params[1]
854
    return backend.RenameFileStorageDir(old_file_storage_dir,
855
                                        new_file_storage_dir)
856

    
857
  # jobs ------------------------
858

    
859
  @staticmethod
860
  @_RequireJobQueueLock
861
  def perspective_jobqueue_update(params):
862
    """Update job queue.
863

864
    """
865
    (file_name, content) = params
866
    return backend.JobQueueUpdate(file_name, content)
867

    
868
  @staticmethod
869
  @_RequireJobQueueLock
870
  def perspective_jobqueue_purge(params):
871
    """Purge job queue.
872

873
    """
874
    return backend.JobQueuePurge()
875

    
876
  @staticmethod
877
  @_RequireJobQueueLock
878
  def perspective_jobqueue_rename(params):
879
    """Rename a job queue file.
880

881
    """
882
    # TODO: What if a file fails to rename?
883
    return [backend.JobQueueRename(old, new) for old, new in params]
884

    
885
  # hypervisor ---------------
886

    
887
  @staticmethod
888
  def perspective_hypervisor_validate_params(params):
889
    """Validate the hypervisor parameters.
890

891
    """
892
    (hvname, hvparams) = params
893
    return backend.ValidateHVParams(hvname, hvparams)
894

    
895
  # Crypto
896

    
897
  @staticmethod
898
  def perspective_x509_cert_create(params):
899
    """Creates a new X509 certificate for SSL/TLS.
900

901
    """
902
    (validity, ) = params
903
    return backend.CreateX509Certificate(validity)
904

    
905
  @staticmethod
906
  def perspective_x509_cert_remove(params):
907
    """Removes a X509 certificate.
908

909
    """
910
    (name, ) = params
911
    return backend.RemoveX509Certificate(name)
912

    
913
  # Import and export
914

    
915
  @staticmethod
916
  def perspective_import_start(params):
917
    """Starts an import daemon.
918

919
    """
920
    (opts_s, instance, dest, dest_args) = params
921

    
922
    opts = objects.ImportExportOptions.FromDict(opts_s)
923

    
924
    return backend.StartImportExportDaemon(constants.IEM_IMPORT, opts,
925
                                           None, None,
926
                                           objects.Instance.FromDict(instance),
927
                                           dest,
928
                                           _DecodeImportExportIO(dest,
929
                                                                 dest_args))
930

    
931
  @staticmethod
932
  def perspective_export_start(params):
933
    """Starts an export daemon.
934

935
    """
936
    (opts_s, host, port, instance, source, source_args) = params
937

    
938
    opts = objects.ImportExportOptions.FromDict(opts_s)
939

    
940
    return backend.StartImportExportDaemon(constants.IEM_EXPORT, opts,
941
                                           host, port,
942
                                           objects.Instance.FromDict(instance),
943
                                           source,
944
                                           _DecodeImportExportIO(source,
945
                                                                 source_args))
946

    
947
  @staticmethod
948
  def perspective_impexp_status(params):
949
    """Retrieves the status of an import or export daemon.
950

951
    """
952
    return backend.GetImportExportStatus(params[0])
953

    
954
  @staticmethod
955
  def perspective_impexp_abort(params):
956
    """Aborts an import or export.
957

958
    """
959
    return backend.AbortImportExport(params[0])
960

    
961
  @staticmethod
962
  def perspective_impexp_cleanup(params):
963
    """Cleans up after an import or export.
964

965
    """
966
    return backend.CleanupImportExport(params[0])
967

    
968

    
969
def CheckNoded(_, args):
970
  """Initial checks whether to run or exit with a failure.
971

972
  """
973
  if args: # noded doesn't take any arguments
974
    print >> sys.stderr, ("Usage: %s [-f] [-d] [-p port] [-b ADDRESS]" %
975
                          sys.argv[0])
976
    sys.exit(constants.EXIT_FAILURE)
977

    
978

    
979
def PrepNoded(options, _):
980
  """Preparation node daemon function, executed with the PID file held.
981

982
  """
983
  if options.mlock:
984
    request_executor_class = MlockallRequestExecutor
985
    try:
986
      utils.Mlockall()
987
    except errors.NoCtypesError:
988
      logging.warning("Cannot set memory lock, ctypes module not found")
989
      request_executor_class = http.server.HttpServerRequestExecutor
990
  else:
991
    request_executor_class = http.server.HttpServerRequestExecutor
992

    
993
  # Read SSL certificate
994
  if options.ssl:
995
    ssl_params = http.HttpSslParams(ssl_key_path=options.ssl_key,
996
                                    ssl_cert_path=options.ssl_cert)
997
  else:
998
    ssl_params = None
999

    
1000
  err = _PrepareQueueLock()
1001
  if err is not None:
1002
    # this might be some kind of file-system/permission error; while
1003
    # this breaks the job queue functionality, we shouldn't prevent
1004
    # startup of the whole node daemon because of this
1005
    logging.critical("Can't init/verify the queue, proceeding anyway: %s", err)
1006

    
1007
  mainloop = daemon.Mainloop()
1008
  server = NodeHttpServer(mainloop, options.bind_address, options.port,
1009
                          ssl_params=ssl_params, ssl_verify_peer=True,
1010
                          request_executor_class=request_executor_class)
1011
  server.Start()
1012
  return (mainloop, server)
1013

    
1014

    
1015
def ExecNoded(options, args, prep_data): # pylint: disable-msg=W0613
1016
  """Main node daemon function, executed with the PID file held.
1017

1018
  """
1019
  (mainloop, server) = prep_data
1020
  try:
1021
    mainloop.Run()
1022
  finally:
1023
    server.Stop()
1024

    
1025

    
1026
def Main():
1027
  """Main function for the node daemon.
1028

1029
  """
1030
  parser = OptionParser(description="Ganeti node daemon",
1031
                        usage="%prog [-f] [-d] [-p port] [-b ADDRESS]",
1032
                        version="%%prog (ganeti) %s" %
1033
                        constants.RELEASE_VERSION)
1034
  parser.add_option("--no-mlock", dest="mlock",
1035
                    help="Do not mlock the node memory in ram",
1036
                    default=True, action="store_false")
1037

    
1038
  daemon.GenericMain(constants.NODED, parser, CheckNoded, PrepNoded, ExecNoded,
1039
                     default_ssl_cert=constants.NODED_CERT_FILE,
1040
                     default_ssl_key=constants.NODED_CERT_FILE,
1041
                     console_logging=True)