class WatcherState(object): """Interface to a state file recording restart attempts. """ def __init__(self, statefile): """Open, lock, read and parse the file. @type statefile: file @param statefile: State file object """ self.statefile = statefile try: state_data = self.statefile.read() if not state_data: self._data = {} else: self._data = serializer.Load(state_data) except Exception, msg: # pylint: disable=W0703 # Ignore errors while loading the file and treat it as empty self._data = {} logging.warning(("Invalid state file. Using defaults." " Error message: %s"), msg) if "instance" not in self._data: self._data["instance"] = {} if "node" not in self._data: self._data["node"] = {} self._orig_data = serializer.Dump(self._data)
def AddFd(self, fds): """Pass file descriptor to kvm process via qmp socket using SCM_RIGHTS Add the fds to an fdset so that they can be used later by hot-add commands @type fds: list @param fds: The list of file descriptors to pass @return: The fdset ID that the fds have been added to (None if operation fails) """ self._check_connection() if not fdsend or "add-fd" not in self.supported_commands: return None try: # Omit fdset-id and let qemu create a new one (see qmp-commands.hx) command = {"execute": "add-fd"} fdsend.sendfds(self.sock, serializer.Dump(command), fds=fds) # Get the response out of the buffer response = self._GetResponse("add-fd") fdset = response["fdset-id"] logging.info("Sent fds %s and added to fdset %s", fds, fdset) except errors.HypervisorError, err: # In case _GetResponse() fails fdset = None logging.info("Sending fds %s failed: %s", fds, err)
def _BuildInputData(self, req): """Build input data structures. """ request = req.GetRequest(self.cfg) disk_template = None if request.get("disk_template") is not None: disk_template = request["disk_template"] elif isinstance(req, IAReqRelocate): disk_template = self.cfg.GetInstanceDiskTemplate( self.req.inst_uuid) self._ComputeClusterData(disk_template=disk_template) request["type"] = req.MODE if isinstance(self.req, IAReqInstanceAlloc): node_whitelist = self.req.node_whitelist else: node_whitelist = None if node_whitelist is not None: request["restrict-to-nodes"] = node_whitelist self.in_data["request"] = request self.in_text = serializer.Dump(self.in_data) logging.debug("IAllocator request: %s", self.in_text)
def InitConfig(version, cluster_config, master_node_config, cfg_file=pathutils.CLUSTER_CONF_FILE): """Create the initial cluster configuration. It will contain the current node, which will also be the master node, and no instances. @type version: int @param version: configuration version @type cluster_config: L{objects.Cluster} @param cluster_config: cluster configuration @type master_node_config: L{objects.Node} @param master_node_config: master node configuration @type cfg_file: string @param cfg_file: configuration file path """ uuid_generator = config.TemporaryReservationManager() cluster_config.uuid = uuid_generator.Generate([], utils.NewUUID, _INITCONF_ECID) master_node_config.uuid = uuid_generator.Generate([], utils.NewUUID, _INITCONF_ECID) cluster_config.master_node = master_node_config.uuid nodes = { master_node_config.uuid: master_node_config, } default_nodegroup = objects.NodeGroup( uuid=uuid_generator.Generate([], utils.NewUUID, _INITCONF_ECID), name=constants.INITIAL_NODE_GROUP_NAME, members=[master_node_config.uuid], diskparams={}, ) nodegroups = { default_nodegroup.uuid: default_nodegroup, } now = time.time() maintenance = objects.Maintenance(serial_no=1, ctime=now, mtime=now) config_data = objects.ConfigData(version=version, cluster=cluster_config, nodegroups=nodegroups, nodes=nodes, instances={}, networks={}, disks={}, filters={}, maintenance=maintenance, serial_no=1, ctime=now, mtime=now) utils.WriteFile(cfg_file, data=serializer.Dump(config_data.ToDict()), mode=0600)
def testLeak(self): pDict = serializer.PrivateDict() pDict["bar"] = "egg" self.assertTrue("egg" not in str(pDict), "Value leaked in str(PrivateDict)") self.assertTrue("egg" not in repr(pDict), "Value leak in repr(PrivateDict)") self.assertTrue("egg" not in "{0}".format(pDict), "Value leaked in PrivateDict.__format__") self.assertTrue(b"egg" not in serializer.Dump(pDict), "Value leaked in serializer.Dump(PrivateDict)")
def _SaveInstanceStash(self, instance_name, data): """Save data to the instance stash file in serialized format. """ stash_file = self._InstanceStashFilePath(instance_name) serialized = serializer.Dump(data) try: utils.WriteFile(stash_file, data=serialized, mode=constants.SECURE_FILE_MODE) except EnvironmentError as err: raise HypervisorError( "Failed to save instance stash file %s : %s" % (stash_file, err))
def _BuildInputData(self, req): """Build input data structures. """ request = req.GetRequest(self.cfg) disk_template = None if "disk_template" in request: disk_template = request["disk_template"] self._ComputeClusterData(disk_template=disk_template) request["type"] = req.MODE self.in_data["request"] = request self.in_text = serializer.Dump(self.in_data)
def testProperAccess(self): pDict = serializer.PrivateDict() pDict["bar"] = "egg" self.assertTrue("egg" == pDict["bar"].Get(), "Value not returned by Private.Get()") self.assertTrue("egg" == pDict.GetPrivate("bar"), "Value not returned by Private.GetPrivate()") self.assertTrue("egg" == pDict.Unprivate()["bar"], "Value not returned by PrivateDict.Unprivate()") json = serializer.Dump( pDict, private_encoder=serializer.EncodeWithPrivateFields) self.assertTrue(b"egg" in json)
def Save(self, filename): """Save state to file, then unlock and close it. """ assert self.statefile serialized_form = serializer.Dump(self._data) if self._orig_data == serialized_form: logging.debug("Data didn't change, just touching status file") os.utime(filename, None) return # We need to make sure the file is locked before renaming it, otherwise # starting ganeti-watcher again at the same time will create a conflict. fd = utils.WriteFile(filename, data=serialized_form, prewrite=utils.LockFile, close=False) self.statefile = os.fdopen(fd, "w+")
def _BuildInputData(self, req): """Build input data structures. """ request = req.GetRequest(self.cfg) disk_template = None if request.get("disk_template") is not None: disk_template = request["disk_template"] else: disk_template = self.cfg.GetInstanceDiskTemplate( self.req.inst_uuid) if disk_template is None: raise errors.ProgrammerError("disk template should not be none") self._ComputeClusterData(disk_template=disk_template) request["type"] = req.MODE self.in_data["request"] = request self.in_text = serializer.Dump(self.in_data)