aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/af_xdp/test_api.c
blob: 46ba6f100eef3ef111ac517fe9b4194a9b6984c8 (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
/*
 *------------------------------------------------------------------
 * Copyright (c) 2020 Cisco and/or its affiliates.
 * 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.
 *------------------------------------------------------------------
 */

#include <vlib/vlib.h>
#include <vlib/unix/unix.h>
#include <vlib/pci/pci.h>
#include <vnet/ethernet/ethernet.h>

#include <vat/vat.h>
#include <vlibapi/api.h>
#include <vlibmemory/api.h>

#include <vppinfra/error.h>
#include <af_xdp/af_xdp.h>

#define __plugin_msg_base af_xdp_test_main.msg_id_base
#include <vlibapi/vat_helper_macros.h>

/* declare message IDs */
#include <af_xdp/af_xdp.api_enum.h>
#include <af_xdp/af_xdp.api_types.h>

typedef struct
{
  /* API message ID base */
  u16 msg_id_base;
  vat_main_t *vat_main;
} af_xdp_test_main_t;

af_xdp_test_main_t af_xdp_test_main;

static vl_api_af_xdp_mode_t
api_af_xdp_mode (af_xdp_mode_t mode)
{
  switch (mode)
    {
    case AF_XDP_MODE_AUTO:
      return AF_XDP_API_MODE_AUTO;
    case AF_XDP_MODE_COPY:
      return AF_XDP_API_MODE_COPY;
    case AF_XDP_MODE_ZERO_COPY:
      return AF_XDP_API_MODE_ZERO_COPY;
    }
  return ~0;
}

/* af_xdp create API */
static int
api_af_xdp_create (vat_main_t * vam)
{
  vl_api_af_xdp_create_t *mp;
  af_xdp_create_if_args_t args;
  int ret;

  if (!unformat_user (vam->input, unformat_af_xdp_create_if_args, &args))
    {
      clib_warning ("unknown input `%U'", format_unformat_error, vam->input);
      return -99;
    }

  M (AF_XDP_CREATE, mp);

  snprintf ((char *) mp->host_if, sizeof (mp->host_if), "%s",
	    args.linux_ifname ? : "");
  snprintf ((char *) mp->name, sizeof (mp->name), "%s", args.name ? : "");
  mp->rxq_num = clib_host_to_net_u16 (args.rxq_num);
  mp->rxq_size = clib_host_to_net_u16 (args.rxq_size);
  mp->txq_size = clib_host_to_net_u16 (args.txq_size);
  mp->mode = api_af_xdp_mode (args.mode);
  if (args.flags & AF_XDP_CREATE_FLAGS_NO_SYSCALL_LOCK)
    mp->flags |= AF_XDP_API_FLAGS_NO_SYSCALL_LOCK;
  snprintf ((char *) mp->prog, sizeof (mp->prog), "%s", args.prog ? : "");

  S (mp);
  W (ret);

  return ret;
}

/* af_xdp create v2 API */
static int
api_af_xdp_create_v2 (vat_main_t *vam)
{
  vl_api_af_xdp_create_v2_t *mp;
  af_xdp_create_if_args_t args;
  int ret;

  if (!unformat_user (vam->input, unformat_af_xdp_create_if_args, &args))
    {
      clib_warning ("unknown input `%U'", format_unformat_error, vam->input);
      return -99;
    }

  M (AF_XDP_CREATE, mp);

  snprintf ((char *) mp->host_if, sizeof (mp->host_if), "%s",
	    args.linux_ifname ?: "");
  snprintf ((char *) mp->name, sizeof (mp->name), "%s", args.name ?: "");
  snprintf ((char *) mp->namespace, sizeof (mp->namespace), "%s",
	    args.netns ?: "");
  mp->rxq_num = clib_host_to_net_u16 (args.rxq_num);
  mp->rxq_size = clib_host_to_net_u16 (args.rxq_size);
  mp->txq_size = clib_host_to_net_u16 (args.txq_size);
  mp->mode = api_af_xdp_mode (args.mode);
  if (args.flags & AF_XDP_CREATE_FLAGS_NO_SYSCALL_LOCK)
    mp->flags |= AF_XDP_API_FLAGS_NO_SYSCALL_LOCK;
  snprintf ((char *) mp->prog, sizeof (mp->prog), "%s", args.prog ?: "");

  S (mp);
  W (ret);

  return ret;
}

/* af_xdp-create reply handler */
static void
vl_api_af_xdp_create_reply_t_handler (vl_api_af_xdp_create_reply_t * mp)
{
  vat_main_t *vam = af_xdp_test_main.vat_main;
  i32 retval = ntohl (mp->retval);

  if (retval == 0)
    {
      fformat (vam->ofp, "created af_xdp with sw_if_index %d\n",
	       ntohl (mp->sw_if_index));
    }

  vam->retval = retval;
  vam->result_ready = 1;
  vam->regenerate_interface_table = 1;
}

/* af_xdp-create v2 reply handler */
static void
vl_api_af_xdp_create_v2_reply_t_handler (vl_api_af_xdp_create_v2_reply_t *mp)
{
  vat_main_t *vam = af_xdp_test_main.vat_main;
  i32 retval = ntohl (mp->retval);

  if (retval == 0)
    {
      fformat (vam->ofp, "created af_xdp with sw_if_index %d\n",
	       ntohl (mp->sw_if_index));
    }

  vam->retval = retval;
  vam->result_ready = 1;
  vam->regenerate_interface_table = 1;
}

/* af_xdp delete API */
static int
api_af_xdp_delete (vat_main_t * vam)
{
  unformat_input_t *i = vam->input;
  vl_api_af_xdp_delete_t *mp;
  u32 sw_if_index = 0;
  u8 index_defined = 0;
  int ret;

  while (unformat_check_input (i) != UNFORMAT_END_OF_INPUT)
    {
      if (unformat (i, "sw_if_index %u", &sw_if_index))
	index_defined = 1;
      else
	{
	  clib_warning ("unknown input '%U'", format_unformat_error, i);
	  return -99;
	}
    }

  if (!index_defined)
    {
      errmsg ("missing sw_if_index\n");
      return -99;
    }

  M (AF_XDP_DELETE, mp);

  mp->sw_if_index = clib_host_to_net_u32 (sw_if_index);

  S (mp);
  W (ret);

  return ret;
}

#include <af_xdp/af_xdp.api_test.c>

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */
an> else: raise AlertingError("Alert of type '{0}' is not implemented.". format(config_type)) self.alerts = self._spec_alert.get("alerts", None) if not self.alerts: raise AlertingError("No alert is specified.") for alert, alert_data in self.alerts.iteritems(): if not alert_data.get("title", None): raise AlertingError("Parameter 'title' is missing.") if not alert_data.get("type", None) in self._ALERTS: raise AlertingError("Parameter 'failed-tests' is missing or " "incorrect.") if not alert_data.get("way", None) in self.configs.keys(): raise AlertingError("Parameter 'way' is missing or incorrect.") if not alert_data.get("include", None): raise AlertingError("Parameter 'include' is missing or the " "list is empty.") def __str__(self): """Return string with human readable description of the alert. :returns: Readable description. :rtype: str """ return "configs={configs}, alerts={alerts}".format( configs=self.configs, alerts=self.alerts) def __repr__(self): """Return string executable as Python constructor call. :returns: Executable constructor call. :rtype: str """ return "Alerting(spec={spec})".format( spec=self._spec) def generate_alerts(self): """Generate alert(s) using specified way(s). """ for alert, alert_data in self.alerts.iteritems(): if alert_data["way"] == "jenkins": self._generate_email_body(alert_data) else: raise AlertingError("Alert with way '{0}' is not implemented.". format(alert_data["way"])) @staticmethod def _send_email(server, addr_from, addr_to, subject, text=None, html=None): """Send an email using predefined configuration. :param server: SMTP server used to send email. :param addr_from: Sender address. :param addr_to: Recipient address(es). :param subject: Subject of the email. :param text: Message in the ASCII text format. :param html: Message in the HTML format. :type server: str :type addr_from: str :type addr_to: list :type subject: str :type text: str :type html: str """ if not text and not html: raise AlertingError("No text/data to send.") msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = addr_from msg['To'] = ", ".join(addr_to) if text: msg.attach(MIMEText(text, 'plain')) if html: msg.attach(MIMEText(html, 'html')) smtp_server = None try: logging.info("Trying to send alert '{0}' ...".format(subject)) logging.debug("SMTP Server: {0}".format(server)) logging.debug("From: {0}".format(addr_from)) logging.debug("To: {0}".format(", ".join(addr_to))) logging.debug("Message: {0}".format(msg.as_string())) smtp_server = smtplib.SMTP(server) smtp_server.sendmail(addr_from, addr_to, msg.as_string()) except smtplib.SMTPException as err: raise AlertingError("Not possible to send the alert via email.", str(err)) finally: if smtp_server: smtp_server.quit() def _get_compressed_failed_tests(self, alert, test_set, sort=True): """Return the dictionary with compressed faild tests. The compression is done by grouping the tests from the same area but with different NICs, frame sizes and number of processor cores. For example, the failed tests: 10ge2p1x520-64b-1c-ethip4udp-ip4scale4000-udpsrcscale15-nat44-mrr 10ge2p1x520-64b-2c-ethip4udp-ip4scale4000-udpsrcscale15-nat44-mrr 10ge2p1x520-64b-4c-ethip4udp-ip4scale4000-udpsrcscale15-nat44-mrr 10ge2p1x520-imix-1c-ethip4udp-ip4scale4000-udpsrcscale15-nat44-mrr 10ge2p1x520-imix-2c-ethip4udp-ip4scale4000-udpsrcscale15-nat44-mrr 10ge2p1x520-imix-4c-ethip4udp-ip4scale4000-udpsrcscale15-nat44-mrr will be represented as: ethip4udp-ip4scale4000-udpsrcscale15-nat44 \ (10ge2p1x520, 64b, imix, 1c, 2c, 4c) Structure of returned data: { "trimmed_TC_name_1": { "nics": [], "framesizes": [], "cores": [] } ... "trimmed_TC_name_N": { "nics": [], "framesizes": [], "cores": [] } } :param alert: Files are created for this alert. :param test_set: Specifies which set of tests will be included in the result. Its name is the same as the name of file with failed tests. :param sort: If True, the failed tests are sorted alphabetically. :type alert: dict :type test_set: str :type sort: bool :returns: CSIT build number, VPP version, Number of failed tests, Compressed failed tests. :rtype: tuple(str, str, int, OrderedDict) """ directory = self.configs[alert["way"]]["output-dir"] failed_tests = OrderedDict() file_path = "{0}/{1}.txt".format(directory, test_set) version = "" try: with open(file_path, 'r') as f_txt: for idx, line in enumerate(f_txt): if idx == 0: build = line[:-1] continue if idx == 1: version = line[:-1] continue try: test = line[:-1].split('-') nic = test[0] framesize = test[1] cores = test[2] name = '-'.join(test[3:-1]) except IndexError: continue if failed_tests.get(name, None) is None: failed_tests[name] = dict(nics=list(), framesizes=list(), cores=list()) if nic not in failed_tests[name]["nics"]: failed_tests[name]["nics"].append(nic) if framesize not in failed_tests[name]["framesizes"]: failed_tests[name]["framesizes"].append(framesize) if cores not in failed_tests[name]["cores"]: failed_tests[name]["cores"].append(cores) except IOError: logging.error("No such file or directory: {file}". format(file=file_path)) return None, None, None, None if sort: sorted_failed_tests = OrderedDict() keys = [k for k in failed_tests.keys()] keys.sort() for key in keys: sorted_failed_tests[key] = failed_tests[key] return build, version, idx-1, sorted_failed_tests else: return build, version, idx-1, failed_tests def _generate_email_body(self, alert): """Create the file which is used in the generated alert. :param alert: Files are created for this alert. :type alert: dict """ if alert["type"] != "failed-tests": raise AlertingError("Alert of type '{0}' is not implemented.". format(alert["type"])) config = self.configs[alert["way"]] text = "" for idx, test_set in enumerate(alert.get("include", [])): build, version, nr, failed_tests = \ self._get_compressed_failed_tests(alert, test_set) if build is None: ret_code, build_nr, _ = get_last_completed_build_number( self._spec.environment["urls"]["URL[JENKINS,CSIT]"], alert["urls"][idx].split('/')[-1]) if ret_code != 0: build_nr = '' text += "\n\nNo input data available for '{set}'. See CSIT " \ "build {link}/{build} for more information.\n".\ format(set='-'.join(test_set.split('-')[-2:]), link=alert["urls"][idx], build=build_nr) continue text += ("\n\n{topo}-{arch}, " "{nr} tests failed, " "CSIT build: {link}/{build}, " "VPP version: {version}\n\n". format(topo=test_set.split('-')[-2], arch=test_set.split('-')[-1], nr=nr, link=alert["urls"][idx], build=build, version=version)) max_len_name = 0 max_len_nics = 0 max_len_framesizes = 0 max_len_cores = 0 for name, params in failed_tests.items(): failed_tests[name]["nics"] = ",".join(sorted(params["nics"])) failed_tests[name]["framesizes"] = \ ",".join(sorted(params["framesizes"])) failed_tests[name]["cores"] = ",".join(sorted(params["cores"])) if len(name) > max_len_name: max_len_name = len(name) if len(failed_tests[name]["nics"]) > max_len_nics: max_len_nics = len(failed_tests[name]["nics"]) if len(failed_tests[name]["framesizes"]) > max_len_framesizes: max_len_framesizes = len(failed_tests[name]["framesizes"]) if len(failed_tests[name]["cores"]) > max_len_cores: max_len_cores = len(failed_tests[name]["cores"]) for name, params in failed_tests.items(): text += "{name} {nics} {frames} {cores}\n".format( name=name + " " * (max_len_name - len(name)), nics=params["nics"] + " " * (max_len_nics - len(params["nics"])), frames=params["framesizes"] + " " * (max_len_framesizes - len(params["framesizes"])), cores=params["cores"] + " " * (max_len_cores - len(params["cores"]))) text += "\nFor detailed information visit: {url}\n".\ format(url=alert["url-details"]) file_name = "{0}/{1}".format(config["output-dir"], config["output-file"]) logging.info("Writing the file '{0}.txt' ...".format(file_name)) try: with open("{0}.txt".format(file_name), 'w') as txt_file: txt_file.write(text) except IOError: logging.error("Not possible to write the file '{0}.txt'.". format(file_name))