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 # functions in this module need to have a given name structure, so:
25 # pylint: disable-msg=C0103
35 from optparse import OptionParser
37 from ganeti import backend
38 from ganeti import constants
39 from ganeti import objects
40 from ganeti import errors
41 from ganeti import jstore
42 from ganeti import daemon
43 from ganeti import http
44 from ganeti import utils
50 def _RequireJobQueueLock(fn):
51 """Decorator for job queue manipulating functions.
54 QUEUE_LOCK_TIMEOUT = 10
56 def wrapper(*args, **kwargs):
57 # Locking in exclusive, blocking mode because there could be several
58 # children running at the same time. Waiting up to 10 seconds.
59 queue_lock.Exclusive(blocking=True, timeout=QUEUE_LOCK_TIMEOUT)
61 return fn(*args, **kwargs)
68 class NodeHttpServer(http.HttpServer):
69 """The server implementation.
71 This class holds all methods exposed over the RPC interface.
74 def __init__(self, *args, **kwargs):
75 http.HttpServer.__init__(self, *args, **kwargs)
76 self.noded_pid = os.getpid()
78 def HandleRequest(self, req):
82 if req.request_method.upper() != "PUT":
83 raise http.HTTPBadRequest()
85 path = req.request_path
86 if path.startswith("/"):
89 method = getattr(self, "perspective_%s" % path, None)
91 raise http.HTTPNotFound()
95 return method(req.request_post_data)
97 logging.exception("Error in RPC call")
99 except errors.QuitGanetiException, err:
100 # Tell parent to quit
101 os.kill(self.noded_pid, signal.SIGTERM)
103 # the new block devices --------------------------
106 def perspective_blockdev_create(params):
107 """Create a block device.
110 bdev_s, size, owner, on_primary, info = params
111 bdev = objects.Disk.FromDict(bdev_s)
113 raise ValueError("can't unserialize data!")
114 return backend.CreateBlockDevice(bdev, size, owner, on_primary, info)
117 def perspective_blockdev_remove(params):
118 """Remove a block device.
122 bdev = objects.Disk.FromDict(bdev_s)
123 return backend.RemoveBlockDevice(bdev)
126 def perspective_blockdev_rename(params):
127 """Remove a block device.
130 devlist = [(objects.Disk.FromDict(ds), uid) for ds, uid in params]
131 return backend.RenameBlockDevices(devlist)
134 def perspective_blockdev_assemble(params):
135 """Assemble a block device.
138 bdev_s, owner, on_primary = params
139 bdev = objects.Disk.FromDict(bdev_s)
141 raise ValueError("can't unserialize data!")
142 return backend.AssembleBlockDevice(bdev, owner, on_primary)
145 def perspective_blockdev_shutdown(params):
146 """Shutdown a block device.
150 bdev = objects.Disk.FromDict(bdev_s)
152 raise ValueError("can't unserialize data!")
153 return backend.ShutdownBlockDevice(bdev)
156 def perspective_blockdev_addchildren(params):
157 """Add a child to a mirror device.
159 Note: this is only valid for mirror devices. It's the caller's duty
160 to send a correct disk, otherwise we raise an error.
163 bdev_s, ndev_s = params
164 bdev = objects.Disk.FromDict(bdev_s)
165 ndevs = [objects.Disk.FromDict(disk_s) for disk_s in ndev_s]
166 if bdev is None or ndevs.count(None) > 0:
167 raise ValueError("can't unserialize data!")
168 return backend.MirrorAddChildren(bdev, ndevs)
171 def perspective_blockdev_removechildren(params):
172 """Remove a child from a mirror device.
174 This is only valid for mirror devices, of course. It's the callers
175 duty to send a correct disk, otherwise we raise an error.
178 bdev_s, ndev_s = params
179 bdev = objects.Disk.FromDict(bdev_s)
180 ndevs = [objects.Disk.FromDict(disk_s) for disk_s in ndev_s]
181 if bdev is None or ndevs.count(None) > 0:
182 raise ValueError("can't unserialize data!")
183 return backend.MirrorRemoveChildren(bdev, ndevs)
186 def perspective_blockdev_getmirrorstatus(params):
187 """Return the mirror status for a list of disks.
190 disks = [objects.Disk.FromDict(dsk_s)
192 return backend.GetMirrorStatus(disks)
195 def perspective_blockdev_find(params):
196 """Expose the FindBlockDevice functionality for a disk.
198 This will try to find but not activate a disk.
201 disk = objects.Disk.FromDict(params[0])
202 return backend.FindBlockDevice(disk)
205 def perspective_blockdev_snapshot(params):
206 """Create a snapshot device.
208 Note that this is only valid for LVM disks, if we get passed
209 something else we raise an exception. The snapshot device can be
210 remove by calling the generic block device remove call.
213 cfbd = objects.Disk.FromDict(params[0])
214 return backend.SnapshotBlockDevice(cfbd)
217 def perspective_blockdev_grow(params):
218 """Grow a stack of devices.
221 cfbd = objects.Disk.FromDict(params[0])
223 return backend.GrowBlockDevice(cfbd, amount)
226 def perspective_blockdev_close(params):
227 """Closes the given block devices.
230 disks = [objects.Disk.FromDict(cf) for cf in params]
231 return backend.CloseBlockDevices(disks)
233 # export/import --------------------------
236 def perspective_snapshot_export(params):
237 """Export a given snapshot.
240 disk = objects.Disk.FromDict(params[0])
241 dest_node = params[1]
242 instance = objects.Instance.FromDict(params[2])
243 cluster_name = params[3]
244 return backend.ExportSnapshot(disk, dest_node, instance, cluster_name)
247 def perspective_finalize_export(params):
248 """Expose the finalize export functionality.
251 instance = objects.Instance.FromDict(params[0])
252 snap_disks = [objects.Disk.FromDict(str_data)
253 for str_data in params[1]]
254 return backend.FinalizeExport(instance, snap_disks)
257 def perspective_export_info(params):
258 """Query information about an existing export on this node.
260 The given path may not contain an export, in which case we return
265 einfo = backend.ExportInfo(path)
271 def perspective_export_list(params):
272 """List the available exports on this node.
274 Note that as opposed to export_info, which may query data about an
275 export in any path, this only queries the standard Ganeti path
276 (constants.EXPORT_DIR).
279 return backend.ListExports()
282 def perspective_export_remove(params):
287 return backend.RemoveExport(export)
289 # volume --------------------------
292 def perspective_volume_list(params):
293 """Query the list of logical volumes in a given volume group.
297 return backend.GetVolumeList(vgname)
300 def perspective_vg_list(params):
301 """Query the list of volume groups.
304 return backend.ListVolumeGroups()
306 # bridge --------------------------
309 def perspective_bridges_exist(params):
310 """Check if all bridges given exist on this node.
313 bridges_list = params[0]
314 return backend.BridgesExist(bridges_list)
316 # instance --------------------------
319 def perspective_instance_os_add(params):
320 """Install an OS on a given instance.
324 inst = objects.Instance.FromDict(inst_s)
325 return backend.AddOSToInstance(inst)
328 def perspective_instance_run_rename(params):
329 """Runs the OS rename script for an instance.
332 inst_s, old_name = params
333 inst = objects.Instance.FromDict(inst_s)
334 return backend.RunRenameInstance(inst, old_name)
337 def perspective_instance_os_import(params):
338 """Run the import function of an OS onto a given instance.
341 inst_s, os_disk, swap_disk, src_node, src_image, cluster_name = params
342 inst = objects.Instance.FromDict(inst_s)
343 return backend.ImportOSIntoInstance(inst, os_disk, swap_disk,
344 src_node, src_image, cluster_name)
347 def perspective_instance_shutdown(params):
348 """Shutdown an instance.
351 instance = objects.Instance.FromDict(params[0])
352 return backend.ShutdownInstance(instance)
355 def perspective_instance_start(params):
356 """Start an instance.
359 instance = objects.Instance.FromDict(params[0])
360 extra_args = params[1]
361 return backend.StartInstance(instance, extra_args)
364 def perspective_instance_migrate(params):
365 """Migrates an instance.
368 instance, target, live = params
369 instance = objects.Instance.FromDict(instance)
370 return backend.MigrateInstance(instance, target, live)
373 def perspective_instance_reboot(params):
374 """Reboot an instance.
377 instance = objects.Instance.FromDict(params[0])
378 reboot_type = params[1]
379 extra_args = params[2]
380 return backend.RebootInstance(instance, reboot_type, extra_args)
383 def perspective_instance_info(params):
384 """Query instance information.
387 return backend.GetInstanceInfo(params[0], params[1])
390 def perspective_all_instances_info(params):
391 """Query information about all instances.
394 return backend.GetAllInstancesInfo(params[0])
397 def perspective_instance_list(params):
398 """Query the list of running instances.
401 return backend.GetInstanceList(params[0])
403 # node --------------------------
406 def perspective_node_tcp_ping(params):
407 """Do a TcpPing on the remote node.
410 return utils.TcpPing(params[1], params[2], timeout=params[3],
411 live_port_needed=params[4], source=params[0])
414 def perspective_node_has_ip_address(params):
415 """Checks if a node has the given ip address.
418 return utils.OwnIpAddress(params[0])
421 def perspective_node_info(params):
422 """Query node information.
425 vgname, hypervisor_type = params
426 return backend.GetNodeInfo(vgname, hypervisor_type)
429 def perspective_node_add(params):
430 """Complete the registration of this node in the cluster.
433 return backend.AddNode(params[0], params[1], params[2],
434 params[3], params[4], params[5])
437 def perspective_node_verify(params):
438 """Run a verify sequence on this node.
441 return backend.VerifyNode(params[0], params[1])
444 def perspective_node_start_master(params):
445 """Promote this node to master status.
448 return backend.StartMaster(params[0])
451 def perspective_node_stop_master(params):
452 """Demote this node from master status.
455 return backend.StopMaster(params[0])
458 def perspective_node_leave_cluster(params):
459 """Cleanup after leaving a cluster.
462 return backend.LeaveCluster()
465 def perspective_node_volumes(params):
466 """Query the list of all logical volume groups.
469 return backend.NodeVolumes()
471 # cluster --------------------------
474 def perspective_version(params):
475 """Query version information.
478 return constants.PROTOCOL_VERSION
481 def perspective_upload_file(params):
484 Note that the backend implementation imposes strict rules on which
488 return backend.UploadFile(*params)
491 def perspective_master_info(params):
492 """Query master information.
495 return backend.GetMasterInfo()
497 # os -----------------------
500 def perspective_os_diagnose(params):
501 """Query detailed information about existing OSes.
504 return [os.ToDict() for os in backend.DiagnoseOS()]
507 def perspective_os_get(params):
508 """Query information about a given OS.
513 os_obj = backend.OSFromDisk(name)
514 except errors.InvalidOS, err:
515 os_obj = objects.OS.FromInvalidOS(err)
516 return os_obj.ToDict()
518 # hooks -----------------------
521 def perspective_hooks_runner(params):
525 hpath, phase, env = params
526 hr = backend.HooksRunner()
527 return hr.RunHooks(hpath, phase, env)
529 # iallocator -----------------
532 def perspective_iallocator_runner(params):
533 """Run an iallocator script.
537 iar = backend.IAllocatorRunner()
538 return iar.Run(name, idata)
540 # test -----------------------
543 def perspective_test_delay(params):
548 return utils.TestDelay(duration)
550 # file storage ---------------
553 def perspective_file_storage_dir_create(params):
554 """Create the file storage directory.
557 file_storage_dir = params[0]
558 return backend.CreateFileStorageDir(file_storage_dir)
561 def perspective_file_storage_dir_remove(params):
562 """Remove the file storage directory.
565 file_storage_dir = params[0]
566 return backend.RemoveFileStorageDir(file_storage_dir)
569 def perspective_file_storage_dir_rename(params):
570 """Rename the file storage directory.
573 old_file_storage_dir = params[0]
574 new_file_storage_dir = params[1]
575 return backend.RenameFileStorageDir(old_file_storage_dir,
576 new_file_storage_dir)
578 # jobs ------------------------
581 @_RequireJobQueueLock
582 def perspective_jobqueue_update(params):
586 (file_name, content) = params
587 return backend.JobQueueUpdate(file_name, content)
590 @_RequireJobQueueLock
591 def perspective_jobqueue_purge(params):
595 return backend.JobQueuePurge()
598 @_RequireJobQueueLock
599 def perspective_jobqueue_rename(params):
600 """Rename a job queue file.
605 return backend.JobQueueRename(old, new)
608 def perspective_jobqueue_set_drain(params):
609 """Set/unset the queue drain flag.
612 drain_flag = params[0]
613 return backend.JobQueueSetDrainFlag(drain_flag)
616 # hypervisor ---------------
619 def perspective_hypervisor_validate_params(params):
620 """Validate the hypervisor parameters.
623 (hvname, hvparams) = params
624 return backend.ValidateHVParams(hvname, hvparams)
628 """Parse the command line options.
631 (options, args) as from OptionParser.parse_args()
634 parser = OptionParser(description="Ganeti node daemon",
635 usage="%prog [-f] [-d]",
636 version="%%prog (ganeti) %s" %
637 constants.RELEASE_VERSION)
639 parser.add_option("-f", "--foreground", dest="fork",
640 help="Don't detach from the current terminal",
641 default=True, action="store_false")
642 parser.add_option("-d", "--debug", dest="debug",
643 help="Enable some debug messages",
644 default=False, action="store_true")
645 options, args = parser.parse_args()
650 """Main function for the node daemon.
655 options, args = ParseOptions()
656 utils.debug = options.debug
657 for fname in (constants.SSL_CERT_FILE,):
658 if not os.path.isfile(fname):
659 print "config %s not there, will not run." % fname
663 port = utils.GetNodeDaemonPort()
664 pwdata = utils.GetNodeDaemonPassword()
665 except errors.ConfigurationError, err:
666 print "Cluster configuration incomplete: '%s'" % str(err)
669 # create the various SUB_RUN_DIRS, if not existing, so that we handle the
670 # situation where RUN_DIR is tmpfs
671 for dir_name in constants.SUB_RUN_DIRS:
672 if not os.path.exists(dir_name):
674 os.mkdir(dir_name, 0755)
675 except EnvironmentError, err:
676 if err.errno != errno.EEXIST:
677 print ("Node setup wrong, cannot create directory %s: %s" %
680 if not os.path.isdir(dir_name):
681 print ("Node setup wrong, %s is not a directory" % dir_name)
686 utils.Daemonize(logfile=constants.LOG_NODESERVER)
688 utils.WritePidFile(constants.NODED_PID)
690 utils.SetupLogging(logfile=constants.LOG_NODESERVER, debug=options.debug,
691 stderr_logging=not options.fork)
692 logging.info("ganeti node daemon startup")
695 queue_lock = jstore.InitAndVerifyQueue(must_lock=False)
697 mainloop = daemon.Mainloop()
698 server = NodeHttpServer(mainloop, ("", port))
705 utils.RemovePidFile(constants.NODED_PID)
708 if __name__ == '__main__':