X-Git-Url: http://git.onelab.eu/?a=blobdiff_plain;f=sfatables%2Fcommands%2FAdd.py;h=da02e869258646c75e1cdd2fac8ca19a15dffe47;hb=b940fd55d99f2929cd0d6b47dd6d75db714c90cd;hp=79bb2d9761d2f73b4150926607a1c3bdbd0d7204;hpb=f5194b0cf1858313770d6796411fec30190b5522;p=sfa.git diff --git a/sfatables/commands/Add.py b/sfatables/commands/Add.py index 79bb2d97..da02e869 100644 --- a/sfatables/commands/Add.py +++ b/sfatables/commands/Add.py @@ -1,19 +1,71 @@ import os, time -from sfa.sfatables.command import Add +import libxml2 +from sfatables.command import Command +from sfatables.globals import * class Add(Command): options = [('-A','--add')] help = 'Add a rule to a chain' - key='add_rule' - matches = False - targets = False + matches = True + targets = True def __init__(self): return - def call(self): - # Override this function + def getnextfilename(self,type,chain): + dir = sfatables_config + "/"+chain; + last_rule_number = 0 + + for (root, dirs, files) in os.walk(dir): + for file in files: + if (file.startswith('sfatables-') and file.endswith(type)): + number_str = file.split('-')[1] + number = int(number_str) + if (number>last_rule_number): + last_rule_number = number + + return "sfatables-%d-%s"%(last_rule_number+1,type) + + def call_gen(self, chain, type, dir, options): + filename = os.path.join(dir, options.name+".xml") + xmldoc = libxml2.parseFile(filename) + + p = xmldoc.xpathNewContext() + + supplied_arguments = options.arguments + if (hasattr(options,'element') and options.element): + element = options.element + else: + element='*' + + for option in supplied_arguments: + option_name = option['name'] + option_value = getattr(options,option_name) + + if (hasattr(options,option_name)): + context = p.xpathEval("//rule[@element='%s' or @element='*']/argument[name='%s']"%(element, option_name)) + if (not context): + raise Exception('Unknown option %s for match %s and element %s'%(option,option['name'], element)) + else: + # Add the value of option + valueNode = libxml2.newNode('value') + valueNode.addContent(option_value) + context[0].addChild(valueNode) + + filename = self.getnextfilename(type,chain) + file_path = os.path.join(sfatables_config, chain, filename) + if not os.path.isdir(os.path.dirname(file_path)): + os.makedirs(os.path.dirname(file_path)) + xmldoc.saveFile(file_path) + p.xpathFreeContext() + xmldoc.freeDoc() + return True - def __call__(self, option, opt_str, value, parser, *args, **kwargs): - return self.call(option) + def call(self, command_options, match_options, target_options): + chain = command_options.args[0] + ret = self.call_gen(chain, 'match',match_dir, match_options) + if (ret): + ret = self.call_gen(chain, 'target',target_dir, target_options) + + return ret