From a5c4fd62091ceaf5b0a33c573e5c7d3cdcca2f07 Mon Sep 17 00:00:00 2001
From: Diego Giovane Pasqualin <dpasqualin@c3sl.ufpr.br>
Date: Wed, 13 Aug 2014 20:41:25 -0300
Subject: [PATCH] datasid-netmon.sh: Make sure no duplicate lines are added to
 net usage file

In the unlikely event where this script is called twice less than
five minutes apart, there would be two lines about the same time interval,
which would produce an incorrect xml. We fix this by replacing all
duplicated lines by a single one which is the sum of them.

Signed-off-by: Diego Giovane Pasqualin <dpasqualin@c3sl.ufpr.br>
---
 agent/bin/datasid-netmon.sh | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/agent/bin/datasid-netmon.sh b/agent/bin/datasid-netmon.sh
index 4e0f356..d528120 100755
--- a/agent/bin/datasid-netmon.sh
+++ b/agent/bin/datasid-netmon.sh
@@ -123,8 +123,23 @@ OUTPUT_COUNT=$(sudo $IPTABLES -nvxL OUTPUT | grep DS_OUTPUT_COUNTS | \
                     {pkts+=$1; bytes+=$2} \
                     END{print pkts,bytes}')
 
+# Add new entry to traffic file
 echo "$INTERVALID $INPUT_COUNT $OUTPUT_COUNT" >> $TRAFFIC
 
+# If this script is run more than once in less than a five minutes interval we
+# might end up with duplicated lines, which could mess with the XML file
+# later, so better make sure this doesn't happen.
+if [ $(grep -cw "^$INTERVALID" $TRAFFIC) -gt 1 ]; then
+    # If we are unfortunate enough to have duplicated lines we sum up them with
+    # the new network data aquired.
+    IN_OUT=$(awk -v inp=$INTERVALID 'BEGIN{rxpkts=0; rxbytes=0; txpkts=0; txbytes=0} $1==inp \
+                                    {rxpkts+=$2; rxbytes+=$3; txpkts+=$4; txbytes+=$5} \
+                                    END{print rxpkts,rxbytes,txpkts,txbytes}' $TRAFFIC)
+
+    # Remove all lines and add only the sum of them.
+    sed -i "/^$INTERVALID/d" $TRAFFIC
+    echo "$INTERVALID $IN_OUT" >> $TRAFFIC
+fi
 
 #------------------------------------------------------------------------------
 # Create or update iptables rules (used for counting) based on the interfaces
-- 
GitLab