#!/usr/bin/python # Adminstrate kforge environments from the command line """ TODO: * support for verbosity * make non-interactive the default and have a -i option for interactive """ import sys import os import cmd import optparse # All kforge modules must be imported in __init__ as we need to set pythonpath class KforgeAdmin(cmd.Cmd): prompt = 'kforge $ ' def __init__(self, envPath=None, systemPath=None): """Initialise command. """ cmd.Cmd.__init__(self) # cmd.Cmd is not a new style class self.interactive = 0 self.envPath = None self.systemPath = systemPath if envPath is not None: self.set_environment(envPath) def set_environment(self, envPath): self.envPath = os.path.abspath(envPath) os.environ['KFORGEHOME'] = self.envPath # system dictionary needs this self.prompt = 'Kforge [%s]$ ' % self.envPath def run_interactive(self): """Run an interactive session. """ print 'Welcome to the kforge-admin interactive mode\n' print 'Type: "?" or "help" for help on commands.\n' self.do_about() while 1: try: self.cmdloop() break except KeyboardInterrupt: raise # print '\n** Interrupt. Use "quit" to exit **' # ========================= # START OF Commands section def do_data(self, line=None): args = self._lineToArgs(line) if len(args) != 1: print 'ERROR: Insufficient arguments\n' self.help_data(line) return 1 elif args[0] == 'create': from kforge.utils.admin import InitialiseEnvCmd cmd = InitialiseEnvCmd(self.envPath, self.systemPath) cmd.execute() return 0 else: self.help_data() return 1 def help_data(self, line=None): usage = \ '''data action = create Create environment data ''' print usage def do_backup(self, line): args = self._lineToArgs(line) import kforge.application app = kforge.application.Application() if len(args) != 1: print 'ERROR: Insufficient arguments\n' self.help_backup(line) return 1 else: cmd = app.commands['Backup'](args[0]) cmd.execute() return 0 def help_backup(self, line=None): usage = 'backup dest\n' usage += '\tdest is the path to which you wish to backup' print usage def do_db(self, line=None): """Run db commands """ args = self._lineToArgs(line) if len(args) != 1: print 'ERROR: Insufficient arguments\n' self.help_db(line) return 1 # let's do this reflectively from kforge.utils.db import Database db = Database() try: Database.__dict__[args[0]](db) except Exception, inst: print 'Command failed. Details: %s' % inst return 1 def help_db(self): usage = \ '''db action = create | delete | init | rebuild NB: a known issue is that due to a persisted db connection once you have run init or rebuild you cannot run any of the other commands again in the same session''' # [[TODO: display docstrings for each function from db class here # Database.__dict__[cmd].__doc__ print usage def do_upgrade(self, line=None): # TODO use KForge version to specify upgrade script used args = self._lineToArgs(line) import kforge.utils.upgrade if len(args) != 1: self.help_upgrade(line) return 1 elif args[0] == 'data': cmd = kforge.utils.upgrade.UpgradeDataTo0Point11( self.envPath, self.systemPath) cmd.execute() return 0 elif args[0] == 'db': cmd = kforge.utils.upgrade.UpgradeDbTo0Point11() cmd.execute() return 0 else: print 'Unknown arguments: %s' % args self.help_upgrade() def help_upgrade(self, line=None): usage = \ '''upgrade object = data | db Upgrade a KForge environment (data and db)''' print usage def do_www(self, line=None): args = self._lineToArgs(line) if len(args) == 0: self.help_www(line) return 1 import kforge kforge.getA() # have to do this to set up features (dictionary etc) from kforge.apache.apacheconfig import ApacheConfigBuilder configBuilder = ApacheConfigBuilder() if args[0] == 'build': configBuilder.buildConfig() elif args[0] == 'reload': configBuilder.reloadConfig() else: self.help_www(line) return 1 def help_www(self, line=None): help = 'www [ build | reload ]\n' help += '\tbuild: build web server configuration\n' help += '\treload: reload web server configuration\n' print help def do_shell(self, line=None): import code code.interact() def help_shell(self, line=None): help = \ '''shell (or !): run a python shell Used to administer domain objects. Read docs/cli_shell.txt for a full guide to use of the shell for administration of the domain model. Preferred to direct invocation of a python shell as this ensures all relevant environment variables are correctly set. ''' print help def do_about(self, args=None): import kforge version = kforge.__version__ about = \ '''KForge version %s Copyright the Open Knowledge Foundation. KForge is open-source software licensed under the GPL v2.0. See COPYING for details. ''' % version print about def do_help(self, line=None): cmd.Cmd.do_help(self, line) def do_quit(self, line=None): sys.exit() def do_EOF(self, *args): print '' sys.exit() def _lineToArgs(self, line): args = line.strip().split() args = [ x.strip() for x in args] return args def main(): usage = \ '''usage: %prog [options] [cmd] Administer a KForge environment/instance and its associated domain objects. Can be run in two modes: 1. single command: run the command provided and exit (Default) 2. interactive To obtain information about the commands available run the "help" command. Domain objects (e.g. persons, projects, etc) are administered by starting a python shell from within interactive mode. Run "help shell" for more details. ''' parser = optparse.OptionParser(usage) parser.add_option('-i', '--interactive', action='store_true', dest='interactive', default=False, help='Run in interactive mode. If this option is specified any commands at invocation will be ignored.' ) parser.add_option('--version', action='store_true', dest='version', default=False, help='Display version information' ) parser.add_option('--system', action='store', dest='system_path', default=None, help='If you have installed the KForge system to a path other\n' + \ 'than the default (sys.prefix) you need to specify the path here.' ) parser.add_option('--env', action='store', dest='env_path', default='', help='Path to environment you wish to administer. ' + \ 'If not provided use shell environment variable KFORGEHOME' ) (options, args) = parser.parse_args() # concatenate all arguments back together for cmd.Cmd line = '' if len(args) > 0: line = ' '.join(['%s' % s for s in args]) # special cases kforgeAdmin = KforgeAdmin() if len(args) > 0 and args[0] in [ 'help' ]: return kforgeAdmin.onecmd(line) elif options.version: return kforgeAdmin.onecmd('about') # going to administer an environment envPath = options.env_path if not envPath: if os.environ.has_key('KFORGEHOME'): envPath = os.environ['KFORGEHOME'] else: print 'ERROR. Please provide a path to the KForge environment you wish to administer\n\n' parser.print_help() sys.exit(1) kforgeAdmin = KforgeAdmin(envPath, options.system_path) if options.interactive: return kforgeAdmin.run_interactive() elif len(args) > 0: status = kforgeAdmin.onecmd(line) sys.exit(status) else: parser.print_help() if __name__ == '__main__': # unittest.main() main()