aboutsummaryrefslogtreecommitdiffstats
path: root/contrail-agent/hooks/contrail_agent_utils.py
blob: 1f9e6171e489f44a0e7a9ae2a85a2d71c80b683c (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
from base64 import b64decode
import functools
import os
from socket import gethostname
from subprocess import (
    check_call,
    check_output,
)
from time import sleep, time

import apt_pkg
import json

import netaddr
import netifaces

from charmhelpers.contrib.network.ip import get_address_in_network
from charmhelpers.core.hookenv import (
    config,
    log,
    related_units,
    relation_get,
    relation_ids,
    status_set,
    ERROR,
    WARNING,
)

from charmhelpers.core.host import (
    restart_on_change,
    write_file,
    service_restart,
)

from charmhelpers.core.templating import render

apt_pkg.init()
config = config()


# as it's hardcoded in several scripts/configs
VROUTER_INTERFACE = "vhost0"


def retry(f=None, timeout=10, delay=2):
    """Retry decorator.

    Provides a decorator that can be used to retry a function if it raises
    an exception.

    :param timeout: timeout in seconds (default 10)
    :param delay: retry delay in seconds (default 2)

    Examples::

        # retry fetch_url function
        @retry
        def fetch_url():
            # fetch url

        # retry fetch_url function for 60 secs
        @retry(timeout=60)
        def fetch_url():
            # fetch url
    """
    if not f:
        return functools.partial(retry, timeout=timeout, delay=delay)

    @functools.wraps(f)
    def func(*args, **kwargs):
        start = time()
        error = None
        while True:
            try:
                return f(*args, **kwargs)
            except Exception as e:
                error = e
            elapsed = time() - start
            if elapsed >= timeout:
                raise error
            remaining = timeout - elapsed
            sleep(delay if delay <= remaining else remaining)
    return func


def configure_vrouter_interface():
    # run external script to configure vrouter
    args = ["./create-vrouter.sh"]
    if config["remove-juju-bridge"]:
        args.append("-b")
    iface = config.get("physical-interface")
    if iface:
        args.append(iface)
    check_call(args, cwd="scripts")


def drop_caches():
    """Clears OS pagecache"""
    log("Clearing pagecache")
    check_call(["sync"])
    with open("/proc/sys/vm/drop_caches", "w") as f:
        f.write("3\n")


def dkms_autoinstall(module):
    """Allows loading of a kernel module.

    'dkms_autoinstall' is useful for DKMS kernel modules. Juju often upgrades
    units to newer kernels before charm install, which won't be used until the
    machine is rebooted. In these cases, some modules may not be compiled for
    the newer kernel. Setting this argument to True will ensure these modules
    are compiled for newer kernels.

    :param module: module to load
    """
    current = check_output(["uname", "-r"]).rstrip()
    for kernel in os.listdir("/lib/modules"):
        if kernel == current:
            continue
        log("DKMS auto installing for kernel {}".format(kernel))
        check_call(["dkms", "autoinstall", "-k", kernel])


def update_vrouter_provision_status():
    # TODO: update this logic with various scenario for data in relation
    info = _load_json_from_config("orchestrator_info")
    ready = (
        config.get("api_port")
        and (config.get("api_ip") or config.get("api_vip"))
        and config.get("analytics_servers")
        and info.get("cloud_orchestrator"))
    if config.get("vrouter-expected-provision-state"):
        if ready and not config.get("vrouter-provisioned"):
            try:
                provision_vrouter("add")
                config["vrouter-provisioned"] = True
            except Exception as e:
                # vrouter is not up yet
                log("Couldn't provision vrouter: " + str(e), level=WARNING)
    elif config.get("vrouter-provisioned"):
        try:
            provision_vrouter("del")
        except Exception as e:
            log("Couldn't unprovision vrouter: " + str(e), level=WARNING)
        config["vrouter-provisioned"] = False


def get_control_network_ip(control_network=None):
    network = control_network
    if not network:
        network = config.get("control-network")
    ip = get_address_in_network(network) if network else None
    if not ip:
        ip = iface_addr(VROUTER_INTERFACE)["addr"]
    return ip


def reprovision_vrouter(old_ip):
    if not config.get("vrouter-provisioned"):
        return

    old_ip = get_control_network_ip(config.prev("control-network"))
    try:
        provision_vrouter("del", old_ip)
    except Exception as e:
        log("Couldn't unprovision vrouter: " + str(e), level=WARNING)
    try:
        provision_vrouter("add")
    except Exception as e:
        # vrouter is not up yet
        log("Couldn't provision vrouter: " + str(e), level=WARNING)


def provision_vrouter(op, self_ip=None):
    ip = self_ip if self_ip else get_control_network_ip()
    api_ip, api_port = get_controller_address()
    identity = _load_json_from_config("auth_info")
    params = [
        "contrail-provision-vrouter",
        "--host_name", gethostname(),
        "--host_ip", ip,
        "--api_server_ip", api_ip,
        "--api_server_port", str(api_port),
        "--oper", op]
    if "keystone_admin_user" in identity:
        params += [
            "--admin_user", identity.get("keystone_admin_user"),
            "--admin_password", identity.get("keystone_admin_password"),
            "--admin_tenant_name", identity.get("keystone_admin_tenant")]

    @retry(timeout=65, delay=20)
    def _call():
        check_call(params)
        log("vrouter operation '{}' was successful".format(op))

    log("{} vrouter {}".format(op, ip))
    _call()


def get_controller_address():
    ip = config.get("api_ip")
    port = config.get("api_port")
    api_vip = config.get("api_vip")
    if api_vip:
        ip = api_vip
    return (ip, port) if ip and port else (None, None)


def iface_addr(iface):
    return netifaces.ifaddresses(iface)[netifaces.AF_INET][0]


def vhost_ip(addr):
    # return a vhost formatted address and mask - x.x.x.x/xx
    addr = iface_addr(VROUTER_INTERFACE)
    ip = addr["addr"]
    cidr = netaddr.IPNetwork(ip + "/" + addr["netmask"]).prefixlen
    return ip + "/" + str(cidr)


def vhost_gateway(iface):
    # determine vhost gateway
    gateway = config.get("vhost-gateway")
    if gateway == "auto":
        for line in check_output(["route", "-n"]).splitlines()[2:]:
            l = line.decode('UTF-8').split()
            if "G" in l[3] and l[7] == iface:
                return l[1]
        gateway = None
    return gateway


def vhost_phys(iface):
    # run external script to determine physical interface of 'vhost0'
    cmd = ["scripts/vhost-phys.sh", iface]
    return (check_output(cmd).decode('UTF-8').rstrip())


def _load_json_from_config(key):
    value = config.get(key)
    return json.loads(value) if value else {}


def get_context():
    ctx = {}
    ssl_ca = _decode_cert("ssl_ca")
    ctx["ssl_ca"] = ssl_ca
    ctx["ssl_enabled"] = (ssl_ca is not None and len(ssl_ca) > 0)

    ip, port = get_controller_address()
    ctx["api_server"] = ip
    ctx["api_port"] = port
    ctx["control_nodes"] = [
        relation_get("private-address", unit, rid)
         for rid in relation_ids("contrail-controller")
         for unit in related_units(rid)]
    ctx["analytics_nodes"] = _load_json_from_config("analytics_servers")
    info = _load_json_from_config("orchestrator_info")
    ctx["metadata_shared_secret"] = info.get("metadata_shared_secret")

    ctx["control_network_ip"] = get_control_network_ip()

    ctx["vhost_ip"] = vhost_ip(VROUTER_INTERFACE)
    ctx["vhost_gateway"] = vhost_gateway(VROUTER_INTERFACE)
    ctx["vhost_physical"] = vhost_phys(VROUTER_INTERFACE)

    log("CTX: " + str(ctx))

    ctx.update(_load_json_from_config("auth_info"))
    return ctx


def _decode_cert(key):
    val = config.get(key)
    if not val:
        return None
    try:
        return b64decode(val)
    except Exception as e:
        log("Couldn't decode certificate from config['{}']: {}".format(
            key, str(e)), level=ERROR)
    return None


def _save_file(path, data):
    if data:
        fdir = os.path.dirname(path)
        if not os.path.exists(fdir):
            os.makedirs(fdir)
        write_file(path, data, perms=0o400)
    elif os.path.exists(path):
        os.remove(path)


@restart_on_change({
    "/etc/contrail/ssl/certs/ca-cert.pem":
        ["contrail-vrouter-agent", "contrail-vrouter-nodemgr"],
    "/etc/contrail/contrail-vrouter-agent.conf":
        ["contrail-vrouter-agent"],
    "/etc/contrail/contrail-vrouter-nodemgr.conf":
        ["contrail-vrouter-nodemgr"]})
def write_configs():
    ctx = get_context()

    # TODO: what we should do with two other certificates?
    # NOTE: store files in the same paths as in tepmlates
    ca_path = "/etc/contrail/ssl/certs/ca-cert.pem"
    ssl_ca = ctx["ssl_ca"]
    _save_file(ca_path, ssl_ca)
    ctx["ssl_ca_path"] = ca_path

    render("contrail-vrouter-nodemgr.conf",
           "/etc/contrail/contrail-vrouter-nodemgr.conf", ctx)
    render("vnc_api_lib.ini", "/etc/contrail/vnc_api_lib.ini", ctx)
    render("contrail-vrouter-agent.conf",
           "/etc/contrail/contrail-vrouter-agent.conf", ctx, perms=0o440)


def update_unit_status():
    if not config.get("vrouter-provisioned"):
        units = [unit for rid in relation_ids("contrail-controller")
                          for unit in related_units(rid)]
        if units:
            status_set("waiting", "There is no enough info to provision.")
        else:
            status_set("blocked", "Missing relation to contrail-controller")

    status, _ = _get_agent_status()
    if status == 'initializing':
        # some hacks
        log("Run agent hack: service restart")
        service_restart("contrail-vrouter-agent")
        sleep(10)
        status, msg = _get_agent_status()
        if status == 'initializing' and "(No Configuration for self)" in msg:
            log("Run agent hack: reinitialize config client")
            ip = config.get("api_ip")
            try:
                # TODO: apply SSL if needed
                check_call(
                    ["curl", "-s",
                     "http://{}:8083/Snh_ConfigClientReinitReq?".format(ip)])
                sleep(5)
                status, _ = _get_agent_status()
            except Exception as e:
                log("Reinitialize returns error: " + str(e))

    if status == 'active':
        status_set("active", "Unit is ready")
        return

    status_set("waiting", "vrouter-agent is not up")


def _get_agent_status():
    """ Analyzes output of 'contrail-status' utility

    returns status from agent service:
    """
    output = check_output("contrail-status", shell=True)
    for line in output.splitlines()[1:]:
        if len(line) == 0:
            return
        lst = line.decode('UTF-8').split()
        if len(lst) < 2:
            continue
        s_name = lst[0].strip()
        s_status = lst[1].strip()
        if 'contrail-vrouter-agent' not in s_name:
            continue

        log("contrail-status: " + line)
        return s_status, line