fix config pointer
[plcapi.git] / plcsh
1 #!/usr/bin/python
2 #
3 # Interactive shell for testing PLCAPI
4 #
5 # Mark Huang <mlhuang@cs.princeton.edu>
6 # Copyright (C) 2005 The Trustees of Princeton University
7 #
8 # $Id: plcsh,v 1.2 2007/01/11 05:28:49 mlhuang Exp $
9 #
10
11 import os
12 import sys
13 from optparse import OptionParser
14 from traceback import print_exc
15
16 sys.path.append(os.path.dirname(os.path.realpath(sys.argv[0])))
17 from PLC.Shell import Shell
18
19 parser = OptionParser(add_help_option = False)
20 parser.add_option("-f", "--config", help = "PLC configuration file")
21 parser.add_option("-h", "--url", help = "API URL")
22 parser.add_option("-c", "--cacert", help = "API SSL certificate")
23 parser.add_option("-m", "--method", help = "API authentication method")
24 parser.add_option("-u", "--user", help = "API user name")
25 parser.add_option("-p", "--password", help = "API password")
26 parser.add_option("-r", "--role", help = "API role")
27 parser.add_option("-x", "--xmlrpc", action = "store_true", default = False, help = "Use XML-RPC interface")
28 parser.add_option("--help", action = "help", help = "show this help message and exit")
29 (options, args) = parser.parse_args()
30
31 # If user is specified but password is not
32 if options.user is not None and options.password is None:
33     try:
34         options.password = getpass.getpass()
35     except (EOFError, KeyboardInterrupt):
36         print
37         sys.exit(0)
38
39 # Initialize a single global instance (scripts may re-initialize
40 # this instance and/or create additional instances).
41 try:
42     shell = Shell(globals = globals(),
43                   config = options.config,
44                   url = options.url, xmlrpc = options.xmlrpc, cacert = options.cacert,
45                   method = options.method, role = options.role,
46                   user = options.user, password = options.password)
47     # Register a few more globals for backward compatibility
48     auth = shell.auth
49     api = shell.api
50     config = shell.config
51 except Exception, err:
52     print "Error:", err
53     print
54     parser.print_help()
55     sys.exit(1)
56
57 # If called by a script
58 if len(sys.argv) > 1 and os.path.exists(sys.argv[1]):
59     # Pop us off the argument stack
60     sys.argv.pop(0)
61     execfile(sys.argv[0])
62
63 # Otherwise, run an interactive shell environment
64 else:
65     if shell.server is None:
66         print "PlanetLab Central Direct API Access"
67         prompt = ""
68     elif shell.auth['AuthMethod'] == "anonymous":
69         prompt = "[anonymous]"
70         print "Connected anonymously"
71     else:
72         prompt = "[%s]" % shell.auth['Username']
73         print "%s connected using %s authentication" % \
74               (shell.auth['Username'], shell.auth['AuthMethod'])
75
76     # Readline and tab completion support
77     import atexit
78     import readline
79     import rlcompleter
80
81     print 'Type "system.listMethods()" or "help(method)" for more information.'
82     # Load command history
83     history_path = os.path.join(os.environ["HOME"], ".plcapi_history")
84     try:
85         file(history_path, 'a').close()
86         readline.read_history_file(history_path)
87         atexit.register(readline.write_history_file, history_path)
88     except IOError:
89         pass
90
91     # Enable tab completion
92     readline.parse_and_bind("tab: complete")
93
94     try:
95         while True:
96             command = ""
97             while True:
98                 # Get line
99                 try:
100                     if command == "":
101                         sep = ">>> "
102                     else:
103                         sep = "... "
104                     line = raw_input(prompt + sep)
105                 # Ctrl-C
106                 except KeyboardInterrupt:
107                     command = ""
108                     print
109                     break
110
111                 # Build up multi-line command
112                 command += line
113
114                 # Blank line or first line does not end in :
115                 if line == "" or (command == line and line[-1] != ':'):
116                     break
117
118                 command += os.linesep
119
120             # Blank line
121             if command == "":
122                 continue
123             # Quit
124             elif command in ["q", "quit", "exit"]:
125                 break
126
127             try:
128                 try:
129                     # Try evaluating as an expression and printing the result
130                     result = eval(command)
131                     if result is not None:
132                         print result
133                 except SyntaxError:
134                     # Fall back to executing as a statement
135                     exec command
136             except Exception, err:
137                 print_exc()
138
139     except EOFError:
140         print
141         pass