alignak_backend_client/backend_client.py
def get_resource(self, resource_name, name):
        # pylint: disable=too-many-locals, too-many-nested-blocks
        """Get a specific resource by name"""
        try:
            logger.info("Trying to get %s: '%s'", resource_name, name)

            services_list = False
            if resource_name == 'host' and '/' in name:
                splitted_name = name.split('/')
                services_list = True
                name = splitted_name[0]

            params = {'where': json.dumps({'name': name})}

            if resource_name in ['host', 'service', 'user']:
                params = {'where': json.dumps({'name': name, '_is_template': self.model})}

            if resource_name == 'service' and '/' in name:
                splitted_name = name.split('/')
                # new_name = splitted_name[0] + '_' + splitted_name[1]
                # name = splitted_name[1]

                # Get host from name
                response2 = self.backend.get(
                    'host', params={'where': json.dumps({'name': splitted_name[0]})})
                if response2['_items']:
                    host = response2['_items'][0]
                    logger.info("Got host '%s' for the service '%s'",
                                splitted_name[0], splitted_name[1])
                else:
                    logger.warning("Not found host '%s'!", splitted_name[0])
                    return False

                params = {'where': json.dumps({'name': splitted_name[1],
                                               'host': host['_id'],
                                               '_is_template': self.model})}

            if self.embedded and resource_name in self.embedded_resources:
                params.update({'embedded': json.dumps(self.embedded_resources[resource_name])})

            response = self.backend.get(resource_name, params=params)
            if response['_items']:
                response = response['_items'][0]

                logger.info("-> found %s '%s': %s", resource_name, name, response['_id'])

                if services_list:
                    # Get services for the host
                    params = {'where': json.dumps({'host': response['_id']})}
                    if self.embedded and 'service' in self.embedded_resources:
                        params.update(
                            {'embedded': json.dumps(self.embedded_resources['service'])})

                    response2 = self.backend.get('service', params=params)
                    if response2['_items']:
                        response['_services'] = response2['_items']
                        logger.info("Got %d services for host '%s'",
                                    len(response2['_items']), splitted_name[0])
                    else:
                        logger.warning("Not found host '%s'!", splitted_name[0])
                        return False

                # Exists in the backend, we got the element
                if not self.dry_run:
                    logger.info("-> dumping %s: %s", resource_name, name)
                    # Filter fields prefixed with an _ (internal backend fields)
                    for field in list(response):
                        if field in ['_created', '_updated', '_etag', '_links', '_status']:
                            response.pop(field)
                            continue

                        # Filter fields prefixed with an _ in embedded items
                        if self.embedded and resource_name in self.embedded_resources and \
                                field in self.embedded_resources[resource_name]:
                            logger.info("-> embedded %s", field)
                            # Embedded items may be a list or a simple dictionary,
                            # always make it a list
                            embedded_items = response[field]
                            if not isinstance(response[field], list):
                                embedded_items = [response[field]]
                            # Filter fields in each embedded item
                            for embedded_item in embedded_items:
                                if not embedded_item:
                                    continue
                                for embedded_field in list(embedded_item):
                                    if embedded_field.startswith('_'):
                                        embedded_item.pop(embedded_field)

                    dump = json.dumps(response, indent=4,
                                      separators=(',', ': '), sort_keys=True)
                    if not self.quiet:
                        print(dump)

                    if resource_name == 'service' and '/' in name:
                        name = splitted_name[0] + '_' + splitted_name[1]
                    filename = self.file_dump(response,
                                              'alignak-object-dump-%s-%s.json'
                                              % (resource_name, name))
                    if filename:
                        logger.info("-> dumped %s '%s' to %s", resource_name, name, filename)

                    logger.info("-> dumped %s: %s", resource_name, name)
                else:
                    if resource_name == 'service' and '/' in name:
                        name = splitted_name[0] + '_' + splitted_name[1]
                    logger.info("Dry-run mode: should have dumped an %s '%s'",
                                resource_name, name)

                return True
            else:
                logger.warning("-> %s '%s' not found", resource_name, name)
                return False

        except BackendException as exp:  # pragma: no cover, should never happen
            logger.exception("Exception: %s", exp)
            logger.error("Response: %s", exp.response)
            print("Get error for  '%s' : %s" % (resource_name, name))
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
            print("Exiting with error code: 5")
            return False
def get_resource(self, resource_name, name):
        # pylint: disable=too-many-locals, too-many-nested-blocks
        """Get a specific resource by name"""
        try:
            logger.info("Trying to get %s: '%s'", resource_name, name)

            services_list = False
            if resource_name == 'host' and '/' in name:
                splitted_name = name.split('/')
                services_list = True
                name = splitted_name[0]

            params = {'where': json.dumps({'name': name})}

            if resource_name in ['host', 'service', 'user']:
                params = {'where': json.dumps({'name': name, '_is_template': self.model})}

            if resource_name == 'service' and '/' in name:
                splitted_name = name.split('/')
                # new_name = splitted_name[0] + '_' + splitted_name[1]
                # name = splitted_name[1]

                # Get host from name
                response2 = self.backend.get(
                    'host', params={'where': json.dumps({'name': splitted_name[0]})})
                if response2['_items']:
                    host = response2['_items'][0]
                    logger.info("Got host '%s' for the service '%s'",
                                splitted_name[0], splitted_name[1])
                else:
                    logger.warning("Not found host '%s'!", splitted_name[0])
                    return False

                params = {'where': json.dumps({'name': splitted_name[1],
                                               'host': host['_id'],
                                               '_is_template': self.model})}

            if self.embedded and resource_name in self.embedded_resources:
                params.update({'embedded': json.dumps(self.embedded_resources[resource_name])})

            response = self.backend.get(resource_name, params=params)
            if response['_items']:
                response = response['_items'][0]

                logger.info("-> found %s '%s': %s", resource_name, name, response['_id'])

                if services_list:
                    # Get services for the host
                    params = {'where': json.dumps({'host': response['_id']})}
                    if self.embedded and 'service' in self.embedded_resources:
                        params.update(
                            {'embedded': json.dumps(self.embedded_resources['service'])})

                    response2 = self.backend.get('service', params=params)
                    if response2['_items']:
                        response['_services'] = response2['_items']
                        logger.info("Got %d services for host '%s'",
                                    len(response2['_items']), splitted_name[0])
                    else:
                        logger.warning("Not found host '%s'!", splitted_name[0])
                        return False

                # Exists in the backend, we got the element
                if not self.dry_run:
                    logger.info("-> dumping %s: %s", resource_name, name)
                    # Filter fields prefixed with an _ (internal backend fields)
                    for field in list(response):
                        if field in ['_created', '_updated', '_etag', '_links', '_status']:
                            response.pop(field)
                            continue

                        # Filter fields prefixed with an _ in embedded items
                        if self.embedded and resource_name in self.embedded_resources and \
                                field in self.embedded_resources[resource_name]:
                            logger.info("-> embedded %s", field)
                            # Embedded items may be a list or a simple dictionary,
                            # always make it a list
                            embedded_items = response[field]
                            if not isinstance(response[field], list):
                                embedded_items = [response[field]]
                            # Filter fields in each embedded item
                            for embedded_item in embedded_items:
                                if not embedded_item:
                                    continue
                                for embedded_field in list(embedded_item):
                                    if embedded_field.startswith('_'):
                                        embedded_item.pop(embedded_field)

                    dump = json.dumps(response, indent=4,
                                      separators=(',', ': '), sort_keys=True)
                    if not self.quiet:
                        print(dump)

                    if resource_name == 'service' and '/' in name:
                        name = splitted_name[0] + '_' + splitted_name[1]
                    filename = self.file_dump(response,
                                              'alignak-object-dump-%s-%s.json'
                                              % (resource_name, name))
                    if filename:
                        logger.info("-> dumped %s '%s' to %s", resource_name, name, filename)

                    logger.info("-> dumped %s: %s", resource_name, name)
                else:
                    if resource_name == 'service' and '/' in name:
                        name = splitted_name[0] + '_' + splitted_name[1]
                    logger.info("Dry-run mode: should have dumped an %s '%s'",
                                resource_name, name)

                return True
            else:
                logger.warning("-> %s '%s' not found", resource_name, name)
                return False

        except BackendException as exp:  # pragma: no cover, should never happen
            logger.exception("Exception: %s", exp)
            logger.error("Response: %s", exp.response)
            print("Get error for  '%s' : %s" % (resource_name, name))
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
            print("Exiting with error code: 5")
            return False
Get a specific resource by name