navigator.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env python
  2. # -- coding: utf-8 --
  3. # Licensed to Cloudera, Inc. under one
  4. # or more contributor license agreements. See the NOTICE file
  5. # distributed with this work for additional information
  6. # regarding copyright ownership. Cloudera, Inc. licenses this file
  7. # to you under the Apache License, Version 2.0 (the
  8. # "License"); you may not use this file except in compliance
  9. # with the License. You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. import logging
  19. from desktop.lib.rest.http_client import HttpClient, RestException
  20. from desktop.lib.rest import resource
  21. from metadata.conf import NAVIGATOR
  22. LOG = logging.getLogger(__name__)
  23. class NavigatorApiException(Exception):
  24. pass
  25. class NavigatorApi(object):
  26. """
  27. http://cloudera.github.io/navigator/apidocs/v2/index.html
  28. """
  29. def __init__(self, api_url=None, user=None, password=None):
  30. self._api_url = (api_url or NAVIGATOR.API_URL.get()).strip('/')
  31. self._username = user or NAVIGATOR.AUTH_USERNAME.get()
  32. self._password = password or NAVIGATOR.AUTH_PASSWORD.get()
  33. self._client = HttpClient(self._api_url, logger=LOG)
  34. self._client.set_basic_auth(self._username, self._password)
  35. self._root = resource.Resource(self._client)
  36. self.__headers = {}
  37. self.__params = ()
  38. def find_entity(self, type, name):
  39. """
  40. GET /api/v2/interactive/entities?query=((originalName:<name>)AND(type:<type>))
  41. http://cloudera.github.io/navigator/apidocs/v2/path__v2_interactive_entities.html
  42. """
  43. try:
  44. params = self.__params
  45. filter_query = '((originalName:%(name)s)AND(type:%(type)s))' % {'name': name, 'type': type}
  46. params += (
  47. ('query', filter_query),
  48. ('offset', 0),
  49. )
  50. response = self._root.get('interactive/entities', headers=self.__headers, params=params)
  51. if response['totalMatched'] == 0:
  52. raise NavigatorApiException('Could not find entity with type %s and name %s') % (type, name)
  53. elif response['totalMatched'] > 1:
  54. raise NavigatorApiException('Found more than 1 entity with type %s and name %s') % (type, name)
  55. else:
  56. return response['results'][0]
  57. except RestException, e:
  58. raise NavigatorApiException('Failed to find entity with type %s and name %s: %s' % (type, name, str(e)))