示例#1
0
 def rollback(self, service=None, zone=None):
     """Rolls back changes in zone."""
     service = self.default_service if service is None else service
     zone = self.default_zone if zone is None else zone
     response = self._post('/services/{}/zones/{}/rollback'.format(
         service, zone))
     if response.status_code != requests.codes.ok:
         raise DnsApiException('Failed to rollback changes:\n{}'.format(
             response.text))
     self.logger.info('Changes are rolled back!')
示例#2
0
 def commit(self, service=None, zone=None):
     """Commits changes in zone."""
     service = self.default_service if service is None else service
     zone = self.default_zone if zone is None else zone
     response = self._post('/services/{}/zones/{}/commit'.format(
         service, zone))
     if response.status_code != requests.codes.ok:
         raise DnsApiException('Failed to commit changes:\n{}'.format(
             response.text))
     self.logger.info('Changes committed!')
示例#3
0
 def commit(self, service=None, zone=None):
     """Commits changes in zone."""
     service = self.default_service if service is None else service
     zone = self.default_zone if zone is None else zone
     response = self._post("services/{}/zones/{}/commit".format(
         service, zone))
     if response.status_code != requests.codes.ok:
         if raise_error(response.text) is None:
             raise DnsApiException("Failed to commit changes:\n{}".format(
                 response.text))
     logger.info("Changes committed")
示例#4
0
 def refresh_token(self, refresh_token):
     """Refreshes authorization token."""
     try:
         token = self._session.refresh_token(
             token_url=self.token_url,
             refresh_token=refresh_token,
             client_id=self._app_login,
             client_secret=self._app_password,
             offline=self._offline,
         )
     except (InvalidGrantError, InvalidClientError) as err:
         raise DnsApiException(str(err))
     self._token_updater(token)
示例#5
0
 def get_token(self, username, password):
     """Gets authorization token."""
     try:
         token = self._session.fetch_token(
             token_url=self.token_url,
             username=username,
             password=password,
             client_id=self._app_login,
             client_secret=self._app_password,
             offline=self._offline,
         )
     except (InvalidGrantError, InvalidClientError) as err:
         raise DnsApiException(str(err))
     self._token_updater(token)
示例#6
0
    def delete_record(self, record_id, service=None, zone=None):
        """Deletes record by id."""
        if not isinstance(record_id, int):
            raise TypeError('"record_id" is not a valid int!')
        service = self.default_service if service is None else service
        zone = self.default_zone if zone is None else zone

        self.logger.debug('Deleting record #%s on service %s zone %s',
                          record_id, service, zone)

        response = self._delete('/services/{}/zones/{}/records/{}'.format(
            service, zone, record_id))

        if response.status_code != requests.codes.ok:
            raise DnsApiException('Failed to delete record: {}'.format(
                response.text))
        self.logger.info('Record #%s deleted!', record_id)
示例#7
0
    def add_record(self, records, service=None, zone=None):
        """Adds records.

        Returns:
            a list with DNSRecord subclasses objects (with added IDs).
        """
        service = self.default_service if service is None else service
        zone = self.default_zone if zone is None else zone
        if not is_sequence(records):
            _records = [records]
        else:
            _records = list(records)

        rr_list = []  # for XML representations

        for record in _records:
            if not isinstance(record, DNSRecord):
                raise TypeError("{} is not a valid DNS record".format(record))
            record_xml = record.to_xml()
            rr_list.append(record_xml)
            logger.debug(
                "Preparing to add a new record on service %s zone %s: %s",
                service,
                zone,
                record_xml,
            )

        _xml = ('<?xml version="1.0" encoding="UTF-8" ?>'
                "<request><rr-list>"
                "{}"
                "</rr-list></request>").format("".join(rr_list))

        response = self._put("services/{}/zones/{}/records".format(
            service, zone),
                             data=_xml)

        if response.status_code != requests.codes.ok:
            if raise_error(response.text) is None:
                raise DnsApiException("Failed to add new records:\n{}".format(
                    response.text))

        logger.info("Successfully added %s records", len(rr_list))
        data = get_data(response)
        _zone = data.find("zone")
        assert _zone.attrib["name"] == zone
        return [parse_record(rr) for rr in _zone.findall("rr")]
示例#8
0
def get_token(oauth_config, username, password):
    """Returns a new OAuth token."""
    if not all([username, password]):
        raise EmptyCredentials(
            'No credentials were provided for the OAuth token request!')

    oauth_data = {
        'grant_type': 'password',
        'username': username,
        'password': password,
        'scope': r'.+:/dns-master/.+'
    }

    oauth_creds = (oauth_config['APP_LOGIN'], oauth_config['APP_PASSWORD'])

    result = requests.post(OAUTH_URL, data=oauth_data, auth=oauth_creds)

    if result.status_code != requests.codes.ok:
        raise DnsApiException(result.text)

    return OAuth2Token(**result.json())
示例#9
0
def get_data(response):
    """Gets <data> from XML response.

    Arguments:
        response: an instance of requests.Response;

    Returns:
        (xml.etree.ElementTree.Element) <data> tag of response.
    """
    if not isinstance(response, requests.Response):
        raise TypeError('"response" must be an instance of requests.Response!')

    # Processing API errors
    if response.status_code != requests.codes.ok:
        raise DnsApiException(response.text)

    root = ElementTree.fromstring(response.text)
    datas = root.findall('data')
    if len(datas) != 1:
        raise ValueError("Can't find exact 1 <data> in response:\n{}".format(
            response.text))

    return datas[0]
示例#10
0
    def add_record(self, records, service=None, zone=None):
        """Adds records."""
        service = self.default_service if service is None else service
        zone = self.default_zone if zone is None else zone
        if not is_sequence(records):
            _records = [records]
        else:
            _records = list(records)

        rr_list = []  # for XML representations

        for record in _records:
            if not isinstance(record, _RECORD_CLASSES):
                raise TypeError('{} is not a valid DNS record!'.format(record))
            record_xml = record.to_xml()
            rr_list.append(record_xml)
            self.logger.debug(
                'Prepared for addition new record on service %s'
                ' zone %s: %s', service, zone, record_xml)

        _xml = textwrap.dedent("""\
            <?xml version="1.0" encoding="UTF-8" ?>
            <request><rr-list>
            {}
            </rr-list></request>""").format('\n'.join(rr_list))

        response = self._put('/services/{}/zones/{}/records'.format(
            service, zone),
                             data=_xml)

        self.logger.debug('Got response:\n%s', response.text)

        if response.status_code != requests.codes.ok:
            raise DnsApiException('Failed to add new records:\n{}'.format(
                response.text))

        self.logger.info('Successfully added %s records', len(rr_list))