summaryrefslogtreecommitdiffstats
path: root/src/plugins/lisp/lisp-gpe/lisp_gpe_test.c
blob: 2f1a4187551096a35cd78979dbfceaade5f14d0a (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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
/*
 * Copyright (c) 2015 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 <vat/vat.h>
#include <vlibapi/api.h>
#include <vlibmemory/api.h>
#include <vppinfra/error.h>

#include <vnet/ip/ip_format_fns.h>
#include <vnet/ethernet/ethernet_format_fns.h>
#include <vnet/ethernet/mac_address.h>
#include <lisp/lisp-cp/lisp_types.h>

/* define message IDs */
#include <lisp/lisp-gpe/lisp_gpe.api_enum.h>
#include <lisp/lisp-gpe/lisp_gpe.api_types.h>
#include <vlibmemory/vlib.api_types.h>

typedef struct
{
  /* API message ID base */
  u16 msg_id_base;
  vat_main_t *vat_main;
  u32 ping_id;
} lisp_gpe_test_main_t;

lisp_gpe_test_main_t lisp_gpe_test_main;

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

#define FINISH                                                                \
  vec_add1 (s, 0);                                                            \
  vlib_cli_output (handle, (char *) s);                                       \
  vec_free (s);                                                               \
  return handle;

#define LISP_PING(_lm, mp_ping)                                         \
  if (!(_lm)->ping_id)                                                  \
    (_lm)->ping_id = vl_msg_api_get_msg_index ((u8 *) (VL_API_CONTROL_PING_CRC)); \
  mp_ping = vl_msg_api_alloc_as_if_client (sizeof (*mp_ping));          \
  mp_ping->_vl_msg_id = htons ((_lm)->ping_id);                         \
  mp_ping->client_index = vam->my_client_index;                         \
  fformat (vam->ofp, "Sending ping id=%d\n", (_lm)->ping_id);           \
  vam->result_ready = 0;                                                \

typedef struct
{
  u32 spi;
  u8 si;
} __attribute__ ((__packed__)) lisp_nsh_api_t;

static uword
unformat_nsh_address (unformat_input_t * input, va_list * args)
{
  lisp_nsh_api_t *nsh = va_arg (*args, lisp_nsh_api_t *);
  return unformat (input, "SPI:%d SI:%d", &nsh->spi, &nsh->si);
}

static u8 *
format_nsh_address_vat (u8 * s, va_list * args)
{
  nsh_t *a = va_arg (*args, nsh_t *);
  return format (s, "SPI:%d SI:%d", clib_net_to_host_u32 (a->spi), a->si);
}

static u8 *
format_lisp_flat_eid (u8 * s, va_list * args)
{
  vl_api_eid_t *eid = va_arg (*args, vl_api_eid_t *);

  switch (eid->type)
    {
    case EID_TYPE_API_PREFIX:
      if (eid->address.prefix.address.af)
	return format (s, "%U/%d", format_ip6_address,
		       eid->address.prefix.address.un.ip6,
		       eid->address.prefix.len);
      return format (s, "%U/%d", format_ip4_address,
		     eid->address.prefix.address.un.ip4,
		     eid->address.prefix.len);
    case EID_TYPE_API_MAC:
      return format (s, "%U", format_ethernet_address, eid->address.mac);
    case EID_TYPE_API_NSH:
      return format (s, "%U", format_nsh_address_vat, eid->address.nsh);
    }
  return 0;
}

static void vl_api_gpe_add_del_fwd_entry_reply_t_handler
  (vl_api_gpe_add_del_fwd_entry_reply_t * mp)
{
  vat_main_t *vam = &vat_main;
  i32 retval = ntohl (mp->retval);
  if (vam->async_mode)
    {
      vam->async_errors += (retval < 0);
    }
  else
    {
      vam->retval = retval;
      vam->result_ready = 1;
    }
}

static void
api_gpe_fwd_entry_net_to_host (vl_api_gpe_fwd_entry_t * e)
{
  e->dp_table = clib_net_to_host_u32 (e->dp_table);
  e->fwd_entry_index = clib_net_to_host_u32 (e->fwd_entry_index);
  e->vni = clib_net_to_host_u32 (e->vni);
}

static void
  gpe_fwd_entries_get_reply_t_net_to_host
  (vl_api_gpe_fwd_entries_get_reply_t * mp)
{
  u32 i;

  mp->count = clib_net_to_host_u32 (mp->count);
  for (i = 0; i < mp->count; i++)
    {
      api_gpe_fwd_entry_net_to_host (&mp->entries[i]);
    }
}

static u8 *
format_gpe_encap_mode (u8 * s, va_list * args)
{
  u32 mode = va_arg (*args, u32);

  switch (mode)
    {
    case 0:
      return format (s, "lisp");
    case 1:
      return format (s, "vxlan");
    }
  return 0;
}

static void
  vl_api_gpe_get_encap_mode_reply_t_handler
  (vl_api_gpe_get_encap_mode_reply_t * mp)
{
  vat_main_t *vam = &vat_main;

  print (vam->ofp, "gpe mode: %U", format_gpe_encap_mode, mp->encap_mode);
  vam->retval = ntohl (mp->retval);
  vam->result_ready = 1;
}

static void
  vl_api_gpe_fwd_entry_path_details_t_handler
  (vl_api_gpe_fwd_entry_path_details_t * mp)
{
  vat_main_t *vam = &vat_main;
  u8 *(*format_ip_address_fcn) (u8 *, va_list *) = 0;

  if (mp->lcl_loc.addr.af)
    format_ip_address_fcn = format_ip6_address;
  else
    format_ip_address_fcn = format_ip4_address;

  print (vam->ofp, "w:%d %30U %30U", mp->rmt_loc.weight,
	 format_ip_address_fcn, &mp->lcl_loc.addr.un,
	 format_ip_address_fcn, &mp->rmt_loc.addr.un);
}

static void
  vl_api_gpe_fwd_entries_get_reply_t_handler
  (vl_api_gpe_fwd_entries_get_reply_t * mp)
{
  vat_main_t *vam = &vat_main;
  u32 i;
  int retval = clib_net_to_host_u32 (mp->retval);
  vl_api_gpe_fwd_entry_t *e;

  if (retval)
    goto end;

  gpe_fwd_entries_get_reply_t_net_to_host (mp);

  for (i = 0; i < mp->count; i++)
    {
      e = &mp->entries[i];
      print (vam->ofp, "%10d %10d %U %40U", e->fwd_entry_index, e->dp_table,
	     format_lisp_flat_eid, e->leid, format_lisp_flat_eid, e->reid);
    }

end:
  vam->retval = retval;
  vam->result_ready = 1;
}

static void
  vl_api_gpe_native_fwd_rpaths_get_reply_t_handler
  (vl_api_gpe_native_fwd_rpaths_get_reply_t * mp)
{
  vat_main_t *vam = &vat_main;
  u32 i, n;
  int retval = clib_net_to_host_u32 (mp->retval);
  vl_api_gpe_native_fwd_rpath_t *r;

  if (retval)
    goto end;

  n = clib_net_to_host_u32 (mp->count);

  for (i = 0; i < n; i++)
    {
      r = &mp->entries[i];
      print (vam->ofp, "fib_index: %d sw_if_index %d nh %U",
	     clib_net_to_host_u32 (r->fib_index),
	     clib_net_to_host_u32 (r->nh_sw_if_index),
	     r->nh_addr.af ? format_ip6_address : format_ip4_address,
	     r->nh_addr.un);
    }

end:
  vam->retval = retval;
  vam->result_ready = 1;
}

static void
  vl_api_gpe_fwd_entry_vnis_get_reply_t_handler
  (vl_api_gpe_fwd_entry_vnis_get_reply_t * mp)
{
  vat_main_t *vam = &vat_main;
  u32 i, n;
  int retval = clib_net_to_host_u32 (mp->retval);

  if (retval)
    goto end;

  n = clib_net_to_host_u32 (mp->count);

  for (i = 0; i < n; i++)
    print (vam->ofp, "%d", clib_net_to_host_u32 (mp->vnis[i]));

end:
  vam->retval = retval;
  vam->result_ready = 1;
}


/* *INDENT-OFF* */
/** Used for parsing LISP eids */
typedef CLIB_PACKED(struct{
  union {
          ip46_address_t ip;
          mac_address_t mac;
          lisp_nsh_api_t nsh;
  } addr;
  u32 len;       /**< prefix length if IP */
  u8 type;      /**< type of eid */
}) lisp_eid_vat_t;
/* *INDENT-ON* */

static uword
unformat_lisp_eid_vat (unformat_input_t * input, va_list * args)
{
  lisp_eid_vat_t *a = va_arg (*args, lisp_eid_vat_t *);

  clib_memset (a, 0, sizeof (a[0]));

  if (unformat (input, "%U/%d", unformat_ip46_address, a->addr.ip, &a->len))
    {
      a->type = 0;		/* ip prefix type */
    }
  else if (unformat (input, "%U", unformat_ethernet_address, &a->addr.mac))
    {
      a->type = 1;		/* mac type */
    }
  else if (unformat (input, "%U", unformat_nsh_address, a->addr.nsh))
    {
      a->type = 2;		/* NSH type */
      a->addr.nsh.spi = clib_host_to_net_u32 (a->addr.nsh.spi);
    }
  else
    {
      return 0;
    }

  if (a->type == 0)
    {
      if (ip46_address_is_ip4 (&a->addr.ip))
	return a->len > 32 ? 1 : 0;
      else
	return a->len > 128 ? 1 : 0;
    }

  return 1;
}

static void
lisp_eid_put_vat (vl_api_eid_t * eid, const lisp_eid_vat_t * vat_eid)
{
  eid->type = vat_eid->type;
  switch (eid->type)
    {
    case EID_TYPE_API_PREFIX:
      if (ip46_address_is_ip4 (&vat_eid->addr.ip))
	{
	  clib_memcpy (&eid->address.prefix.address.un.ip4,
		       &vat_eid->addr.ip.ip4, 4);
	  eid->address.prefix.address.af = ADDRESS_IP4;
	  eid->address.prefix.len = vat_eid->len;
	}
      else
	{
	  clib_memcpy (&eid->address.prefix.address.un.ip6,
		       &vat_eid->addr.ip.ip6, 16);
	  eid->address.prefix.address.af = ADDRESS_IP6;
	  eid->address.prefix.len = vat_eid->len;
	}
      return;
    case EID_TYPE_API_MAC:
      clib_memcpy (&eid->address.mac, &vat_eid->addr.mac,
		   sizeof (eid->address.mac));
      return;
    case EID_TYPE_API_NSH:
      clib_memcpy (&eid->address.nsh, &vat_eid->addr.nsh,
		   sizeof (eid->address.nsh));
      return;
    default:
      ASSERT (0);
      return;
    }
}

static int
api_gpe_add_del_fwd_entry (vat_main_t * vam)
{
  u32 dp_table = 0, vni = 0;;
  unformat_input_t *input = vam->input;
  vl_api_gpe_add_del_fwd_entry_t *mp;
  u8 is_add = 1;
  lisp_eid_vat_t _rmt_eid, *rmt_eid = &_rmt_eid;
  lisp_eid_vat_t _lcl_eid, *lcl_eid = &_lcl_eid;
  u8 rmt_eid_set = 0, lcl_eid_set = 0;
  u32 action = ~0, w;
  ip4_address_t rmt_rloc4, lcl_rloc4;
  ip6_address_t rmt_rloc6, lcl_rloc6;
  vl_api_gpe_locator_t *rmt_locs = 0, *lcl_locs = 0, rloc, *curr_rloc = 0;
  int ret;

  clib_memset (&rloc, 0, sizeof (rloc));

  /* Parse args required to build the message */
  while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
    {
      if (unformat (input, "del"))
	is_add = 0;
      else if (unformat (input, "add"))
	is_add = 1;
      else if (unformat (input, "reid %U", unformat_lisp_eid_vat, rmt_eid))
	{
	  rmt_eid_set = 1;
	}
      else if (unformat (input, "leid %U", unformat_lisp_eid_vat, lcl_eid))
	{
	  lcl_eid_set = 1;
	}
      else if (unformat (input, "vrf %d", &dp_table))
	;
      else if (unformat (input, "bd %d", &dp_table))
	;
      else if (unformat (input, "vni %d", &vni))
	;
      else if (unformat (input, "w %d", &w))
	{
	  if (!curr_rloc)
	    {
	      errmsg ("No RLOC configured for setting priority/weight!");
	      return -99;
	    }
	  curr_rloc->weight = w;
	}
      else if (unformat (input, "loc-pair %U %U", unformat_ip4_address,
			 &lcl_rloc4, unformat_ip4_address, &rmt_rloc4))
	{
	  rloc.addr.af = 0;
	  clib_memcpy (&rloc.addr.un.ip4, &lcl_rloc4, sizeof (lcl_rloc4));
	  rloc.weight = 0;
	  vec_add1 (lcl_locs, rloc);

	  clib_memcpy (&rloc.addr.un.ip4, &rmt_rloc4, sizeof (rmt_rloc4));
	  vec_add1 (rmt_locs, rloc);
	  /* weight saved in rmt loc */
	  curr_rloc = &rmt_locs[vec_len (rmt_locs) - 1];
	}
      else if (unformat (input, "loc-pair %U %U", unformat_ip6_address,
			 &lcl_rloc6, unformat_ip6_address, &rmt_rloc6))
	{
	  rloc.addr.af = 1;
	  clib_memcpy (&rloc.addr.un.ip6, &lcl_rloc6, sizeof (lcl_rloc6));
	  rloc.weight = 0;
	  vec_add1 (lcl_locs, rloc);

	  clib_memcpy (&rloc.addr.un.ip6, &rmt_rloc6, sizeof (rmt_rloc6));
	  vec_add1 (rmt_locs, rloc);
	  /* weight saved in rmt loc */
	  curr_rloc = &rmt_locs[vec_len (rmt_locs) - 1];
	}
      else if (unformat (input, "action %d", &action))
	{
	  ;
	}
      else
	{
	  clib_warning ("parse error '%U'", format_unformat_error, input);
	  return -99;
	}
    }

  if (!rmt_eid_set)
    {
      errmsg ("remote eid addresses not set");
      return -99;
    }

  if (lcl_eid_set && rmt_eid->type != lcl_eid->type)
    {
      errmsg ("eid types don't match");
      return -99;
    }

  if (0 == rmt_locs && (u32) ~ 0 == action)
    {
      errmsg ("action not set for negative mapping");
      return -99;
    }

  /* Construct the API message */
  M2 (GPE_ADD_DEL_FWD_ENTRY, mp,
      sizeof (vl_api_gpe_locator_t) * vec_len (rmt_locs) * 2);

  mp->is_add = is_add;
  lisp_eid_put_vat (&mp->rmt_eid, rmt_eid);
  lisp_eid_put_vat (&mp->lcl_eid, lcl_eid);
  mp->dp_table = clib_host_to_net_u32 (dp_table);
  mp->vni = clib_host_to_net_u32 (vni);
  mp->action = action;

  if (0 != rmt_locs && 0 != lcl_locs)
    {
      mp->loc_num = clib_host_to_net_u32 (vec_len (rmt_locs) * 2);
      clib_memcpy (mp->locs, lcl_locs,
		   (sizeof (vl_api_gpe_locator_t) * vec_len (lcl_locs)));

      u32 offset = sizeof (vl_api_gpe_locator_t) * vec_len (lcl_locs);
      clib_memcpy (((u8 *) mp->locs) + offset, rmt_locs,
		   (sizeof (vl_api_gpe_locator_t) * vec_len (rmt_locs)));
    }
  vec_free (lcl_locs);
  vec_free (rmt_locs);

  /* send it... */
  S (mp);

  /* Wait for a reply... */
  W (ret);
  return ret;
}

static int
api_gpe_enable_disable (vat_main_t * vam)
{
  unformat_input_t *input = vam->input;
  vl_api_gpe_enable_disable_t *mp;
  u8 is_set = 0;
  u8 is_enable = 1;
  int ret;

  /* Parse args required to build the message */
  while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
    {
      if (unformat (input, "enable"))
	{
	  is_set = 1;
	  is_enable = 1;
	}
      else if (unformat (input, "disable"))
	{
	  is_set = 1;
	  is_enable = 0;
	}
      else
	break;
    }

  if (is_set == 0)
    {
      errmsg ("Value not set");
      return -99;
    }

  /* Construct the API message */
  M (GPE_ENABLE_DISABLE, mp);

  mp->is_enable = is_enable;

  /* send it... */
  S (mp);

  /* Wait for a reply... */
  W (ret);
  return ret;
}

uword
unformat_gpe_encap_mode (unformat_input_t * input, va_list * args)
{
  u32 *mode = va_arg (*args, u32 *);

  if (unformat (input, "lisp"))
    *mode = 0;
  else if (unformat (input, "vxlan"))
    *mode = 1;
  else
    return 0;

  return 1;
}

static int
api_gpe_get_encap_mode (vat_main_t * vam)
{
  vl_api_gpe_get_encap_mode_t *mp;
  int ret;

  /* Construct the API message */
  M (GPE_GET_ENCAP_MODE, mp);

  /* send it... */
  S (mp);

  /* Wait for a reply... */
  W (ret);
  return ret;
}

static int
api_gpe_set_encap_mode (vat_main_t * vam)
{
  unformat_input_t *input = vam->input;
  vl_api_gpe_set_encap_mode_t *mp;
  int ret;
  u32 mode = 0;

  /* Parse args required to build the message */
  while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
    {
      if (unformat (input, "%U", unformat_gpe_encap_mode, &mode))
	;
      else
	break;
    }

  /* Construct the API message */
  M (GPE_SET_ENCAP_MODE, mp);

  mp->is_vxlan = mode;

  /* send it... */
  S (mp);

  /* Wait for a reply... */
  W (ret);
  return ret;
}

static int
api_gpe_add_del_iface (vat_main_t * vam)
{
  unformat_input_t *input = vam->input;
  vl_api_gpe_add_del_iface_t *mp;
  u8 action_set = 0, is_add = 1, is_l2 = 0, dp_table_set = 0, vni_set = 0;
  u32 dp_table = 0, vni = 0;
  int ret;

  /* Parse args required to build the message */
  while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
    {
      if (unformat (input, "up"))
	{
	  action_set = 1;
	  is_add = 1;
	}
      else if (unformat (input, "down"))
	{
	  action_set = 1;
	  is_add = 0;
	}
      else if (unformat (input, "table_id %d", &dp_table))
	{
	  dp_table_set = 1;
	}
      else if (unformat (input, "bd_id %d", &dp_table))
	{
	  dp_table_set = 1;
	  is_l2 = 1;
	}
      else if (unformat (input, "vni %d", &vni))
	{
	  vni_set = 1;
	}
      else
	break;
    }

  if (action_set == 0)
    {
      errmsg ("Action not set");
      return -99;
    }
  if (dp_table_set == 0 || vni_set == 0)
    {
      errmsg ("vni and dp_table must be set");
      return -99;
    }

  /* Construct the API message */
  M (GPE_ADD_DEL_IFACE, mp);

  mp->is_add = is_add;
  mp->dp_table = clib_host_to_net_u32 (dp_table);
  mp->is_l2 = is_l2;
  mp->vni = clib_host_to_net_u32 (vni);

  /* send it... */
  S (mp);

  /* Wait for a reply... */
  W (ret);
  return ret;
}

static int
api_gpe_fwd_entries_get (vat_main_t * vam)
{
  unformat_input_t *i = vam->input;
  vl_api_gpe_fwd_entries_get_t *mp;
  u8 vni_set = 0;
  u32 vni = ~0;
  int ret;

  while (unformat_check_input (i) != UNFORMAT_END_OF_INPUT)
    {
      if (unformat (i, "vni %d", &vni))
	{
	  vni_set = 1;
	}
      else
	{
	  errmsg ("parse error '%U'", format_unformat_error, i);
	  return -99;
	}
    }

  if (!vni_set)
    {
      errmsg ("vni not set!");
      return -99;
    }

  if (!vam->json_output)
    {
      print (vam->ofp, "%10s %10s %s %40s", "fwd_index", "dp_table",
	     "leid", "reid");
    }

  M (GPE_FWD_ENTRIES_GET, mp);
  mp->vni = clib_host_to_net_u32 (vni);

  /* send it... */
  S (mp);

  /* Wait for a reply... */
  W (ret);
  return ret;
}

static int
api_gpe_native_fwd_rpaths_get (vat_main_t * vam)
{
  unformat_input_t *i = vam->input;
  vl_api_gpe_native_fwd_rpaths_get_t *mp;
  int ret;
  u8 ip_family_set = 0, is_ip4 = 1;

  while (unformat_check_input (i) != UNFORMAT_END_OF_INPUT)
    {
      if (unformat (i, "ip4"))
	{
	  ip_family_set = 1;
	  is_ip4 = 1;
	}
      else if (unformat (i, "ip6"))
	{
	  ip_family_set = 1;
	  is_ip4 = 0;
	}
      else
	{
	  errmsg ("parse error '%U'", format_unformat_error, i);
	  return -99;
	}
    }

  if (!ip_family_set)
    {
      errmsg ("ip family not set!");
      return -99;
    }

  M (GPE_NATIVE_FWD_RPATHS_GET, mp);
  mp->is_ip4 = is_ip4;

  /* send it... */
  S (mp);

  /* Wait for a reply... */
  W (ret);
  return ret;
}

static int
api_gpe_fwd_entry_vnis_get (vat_main_t * vam)
{
  vl_api_gpe_fwd_entry_vnis_get_t *mp;
  int ret;

  if (!vam->json_output)
    {
      print (vam->ofp, "VNIs");
    }

  M (GPE_FWD_ENTRY_VNIS_GET, mp);

  /* send it... */
  S (mp);

  /* Wait for a reply... */
  W (ret);
  return ret;
}

static int
api_gpe_add_del_native_fwd_rpath (vat_main_t * vam)
{
  unformat_input_t *i = vam->input;
  vl_api_gpe_add_del_native_fwd_rpath_t *mp;
  int ret = 0;
  u8 is_add = 1, ip_set = 0, is_ip4 = 1;
  struct in_addr ip4;
  struct in6_addr ip6;
  u32 table_id = 0, nh_sw_if_index = ~0;

  clib_memset (&ip4, 0, sizeof (ip4));
  clib_memset (&ip6, 0, sizeof (ip6));

  while (unformat_check_input (i) != UNFORMAT_END_OF_INPUT)
    {
      if (unformat (i, "del"))
	is_add = 0;
      else if (unformat (i, "via %U %U", unformat_ip4_address, &ip4,
			 unformat_sw_if_index, vam, &nh_sw_if_index))
	{
	  ip_set = 1;
	  is_ip4 = 1;
	}
      else if (unformat (i, "via %U %U", unformat_ip6_address, &ip6,
			 unformat_sw_if_index, vam, &nh_sw_if_index))
	{
	  ip_set = 1;
	  is_ip4 = 0;
	}
      else if (unformat (i, "via %U", unformat_ip4_address, &ip4))
	{
	  ip_set = 1;
	  is_ip4 = 1;
	  nh_sw_if_index = ~0;
	}
      else if (unformat (i, "via %U", unformat_ip6_address, &ip6))
	{
	  ip_set = 1;
	  is_ip4 = 0;
	  nh_sw_if_index = ~0;
	}
      else if (unformat (i, "table %d", &table_id))
	;
      else
	{
	  errmsg ("parse error '%U'", format_unformat_error, i);
	  return -99;
	}
    }

  if (!ip_set)
    {
      errmsg ("nh addr not set!");
      return -99;
    }

  M (GPE_ADD_DEL_NATIVE_FWD_RPATH, mp);
  mp->is_add = is_add;
  mp->table_id = clib_host_to_net_u32 (table_id);
  mp->nh_sw_if_index = clib_host_to_net_u32 (nh_sw_if_index);
  mp->nh_addr.af = is_ip4 ? 0 : 1;
  if (is_ip4)
    clib_memcpy (mp->nh_addr.un.ip4, &ip4, sizeof (ip4));
  else
    clib_memcpy (mp->nh_addr.un.ip6, &ip6, sizeof (ip6));

  /* send it... */
  S (mp);

  /* Wait for a reply... */
  W (ret);
  return ret;
}

static int
api_gpe_fwd_entry_path_dump (vat_main_t * vam)
{
  vl_api_gpe_fwd_entry_path_dump_t *mp;
  vl_api_control_ping_t *mp_ping;
  unformat_input_t *i = vam->input;
  u32 fwd_entry_index = ~0;
  int ret;

  while (unformat_check_input (i) != UNFORMAT_END_OF_INPUT)
    {
      if (unformat (i, "index %d", &fwd_entry_index))
	;
      else
	break;
    }

  if (~0 == fwd_entry_index)
    {
      errmsg ("no index specified!");
      return -99;
    }

  if (!vam->json_output)
    {
      print (vam->ofp, "first line");
    }

  M (GPE_FWD_ENTRY_PATH_DUMP, mp);

  /* send it... */
  S (mp);
  /* Use a control ping for synchronization */
  LISP_PING (&lisp_gpe_test_main, mp_ping);
  S (mp_ping);

  /* Wait for a reply... */
  W (ret);
  return ret;
}

#define vat_plugin_register vat_plugin_register_gpe
#include <lisp/lisp-gpe/lisp_gpe.api_test.c>

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */
rt + node['cpu']['total_other_cpus'] - 1 other_workers = None if other_cpus_end != 0: other_workers = (other_cpus_start, other_cpus_end) node['cpu']['other_workers'] = other_workers # Allocate the VPP main core and workers vpp_workers = [] reserve_vpp_main_core = node['cpu']['reserve_vpp_main_core'] total_vpp_cpus = node['cpu']['total_vpp_cpus'] total_rx_queues = node['cpu']['total_rx_queues'] # If total_vpp_cpus is 0 or is less than the numa nodes with ports # then we shouldn't get workers total_workers_node = 0 if len(ports_per_numa): total_workers_node = total_vpp_cpus // len(ports_per_numa) total_main = 0 if reserve_vpp_main_core: total_main = 1 total_mbufs = 0 if total_main + total_workers_node != 0: for item in ports_per_numa.items(): numa_node = item[0] value = item[1] # Get the number of descriptors and queues mbufs = self._calc_desc_and_queues( len(ports_per_numa), len(value['interfaces']), total_rx_queues, value) total_mbufs += mbufs # Get the VPP workers reserve_vpp_main_core = self._calc_vpp_workers( node, vpp_workers, numa_node, other_cpus_end, total_workers_node, reserve_vpp_main_core) total_mbufs *= 2.5 total_mbufs = int(total_mbufs) else: total_mbufs = 0 # Save the info node['cpu']['vpp_workers'] = vpp_workers node['cpu']['total_mbufs'] = total_mbufs # Write the config self.updateconfig() @staticmethod def _apply_vpp_tcp(node): """ Apply the tcp config :param node: Node dictionary with cpuinfo. :type node: dict """ active_open_sessions = node['tcp']['active_open_sessions'] aos = int(active_open_sessions) passive_open_sessions = node['tcp']['passive_open_sessions'] pos = int(passive_open_sessions) # Generate the api-segment gid vpp sheit in any case if (aos + pos) == 0: tcp = '\n'.join([ "api-segment {", " gid vpp", "}" ]) return tcp.rstrip('\n') tcp = '\n'.join([ "# TCP stack-related configuration parameters", "# expecting {:d} client sessions, {:d} server sessions\n".format( aos, pos), "heapsize 4g\n", "api-segment {", " global-size 2000M", " api-size 1G", "}\n", "session {", " event-queue-length {:d}".format(aos + pos), " preallocated-sessions {:d}".format(aos + pos), " v4-session-table-buckets {:d}".format((aos + pos) // 4), " v4-session-table-memory 3g\n" ]) if aos > 0: tcp = tcp + " v4-halfopen-table-buckets {:d}".format( (aos + pos) // 4) + "\n" tcp = tcp + " v4-halfopen-table-memory 3g\n" tcp = tcp + " local-endpoints-table-buckets {:d}".format( (aos + pos) // 4) + "\n" tcp = tcp + " local-endpoints-table-memory 3g\n" tcp = tcp + "}\n\n" tcp = tcp + "tcp {\n" tcp = tcp + " preallocated-connections {:d}".format(aos + pos) + "\n" if aos > 0: tcp = tcp + " preallocated-half-open-connections {:d}".format( aos) + "\n" tcp = tcp + "}\n\n" return tcp.rstrip('\n') def apply_vpp_startup(self): """ Apply the vpp startup configration """ # Apply the VPP startup configruation for i in self._nodes.items(): node = i[1] # Get the startup file rootdir = node['rootdir'] sfile = rootdir + node['vpp']['startup_config_file'] # Get the buffers devices = self._apply_vpp_devices(node) # Get the CPU config cpu = self._apply_vpp_cpu(node) # Get the buffer configuration buffers = self._apply_buffers(node) # Get the TCP configuration, if any tcp = self._apply_vpp_tcp(node) # Make a backup if needed self._autoconfig_backup_file(sfile) # Get the template tfile = sfile + '.template' (ret, stdout, stderr) = \ VPPUtil.exec_command('cat {}'.format(tfile)) if ret != 0: raise RuntimeError('Executing cat command failed to node {}'. format(node['host'])) startup = stdout.format(cpu=cpu, buffers=buffers, devices=devices, tcp=tcp) (ret, stdout, stderr) = \ VPPUtil.exec_command('rm {}'.format(sfile)) if ret != 0: logging.debug(stderr) cmd = "sudo cat > {0} << EOF\n{1}\n".format(sfile, startup) (ret, stdout, stderr) = VPPUtil.exec_command(cmd) if ret != 0: raise RuntimeError('Writing config failed node {}'. format(node['host'])) def apply_grub_cmdline(self): """ Apply the grub cmdline """ for i in self._nodes.items(): node = i[1] # Get the isolated CPUs other_workers = node['cpu']['other_workers'] vpp_workers = node['cpu']['vpp_workers'] if 'vpp_main_core' in node['cpu']: vpp_main_core = node['cpu']['vpp_main_core'] else: vpp_main_core = 0 all_workers = [] if other_workers is not None: all_workers = [other_workers] if vpp_main_core != 0: all_workers += [(vpp_main_core, vpp_main_core)] all_workers += vpp_workers isolated_cpus = '' for idx, worker in enumerate(all_workers): if worker is None: continue if idx > 0: isolated_cpus += ',' if worker[0] == worker[1]: isolated_cpus += "{}".format(worker[0]) else: isolated_cpus += "{}-{}".format(worker[0], worker[1]) vppgrb = VppGrubUtil(node) current_cmdline = vppgrb.get_current_cmdline() if 'grub' not in node: node['grub'] = {} node['grub']['current_cmdline'] = current_cmdline node['grub']['default_cmdline'] = \ vppgrb.apply_cmdline(node, isolated_cpus) self.updateconfig() def get_hugepages(self): """ Get the hugepage configuration """ for i in self._nodes.items(): node = i[1] hpg = VppHugePageUtil(node) max_map_count, shmmax = hpg.get_huge_page_config() node['hugepages']['max_map_count'] = max_map_count node['hugepages']['shmax'] = shmmax total, free, size, memtotal, memfree = hpg.get_actual_huge_pages() node['hugepages']['actual_total'] = total node['hugepages']['free'] = free node['hugepages']['size'] = size node['hugepages']['memtotal'] = memtotal node['hugepages']['memfree'] = memfree self.updateconfig() def get_grub(self): """ Get the grub configuration """ for i in self._nodes.items(): node = i[1] vppgrb = VppGrubUtil(node) current_cmdline = vppgrb.get_current_cmdline() default_cmdline = vppgrb.get_default_cmdline() # Get the total number of isolated CPUs current_iso_cpus = 0 iso_cpur = re.findall(r'isolcpus=[\w+\-,]+', current_cmdline) iso_cpurl = len(iso_cpur) if iso_cpurl > 0: iso_cpu_str = iso_cpur[0] iso_cpu_str = iso_cpu_str.split('=')[1] iso_cpul = iso_cpu_str.split(',') for iso_cpu in iso_cpul: isocpuspl = iso_cpu.split('-') if len(isocpuspl) == 1: current_iso_cpus += 1 else: first = int(isocpuspl[0]) second = int(isocpuspl[1]) if first == second: current_iso_cpus += 1 else: current_iso_cpus += second - first if 'grub' not in node: node['grub'] = {} node['grub']['current_cmdline'] = current_cmdline node['grub']['default_cmdline'] = default_cmdline node['grub']['current_iso_cpus'] = current_iso_cpus self.updateconfig() @staticmethod def _get_device(node): """ Get the device configuration for a single node :param node: Node dictionary with cpuinfo. :type node: dict """ vpp = VppPCIUtil(node) vpp.get_all_devices() # Save the device information node['devices'] = {} node['devices']['dpdk_devices'] = vpp.get_dpdk_devices() node['devices']['kernel_devices'] = vpp.get_kernel_devices() node['devices']['other_devices'] = vpp.get_other_devices() node['devices']['linkup_devices'] = vpp.get_link_up_devices() def get_devices_per_node(self): """ Get the device configuration for all the nodes """ for i in self._nodes.items(): node = i[1] # Update the interface data self._get_device(node) self.updateconfig() @staticmethod def get_cpu_layout(node): """ Get the cpu layout using lscpu -p get the cpu layout. Returns a list with each item representing a single cpu. :param node: Node dictionary. :type node: dict :returns: The cpu layout :rtype: list """ cmd = 'lscpu -p' (ret, stdout, stderr) = VPPUtil.exec_command(cmd) if ret != 0: raise RuntimeError('{} failed on node {} {}'. format(cmd, node['host'], stderr)) pcpus = [] lines = stdout.split('\n') for line in lines: if line == '' or line[0] == '#': continue linesplit = line.split(',') layout = {'cpu': linesplit[0], 'core': linesplit[1], 'socket': linesplit[2], 'node': linesplit[3]} # cpu, core, socket, node pcpus.append(layout) return pcpus def get_cpu(self): """ Get the cpu configuration """ # Get the CPU layout CpuUtils.get_cpu_layout_from_all_nodes(self._nodes) for i in self._nodes.items(): node = i[1] # Get the cpu layout layout = self.get_cpu_layout(node) node['cpu']['layout'] = layout cpuinfo = node['cpuinfo'] smt_enabled = CpuUtils.is_smt_enabled(cpuinfo) node['cpu']['smt_enabled'] = smt_enabled # We don't want to write the cpuinfo node['cpuinfo'] = "" # Write the config self.updateconfig() def discover(self): """ Get the current system configuration. """ # Get the Huge Page configuration self.get_hugepages() # Get the device configuration self.get_devices_per_node() # Get the CPU configuration self.get_cpu() # Get the current grub cmdline self.get_grub() def _modify_cpu_questions(self, node, total_cpus, numa_nodes): """ Ask the user questions related to the cpu configuration. :param node: Node dictionary :param total_cpus: The total number of cpus in the system :param numa_nodes: The list of numa nodes in the system :type node: dict :type total_cpus: int :type numa_nodes: list """ print("\nYour system has {} core(s) and {} Numa Nodes.". format(total_cpus, len(numa_nodes))) print("To begin, we suggest not reserving any cores for " "VPP or other processes.") print("Then to improve performance start reserving cores and " "adding queues as needed.") # Leave 1 for the general system total_cpus -= 1 max_vpp_cpus = min(total_cpus, 4) total_vpp_cpus = 0 if max_vpp_cpus > 0: question = "\nHow many core(s) shall we reserve for " \ "VPP [0-{}][0]? ".format(max_vpp_cpus) total_vpp_cpus = self._ask_user_range(question, 0, max_vpp_cpus, 0) node['cpu']['total_vpp_cpus'] = total_vpp_cpus total_other_cpus = 0 max_other_cores = total_cpus - total_vpp_cpus if max_other_cores > 0: question = 'How many core(s) do you want to reserve for ' \ 'processes other than VPP? [0-{}][0]? '. format(str(max_other_cores)) total_other_cpus = self._ask_user_range(question, 0, max_other_cores, 0) node['cpu']['total_other_cpus'] = total_other_cpus max_main_cpus = total_cpus - total_vpp_cpus - total_other_cpus reserve_vpp_main_core = False if max_main_cpus > 0: question = "Should we reserve 1 core for the VPP Main thread? " question += "[y/N]? " answer = self._ask_user_yn(question, 'n') if answer == 'y': reserve_vpp_main_core = True node['cpu']['reserve_vpp_main_core'] = reserve_vpp_main_core node['cpu']['vpp_main_core'] = 0 question = "How many RX queues per port shall we use for " \ "VPP [1-4][1]? ".format(max_vpp_cpus) total_rx_queues = self._ask_user_range(question, 1, 4, 1) node['cpu']['total_rx_queues'] = total_rx_queues def modify_cpu(self, ask_questions=True): """ Modify the cpu configuration, asking for the user for the values. :param ask_questions: When true ask the user for config parameters """ # Get the CPU layout CpuUtils.get_cpu_layout_from_all_nodes(self._nodes) for i in self._nodes.items(): node = i[1] total_cpus = 0 total_cpus_per_slice = 0 cpus_per_node = {} numa_nodes = [] cores = [] cpu_layout = self.get_cpu_layout(node) # Assume the number of cpus per slice is always the same as the # first slice first_node = '0' for cpu in cpu_layout: if cpu['node'] != first_node: break total_cpus_per_slice += 1 # Get the total number of cpus, cores, and numa nodes from the # cpu layout for cpul in cpu_layout: numa_node = cpul['node'] core = cpul['core'] cpu = cpul['cpu'] total_cpus += 1 if numa_node not in cpus_per_node: cpus_per_node[numa_node] = [] cpuperslice = int(cpu) % total_cpus_per_slice if cpuperslice == 0: cpus_per_node[numa_node].append((int(cpu), int(cpu) + total_cpus_per_slice - 1)) if numa_node not in numa_nodes: numa_nodes.append(numa_node) if core not in cores: cores.append(core) node['cpu']['cpus_per_node'] = cpus_per_node # Ask the user some questions if ask_questions and total_cpus >= 4: self._modify_cpu_questions(node, total_cpus, numa_nodes) # Populate the interfaces with the numa node if 'interfaces' in node: ikeys = node['interfaces'].keys() VPPUtil.get_interfaces_numa_node(node, *tuple(ikeys)) # We don't want to write the cpuinfo node['cpuinfo'] = "" # Write the configs self._update_auto_config() self.updateconfig() def _modify_other_devices(self, node, other_devices, kernel_devices, dpdk_devices): """ Modify the devices configuration, asking for the user for the values. """ odevices_len = len(other_devices) if odevices_len > 0: print("\nThese device(s) are currently NOT being used " "by VPP or the OS.\n") VppPCIUtil.show_vpp_devices(other_devices, show_interfaces=False) question = "\nWould you like to give any of these devices" question += " back to the OS [Y/n]? " answer = self._ask_user_yn(question, 'Y') if answer == 'y': vppd = {} for dit in other_devices.items(): dvid = dit[0] device = dit[1] question = "Would you like to use device {} for". \ format(dvid) question += " the OS [y/N]? " answer = self._ask_user_yn(question, 'n') if answer == 'y': if 'unused' in device and len( device['unused']) != 0 and \ device['unused'][0] != '': driver = device['unused'][0] ret = VppPCIUtil.bind_vpp_device( node, driver, dvid) if ret: logging.debug( 'Could not bind device {}'.format(dvid)) else: vppd[dvid] = device for dit in vppd.items(): dvid = dit[0] device = dit[1] kernel_devices[dvid] = device del other_devices[dvid] odevices_len = len(other_devices) if odevices_len > 0: print("\nThese device(s) are still NOT being used " "by VPP or the OS.\n") VppPCIUtil.show_vpp_devices(other_devices, show_interfaces=False) question = "\nWould you like use any of these for VPP [y/N]? " answer = self._ask_user_yn(question, 'N') if answer == 'y': vppd = {} for dit in other_devices.items(): dvid = dit[0] device = dit[1] question = "Would you like to use device {} ".format(dvid) question += "for VPP [y/N]? " answer = self._ask_user_yn(question, 'n') if answer == 'y': vppd[dvid] = device for dit in vppd.items(): dvid = dit[0] device = dit[1] if 'unused' in device and len(device['unused']) != 0 and \ device['unused'][0] != '': driver = device['unused'][0] logging.debug( 'Binding device {} to driver {}'.format(dvid, driver)) ret = VppPCIUtil.bind_vpp_device(node, driver, dvid) if ret: logging.debug( 'Could not bind device {}'.format(dvid)) else: dpdk_devices[dvid] = device del other_devices[dvid] def update_interfaces_config(self): """ Modify the interfaces directly from the config file. """ for i in self._nodes.items(): node = i[1] devices = node['devices'] all_devices = devices['other_devices'] all_devices.update(devices['dpdk_devices']) all_devices.update(devices['kernel_devices']) current_ifcs = {} interfaces = {} if 'interfaces' in node: current_ifcs = node['interfaces'] if current_ifcs: for ifc in current_ifcs.values(): dvid = ifc['pci_address'] if dvid in all_devices: VppPCIUtil.vpp_create_interface(interfaces, dvid, all_devices[dvid]) node['interfaces'] = interfaces self.updateconfig() def modify_devices(self): """ Modify the devices configuration, asking for the user for the values. """ for i in self._nodes.items(): node = i[1] devices = node['devices'] other_devices = devices['other_devices'] kernel_devices = devices['kernel_devices'] dpdk_devices = devices['dpdk_devices'] if other_devices: self._modify_other_devices(node, other_devices, kernel_devices, dpdk_devices) # Get the devices again for this node self._get_device(node) devices = node['devices'] kernel_devices = devices['kernel_devices'] dpdk_devices = devices['dpdk_devices'] klen = len(kernel_devices) if klen > 0: print("\nThese devices are safe to be used with VPP.\n") VppPCIUtil.show_vpp_devices(kernel_devices) question = "\nWould you like to use any of these " \ "device(s) for VPP [y/N]? " answer = self._ask_user_yn(question, 'n') if answer == 'y': vppd = {} for dit in kernel_devices.items(): dvid = dit[0] device = dit[1] question = "Would you like to use device {} ".format(dvid) question += "for VPP [y/N]? " answer = self._ask_user_yn(question, 'n') if answer == 'y': vppd[dvid] = device for dit in vppd.items(): dvid = dit[0] device = dit[1] if 'unused' in device and len( device['unused']) != 0 and device['unused'][0] != '': driver = device['unused'][0] question = "Would you like to bind the driver {} for {} [y/N]? ".format(driver, dvid) answer = self._ask_user_yn(question, 'n') if answer == 'y': logging.debug('Binding device {} to driver {}'.format(dvid, driver)) ret = VppPCIUtil.bind_vpp_device(node, driver, dvid) if ret: logging.debug('Could not bind device {}'.format(dvid)) dpdk_devices[dvid] = device del kernel_devices[dvid] dlen = len(dpdk_devices) if dlen > 0: print("\nThese device(s) are already using DPDK.\n") VppPCIUtil.show_vpp_devices(dpdk_devices, show_interfaces=False) question = "\nWould you like to remove any of " question += "these device(s) [y/N]? " answer = self._ask_user_yn(question, 'n') if answer == 'y': vppdl = {} for dit in dpdk_devices.items(): dvid = dit[0] device = dit[1] question = "Would you like to remove {} [y/N]? ". \ format(dvid) answer = self._ask_user_yn(question, 'n') if answer == 'y': vppdl[dvid] = device for dit in vppdl.items(): dvid = dit[0] device = dit[1] if 'unused' in device and len( device['unused']) != 0 and device['unused'][0] != '': driver = device['unused'][0] logging.debug( 'Binding device {} to driver {}'.format( dvid, driver)) ret = VppPCIUtil.bind_vpp_device(node, driver, dvid) if ret: logging.debug( 'Could not bind device {}'.format(dvid)) else: kernel_devices[dvid] = device del dpdk_devices[dvid] interfaces = {} for dit in dpdk_devices.items(): dvid = dit[0] device = dit[1] VppPCIUtil.vpp_create_interface(interfaces, dvid, device) node['interfaces'] = interfaces self._update_auto_config() self.updateconfig() def modify_huge_pages(self): """ Modify the huge page configuration, asking for the user for the values. """ for i in self._nodes.items(): node = i[1] total = node['hugepages']['actual_total'] free = node['hugepages']['free'] size = node['hugepages']['size'] memfree = node['hugepages']['memfree'].split(' ')[0] hugesize = int(size.split(' ')[0]) # The max number of huge pages should be no more than # 70% of total free memory maxpages = (int(memfree) * MAX_PERCENT_FOR_HUGE_PAGES // 100) // hugesize print("\nThere currently {} {} huge pages free.".format( free, size)) question = "Do you want to reconfigure the number of " \ "huge pages [y/N]? " answer = self._ask_user_yn(question, 'n') if answer == 'n': node['hugepages']['total'] = total continue print("\nThere currently a total of {} huge pages.". format(total)) question = "How many huge pages do you want [{} - {}][{}]? ". \ format(MIN_TOTAL_HUGE_PAGES, maxpages, MIN_TOTAL_HUGE_PAGES) answer = self._ask_user_range(question, 1024, maxpages, 1024) node['hugepages']['total'] = str(answer) # Update auto-config.yaml self._update_auto_config() # Rediscover just the hugepages self.get_hugepages() def get_tcp_params(self): """ Get the tcp configuration """ # maybe nothing to do here? self.updateconfig() def acquire_tcp_params(self): """ Ask the user for TCP stack configuration parameters """ for i in self._nodes.items(): node = i[1] question = "\nHow many active-open / tcp client sessions are " \ "expected [0-10000000][0]? " answer = self._ask_user_range(question, 0, 10000000, 0) # Less than 10K is equivalent to 0 if int(answer) < 10000: answer = 0 node['tcp']['active_open_sessions'] = answer question = "How many passive-open / tcp server sessions are " \ "expected [0-10000000][0]? " answer = self._ask_user_range(question, 0, 10000000, 0) # Less than 10K is equivalent to 0 if int(answer) < 10000: answer = 0 node['tcp']['passive_open_sessions'] = answer # Update auto-config.yaml self._update_auto_config() # Rediscover tcp parameters self.get_tcp_params() @staticmethod def patch_qemu(node): """ Patch qemu with the correct patches. :param node: Node dictionary :type node: dict """ print('\nWe are patching the node "{}":\n'.format(node['host'])) QemuUtils.build_qemu(node, force_install=True, apply_patch=True) @staticmethod def cpu_info(node): """ print the CPU information """ cpu = CpuUtils.get_cpu_info_per_node(node) item = 'Model name' if item in cpu: print("{:>20}: {}".format(item, cpu[item])) item = 'CPU(s)' if item in cpu: print("{:>20}: {}".format(item, cpu[item])) item = 'Thread(s) per core' if item in cpu: print("{:>20}: {}".format(item, cpu[item])) item = 'Core(s) per socket' if item in cpu: print("{:>20}: {}".format(item, cpu[item])) item = 'Socket(s)' if item in cpu: print("{:>20}: {}".format(item, cpu[item])) item = 'NUMA node(s)' numa_nodes = 0 if item in cpu: numa_nodes = int(cpu[item]) for i in range(0, numa_nodes): item = "NUMA node{} CPU(s)".format(i) print("{:>20}: {}".format(item, cpu[item])) item = 'CPU max MHz' if item in cpu: print("{:>20}: {}".format(item, cpu[item])) item = 'CPU min MHz' if item in cpu: print("{:>20}: {}".format(item, cpu[item])) if node['cpu']['smt_enabled']: smt = 'Enabled' else: smt = 'Disabled' print("{:>20}: {}".format('SMT', smt)) # VPP Threads print("\nVPP Threads: (Name: Cpu Number)") vpp_processes = cpu['vpp_processes'] for i in vpp_processes.items(): print(" {:10}: {:4}".format(i[0], i[1])) @staticmethod def device_info(node): """ Show the device information. """ if 'cpu' in node and 'total_mbufs' in node['cpu']: total_mbufs = node['cpu']['total_mbufs'] if total_mbufs != 0: print("Total Number of Buffers: {}".format(total_mbufs)) vpp = VppPCIUtil(node) vpp.get_all_devices() linkup_devs = vpp.get_link_up_devices() if len(linkup_devs): print("\nDevices with link up (can not be used with VPP):") vpp.show_vpp_devices(linkup_devs, show_header=False) # for dev in linkup_devs: # print (" " + dev) kernel_devs = vpp.get_kernel_devices() if len(kernel_devs): print("\nDevices bound to kernel drivers:") vpp.show_vpp_devices(kernel_devs, show_header=False) else: print("\nNo devices bound to kernel drivers") dpdk_devs = vpp.get_dpdk_devices() if len(dpdk_devs): print("\nDevices bound to DPDK drivers:") vpp.show_vpp_devices(dpdk_devs, show_interfaces=True, show_header=False) else: print("\nNo devices bound to DPDK drivers") other_devs = vpp.get_other_devices() if len(other_devs): print("\nDevices not bound to Kernel or DPDK drivers:") vpp.show_vpp_devices(other_devs, show_interfaces=True, show_header=False) else: print("\nNo devices not bound to Kernel or DPDK drivers") vpputl = VPPUtil() interfaces = vpputl.get_hardware(node) if interfaces == {}: return print("\nDevices in use by VPP:") if len(interfaces.items()) < 2: print("None") return print("{:30} {:4} {:4} {:7} {:4} {:7}". format('Name', 'Numa', 'RXQs', 'RXDescs', 'TXQs', 'TXDescs')) for intf in sorted(interfaces.items()): name = intf[0] value = intf[1] if name == 'local0': continue numa = rx_qs = rx_ds = tx_qs = tx_ds = '' if 'numa' in value: numa = int(value['numa']) if 'rx queues' in value: rx_qs = int(value['rx queues']) if 'rx descs' in value: rx_ds = int(value['rx descs']) if 'tx queues' in value: tx_qs = int(value['tx queues']) if 'tx descs' in value: tx_ds = int(value['tx descs']) print("{:30} {:>4} {:>4} {:>7} {:>4} {:>7}". format(name, numa, rx_qs, rx_ds, tx_qs, tx_ds)) @staticmethod def hugepage_info(node): """ Show the huge page information. """ hpg = VppHugePageUtil(node) hpg.show_huge_pages() @staticmethod def has_interfaces(node): """ Check for interfaces, return tru if there is at least one :returns: boolean """ if 'interfaces' in node and len(node['interfaces']): return True else: return False @staticmethod def min_system_resources(node): """ Check the system for basic minimum resources, return true if there is enough. :returns: boolean """ min_sys_res = True # CPUs if 'layout' in node['cpu']: total_cpus = len(node['cpu']['layout']) if total_cpus < 2: print("\nThere is only {} CPU(s) available on this system. " "This is not enough to run VPP.".format(total_cpus)) min_sys_res = False # System Memory if 'free' in node['hugepages'] and \ 'memfree' in node['hugepages'] and \ 'size' in node['hugepages']: free = node['hugepages']['free'] memfree = float(node['hugepages']['memfree'].split(' ')[0]) hugesize = float(node['hugepages']['size'].split(' ')[0]) memhugepages = MIN_TOTAL_HUGE_PAGES * hugesize percentmemhugepages = (memhugepages / memfree) * 100 if free is '0' and \ percentmemhugepages > MAX_PERCENT_FOR_HUGE_PAGES: print( "\nThe System has only {} of free memory. You will not " "be able to allocate enough Huge Pages for VPP.".format( int( memfree)) ) min_sys_res = False return min_sys_res def sys_info(self): """ Print the system information """ for i in self._nodes.items(): print("\n==============================") name = i[0] node = i[1] print("NODE: {}\n".format(name)) # CPU print("CPU:") self.cpu_info(node) # Grub print("\nGrub Command Line:") if 'grub' in node: print(" Current: {}".format( node['grub']['current_cmdline'])) print(" Configured: {}".format( node['grub']['default_cmdline'])) # Huge Pages print("\nHuge Pages:") self.hugepage_info(node) # Devices print("\nDevices:") self.device_info(node) # Status print("\nVPP Service Status:") state, errors = VPPUtil.status(node) print(" {}".format(state)) for e in errors: print(" {}".format(e)) # Minimum system resources self.min_system_resources(node) print("\n==============================") def _ipv4_interface_setup_questions(self, node): """ Ask the user some questions and get a list of interfaces and IPv4 addresses associated with those interfaces :param node: Node dictionary. :type node: dict :returns: A list or interfaces with ip addresses :rtype: dict """ vpputl = VPPUtil() interfaces = vpputl.get_hardware(node) if interfaces == {}: return interfaces_with_ip = [] for intf in sorted(interfaces.items()): name = intf[0] if name == 'local0': continue question = "Would you like add address to " \ "interface {} [Y/n]? ".format(name) answer = self._ask_user_yn(question, 'y') if answer == 'y': address = {} addr = self._ask_user_ipv4() address['name'] = name address['addr'] = addr interfaces_with_ip.append(address) return interfaces_with_ip def ipv4_interface_setup(self): """ After asking the user some questions, get a list of interfaces and IPv4 addresses associated with those interfaces """ for i in self._nodes.items(): node = i[1] # Show the current interfaces with IP addresses current_ints = VPPUtil.get_int_ip(node) if current_ints != {}: print("\nThese are the current interfaces with IP addresses:") for items in sorted(current_ints.items()): name = items[0] value = items[1] if 'address' not in value: address = 'Not Set' else: address = value['address'] print("{:30} {:20} {:10}".format(name, address, value['state'])) question = "\nWould you like to keep this configuration " \ "[Y/n]? " answer = self._ask_user_yn(question, 'y') if answer == 'y': continue else: print("\nThere are currently no interfaces with IP " "addresses.") # Create a script that add the ip addresses to the interfaces # and brings the interfaces up ints_with_addrs = self._ipv4_interface_setup_questions(node) content = '' for ints in ints_with_addrs: name = ints['name'] addr = ints['addr'] setipstr = 'set int ip address {} {}\n'.format(name, addr) setintupstr = 'set int state {} up\n'.format(name) content += setipstr + setintupstr # Write the content to the script rootdir = node['rootdir'] filename = rootdir + '/vpp/vpp-config/scripts/set_int_ipv4_and_up' with open(filename, 'w+') as sfile: sfile.write(content) # Execute the script cmd = 'vppctl exec {}'.format(filename) (ret, stdout, stderr) = VPPUtil.exec_command(cmd) if ret != 0: logging.debug(stderr) print("\nA script as been created at {}".format(filename)) print("This script can be run using the following:") print("vppctl exec {}\n".format(filename)) def _create_vints_questions(self, node): """ Ask the user some questions and get a list of interfaces and IPv4 addresses associated with those interfaces :param node: Node dictionary. :type node: dict :returns: A list or interfaces with ip addresses :rtype: list """ vpputl = VPPUtil() interfaces = vpputl.get_hardware(node) if interfaces == {}: return [] # First delete all the Virtual interfaces for intf in sorted(interfaces.items()): name = intf[0] if name[:7] == 'Virtual': cmd = 'vppctl delete vhost-user {}'.format(name) (ret, stdout, stderr) = vpputl.exec_command(cmd) if ret != 0: logging.debug('{} failed on node {} {}'.format( cmd, node['host'], stderr)) # Create a virtual interface, for each interface the user wants to use interfaces = vpputl.get_hardware(node) if interfaces == {}: return [] interfaces_with_virtual_interfaces = [] inum = 1 for intf in sorted(interfaces.items()): name = intf[0] if name == 'local0': continue question = "Would you like connect this interface {} to " \ "the VM [Y/n]? ".format(name) answer = self._ask_user_yn(question, 'y') if answer == 'y': sockfilename = '/var/run/vpp/{}.sock'.format( name.replace('/', '_')) if os.path.exists(sockfilename): os.remove(sockfilename) cmd = 'vppctl create vhost-user socket {} server'.format( sockfilename) (ret, stdout, stderr) = vpputl.exec_command(cmd) if ret != 0: raise RuntimeError( "Couldn't execute the command {}, {}.".format(cmd, stderr)) vintname = stdout.rstrip('\r\n') cmd = 'chmod 777 {}'.format(sockfilename) (ret, stdout, stderr) = vpputl.exec_command(cmd) if ret != 0: raise RuntimeError( "Couldn't execute the command {}, {}.".format(cmd, stderr)) interface = {'name': name, 'virtualinterface': '{}'.format(vintname), 'bridge': '{}'.format(inum)} inum += 1 interfaces_with_virtual_interfaces.append(interface) return interfaces_with_virtual_interfaces def create_and_bridge_virtual_interfaces(self): """ After asking the user some questions, create a VM and connect the interfaces to VPP interfaces """ for i in self._nodes.items(): node = i[1] # Show the current bridge and interface configuration print("\nThis the current bridge configuration:") VPPUtil.show_bridge(node) question = "\nWould you like to keep this configuration [Y/n]? " answer = self._ask_user_yn(question, 'y') if answer == 'y': continue # Create a script that builds a bridge configuration with # physical interfaces and virtual interfaces ints_with_vints = self._create_vints_questions(node) content = '' for intf in ints_with_vints: vhoststr = '\n'.join([ 'comment { The following command creates the socket }', 'comment { and returns a virtual interface }', 'comment {{ create vhost-user socket ' '/var/run/vpp/sock{}.sock server }}\n'.format( intf['bridge']) ]) setintdnstr = 'set interface state {} down\n'.format( intf['name']) setintbrstr = 'set interface l2 bridge {} {}\n'.format( intf['name'], intf['bridge']) setvintbrstr = 'set interface l2 bridge {} {}\n'.format( intf['virtualinterface'], intf['bridge']) # set interface state VirtualEthernet/0/0/0 up setintvststr = 'set interface state {} up\n'.format( intf['virtualinterface']) # set interface state VirtualEthernet/0/0/0 down setintupstr = 'set interface state {} up\n'.format( intf['name']) content += vhoststr + setintdnstr + setintbrstr + setvintbrstr + setintvststr + setintupstr # Write the content to the script rootdir = node['rootdir'] filename = rootdir + '/vpp/vpp-config/scripts/create_vms_and_connect_to_vpp' with open(filename, 'w+') as sfile: sfile.write(content) # Execute the script cmd = 'vppctl exec {}'.format(filename) (ret, stdout, stderr) = VPPUtil.exec_command(cmd) if ret != 0: logging.debug(stderr) print("\nA script as been created at {}".format(filename)) print("This script can be run using the following:") print("vppctl exec {}\n".format(filename)) def _iperf_vm_questions(self, node): """ Ask the user some questions and get a list of interfaces and IPv4 addresses associated with those interfaces :param node: Node dictionary. :type node: dict :returns: A list or interfaces with ip addresses :rtype: list """ vpputl = VPPUtil() interfaces = vpputl.get_hardware(node) if interfaces == {}: return [] # First delete all the Virtual interfaces for intf in sorted(interfaces.items()): name = intf[0] if name[:7] == 'Virtual': cmd = 'vppctl delete vhost-user {}'.format(name) (ret, stdout, stderr) = vpputl.exec_command(cmd) if ret != 0: logging.debug('{} failed on node {} {}'.format( cmd, node['host'], stderr)) # Create a virtual interface, for each interface the user wants to use interfaces = vpputl.get_hardware(node) if interfaces == {}: return [] interfaces_with_virtual_interfaces = [] inum = 1 while True: print('\nPlease pick one interface to connect to the iperf VM.') for intf in sorted(interfaces.items()): name = intf[0] if name == 'local0': continue question = "Would you like connect this interface {} to " \ "the VM [y/N]? ".format(name) answer = self._ask_user_yn(question, 'n') if answer == 'y': self._sockfilename = '/var/run/vpp/{}.sock'.format( name.replace('/', '_')) if os.path.exists(self._sockfilename): os.remove(self._sockfilename) cmd = 'vppctl create vhost-user socket {} server'.format( self._sockfilename) (ret, stdout, stderr) = vpputl.exec_command(cmd) if ret != 0: raise RuntimeError( "Couldn't execute the command {}, {}.".format( cmd, stderr)) vintname = stdout.rstrip('\r\n') cmd = 'chmod 777 {}'.format(self._sockfilename) (ret, stdout, stderr) = vpputl.exec_command(cmd) if ret != 0: raise RuntimeError( "Couldn't execute the command {}, {}.".format( cmd, stderr)) interface = {'name': name, 'virtualinterface': '{}'.format(vintname), 'bridge': '{}'.format(inum)} inum += 1 interfaces_with_virtual_interfaces.append(interface) return interfaces_with_virtual_interfaces def create_and_bridge_iperf_virtual_interface(self): """ After asking the user some questions, and create and bridge a virtual interface to be used with iperf VM """ for i in self._nodes.items(): node = i[1] # Show the current bridge and interface configuration print("\nThis the current bridge configuration:") ifaces = VPPUtil.show_bridge(node) question = "\nWould you like to keep this configuration [Y/n]? " answer = self._ask_user_yn(question, 'y') if answer == 'y': self._sockfilename = '/var/run/vpp/{}.sock'.format( ifaces[0]['name'].replace('/', '_')) if os.path.exists(self._sockfilename): continue # Create a script that builds a bridge configuration with # physical interfaces and virtual interfaces ints_with_vints = self._iperf_vm_questions(node) content = '' for intf in ints_with_vints: vhoststr = '\n'.join([ 'comment { The following command creates the socket }', 'comment { and returns a virtual interface }', 'comment {{ create vhost-user socket ' '/var/run/vpp/sock{}.sock server }}\n'.format( intf['bridge']) ]) setintdnstr = 'set interface state {} down\n'.format( intf['name']) setintbrstr = 'set interface l2 bridge {} {}\n'.format( intf['name'], intf['bridge']) setvintbrstr = 'set interface l2 bridge {} {}\n'.format( intf['virtualinterface'], intf['bridge']) # set interface state VirtualEthernet/0/0/0 up setintvststr = 'set interface state {} up\n'.format( intf['virtualinterface']) # set interface state VirtualEthernet/0/0/0 down setintupstr = 'set interface state {} up\n'.format( intf['name']) content += vhoststr + setintdnstr + setintbrstr + setvintbrstr + setintvststr + setintupstr # Write the content to the script rootdir = node['rootdir'] filename = rootdir + '/vpp/vpp-config/scripts/create_iperf_vm' with open(filename, 'w+') as sfile: sfile.write(content) # Execute the script cmd = 'vppctl exec {}'.format(filename) (ret, stdout, stderr) = VPPUtil.exec_command(cmd) if ret != 0: logging.debug(stderr) print("\nA script as been created at {}".format(filename)) print("This script can be run using the following:") print("vppctl exec {}\n".format(filename)) @staticmethod def destroy_iperf_vm(name): """ After asking the user some questions, create a VM and connect the interfaces to VPP interfaces :param name: The name of the VM to be be destroyed :type name: str """ cmd = 'virsh list' (ret, stdout, stderr) = VPPUtil.exec_command(cmd) if ret != 0: logging.debug(stderr) raise RuntimeError( "Couldn't execute the command {} : {}".format(cmd, stderr)) if re.findall(name, stdout): cmd = 'virsh destroy {}'.format(name) (ret, stdout, stderr) = VPPUtil.exec_command(cmd) if ret != 0: logging.debug(stderr) raise RuntimeError( "Couldn't execute the command {} : {}".format( cmd, stderr)) def create_iperf_vm(self, vmname): """ After asking the user some questions, create a VM and connect the interfaces to VPP interfaces """ # Read the iperf VM template file distro = VPPUtil.get_linux_distro() if distro[0] == 'Ubuntu': tfilename = \ '{}/vpp/vpp-config/configs/iperf-ubuntu.xml.template'.format( self._rootdir) else: tfilename = \ '{}/vpp/vpp-config/configs/iperf-centos.xml.template'.format( self._rootdir) with open(tfilename, 'r') as tfile: tcontents = tfile.read() tfile.close() # Add the variables imagename = '{}/vpp/vpp-config/{}'.format( self._rootdir, IPERFVM_IMAGE) isoname = '{}/vpp/vpp-config/{}'.format(self._rootdir, IPERFVM_ISO) tcontents = tcontents.format(vmname=vmname, imagename=imagename, isoname=isoname, vhostsocketname=self._sockfilename) # Write the xml ifilename = '{}/vpp/vpp-config/{}'.format(self._rootdir, IPERFVM_XML) with open(ifilename, 'w+') as ifile: ifile.write(tcontents) ifile.close() cmd = 'virsh create {}'.format(ifilename) (ret, stdout, stderr) = VPPUtil.exec_command(cmd) if ret != 0: logging.debug(stderr) raise RuntimeError( "Couldn't execute the command {} : {}".format(cmd, stderr))