source: fedd/fixed_resource.py @ 7ca25b3

axis_examplecompt_changesinfo-opsversion-1.30version-2.00version-3.01version-3.02
Last change on this file since 7ca25b3 was 266e866, checked in by Ted Faber <faber@…>, 16 years ago

Add user databas manipulation commands. Collapse some code

  • Property mode set to 100755
File size: 3.8 KB
Line 
1#!/usr/local/bin/python
2
3import sys
4import MySQLdb
5from federation.fixed_resource import read_key_db, write_key_db, \
6        read_project_db, write_project_db, read_user_db, write_user_db
7from optparse import OptionParser
8
9actions = set(("initall", "init", "add", "delete"))
10
11def read_key_file(file):
12    """
13    Read a single line from a keyfile and trim the whitespace
14    """
15    f = open(file, 'r')
16    key = f.readline().rstrip()
17    f.close()
18    return key
19
20class key_opts(OptionParser):
21    """
22    Options to the command line, pretty self describing
23    """
24    def __init__(self):
25        OptionParser.__init__(self, usage="%prog " + \
26                "(init|add|delete|initall) " + \
27                "[opts] (--help for details)", version="0.1")
28        self.add_option('-t','--type', dest='type', type='choice', 
29                choices=['keys','projects', 'users'], help="database type")
30        self.add_option('-u','--user', dest='user', default=None,
31                action='store', help='user to add/delete')
32        self.add_option('-p','--project', dest='project', default=None,
33                action='store', help='project to add/delete')
34        self.add_option('-k','--key', dest='key', default=None,
35                action='store', help='key to add/delete (string)')
36        self.add_option('-K','--keyfile', dest='keyfile', default=None,
37                action='store', help='key to add/delete (file)')
38        self.add_option('-d', '--database', dest='file', default=None,
39                action='store', help='database file')
40        self.add_option('-f', '--file', dest='file', action='store',
41                help='database file (synonym for --database)')
42
43def process_db(action, file, key, read_db, write_db, query):
44    """
45    The logic of insertion/deletion/initialization is the same regardless of
46    the DB.  This function encapsulates that control flow.
47    """
48
49    if action != 'init' and action != 'initall':
50        keys = read_db(file)
51    else:
52        keys = set()
53
54    # init action falls through to write an empty DB
55    if action == 'initall':
56        # Add all keys returned by the query from the Emulab DB
57        try:
58            db = MySQLdb.connect(db="tbdb")
59        except:
60            sys.exit("Cannot access the Emulab database")
61
62        c = db.cursor()
63        c.execute(query)
64        for k in c.fetchall():
65            keys.add(k)
66        c.close()
67        db.close()
68    elif action == 'add':
69        keys.add(key)
70    elif action == 'delete': 
71        if key in keys:
72            keys.remove(key)
73        else:
74            print >>sys.stderr, "Cannot delete %s: not in db" % (key,)
75
76    write_db(file, keys)
77
78
79parser = key_opts()
80action = sys.argv[1]
81init_actions = set(['init', 'initall'])
82
83# Check the action
84if action in actions: del sys.argv[1]
85else: sys.exit("Bad action, must be one of %s" % ", ".join(actions))
86
87(opts, args) = parser.parse_args()
88if not opts.file:
89    sys.exit("Must specify DB file")
90if not opts.type:
91    sys.exit("Must specify database type (--type)")
92elif opts.type == 'keys':
93    if action not in init_actions:
94        if opts.user and (opts.key or opts.keyfile):
95            user = opts.user
96            if opts.key:
97                key = opts.key
98            elif opts.keyfile: 
99                try:
100                    key = read_key_file(opts.keyfile)
101                except IOError, e:
102                    sys.exit("Error reading keyfile: %s" % e)
103        else:
104            sys.exit("Must specify user and key")
105    else: 
106        key = None
107        user = None
108    process_db(action, opts.file, (user, key), read_key_db, write_key_db,
109            "SELECT uid, pubkey FROM user_pubkeys")
110
111elif opts.type == 'projects':
112    if action not in init_actions:
113        if opts.project: project = opts.project
114        else: sys.exit("Must specify project")
115    else: project = None
116    process_db(action, opts.file, project, read_project_db, write_project_db, 
117            "SELECT pid FROM projects")
118elif opts.type == 'users':
119    if action not in init_actions:
120        if opts.user: user = opts.user
121        else: sys.exit("Must specify user")
122    else: user = None
123    process_db(action, opts.file, user, read_user_db, write_user_db, 
124            "SELECT uid FROM users")
125else:
126    sys.exit("Invalid --type field (how'd you do that?)")
127
128sys.exit(0)
Note: See TracBrowser for help on using the repository browser.