def docs(ctx, clear_target): """Build and install documentation""" # TODO: Move this to the environment handling and deprecate it here install_docs(str(ctx.obj["instance"]), clear_target) finish(ctx)
def rename(ctx, source, destination, keep, clear_target): """Rename Mongodb databases""" from pymongo import MongoClient client = MongoClient(ctx.obj["dbhost"]) if source not in client.list_database_names(): log("Source database", source, "does not exist!", lvl=warn) abort(-1) database = client.admin log("Copying", source, "to", destination) if destination in client.list_database_names(): log("Destination exists") if clear_target: log("Clearing") client.drop_database(destination) else: log("Not destroying existing data", lvl=warn) abort(-1) database.command("copydb", fromdb=source, todb=destination) if not keep: log("Deleting old database") client.drop_database(source) finish(ctx)
def view(ctx, schema, uuid, object_filter): """Show stored objects""" database = ctx.obj["db"] if schema is None: log("No schema given. Read the help", lvl=warn) return model = database.objectmodels[schema] if uuid: obj = model.find({"uuid": uuid}) elif object_filter: obj = model.find(literal_eval(object_filter)) else: obj = model.find() if obj is None or model.count() == 0: log("No objects found.", lvl=warn) for item in obj: pprint(item._fields) finish(ctx)
def install(ctx, **kwargs): """Install a new environment of an instance""" log("Installing instance") env = ctx.obj["instance_configuration"]["environments"] green = env["green"]["installed"] blue = env["blue"]["installed"] if green or blue: log( "At least one environment is installed or in a non-clear state.\n" "Please use 'iso instance upgrade' to upgrade an instance.", lvl=warn, ) abort(50081) _clear_instance(ctx, force=kwargs["force"], clear=False, no_archive=True) _install_environment(ctx, **kwargs) ctx.obj["instance_configuration"]["source"] = kwargs["source"] ctx.obj["instance_configuration"]["url"] = kwargs["url"] write_instance(ctx.obj["instance_configuration"]) _turnover(ctx, force=kwargs["force"]) finish(ctx)
def _clear_instance(ctx, force, clear, no_archive): log("Clearing instance:", ctx.obj["instance"]) log("Clearing blue environment.", lvl=debug) _clear_environment(ctx, force, "blue", clear, no_archive) log("Clearing green environment.", lvl=debug) _clear_environment(ctx, force, "green", clear, no_archive) finish(ctx)
def illegalcheck(ctx, schema, delete_duplicates, fix, test): """Tool to find erroneous objects created with old legacy bugs. Should be obsolete!""" database = ctx.obj["db"] if delete_duplicates and fix: log("Delete and fix operations are exclusive.") return if schema is None: schemata = database.objectmodels.keys() else: schemata = [schema] for thing in schemata: log("Schema:", thing) for item in database.objectmodels[thing].find(): if not isinstance(item._fields["_id"], bson.objectid.ObjectId): if not delete_duplicates: log(item.uuid) log(item._fields, pretty=True, lvl=verbose) if test: if database.objectmodels[thing].count({"uuid": item.uuid}) == 1: log("Only a faulty object exists.") if delete_duplicates: item.delete() if fix: _id = item._fields["_id"] item._fields["_id"] = bson.objectid.ObjectId(_id) if not isinstance(item._fields["_id"], bson.objectid.ObjectId): log("Object mongo ID field not valid!", lvl=warn) item.save() database.objectmodels[thing].find_one({"_id": _id}).delete() finish(ctx)
def modify(ctx, schema, uuid, object_filter, field, value): """Modify field values of objects""" database = ctx.obj["db"] model = database.objectmodels[schema] obj = None if uuid: obj = model.find_one({"uuid": uuid}) elif object_filter: obj = model.find_one(literal_eval(object_filter)) else: log("No object uuid or filter specified.", lvl=error) if obj is None: log("No object found", lvl=error) return log("Object found, modifying", lvl=debug) try: new_value = literal_eval(value) except ValueError: log("Interpreting value as string") new_value = str(value) obj._fields[field] = new_value obj.validate() log("Changed object validated", lvl=debug) obj.save() finish(ctx)
def validate(ctx, schema, all_schemata): """Validates all objects or all objects of a given schema.""" database = ctx.obj["db"] if schema is None: if all_schemata is False: log("No schema given. Read the help", lvl=warn) return else: schemata = database.objectmodels.keys() else: schemata = [schema] for schema in schemata: try: things = database.objectmodels[schema] with click.progressbar( things.find(), length=things.count(), label="Validating %15s" % schema ) as object_bar: for obj in object_bar: obj.validate() except Exception as e: log( "Exception while validating:", schema, e, type(e), "\n\nFix this object and rerun validation!", emitter="MANAGE", lvl=error, ) finish(ctx)
def update_nginx(ctx, hostname): """instance nginx configuration""" ctx.obj["hostname"] = hostname _create_nginx_config(ctx) finish(ctx)
def check_environment(ctx, dev): """General fitness tests of the built environment""" if _check_environment(ctx, dev=dev): log("Environment seems healthy") finish(ctx)
def install_frontend(ctx): """Install frontend into an environment""" next_environment = get_next_environment(ctx) set_instance(ctx.obj["instance"], next_environment) _install_frontend(ctx) finish(ctx)
def provisions(ctx, package, clear_existing, overwrite, list_provisions): """Install default provisioning data""" # TODO: Move this to the environment handling and deprecate it here install_provisions(ctx, package, clear_existing, overwrite, list_provisions) finish(ctx)
def list_all(ctx): """List all available Mongo Databases on the configured database host.""" from pymongo import MongoClient client = MongoClient(ctx.obj["dbhost"]) log(client.list_database_names()) finish(ctx)
def configure(ctx): """Generate a skeleton configuration for Isomer (needs sudo)""" if os.path.exists(get_etc_path()): abort(EXIT_NOT_OVERWRITING_CONFIGURATION) ctx = create_configuration(ctx) finish(ctx)
def copy(ctx, source, destination): """Copies an entire database""" if source is None: source = ctx.obj["dbname"] copy_database(ctx.obj["dbhost"], source, destination) finish(ctx)
def configure(ctx): """Generate a skeleton configuration for Isomer (needs sudo)""" if os.path.exists(os.path.join(get_etc_path(), "isomer.conf")): abort(EXIT_NOT_OVERWRITING_CONFIGURATION) ctx = create_configuration(ctx) write_configuration(ctx.obj['config']) finish(ctx)
def create_user(ctx): """Creates a new local user""" try: new_user = _create_user(ctx) new_user.save() finish(ctx) except KeyError: log("User already exists", lvl=warn)
def archive(ctx, force, dynamic): """Archive the specified or non-active environment""" result = _archive(ctx, force, dynamic) if result: log("Archived to '%s'" % result) finish(ctx) else: log("Could not archive.", lvl=error) abort(50060)
def create_admin(ctx): """Creates a new local user and assigns admin role""" try: admin = _create_user(ctx) admin.roles.append("admin") admin.save() finish(ctx) except KeyError: log("User already exists", lvl=warn)
def enable(ctx): """Enable an existing user""" if ctx.obj["username"] is None: log('Specify the username with "iso db user --username ..."') return change_user = (ctx.obj["db"].objectmodels["user"].find_one( {"name": ctx.obj["username"]})) change_user.active = True change_user.save() finish(ctx)
def install_modules(ctx): """Installs all instance configured modules To configure (and install) modules for an instance, use iso instance install-modules -s <SOURCE> [URLS] To immediately install them, add --install """ _install_modules(ctx) finish(ctx)
def remove(ctx, clear, no_archive): """Irrevocably remove a whole instance""" if clear: log("Destructively removing instance:", ctx.obj["instance"], lvl=warn) if not ask("Are you sure", default=False, data_type="bool"): abort(EXIT_USER_BAILED_OUT) if clear: _clear_instance(ctx, force=True, clear=clear, no_archive=no_archive) remove_instance(ctx.obj["instance"]) finish(ctx)
def list_users(ctx, search, uuid, active): """List all locally known users""" users = ctx.obj["db"].objectmodels["user"] for found_user in users.find(): if not search or (search and search in found_user.name): print(found_user.name, end=" " if active or uuid else "\n") if uuid: print(found_user.uuid, end=" " if active else "\n") if active: print(found_user.active) finish(ctx)
def dependencies(ctx): """Install Isomer platform dependencies""" log("Installing platform dependencies") install_isomer( ctx.obj["platform"], ctx.obj["use_sudo"], show=ctx.obj["log_actions"], omit_platform=ctx.obj['platform'], omit_common=True, ) finish(ctx)
def frontend(ctx, dev, rebuild, no_install, build_type): """Build and install frontend""" # TODO: Move this to the environment handling and deprecate it here installed = install_frontend( force_rebuild=rebuild, development=dev, install=not no_install, build_type=build_type, ) if installed is True: finish(ctx) else: abort(EXIT_FRONTEND_BUILD_FAILED, ctx)
def delete(ctx, component): """Delete an existing component configuration. This will trigger the creation of its default configuration upon next restart.""" col = ctx.obj["col"] log("Deleting component configuration", component, emitter="MANAGE") configuration = get_configuration(col, component) if configuration is None: log("No component with that name or uuid found.") return configuration.delete() finish(ctx)
def create(ctx, instance_name): """Create a new instance""" if instance_name == "": instance_name = ctx.obj["instance"] if instance_name in ctx.obj["instances"]: abort(EXIT_INSTANCE_EXISTS) log("Creating instance:", instance_name) instance_configuration = instance_template instance_configuration["name"] = instance_name ctx.obj["instances"][instance_name] = instance_configuration write_instance(instance_configuration) finish(ctx)
def change_password(ctx): """Change password of an existing user""" username, passhash = _get_credentials(ctx.obj["username"], ctx.obj["password"], ctx.obj["db"]) change_user = ctx.obj["db"].objectmodels["user"].find_one( {"name": username}) if change_user is None: log("No such user", lvl=warn) return change_user.passhash = passhash change_user.save() finish(ctx)
def delete_user(ctx, yes): """Delete a local user""" if ctx.obj["username"] is None: username = ask("Please enter username:"******"username"] del_user = ctx.obj["db"].objectmodels["user"].find_one({"name": username}) if yes or ask("Confirm deletion", default=False, data_type="bool"): try: del_user.delete() finish(ctx) except AttributeError: log("User not found", lvl=warn) else: log("Cancelled")
def add_role(ctx, role): """Grant a role to an existing user""" if role is None: log("Specify the role with --role") return if ctx.obj["username"] is None: log("Specify the username with --username") return change_user = (ctx.obj["db"].objectmodels["user"].find_one( {"name": ctx.obj["username"]})) if role not in change_user.roles: change_user.roles.append(role) change_user.save() finish(ctx) else: log("User already has that role!", lvl=warn)