Create both A and PTR (reverse) records for a host.

    CLI Example:

    .. code-block:: bash

        salt-run ddns.add_host domain.com my-test-vm 3600 10.20.30.40 my-tsig-key /etc/salt/tsig.keyring 10.0.0.1 5
508290
def add_host(zone, name, ttl, ip, keyname, keyfile, nameserver, timeout,
             port=53, keyalgorithm='hmac-md5'):
    '''
    
    '''
    res = []
    if zone in name:
        name = name.replace(zone, '').rstrip('.')
    fqdn = '{0}.{1}'.format(name, zone)

    ret = create(zone, name, ttl, 'A', ip, keyname, keyfile, nameserver,
                 timeout, port, keyalgorithm)
    res.append(ret[fqdn])

    parts = ip.split('.')[::-1]
    i = len(parts)
    popped = []

    # Iterate over possible reverse zones
    while i > 1:
        p = parts.pop(0)
        i -= 1
        popped.append(p)

        zone = '{0}.{1}'.format('.'.join(parts), 'in-addr.arpa.')
        name = '.'.join(popped)
        rev_fqdn = '{0}.{1}'.format(name, zone)
        ret = create(zone, name, ttl, 'PTR', "{0}.".format(fqdn), keyname,
                     keyfile, nameserver, timeout, port, keyalgorithm)

        if "Created" in ret[rev_fqdn]:
            res.append(ret[rev_fqdn])
            return {fqdn: res}

    res.append(ret[rev_fqdn])

    return {fqdn: res}
1044875
def build(template='/', host=None, scheme=None, port=None, **template_vars):
        
        # TODO: refactor to build_absolute and build_relative instead of handling based on params
        parsed_host = urlparse.urlparse(host if host is not None else '')
        host_has_scheme = bool(parsed_host.scheme)

        if host_has_scheme:
            host = parsed_host.netloc
            # Prioritize scheme parameter, but if not specified, use scheme implied from host
            scheme = parsed_host.scheme if scheme is None else scheme

        port = port or parsed_host.port  # Default to port override

        unparsed_path = urlparse.urlparse(template.format(**template_vars)).geturl()

        # If a host was specified, try to return a full url
        if host:
            if not scheme:
                raise ValueError('No scheme supplied and scheme could not be inferred from the host: {}'.format(host))
            if port:
                host_no_port = host.partition(':')[0]  # Extract the host with no port supplied
                host = '{host_no_port}:{port}'.format(host_no_port=host_no_port, port=port)
            constructed_url = '//' + host + unparsed_path
            url = urlparse.urlparse(constructed_url, scheme=scheme).geturl()
        else:
            url = unparsed_path

        # Remove trailing parameter characters
        url = url[:-1] if url[-1] == '?' else url
        url = url[:-1] if url[-1] == '&' else url
        return url
1162298
def buildProtocol(self, addr):
        
        self.resetDelay()  # reset reconnection backoff state
        clargs = self.client_args.copy()

        # optionally configure antennas from self.antenna_dict, which looks
        # like {'10.0.0.1:5084': {'1': 'ant1', '2': 'ant2'}}
        hostport = '{}:{}'.format(addr.host, addr.port)
        logger.debug('Building protocol for %s', hostport)
        if hostport in self.antenna_dict:
            clargs['antennas'] = [
                int(x) for x in self.antenna_dict[hostport].keys()]
        elif addr.host in self.antenna_dict:
            clargs['antennas'] = [
                int(x) for x in self.antenna_dict[addr.host].keys()]
        logger.debug('Antennas in buildProtocol: %s', clargs.get('antennas'))

        logger.debug('%s start_inventory: %s', hostport,
                     clargs.get('start_inventory'))
        if self.start_first and not self.protocols:
            # this is the first protocol, so let's start it inventorying
            clargs['start_inventory'] = True
        proto = LLRPClient(factory=self, **clargs)

        # register state-change callbacks with new client
        for state, cbs in self._state_callbacks.items():
            for cb in cbs:
                proto.addStateCallback(state, cb)

        # register message callbacks with new client
        for msg_type, cbs in self._message_callbacks.items():
            for cb in cbs:
                proto.addMessageCallback(msg_type, cb)

        return proto
753032
def create(host, port):
    
    wrapper = WrapperServer({
        'server': None
    })
    d = {
        'listen_port': port,
        'changer': wrapper
    }
    if host:
        d['listen_bind_ip'] = host

    ses = MeasureServer(d)
    wrapper.server = ses
    return [wrapper], cmd_line
362717
def keys_create(cls, fqdn, flag):
        """"""
        data = {
            "flags": flag,
        }
        meta = cls.get_fqdn_info(fqdn)
        url = meta['domain_keys_href']
        ret, headers = cls.json_post(url, data=json.dumps(data),
                                     return_header=True)
        return cls.json_get(headers['location'])
1322185
def cli(env, **kwargs):
    

    mgr = SoftLayer.DedicatedHostManager(env.client)
    tables = []

    if not kwargs['flavor'] and not kwargs['datacenter']:
        options = mgr.get_create_options()

        # Datacenters
        dc_table = formatting.Table(['datacenter', 'value'])
        dc_table.sortby = 'value'
        for location in options['locations']:
            dc_table.add_row([location['name'], location['key']])
        tables.append(dc_table)

        dh_table = formatting.Table(['Dedicated Virtual Host Flavor(s)', 'value'])
        dh_table.sortby = 'value'
        for item in options['dedicated_host']:
            dh_table.add_row([item['name'], item['key']])
        tables.append(dh_table)
    else:
        if kwargs['flavor'] is None or kwargs['datacenter'] is None:
            raise exceptions.ArgumentError('Both a flavor and datacenter need '
                                           'to be passed as arguments '
                                           'ex. slcli dh create-options -d '
                                           'ams01 -f '
                                           '56_CORES_X_242_RAM_X_1_4_TB')
        router_opt = mgr.get_router_options(kwargs['datacenter'], kwargs['flavor'])
        br_table = formatting.Table(
            ['Available Backend Routers'])
        for router in router_opt:
            br_table.add_row([router['hostname']])
        tables.append(br_table)

    env.fout(formatting.listing(tables, separator='\n'))
641602
def recordHostname(self, basedir):
        ""
        log.msg("recording hostname in twistd.hostname")
        filename = os.path.join(basedir, "twistd.hostname")

        try:
            hostname = os.uname()[1]  # only on unix
        except AttributeError:
            # this tends to fail on non-connected hosts, e.g., laptops
            # on planes
            hostname = socket.getfqdn()

        try:
            with open(filename, "w") as f:
                f.write("{0}\n".format(hostname))
        except Exception:
            log.msg("failed - ignoring")
870081
def lookup_reverse(ip_address):
    """"""
    try:
        type(ipaddress.ip_address(ip_address))
    except ValueError:
        return {}

    record = reversename.from_address(ip_address)
    hostname = str(resolver.query(record, "PTR")[0])[:-1]
    return {'hostname': hostname}
38643
def _create_record(self, rtype, name, content):
        """"""
        # check if record already exists
        existing_records = self._list_records(rtype, name, content)
        if len(existing_records) >= 1:
            return True

        record = {
            "record_type": rtype,
            "name": self._relative_name(name),
            "content": content,
        }
        if self._get_lexicon_option("ttl"):
            record["ttl"] = self._get_lexicon_option("ttl")
        if self._get_lexicon_option("priority"):
            record["prio"] = self._get_lexicon_option("priority")

        payload = self._post(
            "/v1/domains/{0}/records".format(self.domain),
            {"record": record},
        )

        status = "id" in payload.get("record", {})
        LOGGER.debug("create_record: %s", status)
        return status
628546
def add_record(cls, fqdn, name, type, value, ttl):
        """"""
        data = {
            "rrset_name": name,
            "rrset_type": type,
            "rrset_values": value,
        }
        if ttl:
            data['rrset_ttl'] = int(ttl)
        meta = cls.get_fqdn_info(fqdn)
        url = meta['domain_records_href']
        return cls.json_post(url, data=json.dumps(data))
965660
def create_record(self, rtype, name, content, ttl):
        """"""
        version = None
        ret = False

        # This isn't quite "do nothing" if the record already exists.
        # In this case, no new record will be created, but a new zone version
        # will be created and set.
        try:
            version = self._api.domain.zone.version.new(
                self._api_key, self._zone_id)
            self._api.domain.zone.record.add(self._api_key, self._zone_id, version,
                                             {'type': rtype.upper(),
                                              'name': name,
                                              'value': content,
                                              'ttl': ttl
                                              })
            self._api.domain.zone.version.set(
                self._api_key, self._zone_id, version)
            ret = True

        finally:
            if not ret and version is not None:
                self._api.domain.zone.version.delete(
                    self._api_key, self._zone_id, version)

        LOGGER.debug("create_record: %s", ret)
        return ret
219783
def create(cls, name, datacenter, backends, vhosts, algorithm,
               ssl_enable, zone_alter):
        
        datacenter_id_ = int(Datacenter.usable_id(datacenter))
        params = {
            'datacenter_id': datacenter_id_,
            'name': name,
            'lb': {'algorithm': algorithm},
            'override': True,
            'ssl_enable': ssl_enable,
            'zone_alter': zone_alter
        }
        if vhosts:
            params['vhosts'] = vhosts
        if backends:
            params['servers'] = backends
        try:
            result = cls.call('hosting.rproxy.create', params)
            cls.echo('Creating your webaccelerator %s' % params['name'])
            cls.display_progress(result)
            cls.echo('Your webaccelerator have been created')
            return result
        except Exception as err:
            if err.code == 580142:
                for vhost in params['vhosts']:
                    dns_entry = cls.call(
                        'hosting.rproxy.vhost.get_dns_entries',
                        {'datacenter': datacenter_id_, 'vhost': vhost})
                    txt_record = "@ 3600 IN TXT \"%s=%s\"" % (dns_entry['key'],
                                                              dns_entry['txt'])

                    cname_record = "%s 3600 IN CNAME %s" % (dns_entry['key'],
                                                            dns_entry['cname'])

                    cls.echo('The domain %s don\'t use Gandi DNS or you have'
                             ' not sufficient right to alter the zone file. '
                             'Edit your zone file adding this TXT and CNAME '
                             'record and try again :' % vhost)
                    cls.echo(txt_record)
                    cls.echo(cname_record)
                    cls.echo('\nOr add a file containing %s at :\n'
                             'http://%s/%s.txt\n' % (dns_entry['txt'],
                                                     dns_entry['domain'],
                                                     dns_entry['txt']))
                    cls.separator_line('-', 4)
            else:
                cls.echo(err)
960102
def create(host, port):
    
    wrapper = WrapperEchoServer({
        'server': None
    })
    d = {
        'listen_port': port,
        'changer': wrapper
    }
    if host:
        d['listen_bind_ip'] = host

    ses = EchoServer(d)
    wrapper.server = ses
    return [wrapper], cmd_line
1277570
def parse_create(prs, conn):
    
    prs_create = prs.add_parser(
        'create', help='create record of specific zone')
    set_option(prs_create, 'domain')
    conn_options(prs_create, conn)
    prs_create.set_defaults(func=create)
343940
function createServer(listen, opt) {

  if (!listen) {
    throw new TypeError('listen required');
  }
  var options = opt || Object.create(null);
  var my = {
    keepalive: Number(options.keepalive) || 2000,
    callback: typeof options.callback === 'function' ? options.callback : false,
    http: false,
    https: false
  };
  if (typeof options.http === 'object') {
    my.http = {
      port: Number(options.http.port) || 3000,
      host: String(options.http.host || '127.0.0.1')
    };
  }
  if (typeof options.https === 'object') {
    my.https = options.https;
    my.https.port = Number(options.https.port) || 3000;
    my.https.host = String(options.https.host || '127.0.0.1');
  }

  var hosts = Object.create(null);
  var server = net.createServer(function(sock) {

    sock.setKeepAlive(true, my.keepalive); // https://en.wikipedia.org/wiki/Keepalive
    sock.on('data', function(buff) {

      if (sock._id) {
        hosts[sock._id] = {
          state: sock.readyState,
          beat: Date.now()
        };
      } else if (buff.length > 1) { // set client id
        var _id = String(buff);
        hosts[_id] = {
          state: sock.readyState,
          beat: Date.now()
        };
        sock._id = _id;
      }
      return;

    }).on('close', function(had_error) {

      if (sock._id) {
        hosts[sock._id] = {
          state: sock.readyState,
          beat: Date.now()
        };
      }
      // error hook [with client id]
      return my.callback !== false ? my.callback(had_error, sock._id) : null;
    });
  });

  if (options.host && typeof listen === 'number') { // tpc only
    server.listen(listen, options.host);
  } else {
    server.listen(listen);
  }

  if (my.http || my.https) {
    var web = function(req, res) {

      var out = '';
      res.setHeader('Content-Type', 'application/json; charset=utf-8');
      var url = decodeURI(req.url);
      url = url.substr(1, url.length);
      if (url === '') {
        out = JSON.stringify(hosts);
      } else if (hosts[url] !== undefined) {
        out = JSON.stringify(hosts[url]);
      } else {
        res.statusCode = 404;
      }
      return res.end(out);
    };
    if (my.http) {
      require('http').createServer(web).listen(my.http.port, my.http.host);
    }
    if (my.https) {
      require('https').createServer(my.https, web).listen(my.https.port,
        my.https.host);
    }
  }

  server._hosts = hosts; // hosts reference
  return server;
}
1015992
def create_result(self, ip, host_port, container_port, meta, val, dividers):
        
        if host_port in ('', NotSpecified) and container_port in ('', NotSpecified):
            container_port = ip
            ip = NotSpecified
            host_port = NotSpecified
        elif container_port in ('', NotSpecified):
            container_port = host_port
            host_port = ip
            ip = NotSpecified
        elif host_port in ('', NotSpecified):
            host_port = NotSpecified

        if host_port == '':
            host_port = NotSpecified
        if container_port == '':
            container_port = NotSpecified

        if host_port is not NotSpecified:
            host_port = sb.integer_spec().normalise(meta.indexed_at('host_port'), host_port)
        container_port = sb.required(container_port_spec()).normalise(meta.indexed_at('container_port'), container_port)

        return Port(ip, host_port, container_port)
1158738
function createMXRecord (domain, subdomain, priority, ip, cb) {
        var body = {
            name: subdomain,
            type: 'MX',
            content: [priority, ip].join(' ')
        };
        _hoverRequest('POST', '/domains/' + domain + '/dns', body, cb);
    }