'Apply the current in-memory set of iptables rules.
This will create a diff between the rules from the previous runs
and replace them with the current set of rules.
This happens atomically, thanks to iptables-restore.
Returns a list of the changes that were sent to iptables-save.'

def _apply_synchronized(self):

    s = [('iptables', self.ipv4)]
    if self.use_ipv6:
        s += [('ip6tables', self.ipv6)]
    all_commands = []
    for (cmd, tables) in s:
        args = [('%s-save' % (cmd,))]
        if self.namespace:
            args = (['ip', 'netns', 'exec', self.namespace] + args)
        try:
            save_output = self.execute(args, run_as_root=True)
        except RuntimeError:
            with excutils.save_and_reraise_exception() as ctx:
                if (self.namespace and (not ip_lib.IPWrapper().netns.exists(self.namespace))):
                    ctx.reraise = False
                    LOG.error('Namespace    %s    was    deleted    during    IPTables    operations.', self.namespace)
                    return []
        all_lines = save_output.split('\n')
        commands = []
        for table_name in sorted(tables):
            table = tables[table_name]
            (start, end) = self._find_table(all_lines, table_name)
            old_rules = all_lines[start:end]
            new_rules = self._modify_rules(old_rules, table, table_name)
            changes = _generate_path_between_rules(old_rules, new_rules)
            if changes:
                commands += (((['#    Generated    by    iptables_manager'] + [('*%s' % table_name)]) + changes) + ['COMMIT', '#    Completed    by    iptables_manager'])
        if (not commands):
            continue
        all_commands += commands
        args = [('%s-restore' % (cmd,)), '-n']
        if self.namespace:
            args = (['ip', 'netns', 'exec', self.namespace] + args)
        try:
            commands.append('')
            self.execute(args, process_input='\n'.join(commands), run_as_root=True)
        except RuntimeError as r_error:
            with excutils.save_and_reraise_exception():
                try:
                    line_no = int(re.search('iptables-restore:    line    ([0-9]+?)    failed', str(r_error)).group(1))
                    context = IPTABLES_ERROR_LINES_OF_CONTEXT
                    log_start = max(0, (line_no - context))
                    log_end = (line_no + context)
                except AttributeError:
                    log_start = 0
                    log_end = len(commands)
                log_lines = (('%7d.    %s' % (idx, l)) for (idx, l) in enumerate(commands[log_start:log_end], (log_start + 1)))
                LOG.error(_LE('IPTablesManager.apply    failed    to    apply    the    following    set    of    iptables    rules:\n%s'), '\n'.join(log_lines))
    LOG.debug('IPTablesManager.apply    completed    with    success.    %d    iptables    commands    were    issued', len(all_commands))
    return all_commands
