Example #1
0
def main():
    # expect to be called with
    #   <freq> <semaphore-name> <module-name> args
    if len(sys.argv) < 4:
        Usage(sys.stderr)
        sys.exit(1)

    (freq, semname, modname) = sys.argv[1:4]
    run_args = sys.argv[4:]

    cloudinit.logging_set_from_cfg_file()
    log = logging.getLogger()
    log.info("cloud-init-run-module %s" % sys.argv[1:])
    cloud = cloudinit.CloudInit()
    try:
        cloud.get_data_source()
    except Exception as e:
        fail("Failed to get instance data\n\t%s" % traceback.format_exc(), log)

    if cloud.sem_has_run(semname, freq):
        msg = "%s already ran %s" % (semname, freq)
        sys.stderr.write("%s\n" % msg)
        log.debug(msg)
        sys.exit(0)

    try:
        mod = __import__('cloudinit.' + modname)
        inst = getattr(mod, modname)
    except:
        fail("Failed to load module cloudinit.%s\n" % modname)

    import os

    cfg_path = None
    cfg_env_name = cloudinit.cfg_env_name
    if os.environ.has_key(cfg_env_name):
        cfg_path = os.environ[cfg_env_name]

    try:
        cloud.sem_and_run(semname, freq, inst.run, [run_args, cfg_path, log],
                          False)
    except Exception as e:
        fail("Execution of %s failed:%s" % (semname, e), log)

    sys.exit(0)
def main():
    # expect to be called with
    #   <freq> <semaphore-name> <module-name> args
    if len(sys.argv) < 4:
        Usage(sys.stderr)
        sys.exit(1)

    (freq,semname,modname)=sys.argv[1:4]
    run_args=sys.argv[4:]

    cloudinit.logging_set_from_cfg_file()
    log = logging.getLogger()
    log.info("cloud-init-run-module %s" % sys.argv[1:])
    cloud = cloudinit.CloudInit()
    try:
        cloud.get_data_source()
    except Exception as e:
        fail("Failed to get instance data\n\t%s" % traceback.format_exc(),log)

    if cloud.sem_has_run(semname,freq):
        msg="%s already ran %s" % (semname,freq)
        sys.stderr.write("%s\n" % msg)
        log.debug(msg)
        sys.exit(0)

    try:
        mod = __import__('cloudinit.' + modname)
        inst = getattr(mod,modname)
    except:
        fail("Failed to load module cloudinit.%s\n" % modname)

    import os

    cfg_path = None
    cfg_env_name = cloudinit.cfg_env_name
    if os.environ.has_key(cfg_env_name):
        cfg_path = os.environ[cfg_env_name]

    try:
        cloud.sem_and_run(semname, freq, inst.run, [run_args,cfg_path,log], False)
    except Exception as e:
        fail("Execution of %s failed:%s" % (semname,e), log)

    sys.exit(0)
Example #3
0
def main():
    cmds = ( "start", "start-local" )
    cmd = ""
    if len(sys.argv) > 1:
        cmd = sys.argv[1]

    if not cmd in cmds:
        sys.stderr.write("bad command %s. use one of %s\n" % (cmd, cmds))
        sys.exit(1)

    now = time.strftime("%a, %d %b %Y %H:%M:%S %z")
    try:
       uptimef=open("/proc/uptime")
       uptime=uptimef.read().split(" ")[0]
       uptimef.close()
    except IOError as e:
       warn("unable to open /proc/uptime\n")
       uptime = "na"

    msg = "cloud-init %s running: %s. up %s seconds" % (cmd, now, uptime)
    sys.stderr.write(msg + "\n")
    sys.stderr.flush()

    source_type = "all"
    if cmd == "start-local":
        source_type = "local"

    cloudinit.logging_set_from_cfg_file()
    log = logging.getLogger()
    log.info(msg)

    # cache is not instance specific, so it has to be purged
    # but we want 'start' to benefit from a cache if
    # a previous start-local populated one
    if cmd == "start-local":
        cloudinit.purge_cache()

    cloud = cloudinit.CloudInit(source_type=source_type)
    dist  = cloudinit.DistAction.DistAction("/etc/cloud/dist-defs.cfg")

    try:
        cloud.get_data_source()
    except cloudinit.DataSourceNotFoundException as e:
        sys.stderr.write("no instance data found in %s\n" % cmd)
        sys.exit(1)

    # store the metadata
    cloud.update_cache()

    msg = "found data source: %s" % cloud.datasource
    sys.stderr.write(msg + "\n")
    log.debug(msg)

    # parse the user data (ec2-run-userdata.py)
    try:
        cloud.sem_and_run("consume_userdata", "once-per-instance",
            cloud.consume_userdata,[],False)
    except:
        warn("consuming user data failed!\n")
        raise

    #print "user data is:" + cloud.get_userdata()

    # finish, send the cloud-config event
    dist.init_notify(cloudinit.cfg_env_name, cloudinit.cloud_config)

    sys.exit(0)
Example #4
0
def handle(_name, cfg, _cloud, log, _args):
    # rsyslog:
    #  - "*.* @@192.158.1.1"
    #  - content: "*.*   @@192.0.2.1:10514"
    #  - filename: 01-examplecom.conf
    #    content: |
    #      *.*   @@syslogd.example.com

    # process 'rsyslog'
    if not 'rsyslog' in cfg:
        return

    def_dir = cfg.get('rsyslog_dir', DEF_DIR)
    def_fname = cfg.get('rsyslog_filename', DEF_FILENAME)

    files = []
    elst = []
    for ent in cfg['rsyslog']:
        if isinstance(ent, dict):
            if not "content" in ent:
                elst.append((ent, "no 'content' entry"))
                continue
            content = ent['content']
            filename = ent.get("filename", def_fname)
        else:
            content = ent
            filename = def_fname

        if not filename.startswith("/"):
            filename = "%s/%s" % (def_dir, filename)

        omode = "ab"
        # truncate filename first time you see it
        if filename not in files:
            omode = "wb"
            files.append(filename)

        try:
            util.write_file(filename, content + "\n", omode=omode)
        except Exception as e:
            log.debug(traceback.format_exc(e))
            elst.append((content, "failed to write to %s" % filename))

    # need to restart syslogd
    restarted = False
    try:
        # if this config module is running at cloud-init time
        # (before rsyslog is running) we don't actually have to
        # restart syslog.
        #
        # upstart actually does what we want here, in that it doesn't
        # start a service that wasn't running already on 'restart'
        # it will also return failure on the attempt, so 'restarted'
        # won't get set
        log.debug("restarting rsyslog")
        util.subp(['service', 'rsyslog', 'restart'])
        restarted = True

    except Exception as e:
        elst.append(("restart", str(e)))

    if restarted:
        # this only needs to run if we *actually* restarted
        # syslog above.
        cloudinit.logging_set_from_cfg_file()
        log = logging.getLogger()
        log.debug("rsyslog configured %s" % files)

    for e in elst:
        log.warn("rsyslog error: %s\n" % ':'.join(e))

    return
Example #5
0
def main():
    # expect to be called with
    #   name [ freq [ args ]
    #   run the cloud-config job 'name' at with given args
    # or
    #   read cloud config jobs from config (builtin -> system)
    #   and run all in order

    if len(sys.argv) < 2:
        Usage(sys.stderr)
        sys.exit(1)
    if sys.argv[1] == "all":
        name = "all"
    else:
        freq = None
        run_args = []
        name=sys.argv[1]
        if len(sys.argv) > 2:
            freq = sys.argv[2]
            if freq == "None":
                freq = None
        if len(sys.argv) > 3:
            run_args=sys.argv[3:]

    cloudinit.logging_set_from_cfg_file()
    log = logging.getLogger()
    log.info("cloud-init-cfg %s" % sys.argv[1:])

    cfg_path = cloudinit.cloud_config
    cfg_env_name = cloudinit.cfg_env_name
    if os.environ.has_key(cfg_env_name):
        cfg_path = os.environ[cfg_env_name]

    cc = cloudinit.CloudConfig.CloudConfig(cfg_path)

    module_list = [ ]
    if name == "all":
        # create 'module_list', an array of arrays
        # where array[0] = config
        #       array[1] = freq
        #       array[2:] = arguemnts
        if "cloud_config_modules" in cc.cfg:
            for item in cc.cfg["cloud_config_modules"]:
                if isinstance(item,str):
                    module_list.append((item,))
                elif isinstance(item,list):
                    module_list.append(item)
                else:
                    fail("Failed to parse cloud_config_modules",log)
        else:
            fail("No cloud_config_modules found in config",log)
    else:
        module_list.append( [ name, freq ] + run_args )

    failures = []
    for cfg_mod in module_list:
        name = cfg_mod[0]
        freq = None
        run_args = [ ]
        if len(cfg_mod) > 1:
            freq = cfg_mod[1]
        if len(cfg_mod) > 2:
            run_args = cfg_mod[2:]
        try:
            log.debug("handling %s with freq=%s and args=%s" %
                (name, freq, run_args ))
            cc.handle(name, run_args, freq=freq)
        except:
            log.warn(traceback.format_exc())
            err("config handling of %s, %s, %s failed\n" %
                (name,freq,run_args), log)
            failures.append(name)
            
    sys.exit(len(failures))
Example #6
0
def main():
    cmds = ("start", "start-local")
    cmd = ""
    if len(sys.argv) > 1:
        cmd = sys.argv[1]

    if not cmd in cmds:
        sys.stderr.write("bad command %s. use one of %s\n" % (cmd, cmds))
        sys.exit(1)

    now = time.strftime("%a, %d %b %Y %H:%M:%S %z")
    try:
        uptimef = open("/proc/uptime")
        uptime = uptimef.read().split(" ")[0]
        uptimef.close()
    except IOError as e:
        warn("unable to open /proc/uptime\n")
        uptime = "na"

    msg = "cloud-init %s running: %s. up %s seconds" % (cmd, now, uptime)
    sys.stderr.write(msg + "\n")
    sys.stderr.flush()

    source_type = "all"
    if cmd == "start-local":
        source_type = "local"

    cloudinit.logging_set_from_cfg_file()
    log = logging.getLogger()
    log.info(msg)

    # cache is not instance specific, so it has to be purged
    # but we want 'start' to benefit from a cache if
    # a previous start-local populated one
    if cmd == "start-local":
        cloudinit.purge_cache()

    cloud = cloudinit.CloudInit(source_type=source_type)
    dist = cloudinit.DistAction.DistAction("/etc/cloud/dist-defs.cfg")

    try:
        cloud.get_data_source()
    except cloudinit.DataSourceNotFoundException as e:
        sys.stderr.write("no instance data found in %s\n" % cmd)
        sys.exit(1)

    # store the metadata
    cloud.update_cache()

    msg = "found data source: %s" % cloud.datasource
    sys.stderr.write(msg + "\n")
    log.debug(msg)

    # parse the user data (ec2-run-userdata.py)
    try:
        cloud.sem_and_run("consume_userdata", "once-per-instance",
                          cloud.consume_userdata, [], False)
    except:
        warn("consuming user data failed!\n")
        raise

    #print "user data is:" + cloud.get_userdata()

    # finish, send the cloud-config event
    dist.init_notify(cloudinit.cfg_env_name, cloudinit.cloud_config)

    sys.exit(0)