|
| 1 | +"""Module provider for Name.com""" |
| 2 | +from __future__ import absolute_import |
| 3 | + |
| 4 | +import logging |
| 5 | + |
| 6 | +from requests import HTTPError, Session |
| 7 | +from requests.auth import HTTPBasicAuth |
| 8 | + |
| 9 | +from lexicon.providers.base import Provider as BaseProvider |
| 10 | + |
| 11 | +LOGGER = logging.getLogger(__name__) |
| 12 | + |
| 13 | +NAMESERVER_DOMAINS = ['name.com'] |
| 14 | + |
| 15 | +DUPLICATE_ERROR = { |
| 16 | + 'message': 'Invalid Argument', |
| 17 | + 'details': 'Parameter Value Error - Duplicate Record' |
| 18 | +} |
| 19 | + |
| 20 | + |
| 21 | +def provider_parser(subparser): |
| 22 | + """Configure a subparser for Name.com.""" |
| 23 | + |
| 24 | + subparser.add_argument('--auth-username', help='specify a username') |
| 25 | + subparser.add_argument('--auth-token', help='specify an API token') |
| 26 | + |
| 27 | + |
| 28 | +class NamecomLoader(object): # pylint: disable=useless-object-inheritance,too-few-public-methods |
| 29 | + """Loader that handles pagination for the Name.com provider.""" |
| 30 | + |
| 31 | + def __init__(self, get, url, data_key, next_page=1): |
| 32 | + self.get = get |
| 33 | + self.url = url |
| 34 | + self.data_key = data_key |
| 35 | + self.next_page = next_page |
| 36 | + |
| 37 | + def __iter__(self): |
| 38 | + while self.next_page: |
| 39 | + response = self.get(self.url, {'page': self.next_page}) |
| 40 | + for data in response[self.data_key]: |
| 41 | + yield data |
| 42 | + self.next_page = response.get('next_page') |
| 43 | + |
| 44 | + |
| 45 | +class NamecomProvider(BaseProvider): |
| 46 | + """Provider implementation for Name.com.""" |
| 47 | + |
| 48 | + def __init__(self, config): |
| 49 | + super(Provider, self).__init__(config) |
| 50 | + self.api_endpoint = 'https://api.name.com/v4' |
| 51 | + self.session = Session() |
| 52 | + |
| 53 | + def _authenticate(self): |
| 54 | + self.session.auth = HTTPBasicAuth( |
| 55 | + username=self._get_provider_option('auth_username'), |
| 56 | + password=self._get_provider_option('auth_token') |
| 57 | + ) |
| 58 | + |
| 59 | + # checking domain existence |
| 60 | + domain_name = self.domain |
| 61 | + for domain in NamecomLoader(self._get, '/domains', 'domains'): |
| 62 | + if domain['domainName'] == domain_name: |
| 63 | + self.domain_id = domain_name |
| 64 | + return |
| 65 | + |
| 66 | + raise Exception('{} domain does not exist'.format(domain_name)) |
| 67 | + |
| 68 | + def _create_record(self, rtype, name, content): |
| 69 | + data = { |
| 70 | + 'type': rtype, |
| 71 | + 'host': self._relative_name(name), |
| 72 | + 'answer': content, |
| 73 | + 'ttl': self._get_lexicon_option('ttl') |
| 74 | + } |
| 75 | + |
| 76 | + if rtype in ('MX', 'SRV'): |
| 77 | + # despite the documentation says a priority is |
| 78 | + # required for MX and SRV, it's actually optional |
| 79 | + priority = self._get_lexicon_option('priority') |
| 80 | + if priority: |
| 81 | + data['priority'] = priority |
| 82 | + |
| 83 | + url = '/domains/{}/records'.format(self.domain) |
| 84 | + try: |
| 85 | + record_id = self._post(url, data)['id'] |
| 86 | + except HTTPError as error: |
| 87 | + response = error.response |
| 88 | + if response.status_code == 400 and \ |
| 89 | + response.json() == DUPLICATE_ERROR: |
| 90 | + LOGGER.warning( |
| 91 | + 'create_record: duplicate record has been skipped' |
| 92 | + ) |
| 93 | + return True |
| 94 | + raise |
| 95 | + |
| 96 | + LOGGER.debug('create_record: record %s has been created', record_id) |
| 97 | + |
| 98 | + return record_id |
| 99 | + |
| 100 | + def _list_records(self, rtype=None, name=None, content=None): |
| 101 | + url = '/domains/{}/records'.format(self.domain) |
| 102 | + records = [] |
| 103 | + |
| 104 | + for raw in NamecomLoader(self._get, url, 'records'): |
| 105 | + record = { |
| 106 | + 'id': raw['id'], |
| 107 | + 'type': raw['type'], |
| 108 | + 'name': raw['fqdn'][:-1], |
| 109 | + 'ttl': raw['ttl'], |
| 110 | + 'content': raw['answer'], |
| 111 | + } |
| 112 | + records.append(record) |
| 113 | + |
| 114 | + LOGGER.debug('list_records: retrieved %s records', len(records)) |
| 115 | + |
| 116 | + if rtype: |
| 117 | + records = (record for record in records if record['type'] == rtype) |
| 118 | + if name: |
| 119 | + name = self._full_name(name) |
| 120 | + records = (record for record in records if record['name'] == name) |
| 121 | + if content: |
| 122 | + records = (record for record in records |
| 123 | + if record['content'] == content) |
| 124 | + |
| 125 | + if not isinstance(records, list): |
| 126 | + records = list(records) |
| 127 | + LOGGER.debug('list_records: filtered %s records', len(records)) |
| 128 | + |
| 129 | + return records |
| 130 | + |
| 131 | + def _update_record(self, identifier, rtype=None, name=None, content=None): |
| 132 | + if not identifier: |
| 133 | + if not (rtype and name): |
| 134 | + raise ValueError( |
| 135 | + 'Record identifier or rtype+name must be specified' |
| 136 | + ) |
| 137 | + records = self._list_records(rtype, name) |
| 138 | + if not records: |
| 139 | + raise Exception('There is no record to update') |
| 140 | + |
| 141 | + if len(records) > 1: |
| 142 | + filtered_records = [record for record in records |
| 143 | + if record['content'] == content] |
| 144 | + if filtered_records: |
| 145 | + records = filtered_records |
| 146 | + |
| 147 | + if len(records) > 1: |
| 148 | + raise Exception( |
| 149 | + 'There are multiple records to update: {}'.format( |
| 150 | + ', '.join(record['id'] for record in records) |
| 151 | + ) |
| 152 | + ) |
| 153 | + |
| 154 | + record_id = records[0]['id'] |
| 155 | + else: |
| 156 | + record_id = identifier |
| 157 | + |
| 158 | + data = {'ttl': self._get_lexicon_option('ttl')} |
| 159 | + |
| 160 | + # even though the documentation says a type and an answer |
| 161 | + # are required, they are not required actually |
| 162 | + if rtype: |
| 163 | + data['type'] = rtype |
| 164 | + if name: |
| 165 | + data['host'] = self._relative_name(name) |
| 166 | + if content: |
| 167 | + data['answer'] = content |
| 168 | + |
| 169 | + url = '/domains/{}/records/{}'.format(self.domain, record_id) |
| 170 | + record_id = self._put(url, data)['id'] |
| 171 | + logging.debug('update_record: record %s has been updated', record_id) |
| 172 | + |
| 173 | + return record_id |
| 174 | + |
| 175 | + def _delete_record(self, identifier=None, |
| 176 | + rtype=None, name=None, content=None): |
| 177 | + if not identifier: |
| 178 | + if not (rtype and name): |
| 179 | + raise ValueError( |
| 180 | + 'Record identifier or rtype+name must be specified' |
| 181 | + ) |
| 182 | + records = self._list_records(rtype, name, content) |
| 183 | + if not records: |
| 184 | + LOGGER.warning('delete_record: there is no record to delete') |
| 185 | + return None |
| 186 | + record_ids = tuple(record['id'] for record in records) |
| 187 | + else: |
| 188 | + record_ids = (identifier,) |
| 189 | + |
| 190 | + for record_id in record_ids: |
| 191 | + url = '/domains/{}/records/{}'.format(self.domain, record_id) |
| 192 | + self._delete(url) |
| 193 | + LOGGER.debug( |
| 194 | + 'delete_record: record %s has been deleted', record_id |
| 195 | + ) |
| 196 | + |
| 197 | + return record_ids if len(record_ids) > 1 else record_ids[0] |
| 198 | + |
| 199 | + def _get_raw_record(self, record_id): |
| 200 | + url = '/domains/{}/records/{}'.format(self.domain, record_id) |
| 201 | + return self._get(url) |
| 202 | + |
| 203 | + def _request(self, action='GET', url='/', data=None, query_params=None): |
| 204 | + response = self.session.request(method=action, |
| 205 | + url=self.api_endpoint + url, |
| 206 | + json=data, |
| 207 | + params=query_params) |
| 208 | + response.raise_for_status() |
| 209 | + return response.json() |
| 210 | + |
| 211 | + |
| 212 | +Provider = NamecomProvider |
0 commit comments