Example #1
0
    def has_snapshot(self, vm_name, snapshot_title):
        """
        Returns whether a particular virtual machine is currently protected
        by a snapshot. This requires specifying a VM name.

        :param vm_name: Name of a virtual machine
        :type vm_name: str
        :param snapshot_title: Snapshot title
        :type snapshot_title: str
        """
        #get _all_ the snapshots
        snapshots = self.__get_snapshots(vm_name)
        try:
            for snapshot in snapshots:
                childs = snapshot.childSnapshotList
                if snapshot.name == snapshot_title:
                    return True
                #also check childs
                elif childs:
                    for child in childs:
                        if child.name == snapshot_title:
                            return True
            raise EmptySetException("No snapshots found")
        except TypeError:
            #no snapshots
            raise EmptySetException("No snapshots found")
Example #2
0
    def get_services(self, object_name, only_failed=True):
        """
        Returns all or failed services for a particular host.

        :param object_name:
        :type object_name: str
        :param only_failed: True will only report failed services
        :type only_failed: bool
        """
        #retrieve result
        result = self.__api_get(
            '/objects/services?filter=match("{}",host.name)'.format(
                object_name))
        data = json.loads(result.text)
        services = []
        for result in data["results"]:
            #get all the service information
            service = result["attrs"]["display_name"]
            state = result["attrs"]["state"]
            self.LOGGER.debug("Found service '%s' with state '%s'", service,
                              state)
            if only_failed == False or float(state) != 0.0:
                #append service if ok or state not ok
                this_service = {"name": service, "state": state}
                services.append(this_service)
        if len(services) == 0:
            #empty set
            raise EmptySetException(
                "No results for host '%s'".format(object_name))
        else:
            return services
Example #3
0
    def has_downtime(self, object_name, object_type="host"):
        """
        Returns whether a particular object (host, hostgroup) is currently in
        scheduled downtime. This required specifying an object name and type.

        :param object_name: Hostname or hostgroup name
        :type object_name: str
        :param object_type: Host or hostgroup (default: host)
        :type object_type: str
        """
        #retrieve and load data
        try:
            result = self.__api_get("/objects/{}s?host={}".format(
                object_type, object_name))
            data = json.loads(result.text)
            #check if downtime
            #TODO: how to do this for hostgroups?!
            if object_type == "host":
                for result in data["results"]:
                    if result["attrs"]["downtime_depth"] > 0:
                        return True
                return False
        except SessionException as err:
            if "404" in err.message:
                raise EmptySetException("Host not found")
Example #4
0
    def __api_request(self, method, sub_url, payload=""):
        """
        Sends a HTTP request to the Nagios/Icinga API. This function requires
        a valid HTTP method and a sub-URL (such as /cgi-bin/status.cgi).
        Optionally, you can also specify payload (for POST).
        There are also alias functions available.

        :param method: HTTP request method (GET, POST)
        :type method: str
        :param sub_url: relative path (e.g. /cgi-bin/status.cgi)
        :type sub_url: str
        :param payload: payload for POST requests
        :type payload: str
        """
        #send request to API
        try:
            if method.lower() not in ["get", "post"]:
                #going home
                raise SessionException(
                    "Illegal method '{}' specified".format(method))
            self.LOGGER.debug("%s request to %s (payload: %s)", method.upper(),
                              sub_url, payload)

            #execute request
            if method.lower() == "post":
                #POST
                result = self.SESSION.post("{}{}".format(self.URL, sub_url),
                                           headers=self.HEADERS,
                                           data=payload,
                                           verify=self.VERIFY_SSL)
            else:
                #GET
                result = self.SESSION.get("{}{}".format(self.URL, sub_url),
                                          headers=self.HEADERS,
                                          verify=self.VERIFY_SSL)

            if result.status_code == 404:
                raise EmptySetException(
                    "HTTP resource not found: {}".format(sub_url))
            elif result.status_code != 200:
                raise SessionException(
                    "{}: HTTP operation not successful".format(
                        result.status_code))
            else:
                #return result
                self.LOGGER.debug(result.text)
                return result

        except ValueError as err:
            self.LOGGER.error(err)
            raise SessionException(err)
Example #5
0
    def __get_snapshots(self, vm_name):
        """
        Returns a set of all snapshots for a particular VM.

        :param vm_name: Name of a virtual machine
        :type vm_name: str
        """
        try:
            content = self.SESSION.RetrieveContent()
            container = content.viewManager.CreateContainerView(
                content.rootFolder, [vim.VirtualMachine], True)
            for c in container.view:
                if c.name == vm_name:
                    snapshots = c.snapshot.rootSnapshotList
                    return snapshots
        except AttributeError:
            raise EmptySetException("No snapshots found")
Example #6
0
    def has_snapshot(self, vm_name, snapshot_title):
        """
        Returns whether a particular virtual machine is currently protected
        by a snapshot. This requires specifying a VM name.

        :param vm_name: Name of a virtual machine
        :type vm_name: str
        :param snapshot_title: Snapshot title
        :type snapshot_title: str
        """
        try:
            #find VM and get all snapshots
            target_vm = self.SESSION.lookupByName(vm_name)
            target_snapshots = target_vm.snapshotListNames(0)
            if snapshot_title in target_snapshots:
                return True
        except libvirt.libvirtError as err:
            if "no domain with name" in err.message.lower():
                #snapshot not found
                raise EmptySetException("No snapshots found")
            else:
                self.LOGGER.error(
                    "Unable to determine snapshot: '{}'".format(err))
                raise SessionException(err)
Example #7
0
    def __manage_downtime(self, object_name, object_type, hours, comment,
                          remove_downtime):
        """
        Adds or removes scheduled downtime for a host or hostgroup.
        For this, a object name and type are required.
        You can also specify a comment and downtime period.

        :param object_name: Hostname or hostgroup name
        :type object_name: str
        :param object_type: host or hostgroup
        :type object_type: str
        :param hours: Amount of hours for the downtime
        :type hours: int
        :param comment: Downtime comment
        :type comment: str
        :param remove_downtime: Removes a previously scheduled downtime
        :type remove_downtime: bool
        """
        #calculate timerange
        (current_time, end_time) = self.__calculate_time(hours)

        if object_type.lower() == "hostgroup":
            if remove_downtime:
                #remove hostgroup downtime
                payload = {
                    "type": "Host",
                    "filter": "\"{}\" in host.groups".format(object_name),
                }
            else:
                #create hostgroup downtime
                payload = {
                    "type": "Host",
                    "filter": "\"{}\" in host.groups".format(object_name),
                    "start_time": current_time.timestamp(),
                    "end_time": end_time.timestamp(),
                    "fixed": True,
                    "author": self.USERNAME,
                    "comment": comment,
                }
        else:
            if remove_downtime:
                #remove host downtime
                payload = {
                    "type": "Host",
                    "filter": "host.name==\"{}\"".format(object_name),
                }
            else:
                #create host downtime
                payload = {
                    "type": "Host",
                    "filter": "host.name==\"{}\"".format(object_name),
                    "start_time": current_time.timestamp(),
                    "end_time": end_time.timestamp(),
                    "fixed": True,
                    "author": self.USERNAME,
                    "comment": comment,
                }
        #send POST
        result = ""
        if remove_downtime:
            payload["type"] = "Host"
            result = self.__api_post("/actions/remove-downtime",
                                     json.dumps(payload))
            payload["type"] = "Service"
            result = self.__api_post("/actions/remove-downtime",
                                     json.dumps(payload))
        else:
            payload["type"] = "Host"
            result = self.__api_post("/actions/schedule-downtime",
                                     json.dumps(payload))
            payload["type"] = "Service"
            result = self.__api_post("/actions/schedule-downtime",
                                     json.dumps(payload))
        #return result
        result_obj = json.loads(result.text)
        if len(result_obj["results"]) == 0:
            raise EmptySetException("Host/service not found")
        else:
            return result