pyldb: avoid segfault when adding an element with no name
[sfrench/samba-autobuild/.git] / script / traffic_learner
1 #!/usr/bin/env python3
2 # Generate a traffic model from a traffic summary file
3 #
4 # Copyright (C) Catalyst IT Ltd. 2017
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 #
19 from __future__ import print_function
20 import sys
21 import argparse
22
23 sys.path.insert(0, "bin/python")
24 from samba.emulate import traffic
25
26 from samba.logger import get_samba_logger
27 logger = get_samba_logger(name=__name__, level=20)
28 error = logger.error
29 info = logger.info
30
31 def main():
32     parser = argparse.ArgumentParser(description=__doc__,
33                         formatter_class=argparse.RawDescriptionHelpFormatter)
34     parser.add_argument('-o', '--out',
35                         help="write model here")
36     parser.add_argument('--dns-mode', choices=['inline', 'count'],
37                         help='how to deal with DNS', default='count')
38     parser.add_argument('SUMMARY_FILE', nargs='*', type=argparse.FileType('r'),
39                         default=[sys.stdin],
40                         help="read from this file (default STDIN)")
41     args = parser.parse_args()
42
43     if args.out is None:
44         error("No output file was specified to write the model to.")
45         error("Please specify a filename using the --out option.")
46         return 1
47
48     try:
49         outfile = open(args.out, 'w')
50     except IOError as e:
51         error("could not open %s" % args.out)
52         error(e)
53         return 1
54
55     if args.SUMMARY_FILE is sys.stdin:
56         info("reading from STDIN...")
57
58     (conversations,
59      interval,
60      duration,
61      dns_counts) = traffic.ingest_summaries(args.SUMMARY_FILE,
62                                             dns_mode=args.dns_mode)
63
64     model = traffic.TrafficModel()
65     info("learning model")
66     if args.dns_mode == 'count':
67         model.learn(conversations, dns_counts)
68     else:
69         model.learn(conversations)
70
71     model.save(args.out)
72
73 sys.exit(main())