From f38729bd8d448faa578ccd5ab24b024c994522e0 Mon Sep 17 00:00:00 2001
From: Viacheslav Hletenko <v.gletenko@vyos.io>
Date: Thu, 28 Jul 2022 12:37:15 +0000
Subject: nat: T4543: Fix and rewrite show nat source statistics

Rewrite "show nat source statistics"
Use new format 'vyos.opmode module'
Ability to get raw and formatted output
---
 src/op_mode/nat.py | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)

(limited to 'src/op_mode')

diff --git a/src/op_mode/nat.py b/src/op_mode/nat.py
index 666c72c7c..4b54ecf31 100755
--- a/src/op_mode/nat.py
+++ b/src/op_mode/nat.py
@@ -147,6 +147,24 @@ port {port}'''
     return output
 
 
+def _get_formatted_output_statistics(data, direction):
+    data_entries = []
+    for rule in data:
+        if 'comment' in rule['rule']:
+            comment = rule.get('rule').get('comment')
+            rule_number = comment.split('-')[-1]
+            rule_number = rule_number.split(' ')[0]
+        if 'expr' in rule['rule']:
+            interface = rule.get('rule').get('expr')[0].get('match').get('right') \
+                if jmespath.search('rule.expr[*].match.left.meta', rule) else 'any'
+            packets = jmespath.search('rule.expr[*].counter.packets | [0]', rule)
+            _bytes = jmespath.search('rule.expr[*].counter.bytes | [0]', rule)
+        data_entries.append([rule_number, packets, _bytes, interface])
+    headers = ["Rule", "Packets", "Bytes", "Interface"]
+    output = tabulate(data_entries, headers, numalign="left")
+    return output
+
+
 def show_rules(raw: bool, direction: str):
     nat_rules = _get_raw_data_rules(direction)
     if raw:
@@ -155,6 +173,14 @@ def show_rules(raw: bool, direction: str):
         return _get_formatted_output_rules(nat_rules, direction)
 
 
+def show_statistics(raw: bool, direction: str):
+    nat_statistics = _get_raw_data_rules(direction)
+    if raw:
+        return nat_statistics
+    else:
+        return _get_formatted_output_statistics(nat_statistics, direction)
+
+
 if __name__ == '__main__':
     try:
         res = vyos.opmode.run(sys.modules[__name__])
-- 
cgit v1.2.3