Esempio n. 1
0
def createDomain(url,
                 user,
                 password,
                 project,
                 domain,
                 orig_project,
                 region='eqiad1-r',
                 ttl=120):
    auth = v3.Password(auth_url=url,
                       username=user,
                       password=password,
                       user_domain_name='Default',
                       project_domain_name='Default',
                       project_id=orig_project)

    createSession = keystone_session.Session(auth=auth)
    createClient = client.Client(session=createSession, region_name=region)

    auth = v3.Password(auth_url=url,
                       username=user,
                       password=password,
                       user_domain_name='Default',
                       project_domain_name='Default',
                       project_id=project)

    targetSession = keystone_session.Session(auth=auth)

    # Fixme:  Once we move to a more modern version of designateclient (newton?)
    #  we should pass sudo-project-id=wmflabsdotorg here, change createSession
    #  to use the 'admin' project, and remove novaadmin's 'admin' role from wmflabsdotorg.
    targetClient = client.Client(session=targetSession, region_name=region)

    # Create the zone in the initial wmflabsdotorg project.  This
    #  is needed since wmflabs.org lives in that project and
    #  designate prevents subdomain creation elsewhere.
    LOG.info("Creating %s" % domain)
    zone = createClient.zones.create(domain, email='*****@*****.**', ttl=ttl)
    status = 'PENDING'
    # Wait for the domain to actually exist before we transfer it
    while status == 'PENDING':
        zone = createClient.zones.get(domain)
        status = zone['status']
        time.sleep(2)

    transferRequest = createClient.zone_transfers.create_request(
        domain, project)
    transferId = transferRequest['id']
    transferKey = transferRequest['key']

    targetClient.zone_transfers.accept_request(transferId, transferKey)
Esempio n. 2
0
def get_designateclient():
    session = _get_session()

    return designate_client.Client(
        session=session,
        region_name=CONF.service_credentials.os_region_name,
        endpoint_type=CONF.service_credentials.os_endpoint_type)
Esempio n. 3
0
    def _get_client(self):
        if self._client is not None:
            return self._client

        if (self.tenant_id is not None or self.tenant_name is not None):
            auth = v2_auth.Password(auth_url=self.auth_url,
                                    username=self.username,
                                    password=self.password,
                                    tenant_id=self.tenant_id,
                                    tenant_name=self.tenant_name)
        elif self.project_name is not None:
            auth = v3_auth.Password(
                auth_url=self.auth_url,
                username=self.username,
                password=self.password,
                project_name=self.project_name,
                project_domain_name=self.project_domain_name,
                user_domain_name=self.user_domain_name)
        else:
            auth = None

        session = ks_session.Session(auth=auth)
        self._client = client.Client(session=session,
                                     service_type=self.service_type)
        return self._client
Esempio n. 4
0
def designateclient(request):
    token = request.user.token.id

    if keystone.get_version() < 3:
        tenant_id = request.user.tenant_id
        logwrap_info("using keystone v2.")
        # keystone auth object
        auth = v2_plugin.Token(auth_url="https://%s:5000/v2.0" %
                               settings.OPENSTACK_HOST,
                               tenant_id=tenant_id,
                               token=token)
    else:
        project_id = request.user.project_id
        project_domain_id = request.session.get('domain_context')
        logwrap_info("using keystone v3.")
        auth = v3_plugin.Token(auth_url="https://%s:5000/v3" %
                               settings.OPENSTACK_HOST,
                               token=token,
                               project_id=project_id,
                               project_domain_id=project_domain_id)

    # create a session
    ks_session = keystone_session.Session(auth=auth)

    # spawn designate client object
    dns_client = designate_client.Client(session=ks_session)

    logwrap_info("Created a new DNSaaS API Client Object.")
    return dns_client
Esempio n. 5
0
def deleteDomain(url,
                 user,
                 password,
                 project,
                 domain="",
                 region='eqiad1-r',
                 delete_all=False):
    auth = v3.Password(auth_url=url,
                       username=user,
                       password=password,
                       user_domain_name='Default',
                       project_domain_name='Default',
                       project_id=project)

    targetSession = keystone_session.Session(auth=auth)
    targetClient = client.Client(session=targetSession, region_name=region)

    domains = targetClient.zones.list()
    for thisdomain in domains:
        if delete_all:
            LOG.info("Deleting %s" % thisdomain['name'])
            targetClient.zones.delete(thisdomain['id'])
        else:
            if thisdomain['name'] == domain:
                targetClient.zones.delete(thisdomain['id'])
                return
    if not delete_all:
        LOG.warning("Domain %s not found" % domain)
Esempio n. 6
0
def free(network, display, limit):
    """Display defined PTR record for the given CIDR range."""
    ds = designate_client.Client(session=get_session())

    # Save the raw input of the network
    raw_network = network
    network = try_assign(ipaddress.ip_network,
                         network,
                         strict=False,
                         exit=True)

    # Get the lead IP address to skip of the network
    lead_ip_address = raw_network.split('/')[0]

    # Break the network into /24 chunks for PTR search
    # if NETWORK prefix < 24
    if (network.prefixlen < 24):
        network = network.subnets(new_prefix=24)
    else:
        network = [network]
    # Search the subnet for data
    records = []
    for net in network:
        net_ptr, net_zone = _get_ptr_name_zone(net)
        records.extend(_find_free_entries(ds, net, net_zone))
    _list(records, display, limit, lead_ip_address)
Esempio n. 7
0
def get_clients(context):
    global _SESSION

    if not _SESSION:
        _SESSION = session.Session()

    auth = token_endpoint.Token(CONF.designate.url, context.auth_token)
    client = d_client.Client(session=_SESSION, auth=auth)
    admin_auth = password.Password(
        auth_url=CONF.designate.admin_auth_url,
        username=CONF.designate.admin_username,
        password=CONF.designate.admin_password,
        tenant_name=CONF.designate.admin_tenant_name,
        tenant_id=CONF.designate.admin_tenant_id)
    admin_client = d_client.Client(session=_SESSION, auth=admin_auth)
    return client, admin_client
Esempio n. 8
0
 def __init__(self, config_path, debug=False, log=None, region=None):
     """ Create a new designate client to manaage DNS
     `**config_path`` path to ini file with config
     `**log` logger object
     """
     super(Designate, self).__init__(config_path, debug, log, region)
     self.client = designateclient.Client(session=self.sess,
                                          service_type=self.SERVICE_TYPE,
                                          region_name=self.region)
    def designateclient(self, project=None):
        if not project:
            project = self.project

        if project not in self.designateclients:
            session = self.session(project)
            self.designateclients[project] = designateclient.Client(
                session=session, timeout=300, sudo_project_id=project,
                region_name=self.region)
        return self.designateclients[project]
Esempio n. 10
0
def get_clients(context):
    global _SESSION

    if not _SESSION:
        _SESSION = loading.load_session_from_conf_options(CONF, 'designate')

    auth = token_endpoint.Token(CONF.designate.url, context.auth_token)
    client = d_client.Client(session=_SESSION, auth=auth)
    if CONF.designate.auth_type:
        admin_auth = loading.load_auth_from_conf_options(CONF, 'designate')
    else:
        admin_auth = password.Password(
            auth_url=CONF.designate.admin_auth_url,
            username=CONF.designate.admin_username,
            password=CONF.designate.admin_password,
            tenant_name=CONF.designate.admin_tenant_name,
            tenant_id=CONF.designate.admin_tenant_id)
    admin_client = d_client.Client(session=_SESSION, auth=admin_auth)
    return client, admin_client
Esempio n. 11
0
def client(request):
    auth_url = base.url_for(request, 'identity')
    token_kwargs = dict(
        auth_url=auth_url,
        token=request.user.token.id,
        tenant_id=request.user.project_id,
        tenant_name=request.user.project_name,
    )
    auth = generic.Token(**token_kwargs)
    session = keystone_session.Session(auth=auth)
    return designate.Client(session=session)
Esempio n. 12
0
def get_clients(context):
    global _SESSION

    if not _SESSION:
        if CONF.designate.insecure:
            verify = False
        else:
            verify = CONF.designate.ca_cert or True
        _SESSION = session.Session(verify=verify)

    auth = token_endpoint.Token(CONF.designate.url, context.auth_token)
    client = d_client.Client(session=_SESSION, auth=auth)
    admin_auth = password.Password(
        auth_url=CONF.designate.admin_auth_url,
        username=CONF.designate.admin_username,
        password=CONF.designate.admin_password,
        tenant_name=CONF.designate.admin_tenant_name,
        tenant_id=CONF.designate.admin_tenant_id)
    admin_client = d_client.Client(session=_SESSION, auth=admin_auth)
    return client, admin_client
Esempio n. 13
0
def get_clients(context):
    global _SESSION

    if not _SESSION:
        _SESSION = loading.load_session_from_conf_options(CONF, 'designate')

    auth = token_endpoint.Token(CONF.designate.url, context.auth_token)
    client = d_client.Client(session=_SESSION, auth=auth)
    if CONF.designate.auth_type:
        admin_auth = loading.load_auth_from_conf_options(CONF, 'designate')
    else:
        # TODO(tkajinam): Make this fail when admin_* parameters are removed.
        admin_auth = password.Password(
            auth_url=CONF.designate.admin_auth_url,
            username=CONF.designate.admin_username,
            password=CONF.designate.admin_password,
            tenant_name=CONF.designate.admin_tenant_name,
            tenant_id=CONF.designate.admin_tenant_id)
    admin_client = d_client.Client(session=_SESSION,
                                   auth=admin_auth,
                                   endpoint_override=CONF.designate.url)
    return client, admin_client
Esempio n. 14
0
def create(zone, name, type, record, description, ttl, yes):
    """Create a new designate NAME record in the fully qualified ZONE."""
    ds = designate_client.Client(session=get_session())

    if type in 'A':
        # Validate the record IP address
        ip_address = try_assign(ipaddress.ip_address, record, exit=True)
        _create_A_and_PTR_record(ds, zone, name, ip_address, description,
                                 ttl, yes)
    elif type in 'CNAME':
        _create_CNAME_record(ds, zone, name, record, description, ttl, yes)
    else:
        click.echo("Type")
Esempio n. 15
0
    def _get_client(self):
        if self._client is not None:
            return self._client

        auth = v3_auth.Password(
            auth_url=self.auth_url,
            username=self.username,
            password=self.password,
            project_name=self.project_name,
            project_domain_name=self.project_domain_name,
            user_domain_name=self.user_domain_name,
        )

        session = ks_session.Session(auth=auth)
        self._client = client.Client(
            session=session,
            service_type=self.service_type,
            region_name=self.region_name,
        )
        return self._client
Esempio n. 16
0
def delete(zone, name, yes):
    """Delete the A record and PTR reverse record."""
    ds = designate_client.Client(session=get_session())

    # Get the record name
    record_name = "%s.%s" % (name, zone)
    record = try_assign(ds.recordsets.get, zone, record_name, exit=True)

    # Delete A record
    if record['type'] in 'A':
        _show(record)
        if (yes or
            click.confirm("Are you sure you want to delete this record?",
                          abort=True)):
            click.echo("Deleting A record for %s" % record_name)
            old_record_ip = ipaddress.ip_address(record['records'][0])
            old_ptr_record_name, old_ptr_zone = \
                _get_ptr_name_zone(old_record_ip)

            _show(ds.recordsets.delete(zone, record_name))

            ptr_record = try_assign(ds.recordsets.get, old_ptr_zone,
                                    old_ptr_record_name)
            if ptr_record is not None:
                _show(ptr_record)
                if (yes or
                    click.confirm("Do you want to delete PTR record?",
                                  abort=True)):
                    print("Deleting PTR record for %s" %
                          old_ptr_record_name)
                    _show(ds.recordsets.delete(old_ptr_zone,
                                               old_ptr_record_name))
    # Delete CNAME record
    elif record['type'] in 'CNAME':
        _show(record)
        if (yes or
            click.confirm("Are you sure you want to delete this record?",
                          abort=True)):
            click.echo("Deleting CNAME record for %s" % record_name)
            _show(ds.recordsets.delete(zone, record_name))
logging.basicConfig(level='DEBUG')
"""
Example script to create or get a domain and add some records to it.
"""

auth = generic.Password(auth_url=shell.env('OS_AUTH_URL'),
                        username=shell.env('OS_USERNAME'),
                        password=shell.env('OS_PASSWORD'),
                        project_name=shell.env('OS_PROJECT_NAME'),
                        project_domain_id='default',
                        user_domain_id='default')

session = keystone_session.Session(auth=auth)

client = client.Client(session=session)

try:
    zone = client.zones.create('i.io.', email='*****@*****.**')
except exceptions.RemoteError:
    zone = dict([(z['name'], z) for z in client.zones.list()])['i.io.']

print("Recordset list...")
for rs in client.recordsets.list(zone['id']):
    print(rs)

# Here's an example of just passing "www" as the record name vs "www.i.io."
records = ["10.0.0.1"]
rs = client.recordsets.create(zone['id'], 'www', 'A', records)

# Here we're replacing the records with new ones
Esempio n. 18
0
def get_proxy_dns_zones():
    session = clients.session('wmflabsdotorg')
    client = designateclientv2.Client(session=session)
    zones = client.zones.list()
    return zones
Esempio n. 19
0
def get_proxy_dns_recordsets(zone):
    session = clients.session('wmflabsdotorg')
    client = designateclientv2.Client(session=session)
    domains = client.recordsets.list(zone['id'])
    return domains
Esempio n. 20
0
    set_castellan_defaults(GCONF)
else:
    LOG.debug("Using Tatu as key manager.")
    set_castellan_defaults(GCONF, api_class='tatu.castellano.TatuKeyManager')

global_config_files = ['/etc/tatu/tatu.conf']
if CONF.tatu.use_pat_bastions:
    from dragonflow import conf as dragonflow_cfg
    from dragonflow.db import api_nb
    global_files.append('/etc/neutron/dragonflow.ini')

GCONF(args=[], default_config_files=global_config_files)

auth = v3.Password(auth_url=CONF.tatu.auth_url,
                   user_id=CONF.tatu.user_id,
                   password=CONF.tatu.password,
                   project_id=CONF.tatu.project_id)
session = keystone_session.Session(auth=auth)
KEYSTONE = keystone_client.Client(session=session)
NOVA = nova_client.Client('2', session=session)
NEUTRON = neutron_client.Client(session=session)
DESIGNATE = designate_client.Client(session=session)

DRAGONFLOW = None
if CONF.tatu.use_pat_bastions:
    dragonflow_cfg.CONF.set_override('enable_df_pub_sub', False, group='df')
    DRAGONFLOW = api_nb.NbApi.get_instance(False)

# Create a context for use by Castellan
CONTEXT = castellan_utils.credential_factory(conf=CONF)
Esempio n. 21
0
    def __init__(self, instance_id, common_config, source_config, dest_config):

        self.dnsdomain = common_config['dnsdomain']
        self.instance_id = instance_id
        self.source_config = source_config
        self.dest_config = dest_config
        self.common_config = common_config

        source_auth = generic.Password(
            auth_url=self.common_config['keystone_url'],
            username=self.common_config['user'],
            password=self.common_config['password'],
            user_domain_name='Default',
            project_domain_name='Default',
            project_name='admin')
        source_session = keystone_session.Session(auth=source_auth)
        self.source_novaclient = novaclient.Client(
            '2', session=source_session, region_name=source_config['region'])

        self.refresh_instance()
        self.project_id = self.source_instance.tenant_id
        self.user_id = self.source_instance.user_id

        project_auth = generic.Password(
            auth_url=self.common_config['keystone_url'],
            username=self.common_config['user'],
            password=self.common_config['password'],
            user_domain_name='Default',
            project_domain_name='Default',
            project_name=self.project_id)
        project_session = keystone_session.Session(auth=project_auth)
        self.designateclient = designateclient.Client(
            session=project_session, region_name=source_config['region'])

        self.novaclient_projectscope = novaclient.Client(
            '2', session=project_session, region_name=dest_config['region'])

        wmflabs_auth = generic.Password(
            auth_url=self.common_config['keystone_url'],
            username=self.common_config['user'],
            password=self.common_config['password'],
            user_domain_name='Default',
            project_domain_name='Default',
            project_name='wmflabsdotorg')
        wmflabs_session = keystone_session.Session(auth=wmflabs_auth)
        self.wmflabsdesignateclient = designateclient.Client(
            session=wmflabs_session, region_name=source_config['region'])

        dest_auth = generic.Password(
            auth_url=self.common_config['keystone_url'],
            username=self.common_config['user'],
            password=self.common_config['password'],
            user_domain_name='Default',
            project_domain_name='Default',
            project_name='admin')
        self.dest_session = keystone_session.Session(auth=dest_auth)

        self.dest_novaclient = novaclient.Client(
            '2', session=self.dest_session, region_name=dest_config['region'])
        self.dest_neutronclient = neutronclient.Client(
            session=self.dest_session, region_name=dest_config['region'])
        self.dest_keystoneclient = keystoneclient.Client(
            session=self.dest_session, region_name=dest_config['region'])
        self.proxy_endpoint = self.get_proxy_endpoint(self.dest_keystoneclient,
                                                      dest_config['region'])
Esempio n. 22
0
def purge_leaks(delete=False):
    proxyzones = get_proxy_dns_zones()
    proxy_recordsets = {}
    for zone in proxyzones:
        if zone['name'] == 'wmflabs.org.':
            for recordset in get_proxy_dns_recordsets(zone):
                if recordset['records'][0] == PROXY_BACKEND_IP:
                    proxy_recordsets[recordset['name']] = recordset

    allinstances = clients.allinstances(allregions=True)
    all_nova_ips = []
    for instance in allinstances:
        for network in instance.addresses:
            all_nova_ips.append(instance.addresses[network][0]['addr'])

    for project in clients.allprojects():
        projectzones = get_project_dns_zones(project.id)
        project_recordsets = {}
        for zone in projectzones:
            for recordset in get_project_dns_recordsets(project.id, zone):
                if recordset['records'][0] == PROXY_BACKEND_IP:
                    project_recordsets[recordset['name']] = recordset

        mappings = all_mappings(project.id)
        projectinstances = clients.allinstances(project.id, allregions=True)

        all_project_ips = []
        for instance in projectinstances:
            for network in instance.addresses:
                all_project_ips.append(instance.addresses[network][0]['addr'])

        for mapping in mappings:
            backend_ip = mapping['backends'][0].split(":")[1].strip('/')
            if backend_ip not in all_project_ips:
                if backend_ip not in all_nova_ips:
                    print "%s: possible stray proxy: %s" % (project.id, mapping)
                    if delete:
                        delete_mapping(project.id, mapping['domain'])
                else:
                    print "%s: proxy mapping outside of its project: %s" % (project.id, mapping)
            searchname = mapping['domain']
            if not searchname.endswith('.'):
                searchname += '.'
            if searchname.count('.') > 3:
                print "ignoring outlier %s" % searchname
                # These are old leftovers in a different domain, hard to deal with automatically
                continue
            if searchname not in proxy_recordsets and searchname not in project_recordsets:
                print "No dns recordset found for %s" % searchname
            else:
                proxy_recordsets.pop(searchname, None)

    session = clients.session('wmflabsdotorg')
    dotorgclient = designateclientv2.Client(session=session)
    for domain in proxy_recordsets:
        if domain == 'wmflabs.org.':
            continue
        if domain == 'proxy-eqiad.wmflabs.org.':
            continue
        if domain == 'proxy-eqiad1.wmflabs.org.':
            continue
        rset = proxy_recordsets[domain]
        print "found record unassociated with a proxy: %s" % rset
        # Let's make sure there's really nothing there.
        url = "https://%s" % domain.rstrip('.')
        resp = requests.get(url, verify=False)
        print "%s: %s" % (resp.status_code, url)
        if resp.status_code != 502 and resp.status_code != 404:
            print " ----   We found a weird one, at %s" % url
        else:
            if delete:
                dotorgclient.recordsets.delete(rset['zone_id'], rset['id'])
Esempio n. 23
0
for p in payloads:
    # Decode data from base64
    data = base64.b64decode(p['Payload'])
    try:
        # Retrieve data from Payload
        data = json.loads(base64.b64decode(p['Payload']))
        tenant_id = data['tenant_id']
        floating_ip = data['floating_ip']
        tenant_name = getTenantName(tenant_id)
        if tenant_name is not None:
            print "Modifying Tenant " + tenant_name

            # Set authentication of admin user for this tenant
            session = getAuthSession(tenant_id)
            client = desigClient.Client(session=session)

            # Get default zone of tenant
            zone_id = getZoneID(client, tenant_id)

            if zone_id is not None:
                print "Zone present : " + zone_id
                rs = client.recordsets.create(zone_id, '*', 'A', [floating_ip])
                print "New IP added : " + floating_ip
            else:
                syslog.syslog(
                    syslog.LOG_ERR,
                    '[CONSUL_HANDLER] Zone ID not found for tenant_id: ' +
                    tenant_id)
        else:
            print "Tenant Not Found for id : " + tenant_id
Esempio n. 24
0
from keystoneclient.session import Session as KeystoneSession
from keystoneclient.auth.identity.v3 import Password as KeystonePassword
from keystoneclient.v3 import Client as KeystoneClient
#from novaclient import client as novaclient
from designateclient.v2 import client as designateclient


def get_keystone_session(project):
    return KeystoneSession(auth=KeystonePassword(
        auth_url="http://cloudcontrol1003.wikimedia.org:5000/v3",
        username="******",
        password=open('novaobserver_password').read(),
        project_name=project,
        user_domain_name='default',
        project_domain_name='default'))


session = get_keystone_session('admin')
#nclient = novaclient.Client("2.0", session=session, region_name='eqiad1-r')
#for s in nclient.servers.list():
#    print(s)

from designateclient.v2.base import V2Controller

client = designateclient.Client(session=session)
for zone in client.zones.list():
    print(zone, dir(zone))
Esempio n. 25
0
def get_project_dns_zones(project_id):
    session = clients.session(project_id)
    client = designateclientv2.Client(session=session)
    zones = client.zones.list()
    return zones
def main():
    if len(sys.argv) != 6 and len(sys.argv) != 2:
        print(
            "Usgae:  {} input_file [auth_url username password tenant]".format(
                sys.argv[0]))
        exit(1)
    if len(sys.argv) == 6:
        print(
            "Creating DNS records using record defs from {}, authurl {}, username {}, tenant {}"
            .format(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[5]))
    else:
        print(
            "Creating DNS records using record defs from {}, authurl {}, username {}, tenant {}"
            .format(shell.env('OS_AUTH_URL'), shell.env('OS_USERNAME'),
                    shell.env('OS_PASSWORD'), shell.env('OS_PROJECT_NAME')))

    print("Usage:  {} disabled until changed".format(sys.argv[0]))
    exit(1)

    inputfilepath = sys.argv[1]
    auth = ""

    if len(sys.argv) == 2:
        auth = generic.Password(auth_url=shell.env('OS_AUTH_URL'),
                                username=shell.env('OS_USERNAME'),
                                password=shell.env('OS_PASSWORD'),
                                project_name=shell.env('OS_PROJECT_NAME'),
                                project_domain_id='default',
                                user_domain_id='default')
    else:
        auth = generic.Password(auth_url=sys.argv[2],
                                username=sys.argv[3],
                                password=sys.argv[4],
                                project_name=sys.argv[5],
                                project_domain_id='default',
                                user_domain_id='default')

    if not auth:
        print("Fail to get authenticated from OpenStack")
        exit(1)

    session = keystone_session.Session(auth=auth)
    client = designate_client.Client(session=session)

    zone_name = 'simpledemo.onap.org'
    zone_name_dot = zone_name + '.'

    zone_list = client.zones.list()
    print("before: \n{}".format(json.dumps(zone_list, indent=4)))

    zone = find_entry_by_name(entry_list=zone_list, entry_name=zone_name_dot)
    if zone:
        print("exitsing zone: zone id {}".format(zone['id']))
    else:
        zone = client.zones.create(zone_name_dot, email='*****@*****.**')
        print("newly created zone: zone id {}".format(zone['id']))

    recordsets = client.recordsets.list(zone['id'])
    # delete all exitsing A and CNAME records under the zone_name
    for recordset in recordsets:
        if not recordset['name'].endswith(zone_name_dot):
            continue
        print("Deleting recordset {}".format(recordset['name']))
        if recordset['type'] == 'A':
            client.recordsets.delete(zone['id'], recordset['id'])
        elif recordset['type'] == 'CNAME':
            client.recordsets.delete(zone['id'], recordset['id'])

    with open(inputfilepath, 'r') as inputfile:
        records_to_add = yaml.load(inputfile)
        for key, value in records_to_add.iteritems():
            if not key.endswith(zone_name):
                continue
            try:
                socket.inet_aton(value)
                # take zone name out (including the . before it)
                key = key[:-(len(zone_name) + 1)]
                print("Creating DNS A record for: {} - {}".format(key, value))
                rs = client.recordsets.create(zone['id'], key, 'A', [value])
            except:
                print()

        for key, value in records_to_add.iteritems():
            if not key.endswith(zone_name):
                continue
            try:
                socket.inet_aton(value)
            except:
                # take zone name out (and the . before it)
                key = key[:-(len(zone_name) + 1)]
                if not value.endswith('.'):
                    value = value + '.'
                print("Creating DNS CNAME record for: {} - {}".format(
                    key, value))
                rs = client.recordsets.create(zone['id'], key, 'CNAME',
                                              [value])

    recordsets = client.recordsets.list(zone['id'])
    print("before: \n{}".format(json.dumps(recordsets, indent=4)))
Esempio n. 27
0
def get_project_dns_recordsets(project_id, zone):
    session = clients.session(project_id)
    client = designateclientv2.Client(session=session)
    domains = client.recordsets.list(zone['id'])
    return domains
Esempio n. 28
0
    def handle(self, request, data):
        proxyip = socket.gethostbyname(
            urlparse.urlparse(base.url_for(request, 'proxy')).hostname)
        if data.get('domain') == 'wmflabs.org.':
            auth = identity_generic.Password(
                auth_url=base.url_for(request, 'identity'),
                username=getattr(settings, "WMFLABSDOTORG_ADMIN_USERNAME", ''),
                password=getattr(settings, "WMFLABSDOTORG_ADMIN_PASSWORD", ''),
                tenant_name='wmflabsdotorg',
                user_domain_id='default',
                project_domain_id='default')
            c = designateclientv2.Client(session=keystone_session.Session(
                auth=auth))

            LOG.warn('Got create client')
            # Create the record in the wmflabsdotorg project. This is needed
            # since wmflabs.org lives in that project and designate prevents
            # subdomain creation elsewhere.
            zoneid = None
            for zone in c.zones.list():
                if zone['name'] == 'wmflabs.org.':
                    zoneid = zone['id']
                    break
            else:
                raise Exception("No zone ID")
            LOG.warn('Got zone ID')
            c.recordsets.create(zoneid,
                                data.get('record') + '.wmflabs.org.', 'A',
                                [proxyip])
        else:
            # TODO: Move this to designate v2 API, reuse some code
            c = designateapi.designateclient(request)
            domainid = None
            for domain in c.domains.list():
                if domain.name == data.get('domain'):
                    domainid = domain.id
                    break
            else:
                raise Exception("No domain ID")
            record = Record(name=data.get('record') + '.' + data.get('domain'),
                            type='A',
                            data=proxyip)
            c.records.create(domainid, record)

        d = {
            "backends": [
                'http://%s:%s' %
                (data.get('backendInstance'), data.get('backendPort'))
            ],
            "domain":
            data.get('record') + '.' + data.get('domain').rstrip('.')
        }

        try:
            resp = requests.put(base.url_for(request, 'proxy') + '/mapping',
                                data=json.dumps(d))
            if resp:
                return True
            else:
                raise Exception("Got status: " + resp.status_code)
        except Exception:
            exceptions.handle(self.request,
                              _("Unable to create proxy: " + resp.text))
            return False
Esempio n. 29
0
#!/usr/bin/python3
from datetime import datetime, timedelta
import yaml

from designateclient.v2 import client as designateclient
from keystoneauth1.identity import v3
from keystoneauth1 import session as keystone_session

with open('/etc/acme-chief/designate-sync-config.yaml') as f:
    config = yaml.safe_load(f)

client = designateclient.Client(session=keystone_session.Session(
    auth=v3.Password(auth_url=config['OS_AUTH_URL'],
                     username=config['OS_USERNAME'],
                     password=config['OS_PASSWORD'],
                     user_domain_name='default',
                     project_domain_name='default',
                     project_name=config['OS_PROJECT_NAME'])),
                                region_name=config['OS_REGION_NAME'])

# This type of script is unnecessary for gdnsd which doesn't really have much
# of an API, it just has a command to add records specifically for ACME.
# However, when we add such records to designate in designate-sync.py it
# expects them to be permanent - they're not, so this script cleans them up
# after an hour.
for zone in client.zones.list():
    for recordset in client.recordsets.list(zone['id']):
        if recordset['name'].startswith(
                '_acme-challenge.') and recordset['type'] == 'TXT':
            updated = datetime.fromisoformat(recordset['updated_at']
                                             or recordset['created_at'])
Esempio n. 30
0
    def delete(self, request, obj_id):
        record = obj_id[:obj_id.find('.')]
        domain = obj_id[obj_id.find('.') + 1:]
        if not domain.endswith('.'):
            domain += '.'

        # First let's make sure that this proxy is really ours to delete.
        existing_domains = [proxy.domain for proxy in get_proxy_list(request)]
        if obj_id not in existing_domains:
            raise Exception(
                "Proxy \'%s\' is to be deleted but is not owned by this view."
                % obj_id)

        if domain == 'wmflabs.org.':
            auth = identity_generic.Password(
                auth_url=base.url_for(request, 'identity'),
                username=getattr(settings, "WMFLABSDOTORG_ADMIN_USERNAME", ''),
                password=getattr(settings, "WMFLABSDOTORG_ADMIN_PASSWORD", ''),
                tenant_name='wmflabsdotorg',
                user_domain_id='default',
                project_domain_id='default')
            c = designateclientv2.Client(session=keystone_session.Session(
                auth=auth))

            # Delete the record from the wmflabsdotorg project. This is needed
            # since wmflabs.org lives in that project and designate (quite
            # reasonably) prevents subdomain deletion elsewhere.
            zoneid = None
            for zone in c.zones.list():
                if zone['name'] == 'wmflabs.org.':
                    zoneid = zone['id']
                    break
            else:
                raise Exception("No zone ID")
            recordsetid = None
            for recordset in c.recordsets.list(zoneid):
                if recordset['type'] == 'A' and recordset[
                        'name'] == record + '.' + domain:
                    recordsetid = recordset['id']
                    break
            else:
                raise Exception("No recordset ID")
            c.recordsets.delete(zoneid, recordsetid)
        else:
            c = designateapi.designateclient(request)
            domainid = None
            for d in c.domains.list():
                if d.name == domain:
                    domainid = d.id
                    break
            else:
                LOG.warn('Woops! Failed domain ID for domain ' + domain)
                raise Exception("No domain ID")
            recordid = None
            for r in c.records.list(domainid):
                if r.name == obj_id and r.type == 'A':
                    recordid = r.id
                    break
            else:
                LOG.warn('Woops! Failed record ID for record ' + record)
                raise Exception("No record ID")

            c.records.delete(domainid, recordid)

        resp = requests.delete(
            base.url_for(request, 'proxy') + '/mapping/' + obj_id)
        if not resp:
            raise Exception("Got status " + resp.status_code)