summaryrefslogtreecommitdiffstats
path: root/scripts/automation/trex_control_plane/client/trex_stateless_sim.py
blob: 4382e9fb2c55a94b38b440df430ad1846a167d8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Itay Marom
Cisco Systems, Inc.

Copyright (c) 2015-2015 Cisco Systems, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

try:
    # support import for Python 2
    import outer_packages
except ImportError:
    # support import for Python 3
    import client.outer_packages

from client_utils.jsonrpc_client import JsonRpcClient, BatchMessage
from client_utils.packet_builder import CTRexPktBuilder
from client_utils import parsing_opts

import json

from common.trex_streams import *

import argparse
import tempfile
import subprocess
import os
from dpkt import pcap
from operator import itemgetter


def merge_cap_files (pcap_file_list, out_filename, delete_src = False):

    out_pkts = []

    # read all packets to a list
    for src in pcap_file_list:
        f = open(src, 'r')
        reader = pcap.Reader(f)
        pkts = reader.readpkts()
        out_pkts += pkts
        f.close()
        if delete_src:
            os.unlink(src)

    # sort by the timestamp
    out_pkts = sorted(out_pkts, key=itemgetter(0))


    out = open(out_filename, 'w')
    out_writer = pcap.Writer(out)

    for ts, pkt in out_pkts:
        out_writer.writepkt(pkt, ts)

    out.close()




class SimRun(object):
    def __init__ (self, options):

        self.options = options

        # dummies
        self.handler = 0
        self.port_id = 0

        self.mul = options.mult

        self.duration = -1

    def load_yaml_file (self):
        streams_db = CStreamsDB()
        stream_list = streams_db.load_yaml_file(self.options.input_file)

        streams_json = []
        for stream in stream_list.compiled:
            stream_json = {"id":1,
                           "jsonrpc": "2.0",
                           "method": "add_stream",
                           "params": {"handler": self.handler,
                                      "port_id": self.port_id,
                                      "stream_id": stream.stream_id,
                                      "stream": stream.stream}
                           }

            streams_json.append(stream_json)

        return streams_json


    def generate_start_cmd (self):
        return  {"id":1,
                 "jsonrpc": "2.0",
                 "method": "start_traffic",
                 "params": {"handler": self.handler,
                            "port_id": self.port_id,
                            "mul": self.mul,
                            "duration": self.duration}
                 }


    def run (self):

        # load the streams
        cmds_json = (self.load_yaml_file())
        cmds_json.append(self.generate_start_cmd())

        f = tempfile.NamedTemporaryFile(delete = False)
        f.write(json.dumps(cmds_json))
        f.close()

        try:
            if self.options.json:
                with open(f.name) as file:
                    data = "\n".join(file.readlines())
                    print json.dumps(json.loads(data), indent = 4, separators=(',', ': '), sort_keys = True)
            else:
                self.execute_bp_sim(f.name)
        finally:
            os.unlink(f.name)


    def execute_bp_sim (self, json_filename):
        exe = 'bp-sim-64' if self.options.release else 'bp-sim-64-debug'
        if not os.path.exists(exe):
            print "cannot find executable '{0}'".format(exe)
            exit(-1)

        cmd = [exe,
               '--pcap',
               '--sl',
               '--cores',
               str(self.options.cores),
               '--limit',
               str(self.options.limit),
               '-f',
               json_filename,
               '-o',
               self.options.output_file]

        if self.options.dry:
            cmd += ['--dry']

        if self.options.core_index != None:
            cmd += ['--core_index', str(self.options.core_index)]

        if self.options.valgrind:
            cmd = ['valgrind', '--leak-check=full'] + cmd

        elif self.options.gdb:
            cmd = ['gdb', '--args'] + cmd

        print "executing command: '{0}'".format(" ".join(cmd))
        subprocess.call(cmd)

        self.merge_results()


    def merge_results (self):
        if self.options.dry:
            return

        if self.options.cores == 1:
            return

        if self.options.core_index != None:
            return


        inputs = ["{0}-{1}".format(self.options.output_file, index) for index in xrange(0, self.options.cores)]
        merge_cap_files(inputs, self.options.output_file, delete_src = True)



def is_valid_file(filename):
    if not os.path.isfile(filename):
        raise argparse.ArgumentTypeError("The file '%s' does not exist" % filename)

    return filename


def unsigned_int (x):
    x = int(x)
    if x < 0:
        raise argparse.ArgumentTypeError("argument must be >= 0")

    return x

def setParserOptions():
    parser = argparse.ArgumentParser(prog="stl_sim.py")

    parser.add_argument("input_file",
                        help = "input file in YAML or Python format",
                        type = is_valid_file)

    parser.add_argument("output_file",
                        help = "output file in ERF format")


    parser.add_argument("-c", "--cores",
                        help = "DP core count [default is 1]",
                        default = 1,
                        type = int,
                        choices = xrange(1, 9))

    parser.add_argument("-n", "--core_index",
                        help = "Record only a specific core",
                        default = None,
                        type = int)

    parser.add_argument("-r", "--release",
                        help = "runs on release image instead of debug [default is False]",
                        action = "store_true",
                        default = False)

    parser.add_argument("-s", "--dry",
                        help = "dry run only (nothing will be written to the file) [default is False]",
                        action = "store_true",
                        default = False)

    parser.add_argument("-l", "--limit",
                        help = "limit test total packet count [default is 5000]",
                        default = 5000,
                        type = unsigned_int)

    parser.add_argument('-m', '--multiplier',
                        help = parsing_opts.match_multiplier_help,
                        dest = 'mult',
                        default = {'type':'raw', 'value':1, 'op': 'abs'},
                        type = parsing_opts.match_multiplier_strict)

    group = parser.add_mutually_exclusive_group()

    group.add_argument("-x", "--valgrind",
                       help = "run under valgrind [default is False]",
                       action = "store_true",
                       default = False)

    group.add_argument("-g", "--gdb",
                       help = "run under GDB [default is False]",
                       action = "store_true",
                       default = False)

    group.add_argument("--json",
                       help = "generate JSON output only to stdout [default is False]",
                       action = "store_true",
                       default = False)

    return parser


def validate_args (parser, options):

    if options.core_index:
        if not options.core_index in xrange(0, options.cores):
            parser.error("DP core index valid range is 0 to {0}".format(options.cores - 1))

    # zero is ok - no limit, but other values must be at least as the number of cores
    if (options.limit != 0) and options.limit < options.cores:
        parser.error("limit cannot be lower than number of DP cores")


def main ():
    parser = setParserOptions()
    options = parser.parse_args()

    validate_args(parser, options)

    r = SimRun(options)

    r.run()


if __name__ == '__main__':
    main()