4 # Copyright (C) 2006, 2007, 2010, 2011, 2012 Google Inc.
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.
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.
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
22 """Ganeti node daemon"""
24 # pylint: disable=C0103,W0142
26 # C0103: Functions in this module need to have a given name structure,
27 # and the name of the daemon doesn't match
29 # W0142: Used * or ** magic, since we do use it extensively in this
38 from optparse import OptionParser
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
54 import ganeti.http.server # pylint: disable=W0611
60 def _extendReasonTrail(trail, source, reason=""):
61 """Extend the reason trail with noded information
63 The trail is extended by appending the name of the noded functionality
65 assert trail is not None
66 trail_source = "%s:%s" % (constants.OPCODE_REASON_SRC_NODED, source)
67 trail.append((trail_source, reason, utils.EpochNano()))
70 def _PrepareQueueLock():
71 """Try to prepare the queue lock.
73 @return: None for success, otherwise an exception object
76 global queue_lock # pylint: disable=W0603
78 if queue_lock is not None:
83 queue_lock = jstore.InitAndVerifyQueue(must_lock=False)
85 except EnvironmentError, err:
89 def _RequireJobQueueLock(fn):
90 """Decorator for job queue manipulating functions.
93 QUEUE_LOCK_TIMEOUT = 10
95 def wrapper(*args, **kwargs):
96 # Locking in exclusive, blocking mode because there could be several
97 # children running at the same time. Waiting up to 10 seconds.
98 if _PrepareQueueLock() is not None:
99 raise errors.JobQueueError("Job queue failed initialization,"
100 " cannot update jobs")
101 queue_lock.Exclusive(blocking=True, timeout=QUEUE_LOCK_TIMEOUT)
103 return fn(*args, **kwargs)
110 def _DecodeImportExportIO(ieio, ieioargs):
111 """Decodes import/export I/O information.
114 if ieio == constants.IEIO_RAW_DISK:
115 assert len(ieioargs) == 1
116 return (objects.Disk.FromDict(ieioargs[0]), )
118 if ieio == constants.IEIO_SCRIPT:
119 assert len(ieioargs) == 2
120 return (objects.Disk.FromDict(ieioargs[0]), ieioargs[1])
125 def _DefaultAlternative(value, default):
126 """Returns value or, if evaluating to False, a default value.
128 Returns the given value, unless it evaluates to False. In the latter case the
129 default value is returned.
131 @param value: Value to return if it doesn't evaluate to False
132 @param default: Default value
133 @return: Given value or the default
142 class MlockallRequestExecutor(http.server.HttpServerRequestExecutor):
143 """Subclass ensuring request handlers are locked in RAM.
146 def __init__(self, *args, **kwargs):
149 http.server.HttpServerRequestExecutor.__init__(self, *args, **kwargs)
152 class NodeRequestHandler(http.server.HttpServerHandler):
153 """The server implementation.
155 This class holds all methods exposed over the RPC interface.
158 # too many public methods, and unused args - all methods get params
160 # pylint: disable=R0904,W0613
162 http.server.HttpServerHandler.__init__(self)
163 self.noded_pid = os.getpid()
165 def HandleRequest(self, req):
169 if req.request_method.upper() != http.HTTP_POST:
170 raise http.HttpBadRequest("Only the POST method is supported")
172 path = req.request_path
173 if path.startswith("/"):
176 method = getattr(self, "perspective_%s" % path, None)
178 raise http.HttpNotFound()
181 result = (True, method(serializer.LoadJson(req.request_body)))
183 except backend.RPCFail, err:
184 # our custom failure exception; str(err) works fine if the
185 # exception was constructed with a single argument, and in
186 # this case, err.message == err.args[0] == str(err)
187 result = (False, str(err))
188 except errors.QuitGanetiException, err:
189 # Tell parent to quit
190 logging.info("Shutting down the node daemon, arguments: %s",
192 os.kill(self.noded_pid, signal.SIGTERM)
193 # And return the error's arguments, which must be already in
194 # correct tuple format
196 except Exception, err:
197 logging.exception("Error in RPC call")
198 result = (False, "Error while executing backend function: %s" % str(err))
200 return serializer.DumpJson(result)
202 # the new block devices --------------------------
205 def perspective_blockdev_create(params):
206 """Create a block device.
209 (bdev_s, size, owner, on_primary, info, excl_stor) = params
210 bdev = objects.Disk.FromDict(bdev_s)
212 raise ValueError("can't unserialize data!")
213 return backend.BlockdevCreate(bdev, size, owner, on_primary, info,
217 def perspective_blockdev_pause_resume_sync(params):
218 """Pause/resume sync of a block device.
221 disks_s, pause = params
222 disks = [objects.Disk.FromDict(bdev_s) for bdev_s in disks_s]
223 return backend.BlockdevPauseResumeSync(disks, pause)
226 def perspective_blockdev_wipe(params):
227 """Wipe a block device.
230 bdev_s, offset, size = params
231 bdev = objects.Disk.FromDict(bdev_s)
232 return backend.BlockdevWipe(bdev, offset, size)
235 def perspective_blockdev_remove(params):
236 """Remove a block device.
240 bdev = objects.Disk.FromDict(bdev_s)
241 return backend.BlockdevRemove(bdev)
244 def perspective_blockdev_rename(params):
245 """Remove a block device.
248 devlist = [(objects.Disk.FromDict(ds), uid) for ds, uid in params[0]]
249 return backend.BlockdevRename(devlist)
252 def perspective_blockdev_assemble(params):
253 """Assemble a block device.
256 bdev_s, owner, on_primary, idx = params
257 bdev = objects.Disk.FromDict(bdev_s)
259 raise ValueError("can't unserialize data!")
260 return backend.BlockdevAssemble(bdev, owner, on_primary, idx)
263 def perspective_blockdev_shutdown(params):
264 """Shutdown a block device.
268 bdev = objects.Disk.FromDict(bdev_s)
270 raise ValueError("can't unserialize data!")
271 return backend.BlockdevShutdown(bdev)
274 def perspective_blockdev_addchildren(params):
275 """Add a child to a mirror device.
277 Note: this is only valid for mirror devices. It's the caller's duty
278 to send a correct disk, otherwise we raise an error.
281 bdev_s, ndev_s = params
282 bdev = objects.Disk.FromDict(bdev_s)
283 ndevs = [objects.Disk.FromDict(disk_s) for disk_s in ndev_s]
284 if bdev is None or ndevs.count(None) > 0:
285 raise ValueError("can't unserialize data!")
286 return backend.BlockdevAddchildren(bdev, ndevs)
289 def perspective_blockdev_removechildren(params):
290 """Remove a child from a mirror device.
292 This is only valid for mirror devices, of course. It's the callers
293 duty to send a correct disk, otherwise we raise an error.
296 bdev_s, ndev_s = params
297 bdev = objects.Disk.FromDict(bdev_s)
298 ndevs = [objects.Disk.FromDict(disk_s) for disk_s in ndev_s]
299 if bdev is None or ndevs.count(None) > 0:
300 raise ValueError("can't unserialize data!")
301 return backend.BlockdevRemovechildren(bdev, ndevs)
304 def perspective_blockdev_getmirrorstatus(params):
305 """Return the mirror status for a list of disks.
308 disks = [objects.Disk.FromDict(dsk_s)
309 for dsk_s in params[0]]
310 return [status.ToDict()
311 for status in backend.BlockdevGetmirrorstatus(disks)]
314 def perspective_blockdev_getmirrorstatus_multi(params):
315 """Return the mirror status for a list of disks.
318 (node_disks, ) = params
320 disks = [objects.Disk.FromDict(dsk_s) for dsk_s in node_disks]
324 for (success, status) in backend.BlockdevGetmirrorstatusMulti(disks):
326 result.append((success, status.ToDict()))
328 result.append((success, status))
333 def perspective_blockdev_find(params):
334 """Expose the FindBlockDevice functionality for a disk.
336 This will try to find but not activate a disk.
339 disk = objects.Disk.FromDict(params[0])
341 result = backend.BlockdevFind(disk)
345 return result.ToDict()
348 def perspective_blockdev_snapshot(params):
349 """Create a snapshot device.
351 Note that this is only valid for LVM disks, if we get passed
352 something else we raise an exception. The snapshot device can be
353 remove by calling the generic block device remove call.
356 cfbd = objects.Disk.FromDict(params[0])
357 return backend.BlockdevSnapshot(cfbd)
360 def perspective_blockdev_grow(params):
361 """Grow a stack of devices.
365 raise ValueError("Received only 3 parameters in blockdev_grow,"
367 cfbd = objects.Disk.FromDict(params[0])
370 backingstore = params[3]
371 return backend.BlockdevGrow(cfbd, amount, dryrun, backingstore)
374 def perspective_blockdev_close(params):
375 """Closes the given block devices.
378 disks = [objects.Disk.FromDict(cf) for cf in params[1]]
379 return backend.BlockdevClose(params[0], disks)
382 def perspective_blockdev_getsize(params):
383 """Compute the sizes of the given block devices.
386 disks = [objects.Disk.FromDict(cf) for cf in params[0]]
387 return backend.BlockdevGetsize(disks)
390 def perspective_blockdev_export(params):
391 """Compute the sizes of the given block devices.
394 disk = objects.Disk.FromDict(params[0])
395 dest_node, dest_path, cluster_name = params[1:]
396 return backend.BlockdevExport(disk, dest_node, dest_path, cluster_name)
399 def perspective_blockdev_setinfo(params):
400 """Sets metadata information on the given block device.
403 (disk, info) = params
404 disk = objects.Disk.FromDict(disk)
405 return backend.BlockdevSetInfo(disk, info)
407 # blockdev/drbd specific methods ----------
410 def perspective_drbd_disconnect_net(params):
411 """Disconnects the network connection of drbd disks.
413 Note that this is only valid for drbd disks, so the members of the
414 disk list must all be drbd devices.
417 nodes_ip, disks = params
418 disks = [objects.Disk.FromDict(cf) for cf in disks]
419 return backend.DrbdDisconnectNet(nodes_ip, disks)
422 def perspective_drbd_attach_net(params):
423 """Attaches the network connection of drbd disks.
425 Note that this is only valid for drbd disks, so the members of the
426 disk list must all be drbd devices.
429 nodes_ip, disks, instance_name, multimaster = params
430 disks = [objects.Disk.FromDict(cf) for cf in disks]
431 return backend.DrbdAttachNet(nodes_ip, disks,
432 instance_name, multimaster)
435 def perspective_drbd_wait_sync(params):
436 """Wait until DRBD disks are synched.
438 Note that this is only valid for drbd disks, so the members of the
439 disk list must all be drbd devices.
442 nodes_ip, disks = params
443 disks = [objects.Disk.FromDict(cf) for cf in disks]
444 return backend.DrbdWaitSync(nodes_ip, disks)
447 def perspective_drbd_helper(params):
448 """Query drbd helper.
451 return backend.GetDrbdUsermodeHelper()
453 # export/import --------------------------
456 def perspective_finalize_export(params):
457 """Expose the finalize export functionality.
460 instance = objects.Instance.FromDict(params[0])
463 for disk in params[1]:
464 if isinstance(disk, bool):
465 snap_disks.append(disk)
467 snap_disks.append(objects.Disk.FromDict(disk))
469 return backend.FinalizeExport(instance, snap_disks)
472 def perspective_export_info(params):
473 """Query information about an existing export on this node.
475 The given path may not contain an export, in which case we return
480 return backend.ExportInfo(path)
483 def perspective_export_list(params):
484 """List the available exports on this node.
486 Note that as opposed to export_info, which may query data about an
487 export in any path, this only queries the standard Ganeti path
488 (pathutils.EXPORT_DIR).
491 return backend.ListExports()
494 def perspective_export_remove(params):
499 return backend.RemoveExport(export)
501 # block device ---------------------
503 def perspective_bdev_sizes(params):
504 """Query the list of block devices
508 return backend.GetBlockDevSizes(devices)
510 # volume --------------------------
513 def perspective_lv_list(params):
514 """Query the list of logical volumes in a given volume group.
518 return backend.GetVolumeList(vgname)
521 def perspective_vg_list(params):
522 """Query the list of volume groups.
525 return backend.ListVolumeGroups()
527 # Storage --------------------------
530 def perspective_storage_list(params):
531 """Get list of storage units.
534 (su_name, su_args, name, fields) = params
535 return storage.GetStorage(su_name, *su_args).List(name, fields)
538 def perspective_storage_modify(params):
539 """Modify a storage unit.
542 (su_name, su_args, name, changes) = params
543 return storage.GetStorage(su_name, *su_args).Modify(name, changes)
546 def perspective_storage_execute(params):
547 """Execute an operation on a storage unit.
550 (su_name, su_args, name, op) = params
551 return storage.GetStorage(su_name, *su_args).Execute(name, op)
553 # bridge --------------------------
556 def perspective_bridges_exist(params):
557 """Check if all bridges given exist on this node.
560 bridges_list = params[0]
561 return backend.BridgesExist(bridges_list)
563 # instance --------------------------
566 def perspective_instance_os_add(params):
567 """Install an OS on a given instance.
571 inst = objects.Instance.FromDict(inst_s)
572 reinstall = params[1]
574 return backend.InstanceOsAdd(inst, reinstall, debug)
577 def perspective_instance_run_rename(params):
578 """Runs the OS rename script for an instance.
581 inst_s, old_name, debug = params
582 inst = objects.Instance.FromDict(inst_s)
583 return backend.RunRenameInstance(inst, old_name, debug)
586 def perspective_instance_shutdown(params):
587 """Shutdown an instance.
590 instance = objects.Instance.FromDict(params[0])
593 _extendReasonTrail(trail, "shutdown")
594 return backend.InstanceShutdown(instance, timeout, trail)
597 def perspective_instance_start(params):
598 """Start an instance.
601 (instance_name, startup_paused, trail) = params
602 instance = objects.Instance.FromDict(instance_name)
603 _extendReasonTrail(trail, "start")
604 return backend.StartInstance(instance, startup_paused, trail)
607 def perspective_migration_info(params):
608 """Gather information about an instance to be migrated.
611 instance = objects.Instance.FromDict(params[0])
612 return backend.MigrationInfo(instance)
615 def perspective_accept_instance(params):
616 """Prepare the node to accept an instance.
619 instance, info, target = params
620 instance = objects.Instance.FromDict(instance)
621 return backend.AcceptInstance(instance, info, target)
624 def perspective_instance_finalize_migration_dst(params):
625 """Finalize the instance migration on the destination node.
628 instance, info, success = params
629 instance = objects.Instance.FromDict(instance)
630 return backend.FinalizeMigrationDst(instance, info, success)
633 def perspective_instance_migrate(params):
634 """Migrates an instance.
637 instance, target, live = params
638 instance = objects.Instance.FromDict(instance)
639 return backend.MigrateInstance(instance, target, live)
642 def perspective_instance_finalize_migration_src(params):
643 """Finalize the instance migration on the source node.
646 instance, success, live = params
647 instance = objects.Instance.FromDict(instance)
648 return backend.FinalizeMigrationSource(instance, success, live)
651 def perspective_instance_get_migration_status(params):
652 """Reports migration status.
655 instance = objects.Instance.FromDict(params[0])
656 return backend.GetMigrationStatus(instance).ToDict()
659 def perspective_instance_reboot(params):
660 """Reboot an instance.
663 instance = objects.Instance.FromDict(params[0])
664 reboot_type = params[1]
665 shutdown_timeout = params[2]
667 _extendReasonTrail(trail, "reboot")
668 return backend.InstanceReboot(instance, reboot_type, shutdown_timeout,
672 def perspective_instance_balloon_memory(params):
673 """Modify instance runtime memory.
676 instance_dict, memory = params
677 instance = objects.Instance.FromDict(instance_dict)
678 return backend.InstanceBalloonMemory(instance, memory)
681 def perspective_instance_info(params):
682 """Query instance information.
685 return backend.GetInstanceInfo(params[0], params[1])
688 def perspective_instance_migratable(params):
689 """Query whether the specified instance can be migrated.
692 instance = objects.Instance.FromDict(params[0])
693 return backend.GetInstanceMigratable(instance)
696 def perspective_all_instances_info(params):
697 """Query information about all instances.
700 return backend.GetAllInstancesInfo(params[0])
703 def perspective_instance_list(params):
704 """Query the list of running instances.
707 return backend.GetInstanceList(params[0])
709 # node --------------------------
712 def perspective_node_has_ip_address(params):
713 """Checks if a node has the given ip address.
716 return netutils.IPAddress.Own(params[0])
719 def perspective_node_info(params):
720 """Query node information.
723 (vg_names, hv_names, excl_stor) = params
724 return backend.GetNodeInfo(vg_names, hv_names, excl_stor)
727 def perspective_etc_hosts_modify(params):
728 """Modify a node entry in /etc/hosts.
731 backend.EtcHostsModify(params[0], params[1], params[2])
736 def perspective_node_verify(params):
737 """Run a verify sequence on this node.
740 return backend.VerifyNode(params[0], params[1])
743 def perspective_node_verify_light(cls, params):
744 """Run a light verify sequence on this node.
747 # So far it's the same as the normal node_verify
748 return cls.perspective_node_verify(params)
751 def perspective_node_start_master_daemons(params):
752 """Start the master daemons on this node.
755 return backend.StartMasterDaemons(params[0])
758 def perspective_node_activate_master_ip(params):
759 """Activate the master IP on this node.
762 master_params = objects.MasterNetworkParameters.FromDict(params[0])
763 return backend.ActivateMasterIp(master_params, params[1])
766 def perspective_node_deactivate_master_ip(params):
767 """Deactivate the master IP on this node.
770 master_params = objects.MasterNetworkParameters.FromDict(params[0])
771 return backend.DeactivateMasterIp(master_params, params[1])
774 def perspective_node_stop_master(params):
775 """Stops master daemons on this node.
778 return backend.StopMasterDaemons()
781 def perspective_node_change_master_netmask(params):
782 """Change the master IP netmask.
785 return backend.ChangeMasterNetmask(params[0], params[1], params[2],
789 def perspective_node_leave_cluster(params):
790 """Cleanup after leaving a cluster.
793 return backend.LeaveCluster(params[0])
796 def perspective_node_volumes(params):
797 """Query the list of all logical volume groups.
800 return backend.NodeVolumes()
803 def perspective_node_demote_from_mc(params):
804 """Demote a node from the master candidate role.
807 return backend.DemoteFromMC()
810 def perspective_node_powercycle(params):
811 """Tries to powercycle the nod.
814 hypervisor_type = params[0]
815 return backend.PowercycleNode(hypervisor_type)
817 # cluster --------------------------
820 def perspective_version(params):
821 """Query version information.
824 return constants.PROTOCOL_VERSION
827 def perspective_upload_file(params):
830 Note that the backend implementation imposes strict rules on which
834 return backend.UploadFile(*(params[0]))
837 def perspective_master_info(params):
838 """Query master information.
841 return backend.GetMasterInfo()
844 def perspective_run_oob(params):
848 output = backend.RunOob(params[0], params[1], params[2], params[3])
850 result = serializer.LoadJson(output)
856 def perspective_restricted_command(params):
857 """Runs a restricted command.
862 return backend.RunRestrictedCmd(cmd)
865 def perspective_write_ssconf_files(params):
866 """Write ssconf files.
870 return ssconf.WriteSsconfFiles(values)
873 def perspective_get_watcher_pause(params):
874 """Get watcher pause end.
877 return utils.ReadWatcherPauseFile(pathutils.WATCHER_PAUSEFILE)
880 def perspective_set_watcher_pause(params):
881 """Set watcher pause.
885 return backend.SetWatcherPause(until)
887 # os -----------------------
890 def perspective_os_diagnose(params):
891 """Query detailed information about existing OSes.
894 return backend.DiagnoseOS()
897 def perspective_os_get(params):
898 """Query information about a given OS.
902 os_obj = backend.OSFromDisk(name)
903 return os_obj.ToDict()
906 def perspective_os_validate(params):
907 """Run a given OS' validation routine.
910 required, name, checks, params = params
911 return backend.ValidateOS(required, name, checks, params)
913 # extstorage -----------------------
916 def perspective_extstorage_diagnose(params):
917 """Query detailed information about existing extstorage providers.
920 return backend.DiagnoseExtStorage()
922 # hooks -----------------------
925 def perspective_hooks_runner(params):
929 hpath, phase, env = params
930 hr = backend.HooksRunner()
931 return hr.RunHooks(hpath, phase, env)
933 # iallocator -----------------
936 def perspective_iallocator_runner(params):
937 """Run an iallocator script.
941 iar = backend.IAllocatorRunner()
942 return iar.Run(name, idata)
944 # test -----------------------
947 def perspective_test_delay(params):
952 status, rval = utils.TestDelay(duration)
954 raise backend.RPCFail(rval)
957 # file storage ---------------
960 def perspective_file_storage_dir_create(params):
961 """Create the file storage directory.
964 file_storage_dir = params[0]
965 return backend.CreateFileStorageDir(file_storage_dir)
968 def perspective_file_storage_dir_remove(params):
969 """Remove the file storage directory.
972 file_storage_dir = params[0]
973 return backend.RemoveFileStorageDir(file_storage_dir)
976 def perspective_file_storage_dir_rename(params):
977 """Rename the file storage directory.
980 old_file_storage_dir = params[0]
981 new_file_storage_dir = params[1]
982 return backend.RenameFileStorageDir(old_file_storage_dir,
983 new_file_storage_dir)
985 # jobs ------------------------
988 @_RequireJobQueueLock
989 def perspective_jobqueue_update(params):
993 (file_name, content) = params
994 return backend.JobQueueUpdate(file_name, content)
997 @_RequireJobQueueLock
998 def perspective_jobqueue_purge(params):
1002 return backend.JobQueuePurge()
1005 @_RequireJobQueueLock
1006 def perspective_jobqueue_rename(params):
1007 """Rename a job queue file.
1010 # TODO: What if a file fails to rename?
1011 return [backend.JobQueueRename(old, new) for old, new in params[0]]
1014 @_RequireJobQueueLock
1015 def perspective_jobqueue_set_drain_flag(params):
1016 """Set job queue's drain flag.
1021 return jstore.SetDrainFlag(flag)
1023 # hypervisor ---------------
1026 def perspective_hypervisor_validate_params(params):
1027 """Validate the hypervisor parameters.
1030 (hvname, hvparams) = params
1031 return backend.ValidateHVParams(hvname, hvparams)
1036 def perspective_x509_cert_create(params):
1037 """Creates a new X509 certificate for SSL/TLS.
1040 (validity, ) = params
1041 return backend.CreateX509Certificate(validity)
1044 def perspective_x509_cert_remove(params):
1045 """Removes a X509 certificate.
1049 return backend.RemoveX509Certificate(name)
1054 def perspective_import_start(params):
1055 """Starts an import daemon.
1058 (opts_s, instance, component, (dest, dest_args)) = params
1060 opts = objects.ImportExportOptions.FromDict(opts_s)
1062 return backend.StartImportExportDaemon(constants.IEM_IMPORT, opts,
1064 objects.Instance.FromDict(instance),
1066 _DecodeImportExportIO(dest,
1070 def perspective_export_start(params):
1071 """Starts an export daemon.
1074 (opts_s, host, port, instance, component, (source, source_args)) = params
1076 opts = objects.ImportExportOptions.FromDict(opts_s)
1078 return backend.StartImportExportDaemon(constants.IEM_EXPORT, opts,
1080 objects.Instance.FromDict(instance),
1082 _DecodeImportExportIO(source,
1086 def perspective_impexp_status(params):
1087 """Retrieves the status of an import or export daemon.
1090 return backend.GetImportExportStatus(params[0])
1093 def perspective_impexp_abort(params):
1094 """Aborts an import or export.
1097 return backend.AbortImportExport(params[0])
1100 def perspective_impexp_cleanup(params):
1101 """Cleans up after an import or export.
1104 return backend.CleanupImportExport(params[0])
1107 def CheckNoded(_, args):
1108 """Initial checks whether to run or exit with a failure.
1111 if args: # noded doesn't take any arguments
1112 print >> sys.stderr, ("Usage: %s [-f] [-d] [-p port] [-b ADDRESS]" %
1114 sys.exit(constants.EXIT_FAILURE)
1116 codecs.lookup("string-escape")
1118 print >> sys.stderr, ("Can't load the string-escape code which is part"
1119 " of the Python installation. Is your installation"
1120 " complete/correct? Aborting.")
1121 sys.exit(constants.EXIT_FAILURE)
1124 def PrepNoded(options, _):
1125 """Preparation node daemon function, executed with the PID file held.
1129 request_executor_class = MlockallRequestExecutor
1132 except errors.NoCtypesError:
1133 logging.warning("Cannot set memory lock, ctypes module not found")
1134 request_executor_class = http.server.HttpServerRequestExecutor
1136 request_executor_class = http.server.HttpServerRequestExecutor
1138 # Read SSL certificate
1140 ssl_params = http.HttpSslParams(ssl_key_path=options.ssl_key,
1141 ssl_cert_path=options.ssl_cert)
1145 err = _PrepareQueueLock()
1147 # this might be some kind of file-system/permission error; while
1148 # this breaks the job queue functionality, we shouldn't prevent
1149 # startup of the whole node daemon because of this
1150 logging.critical("Can't init/verify the queue, proceeding anyway: %s", err)
1152 handler = NodeRequestHandler()
1154 mainloop = daemon.Mainloop()
1156 http.server.HttpServer(mainloop, options.bind_address, options.port,
1157 handler, ssl_params=ssl_params, ssl_verify_peer=True,
1158 request_executor_class=request_executor_class)
1161 return (mainloop, server)
1164 def ExecNoded(options, args, prep_data): # pylint: disable=W0613
1165 """Main node daemon function, executed with the PID file held.
1168 (mainloop, server) = prep_data
1176 """Main function for the node daemon.
1179 parser = OptionParser(description="Ganeti node daemon",
1180 usage="%prog [-f] [-d] [-p port] [-b ADDRESS]",
1181 version="%%prog (ganeti) %s" %
1182 constants.RELEASE_VERSION)
1183 parser.add_option("--no-mlock", dest="mlock",
1184 help="Do not mlock the node memory in ram",
1185 default=True, action="store_false")
1187 daemon.GenericMain(constants.NODED, parser, CheckNoded, PrepNoded, ExecNoded,
1188 default_ssl_cert=pathutils.NODED_CERT_FILE,
1189 default_ssl_key=pathutils.NODED_CERT_FILE,
1190 console_logging=True)