Debian Codegraph @

src/deprecated/fix-pathhash

raw
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 #
4 # =================================================================
5 # # # # #
6 # ## # #### ##### ## # ###### #####
7 # # # # # # # # # # # # #
8 # # # # # # # # # # # ##### #
9 # # # # # # ##### # # # # #
10 # # ## # # # # # ## # #
11 # # # #### # # # # ###### #
12 #
13 # --- The NorNet Testbed for Multi-Homed Systems ---
14 # https://www.nntb.no
15 # =================================================================
16 #
17 # High-Performance Connectivity Tracer (HiPerConTracer)
18 # Copyright (C) 2015-2026 by Thomas Dreibholz
19 #
20 # This program is free software: you can redistribute it and/or modify
21 # it under the terms of the GNU General Public License as published by
22 # the Free Software Foundation, either version 3 of the License, or
23 # (at your option) any later version.
24 #
25 # This program is distributed in the hope that it will be useful,
26 # but WITHOUT ANY WARRANTY; without even the implied warranty of
27 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 # GNU General Public License for more details.
29 #
30 # You should have received a copy of the GNU General Public License
31 # along with this program. If not, see <http://www.gnu.org/licenses/>.
32 #
33 # Contact: [email protected]
34
35 import os
36 import sys
37 import io
38 import datetime
39 import bz2
40 import shutil
41 import psycopg2
42 import configparser
43 import hashlib
44
45
46 # ###### Print log message ##################################################
47 def log(logstring):
48 print('\x1b[32m' + datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S') + ': ' + logstring + '\x1b[0m');
49
50
51 # ###### Abort with error ###################################################
52 def error(logstring):
53 sys.stderr.write(datetime.datetime.now().isoformat() + \
54 ' ===== ERROR: ' + logstring + ' =====\n')
55 sys.exit(1)
56
57
58
59 # ###### Main program #######################################################
60 if len(sys.argv) < 3:
61 error('Usage: ' + sys.argv[0] + ' database_configuration days_in_past')
62
63 configFileName = sys.argv[1]
64 daysInPast = int(sys.argv[2])
65 badFilePath = None
66 dbServer = 'localhost'
67 dbPort = 5432
68 dbUser = 'importer'
69 dbPassword = None
70 dbName = 'pingtraceroutedb'
71
72
73 # ====== Get parameters =====================================================
74 parsedConfigFile = configparser.RawConfigParser()
75 parsedConfigFile.optionxform = str # Make it case-sensitive!
76 try:
77 parsedConfigFile.readfp(io.StringIO('[root]\n' + open(configFileName, 'r').read()))
78 except Exception as e:
79 error('Unable to read database configuration file' + sys.argv[1] + ': ' + str(e))
80 sys.exit(1)
81
82 for parameterName in parsedConfigFile.options('root'):
83 parameterValue = parsedConfigFile.get('root', parameterName)
84 if parameterName == 'transactions_path':
85 continue
86 elif parameterName == 'bad_file_path':
87 badFilePath = parameterValue
88 elif parameterName == 'dbserver':
89 dbServer = parameterValue
90 elif parameterName == 'dbport':
91 dbPort = parameterValue
92 elif parameterName == 'dbuser':
93 dbUser = parameterValue
94 elif parameterName == 'dbpassword':
95 dbPassword = parameterValue
96 elif parameterName == 'database':
97 dbName = parameterValue
98 else:
99 error('Unknown parameter ' + parameterName + ' in ' + sys.argv[1] + '!')
100
101
102 # ====== Connect to the database ============================================
103 try:
104 dbConnection = psycopg2.connect(host=str(dbServer), port=str(dbPort),
105 user=str(dbUser), password=str(dbPassword),
106 dbname=str(dbName))
107 dbConnection.autocommit = False
108 except:
109 log('Unable to connect to the database!')
110 sys.exit(1)
111
112 dbCursor = dbConnection.cursor()
113
114
115 # ====== Run ================================================================
116 dbCursor.execute("""
117 select t.TimeStamp, t.FromIP, t.ToIP, t.HopNumber, t.HopIP, t.PathHash, t.Status, t.RTT
118 from Traceroute t
119 where
120 t.TimeStamp >= (select max(TimeStamp) from Traceroute) - interval '""" + str(daysInPast + 1) + """ days' and
121 t.TimeStamp <= (select max(TimeStamp) from Traceroute) - interval '""" + str(daysInPast) + """ days'
122 order by t.TimeStamp asc, t.fromIP, t.toIP, t.HopNumber, t.HopIP;
123 """)
124
125 rows = dbCursor.fetchall()
126
127
128 oldPathHash = 0
129 pathString = ""
130 pathHasStar = False
131
132 for row in rows:
133 timeStamp = row[0]
134 fromIP = row[1]
135 toIP = row[2]
136 hopNumber = row[3]
137 hopIP = row[4]
138 pathHash = row[5]
139 status = row[6]
140 rtt = row[7]
141
142 # ====== One path is finished ============================================
143 if hopNumber == 1:
144 # ------ Finished a path ----------------------------
145 if pathString != "":
146 m = hashlib.sha1()
147 m.update(pathString.encode('ascii'))
148 digest = m.hexdigest()[0:16]
149
150 m = hashlib.sha1()
151 m.update(pathString.encode('ascii'))
152 digest = m.hexdigest()[0:16]
153
154 a = int(digest[0:8], 16)
155 b = int(digest[8:16], 16)
156 newPathHash = (a << 32) | b
157 if newPathHash > 0x7FFFFFFFFFFFFFFF:
158 newPathHash -= 0x10000000000000000
159
160 #print(pathString)
161 #print(newPathHash, format(a, 'x'), format(b, 'x'), newPathHash, "OLD:", oldPathHash)
162
163 if (oldPathHash != 0) and (oldPathHash != newPathHash):
164 sys.stderr.write('ERROR: Hash values differ!\n')
165 sys.exit(1)
166
167 if ((newStatusFlags != oldStatusFlags) or
168 (newPathHash != oldPathHash)):
169 #print(oldPathHash, newPathHash, oldStatusFlags, newStatusFlags)
170 sql = """UPDATE Traceroute SET PathHash = """ + str(newPathHash) + """, Status = (Status & 255) | """ + str(newStatusFlags) + """ WHERE TimeStamp='""" + str(oldTimeStamp) + """' AND FromIP='""" + oldFromIP + """' AND ToIP='""" + oldToIP + """';"""
171 print(sql)
172
173
174 # ------ Start next path ----------------------------
175 #print("-----")
176 oldTimeStamp = timeStamp
177 oldFromIP = fromIP
178 oldToIP = toIP
179 oldPathHash = pathHash
180 oldStatusFlags = status & ~0xff
181 pathString = fromIP
182 newStatusFlags = 0x0000
183
184 # ====== Set status ======================================================
185 if (((status & 0xff) >= 200) and ((status & 0xff) <= 254)):
186 pathString = pathString + '-*'
187 newStatusFlags = newStatusFlags | 0x0100 # Route with * (router did not respond)
188 else:
189 if (status & 0xff) == 0xff:
190 newStatusFlags = newStatusFlags | 0x0200 # Destination has responded
191 pathString = pathString + '-' + hopIP
192
193
194 #print(timeStamp,fromIP,toIP,hopNumber,hopIP,pathHash,status & 0xff,rtt)