summaryrefslogtreecommitdiffstats
path: root/src/vnet
diff options
context:
space:
mode:
authorNeale Ranns <nranns@cisco.com>2018-12-06 13:46:49 +0000
committerDamjan Marion <dmarion@me.com>2018-12-07 15:09:37 +0000
commit521a8d7df423a0b5aaf259d49ca9230705bc25ee (patch)
tree12559229002f31b289adb15460b967a3d10900f3 /src/vnet
parentab86f86e7c29393fa1da81b5f86296bd5fcb7420 (diff)
FIB recusrion loop checks traverse midchain adjacencies
if a tunnel's destination address is reachable through the tunnel (see example config belwo) then search for and detect a recursion loop and don't stack the adjacency. Otherwise this results in a nasty surprise. DBGvpp# loop cre DBGvpp# set int state loop0 up DBGvpp# set int ip addr loop0 10.0.0.1/24 DBGvpp# create gre tunnel src 10.0.0.1 dst 1.1.1.1 DBGvpp# set int state gre0 up DBGvpp# set int unnum gre0 use loop0 DBGvpp# ip route 1.1.1.1/32 via gre0 DBGvpp# sh ip fib 1.1.1.1 ipv4-VRF:0, fib_index:0, flow hash:[src dst sport dport proto ] locks:[src:plugin-hi:2, src:default-route:1, ] 1.1.1.1/32 fib:0 index:11 locks:4 <<< this is entry #11 src:CLI refs:1 entry-flags:attached, src-flags:added,contributing,active, path-list:[14] locks:2 flags:shared,looped, uPRF-list:12 len:1 itfs:[2, ] path:[14] pl-index:14 ip4 weight=1 pref=0 attached-nexthop: oper-flags:recursive-loop,resolved, cfg-flags:attached, 1.1.1.1 gre0 (p2p) [@0]: ipv4 via 0.0.0.0 gre0: mtu:9000 4500000000000000fe2fb0cc0a0000010101010100000800 stacked-on entry:11: <<<< and the midchain forwards via entry #11 [@2]: dpo-drop ip4 src:recursive-resolution refs:1 src-flags:added, cover:-1 forwarding: unicast-ip4-chain [@0]: dpo-load-balance: [proto:ip4 index:13 buckets:1 uRPF:12 to:[0:0]] [0] [@6]: ipv4 via 0.0.0.0 gre0: mtu:9000 4500000000000000fe2fb0cc0a0000010101010100000800 stacked-on entry:11: [@2]: dpo-drop ip4 DBGvpp# sh adj 1 [@1] ipv4 via 0.0.0.0 gre0: mtu:9000 4500000000000000fe2fb0cc0a0000010101010100000800 stacked-on entry:11: [@2]: dpo-drop ip4 flags:midchain-ip-stack midchain-looped <<<<< this is a loop counts:[0:0] locks:4 delegates: children: {path:14} Change-Id: I39b82bd1ea439be4611c88b130d40289fa0c1b59 Signed-off-by: Neale Ranns <nranns@cisco.com>
Diffstat (limited to 'src/vnet')
-rw-r--r--src/vnet/adj/adj.c74
-rw-r--r--src/vnet/adj/adj.h63
-rw-r--r--src/vnet/adj/adj_midchain.c124
-rw-r--r--src/vnet/adj/adj_midchain.h34
-rw-r--r--src/vnet/fib/fib_path.c16
-rw-r--r--src/vnet/gre/gre.c11
-rw-r--r--src/vnet/gre/interface.c40
-rw-r--r--src/vnet/ipip/ipip.c65
-rw-r--r--src/vnet/ipip/sixrd.c6
-rw-r--r--src/vnet/lisp-gpe/lisp_gpe_adjacency.c54
10 files changed, 338 insertions, 149 deletions
diff --git a/src/vnet/adj/adj.c b/src/vnet/adj/adj.c
index 8740bb41465..b844073ecfb 100644
--- a/src/vnet/adj/adj.c
+++ b/src/vnet/adj/adj.c
@@ -45,6 +45,11 @@ const ip46_address_t ADJ_BCAST_ADDR = {
},
};
+/**
+ * Adj flag names
+ */
+static const char *adj_attr_names[] = ADJ_ATTR_NAMES;
+
always_inline void
adj_poison (ip_adjacency_t * adj)
{
@@ -95,6 +100,28 @@ adj_index_is_special (adj_index_t adj_index)
return (0);
}
+u8*
+format_adj_flags (u8 * s, va_list * args)
+{
+ adj_flags_t af;
+ adj_attr_t at;
+
+ af = va_arg (*args, int);
+
+ if (ADJ_FLAG_NONE == af)
+ {
+ return (format(s, "None"));
+ }
+ FOR_EACH_ADJ_ATTR(at)
+ {
+ if (af & (1 << at))
+ {
+ s = format(s, "%s ", adj_attr_names[at]);
+ }
+ }
+ return (s);
+}
+
/**
* @brief Pretty print helper function for formatting specific adjacencies.
* @param s - input string to format
@@ -113,10 +140,11 @@ format_ip_adjacency (u8 * s, va_list * args)
adj_index = va_arg (*args, u32);
fiaf = va_arg (*args, format_ip_adjacency_flags_t);
adj = adj_get(adj_index);
-
+
switch (adj->lookup_next_index)
{
case IP_LOOKUP_NEXT_REWRITE:
+ case IP_LOOKUP_NEXT_BCAST:
s = format (s, "%U", format_adj_nbr, adj_index, 0);
break;
case IP_LOOKUP_NEXT_ARP:
@@ -134,8 +162,12 @@ format_ip_adjacency (u8 * s, va_list * args)
case IP_LOOKUP_NEXT_MCAST_MIDCHAIN:
s = format (s, "%U", format_adj_mcast_midchain, adj_index, 0);
break;
- default:
- break;
+ case IP_LOOKUP_NEXT_DROP:
+ case IP_LOOKUP_NEXT_PUNT:
+ case IP_LOOKUP_NEXT_LOCAL:
+ case IP_LOOKUP_NEXT_ICMP_ERROR:
+ case IP_LOOKUP_N_NEXT:
+ break;
}
if (fiaf & FORMAT_IP_ADJACENCY_DETAIL)
@@ -143,6 +175,7 @@ format_ip_adjacency (u8 * s, va_list * args)
vlib_counter_t counts;
vlib_get_combined_counter(&adjacency_counters, adj_index, &counts);
+ s = format (s, "\n flags:%U", format_adj_flags, adj->ia_flags);
s = format (s, "\n counts:[%Ld:%Ld]", counts.packets, counts.bytes);
s = format (s, "\n locks:%d", adj->ia_node.fn_locks);
s = format(s, "\n delegates:\n ");
@@ -159,6 +192,39 @@ format_ip_adjacency (u8 * s, va_list * args)
return s;
}
+int
+adj_recursive_loop_detect (adj_index_t ai,
+ fib_node_index_t **entry_indicies)
+{
+ ip_adjacency_t * adj;
+
+ adj = adj_get(ai);
+
+ switch (adj->lookup_next_index)
+ {
+ case IP_LOOKUP_NEXT_REWRITE:
+ case IP_LOOKUP_NEXT_ARP:
+ case IP_LOOKUP_NEXT_GLEAN:
+ case IP_LOOKUP_NEXT_MCAST:
+ case IP_LOOKUP_NEXT_BCAST:
+ case IP_LOOKUP_NEXT_DROP:
+ case IP_LOOKUP_NEXT_PUNT:
+ case IP_LOOKUP_NEXT_LOCAL:
+ case IP_LOOKUP_NEXT_ICMP_ERROR:
+ case IP_LOOKUP_N_NEXT:
+ /*
+ * these adjcencey types are terminal graph nodes, so there's no
+ * possibility of a loop down here.
+ */
+ break;
+ case IP_LOOKUP_NEXT_MIDCHAIN:
+ case IP_LOOKUP_NEXT_MCAST_MIDCHAIN:
+ return (adj_ndr_midchain_recursive_loop_detect(ai, entry_indicies));
+ }
+
+ return (0);
+}
+
/*
* adj_last_lock_gone
*
@@ -403,7 +469,7 @@ adj_get_link_type (adj_index_t ai)
adj = adj_get(ai);
- return (adj->ia_link);
+ return (adj->ia_link);
}
/**
diff --git a/src/vnet/adj/adj.h b/src/vnet/adj/adj.h
index 18a2e1ddbbb..fb3dc368db0 100644
--- a/src/vnet/adj/adj.h
+++ b/src/vnet/adj/adj.h
@@ -157,14 +157,12 @@ typedef void (*adj_midchain_fixup_t) (vlib_main_t * vm,
/**
* @brief Flags on an IP adjacency
*/
-typedef enum ip_adjacency_flags_t_
+typedef enum adj_attr_t_
{
- ADJ_FLAG_NONE = 0,
-
/**
* Currently a sync walk is active. Used to prevent re-entrant walking
*/
- ADJ_FLAG_SYNC_WALK_ACTIVE = (1 << 0),
+ ADJ_ATTR_SYNC_WALK_ACTIVE = 0,
/**
* Packets TX through the midchain do not increment the interface
@@ -173,10 +171,48 @@ typedef enum ip_adjacency_flags_t_
* the packet will have traversed the interface's TX node, and hence have
* been counted, before it traverses ths midchain
*/
- ADJ_FLAG_MIDCHAIN_NO_COUNT = (1 << 1),
+ ADJ_ATTR_MIDCHAIN_NO_COUNT,
+ /**
+ * When stacking midchains on a fib-entry extract the choice from the
+ * load-balance returned based on an IP hash of the adj's rewrite
+ */
+ ADJ_ATTR_MIDCHAIN_IP_STACK,
+ /**
+ * If the midchain were to stack on its FIB entry a loop would form.
+ */
+ ADJ_ATTR_MIDCHAIN_LOOPED,
+} adj_attr_t;
+
+#define ADJ_ATTR_NAMES { \
+ [ADJ_ATTR_SYNC_WALK_ACTIVE] = "walk-active", \
+ [ADJ_ATTR_MIDCHAIN_NO_COUNT] = "midchain-no-count", \
+ [ADJ_ATTR_MIDCHAIN_IP_STACK] = "midchain-ip-stack", \
+ [ADJ_ATTR_MIDCHAIN_LOOPED] = "midchain-looped", \
+}
+
+#define FOR_EACH_ADJ_ATTR(_attr) \
+ for (_attr = ADJ_ATTR_SYNC_WALK_ACTIVE; \
+ _attr <= ADJ_ATTR_MIDCHAIN_LOOPED; \
+ _attr++)
+
+/**
+ * @brief Flags on an IP adjacency
+ */
+typedef enum adj_flags_t_
+{
+ ADJ_FLAG_NONE = 0,
+ ADJ_FLAG_SYNC_WALK_ACTIVE = (1 << ADJ_ATTR_SYNC_WALK_ACTIVE),
+ ADJ_FLAG_MIDCHAIN_NO_COUNT = (1 << ADJ_ATTR_MIDCHAIN_NO_COUNT),
+ ADJ_FLAG_MIDCHAIN_IP_STACK = (1 << ADJ_ATTR_MIDCHAIN_IP_STACK),
+ ADJ_FLAG_MIDCHAIN_LOOPED = (1 << ADJ_ATTR_MIDCHAIN_LOOPED),
} __attribute__ ((packed)) adj_flags_t;
/**
+ * @brief Format adjacency flags
+ */
+extern u8* format_adj_flags(u8 * s, va_list * args);
+
+/**
* @brief IP unicast adjacency.
* @note cache aligned.
*
@@ -257,6 +293,11 @@ typedef struct ip_adjacency_t_
* Fixup data passed back to the client in the fixup function
*/
const void *fixup_data;
+ /**
+ * the FIB entry this midchain resolves through. required for recursive
+ * loop detection.
+ */
+ fib_node_index_t fei;
} midchain;
/**
* IP_LOOKUP_NEXT_GLEAN
@@ -355,6 +396,18 @@ extern const u8* adj_get_rewrite (adj_index_t ai);
extern void adj_feature_update (u32 sw_if_index, u8 arc_index, u8 is_enable);
/**
+ * @brief descend the FIB graph looking for loops
+ *
+ * @param ai
+ * The adj index to traverse
+ *
+ * @param entry_indicies)
+ * A pointer to a vector of FIB entries already visited.
+ */
+extern int adj_recursive_loop_detect (adj_index_t ai,
+ fib_node_index_t **entry_indicies);
+
+/**
* @brief
* The global adjacnecy pool. Exposed for fast/inline data-plane access
*/
diff --git a/src/vnet/adj/adj_midchain.c b/src/vnet/adj/adj_midchain.c
index 268d9409abf..a4b29c8ce35 100644
--- a/src/vnet/adj/adj_midchain.c
+++ b/src/vnet/adj/adj_midchain.c
@@ -20,7 +20,9 @@
#include <vnet/adj/adj_midchain.h>
#include <vnet/ethernet/arp_packet.h>
#include <vnet/dpo/drop_dpo.h>
+#include <vnet/dpo/load_balance.h>
#include <vnet/fib/fib_walk.h>
+#include <vnet/fib/fib_entry.h>
/**
* The two midchain tx feature node indices
@@ -473,6 +475,7 @@ adj_midchain_setup (adj_index_t adj_index,
adj->sub_type.midchain.fixup_func = fixup;
adj->sub_type.midchain.fixup_data = data;
+ adj->sub_type.midchain.fei = FIB_NODE_INDEX_INVALID;
adj->ia_flags |= flags;
arc_index = adj_midchain_get_feature_arc_index_for_link_type (adj);
@@ -548,11 +551,24 @@ adj_nbr_midchain_update_rewrite (adj_index_t adj_index,
void
adj_nbr_midchain_unstack (adj_index_t adj_index)
{
+ fib_node_index_t *entry_indicies, tmp;
ip_adjacency_t *adj;
ASSERT(ADJ_INDEX_INVALID != adj_index);
+ adj = adj_get (adj_index);
- adj = adj_get(adj_index);
+ /*
+ * check to see if this unstacking breaks a recursion loop
+ */
+ entry_indicies = NULL;
+ tmp = adj->sub_type.midchain.fei;
+ adj->sub_type.midchain.fei = FIB_NODE_INDEX_INVALID;
+
+ if (FIB_NODE_INDEX_INVALID != tmp)
+ {
+ fib_entry_recursive_loop_detect(tmp, &entry_indicies);
+ vec_free(entry_indicies);
+ }
/*
* stack on the drop
@@ -564,6 +580,74 @@ adj_nbr_midchain_unstack (adj_index_t adj_index)
CLIB_MEMORY_BARRIER();
}
+void
+adj_nbr_midchain_stack_on_fib_entry (adj_index_t ai,
+ fib_node_index_t fei,
+ fib_forward_chain_type_t fct)
+{
+ fib_node_index_t *entry_indicies;
+ dpo_id_t tmp = DPO_INVALID;
+ ip_adjacency_t *adj;
+
+ adj = adj_get (ai);
+
+ /*
+ * check to see if this stacking will form a recursion loop
+ */
+ entry_indicies = NULL;
+ adj->sub_type.midchain.fei = fei;
+
+ if (fib_entry_recursive_loop_detect(adj->sub_type.midchain.fei, &entry_indicies))
+ {
+ /*
+ * loop formed, stack on the drop.
+ */
+ dpo_copy(&tmp, drop_dpo_get(fib_forw_chain_type_to_dpo_proto(fct)));
+ }
+ else
+ {
+ fib_entry_contribute_forwarding (fei, fct, &tmp);
+
+ if ((adj->ia_flags & ADJ_FLAG_MIDCHAIN_IP_STACK) &&
+ (DPO_LOAD_BALANCE == tmp.dpoi_type))
+ {
+ /*
+ * do that hash now and stack on the choice.
+ * If the choice is an incomplete adj then we will need a poke when
+ * it becomes complete. This happens since the adj update walk propagates
+ * as far a recursive paths.
+ */
+ const dpo_id_t *choice;
+ load_balance_t *lb;
+ int hash;
+
+ lb = load_balance_get (tmp.dpoi_index);
+
+ if (FIB_FORW_CHAIN_TYPE_UNICAST_IP4 == fct)
+ {
+ hash = ip4_compute_flow_hash ((ip4_header_t *) adj_get_rewrite (ai),
+ lb->lb_hash_config);
+ }
+ else if (FIB_FORW_CHAIN_TYPE_UNICAST_IP6 == fct)
+ {
+ hash = ip6_compute_flow_hash ((ip6_header_t *) adj_get_rewrite (ai),
+ lb->lb_hash_config);
+ }
+ else
+ {
+ hash = 0;
+ ASSERT(0);
+ }
+
+ choice = load_balance_get_bucket_i (lb, hash & lb->lb_n_buckets_minus_1);
+ dpo_copy (&tmp, choice);
+ }
+ }
+ adj_nbr_midchain_stack (ai, &tmp);
+ dpo_reset(&tmp);
+ vec_free(entry_indicies);
+}
+
/**
* adj_nbr_midchain_stack
*/
@@ -585,6 +669,33 @@ adj_nbr_midchain_stack (adj_index_t adj_index,
next);
}
+int
+adj_ndr_midchain_recursive_loop_detect (adj_index_t ai,
+ fib_node_index_t **entry_indicies)
+{
+ fib_node_index_t *entry_index, *entries;
+ ip_adjacency_t * adj;
+
+ adj = adj_get(ai);
+ entries = *entry_indicies;
+
+ vec_foreach(entry_index, entries)
+ {
+ if (*entry_index == adj->sub_type.midchain.fei)
+ {
+ /*
+ * The entry this midchain links to is already in the set
+ * of visisted entries, this is a loop
+ */
+ adj->ia_flags |= ADJ_FLAG_MIDCHAIN_LOOPED;
+ return (1);
+ }
+ }
+
+ adj->ia_flags &= ~ADJ_FLAG_MIDCHAIN_LOOPED;
+ return (0);
+}
+
u8*
format_adj_midchain (u8* s, va_list *ap)
{
@@ -599,8 +710,15 @@ format_adj_midchain (u8* s, va_list *ap)
s = format (s, " %U",
format_vnet_rewrite,
&adj->rewrite_header, sizeof (adj->rewrite_data), indent);
- s = format (s, "\n%Ustacked-on:\n%U%U",
- format_white_space, indent,
+ s = format (s, "\n%Ustacked-on",
+ format_white_space, indent);
+
+ if (FIB_NODE_INDEX_INVALID != adj->sub_type.midchain.fei)
+ {
+ s = format (s, " entry:%d", adj->sub_type.midchain.fei);
+
+ }
+ s = format (s, ":\n%U%U",
format_white_space, indent+2,
format_dpo_id, &adj->sub_type.midchain.next_dpo, indent+2);
diff --git a/src/vnet/adj/adj_midchain.h b/src/vnet/adj/adj_midchain.h
index 65892314f40..24fea427a6b 100644
--- a/src/vnet/adj/adj_midchain.h
+++ b/src/vnet/adj/adj_midchain.h
@@ -53,7 +53,8 @@ extern void adj_nbr_midchain_update_rewrite(adj_index_t adj_index,
/**
* @brief
* [re]stack a midchain. 'Stacking' is the act of forming parent-child
- * relationships in the data-plane graph.
+ * relationships in the data-plane graph. Do NOT use this function to
+ * stack on a DPO type that might form a loop.
*
* @param adj_index
* The index of the midchain to stack
@@ -66,6 +67,25 @@ extern void adj_nbr_midchain_stack(adj_index_t adj_index,
/**
* @brief
+ * [re]stack a midchain. 'Stacking' is the act of forming parent-child
+ * relationships in the data-plane graph. Since function performs recursive
+ * loop detection.
+ *
+ * @param adj_index
+ * The index of the midchain to stack
+ *
+ * @param fei
+ * The FIB entry to stack on
+ *
+ * @param fct
+ * The chain type to use from the fib entry fowarding
+ */
+extern void adj_nbr_midchain_stack_on_fib_entry(adj_index_t adj_index,
+ fib_node_index_t fei,
+ fib_forward_chain_type_t fct);
+
+/**
+ * @brief
* unstack a midchain. This will break the chain between the midchain and
* the next graph section. This is a implemented as stack-on-drop
*
@@ -75,6 +95,18 @@ extern void adj_nbr_midchain_stack(adj_index_t adj_index,
extern void adj_nbr_midchain_unstack(adj_index_t adj_index);
/**
+ * @brief descend the FIB graph looking for loops
+ *
+ * @param ai
+ * The adj index to traverse
+ *
+ * @param entry_indicies)
+ * A pointer to a vector of FIB entries already visited.
+ */
+extern int adj_ndr_midchain_recursive_loop_detect(adj_index_t ai,
+ fib_node_index_t **entry_indicies);
+
+/**
* @brief
* Module initialisation
*/
diff --git a/src/vnet/fib/fib_path.c b/src/vnet/fib/fib_path.c
index baf8275d181..f528c67677f 100644
--- a/src/vnet/fib/fib_path.c
+++ b/src/vnet/fib/fib_path.c
@@ -1802,7 +1802,7 @@ fib_path_recursive_loop_detect (fib_node_index_t path_index,
{
/*
* no loop here yet. keep forward walking the graph.
- */
+ */
if (fib_entry_recursive_loop_detect(path->fp_via_fib, entry_indicies))
{
FIB_PATH_DBG(path, "recursive loop formed");
@@ -1818,6 +1818,18 @@ fib_path_recursive_loop_detect (fib_node_index_t path_index,
}
case FIB_PATH_TYPE_ATTACHED_NEXT_HOP:
case FIB_PATH_TYPE_ATTACHED:
+ if (adj_recursive_loop_detect(path->fp_dpo.dpoi_index,
+ entry_indicies))
+ {
+ FIB_PATH_DBG(path, "recursive loop formed");
+ path->fp_oper_flags |= FIB_PATH_OPER_FLAG_RECURSIVE_LOOP;
+ }
+ else
+ {
+ FIB_PATH_DBG(path, "recursive loop cleared");
+ path->fp_oper_flags &= ~FIB_PATH_OPER_FLAG_RECURSIVE_LOOP;
+ }
+ break;
case FIB_PATH_TYPE_SPECIAL:
case FIB_PATH_TYPE_DEAG:
case FIB_PATH_TYPE_DVR:
@@ -2690,7 +2702,7 @@ show_fib_path_command (vlib_main_t * vm,
path = fib_path_get(pi);
u8 *s = format(NULL, "%U", format_fib_path, pi, 1,
FIB_PATH_FORMAT_FLAGS_NONE);
- s = format(s, "children:");
+ s = format(s, "\n children:");
s = fib_node_children_format(path->fp_node.fn_children, s);
vlib_cli_output (vm, "%s", s);
vec_free(s);
diff --git a/src/vnet/gre/gre.c b/src/vnet/gre/gre.c
index 449968c1be0..e30319f5f99 100644
--- a/src/vnet/gre/gre.c
+++ b/src/vnet/gre/gre.c
@@ -301,17 +301,20 @@ gre_update_adj (vnet_main_t * vnm, u32 sw_if_index, adj_index_t ai)
{
gre_main_t *gm = &gre_main;
gre_tunnel_t *t;
- u32 ti;
+ adj_flags_t af;
u8 is_ipv6;
+ u32 ti;
ti = gm->tunnel_index_by_sw_if_index[sw_if_index];
t = pool_elt_at_index (gm->tunnels, ti);
is_ipv6 = t->tunnel_dst.fp_proto == FIB_PROTOCOL_IP6 ? 1 : 0;
+ af = ADJ_FLAG_MIDCHAIN_IP_STACK;
+
+ if (VNET_LINK_ETHERNET == adj_get_link_type (ai))
+ af |= ADJ_FLAG_MIDCHAIN_NO_COUNT;
adj_nbr_midchain_update_rewrite
- (ai, !is_ipv6 ? gre4_fixup : gre6_fixup, NULL,
- (VNET_LINK_ETHERNET == adj_get_link_type (ai) ?
- ADJ_FLAG_MIDCHAIN_NO_COUNT : ADJ_FLAG_NONE),
+ (ai, !is_ipv6 ? gre4_fixup : gre6_fixup, NULL, af,
gre_build_rewrite (vnm, sw_if_index, adj_get_link_type (ai), NULL));
gre_tunnel_stack (ai);
diff --git a/src/vnet/gre/interface.c b/src/vnet/gre/interface.c
index 6be934af56c..b9bfb79c172 100644
--- a/src/vnet/gre/interface.c
+++ b/src/vnet/gre/interface.c
@@ -128,9 +128,7 @@ gre_tunnel_from_fib_node (fib_node_t * node)
void
gre_tunnel_stack (adj_index_t ai)
{
- fib_forward_chain_type_t fib_fwd;
gre_main_t *gm = &gre_main;
- dpo_id_t tmp = DPO_INVALID;
ip_adjacency_t *adj;
gre_tunnel_t *gt;
u32 sw_if_index;
@@ -149,42 +147,14 @@ gre_tunnel_stack (adj_index_t ai)
VNET_HW_INTERFACE_FLAG_LINK_UP) == 0)
{
adj_nbr_midchain_unstack (ai);
- return;
}
-
- fib_fwd = fib_forw_chain_type_from_fib_proto (gt->tunnel_dst.fp_proto);
-
- fib_entry_contribute_forwarding (gt->fib_entry_index, fib_fwd, &tmp);
- if (DPO_LOAD_BALANCE == tmp.dpoi_type)
+ else
{
- /*
- * post GRE rewrite we will load-balance. However, the GRE encap
- * is always the same for this adjacency/tunnel and hence the IP/GRE
- * src,dst hash is always the same result too. So we do that hash now and
- * stack on the choice.
- * If the choice is an incomplete adj then we will need a poke when
- * it becomes complete. This happens since the adj update walk propagates
- * as far a recursive paths.
- */
- const dpo_id_t *choice;
- load_balance_t *lb;
- int hash;
-
- lb = load_balance_get (tmp.dpoi_index);
-
- if (fib_fwd == FIB_FORW_CHAIN_TYPE_UNICAST_IP4)
- hash = ip4_compute_flow_hash ((ip4_header_t *) adj_get_rewrite (ai),
- lb->lb_hash_config);
- else
- hash = ip6_compute_flow_hash ((ip6_header_t *) adj_get_rewrite (ai),
- lb->lb_hash_config);
- choice =
- load_balance_get_bucket_i (lb, hash & lb->lb_n_buckets_minus_1);
- dpo_copy (&tmp, choice);
+ adj_nbr_midchain_stack_on_fib_entry (ai,
+ gt->fib_entry_index,
+ fib_forw_chain_type_from_fib_proto
+ (gt->tunnel_dst.fp_proto));
}
-
- adj_nbr_midchain_stack (ai, &tmp);
- dpo_reset (&tmp);
}
/**
diff --git a/src/vnet/ipip/ipip.c b/src/vnet/ipip/ipip.c
index 9c58e520623..a5e46c41d6c 100644
--- a/src/vnet/ipip/ipip.c
+++ b/src/vnet/ipip/ipip.c
@@ -186,46 +186,15 @@ ipip_tunnel_stack (adj_index_t ai)
VNET_HW_INTERFACE_FLAG_LINK_UP) == 0)
{
adj_nbr_midchain_unstack (ai);
- return;
}
-
- dpo_id_t tmp = DPO_INVALID;
- fib_forward_chain_type_t fib_fwd =
- t->transport ==
- IPIP_TRANSPORT_IP6 ? FIB_FORW_CHAIN_TYPE_UNICAST_IP6 :
- FIB_FORW_CHAIN_TYPE_UNICAST_IP4;
-
- fib_entry_contribute_forwarding (t->p2p.fib_entry_index, fib_fwd, &tmp);
- if (DPO_LOAD_BALANCE == tmp.dpoi_type)
+ else
{
- /*
- * post IPIP rewrite we will load-balance. However, the IPIP encap
- * is always the same for this adjacency/tunnel and hence the IP/IPIP
- * src,dst hash is always the same result too. So we do that hash now and
- * stack on the choice.
- * If the choice is an incomplete adj then we will need a poke when
- * it becomes complete. This happens since the adj update walk propagates
- * as far a recursive paths.
- */
- const dpo_id_t *choice;
- load_balance_t *lb;
- int hash;
-
- lb = load_balance_get (tmp.dpoi_index);
-
- if (fib_fwd == FIB_FORW_CHAIN_TYPE_UNICAST_IP4)
- hash = ip4_compute_flow_hash ((ip4_header_t *) adj_get_rewrite (ai),
- lb->lb_hash_config);
- else
- hash = ip6_compute_flow_hash ((ip6_header_t *) adj_get_rewrite (ai),
- lb->lb_hash_config);
- choice =
- load_balance_get_bucket_i (lb, hash & lb->lb_n_buckets_minus_1);
- dpo_copy (&tmp, choice);
+ adj_nbr_midchain_stack_on_fib_entry
+ (ai,
+ t->p2p.fib_entry_index,
+ (t->transport == IPIP_TRANSPORT_IP6) ?
+ FIB_FORW_CHAIN_TYPE_UNICAST_IP6 : FIB_FORW_CHAIN_TYPE_UNICAST_IP4);
}
-
- adj_nbr_midchain_stack (ai, &tmp);
- dpo_reset (&tmp);
}
static adj_walk_rc_t
@@ -253,24 +222,24 @@ ipip_tunnel_restack (ipip_tunnel_t * gt)
void
ipip_update_adj (vnet_main_t * vnm, u32 sw_if_index, adj_index_t ai)
{
- ipip_tunnel_t *t;
adj_midchain_fixup_t f;
+ ipip_tunnel_t *t;
+ adj_flags_t af;
t = ipip_tunnel_db_find_by_sw_if_index (sw_if_index);
if (!t)
return;
f = t->transport == IPIP_TRANSPORT_IP6 ? ipip6_fixup : ipip4_fixup;
-
- adj_nbr_midchain_update_rewrite (ai, f, t,
- (VNET_LINK_ETHERNET ==
- adj_get_link_type (ai) ?
- ADJ_FLAG_MIDCHAIN_NO_COUNT :
- ADJ_FLAG_NONE), ipip_build_rewrite (vnm,
- sw_if_index,
- adj_get_link_type
- (ai),
- NULL));
+ af = ADJ_FLAG_MIDCHAIN_IP_STACK;
+ if (VNET_LINK_ETHERNET == adj_get_link_type (ai))
+ af |= ADJ_FLAG_MIDCHAIN_NO_COUNT;
+
+ adj_nbr_midchain_update_rewrite (ai, f, t, af,
+ ipip_build_rewrite (vnm,
+ sw_if_index,
+ adj_get_link_type
+ (ai), NULL));
ipip_tunnel_stack (ai);
}
diff --git a/src/vnet/ipip/sixrd.c b/src/vnet/ipip/sixrd.c
index cc5bfa33d91..30c37c80fe8 100644
--- a/src/vnet/ipip/sixrd.c
+++ b/src/vnet/ipip/sixrd.c
@@ -152,9 +152,9 @@ ip6ip_tunnel_stack (adj_index_t ai, u32 fib_entry_index)
if (vnet_hw_interface_get_flags (vnet_get_main (), t->hw_if_index) &
VNET_HW_INTERFACE_FLAG_LINK_UP)
{
- adj_nbr_midchain_stack (ai,
- fib_entry_contribute_ip_forwarding
- (fib_entry_index));
+ adj_nbr_midchain_stack_on_fib_entry (ai,
+ fib_entry_index,
+ FIB_FORW_CHAIN_TYPE_UNICAST_IP4);
}
else
{
diff --git a/src/vnet/lisp-gpe/lisp_gpe_adjacency.c b/src/vnet/lisp-gpe/lisp_gpe_adjacency.c
index 6f85dc4a761..7361e8eb0d6 100644
--- a/src/vnet/lisp-gpe/lisp_gpe_adjacency.c
+++ b/src/vnet/lisp-gpe/lisp_gpe_adjacency.c
@@ -131,48 +131,13 @@ static void
lisp_gpe_adj_stack_one (lisp_gpe_adjacency_t * ladj, adj_index_t ai)
{
const lisp_gpe_tunnel_t *lgt;
- dpo_id_t tmp = DPO_INVALID;
lgt = lisp_gpe_tunnel_get (ladj->tunnel_index);
- fib_entry_contribute_forwarding (lgt->fib_entry_index,
- lisp_gpe_adj_get_fib_chain_type (ladj),
- &tmp);
- if (DPO_LOAD_BALANCE == tmp.dpoi_type)
- {
- /*
- * post LISP rewrite we will load-balance. However, the LISP encap
- * is always the same for this adjacency/tunnel and hence the IP/UDP src,dst
- * hash is always the same result too. So we do that hash now and
- * stack on the choice.
- * If the choice is an incomplete adj then we will need a poke when
- * it becomes complete. This happens since the adj update walk propagates
- * as far a recursive paths.
- */
- const dpo_id_t *choice;
- load_balance_t *lb;
- int hash;
-
- lb = load_balance_get (tmp.dpoi_index);
-
- if (IP4 == ip_addr_version (&ladj->remote_rloc))
- {
- hash = ip4_compute_flow_hash ((ip4_header_t *) adj_get_rewrite (ai),
- lb->lb_hash_config);
- }
- else
- {
- hash = ip6_compute_flow_hash ((ip6_header_t *) adj_get_rewrite (ai),
- lb->lb_hash_config);
- }
-
- choice =
- load_balance_get_bucket_i (lb, hash & lb->lb_n_buckets_minus_1);
- dpo_copy (&tmp, choice);
- }
-
- adj_nbr_midchain_stack (ai, &tmp);
- dpo_reset (&tmp);
+ adj_nbr_midchain_stack_on_fib_entry (ai,
+ lgt->fib_entry_index,
+ lisp_gpe_adj_get_fib_chain_type
+ (ladj));
}
/**
@@ -332,6 +297,7 @@ lisp_gpe_update_adjacency (vnet_main_t * vnm, u32 sw_if_index, adj_index_t ai)
ip_adjacency_t *adj;
ip_address_t rloc;
vnet_link_t linkt;
+ adj_flags_t af;
index_t lai;
adj = adj_get (ai);
@@ -347,12 +313,12 @@ lisp_gpe_update_adjacency (vnet_main_t * vnm, u32 sw_if_index, adj_index_t ai)
ladj = pool_elt_at_index (lisp_adj_pool, lai);
lgt = lisp_gpe_tunnel_get (ladj->tunnel_index);
linkt = adj_get_link_type (ai);
+ af = ADJ_FLAG_MIDCHAIN_IP_STACK;
+ if (VNET_LINK_ETHERNET == linkt)
+ af |= ADJ_FLAG_MIDCHAIN_NO_COUNT;
+
adj_nbr_midchain_update_rewrite
- (ai, lisp_gpe_fixup,
- NULL,
- (VNET_LINK_ETHERNET == linkt ?
- ADJ_FLAG_MIDCHAIN_NO_COUNT :
- ADJ_FLAG_NONE),
+ (ai, lisp_gpe_fixup, NULL, af,
lisp_gpe_tunnel_build_rewrite (lgt, ladj,
lisp_gpe_adj_proto_from_vnet_link_type
(linkt)));
'n1361' href='#n1361'>1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
# Copyright (c) 2019 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.

"""Data pre-processing

- extract data from output.xml files generated by Jenkins jobs and store in
  pandas' Series,
- provide access to the data.
- filter the data using tags,
"""

import multiprocessing
import os
import re
import pandas as pd
import logging

from robot.api import ExecutionResult, ResultVisitor
from robot import errors
from collections import OrderedDict
from string import replace
from os import remove
from os.path import join
from datetime import datetime as dt
from datetime import timedelta
from json import loads
from jumpavg.AvgStdevMetadataFactory import AvgStdevMetadataFactory

from input_data_files import download_and_unzip_data_file
from utils import Worker


# Separator used in file names
SEPARATOR = "__"


class ExecutionChecker(ResultVisitor):
    """Class to traverse through the test suite structure.

    The functionality implemented in this class generates a json structure:

    Performance tests:

    {
        "metadata": {
            "generated": "Timestamp",
            "version": "SUT version",
            "job": "Jenkins job name",
            "build": "Information about the build"
        },
        "suites": {
            "Suite long name 1": {
                "name": Suite name,
                "doc": "Suite 1 documentation",
                "parent": "Suite 1 parent",
                "level": "Level of the suite in the suite hierarchy"
            }
            "Suite long name N": {
                "name": Suite name,
                "doc": "Suite N documentation",
                "parent": "Suite 2 parent",
                "level": "Level of the suite in the suite hierarchy"
            }
        }
        "tests": {
            # NDRPDR tests:
            "ID": {
                "name": "Test name",
                "parent": "Name of the parent of the test",
                "doc": "Test documentation",
                "msg": "Test message",
                "conf-history": "DUT1 and DUT2 VAT History",
                "show-run": "Show Run",
                "tags": ["tag 1", "tag 2", "tag n"],
                "type": "NDRPDR",
                "status": "PASS" | "FAIL",
                "throughput": {
                    "NDR": {
                        "LOWER": float,
                        "UPPER": float
                    },
                    "PDR": {
                        "LOWER": float,
                        "UPPER": float
                    }
                },
                "latency": {
                    "NDR": {
                        "direction1": {
                            "min": float,
                            "avg": float,
                            "max": float
                        },
                        "direction2": {
                            "min": float,
                            "avg": float,
                            "max": float
                        }
                    },
                    "PDR": {
                        "direction1": {
                            "min": float,
                            "avg": float,
                            "max": float
                        },
                        "direction2": {
                            "min": float,
                            "avg": float,
                            "max": float
                        }
                    }
                }
            }

            # TCP tests:
            "ID": {
                "name": "Test name",
                "parent": "Name of the parent of the test",
                "doc": "Test documentation",
                "msg": "Test message",
                "tags": ["tag 1", "tag 2", "tag n"],
                "type": "TCP",
                "status": "PASS" | "FAIL",
                "result": int
            }

            # MRR, BMRR tests:
            "ID": {
                "name": "Test name",
                "parent": "Name of the parent of the test",
                "doc": "Test documentation",
                "msg": "Test message",
                "tags": ["tag 1", "tag 2", "tag n"],
                "type": "MRR" | "BMRR",
                "status": "PASS" | "FAIL",
                "result": {
                    "receive-rate": AvgStdevMetadata,
                }
            }

            # TODO: Remove when definitely no NDRPDRDISC tests are used:
            # NDRPDRDISC tests:
            "ID": {
                "name": "Test name",
                "parent": "Name of the parent of the test",
                "doc": "Test documentation",
                "msg": "Test message",
                "tags": ["tag 1", "tag 2", "tag n"],
                "type": "PDR" | "NDR",
                "status": "PASS" | "FAIL",
                "throughput": {  # Only type: "PDR" | "NDR"
                    "value": int,
                    "unit": "pps" | "bps" | "percentage"
                },
                "latency": {  # Only type: "PDR" | "NDR"
                    "direction1": {
                        "100": {
                            "min": int,
                            "avg": int,
                            "max": int
                        },
                        "50": {  # Only for NDR
                            "min": int,
                            "avg": int,
                            "max": int
                        },
                        "10": {  # Only for NDR
                            "min": int,
                            "avg": int,
                            "max": int
                        }
                    },
                    "direction2": {
                        "100": {
                            "min": int,
                            "avg": int,
                            "max": int
                        },
                        "50": {  # Only for NDR
                            "min": int,
                            "avg": int,
                            "max": int
                        },
                        "10": {  # Only for NDR
                            "min": int,
                            "avg": int,
                            "max": int
                        }
                    }
                },
                "lossTolerance": "lossTolerance",  # Only type: "PDR"
                "conf-history": "DUT1 and DUT2 VAT History"
                "show-run": "Show Run"
            },
            "ID" {
                # next test
            }
        }
    }


    Functional tests:

    {
        "metadata": {  # Optional
            "version": "VPP version",
            "job": "Jenkins job name",
            "build": "Information about the build"
        },
        "suites": {
            "Suite name 1": {
                "doc": "Suite 1 documentation",
                "parent": "Suite 1 parent",
                "level": "Level of the suite in the suite hierarchy"
            }
            "Suite name N": {
                "doc": "Suite N documentation",
                "parent": "Suite 2 parent",
                "level": "Level of the suite in the suite hierarchy"
            }
        }
        "tests": {
            "ID": {
                "name": "Test name",
                "parent": "Name of the parent of the test",
                "doc": "Test documentation"
                "msg": "Test message"
                "tags": ["tag 1", "tag 2", "tag n"],
                "conf-history": "DUT1 and DUT2 VAT History"
                "show-run": "Show Run"
                "status": "PASS" | "FAIL"
            },
            "ID" {
                # next test
            }
        }
    }

    .. note:: ID is the lowercase full path to the test.
    """

    # TODO: Remove when definitely no NDRPDRDISC tests are used:
    REGEX_RATE = re.compile(r'^[\D\d]*FINAL_RATE:\s(\d+\.\d+)\s(\w+)')

    REGEX_PLR_RATE = re.compile(r'PLRsearch lower bound::\s(\d+.\d+).*\n'
                                r'PLRsearch upper bound::\s(\d+.\d+)')

    REGEX_NDRPDR_RATE = re.compile(r'NDR_LOWER:\s(\d+.\d+).*\n.*\n'
                                   r'NDR_UPPER:\s(\d+.\d+).*\n'
                                   r'PDR_LOWER:\s(\d+.\d+).*\n.*\n'
                                   r'PDR_UPPER:\s(\d+.\d+)')

    # TODO: Remove when definitely no NDRPDRDISC tests are used:
    REGEX_LAT_NDR = re.compile(r'^[\D\d]*'
                               r'LAT_\d+%NDR:\s\[\'(-?\d+/-?\d+/-?\d+)\','
                               r'\s\'(-?\d+/-?\d+/-?\d+)\'\]\s\n'
                               r'LAT_\d+%NDR:\s\[\'(-?\d+/-?\d+/-?\d+)\','
                               r'\s\'(-?\d+/-?\d+/-?\d+)\'\]\s\n'
                               r'LAT_\d+%NDR:\s\[\'(-?\d+/-?\d+/-?\d+)\','
                               r'\s\'(-?\d+/-?\d+/-?\d+)\'\]')

    REGEX_LAT_PDR = re.compile(r'^[\D\d]*'
                               r'LAT_\d+%PDR:\s\[\'(-?\d+/-?\d+/-?\d+)\','
                               r'\s\'(-?\d+/-?\d+/-?\d+)\'\][\D\d]*')

    REGEX_NDRPDR_LAT = re.compile(r'LATENCY.*\[\'(.*)\', \'(.*)\'\]\s\n.*\n.*\n'
                                  r'LATENCY.*\[\'(.*)\', \'(.*)\'\]')

    REGEX_TOLERANCE = re.compile(r'^[\D\d]*LOSS_ACCEPTANCE:\s(\d*\.\d*)\s'
                                 r'[\D\d]*')

    REGEX_VERSION_VPP = re.compile(r"(return STDOUT Version:\s*|"
                                   r"VPP Version:\s*|VPP version:\s*)(.*)")

    REGEX_VERSION_DPDK = re.compile(r"(return STDOUT testpmd)([\d\D\n]*)"
                                    r"(RTE Version: 'DPDK )(.*)(')")

    REGEX_TCP = re.compile(r'Total\s(rps|cps|throughput):\s([0-9]*).*$')

    REGEX_MRR = re.compile(r'MaxReceivedRate_Results\s\[pkts/(\d*)sec\]:\s'
                           r'tx\s(\d*),\srx\s(\d*)')

    REGEX_BMRR = re.compile(r'Maximum Receive Rate trial results'
                            r' in packets per second: \[(.*)\]')

    REGEX_TC_TAG = re.compile(r'\d+[tT]\d+[cC]')

    REGEX_TC_NAME_OLD = re.compile(r'-\d+[tT]\d+[cC]-')

    REGEX_TC_NAME_NEW = re.compile(r'-\d+[cC]-')

    REGEX_TC_NUMBER = re.compile(r'tc[0-9]{2}-')

    def __init__(self, metadata, mapping, ignore):
        """Initialisation.

        :param metadata: Key-value pairs to be included in "metadata" part of
            JSON structure.
        :param mapping: Mapping of the old names of test cases to the new
            (actual) one.
        :param ignore: List of TCs to be ignored.
        :type metadata: dict
        :type mapping: dict
        :type ignore: list
        """

        # Type of message to parse out from the test messages
        self._msg_type = None

        # VPP version
        self._version = None

        # Timestamp
        self._timestamp = None

        # Testbed. The testbed is identified by TG node IP address.
        self._testbed = None

        # Mapping of TCs long names
        self._mapping = mapping

        # Ignore list
        self._ignore = ignore

        # Number of VAT History messages found:
        # 0 - no message
        # 1 - VAT History of DUT1
        # 2 - VAT History of DUT2
        self._lookup_kw_nr = 0
        self._conf_history_lookup_nr = 0

        # Number of Show Running messages found
        # 0 - no message
        # 1 - Show run message found
        self._show_run_lookup_nr = 0

        # Test ID of currently processed test- the lowercase full path to the
        # test
        self._test_ID = None

        # The main data structure
        self._data = {
            "metadata": OrderedDict(),
            "suites": OrderedDict(),
            "tests": OrderedDict()
        }

        # Save the provided metadata
        for key, val in metadata.items():
            self._data["metadata"][key] = val

        # Dictionary defining the methods used to parse different types of
        # messages
        self.parse_msg = {
            "timestamp": self._get_timestamp,
            "vpp-version": self._get_vpp_version,
            "dpdk-version": self._get_dpdk_version,
            "teardown-vat-history": self._get_vat_history,
            "teardown-papi-history": self._get_papi_history,
            "test-show-runtime": self._get_show_run,
            "testbed": self._get_testbed
        }

    @property
    def data(self):
        """Getter - Data parsed from the XML file.

        :returns: Data parsed from the XML file.
        :rtype: dict
        """
        return self._data

    def _get_testbed(self, msg):
        """Called when extraction of testbed IP is required.
        The testbed is identified by TG node IP address.

        :param msg: Message to process.
        :type msg: Message
        :returns: Nothing.
        """

        if msg.message.count("Arguments:"):
            message = str(msg.message).replace(' ', '').replace('\n', '').\
                replace("'", '"').replace('b"', '"').\
                replace("honeycom", "honeycomb")
            message = loads(message[11:-1])
            try:
                self._testbed = message["TG"]["host"]
            except (KeyError, ValueError):
                pass
            finally:
                self._data["metadata"]["testbed"] = self._testbed
                self._msg_type = None

    def _get_vpp_version(self, msg):
        """Called when extraction of VPP version is required.

        :param msg: Message to process.
        :type msg: Message
        :returns: Nothing.
        """

        if msg.message.count("return STDOUT Version:") or \
            msg.message.count("VPP Version:") or \
            msg.message.count("VPP version:"):
            self._version = str(re.search(self.REGEX_VERSION_VPP, msg.message).
                                group(2))
            self._data["metadata"]["version"] = self._version
            self._msg_type = None

    def _get_dpdk_version(self, msg):
        """Called when extraction of DPDK version is required.

        :param msg: Message to process.
        :type msg: Message
        :returns: Nothing.
        """

        if msg.message.count("return STDOUT testpmd"):
            try:
                self._version = str(re.search(
                    self.REGEX_VERSION_DPDK, msg.message). group(4))
                self._data["metadata"]["version"] = self._version
            except IndexError:
                pass
            finally:
                self._msg_type = None

    def _get_timestamp(self, msg):
        """Called when extraction of timestamp is required.

        :param msg: Message to process.
        :type msg: Message
        :returns: Nothing.
        """

        self._timestamp = msg.timestamp[:14]
        self._data["metadata"]["generated"] = self._timestamp
        self._msg_type = None

    def _get_vat_history(self, msg):
        """Called when extraction of VAT command history is required.

        :param msg: Message to process.
        :type msg: Message
        :returns: Nothing.
        """
        if msg.message.count("VAT command history:"):
            self._conf_history_lookup_nr += 1
            if self._conf_history_lookup_nr == 1:
                self._data["tests"][self._test_ID]["conf-history"] = str()
            else:
                self._msg_type = None
            text = re.sub("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3} "
                          "VAT command history:", "", msg.message, count=1). \
                replace("\n\n", "\n").replace('\n', ' |br| ').\
                replace('\r', '').replace('"', "'")

            self._data["tests"][self._test_ID]["conf-history"] += " |br| "
            self._data["tests"][self._test_ID]["conf-history"] += \
                "**DUT" + str(self._conf_history_lookup_nr) + ":** " + text

    def _get_papi_history(self, msg):
        """Called when extraction of PAPI command history is required.

        :param msg: Message to process.
        :type msg: Message
        :returns: Nothing.
        """
        if msg.message.count("PAPI command history:"):
            self._conf_history_lookup_nr += 1
            if self._conf_history_lookup_nr == 1:
                self._data["tests"][self._test_ID]["conf-history"] = str()
            else:
                self._msg_type = None
            text = re.sub("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3} "
                          "PAPI command history:", "", msg.message, count=1). \
                replace("\n\n", "\n").replace('\n', ' |br| ').\
                replace('\r', '').replace('"', "'")

            self._data["tests"][self._test_ID]["conf-history"] += " |br| "
            self._data["tests"][self._test_ID]["conf-history"] += \
                "**DUT" + str(self._conf_history_lookup_nr) + ":** " + text

    def _get_show_run(self, msg):
        """Called when extraction of VPP operational data (output of CLI command
        Show Runtime) is required.

        :param msg: Message to process.
        :type msg: Message
        :returns: Nothing.
        """
        if msg.message.count("Thread 0 vpp_main"):
            self._show_run_lookup_nr += 1
            if self._lookup_kw_nr == 1 and self._show_run_lookup_nr == 1:
                self._data["tests"][self._test_ID]["show-run"] = str()
            if self._lookup_kw_nr > 1:
                self._msg_type = None
            if self._show_run_lookup_nr == 1:
                text = msg.message.replace("vat# ", "").\
                    replace("return STDOUT ", "").replace("\n\n", "\n").\
                    replace('\n', ' |br| ').\
                    replace('\r', '').replace('"', "'")
                try:
                    self._data["tests"][self._test_ID]["show-run"] += " |br| "
                    self._data["tests"][self._test_ID]["show-run"] += \
                        "**DUT" + str(self._lookup_kw_nr) + ":** |br| " + text
                except KeyError:
                    pass

    # TODO: Remove when definitely no NDRPDRDISC tests are used:
    def _get_latency(self, msg, test_type):
        """Get the latency data from the test message.

        :param msg: Message to be parsed.
        :param test_type: Type of the test - NDR or PDR.
        :type msg: str
        :type test_type: str
        :returns: Latencies parsed from the message.
        :rtype: dict
        """

        if test_type == "NDR":
            groups = re.search(self.REGEX_LAT_NDR, msg)
            groups_range = range(1, 7)
        elif test_type == "PDR":
            groups = re.search(self.REGEX_LAT_PDR, msg)
            groups_range = range(1, 3)
        else:
            return {}

        latencies = list()
        for idx in groups_range:
            try:
                lat = [int(item) for item in str(groups.group(idx)).split('/')]
            except (AttributeError, ValueError):
                lat = [-1, -1, -1]
            latencies.append(lat)

        keys = ("min", "avg", "max")
        latency = {
            "direction1": {
            },
            "direction2": {
            }
        }

        latency["direction1"]["100"] = dict(zip(keys, latencies[0]))
        latency["direction2"]["100"] = dict(zip(keys, latencies[1]))
        if test_type == "NDR":
            latency["direction1"]["50"] = dict(zip(keys, latencies[2]))
            latency["direction2"]["50"] = dict(zip(keys, latencies[3]))
            latency["direction1"]["10"] = dict(zip(keys, latencies[4]))
            latency["direction2"]["10"] = dict(zip(keys, latencies[5]))

        return latency

    def _get_ndrpdr_throughput(self, msg):
        """Get NDR_LOWER, NDR_UPPER, PDR_LOWER and PDR_UPPER from the test
        message.

        :param msg: The test message to be parsed.
        :type msg: str
        :returns: Parsed data as a dict and the status (PASS/FAIL).
        :rtype: tuple(dict, str)
        """

        throughput = {
            "NDR": {"LOWER": -1.0, "UPPER": -1.0},
            "PDR": {"LOWER": -1.0, "UPPER": -1.0}
        }
        status = "FAIL"
        groups = re.search(self.REGEX_NDRPDR_RATE, msg)

        if groups is not None:
            try:
                throughput["NDR"]["LOWER"] = float(groups.group(1))
                throughput["NDR"]["UPPER"] = float(groups.group(2))
                throughput["PDR"]["LOWER"] = float(groups.group(3))
                throughput["PDR"]["UPPER"] = float(groups.group(4))
                status = "PASS"
            except (IndexError, ValueError):
                pass

        return throughput, status

    def _get_plr_throughput(self, msg):
        """Get PLRsearch lower bound and PLRsearch upper bound from the test
        message.

        :param msg: The test message to be parsed.
        :type msg: str
        :returns: Parsed data as a dict and the status (PASS/FAIL).
        :rtype: tuple(dict, str)
        """

        throughput = {
            "LOWER": -1.0,
            "UPPER": -1.0
        }
        status = "FAIL"
        groups = re.search(self.REGEX_PLR_RATE, msg)

        if groups is not None:
            try:
                throughput["LOWER"] = float(groups.group(1))
                throughput["UPPER"] = float(groups.group(2))
                status = "PASS"
            except (IndexError, ValueError):
                pass

        return throughput, status

    def _get_ndrpdr_latency(self, msg):
        """Get LATENCY from the test message.

        :param msg: The test message to be parsed.
        :type msg: str
        :returns: Parsed data as a dict and the status (PASS/FAIL).
        :rtype: tuple(dict, str)
        """

        latency = {
            "NDR": {
                "direction1": {"min": -1.0, "avg": -1.0, "max": -1.0},
                "direction2": {"min": -1.0, "avg": -1.0, "max": -1.0}
            },
            "PDR": {
                "direction1": {"min": -1.0, "avg": -1.0, "max": -1.0},
                "direction2": {"min": -1.0, "avg": -1.0, "max": -1.0}
            }
        }
        status = "FAIL"
        groups = re.search(self.REGEX_NDRPDR_LAT, msg)

        if groups is not None:
            keys = ("min", "avg", "max")
            try:
                latency["NDR"]["direction1"] = dict(
                    zip(keys, [float(l) for l in groups.group(1).split('/')]))
                latency["NDR"]["direction2"] = dict(
                    zip(keys, [float(l) for l in groups.group(2).split('/')]))
                latency["PDR"]["direction1"] = dict(
                    zip(keys, [float(l) for l in groups.group(3).split('/')]))
                latency["PDR"]["direction2"] = dict(
                    zip(keys, [float(l) for l in groups.group(4).split('/')]))
                status = "PASS"
            except (IndexError, ValueError):
                pass

        return latency, status

    def visit_suite(self, suite):
        """Implements traversing through the suite and its direct children.

        :param suite: Suite to process.
        :type suite: Suite
        :returns: Nothing.
        """
        if self.start_suite(suite) is not False:
            suite.suites.visit(self)
            suite.tests.visit(self)
            self.end_suite(suite)

    def start_suite(self, suite):
        """Called when suite starts.

        :param suite: Suite to process.
        :type suite: Suite
        :returns: Nothing.
        """

        try:
            parent_name = suite.parent.name
        except AttributeError:
            return

        doc_str = suite.doc.replace('"', "'").replace('\n', ' ').\
            replace('\r', '').replace('*[', ' |br| *[').replace("*", "**")
        doc_str = replace(doc_str, ' |br| *[', '*[', maxreplace=1)

        self._data["suites"][suite.longname.lower().replace('"', "'").
            replace(" ", "_")] = {
                "name": suite.name.lower(),
                "doc": doc_str,
                "parent": parent_name,
                "level": len(suite.longname.split("."))
            }

        suite.keywords.visit(self)

    def end_suite(self, suite):
        """Called when suite ends.

        :param suite: Suite to process.
        :type suite: Suite
        :returns: Nothing.
        """
        pass

    def visit_test(self, test):
        """Implements traversing through the test.

        :param test: Test to process.
        :type test: Test
        :returns: Nothing.
        """
        if self.start_test(test) is not False:
            test.keywords.visit(self)
            self.end_test(test)

    def start_test(self, test):
        """Called when test starts.

        :param test: Test to process.
        :type test: Test
        :returns: Nothing.
        """

        longname_orig = test.longname.lower()

        # Check the ignore list
        if longname_orig in self._ignore:
            return

        tags = [str(tag) for tag in test.tags]
        test_result = dict()

        # Change the TC long name and name if defined in the mapping table
        longname = self._mapping.get(longname_orig, None)
        if longname is not None:
            name = longname.split('.')[-1]
            logging.debug("{0}\n{1}\n{2}\n{3}".format(
                self._data["metadata"], longname_orig, longname, name))
        else:
            longname = longname_orig
            name = test.name.lower()

        # Remove TC number from the TC long name (backward compatibility):
        self._test_ID = re.sub(self.REGEX_TC_NUMBER, "", longname)
        # Remove TC number from the TC name (not needed):
        test_result["name"] = re.sub(self.REGEX_TC_NUMBER, "", name)

        test_result["parent"] = test.parent.name.lower()
        test_result["tags"] = tags
        doc_str = test.doc.replace('"', "'").replace('\n', ' '). \
            replace('\r', '').replace('[', ' |br| [')
        test_result["doc"] = replace(doc_str, ' |br| [', '[', maxreplace=1)
        test_result["msg"] = test.message.replace('\n', ' |br| '). \
            replace('\r', '').replace('"', "'")
        test_result["type"] = "FUNC"
        test_result["status"] = test.status

        if "PERFTEST" in tags:
            # Replace info about cores (e.g. -1c-) with the info about threads
            # and cores (e.g. -1t1c-) in the long test case names and in the
            # test case names if necessary.
            groups = re.search(self.REGEX_TC_NAME_OLD, self._test_ID)
            if not groups:
                tag_count = 0
                for tag in test_result["tags"]:
                    groups = re.search(self.REGEX_TC_TAG, tag)
                    if groups:
                        tag_count += 1
                        tag_tc = tag

                if tag_count == 1:
                    self._test_ID = re.sub(self.REGEX_TC_NAME_NEW,
                                           "-{0}-".format(tag_tc.lower()),
                                           self._test_ID,
                                           count=1)
                    test_result["name"] = re.sub(self.REGEX_TC_NAME_NEW,
                                                 "-{0}-".format(tag_tc.lower()),
                                                 test_result["name"],
                                                 count=1)
                else:
                    test_result["status"] = "FAIL"
                    self._data["tests"][self._test_ID] = test_result
                    logging.debug("The test '{0}' has no or more than one "
                                  "multi-threading tags.".format(self._test_ID))
                    logging.debug("Tags: {0}".format(test_result["tags"]))
                    return

        if test.status == "PASS" and ("NDRPDRDISC" in tags or
                                      "NDRPDR" in tags or
                                      "SOAK" in tags or
                                      "TCP" in tags or
                                      "MRR" in tags or
                                      "BMRR" in tags):
            # TODO: Remove when definitely no NDRPDRDISC tests are used:
            if "NDRDISC" in tags:
                test_result["type"] = "NDR"
            # TODO: Remove when definitely no NDRPDRDISC tests are used:
            elif "PDRDISC" in tags:
                test_result["type"] = "PDR"
            elif "NDRPDR" in tags:
                test_result["type"] = "NDRPDR"
            elif "SOAK" in tags:
                test_result["type"] = "SOAK"
            elif "TCP" in tags:
                test_result["type"] = "TCP"
            elif "MRR" in tags:
                test_result["type"] = "MRR"
            elif "FRMOBL" in tags or "BMRR" in tags:
                test_result["type"] = "BMRR"
            else:
                test_result["status"] = "FAIL"
                self._data["tests"][self._test_ID] = test_result
                return

            # TODO: Remove when definitely no NDRPDRDISC tests are used:
            if test_result["type"] in ("NDR", "PDR"):
                try:
                    rate_value = str(re.search(
                        self.REGEX_RATE, test.message).group(1))
                except AttributeError:
                    rate_value = "-1"
                try:
                    rate_unit = str(re.search(
                        self.REGEX_RATE, test.message).group(2))
                except AttributeError:
                    rate_unit = "-1"

                test_result["throughput"] = dict()
                test_result["throughput"]["value"] = \
                    int(rate_value.split('.')[0])
                test_result["throughput"]["unit"] = rate_unit
                test_result["latency"] = \
                    self._get_latency(test.message, test_result["type"])
                if test_result["type"] == "PDR":
                    test_result["lossTolerance"] = str(re.search(
                        self.REGEX_TOLERANCE, test.message).group(1))

            elif test_result["type"] in ("NDRPDR", ):
                test_result["throughput"], test_result["status"] = \
                    self._get_ndrpdr_throughput(test.message)
                test_result["latency"], test_result["status"] = \
                    self._get_ndrpdr_latency(test.message)

            elif test_result["type"] in ("SOAK", ):
                test_result["throughput"], test_result["status"] = \
                    self._get_plr_throughput(test.message)

            elif test_result["type"] in ("TCP", ):
                groups = re.search(self.REGEX_TCP, test.message)
                test_result["result"] = int(groups.group(2))

            elif test_result["type"] in ("MRR", "BMRR"):
                test_result["result"] = dict()
                groups = re.search(self.REGEX_BMRR, test.message)
                if groups is not None:
                    items_str = groups.group(1)
                    items_float = [float(item.strip()) for item
                                   in items_str.split(",")]
                    metadata = AvgStdevMetadataFactory.from_data(items_float)
                    # Next two lines have been introduced in CSIT-1179,
                    # to be removed in CSIT-1180.
                    metadata.size = 1
                    metadata.stdev = 0.0
                    test_result["result"]["receive-rate"] = metadata
                else:
                    groups = re.search(self.REGEX_MRR, test.message)
                    test_result["result"]["receive-rate"] = \
                        AvgStdevMetadataFactory.from_data([
                            float(groups.group(3)) / float(groups.group(1)), ])

        self._data["tests"][self._test_ID] = test_result

    def end_test(self, test):
        """Called when test ends.

        :param test: Test to process.
        :type test: Test
        :returns: Nothing.
        """
        pass

    def visit_keyword(self, keyword):
        """Implements traversing through the keyword and its child keywords.

        :param keyword: Keyword to process.
        :type keyword: Keyword
        :returns: Nothing.
        """
        if self.start_keyword(keyword) is not False:
            self.end_keyword(keyword)

    def start_keyword(self, keyword):
        """Called when keyword starts. Default implementation does nothing.

        :param keyword: Keyword to process.
        :type keyword: Keyword
        :returns: Nothing.
        """
        try:
            if keyword.type == "setup":
                self.visit_setup_kw(keyword)
            elif keyword.type == "teardown":
                self._lookup_kw_nr = 0
                self.visit_teardown_kw(keyword)
            else:
                self._lookup_kw_nr = 0
                self.visit_test_kw(keyword)
        except AttributeError:
            pass

    def end_keyword(self, keyword):
        """Called when keyword ends. Default implementation does nothing.

        :param keyword: Keyword to process.
        :type keyword: Keyword
        :returns: Nothing.
        """
        pass

    def visit_test_kw(self, test_kw):
        """Implements traversing through the test keyword and its child
        keywords.

        :param test_kw: Keyword to process.
        :type test_kw: Keyword
        :returns: Nothing.
        """
        for keyword in test_kw.keywords:
            if self.start_test_kw(keyword) is not False:
                self.visit_test_kw(keyword)
                self.end_test_kw(keyword)

    def start_test_kw(self, test_kw):
        """Called when test keyword starts. Default implementation does
        nothing.

        :param test_kw: Keyword to process.
        :type test_kw: Keyword
        :returns: Nothing.
        """
        if test_kw.name.count("Show Runtime Counters On All Duts"):
            self._lookup_kw_nr += 1
            self._show_run_lookup_nr = 0
            self._msg_type = "test-show-runtime"
        elif test_kw.name.count("Start The L2fwd Test") and not self._version:
            self._msg_type = "dpdk-version"
        else:
            return
        test_kw.messages.visit(self)

    def end_test_kw(self, test_kw):
        """Called when keyword ends. Default implementation does nothing.

        :param test_kw: Keyword to process.
        :type test_kw: Keyword
        :returns: Nothing.
        """
        pass

    def visit_setup_kw(self, setup_kw):
        """Implements traversing through the teardown keyword and its child
        keywords.

        :param setup_kw: Keyword to process.
        :type setup_kw: Keyword
        :returns: Nothing.
        """
        for keyword in setup_kw.keywords:
            if self.start_setup_kw(keyword) is not False:
                self.visit_setup_kw(keyword)
                self.end_setup_kw(keyword)

    def start_setup_kw(self, setup_kw):
        """Called when teardown keyword starts. Default implementation does
        nothing.

        :param setup_kw: Keyword to process.
        :type setup_kw: Keyword
        :returns: Nothing.
        """
        if setup_kw.name.count("Show Vpp Version On All Duts") \
                and not self._version:
            self._msg_type = "vpp-version"
        elif setup_kw.name.count("Set Global Variable") \
                and not self._timestamp:
            self._msg_type = "timestamp"
        elif setup_kw.name.count("Setup Framework") and not self._testbed:
            self._msg_type = "testbed"
        else:
            return
        setup_kw.messages.visit(self)

    def end_setup_kw(self, setup_kw):
        """Called when keyword ends. Default implementation does nothing.

        :param setup_kw: Keyword to process.
        :type setup_kw: Keyword
        :returns: Nothing.
        """
        pass

    def visit_teardown_kw(self, teardown_kw):
        """Implements traversing through the teardown keyword and its child
        keywords.

        :param teardown_kw: Keyword to process.
        :type teardown_kw: Keyword
        :returns: Nothing.
        """
        for keyword in teardown_kw.keywords:
            if self.start_teardown_kw(keyword) is not False:
                self.visit_teardown_kw(keyword)
                self.end_teardown_kw(keyword)

    def start_teardown_kw(self, teardown_kw):
        """Called when teardown keyword starts. Default implementation does
        nothing.

        :param teardown_kw: Keyword to process.
        :type teardown_kw: Keyword
        :returns: Nothing.
        """

        if teardown_kw.name.count("Show Vat History On All Duts"):
            self._conf_history_lookup_nr = 0
            self._msg_type = "teardown-vat-history"
            teardown_kw.messages.visit(self)
        elif teardown_kw.name.count("Show Papi History On All Duts"):
            self._conf_history_lookup_nr = 0
            self._msg_type = "teardown-papi-history"
            teardown_kw.messages.visit(self)

    def end_teardown_kw(self, teardown_kw):
        """Called when keyword ends. Default implementation does nothing.

        :param teardown_kw: Keyword to process.
        :type teardown_kw: Keyword
        :returns: Nothing.
        """
        pass

    def visit_message(self, msg):
        """Implements visiting the message.

        :param msg: Message to process.
        :type msg: Message
        :returns: Nothing.
        """
        if self.start_message(msg) is not False:
            self.end_message(msg)

    def start_message(self, msg):
        """Called when message starts. Get required information from messages:
        - VPP version.

        :param msg: Message to process.
        :type msg: Message
        :returns: Nothing.
        """

        if self._msg_type:
            self.parse_msg[self._msg_type](msg)

    def end_message(self, msg):
        """Called when message ends. Default implementation does nothing.

        :param msg: Message to process.
        :type msg: Message
        :returns: Nothing.
        """
        pass


class InputData(object):
    """Input data

    The data is extracted from output.xml files generated by Jenkins jobs and
    stored in pandas' DataFrames.

    The data structure:
    - job name
      - build number
        - metadata
          (as described in ExecutionChecker documentation)
        - suites
          (as described in ExecutionChecker documentation)
        - tests
          (as described in ExecutionChecker documentation)
    """

    def __init__(self, spec):
        """Initialization.

        :param spec: Specification.
        :type spec: Specification
        """

        # Specification:
        self._cfg = spec

        # Data store:
        self._input_data = pd.Series()

    @property
    def data(self):
        """Getter - Input data.

        :returns: Input data
        :rtype: pandas.Series
        """
        return self._input_data

    def metadata(self, job, build):
        """Getter - metadata

        :param job: Job which metadata we want.
        :param build: Build which metadata we want.
        :type job: str
        :type build: str
        :returns: Metadata
        :rtype: pandas.Series
        """

        return self.data[job][build]["metadata"]

    def suites(self, job, build):
        """Getter - suites

        :param job: Job which suites we want.
        :param build: Build which suites we want.
        :type job: str
        :type build: str
        :returns: Suites.
        :rtype: pandas.Series
        """

        return self.data[job][str(build)]["suites"]

    def tests(self, job, build):
        """Getter - tests

        :param job: Job which tests we want.
        :param build: Build which tests we want.
        :type job: str
        :type build: str
        :returns: Tests.
        :rtype: pandas.Series
        """

        return self.data[job][build]["tests"]

    def _parse_tests(self, job, build, log):
        """Process data from robot output.xml file and return JSON structured
        data.

        :param job: The name of job which build output data will be processed.
        :param build: The build which output data will be processed.
        :param log: List of log messages.
        :type job: str
        :type build: dict
        :type log: list of tuples (severity, msg)
        :returns: JSON data structure.
        :rtype: dict
        """

        metadata = {
            "job": job,
            "build": build
        }

        with open(build["file-name"], 'r') as data_file:
            try:
                result = ExecutionResult(data_file)
            except errors.DataError as err:
                log.append(("ERROR", "Error occurred while parsing output.xml: "
                                     "{0}".format(err)))
                return None
        checker = ExecutionChecker(metadata, self._cfg.mapping,
                                   self._cfg.ignore)
        result.visit(checker)

        return checker.data

    def _download_and_parse_build(self, pid, data_queue, job, build, repeat):
        """Download and parse the input data file.

        :param pid: PID of the process executing this method.
        :param data_queue: Shared memory between processes. Queue which keeps
            the result data. This data is then read by the main process and used
            in further processing.
        :param job: Name of the Jenkins job which generated the processed input
            file.
        :param build: Information about the Jenkins build which generated the
            processed input file.
        :param repeat: Repeat the download specified number of times if not
            successful.
        :type pid: int
        :type data_queue: multiprocessing.Manager().Queue()
        :type job: str
        :type build: dict
        :type repeat: int
        """

        logs = list()

        logs.append(("INFO", "  Processing the job/build: {0}: {1}".
                     format(job, build["build"])))

        state = "failed"
        success = False
        data = None
        do_repeat = repeat
        while do_repeat:
            success = download_and_unzip_data_file(self._cfg, job, build, pid,
                                                   logs)
            if success:
                break
            do_repeat -= 1
        if not success:
            logs.append(("ERROR", "It is not possible to download the input "
                                  "data file from the job '{job}', build "
                                  "'{build}', or it is damaged. Skipped.".
                         format(job=job, build=build["build"])))
        if success:
            logs.append(("INFO", "    Processing data from the build '{0}' ...".
                         format(build["build"])))
            data = self._parse_tests(job, build, logs)
            if data is None:
                logs.append(("ERROR", "Input data file from the job '{job}', "
                                      "build '{build}' is damaged. Skipped.".
                             format(job=job, build=build["build"])))
            else:
                state = "processed"

            try:
                remove(build["file-name"])
            except OSError as err:
                logs.append(("ERROR", "Cannot remove the file '{0}': {1}".
                             format(build["file-name"], repr(err))))

        # If the time-period is defined in the specification file, remove all
        # files which are outside the time period.
        timeperiod = self._cfg.input.get("time-period", None)
        if timeperiod and data:
            now = dt.utcnow()
            timeperiod = timedelta(int(timeperiod))
            metadata = data.get("metadata", None)
            if metadata:
                generated = metadata.get("generated", None)
                if generated:
                    generated = dt.strptime(generated, "%Y%m%d %H:%M")
                    if (now - generated) > timeperiod:
                        # Remove the data and the file:
                        state = "removed"
                        data = None
                        logs.append(
                            ("INFO",
                             "    The build {job}/{build} is outdated, will be "
                             "removed".format(job=job, build=build["build"])))
                        file_name = self._cfg.input["file-name"]
                        full_name = join(
                            self._cfg.environment["paths"]["DIR[WORKING,DATA]"],
                            "{job}{sep}{build}{sep}{name}".
                                format(job=job,
                                       sep=SEPARATOR,
                                       build=build["build"],
                                       name=file_name))
                        try:
                            remove(full_name)
                            logs.append(("INFO",
                                         "    The file {name} has been removed".
                                         format(name=full_name)))
                        except OSError as err:
                            logs.append(("ERROR",
                                        "Cannot remove the file '{0}': {1}".
                                        format(full_name, repr(err))))
        logs.append(("INFO", "  Done."))

        for level, line in logs:
            if level == "INFO":
                logging.info(line)
            elif level == "ERROR":
                logging.error(line)
            elif level == "DEBUG":
                logging.debug(line)
            elif level == "CRITICAL":
                logging.critical(line)
            elif level == "WARNING":
                logging.warning(line)

        result = {
            "data": data,
            "state": state,
            "job": job,
            "build": build
        }
        data_queue.put(result)

    def download_and_parse_data(self, repeat=1):
        """Download the input data files, parse input data from input files and
        store in pandas' Series.

        :param repeat: Repeat the download specified number of times if not
            successful.
        :type repeat: int
        """

        logging.info("Downloading and parsing input files ...")

        work_queue = multiprocessing.JoinableQueue()
        manager = multiprocessing.Manager()
        data_queue = manager.Queue()
        cpus = multiprocessing.cpu_count()

        workers = list()
        for cpu in range(cpus):
            worker = Worker(work_queue,
                            data_queue,
                            self._download_and_parse_build)
            worker.daemon = True
            worker.start()
            workers.append(worker)
            os.system("taskset -p -c {0} {1} > /dev/null 2>&1".
                      format(cpu, worker.pid))

        for job, builds in self._cfg.builds.items():
            for build in builds:
                work_queue.put((job, build, repeat))

        work_queue.join()

        logging.info("Done.")

        while not data_queue.empty():
            result = data_queue.get()

            job = result["job"]
            build_nr = result["build"]["build"]

            if result["data"]:
                data = result["data"]
                build_data = pd.Series({
                    "metadata": pd.Series(data["metadata"].values(),
                                          index=data["metadata"].keys()),
                    "suites": pd.Series(data["suites"].values(),
                                        index=data["suites"].keys()),
                    "tests": pd.Series(data["tests"].values(),
                                       index=data["tests"].keys())})

                if self._input_data.get(job, None) is None:
                    self._input_data[job] = pd.Series()
                self._input_data[job][str(build_nr)] = build_data

                self._cfg.set_input_file_name(job, build_nr,
                                              result["build"]["file-name"])

            self._cfg.set_input_state(job, build_nr, result["state"])

        del data_queue

        # Terminate all workers
        for worker in workers:
            worker.terminate()
            worker.join()

        logging.info("Done.")

    @staticmethod
    def _end_of_tag(tag_filter, start=0, closer="'"):
        """Return the index of character in the string which is the end of tag.

        :param tag_filter: The string where the end of tag is being searched.
        :param start: The index where the searching is stated.
        :param closer: The character which is the tag closer.
        :type tag_filter: str
        :type start: int
        :type closer: str
        :returns: The index of the tag closer.
        :rtype: int
        """

        try:
            idx_opener = tag_filter.index(closer, start)
            return tag_filter.index(closer, idx_opener + 1)
        except ValueError:
            return None

    @staticmethod
    def _condition(tag_filter):
        """Create a conditional statement from the given tag filter.

        :param tag_filter: Filter based on tags from the element specification.
        :type tag_filter: str
        :returns: Conditional statement which can be evaluated.
        :rtype: str
        """

        index = 0
        while True:
            index = InputData._end_of_tag(tag_filter, index)
            if index is None:
                return tag_filter
            index += 1
            tag_filter = tag_filter[:index] + " in tags" + tag_filter[index:]

    def filter_data(self, element, params=None, data_set="tests",
                    continue_on_error=False):
        """Filter required data from the given jobs and builds.

        The output data structure is:

        - job 1
          - build 1
            - test (or suite) 1 ID:
              - param 1
              - param 2
              ...
              - param n
            ...
            - test (or suite) n ID:
            ...
          ...
          - build n
        ...
        - job n

        :param element: Element which will use the filtered data.
        :param params: Parameters which will be included in the output. If None,
        all parameters are included.
        :param data_set: The set of data to be filtered: tests, suites,
        metadata.
        :param continue_on_error: Continue if there is error while reading the
        data. The Item will be empty then
        :type element: pandas.Series
        :type params: list
        :type data_set: str
        :type continue_on_error: bool
        :returns: Filtered data.
        :rtype pandas.Series
        """

        try:
            if element["filter"] in ("all", "template"):
                cond = "True"
            else:
                cond = InputData._condition(element["filter"])
            logging.debug("   Filter: {0}".format(cond))
        except KeyError:
            logging.error("  No filter defined.")
            return None

        if params is None:
            params = element.get("parameters", None)
            if params:
                params.append("type")

        data = pd.Series()
        try:
            for job, builds in element["data"].items():
                data[job] = pd.Series()
                for build in builds:
                    data[job][str(build)] = pd.Series()
                    try:
                        data_iter = self.data[job][str(build)][data_set].\
                            iteritems()
                    except KeyError:
                        if continue_on_error:
                            continue
                        else:
                            return None
                    for test_ID, test_data in data_iter:
                        if eval(cond, {"tags": test_data.get("tags", "")}):
                            data[job][str(build)][test_ID] = pd.Series()
                            if params is None:
                                for param, val in test_data.items():
                                    data[job][str(build)][test_ID][param] = val
                            else:
                                for param in params:
                                    try:
                                        data[job][str(build)][test_ID][param] =\
                                            test_data[param]
                                    except KeyError:
                                        data[job][str(build)][test_ID][param] =\
                                            "No Data"
            return data

        except (KeyError, IndexError, ValueError) as err:
            logging.error("   Missing mandatory parameter in the element "
                          "specification: {0}".format(err))
            return None
        except AttributeError:
            return None
        except SyntaxError:
            logging.error("   The filter '{0}' is not correct. Check if all "
                          "tags are enclosed by apostrophes.".format(cond))
            return None

    @staticmethod
    def merge_data(data):
        """Merge data from more jobs and builds to a simple data structure.

        The output data structure is:

        - test (suite) 1 ID:
          - param 1
          - param 2
          ...
          - param n
        ...
        - test (suite) n ID:
        ...

        :param data: Data to merge.
        :type data: pandas.Series
        :returns: Merged data.
        :rtype: pandas.Series
        """

        logging.info("    Merging data ...")

        merged_data = pd.Series()
        for _, builds in data.iteritems():
            for _, item in builds.iteritems():
                for ID, item_data in item.iteritems():
                    merged_data[ID] = item_data

        return merged_data