def handle(_name, cfg, _cloud, log, args):
    if len(args) != 0:
        msg_in = args[0]
    else:
        msg_in = util.get_cfg_option_str(cfg, "final_message", final_message)

    try:
        uptimef = open("/proc/uptime")
        uptime = uptimef.read().split(" ")[0]
        uptimef.close()
    except IOError as e:
        log.warn("unable to open /proc/uptime\n")
        uptime = "na"

    try:
        ts = time.strftime("%a, %d %b %Y %H:%M:%S %z", time.gmtime())
    except:
        ts = "na"

    try:
        subs = {'UPTIME': uptime, 'TIMESTAMP': ts}
        sys.stdout.write("%s\n" % util.render_string(msg_in, subs))
    except Exception as e:
        log.warn("failed to render string to stdout: %s" % e)

    fp = open(boot_finished, "wb")
    fp.write(uptime + "\n")
    fp.close()
def add_sources(srclist, searchList=None):
    """
    add entries in /etc/apt/sources.list.d for each abbreviated
    sources.list entry in 'srclist'.  When rendering template, also
    include the values in dictionary searchList
    """
    if searchList is None:
        searchList = {}
    elst = []

    for ent in srclist:
        if 'source' not in ent:
            elst.append(["", "missing source"])
            continue

        source = ent['source']
        if source.startswith("ppa:"):
            try:
                util.subp(["add-apt-repository", source])
            except:
                elst.append([source, "add-apt-repository failed"])
            continue

        source = util.render_string(source, searchList)

        if 'filename' not in ent:
            ent['filename'] = 'cloud_config_sources.list'

        if not ent['filename'].startswith("/"):
            ent['filename'] = "%s/%s" % \
                ("/etc/apt/sources.list.d/", ent['filename'])

        if ('keyid' in ent and 'key' not in ent):
            ks = "keyserver.ubuntu.com"
            if 'keyserver' in ent:
                ks = ent['keyserver']
            try:
                ent['key'] = util.getkeybyid(ent['keyid'], ks)
            except:
                elst.append([source, "failed to get key from %s" % ks])
                continue

        if 'key' in ent:
            try:
                util.subp(('apt-key', 'add', '-'), ent['key'])
            except:
                elst.append([source, "failed add key"])

        try:
            util.write_file(ent['filename'], source + "\n", omode="ab")
        except:
            elst.append([source, "failed write to file %s" % ent['filename']])

    return(elst)
Example #3
0
def handle(_name, cfg, cloud, log, args):
    if len(args) != 0:
        ph_cfg = util.read_conf(args[0])
    else:
        if not 'phone_home' in cfg:
            return
        ph_cfg = cfg['phone_home']

    if 'url' not in ph_cfg:
        log.warn("no 'url' token in phone_home")
        return

    url = ph_cfg['url']
    post_list = ph_cfg.get('post', 'all')
    tries = ph_cfg.get('tries', 10)
    try:
        tries = int(tries)
    except:
        log.warn("tries is not an integer. using 10")
        tries = 10

    if post_list == "all":
        post_list = post_list_all

    all_keys = {}
    all_keys['instance_id'] = cloud.get_instance_id()
    all_keys['hostname'] = cloud.get_hostname()

    pubkeys = {
        'pub_key_dsa': '/etc/ssh/ssh_host_dsa_key.pub',
        'pub_key_rsa': '/etc/ssh/ssh_host_rsa_key.pub',
        'pub_key_ecdsa': '/etc/ssh/ssh_host_ecdsa_key.pub',
    }

    for n, path in pubkeys.iteritems():
        try:
            fp = open(path, "rb")
            all_keys[n] = fp.read()
            fp.close()
        except:
            log.warn("%s: failed to open in phone_home" % path)

    submit_keys = {}
    for k in post_list:
        if k in all_keys:
            submit_keys[k] = all_keys[k]
        else:
            submit_keys[k] = "N/A"
            log.warn("requested key %s from 'post' list not available")

    url = util.render_string(url, {'INSTANCE_ID': all_keys['instance_id']})

    null_exc = object()
    last_e = null_exc
    for i in range(0, tries):
        try:
            util.readurl(url, submit_keys)
            log.debug("succeeded submit to %s on try %i" % (url, i + 1))
            return
        except Exception as e:
            log.debug("failed to post to %s on try %i" % (url, i + 1))
            last_e = e
        sleep(3)

    log.warn("failed to post to %s in %i tries" % (url, tries))
    if last_e is not null_exc:
        raise(last_e)

    return