Improve performance of _modify_rules

The _modify_rules method currently uses nested loop to removes rules
that belong to us but don't have the wrap name. Speed up this operation
by storing our rules as set.
Reduce operation complexity from O(n*m) to O(n).

Change-Id: I82e6184a30ddb25f2258e21fe749573af44a52ca
Related-Bug: #1502297
This commit is contained in:
Quan Tian 2016-11-21 18:37:38 +08:00
parent 2612331a05
commit e83d07d00a
1 changed files with 7 additions and 7 deletions

View File

@ -567,11 +567,17 @@ class IptablesManager(object):
# Sort the output chains here to make their order predictable.
unwrapped_chains = sorted(table.unwrapped_chains)
chains = sorted(table.chains)
rules = set(map(str, table.rules))
# we don't want to change any rules that don't belong to us so we start
# the new_filter with these rules
# there are some rules that belong to us but they don't have the wrap
# name. we want to add them in the right location in case our new rules
# changed the order
# (e.g. '-A FORWARD -j neutron-filter-top')
new_filter = [line.strip() for line in current_lines
if self.wrap_name not in line]
if self.wrap_name not in line and
line.strip() not in rules]
# generate our list of chain names
our_chains = [':%s-%s' % (self.wrap_name, name) for name in chains]
@ -586,12 +592,6 @@ class IptablesManager(object):
our_bottom_rules = []
for rule in table.rules:
rule_str = str(rule)
# similar to the unwrapped chains, there are some rules that belong
# to us but they don't have the wrap name. we want to remove them
# from the new_filter and then add them in the right location in
# case our new rules changed the order.
# (e.g. '-A FORWARD -j neutron-filter-top')
new_filter = [s for s in new_filter if rule_str not in s]
if rule.top:
# rule.top == True means we want this rule to be at the top.