fe0e45b9667a8672f91b2e8fce686e15247c99e0
[nepi.git] / src / nepi / data / processing / ccn / parser.py
1 #!/usr/bin/env python
2
3 ###############################################################################
4 #
5 #    CCNX benchmark
6 #    Copyright (C) 2014 INRIA
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License version 2 as
10 #    published by the Free Software Foundation;
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU General Public License for more details.
16 #
17 #    You should have received a copy of the GNU General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 #
21 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
22 #
23 ###############################################################################
24
25 #
26 # This library contains functions to parse (CCNx) ccnd logs.
27 #
28 # Results from experiments must be stored in a directory
29 # named with the experiment run id.
30 # ccnd logs are stored in .log files in a subdirectory per node.
31 # The following diagram exemplifies the experiment result directory
32 # structure (nidi is the unique identifier assigned to node i):
33 #
34 #    run_id
35 #               \   nid1
36 #                        \ nid2.log
37 #               \   nid2
38 #                        \ nid1.log
39 #               \   nid3
40 #                        \ nid3.log
41 #
42
43 import collections
44 import functools
45 import networkx
46 import os
47 import pickle
48 import tempfile
49
50 from nepi.util.timefuncs import compute_delay_ms
51 from nepi.util.statfuncs import compute_mean
52 import nepi.data.processing.ping.parser as ping_parser
53
54 def is_control(content_name):
55     return content_name.startswith("ccnx:/%C1") or \
56             content_name.startswith("ccnx:/ccnx") or \
57             content_name.startswith("ccnx:/...")
58
59
60 def parse_file(filename):
61     """ Parses message information from ccnd log files
62
63         filename: path to ccndlog file
64
65     """
66
67     faces = dict()
68     sep = " "
69
70     f = open(filename, "r")
71
72     data = []
73
74     for line in f:
75         cols =  line.strip().split(sep)
76
77         # CCN_PEEK
78         # MESSAGE interest_from
79         # 1374181938.808523 ccnd[9245]: debug.4352 interest_from 6 ccnx:/test/bunny.ts (23 bytes,sim=0CDCC1D7)
80         #
81         # MESSAGE interest_to
82         # 1374181938.812750 ccnd[9245]: debug.3502 interest_to 5 ccnx:/test/bunny.ts (39 bytes,i=2844,sim=0CDCC1D7)
83         #
84         # MESSAGE CONTENT FROM
85         # 1374181938.868682 ccnd[9245]: debug.4643 content_from 5 ccnx:/test/bunny.ts/%FD%05%1E%85%8FVw/%00/%9E%3D%01%D9%3Cn%95%2BvZ%8
86         #
87         # MESSAGE CONTENT_TO
88         # 1374181938.868772 ccnd[9245]: debug.1619 content_to 6 ccnx:/test/bunny.ts/%FD%05%1E%85%8FVw/%00/%9E%3D%01%D9%3Cn%95%2BvZ%8
89         #
90         # 1375596708.222304 ccnd[9758]: debug.3692 interest_expiry ccnx:/test/bunny.ts/%FD%05%1E%86%B1GS/%00%0A%F7 (44 bytes,c=0:1,i=2819,sim=49FA8048)
91
92         # External face creation
93         # 1374181452.965961 ccnd[9245]: accepted datagram client id=5 (flags=0x40012) 204.85.191.10 port 9695
94
95         if line.find("accepted datagram client") > -1:
96             face_id = (cols[5]).replace("id=",'')
97             ip = cols[7] 
98             port = cols[9]
99             faces[face_id] = (ip, port)
100             continue
101
102         # 1374181452.985296 ccnd[9245]: releasing face id 4 (slot 4)
103         if line.find("releasing face id") > -1:
104             face_id = cols[5]
105             if face_id in faces:
106                 del faces[face_id]
107             continue
108
109         if len(cols) < 6:
110             continue
111
112         timestamp = cols[0]
113         message_type = cols[3]
114
115         if message_type not in ["interest_from", "interest_to", "content_from", 
116                 "content_to", "interest_dupnonce", "interest_expiry"]:
117             continue
118
119         face_id = cols[4] 
120         content_name = cols[5]
121
122         # Interest Nonce ? -> 412A74-0844-0008-50AA-F6EAD4
123         nonce = ""
124         if message_type in ["interest_from", "interest_to", "interest_dupnonce"]:
125             last = cols[-1]
126             if len(last.split("-")) == 5:
127                 nonce = last
128
129         try:
130             size = int((cols[6]).replace('(',''))
131         except:
132             print "interest_expiry without face id!", line
133             continue
134
135         # If no external IP address was identified for this face
136         # asume it is a local face
137         peer = "localhost"
138
139         if face_id in faces:
140             peer, port = faces[face_id]
141
142         data.append((content_name, timestamp, message_type, peer, face_id, 
143             size, nonce, line))
144
145     f.close()
146
147     return data
148
149 def dump_content_history(content_history):
150     f = tempfile.NamedTemporaryFile(delete=False)
151     pickle.dump(content_history, f)
152     f.close()
153     return f.name
154
155 def load_content_history(fname):
156     f = open(fname, "r")
157     content_history = pickle.load(f)
158     f.close()
159
160     os.remove(fname)
161     return content_history
162
163 def annotate_cn_node(graph, nid, ips2nid, data, content_history):
164     for (content_name, timestamp, message_type, peer, face_id, 
165             size, nonce, line) in data:
166
167         # Ignore control messages for the time being
168         if is_control(content_name):
169             continue
170
171         if message_type == "interest_from" and \
172                 peer == "localhost":
173             graph.node[nid]["ccn_consumer"] = True
174         elif message_type == "content_from" and \
175                 peer == "localhost":
176             graph.node[nid]["ccn_producer"] = True
177
178         # Ignore local messages for the time being. 
179         # They could later be used to calculate the processing times
180         # of messages.
181         if peer == "localhost":
182             continue
183
184         # remove digest
185         if message_type in ["content_from", "content_to"]:
186             content_name = "/".join(content_name.split("/")[:-1])
187            
188         if content_name not in content_history:
189             content_history[content_name] = list()
190       
191         peernid = ips2nid[peer]
192         graph.add_edge(nid, peernid)
193
194         content_history[content_name].append((timestamp, message_type, nid, 
195             peernid, nonce, size, line))
196
197 def annotate_cn_graph(logs_dir, graph, parse_ping_logs = False):
198     """ Adds CCN content history for each node in the topology graph.
199
200     """
201     
202     # Make a copy of the graph to ensure integrity
203     graph = graph.copy()
204
205     ips2nid = dict()
206
207     for nid in graph.nodes():
208         ips = graph.node[nid]["ips"]
209         for ip in ips:
210             ips2nid[ip] = nid
211
212     found_files = False
213
214     # Now walk through the ccnd logs...
215     for dirpath, dnames, fnames in os.walk(logs_dir):
216         # continue if we are not at the leaf level (if there are subdirectories)
217         if dnames: 
218             continue
219         
220         # Each dirpath correspond to a different node
221         nid = os.path.basename(dirpath)
222
223         # Cast to numeric nid if necessary
224         if int(nid) in graph.nodes():
225             nid = int(nid)
226     
227         content_history = dict()
228
229         for fname in fnames:
230             if fname.endswith(".log"):
231                 found_files = True
232                 filename = os.path.join(dirpath, fname)
233                 data = parse_file(filename)
234                 annotate_cn_node(graph, nid, ips2nid, data, content_history)
235
236         # Avoid storing everything in memory, instead dump to a file
237         # and reference the file
238         fname = dump_content_history(content_history)
239         graph.node[nid]["history"] = fname
240
241     if not found_files:
242         msg = "No CCND output files were found to parse at %s " % logs_dir
243         raise RuntimeError, msg
244
245     if parse_ping_logs:
246         ping_parser.annotate_cn_graph(logs_dir, graph)
247
248     return graph
249
250 def ccn_producers(graph):
251     """ Returns the nodes that are content providers """
252     return [nid for nid in graph.nodes() \
253             if graph.node[nid].get("ccn_producer")]
254
255 def ccn_consumers(graph):
256     """ Returns the nodes that are content consumers """
257     return [nid for nid in graph.nodes() \
258             if graph.node[nid].get("ccn_consumer")]
259
260 def process_content_history(graph):
261     """ Compute CCN message counts and aggregates content historical 
262     information in the content_names dictionary 
263     
264     """
265
266     ## Assume single source
267     source = ccn_consumers(graph)[0]
268
269     interest_expiry_count = 0
270     interest_dupnonce_count = 0
271     interest_count = 0
272     content_count = 0
273     content_names = dict()
274
275     # Collect information about exchanged messages by content name and
276     # link delay info.
277     for nid in graph.nodes():
278         # Load the data collected from the node's ccnd log
279         fname = graph.node[nid]["history"]
280         history = load_content_history(fname)
281
282         for content_name in history.keys():
283             hist = history[content_name]
284
285             for (timestamp, message_type, nid1, nid2, nonce, size, line) in hist:
286                 if message_type in ["content_from", "content_to"]:
287                     # The first Interest sent will not have a version or chunk number.
288                     # The first Content sent back in reply, will end in /=00 or /%00.
289                     # Make sure to map the first Content to the first Interest.
290                     if content_name.endswith("/=00"):
291                         content_name = "/".join(content_name.split("/")[0:-2])
292
293                 # Add content name to dictionary
294                 if content_name not in content_names:
295                     content_names[content_name] = dict()
296                     content_names[content_name]["interest"] = dict()
297                     content_names[content_name]["content"] = list()
298
299                 # Classify interests by replica
300                 if message_type in ["interest_from"] and \
301                         nonce not in content_names[content_name]["interest"]:
302                     content_names[content_name]["interest"][nonce] = list()
303      
304                 # Add consumer history
305                 if nid == source:
306                     if message_type in ["interest_to", "content_from"]:
307                         # content name history as seen by the source
308                         if "consumer_history" not in content_names[content_name]:
309                             content_names[content_name]["consumer_history"] = list()
310
311                         content_names[content_name]["consumer_history"].append(
312                                 (timestamp, message_type)) 
313
314                 # Add messages per content name and cumulate totals by message type
315                 if message_type == "interest_dupnonce":
316                     interest_dupnonce_count += 1
317                 elif message_type == "interest_expiry":
318                     interest_expiry_count += 1
319                 elif message_type == "interest_from":
320                     interest_count += 1
321                     # Append to interest history of the content name
322                     content_names[content_name]["interest"][nonce].append(
323                             (timestamp, nid2, nid1))
324                 elif message_type == "content_from":
325                     content_count += 1
326                     # Append to content history of the content name
327                     content_names[content_name]["content"].append((timestamp, nid2, nid1))
328                 else:
329                     continue
330             del hist
331         del history
332
333     # Compute the time elapsed between the time an interest is sent
334     # in the consumer node and when the content is received back
335     for content_name in content_names.keys():
336         # order content and interest messages by timestamp
337         content_names[content_name]["content"] = sorted(
338               content_names[content_name]["content"])
339         
340         for nonce, timestamps in content_names[content_name][
341                     "interest"].iteritems():
342               content_names[content_name]["interest"][nonce] = sorted(
343                         timestamps)
344       
345         history = sorted(content_names[content_name]["consumer_history"])
346         content_names[content_name]["consumer_history"] = history
347
348         # compute the rtt time of the message
349         rtt = None
350         waiting_content = False 
351         interest_timestamp = None
352         content_timestamp = None
353         
354         for (timestamp, message_type) in history:
355             if not waiting_content and message_type == "interest_to":
356                 waiting_content = True
357                 interest_timestamp = timestamp
358                 continue
359
360             if waiting_content and message_type == "content_from":
361                 content_timestamp = timestamp
362                 break
363     
364         # If we can't determine who sent the interest, discard it
365         rtt = -1
366         if interest_timestamp and content_timestamp:
367             rtt = compute_delay_ms(content_timestamp, interest_timestamp)
368
369         content_names[content_name]["rtt"] = rtt
370         content_names[content_name]["lapse"] = (interest_timestamp, content_timestamp)
371
372     return (graph,
373         content_names,
374         interest_expiry_count,
375         interest_dupnonce_count,
376         interest_count,
377         content_count)
378
379 def process_content_history_logs(logs_dir, graph, parse_ping_logs = False):
380     """ Parse CCN logs and aggregate content history information in graph.
381     Returns annotated graph and message countn and content names history.
382
383     """
384     ## Process logs and analyse data
385     try:
386         graph = annotate_cn_graph(logs_dir, graph, 
387                 parse_ping_logs = parse_ping_logs)
388     except:
389         print "Skipping: Error parsing ccnd logs", logs_dir
390         raise
391
392     source = ccn_consumers(graph)[0]
393     target = ccn_producers(graph)[0]
394
395     # Process the data from the ccnd logs, but do not re compute
396     # the link delay. 
397     try:
398         (graph,
399         content_names,
400         interest_expiry_count,
401         interest_dupnonce_count,
402         interest_count,
403         content_count) = process_content_history(graph)
404     except:
405         print "Skipping: Error processing ccn data", logs_dir
406         raise
407
408     return (graph,
409             content_names,
410             interest_expiry_count,
411             interest_dupnonce_count,
412             interest_count,
413             content_count)