예제 #1
0
 def test_returns_test_path(self):
     self.assertEqual(
         os.path.abspath(
             os.path.join(os.path.dirname(__file__), "..", "..",
                          "templates")),
         locate_template(""),
     )
예제 #2
0
파일: config.py 프로젝트: kcns008/maas
def get_config_v4(
        template_name: str, global_dhcp_snippets: Sequence[dict],
        failover_peers: Sequence[dict], shared_networks: Sequence[dict],
        hosts: Sequence[dict], omapi_key: str) -> str:
    """Return a DHCP config file based on the supplied parameters.

    :param template_name: Template file name: `dhcpd.conf.template` for the
        IPv4 template.
    :return: A full configuration, as a string.
    """
    bootloader = compose_conditional_bootloader(False)
    platform_codename = linux_distribution()[2]
    template_file = locate_template('dhcp', template_name)
    template = tempita.Template.from_filename(template_file, encoding="UTF-8")
    dhcp_socket = get_data_path('/var/lib/maas/dhcpd.sock')

    # Helper functions to stuff into the template namespace.
    helpers = {
        "oneline": normalise_whitespace,
        "commalist": normalise_any_iterable_to_comma_list,
        "running_in_snap": snappy.running_in_snap(),
    }

    rack_addrs = [
        IPAddress(addr)
        for addr in net_utils.get_all_interface_addresses()]

    for shared_network in shared_networks:
        for subnet in shared_network["subnets"]:
            cidr = IPNetwork(subnet['subnet_cidr'])
            rack_ips = [
                str(rack_addr)
                for rack_addr in rack_addrs
                if rack_addr in cidr
            ]
            if len(rack_ips) > 0:
                subnet["next_server"] = rack_ips[0]
            ntp_servers = subnet["ntp_servers"]  # Is a list.
            ntp_servers_ipv4, ntp_servers_ipv6 = _get_addresses(*ntp_servers)
            subnet["ntp_servers_ipv4"] = ", ".join(ntp_servers_ipv4)
            subnet["ntp_servers_ipv6"] = ", ".join(ntp_servers_ipv6)

    try:
        return template.substitute(
            global_dhcp_snippets=global_dhcp_snippets, hosts=hosts,
            failover_peers=failover_peers, shared_networks=shared_networks,
            bootloader=bootloader, platform_codename=platform_codename,
            omapi_key=omapi_key, dhcp_helper=(
                get_path('/usr/sbin/maas-dhcp-helper')),
            dhcp_socket=dhcp_socket, **helpers)
    except (KeyError, NameError) as error:
        raise DHCPConfigError(
            "Failed to render DHCP configuration.") from error
예제 #3
0
def render_dns_template(template_name, *parameters):
    """Generate contents for a DNS configuration or zone file.

    :param template_name: Name of the template file that should be rendered.
        It must be in provisioningserver/templates/dns/.
    :param parameters: One or more dicts of paramaters to be passed to the
        template.  Each adds to (and may overwrite) the previous ones.
    """
    template_path = locate_template('dns', template_name)
    template = tempita.Template.from_filename(template_path, encoding="UTF-8")
    combined_params = {}
    for params_dict in parameters:
        combined_params.update(params_dict)
    try:
        return template.substitute(combined_params)
    except NameError as error:
        raise DNSConfigFail(*error.args)
예제 #4
0
    def write_config():
        allowed_subnets = Subnet.objects.filter(allow_proxy=True)
        cidrs = [subnet.cidr for subnet in allowed_subnets]
        config = Config.objects.get_configs([
            'http_proxy', 'maas_proxy_port', 'use_peer_proxy',
            'prefer_v4_proxy', 'enable_http_proxy'
        ])

        http_proxy = config["http_proxy"]
        upstream_proxy_enabled = (config["use_peer_proxy"] and http_proxy)
        context = {
            'allowed': allowed_subnets,
            'modified': str(datetime.date.today()),
            'fqdn': socket.getfqdn(),
            'cidrs': cidrs,
            'running_in_snap': snappy.running_in_snap(),
            'snap_path': snappy.get_snap_path(),
            'snap_data_path': snappy.get_snap_data_path(),
            'snap_common_path': snappy.get_snap_common_path(),
            'upstream_peer_proxy': upstream_proxy_enabled,
            'dns_v4_first': config['prefer_v4_proxy'],
            'maas_proxy_port': config['maas_proxy_port'],
        }

        proxy_enabled = config["enable_http_proxy"]
        if proxy_enabled and upstream_proxy_enabled:
            http_proxy_hostname = urlparse(http_proxy).hostname
            http_proxy_port = urlparse(http_proxy).port
            context.update({
                'upstream_proxy_address': http_proxy_hostname,
                'upstream_proxy_port': http_proxy_port,
            })

        template_path = locate_template('proxy', MAAS_PROXY_CONF_TEMPLATE)
        template = tempita.Template.from_filename(template_path,
                                                  encoding="UTF-8")
        try:
            content = template.substitute(context)
        except NameError as error:
            raise ProxyConfigFail(*error.args)
        # Squid prefers ascii.
        content = content.encode("ascii")
        target_path = get_proxy_config_path()
        atomic_write(content, target_path, overwrite=True, mode=0o644)
예제 #5
0
파일: config.py 프로젝트: casual-lemon/maas
def write_config(
    allowed_cidrs,
    peer_proxies=None,
    prefer_v4_proxy=False,
    maas_proxy_port=8000,
):
    """Write the proxy configuration."""
    if peer_proxies is None:
        peer_proxies = []

    snap_paths = snap.SnapPaths.from_environ()
    context = {
        "modified": str(datetime.date.today()),
        "fqdn": socket.getfqdn(),
        "cidrs": allowed_cidrs,
        "running_in_snap": snap.running_in_snap(),
        "snap_path": snap_paths.snap,
        "snap_data_path": snap_paths.data,
        "snap_common_path": snap_paths.common,
        "dns_v4_first": prefer_v4_proxy,
        "maas_proxy_port": maas_proxy_port,
    }

    formatted_peers = []
    for peer in peer_proxies:
        formatted_peers.append({
            "address": urlparse(peer).hostname,
            "port": urlparse(peer).port
        })
    context["peers"] = formatted_peers

    template_path = locate_template("proxy", MAAS_PROXY_CONF_TEMPLATE)
    template = tempita.Template.from_filename(template_path, encoding="UTF-8")
    try:
        content = template.substitute(context)
    except NameError as error:
        raise ProxyConfigFail(*error.args)

    # Squid prefers ascii.
    content = content.encode("ascii")
    target_path = get_proxy_config_path()
    atomic_write(content, target_path, overwrite=True, mode=0o644)
예제 #6
0
파일: config.py 프로젝트: zhangrb/maas
def write_config(
        allowed_cidrs, peer_proxies=None,
        prefer_v4_proxy=False, maas_proxy_port=8000):
    """Write the proxy configuration."""
    if peer_proxies is None:
        peer_proxies = []

    context = {
        'modified': str(datetime.date.today()),
        'fqdn': socket.getfqdn(),
        'cidrs': allowed_cidrs,
        'running_in_snap': snappy.running_in_snap(),
        'snap_path': snappy.get_snap_path(),
        'snap_data_path': snappy.get_snap_data_path(),
        'snap_common_path': snappy.get_snap_common_path(),
        'dns_v4_first': prefer_v4_proxy,
        'maas_proxy_port': maas_proxy_port,
    }

    formatted_peers = []
    for peer in peer_proxies:
        formatted_peers.append({
            'address': urlparse(peer).hostname,
            'port': urlparse(peer).port
        })
    context['peers'] = formatted_peers

    template_path = locate_template('proxy', MAAS_PROXY_CONF_TEMPLATE)
    template = tempita.Template.from_filename(
        template_path, encoding="UTF-8")
    try:
        content = template.substitute(context)
    except NameError as error:
        raise ProxyConfigFail(*error.args)

    # Squid prefers ascii.
    content = content.encode("ascii")
    target_path = get_proxy_config_path()
    atomic_write(content, target_path, overwrite=True, mode=0o644)
예제 #7
0
def write_config(write_local, forwarders=None, port=None):
    """Write the syslog configuration."""
    context = {
        "user":
        "******",
        "group":
        "maas",
        "drop_priv":
        True,
        "work_dir":
        get_syslog_workdir_path(),
        "log_dir":
        get_syslog_log_path(),
        "write_local":
        write_local,
        "port":
        port if port else 5247,
        "forwarders": (sorted(forwarders, key=itemgetter("name"))
                       if forwarders is not None else []),
    }

    # Running inside the snap rsyslog is root.
    if snappy.running_in_snap():
        context["user"] = "******"
        context["group"] = "root"
        context["drop_priv"] = False

    template_path = locate_template("syslog", MAAS_SYSLOG_CONF_TEMPLATE)
    template = tempita.Template.from_filename(template_path, encoding="UTF-8")
    try:
        content = template.substitute(context)
    except NameError as error:
        raise SyslogConfigFail(*error.args)

    # Squid prefers ascii.
    content = content.encode("ascii")
    target_path = get_syslog_config_path()
    atomic_write(content, target_path, overwrite=True, mode=0o644)
예제 #8
0
파일: config.py 프로젝트: zhangrb/maas
def write_config(write_local, forwarders=None, port=None):
    """Write the syslog configuration."""
    context = {
        'user':
        '******',
        'group':
        'maas',
        'drop_priv':
        True,
        'work_dir':
        get_syslog_workdir_path(),
        'log_dir':
        get_syslog_log_path(),
        'write_local':
        write_local,
        'port':
        port if port else 5247,
        'forwarders': (sorted(forwarders, key=itemgetter('name'))
                       if forwarders is not None else []),
    }

    # Running inside the snap rsyslog is root.
    if snappy.running_in_snap():
        context['user'] = '******'
        context['group'] = 'root'
        context['drop_priv'] = False

    template_path = locate_template('syslog', MAAS_SYSLOG_CONF_TEMPLATE)
    template = tempita.Template.from_filename(template_path, encoding="UTF-8")
    try:
        content = template.substitute(context)
    except NameError as error:
        raise SyslogConfigFail(*error.args)

    # Squid prefers ascii.
    content = content.encode("ascii")
    target_path = get_syslog_config_path()
    atomic_write(content, target_path, overwrite=True, mode=0o644)
예제 #9
0
파일: config.py 프로젝트: kcns008/maas
def get_config_v6(
        template_name: str, global_dhcp_snippets: Sequence[dict],
        failover_peers: Sequence[dict], shared_networks: Sequence[dict],
        hosts: Sequence[dict], omapi_key: str) -> str:
    """Return a DHCP config file based on the supplied parameters.

    :param template_name: Template file name: `dhcpd6.conf.template` for the
        IPv6 template.
    :return: A full configuration, as a string.
    """
    platform_codename = linux_distribution()[2]
    template_file = locate_template('dhcp', template_name)
    template = tempita.Template.from_filename(template_file, encoding="UTF-8")
    # Helper functions to stuff into the template namespace.
    helpers = {
        "oneline": normalise_whitespace,
        "commalist": normalise_any_iterable_to_comma_list,
        "running_in_snap": snappy.running_in_snap(),
    }

    rack_addrs = [
        IPAddress(addr)
        for addr in net_utils.get_all_interface_addresses()]

    shared_networks = _process_network_parameters_v6(
        rack_addrs, failover_peers, shared_networks)

    try:
        return template.substitute(
            global_dhcp_snippets=global_dhcp_snippets, hosts=hosts,
            failover_peers=failover_peers, shared_networks=shared_networks,
            platform_codename=platform_codename,
            omapi_key=omapi_key, **helpers)
    except (KeyError, NameError) as error:
        raise DHCPConfigError(
            "Failed to render DHCP configuration.") from error
예제 #10
0
def get_dns_template_path(template_name):
    """Return the path to a dns template file."""
    # This function exists solely to make unit testing easier.
    return locate_template('dns', template_name)
예제 #11
0
 def get_template_dir(self):
     """Gets the template directory for the boot method."""
     return locate_template("%s" % self.template_subdir)