4 # Copyright (C) 2006, 2007 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-msg=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
37 from optparse import OptionParser
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
50 import ganeti.http.server # pylint: disable-msg=W0611
56 def _PrepareQueueLock():
57 """Try to prepare the queue lock.
59 @return: None for success, otherwise an exception object
62 global queue_lock # pylint: disable-msg=W0603
64 if queue_lock is not None:
69 queue_lock = jstore.InitAndVerifyQueue(must_lock=False)
71 except EnvironmentError, err:
75 def _RequireJobQueueLock(fn):
76 """Decorator for job queue manipulating functions.
79 QUEUE_LOCK_TIMEOUT = 10
81 def wrapper(*args, **kwargs):
82 # Locking in exclusive, blocking mode because there could be several
83 # children running at the same time. Waiting up to 10 seconds.
84 if _PrepareQueueLock() is not None:
85 raise errors.JobQueueError("Job queue failed initialization,"
86 " cannot update jobs")
87 queue_lock.Exclusive(blocking=True, timeout=QUEUE_LOCK_TIMEOUT)
89 return fn(*args, **kwargs)
96 class NodeHttpServer(http.server.HttpServer):
97 """The server implementation.
99 This class holds all methods exposed over the RPC interface.
102 # too many public methods, and unused args - all methods get params
104 # pylint: disable-msg=R0904,W0613
105 def __init__(self, *args, **kwargs):
106 http.server.HttpServer.__init__(self, *args, **kwargs)
107 self.noded_pid = os.getpid()
109 def HandleRequest(self, req):
113 if req.request_method.upper() != http.HTTP_PUT:
114 raise http.HttpBadRequest()
116 path = req.request_path
117 if path.startswith("/"):
120 method = getattr(self, "perspective_%s" % path, None)
122 raise http.HttpNotFound()
125 result = (True, method(serializer.LoadJson(req.request_body)))
127 except backend.RPCFail, err:
128 # our custom failure exception; str(err) works fine if the
129 # exception was constructed with a single argument, and in
130 # this case, err.message == err.args[0] == str(err)
131 result = (False, str(err))
132 except errors.QuitGanetiException, err:
133 # Tell parent to quit
134 logging.info("Shutting down the node daemon, arguments: %s",
136 os.kill(self.noded_pid, signal.SIGTERM)
137 # And return the error's arguments, which must be already in
138 # correct tuple format
140 except Exception, err:
141 logging.exception("Error in RPC call")
142 result = (False, "Error while executing backend function: %s" % str(err))
144 return serializer.DumpJson(result, indent=False)
146 # the new block devices --------------------------
149 def perspective_blockdev_create(params):
150 """Create a block device.
153 bdev_s, size, owner, on_primary, info = params
154 bdev = objects.Disk.FromDict(bdev_s)
156 raise ValueError("can't unserialize data!")
157 return backend.BlockdevCreate(bdev, size, owner, on_primary, info)
160 def perspective_blockdev_remove(params):
161 """Remove a block device.
165 bdev = objects.Disk.FromDict(bdev_s)
166 return backend.BlockdevRemove(bdev)
169 def perspective_blockdev_rename(params):
170 """Remove a block device.
173 devlist = [(objects.Disk.FromDict(ds), uid) for ds, uid in params]
174 return backend.BlockdevRename(devlist)
177 def perspective_blockdev_assemble(params):
178 """Assemble a block device.
181 bdev_s, owner, on_primary = params
182 bdev = objects.Disk.FromDict(bdev_s)
184 raise ValueError("can't unserialize data!")
185 return backend.BlockdevAssemble(bdev, owner, on_primary)
188 def perspective_blockdev_shutdown(params):
189 """Shutdown a block device.
193 bdev = objects.Disk.FromDict(bdev_s)
195 raise ValueError("can't unserialize data!")
196 return backend.BlockdevShutdown(bdev)
199 def perspective_blockdev_addchildren(params):
200 """Add a child to a mirror device.
202 Note: this is only valid for mirror devices. It's the caller's duty
203 to send a correct disk, otherwise we raise an error.
206 bdev_s, ndev_s = params
207 bdev = objects.Disk.FromDict(bdev_s)
208 ndevs = [objects.Disk.FromDict(disk_s) for disk_s in ndev_s]
209 if bdev is None or ndevs.count(None) > 0:
210 raise ValueError("can't unserialize data!")
211 return backend.BlockdevAddchildren(bdev, ndevs)
214 def perspective_blockdev_removechildren(params):
215 """Remove a child from a mirror device.
217 This is only valid for mirror devices, of course. It's the callers
218 duty to send a correct disk, otherwise we raise an error.
221 bdev_s, ndev_s = params
222 bdev = objects.Disk.FromDict(bdev_s)
223 ndevs = [objects.Disk.FromDict(disk_s) for disk_s in ndev_s]
224 if bdev is None or ndevs.count(None) > 0:
225 raise ValueError("can't unserialize data!")
226 return backend.BlockdevRemovechildren(bdev, ndevs)
229 def perspective_blockdev_getmirrorstatus(params):
230 """Return the mirror status for a list of disks.
233 disks = [objects.Disk.FromDict(dsk_s)
235 return [status.ToDict()
236 for status in backend.BlockdevGetmirrorstatus(disks)]
239 def perspective_blockdev_find(params):
240 """Expose the FindBlockDevice functionality for a disk.
242 This will try to find but not activate a disk.
245 disk = objects.Disk.FromDict(params[0])
247 result = backend.BlockdevFind(disk)
251 return result.ToDict()
254 def perspective_blockdev_snapshot(params):
255 """Create a snapshot device.
257 Note that this is only valid for LVM disks, if we get passed
258 something else we raise an exception. The snapshot device can be
259 remove by calling the generic block device remove call.
262 cfbd = objects.Disk.FromDict(params[0])
263 return backend.BlockdevSnapshot(cfbd)
266 def perspective_blockdev_grow(params):
267 """Grow a stack of devices.
270 cfbd = objects.Disk.FromDict(params[0])
272 return backend.BlockdevGrow(cfbd, amount)
275 def perspective_blockdev_close(params):
276 """Closes the given block devices.
279 disks = [objects.Disk.FromDict(cf) for cf in params[1]]
280 return backend.BlockdevClose(params[0], disks)
283 def perspective_blockdev_getsize(params):
284 """Compute the sizes of the given block devices.
287 disks = [objects.Disk.FromDict(cf) for cf in params[0]]
288 return backend.BlockdevGetsize(disks)
291 def perspective_blockdev_export(params):
292 """Compute the sizes of the given block devices.
295 disk = objects.Disk.FromDict(params[0])
296 dest_node, dest_path, cluster_name = params[1:]
297 return backend.BlockdevExport(disk, dest_node, dest_path, cluster_name)
299 # blockdev/drbd specific methods ----------
302 def perspective_drbd_disconnect_net(params):
303 """Disconnects the network connection of drbd disks.
305 Note that this is only valid for drbd disks, so the members of the
306 disk list must all be drbd devices.
309 nodes_ip, disks = params
310 disks = [objects.Disk.FromDict(cf) for cf in disks]
311 return backend.DrbdDisconnectNet(nodes_ip, disks)
314 def perspective_drbd_attach_net(params):
315 """Attaches the network connection of drbd disks.
317 Note that this is only valid for drbd disks, so the members of the
318 disk list must all be drbd devices.
321 nodes_ip, disks, instance_name, multimaster = params
322 disks = [objects.Disk.FromDict(cf) for cf in disks]
323 return backend.DrbdAttachNet(nodes_ip, disks,
324 instance_name, multimaster)
327 def perspective_drbd_wait_sync(params):
328 """Wait until DRBD disks are synched.
330 Note that this is only valid for drbd disks, so the members of the
331 disk list must all be drbd devices.
334 nodes_ip, disks = params
335 disks = [objects.Disk.FromDict(cf) for cf in disks]
336 return backend.DrbdWaitSync(nodes_ip, disks)
338 # export/import --------------------------
341 def perspective_snapshot_export(params):
342 """Export a given snapshot.
345 disk = objects.Disk.FromDict(params[0])
346 dest_node = params[1]
347 instance = objects.Instance.FromDict(params[2])
348 cluster_name = params[3]
350 return backend.ExportSnapshot(disk, dest_node, instance,
351 cluster_name, dev_idx)
354 def perspective_finalize_export(params):
355 """Expose the finalize export functionality.
358 instance = objects.Instance.FromDict(params[0])
359 snap_disks = [objects.Disk.FromDict(str_data)
360 for str_data in params[1]]
361 return backend.FinalizeExport(instance, snap_disks)
364 def perspective_export_info(params):
365 """Query information about an existing export on this node.
367 The given path may not contain an export, in which case we return
372 return backend.ExportInfo(path)
375 def perspective_export_list(params):
376 """List the available exports on this node.
378 Note that as opposed to export_info, which may query data about an
379 export in any path, this only queries the standard Ganeti path
380 (constants.EXPORT_DIR).
383 return backend.ListExports()
386 def perspective_export_remove(params):
391 return backend.RemoveExport(export)
393 # volume --------------------------
396 def perspective_lv_list(params):
397 """Query the list of logical volumes in a given volume group.
401 return backend.GetVolumeList(vgname)
404 def perspective_vg_list(params):
405 """Query the list of volume groups.
408 return backend.ListVolumeGroups()
410 # Storage --------------------------
413 def perspective_storage_list(params):
414 """Get list of storage units.
417 (su_name, su_args, name, fields) = params
418 return storage.GetStorage(su_name, *su_args).List(name, fields)
421 def perspective_storage_modify(params):
422 """Modify a storage unit.
425 (su_name, su_args, name, changes) = params
426 return storage.GetStorage(su_name, *su_args).Modify(name, changes)
429 def perspective_storage_execute(params):
430 """Execute an operation on a storage unit.
433 (su_name, su_args, name, op) = params
434 return storage.GetStorage(su_name, *su_args).Execute(name, op)
436 # bridge --------------------------
439 def perspective_bridges_exist(params):
440 """Check if all bridges given exist on this node.
443 bridges_list = params[0]
444 return backend.BridgesExist(bridges_list)
446 # instance --------------------------
449 def perspective_instance_os_add(params):
450 """Install an OS on a given instance.
454 inst = objects.Instance.FromDict(inst_s)
455 reinstall = params[1]
456 return backend.InstanceOsAdd(inst, reinstall)
459 def perspective_instance_run_rename(params):
460 """Runs the OS rename script for an instance.
463 inst_s, old_name = params
464 inst = objects.Instance.FromDict(inst_s)
465 return backend.RunRenameInstance(inst, old_name)
468 def perspective_instance_os_import(params):
469 """Run the import function of an OS onto a given instance.
472 inst_s, src_node, src_images, cluster_name = params
473 inst = objects.Instance.FromDict(inst_s)
474 return backend.ImportOSIntoInstance(inst, src_node, src_images,
478 def perspective_instance_shutdown(params):
479 """Shutdown an instance.
482 instance = objects.Instance.FromDict(params[0])
484 return backend.InstanceShutdown(instance, timeout)
487 def perspective_instance_start(params):
488 """Start an instance.
491 instance = objects.Instance.FromDict(params[0])
492 return backend.StartInstance(instance)
495 def perspective_migration_info(params):
496 """Gather information about an instance to be migrated.
499 instance = objects.Instance.FromDict(params[0])
500 return backend.MigrationInfo(instance)
503 def perspective_accept_instance(params):
504 """Prepare the node to accept an instance.
507 instance, info, target = params
508 instance = objects.Instance.FromDict(instance)
509 return backend.AcceptInstance(instance, info, target)
512 def perspective_finalize_migration(params):
513 """Finalize the instance migration.
516 instance, info, success = params
517 instance = objects.Instance.FromDict(instance)
518 return backend.FinalizeMigration(instance, info, success)
521 def perspective_instance_migrate(params):
522 """Migrates an instance.
525 instance, target, live = params
526 instance = objects.Instance.FromDict(instance)
527 return backend.MigrateInstance(instance, target, live)
530 def perspective_instance_reboot(params):
531 """Reboot an instance.
534 instance = objects.Instance.FromDict(params[0])
535 reboot_type = params[1]
536 shutdown_timeout = params[2]
537 return backend.InstanceReboot(instance, reboot_type, shutdown_timeout)
540 def perspective_instance_info(params):
541 """Query instance information.
544 return backend.GetInstanceInfo(params[0], params[1])
547 def perspective_instance_migratable(params):
548 """Query whether the specified instance can be migrated.
551 instance = objects.Instance.FromDict(params[0])
552 return backend.GetInstanceMigratable(instance)
555 def perspective_all_instances_info(params):
556 """Query information about all instances.
559 return backend.GetAllInstancesInfo(params[0])
562 def perspective_instance_list(params):
563 """Query the list of running instances.
566 return backend.GetInstanceList(params[0])
568 # node --------------------------
571 def perspective_node_tcp_ping(params):
572 """Do a TcpPing on the remote node.
575 return utils.TcpPing(params[1], params[2], timeout=params[3],
576 live_port_needed=params[4], source=params[0])
579 def perspective_node_has_ip_address(params):
580 """Checks if a node has the given ip address.
583 return utils.OwnIpAddress(params[0])
586 def perspective_node_info(params):
587 """Query node information.
590 vgname, hypervisor_type = params
591 return backend.GetNodeInfo(vgname, hypervisor_type)
594 def perspective_node_add(params):
595 """Complete the registration of this node in the cluster.
598 return backend.AddNode(params[0], params[1], params[2],
599 params[3], params[4], params[5])
602 def perspective_node_verify(params):
603 """Run a verify sequence on this node.
606 return backend.VerifyNode(params[0], params[1])
609 def perspective_node_start_master(params):
610 """Promote this node to master status.
613 return backend.StartMaster(params[0], params[1])
616 def perspective_node_stop_master(params):
617 """Demote this node from master status.
620 return backend.StopMaster(params[0])
623 def perspective_node_leave_cluster(params):
624 """Cleanup after leaving a cluster.
627 return backend.LeaveCluster(params[0])
630 def perspective_node_volumes(params):
631 """Query the list of all logical volume groups.
634 return backend.NodeVolumes()
637 def perspective_node_demote_from_mc(params):
638 """Demote a node from the master candidate role.
641 return backend.DemoteFromMC()
645 def perspective_node_powercycle(params):
646 """Tries to powercycle the nod.
649 hypervisor_type = params[0]
650 return backend.PowercycleNode(hypervisor_type)
653 # cluster --------------------------
656 def perspective_version(params):
657 """Query version information.
660 return constants.PROTOCOL_VERSION
663 def perspective_upload_file(params):
666 Note that the backend implementation imposes strict rules on which
670 return backend.UploadFile(*params)
673 def perspective_master_info(params):
674 """Query master information.
677 return backend.GetMasterInfo()
680 def perspective_write_ssconf_files(params):
681 """Write ssconf files.
685 return backend.WriteSsconfFiles(values)
687 # os -----------------------
690 def perspective_os_diagnose(params):
691 """Query detailed information about existing OSes.
694 return backend.DiagnoseOS()
697 def perspective_os_get(params):
698 """Query information about a given OS.
702 os_obj = backend.OSFromDisk(name)
703 return os_obj.ToDict()
705 # hooks -----------------------
708 def perspective_hooks_runner(params):
712 hpath, phase, env = params
713 hr = backend.HooksRunner()
714 return hr.RunHooks(hpath, phase, env)
716 # iallocator -----------------
719 def perspective_iallocator_runner(params):
720 """Run an iallocator script.
724 iar = backend.IAllocatorRunner()
725 return iar.Run(name, idata)
727 # test -----------------------
730 def perspective_test_delay(params):
735 status, rval = utils.TestDelay(duration)
737 raise backend.RPCFail(rval)
740 # file storage ---------------
743 def perspective_file_storage_dir_create(params):
744 """Create the file storage directory.
747 file_storage_dir = params[0]
748 return backend.CreateFileStorageDir(file_storage_dir)
751 def perspective_file_storage_dir_remove(params):
752 """Remove the file storage directory.
755 file_storage_dir = params[0]
756 return backend.RemoveFileStorageDir(file_storage_dir)
759 def perspective_file_storage_dir_rename(params):
760 """Rename the file storage directory.
763 old_file_storage_dir = params[0]
764 new_file_storage_dir = params[1]
765 return backend.RenameFileStorageDir(old_file_storage_dir,
766 new_file_storage_dir)
768 # jobs ------------------------
771 @_RequireJobQueueLock
772 def perspective_jobqueue_update(params):
776 (file_name, content) = params
777 return backend.JobQueueUpdate(file_name, content)
780 @_RequireJobQueueLock
781 def perspective_jobqueue_purge(params):
785 return backend.JobQueuePurge()
788 @_RequireJobQueueLock
789 def perspective_jobqueue_rename(params):
790 """Rename a job queue file.
793 # TODO: What if a file fails to rename?
794 return [backend.JobQueueRename(old, new) for old, new in params]
797 def perspective_jobqueue_set_drain(params):
798 """Set/unset the queue drain flag.
801 drain_flag = params[0]
802 return backend.JobQueueSetDrainFlag(drain_flag)
805 # hypervisor ---------------
808 def perspective_hypervisor_validate_params(params):
809 """Validate the hypervisor parameters.
812 (hvname, hvparams) = params
813 return backend.ValidateHVParams(hvname, hvparams)
816 def CheckNoded(_, args):
817 """Initial checks whether to run or exit with a failure.
820 if args: # noded doesn't take any arguments
821 print >> sys.stderr, ("Usage: %s [-f] [-d] [-p port] [-b ADDRESS]" %
823 sys.exit(constants.EXIT_FAILURE)
826 def ExecNoded(options, _):
827 """Main node daemon function, executed with the PID file held.
830 # Read SSL certificate
832 ssl_params = http.HttpSslParams(ssl_key_path=options.ssl_key,
833 ssl_cert_path=options.ssl_cert)
837 err = _PrepareQueueLock()
839 # this might be some kind of file-system/permission error; while
840 # this breaks the job queue functionality, we shouldn't prevent
841 # startup of the whole node daemon because of this
842 logging.critical("Can't init/verify the queue, proceeding anyway: %s", err)
844 mainloop = daemon.Mainloop()
845 server = NodeHttpServer(mainloop, options.bind_address, options.port,
846 ssl_params=ssl_params, ssl_verify_peer=True)
855 """Main function for the node daemon.
858 parser = OptionParser(description="Ganeti node daemon",
859 usage="%prog [-f] [-d] [-p port] [-b ADDRESS]",
860 version="%%prog (ganeti) %s" %
861 constants.RELEASE_VERSION)
862 dirs = [(val, constants.RUN_DIRS_MODE) for val in constants.SUB_RUN_DIRS]
863 dirs.append((constants.LOG_OS_DIR, 0750))
864 dirs.append((constants.LOCK_DIR, 1777))
865 daemon.GenericMain(constants.NODED, parser, dirs, CheckNoded, ExecNoded,
866 default_ssl_cert=constants.SSL_CERT_FILE,
867 default_ssl_key=constants.SSL_CERT_FILE)
870 if __name__ == '__main__':