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)
def list_directory(self, path): """Helper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head(). """ try: list = os.listdir(path) except OSError: self.send_error( HTTPStatus.NOT_FOUND, "No permission to list directory") return None list.sort(key=lambda a: a.lower()) r = [] try: displaypath = urllib.parse.unquote(self.path, errors='surrogatepass') except UnicodeDecodeError: displaypath = urllib.parse.unquote(path) displaypath = html.escape(displaypath, quote=False) enc = sys.getfilesystemencoding() title = 'Directory listing for %s' % displaypath r.append('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" ' '"http://www.w3.org/TR/html4/strict.dtd">') r.append('<html>\n<head>') r.append('<meta http-equiv="Content-Type" ' 'content="text/html; charset=%s">' % enc) r.append('<title>%s</title>\n</head>' % title) r.append('<body>\n<h1>%s</h1>' % title) r.append('<hr>\n<ul>') for name in list: fullname = os.path.join(path, name) displayname = linkname = name # Append / for directories or @ for symbolic links if os.path.isdir(fullname): displayname = name + "/" linkname = name + "/" if os.path.islink(fullname): displayname = name + "@" # Note: a link to a directory displays with @ and links with / r.append('<li><a href="%s">%s</a></li>' % (urllib.parse.quote(linkname, errors='surrogatepass'), html.escape(displayname, quote=False))) r.append('</ul>\n<hr>\n</body>\n</html>\n') encoded = '\n'.join(r).encode(enc, 'surrogateescape') f = io.BytesIO() f.write(encoded) f.seek(0) self.send_response(HTTPStatus.OK) self.send_header("Content-type", "text/html; charset=%s" % enc) self.send_header("Content-Length", str(len(encoded))) self.end_headers() return f
def load_plugins(self): """Tries to load all plugins in folder plugins""" config = self.bitHopper.config try: if config.get('pluginmode', 'mode').find('disabled') == -1: if config.get('pluginmode', 'mode').find('auto') > -1: autoMode = True logging.info("Plugin loading mode: auto") else: autoMode = False logging.info("Plugin loading mode: manual") else: logging.info("Plugin loading mode: disabled") return except: logging.debug( 'Unable to find [pluginmode] section from bh.cfg, running with auto plugin loading mode' ) autoMode = True logging.info('Loading Plugins') possible_plugins = os.listdir('plugins') for item in possible_plugins: if os.path.isdir(os.path.join('plugins', item)): if autoMode: pluginEnabled = True else: pluginEnabled = False try: if config.getboolean('plugins', item): pluginEnabled = True except Exception, e: logging.info("" + item + " failed reading main config file: " + str(e)) pass if pluginEnabled: try: module = importlib.import_module('plugins.' + str(item)) bithop_attr = getattr(self.bitHopper, item, None) if bithop_attr is not None: logging.info('name conflict: ' + str(item)) continue #Actually call module and store it in bitHopper return_value = module.main(self.bitHopper) if return_value is None: setattr(self.bitHopper, item, module) else: setattr(self.bitHopper, item, return_value) logging.info("" + item + " loaded") except Exception, e: logging.info("ERROR LOADING PLUGIN: " + item) logging.info(e) else: logging.info("" + item + " has been disabled")
def list_directory(self, path): """Helper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head(). """ try: list = os.listdir(path) except OSError: self.send_error(HTTPStatus.NOT_FOUND, "No permission to list directory") return None list.sort(key=lambda a: a.lower()) r = [] try: displaypath = urllib.parse.unquote(self.path, errors='surrogatepass') except UnicodeDecodeError: displaypath = urllib.parse.unquote(path) displaypath = html.escape(displaypath, quote=False) enc = sys.getfilesystemencoding() title = 'Directory listing for %s' % displaypath r.append('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" ' '"http://www.w3.org/TR/html4/strict.dtd">') r.append('<html>\n<head>') r.append('<meta http-equiv="Content-Type" ' 'content="text/html; charset=%s">' % enc) r.append('<title>%s</title>\n</head>' % title) r.append('<body>\n<h1>%s</h1>' % title) r.append('<hr>\n<ul>') for name in list: fullname = os.path.join(path, name) displayname = linkname = name # Append / for directories or @ for symbolic links if os.path.isdir(fullname): displayname = name + "/" linkname = name + "/" if os.path.islink(fullname): displayname = name + "@" # Note: a link to a directory displays with @ and links with / r.append('<li><a href="%s">%s</a></li>' % (urllib.parse.quote(linkname, errors='surrogatepass'), html.escape(displayname, quote=False))) r.append('</ul>\n<hr>\n</body>\n</html>\n') encoded = '\n'.join(r).encode(enc, 'surrogateescape') f = io.BytesIO() f.write(encoded) f.seek(0) self.send_response(HTTPStatus.OK) self.send_header("Content-type", "text/html; charset=%s" % enc) self.send_header("Content-Length", str(len(encoded))) self.end_headers() return f
def deleteContent(self): # The default implementation deletes all files under the TFTP directory # with a name containing a lowercase or uppercase MAC address that # matches the one assigned for the endpoint lcasemac = self._mac.replace(':', '').lower() ucasemac = self._mac.replace(':', '').upper() for filename in os.listdir(TFTP_DIR): if (lcasemac in filename) or (ucasemac in filename): os.unlink(TFTP_DIR + '/' + filename) # Unregister accounts self._unregister()
def find_account_by_inode(inode): for name in os.listdir(GRIDMAPDIR): if name[0] == "%": continue path = os.path.join(GRIDMAPDIR, name) try: if os.stat(path).st_ino == inode: return name except OSError: continue return None
def load_plugins(self): """Tries to load all plugins in folder plugins""" config = self.bitHopper.config try: if config.get('pluginmode', 'mode').find('disabled') == -1: if config.get('pluginmode', 'mode').find('auto') > -1: autoMode = True logging.info("Plugin loading mode: auto") else: autoMode = False logging.info("Plugin loading mode: manual") else: logging.info("Plugin loading mode: disabled") return except: logging.debug('Unable to find [pluginmode] section from bh.cfg, running with auto plugin loading mode') autoMode = True logging.info('Loading Plugins') possible_plugins = os.listdir('plugins') for item in possible_plugins: if os.path.isdir(os.path.join('plugins', item)): if autoMode: pluginEnabled = True else: pluginEnabled = False try: if config.getboolean('plugins', item): pluginEnabled = True except Exception, e: logging.info("" + item + " failed reading main config file: " + str(e)) pass if pluginEnabled: try: module = importlib.import_module('plugins.' + str(item)) bithop_attr = getattr(self.bitHopper, item, None) if bithop_attr is not None: logging.info('name conflict: ' + str(item)) continue #Actually call module and store it in bitHopper return_value = module.main(self.bitHopper) if return_value is None: setattr(self.bitHopper, item, module) else: setattr(self.bitHopper, item, return_value) logging.info("" + item + " loaded") except Exception, e: logging.info("ERROR LOADING PLUGIN: " + item) logging.info(e) else: logging.info("" + item + " has been disabled")
def generateDirectoryIndex(dirpath, root_dir): current_dir, filenames = dirpath, os.listdir(dirpath) output = StringIO() output.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><html>') output.write("<title>Directory index for {0} </title>".format(current_dir)) output.write("<body><h2>Directory index for {0} </h2><hr><ul>".format(current_dir)) for filename in filenames: if os.path.isdir(os.path.join(dirpath, filename)): filename += "/" output.write('<li><a href="') output.write(filename) output.write('">') output.write(filename) output.write("</a>") output.write("</ul><hr></body></html>") return output.getvalue()
def generateDirectoryIndex(dirpath, root_dir): current_dir, filenames = dirpath, os.listdir(dirpath) output = StringIO() output.write( "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\"><html>") output.write("<title>Directory index for {0} </title>".format(current_dir)) output.write( "<body><h2>Directory index for {0} </h2><hr><ul>".format(current_dir)) for filename in filenames: if os.path.isdir(os.path.join(dirpath, filename)): filename += '/' output.write("<li><a href=\"") output.write(filename) output.write("\">") output.write(filename) output.write("</a>") output.write("</ul><hr></body></html>") return output.getvalue()
def load_plugins(self): """Tries to load all plugins in folder plugins""" self.bitHopper.log_msg('Loading Plugins') possible_plugins = os.listdir('plugins') for item in possible_plugins: if os.path.isdir(item): try: module = importlib.import_module('plugins.' + str(item)) bithop_attr = getattr(self.bitHopper, item, None) if bithop_attr is not None: self.bitHopper.log_msg('Plugin name conflict: ' + str(item)) continue #Actually call module and store it in bitHopper return_value = module.main(self.bitHopper) if return_value is None: setattr(self.bitHopper, item, module) else: setattr(self.bitHopper, item, return_value) except Exception, e: self.bitHopper.log_msg("Error loading plugin: " + item) self.bitHopper.log_msg(e)
def allocate_new_account(mapping, entry): pool = mapping[1:] for name in os.listdir(GRIDMAPDIR): if not name.startswith(pool): continue good = True for ch in name[len(pool):]: if not ch.isdigit(): good = False break if not good: continue path = os.path.join(GRIDMAPDIR, name) st = os.stat(path) if st.st_nlink != 1: continue try: os.link(path, os.path.join(GRIDMAPDIR, entry)) return name except OSError: continue return None
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)