Ejemplo n.º 1
0
def bootstrap():
    defaults_path = os.path.expanduser('~/Library/Preferences/org.ratazzi.ServicesBox.plist')
    defaults = dict()
    if os.path.isfile(defaults_path):
        try:
            defaults = biplist.readPlist(defaults_path)
        except (biplist.InvalidPlistException, biplist.NotBinaryPlistException):
            defaults = plistlib.readPlist(defaults_path)

    if 'dir_library' in defaults:
        env.add('dir_library', defaults['dir_library'])
    else:
        # development environment
        env.add('dir_library', os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))

    bundles = 'darwin' in sys.platform and 'bundles' or 'bundle'

    env.add('dir_bundles', os.path.join(env.get('dir_library'), bundles))
    env.add('dir_config', os.path.join(env.get('dir_library'), 'etc'))
    env.add('dir_bin', os.path.join(env.get('dir_library'), 'bin'))
    env.add('dir_tmp', os.path.join(env.get('dir_library'), 'tmp'))
    env.add('dir_data', os.path.join(env.get('dir_library'), 'data'))
    env.add('dir_log', os.path.join(env.get('dir_library'), 'var', 'log'))
    env.add('dir_run', os.path.join(env.get('dir_library'), 'var', 'run'))

    # custom data path
    for item in DEFAULT_DIRS.keys():
        key = 'dir_%s' % item
        if defaults.get(key):
            env.add(key, defaults[key])

    for k, _dir in os.environ.items():
        if k.startswith('%sDIR_' % env.PREFIX):
            if not os.path.exists(_dir):
                os.makedirs(_dir)
Ejemplo n.º 2
0
def gen_config():
    for item in os.listdir(env.get('dir_config')):
        _path = runtime.path.join(env.get('dir_config'), item)
        if os.path.isfile(_path):
            os.remove(_path)
        else:
            shutil.rmtree(_path)
    for bundle_desc in runtime.path.all_bundles_desc():
        ENV_DICT = env.all_dict()
        with open(bundle_desc, 'r') as fp:
            _bundle_desc = yaml.load(fp.read())
            _bundle = store.find(Bundle, Bundle.name == _bundle_desc['name']).one()
            # _bundle = bundle.get(_bundle_desc['name'])
            ENV_DICT.update(_bundle.env())
            for _conf in _bundle_desc.get('conf', []):
                src = _conf['src'].format(**ENV_DICT)
                dst = _conf['dst'].format(**ENV_DICT)
                dst_dir = os.path.dirname(dst)
                if not os.path.exists(dst_dir):
                    os.makedirs(dst_dir)
                content = None
                with open(src, 'r') as fp:
                    try:
                        content = template.Template(fp.read()).generate(**ENV_DICT)
                    except Exception, e:
                        print e
                        print traceback.format_exc()
                with open(dst, 'w') as fp:
                    fp.write(content)
                    # print dst
                    logger.info('genrate config file %s' % dst)
Ejemplo n.º 3
0
 def env(self, additional=False):
     _env = {"DIR_BUNDLE": runtime.path.join(env.get("dir_bundles"), self.name)}
     for k, v in os.environ.items():
         if k.startswith(env.PREFIX):
             k = k.replace(env.PREFIX, "")
             _env[k] = v
     for _dir in _env.values():
         if not os.path.exists(_dir):
             os.makedirs(_dir)
     _env.update(self.directories_env())
     _env.update(self.options_env())
     return _env
Ejemplo n.º 4
0
def process_bundle_dirs(bundle):
    ENV_DICT = env.all_dict()
    for _dir in bundle.directories:
        if _dir.dir is None and _dir.name not in DEFAULT_DIRS.keys():
            raise Exception("Invalid default dir: `%s'" % _dir.name)

        if _dir.dir is None:
            _dir_name = 'dir_%s' % _dir.name
            _dst = join(env.get(_dir_name), _dir.bundle)
        else:

            _dst = _dir.dir.format(**ENV_DICT)
        if not os.path.exists(_dst):
            os.makedirs(_dst)
Ejemplo n.º 5
0
    def _start(self, **kwargs):
        if self.name in list_running_services():
            runtime.eerror("service `%s' is already running." % self.name)
            return

        if not self.enable:
            runtime.eerror("service `%s' is disabled." % self.name)
            return

        ENV_DICT = env.all_dict()
        ENV_DICT["DIR_BUNDLE"] = runtime.path.join(env.get("dir_bundles"), self.name)
        ENV_DICT["DIR_BUNDLE_CONFIG"] = runtime.path.join(env.get("dir_config"), self.name)
        for _dir in self.directories:
            if _dir.dir is None and _dir.name not in runtime.path.DEFAULT_DIRS.keys():
                raise Exception("Invalid default dir: `%s'" % _dir.name)

            if _dir.dir is None:
                _dir_name = "dir_%s" % _dir.name
                _dst = runtime.path.join(env.get(_dir_name), _dir.bundle)
            else:
                _dst = _dir.dir.format(**ENV_DICT)
            _dir_name = "DIR_BUNDLE_%s" % _dir.name.upper()
            ENV_DICT[_dir_name] = _dst
            if not os.path.exists(_dst):
                os.makedirs(_dst)
        for name, _dir in ENV_DICT.items():
            if name.startswith("DIR_BUNDLE") and not os.path.exists(_dir):
                os.makedirs(_dir)
        cmd = self.start.format(**ENV_DICT)
        _env = self.env
        for key, value in _env.items():
            _env[key] = value.format(**ENV_DICT)
        runtime.einfo(cmd)
        logger.debug(cmd)
        runtime.einfo("start service `%s'." % self.name)
        kwargs = {"env": _env}
        logger.debug(kwargs)
        p = subprocess.Popen(cmd.split(), **kwargs)
        runtime.einfo(p.pid)
Ejemplo n.º 6
0
def _load_bundle(bundle_desc):
    # pprint(bundle_desc)
    print "register bundle `%s'" % bundle_desc['name']
    _bundle = store.find(Bundle, Bundle.name == bundle_desc['name']).one() or Bundle()
    _bundle.name = bundle_desc['name']
    _bundle.description = bundle_desc['description']
    store.add(_bundle)

    if 'options' in bundle_desc:
        for _option_desc in bundle_desc['options']:
            _option = store.find(Option, Option.name == _option_desc['name'], Option.bundle == bundle_desc['name']).one() or Option()
            _option.name = _option_desc['name']
            _option.bundle = bundle_desc['name']
            _option.description = _option_desc.get('description', _option_desc['name'])
            _option.value = unicode(_option_desc['value'])
            store.add(_option)

    if 'service' in bundle_desc:
        _service_desc = bundle_desc['service']
        _service = store.find(Service, Service.name == bundle_desc['name']).one() or Service()
        _service.name = bundle_desc['name']
        _service.bundle = bundle_desc['name']
        _service.description = _service_desc['description']
        _service.start = _service_desc['start']
        _service.stop = _service_desc['stop']
        _service.restart = _service_desc['restart']
        _service.env = _service_desc.get('env', {})
        _service.enable = _service_desc.get('enable', True)
        _service.autostart = _service_desc.get('autostart', True)
        store.add(_service)

    if 'directories' in bundle_desc:
        for _dir_desc in bundle_desc['directories']:
            _dir = store.find(Directory, Directory.name == _dir_desc['name'], Directory.bundle == bundle_desc['name']).one() or Directory()
            _dir.name = _dir_desc['name']
            _dir.bundle = bundle_desc['name']
            _dir.dir = _dir_desc.get('dir', None)
            _dir.permission = _dir_desc.get('permission', u'0755')
            _dir.description = _dir_desc['description']
            store.add(_dir)
    store.commit()

    # copy data
    if 'data' in bundle_desc:
        _env = _bundle.env(True)
        data = bundle_desc['data']
        src = data['src'].format(**_env)
        dst = data['dst'].format(**_env)
        if os.path.exists(dst) and len(os.listdir(dst)) == 0:
            logger.info('remove empty directory %s' % dst)
            shutil.rmtree(dst)
        if not os.path.exists(dst):
            shutil.copytree(src, dst)

    # # bin symlink
    bundle_bin_dir = runtime.path.join(env.get('dir_bundles'), _bundle.name, 'bin')
    if not os.path.exists(env.get('dir_bin')):
        os.makedirs(env.get('dir_bin'))
    if os.path.exists(bundle_bin_dir):
        for item in os.listdir(bundle_bin_dir):
            dst = runtime.path.join(env.get('dir_bin'), item)
            if item in ('.DS_Store'):
                continue
            if os.path.islink(dst) or os.path.isfile(dst):
                os.unlink(dst)
            os.symlink(runtime.path.join(bundle_bin_dir, item), dst)

    # # lib symlink
    bundle_lib_dir = runtime.path.join(env.get('dir_bundles'), _bundle.name, 'lib')
    lib_dir = runtime.path.join(env.get('dir_bundles'), 'lib')
    if not os.path.exists(lib_dir):
        os.makedirs(lib_dir)
    if os.path.exists(bundle_lib_dir):
        for item in os.listdir(bundle_lib_dir):
            src = runtime.path.join(bundle_lib_dir, item)
            dst = runtime.path.join(lib_dir, item)
            if item in ('.DS_Store'):
                continue
            if os.path.islink(dst) or os.path.isfile(dst):
                os.unlink(dst)
            if os.path.isdir(src):
                continue
            os.symlink(src, dst)