Some initial plumbing for sfatables
[sfa.git] / sfatables / sfatables.py
1 #!/usr/bin/python 
2 # SFAtables is a tool for restricting access to an SFA aggregate in a generic
3 # and extensible way. 
4
5 # It is modeled using abstractions in iptables. Specifically, 'matches' specify
6 # criteria for matching certain requests, 'targets' specify actions that treat
7 # requests in a certain way, and 'chains' are used to group related
8 # match-action pairs.
9
10 import sys
11 import os
12 import pdb
13 from optparse import OptionParser
14
15 def load_extensions(module):
16     command_dict={}
17     commands = __import__(module,fromlist=[".".join(module.split('.')[:-1])])
18
19     for command_name in commands.all:
20         command_module = getattr(commands, command_name)
21         command = getattr(command_module, command_name)
22         command_dict[command.key]=command()
23
24     return command_dict
25
26 def create_parser(command_dict):
27     parser = OptionParser(usage="sfatables [command] [chain] [match] [target]",
28                              description='See "man sfatables" for more detail.')
29     
30     for k in command_dict.keys():
31         command = command_dict[k]
32         for (short_option,long_option) in command.options:
33             parser.add_option(short_option,long_option,dest=command.key,help=command.help,metavar=command.help.upper())
34
35     return parser
36
37
38 def main():
39     command_dict = load_extensions("sfa.sfatables.commands")
40     command_parser = create_parser(command_dict)
41     (options, args) = command_parser.parse_args()
42
43     if (len(options.keys() != 1):
44         raise Exception("sfatables takes one command at a time.\n")
45
46     selected_command = command_dict[options.keys()[0]]
47
48     match_options = None
49     target_options = None
50
51     if (selected_command.matches):
52         match_dict = load_extensions("sfa.sfatables.matches")
53         match_parser = create_parser(match_dict)
54         (options, args) = match_parser.parse_args(args[2:]) # Change to next location of --
55
56     if (selected_command.targets):
57         match_dict = load_extensions("sfa.sfatables.targets")
58         target_parser = create_parser(match_dict)
59         (options, args) = target_parser.parse_args(args[5:]) # Change to next location of --
60
61     command(options, match_options, target_options)
62
63 if __name__=='__main__':
64     main()