summaryrefslogtreecommitdiffstats
path: root/apex/overcloud/overcloud_deploy.py
blob: 3b79ec49f6009c787cd01abed0b68e5421677d7d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

@media only all and (prefers-color-scheme: dark) {
.highlight .hll { background-color: #49483e }
.highlight .c { color: #75715e } /* Comment */
.highlight .err { color: #960050; background-color: #1e0010 } /* Error */
.highlight .k { color: #66d9ef } /* Keyword */
.highlight .l { color: #ae81ff } /* Literal */
.highlight .n { color: #f8f8f2 } /* Name */
.highlight .o { color: #f92672 } /* Operator */
.highlight .p { color: #f8f8f2 } /* Punctuation */
.highlight .ch { color: #75715e } /* Comment.Hashbang */
.highlight .cm { color: #75715e } /* Comment.Multiline */
.highlight .cp { color: #75715e } /* Comment.Preproc */
.highlight .cpf { color: #75715e } /* Comment.PreprocFile */
.highlight .c1 { color: #75715e } /* Comment.Single */
.highlight .cs { color: #75715e } /* Comment.Special */
.highlight .gd { color: #f92672 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gi { color: #a6e22e } /* Generic.Inserted */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #75715e } /* Generic.Subheading */
.highlight .kc { color: #66d9ef } /* Keyword.Constant */
.highlight .kd { color: #66d9ef } /* Keyword.Declaration */
.highlight .kn { color: #f92672 } /* Keyword.Namespace */
.highlight .kp { color: #66d9ef } /* Keyword.Pseudo */
.highlight .kr { color: #66d9ef } /* Keyword.Reserved */
.highlight .kt { color: #66d9ef } /* Keyword.Type */
.highlight .ld { color: #e6db74 } /* Literal.Date */
.highlight .m { color: #ae81ff } /* Literal.Number */
.highlight .s { color: #e6db74 } /* Literal.String */
.highlight .na { color: #a6e22e } /* Name.Attribute */
.highlight .nb { color: #f8f8f2 } /* Name.Builtin */
.highlight .nc { color: #a6e22e } /* Name.Class */
.highlight .no { color: #66d9ef } /* Name.Constant */
.highlight .nd { color: #a6e22e } /* Name.Decorator */
.highlight .ni { color: #f8f8f2 } /* Name.Entity */
.highlight .ne { color: #a6e22e } /* Name.Exception */
.highlight .nf { color: #a6e22e } /* Name.Function */
.highlight .nl { color: #f8f8f2 } /* Name.Label */
.highlight .nn { color: #f8f8f2 } /* Name.Namespace */
.highlight .nx { color: #a6e22e } /* Name.Other */
.highlight .py { color: #f8f8f2 } /* Name.Property */
.highlight .nt { color: #f92672 } /* Name.Tag */
.highlight .nv { color: #f8f8f2 } /* Name.Variable */
.highlight .ow { color: #f92672 } /* Operator.Word */
.highlight .w { color: #f8f8f2 } /* Text.Whitespace */
.highlight .mb { color: #ae81ff } /* Literal.Number.Bin */
.highlight .mf { color: #ae81ff } /* Literal.Number.Float */
.highlight .mh { color: #ae81ff } /* Literal.Number.Hex */
.highlight .mi { color: #ae81ff } /* Literal.Number.Integer */
.highlight .mo { color: #ae81ff } /* Literal.Number.Oct */
.highlight .sa { color: #e6db74 } /* Literal.String.Affix */
.highlight .sb { color: #e6db74 } /* Literal.String.Backtick */
.highlight .sc { color: #e6db74 } /* Literal.String.Char */
.highlight .dl { color: #e6db74 } /* Literal.String.Delimiter */
.highlight .sd { color: #e6db74 } /* Literal.String.Doc */
.highlight .s2 { color: #e6db74 } /* Literal.String.Double */
.highlight .se { color: #ae81ff } /* Literal.String.Escape */
.highlight .sh { color: #e6db74 } /* Literal.String.Heredoc */
.highlight .si { color: #e6db74 } /* Literal.String.Interpol */
.highlight .sx { color: #e6db74 } /* Literal.String.Other */
.highlight .sr { color: #e6db74 } /* Literal.String.Regex */
.highlight .s1 { color: #e6db74 } /* Literal.String.Single */
.highlight .ss { color: #e6db74 } /* Literal.String.Symbol */
.highlight .bp { color: #f8f8f2 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #a6e22e } /* Name.Function.Magic */
.highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */
.highlight .vg { color: #f8f8f2 } /* Name.Variable.Global */
.highlight .vi { color: #f8f8f2 } /* Name.Variable.Instance */
.highlight .vm { color: #f8f8f2 } /* Name.Variable.Magic */
.highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */
}
@media (prefers-color-scheme: light) {
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
}
.. _overview:

.. This work is licensed under a Creative Commons Attribution 4.0 International License.
.. SPDX-License-Identifier: CC-BY-4.0
.. (c) Open Platform for NFV Project, Inc. and its contributors

=======================
Infrastructure Overview
=======================

OPNFV develops, operates, and maintains infrastructure which is used by the OPNFV
Community for development, integration, and testing purposes. `OPNFV
Infrastructure Working Group (Infra WG) <https://wiki.opnfv.org/display/INF>`_
oversees the OPNFV Infrastructure, ensures it is kept in a state which serves
the community in best possible way and always up to date.

Infra WG is working towards a model whereby we have a seamless pipeline
for handing resource requests from the OPNFV community for both development and
Continuous Integration perspectives. Automation of requests and integration to
existing automation tools is a primary driver in reaching this model. In the
Infra WG, we imagine a model where the Infrastructure Requirements that are
specified by a Feature, Installer or otherrelevant projects within OPNFV are
requested, provisioned, used, reported on and subsequently torn down with no (or
minimal) user intervention at the physical/infrastructure level.

Objectives of the Infra WG are

* Deliver efficiently dimensions resources to OPNFV community needs on request in a timely manner that ensure maximum usage (capacity) and maximum density (distribution of workloads)
* Satisfy the needs of the twice-yearly release projects, this includes being able to handle load (amount of projects and requests) as well as need (topology and different layouts)
* Support OPNFV community users.  As the INFRA group, we are integral to all aspects of the OPNFV Community (since it starts with the Hardware) - this can mean troubleshooting any element within the stack
* Provide a method to expand and adapt as OPNFV community needs grow and provide this to Hosting Providers (lab providers) for input in growth forecast so they can better judge how best to contribute with their resources.
* Work with reporting and other groups to ensure we have adequate feedback to the end-users of the labs on how their systems, code, feature performs.

The details of what is provided as part of the infrastructure can be seen in following chapters.

Hardware Infrastructure
-----------------------

TBD

Software Infrastructure
-----------------------

.. toctree::
   :maxdepth: 1

   ../submodules/releng/docs/infra/index

Security
--------

.. toctree::
   :maxdepth: 1

   ../submodules/releng-anteater/docs/index
f='#n475'>475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
##############################################################################
# Copyright (c) 2017 Tim Rozet (trozet@redhat.com) and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
##############################################################################

import base64
import fileinput
import logging
import os
import re
import shutil
import uuid
import struct
import time

from apex.common import constants as con
from apex.common.exceptions import ApexDeployException
from apex.common import parsers
from apex.virtual import utils as virt_utils
from cryptography.hazmat.primitives import serialization as \
    crypto_serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend as \
    crypto_default_backend


SDN_FILE_MAP = {
    'opendaylight': {
        'sfc': 'neutron-sfc-opendaylight.yaml',
        'vpn': 'neutron-bgpvpn-opendaylight.yaml',
        'gluon': 'gluon.yaml',
        'vpp': {
            'odl_vpp_netvirt': 'neutron-opendaylight-netvirt-vpp.yaml',
            'default': 'neutron-opendaylight-honeycomb.yaml'
        },
        'default': 'neutron-opendaylight.yaml',
    },
    'onos': {
        'sfc': 'neutron-onos-sfc.yaml',
        'default': 'neutron-onos.yaml'
    },
    'ovn': 'neutron-ml2-ovn.yaml',
    False: {
        'vpp': 'neutron-ml2-vpp.yaml',
        'dataplane': ('ovs_dpdk', 'neutron-ovs-dpdk.yaml')
    }
}

OTHER_FILE_MAP = {
    'tacker': 'enable_tacker.yaml',
    'congress': 'enable_congress.yaml',
    'barometer': 'enable_barometer.yaml',
    'rt_kvm': 'enable_rt_kvm.yaml'
}

OVS_PERF_MAP = {
    'HostCpusList': 'dpdk_cores',
    'NeutronDpdkCoreList': 'pmd_cores',
    'NeutronDpdkSocketMemory': 'socket_memory',
    'NeutronDpdkMemoryChannels': 'memory_channels'
}

OVS_NSH_KMOD_RPM = "openvswitch-kmod-2.6.1-1.el7.centos.x86_64.rpm"
OVS_NSH_RPM = "openvswitch-2.6.1-1.el7.centos.x86_64.rpm"
ODL_NETVIRT_VPP_RPM = "/root/opendaylight-7.0.0-0.1.20170531snap665.el7" \
                      ".noarch.rpm"


def build_sdn_env_list(ds, sdn_map, env_list=None):
    if env_list is None:
        env_list = list()
    for k, v in sdn_map.items():
        if ds['sdn_controller'] == k or (k in ds and ds[k] is True):
            if isinstance(v, dict):
                env_list.extend(build_sdn_env_list(ds, v))
            else:
                env_list.append(os.path.join(con.THT_ENV_DIR, v))
        elif isinstance(v, tuple):
                if ds[k] == v[0]:
                    env_list.append(os.path.join(con.THT_ENV_DIR, v[1]))
    if len(env_list) == 0:
        try:
            env_list.append(os.path.join(
                con.THT_ENV_DIR, sdn_map['default']))
        except KeyError:
            logging.warning("Unable to find default file for SDN")

    return env_list


def create_deploy_cmd(ds, ns, inv, tmp_dir,
                      virtual, env_file='opnfv-environment.yaml'):

    logging.info("Creating deployment command")
    deploy_options = [env_file, 'network-environment.yaml']
    ds_opts = ds['deploy_options']
    deploy_options += build_sdn_env_list(ds_opts, SDN_FILE_MAP)

    # TODO(trozet): make sure rt kvm file is in tht dir
    for k, v in OTHER_FILE_MAP.items():
        if k in ds_opts and ds_opts[k]:
            deploy_options.append(os.path.join(con.THT_ENV_DIR, v))

    if ds_opts['ceph']:
        prep_storage_env(ds, tmp_dir)
        deploy_options.append(os.path.join(con.THT_ENV_DIR,
                                           'storage-environment.yaml'))
    if ds['global_params']['ha_enabled']:
        deploy_options.append(os.path.join(con.THT_ENV_DIR,
                                           'puppet-pacemaker.yaml'))

    if virtual:
        deploy_options.append('virtual-environment.yaml')
    else:
        deploy_options.append('baremetal-environment.yaml')

    nodes = inv['nodes']
    num_control = 0
    num_compute = 0
    for node in nodes:
        if 'profile:control' in node['capabilities']:
            num_control += 1
        elif 'profile:compute' in node['capabilities']:
            num_compute += 1
        else:
            # TODO(trozet) do we want to allow capabilities to not exist?
            logging.error("Every node must include a 'capabilities' key "
                          "tagged with either 'profile:control' or "
                          "'profile:compute'")
            raise ApexDeployException("Node missing capabilities "
                                      "key: {}".format(node))
    if num_control == 0 or num_compute == 0:
        logging.error("Detected 0 control or compute nodes.  Control nodes: "
                      "{}, compute nodes{}".format(num_control, num_compute))
        raise ApexDeployException("Invalid number of control or computes")
    elif num_control > 1 and not ds['global_params']['ha_enabled']:
        num_control = 1
    cmd = "openstack overcloud deploy --templates --timeout {} " \
          "--libvirt-type kvm".format(con.DEPLOY_TIMEOUT)
    # build cmd env args
    for option in deploy_options:
        cmd += " -e {}".format(option)
    cmd += " --ntp-server {}".format(ns['ntp'][0])
    cmd += " --control-scale {}".format(num_control)
    cmd += " --compute-scale {}".format(num_compute)
    cmd += ' --control-flavor control --compute-flavor compute'
    logging.info("Deploy command set: {}".format(cmd))

    with open(os.path.join(tmp_dir, 'deploy_command'), 'w') as fh:
        fh.write(cmd)
    return cmd


def prep_image(ds, img, tmp_dir, root_pw=None):
    """
    Locates sdn image and preps for deployment.
    :param ds: deploy settings
    :param img: sdn image
    :param tmp_dir: dir to store modified sdn image
    :param root_pw: password to configure for overcloud image
    :return: None
    """
    # TODO(trozet): Come up with a better way to organize this logic in this
    # function
    logging.info("Preparing image: {} for deployment".format(img))
    if not os.path.isfile(img):
        logging.error("Missing SDN image {}".format(img))
        raise ApexDeployException("Missing SDN image file: {}".format(img))

    ds_opts = ds['deploy_options']
    virt_cmds = list()
    sdn = ds_opts['sdn_controller']
    # we need this due to rhbz #1436021
    # fixed in systemd-219-37.el7
    if sdn is not False:
        logging.info("Neutron openvswitch-agent disabled")
        virt_cmds.extend([{
            con.VIRT_RUN_CMD:
                "rm -f /etc/systemd/system/multi-user.target.wants/"
                "neutron-openvswitch-agent.service"},
            {
            con.VIRT_RUN_CMD:
                "rm -f /usr/lib/systemd/system/neutron-openvswitch-agent"
                ".service"
        }])

    if ds_opts['vpn']:
        virt_cmds.append({con.VIRT_RUN_CMD: "systemctl enable zrpcd"})
        logging.info("ZRPC and Quagga enabled")

    dataplane = ds_opts['dataplane']
    if dataplane == 'ovs_dpdk' or dataplane == 'fdio':
        logging.info("Enabling kernel modules for dpdk")
        # file to module mapping
        uio_types = {
            os.path.join(tmp_dir, 'vfio_pci.modules'): 'vfio_pci',
            os.path.join(tmp_dir, 'uio_pci_generic.modules'): 'uio_pci_generic'
        }
        for mod_file, mod in uio_types.items():
            with open(mod_file, 'w') as fh:
                fh.write('#!/bin/bash\n')
                fh.write('exec /sbin/modprobe {}'.format(mod))
                fh.close()

            virt_cmds.extend([
                {con.VIRT_UPLOAD: "{}:/etc/sysconfig/modules/".format(
                    mod_file)},
                {con.VIRT_RUN_CMD: "chmod 0755 /etc/sysconfig/modules/"
                                   "{}".format(os.path.basename(mod_file))}
            ])
    if root_pw:
        pw_op = "password:{}".format(root_pw)
        virt_cmds.append({con.VIRT_PW: pw_op})
    if ds_opts['sfc'] and dataplane == 'ovs':
        virt_cmds.extend([
            {con.VIRT_RUN_CMD: "yum -y install "
                               "/root/ovs/rpm/rpmbuild/RPMS/x86_64/"
                               "{}".format(OVS_NSH_KMOD_RPM)},
            {con.VIRT_RUN_CMD: "yum downgrade -y "
                               "/root/ovs/rpm/rpmbuild/RPMS/x86_64/"
                               "{}".format(OVS_NSH_RPM)}
        ])
    if dataplane == 'fdio':
        # Patch neutron with using OVS external interface for router
        # and add generic linux NS interface driver
        virt_cmds.append(
            {con.VIRT_RUN_CMD: "cd /usr/lib/python2.7/site-packages && patch "
                               "-p1 < neutron-patch-NSDriver.patch"})

    if sdn == 'opendaylight':
        if ds_opts['odl_version'] != con.DEFAULT_ODL_VERSION:
            virt_cmds.extend([
                {con.VIRT_RUN_CMD: "yum -y remove opendaylight"},
                {con.VIRT_RUN_CMD: "yum -y install /root/{}/*".format(
                    ds_opts['odl_version'])},
                {con.VIRT_RUN_CMD: "rm -rf /etc/puppet/modules/opendaylight"},
                {con.VIRT_RUN_CMD: "cd /etc/puppet/modules && tar xzf "
                                   "/root/puppet-opendaylight-"
                                   "{}.tar.gz".format(ds_opts['odl_version'])}
            ])
        elif sdn == 'opendaylight' and 'odl_vpp_netvirt' in ds_opts \
                and ds_opts['odl_vpp_netvirt']:
            virt_cmds.extend([
                {con.VIRT_RUN_CMD: "yum -y remove opendaylight"},
                {con.VIRT_RUN_CMD: "yum -y install /root/{}/*".format(
                    ODL_NETVIRT_VPP_RPM)}
            ])

    if sdn == 'ovn':
        virt_cmds.extend([
            {con.VIRT_RUN_CMD: "cd /root/ovs28 && yum update -y "
                               "*openvswitch*"},
            {con.VIRT_RUN_CMD: "cd /root/ovs28 && yum downgrade -y "
                               "*openvswitch*"}
        ])

    tmp_oc_image = os.path.join(tmp_dir, 'overcloud-full.qcow2')
    shutil.copyfile(img, tmp_oc_image)
    logging.debug("Temporary overcloud image stored as: {}".format(
        tmp_oc_image))
    virt_utils.virt_customize(virt_cmds, tmp_oc_image)
    logging.info("Overcloud image customization complete")


def make_ssh_key():
    """
    Creates public and private ssh keys with 1024 bit RSA encryption
    :return: private, public key
    """
    key = rsa.generate_private_key(
        backend=crypto_default_backend(),
        public_exponent=65537,
        key_size=1024
    )

    private_key = key.private_bytes(
        crypto_serialization.Encoding.PEM,
        crypto_serialization.PrivateFormat.PKCS8,
        crypto_serialization.NoEncryption())
    public_key = key.public_key().public_bytes(
        crypto_serialization.Encoding.OpenSSH,
        crypto_serialization.PublicFormat.OpenSSH
    )
    pub_key = re.sub('ssh-rsa\s*', '', public_key.decode('utf-8'))
    return private_key.decode('utf-8'), pub_key


def prep_env(ds, ns, opnfv_env, net_env, tmp_dir):
    """
    Creates modified opnfv/network environments for deployment
    :param ds: deploy settings
    :param ns: network settings
    :param opnfv_env: file path for opnfv-environment file
    :param net_env: file path for network-environment file
    :param tmp_dir: Apex tmp dir
    :return:
    """

    logging.info("Preparing opnfv-environment and network-environment files")
    ds_opts = ds['deploy_options']
    tmp_opnfv_env = os.path.join(tmp_dir, os.path.basename(opnfv_env))
    shutil.copyfile(opnfv_env, tmp_opnfv_env)
    tenant_nic_map = ns['networks']['tenant']['nic_mapping']
    tenant_ctrl_nic = tenant_nic_map['controller']['members'][0]
    tenant_comp_nic = tenant_nic_map['compute']['members'][0]

    # SSH keys
    private_key, public_key = make_ssh_key()

    # Make easier/faster variables to index in the file editor
    if 'performance' in ds_opts:
        perf = True
        # vpp
        if 'vpp' in ds_opts['performance']['Compute']:
            perf_vpp_comp = ds_opts['performance']['Compute']['vpp']
        else:
            perf_vpp_comp = None
        if 'vpp' in ds_opts['performance']['Controller']:
            perf_vpp_ctrl = ds_opts['performance']['Controller']['vpp']
        else:
            perf_vpp_ctrl = None

        # ovs
        if 'ovs' in ds_opts['performance']['Compute']:
            perf_ovs_comp = ds_opts['performance']['Compute']['ovs']
        else:
            perf_ovs_comp = None

        # kernel
        if 'kernel' in ds_opts['performance']['Compute']:
            perf_kern_comp = ds_opts['performance']['Compute']['kernel']
        else:
            perf_kern_comp = None
    else:
        perf = False

    # Modify OPNFV environment
    # TODO: Change to build a dict and outputing yaml rather than parsing
    for line in fileinput.input(tmp_opnfv_env, inplace=True):
        line = line.strip('\n')
        output_line = line
        if 'CloudDomain' in line:
            output_line = "  CloudDomain: {}".format(ns['domain_name'])
        elif 'replace_private_key' in line:
            output_line = "      key: '{}'".format(private_key)
        elif 'replace_public_key' in line:
            output_line = "      key: '{}'".format(public_key)

        if ds_opts['sdn_controller'] == 'opendaylight' and \
                'odl_vpp_routing_node' in ds_opts and ds_opts[
                'odl_vpp_routing_node'] != 'dvr':
            if 'opendaylight::vpp_routing_node' in line:
                output_line = ("    opendaylight::vpp_routing_node: ${}.${}"
                               .format(ds_opts['odl_vpp_routing_node'],
                                       ns['domain_name']))
            elif 'ControllerExtraConfig' in line:
                output_line = ("  ControllerExtraConfig:\n    "
                               "tripleo::profile::base::neutron::agents::"
                               "honeycomb::interface_role_mapping:"
                               " ['{}:tenant-interface]'"
                               .format(tenant_ctrl_nic))
            elif 'NovaComputeExtraConfig' in line:
                output_line = ("  NovaComputeExtraConfig:\n    "
                               "tripleo::profile::base::neutron::agents::"
                               "honeycomb::interface_role_mapping:"
                               " ['{}:tenant-interface]'"
                               .format(tenant_comp_nic))
        elif not ds_opts['sdn_controller'] and ds_opts['dataplane'] == 'fdio':
            if 'NeutronVPPAgentPhysnets' in line:
                output_line = ("  NeutronVPPAgentPhysnets: 'datacentre:{}'".
                               format(tenant_ctrl_nic))

        if perf:
            for role in 'NovaCompute', 'Controller':
                if role == 'NovaCompute':
                    perf_opts = perf_vpp_comp
                else:
                    perf_opts = perf_vpp_ctrl
                cfg = "{}ExtraConfig".format(role)
                if cfg in line and perf_opts:
                    perf_line = ''
                    if 'main-core' in perf_opts:
                        perf_line += ("\n    fdio::vpp_cpu_main_core: '{}'"
                                      .format(perf_opts['main-core']))
                    if 'corelist-workers' in perf_opts:
                        perf_line += ("\n    "
                                      "fdio::vpp_cpu_corelist_workers: '{}'"
                                      .format(perf_opts['corelist-workers']))
                    if perf_line:
                        output_line = ("  {}:{}".format(cfg, perf_line))

            # kernel args
            # (FIXME) use compute's kernel settings for all nodes for now.
            if 'ComputeKernelArgs' in line and perf_kern_comp:
                kernel_args = ''
                for k, v in perf_kern_comp.items():
                    kernel_args += "{}={} ".format(k, v)
                if kernel_args:
                    output_line = "  ComputeKernelArgs: '{}'".\
                        format(kernel_args)
            if ds_opts['dataplane'] == 'ovs_dpdk' and perf_ovs_comp:
                for k, v in OVS_PERF_MAP.items():
                    if k in line and v in perf_ovs_comp:
                        output_line = "  {}: '{}'".format(k, perf_ovs_comp[v])

        print(output_line)

    logging.info("opnfv-environment file written to {}".format(tmp_opnfv_env))

    # Modify Network environment
    for line in fileinput.input(net_env, inplace=True):
        line = line.strip('\n')
        if 'ComputeExtraConfigPre' in line and \
                ds_opts['dataplane'] == 'ovs_dpdk':
            print('  OS::TripleO::ComputeExtraConfigPre: '
                  './ovs-dpdk-preconfig.yaml')
        elif perf and perf_kern_comp:
            if 'resource_registry' in line:
                print("resource_registry:\n"
                      "  OS::TripleO::NodeUserData: first-boot.yaml")
            elif 'NovaSchedulerDefaultFilters' in line:
                print("  NovaSchedulerDefaultFilters: 'RamFilter,"
                      "ComputeFilter,AvailabilityZoneFilter,"
                      "ComputeCapabilitiesFilter,ImagePropertiesFilter,"
                      "NUMATopologyFilter'")
            else:
                print(line)
        else:
            print(line)

    logging.info("network-environment file written to {}".format(net_env))


def generate_ceph_key():
    key = os.urandom(16)
    header = struct.pack('<hiih', 1, int(time.time()), 0, len(key))
    return base64.b64encode(header + key)


def prep_storage_env(ds, tmp_dir):
    """
    Creates storage environment file for deployment.  Source file is copied by
    undercloud playbook to host.
    :param ds:
    :param tmp_dir:
    :return:
    """
    ds_opts = ds['deploy_options']
    storage_file = os.path.join(tmp_dir, 'storage-environment.yaml')
    if not os.path.isfile(storage_file):
        logging.error("storage-environment file is not in tmp directory: {}. "
                      "Check if file was copied from "
                      "undercloud".format(tmp_dir))
        raise ApexDeployException("storage-environment file not copied from "
                                  "undercloud")
    for line in fileinput.input(storage_file, inplace=True):
        line = line.strip('\n')
        if 'CephClusterFSID' in line:
            print("  CephClusterFSID: {}".format(str(uuid.uuid4())))
        elif 'CephMonKey' in line:
            print("  CephMonKey: {}".format(generate_ceph_key().decode(
                'utf-8')))
        elif 'CephAdminKey' in line:
            print("  CephAdminKey: {}".format(generate_ceph_key().decode(
                'utf-8')))
        else:
            print(line)
    if 'ceph_device' in ds_opts and ds_opts['ceph_device']:
        with open(storage_file, 'a') as fh:
            fh.write('  ExtraConfig:\n')
            fh.write("    ceph::profile::params::osds:{{{}:{{}}}}\n".format(
                ds_opts['ceph_device']
            ))


def external_network_cmds(ns):
    """
    Generates external network openstack commands
    :param ns: network settings
    :return: list of commands to configure external network
    """
    if 'external' in ns.enabled_network_list:
        net_config = ns['networks']['external'][0]
        external = True
        pool_start, pool_end = net_config['floating_ip_range']
    else:
        net_config = ns['networks']['admin']
        external = False
        pool_start, pool_end = ns['apex']['networks']['admin'][
            'introspection_range']
    nic_config = net_config['nic_mapping']
    gateway = net_config['gateway']
    cmds = list()
    # create network command
    if nic_config['compute']['vlan'] == 'native':
        ext_type = 'flat'
    else:
        ext_type = "vlan --provider-segment {}".format(nic_config[
                                                       'compute']['vlan'])
    cmds.append("openstack network create external --project service "
                "--external --provider-network-type {} "
                "--provider-physical-network datacentre".format(ext_type))
    # create subnet command
    cidr = net_config['cidr']
    subnet_cmd = "openstack subnet create external-subnet --project " \
                 "service --network external --no-dhcp --gateway {} " \
                 "--allocation-pool start={},end={} --subnet-range " \
                 "{}".format(gateway, pool_start, pool_end, str(cidr))
    if external and cidr.version == 6:
        subnet_cmd += ' --ip-version 6 --ipv6-ra-mode slaac ' \
                      '--ipv6-address-mode slaac'
    cmds.append(subnet_cmd)
    logging.debug("Neutron external network commands determined "
                  "as: {}".format(cmds))
    return cmds


def create_congress_cmds(overcloud_file):
    drivers = ['nova', 'neutronv2', 'cinder', 'glancev2', 'keystone', 'doctor']
    overcloudrc = parsers.parse_overcloudrc(overcloud_file)
    logging.info("Creating congress commands")
    try:
        ds_cfg = [
            "username={}".format(overcloudrc['OS_USERNAME']),
            "tenant_name={}".format(overcloudrc['OS_PROJECT_NAME']),
            "password={}".format(overcloudrc['OS_PASSWORD']),
            "auth_url={}".format(overcloudrc['OS_AUTH_URL'])
        ]
    except KeyError:
        logging.error("Unable to find all keys required for congress in "
                      "overcloudrc: OS_USERNAME, OS_PROJECT_NAME, "
                      "OS_PASSWORD, OS_AUTH_URL.  Please check overcloudrc "
                      "file: {}".format(overcloud_file))
        raise
    cmds = list()
    ds_cfg = '--config ' + ' --config '.join(ds_cfg)

    for driver in drivers:
        if driver == 'doctor':
            cmd = "{} \"{}\"".format(driver, driver)
        else:
            cmd = "{} \"{}\" {}".format(driver, driver, ds_cfg)
        if driver == 'nova':
            cmd += ' --config api_version="2.34"'
        logging.debug("Congress command created: {}".format(cmd))
        cmds.append(cmd)
    return cmds