sflow: Use hash table instead of sparse array for sflow ports.
[sliver-openvswitch.git] / ofproto / ofproto-sflow.c
1 /*
2  * Copyright (c) 2009, 2010 InMon Corp.
3  * Copyright (c) 2009 Nicira Networks.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at:
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <config.h>
19 #include "ofproto-sflow.h"
20 #include <inttypes.h>
21 #include <stdlib.h>
22 #include "collectors.h"
23 #include "dpif.h"
24 #include "compiler.h"
25 #include "hash.h"
26 #include "hmap.h"
27 #include "netdev.h"
28 #include "ofpbuf.h"
29 #include "ofproto.h"
30 #include "poll-loop.h"
31 #include "sflow_api.h"
32 #include "socket-util.h"
33 #include "timeval.h"
34 #include "vlog.h"
35
36 VLOG_DEFINE_THIS_MODULE(sflow)
37
38 struct ofproto_sflow_port {
39     struct hmap_node hmap_node; /* In struct ofproto_sflow's "ports" hmap. */
40     struct netdev *netdev;      /* Underlying network device, for stats. */
41     SFLDataSource_instance dsi; /* sFlow library's notion of port number. */
42     uint16_t odp_port;          /* ODP port number. */
43 };
44
45 struct ofproto_sflow {
46     struct ofproto *ofproto;
47     struct collectors *collectors;
48     SFLAgent *sflow_agent;
49     struct ofproto_sflow_options *options;
50     struct dpif *dpif;
51     time_t next_tick;
52     size_t n_flood, n_all;
53     struct hmap ports;          /* Contains "struct ofproto_sflow_port"s. */
54 };
55
56 static void ofproto_sflow_del_port__(struct ofproto_sflow *,
57                                      struct ofproto_sflow_port *);
58
59 #define RECEIVER_INDEX 1
60
61 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
62
63 static bool
64 nullable_string_is_equal(const char *a, const char *b)
65 {
66     return a ? b && !strcmp(a, b) : !b;
67 }
68
69 static bool
70 ofproto_sflow_options_equal(const struct ofproto_sflow_options *a,
71                             const struct ofproto_sflow_options *b)
72 {
73     return (svec_equal(&a->targets, &b->targets)
74             && a->sampling_rate == b->sampling_rate
75             && a->polling_interval == b->polling_interval
76             && a->header_len == b->header_len
77             && a->sub_id == b->sub_id
78             && nullable_string_is_equal(a->agent_device, b->agent_device)
79             && nullable_string_is_equal(a->control_ip, b->control_ip));
80 }
81
82 static struct ofproto_sflow_options *
83 ofproto_sflow_options_clone(const struct ofproto_sflow_options *old)
84 {
85     struct ofproto_sflow_options *new = xmemdup(old, sizeof *old);
86     svec_clone(&new->targets, &old->targets);
87     new->agent_device = old->agent_device ? xstrdup(old->agent_device) : NULL;
88     new->control_ip = old->control_ip ? xstrdup(old->control_ip) : NULL;
89     return new;
90 }
91
92 static void
93 ofproto_sflow_options_destroy(struct ofproto_sflow_options *options)
94 {
95     if (options) {
96         svec_destroy(&options->targets);
97         free(options->agent_device);
98         free(options->control_ip);
99         free(options);
100     }
101 }
102
103 /* sFlow library callback to allocate memory. */
104 static void *
105 sflow_agent_alloc_cb(void *magic OVS_UNUSED, SFLAgent *agent OVS_UNUSED,
106                      size_t bytes)
107 {
108     return calloc(1, bytes);
109 }
110
111 /* sFlow library callback to free memory. */
112 static int
113 sflow_agent_free_cb(void *magic OVS_UNUSED, SFLAgent *agent OVS_UNUSED,
114                     void *obj)
115 {
116     free(obj);
117     return 0;
118 }
119
120 /* sFlow library callback to report error. */
121 static void
122 sflow_agent_error_cb(void *magic OVS_UNUSED, SFLAgent *agent OVS_UNUSED,
123                      char *msg)
124 {
125     VLOG_WARN("sFlow agent error: %s", msg);
126 }
127
128 /* sFlow library callback to send datagram. */
129 static void
130 sflow_agent_send_packet_cb(void *os_, SFLAgent *agent OVS_UNUSED,
131                            SFLReceiver *receiver OVS_UNUSED, u_char *pkt,
132                            uint32_t pktLen)
133 {
134     struct ofproto_sflow *os = os_;
135     collectors_send(os->collectors, pkt, pktLen);
136 }
137
138 static struct ofproto_sflow_port *
139 ofproto_sflow_find_port(const struct ofproto_sflow *os, uint16_t odp_port)
140 {
141     struct ofproto_sflow_port *osp;
142
143     HMAP_FOR_EACH_IN_BUCKET (osp, struct ofproto_sflow_port, hmap_node,
144                              hash_int(odp_port, 0), &os->ports) {
145         if (osp->odp_port == odp_port) {
146             return osp;
147         }
148     }
149     return NULL;
150 }
151
152 static void
153 sflow_agent_get_counters(void *os_, SFLPoller *poller,
154                          SFL_COUNTERS_SAMPLE_TYPE *cs)
155 {
156     struct ofproto_sflow *os = os_;
157     SFLCounters_sample_element elem;
158     struct ofproto_sflow_port *osp;
159     SFLIf_counters *counters;
160     struct netdev_stats stats;
161     enum netdev_flags flags;
162     uint32_t current;
163
164     osp = ofproto_sflow_find_port(os, poller->bridgePort);
165     if (!osp) {
166         return;
167     }
168
169     elem.tag = SFLCOUNTERS_GENERIC;
170     counters = &elem.counterBlock.generic;
171     counters->ifIndex = SFL_DS_INDEX(poller->dsi);
172     counters->ifType = 6;
173     if (!netdev_get_features(osp->netdev, &current, NULL, NULL, NULL)) {
174       /* The values of ifDirection come from MAU MIB (RFC 2668): 0 = unknown,
175          1 = full-duplex, 2 = half-duplex, 3 = in, 4=out */
176         counters->ifSpeed = netdev_features_to_bps(current);
177         counters->ifDirection = (netdev_features_is_full_duplex(current)
178                                  ? 1 : 2);
179     } else {
180         counters->ifSpeed = 100000000;
181         counters->ifDirection = 0;
182     }
183     if (!netdev_get_flags(osp->netdev, &flags) && flags & NETDEV_UP) {
184         bool carrier;
185
186         counters->ifStatus = 1; /* ifAdminStatus up. */
187         if (!netdev_get_carrier(osp->netdev, &carrier) && carrier) {
188             counters->ifStatus |= 2; /* ifOperStatus us. */
189         }
190     } else {
191         counters->ifStatus = 0;  /* Down. */
192     }
193
194     /* XXX
195        1. Is the multicast counter filled in?
196        2. Does the multicast counter include broadcasts?
197        3. Does the rx_packets counter include multicasts/broadcasts?
198     */
199     netdev_get_stats(osp->netdev, &stats);
200     counters->ifInOctets = stats.rx_bytes;
201     counters->ifInUcastPkts = stats.rx_packets;
202     counters->ifInMulticastPkts = stats.multicast;
203     counters->ifInBroadcastPkts = -1;
204     counters->ifInDiscards = stats.rx_dropped;
205     counters->ifInErrors = stats.rx_errors;
206     counters->ifInUnknownProtos = -1;
207     counters->ifOutOctets = stats.tx_bytes;
208     counters->ifOutUcastPkts = stats.tx_packets;
209     counters->ifOutMulticastPkts = -1;
210     counters->ifOutBroadcastPkts = -1;
211     counters->ifOutDiscards = stats.tx_dropped;
212     counters->ifOutErrors = stats.tx_errors;
213     counters->ifPromiscuousMode = 0;
214
215     SFLADD_ELEMENT(cs, &elem);
216     sfl_poller_writeCountersSample(poller, cs);
217 }
218
219 /* Obtains an address to use for the local sFlow agent and stores it into
220  * '*agent_addr'.  Returns true if successful, false on failure.
221  *
222  * The sFlow agent address should be a local IP address that is persistent and
223  * reachable over the network, if possible.  The IP address associated with
224  * 'agent_device' is used if it has one, and otherwise 'control_ip', the IP
225  * address used to talk to the controller. */
226 static bool
227 sflow_choose_agent_address(const char *agent_device, const char *control_ip,
228                            SFLAddress *agent_addr)
229 {
230     struct in_addr in4;
231
232     memset(agent_addr, 0, sizeof *agent_addr);
233     agent_addr->type = SFLADDRESSTYPE_IP_V4;
234
235     if (agent_device) {
236         struct netdev *netdev;
237
238         if (!netdev_open_default(agent_device, &netdev)) {
239             int error = netdev_get_in4(netdev, &in4, NULL);
240             netdev_close(netdev);
241             if (!error) {
242                 goto success;
243             }
244         }
245     }
246
247     if (control_ip && !lookup_ip(control_ip, &in4)) {
248         goto success;
249     }
250
251     VLOG_ERR("could not determine IP address for sFlow agent");
252     return false;
253
254 success:
255     agent_addr->address.ip_v4.addr = in4.s_addr;
256     return true;
257 }
258
259 void
260 ofproto_sflow_clear(struct ofproto_sflow *os)
261 {
262     if (os->sflow_agent) {
263         sfl_agent_release(os->sflow_agent);
264         os->sflow_agent = NULL;
265     }
266     collectors_destroy(os->collectors);
267     os->collectors = NULL;
268     ofproto_sflow_options_destroy(os->options);
269     os->options = NULL;
270
271     /* Turn off sampling to save CPU cycles. */
272     dpif_set_sflow_probability(os->dpif, 0);
273 }
274
275 bool
276 ofproto_sflow_is_enabled(const struct ofproto_sflow *os)
277 {
278     return os->collectors != NULL;
279 }
280
281 struct ofproto_sflow *
282 ofproto_sflow_create(struct dpif *dpif)
283 {
284     struct ofproto_sflow *os;
285
286     os = xcalloc(1, sizeof *os);
287     os->dpif = dpif;
288     os->next_tick = time_now() + 1;
289     hmap_init(&os->ports);
290     return os;
291 }
292
293 void
294 ofproto_sflow_destroy(struct ofproto_sflow *os)
295 {
296     if (os) {
297         struct ofproto_sflow_port *osp, *next;
298
299         ofproto_sflow_clear(os);
300         HMAP_FOR_EACH_SAFE (osp, next, struct ofproto_sflow_port, hmap_node,
301                             &os->ports) {
302             ofproto_sflow_del_port__(os, osp);
303         }
304         hmap_destroy(&os->ports);
305         free(os);
306     }
307 }
308
309 static void
310 ofproto_sflow_add_poller(struct ofproto_sflow *os,
311                          struct ofproto_sflow_port *osp, uint16_t odp_port)
312 {
313     SFLPoller *poller = sfl_agent_addPoller(os->sflow_agent, &osp->dsi, os,
314                                             sflow_agent_get_counters);
315     sfl_poller_set_sFlowCpInterval(poller, os->options->polling_interval);
316     sfl_poller_set_sFlowCpReceiver(poller, RECEIVER_INDEX);
317     sfl_poller_set_bridgePort(poller, odp_port);
318 }
319
320 static void
321 ofproto_sflow_add_sampler(struct ofproto_sflow *os,
322                           struct ofproto_sflow_port *osp)
323 {
324     SFLSampler *sampler = sfl_agent_addSampler(os->sflow_agent, &osp->dsi);
325     sfl_sampler_set_sFlowFsPacketSamplingRate(sampler, os->options->sampling_rate);
326     sfl_sampler_set_sFlowFsMaximumHeaderSize(sampler, os->options->header_len);
327     sfl_sampler_set_sFlowFsReceiver(sampler, RECEIVER_INDEX);
328 }
329
330 void
331 ofproto_sflow_add_port(struct ofproto_sflow *os, uint16_t odp_port,
332                        const char *netdev_name)
333 {
334     struct ofproto_sflow_port *osp;
335     struct netdev *netdev;
336     uint32_t ifindex;
337     int error;
338
339     ofproto_sflow_del_port(os, odp_port);
340
341     /* Open network device. */
342     error = netdev_open_default(netdev_name, &netdev);
343     if (error) {
344         VLOG_WARN_RL(&rl, "failed to open network device \"%s\": %s",
345                      netdev_name, strerror(error));
346         return;
347     }
348
349     /* Add to table of ports. */
350     osp = xmalloc(sizeof *osp);
351     osp->netdev = netdev;
352     ifindex = netdev_get_ifindex(netdev);
353     if (ifindex <= 0) {
354         ifindex = (os->sflow_agent->subId << 16) + odp_port;
355     }
356     SFL_DS_SET(osp->dsi, 0, ifindex, 0);
357     osp->odp_port = odp_port;
358     hmap_insert(&os->ports, &osp->hmap_node, hash_int(odp_port, 0));
359
360     /* Add poller and sampler. */
361     if (os->sflow_agent) {
362         ofproto_sflow_add_poller(os, osp, odp_port);
363         ofproto_sflow_add_sampler(os, osp);
364     }
365 }
366
367 static void
368 ofproto_sflow_del_port__(struct ofproto_sflow *os,
369                          struct ofproto_sflow_port *osp)
370 {
371     if (os->sflow_agent) {
372         sfl_agent_removePoller(os->sflow_agent, &osp->dsi);
373         sfl_agent_removeSampler(os->sflow_agent, &osp->dsi);
374     }
375     netdev_close(osp->netdev);
376     hmap_remove(&os->ports, &osp->hmap_node);
377     free(osp);
378 }
379
380 void
381 ofproto_sflow_del_port(struct ofproto_sflow *os, uint16_t odp_port)
382 {
383     struct ofproto_sflow_port *osp = ofproto_sflow_find_port(os, odp_port);
384     if (osp) {
385         ofproto_sflow_del_port__(os, osp);
386     }
387 }
388
389 void
390 ofproto_sflow_set_options(struct ofproto_sflow *os,
391                           const struct ofproto_sflow_options *options)
392 {
393     struct ofproto_sflow_port *osp;
394     bool options_changed;
395     SFLReceiver *receiver;
396     SFLAddress agentIP;
397     time_t now;
398
399     if (!options->targets.n || !options->sampling_rate) {
400         /* No point in doing any work if there are no targets or nothing to
401          * sample. */
402         ofproto_sflow_clear(os);
403         return;
404     }
405
406     options_changed = (!os->options
407                        || !ofproto_sflow_options_equal(options, os->options));
408
409     /* Configure collectors if options have changed or if we're shortchanged in
410      * collectors (which indicates that opening one or more of the configured
411      * collectors failed, so that we should retry). */
412     if (options_changed
413         || collectors_count(os->collectors) < options->targets.n) {
414         collectors_destroy(os->collectors);
415         collectors_create(&options->targets, SFL_DEFAULT_COLLECTOR_PORT,
416                           &os->collectors);
417         if (os->collectors == NULL) {
418             VLOG_WARN_RL(&rl, "no collectors could be initialized, "
419                          "sFlow disabled");
420             ofproto_sflow_clear(os);
421             return;
422         }
423     }
424
425     /* Avoid reconfiguring if options didn't change. */
426     if (!options_changed) {
427         return;
428     }
429     ofproto_sflow_options_destroy(os->options);
430     os->options = ofproto_sflow_options_clone(options);
431
432     /* Choose agent IP address. */
433     if (!sflow_choose_agent_address(options->agent_device,
434                                     options->control_ip, &agentIP)) {
435         ofproto_sflow_clear(os);
436         return;
437     }
438
439     /* Create agent. */
440     VLOG_INFO("creating sFlow agent %d", options->sub_id);
441     if (os->sflow_agent) {
442         sfl_agent_release(os->sflow_agent);
443     }
444     os->sflow_agent = xcalloc(1, sizeof *os->sflow_agent);
445     now = time_wall();
446     sfl_agent_init(os->sflow_agent,
447                    &agentIP,
448                    options->sub_id,
449                    now,         /* Boot time. */
450                    now,         /* Current time. */
451                    os,          /* Pointer supplied to callbacks. */
452                    sflow_agent_alloc_cb,
453                    sflow_agent_free_cb,
454                    sflow_agent_error_cb,
455                    sflow_agent_send_packet_cb);
456
457     receiver = sfl_agent_addReceiver(os->sflow_agent);
458     sfl_receiver_set_sFlowRcvrOwner(receiver, "Open vSwitch sFlow");
459     sfl_receiver_set_sFlowRcvrTimeout(receiver, 0xffffffff);
460
461     /* Set the sampling_rate down in the datapath. */
462     dpif_set_sflow_probability(os->dpif,
463                                MAX(1, UINT32_MAX / options->sampling_rate));
464
465     /* Add samplers and pollers for the currently known ports. */
466     HMAP_FOR_EACH (osp, struct ofproto_sflow_port, hmap_node, &os->ports) {
467         ofproto_sflow_add_poller(os, osp, osp->odp_port);
468         ofproto_sflow_add_sampler(os, osp);
469     }
470 }
471
472 static int
473 ofproto_sflow_odp_port_to_ifindex(const struct ofproto_sflow *os,
474                                   uint16_t odp_port)
475 {
476     struct ofproto_sflow_port *osp = ofproto_sflow_find_port(os, odp_port);
477     return osp ? SFL_DS_INDEX(osp->dsi) : 0;
478 }
479
480 void
481 ofproto_sflow_received(struct ofproto_sflow *os, struct odp_msg *msg)
482 {
483     SFL_FLOW_SAMPLE_TYPE fs;
484     SFLFlow_sample_element hdrElem;
485     SFLSampled_header *header;
486     SFLFlow_sample_element switchElem;
487     SFLSampler *sampler;
488     const struct odp_sflow_sample_header *hdr;
489     const union odp_action *actions;
490     struct ofpbuf payload;
491     size_t n_actions, n_outputs;
492     size_t min_size;
493     flow_t flow;
494     size_t i;
495
496     /* Get odp_sflow_sample_header. */
497     min_size = sizeof *msg + sizeof *hdr;
498     if (min_size > msg->length) {
499         VLOG_WARN_RL(&rl, "sFlow packet too small (%"PRIu32" < %zu)",
500                      msg->length, min_size);
501         return;
502     }
503     hdr = (const struct odp_sflow_sample_header *) (msg + 1);
504
505     /* Get actions. */
506     n_actions = hdr->n_actions;
507     if (n_actions > 65536 / sizeof *actions) {
508         VLOG_WARN_RL(&rl, "too many actions in sFlow packet (%zu > %zu)",
509                      65536 / sizeof *actions, n_actions);
510         return;
511     }
512     min_size += n_actions * sizeof *actions;
513     if (min_size > msg->length) {
514         VLOG_WARN_RL(&rl, "sFlow packet with %zu actions too small "
515                      "(%"PRIu32" < %zu)",
516                      n_actions, msg->length, min_size);
517         return;
518     }
519     actions = (const union odp_action *) (hdr + 1);
520
521     /* Get packet payload and extract flow. */
522     payload.data = (union odp_action *) (actions + n_actions);
523     payload.size = msg->length - min_size;
524     flow_extract(&payload, 0, msg->port, &flow);
525
526     /* Build a flow sample */
527     memset(&fs, 0, sizeof fs);
528     fs.input = ofproto_sflow_odp_port_to_ifindex(os, msg->port);
529     fs.output = 0;              /* Filled in correctly below. */
530     fs.sample_pool = hdr->sample_pool;
531
532     /* We are going to give it to the sampler that represents this input port.
533      * By implementing "ingress-only" sampling like this we ensure that we
534      * never have to offer the same sample to more than one sampler. */
535     sampler = sfl_agent_getSamplerByIfIndex(os->sflow_agent, fs.input);
536     if (!sampler) {
537         VLOG_WARN_RL(&rl, "no sampler for input ifIndex (%"PRIu32")",
538                      fs.input);
539         return;
540     }
541
542     /* Sampled header. */
543     memset(&hdrElem, 0, sizeof hdrElem);
544     hdrElem.tag = SFLFLOW_HEADER;
545     header = &hdrElem.flowType.header;
546     header->header_protocol = SFLHEADER_ETHERNET_ISO8023;
547     /* The frame_length should include the Ethernet FCS (4 bytes),
548        but it has already been stripped,  so we need to add 4 here. */
549     header->frame_length = payload.size + 4;
550     /* Ethernet FCS stripped off. */
551     header->stripped = 4;
552     header->header_length = MIN(payload.size,
553                                 sampler->sFlowFsMaximumHeaderSize);
554     header->header_bytes = payload.data;
555
556     /* Add extended switch element. */
557     memset(&switchElem, 0, sizeof(switchElem));
558     switchElem.tag = SFLFLOW_EX_SWITCH;
559     switchElem.flowType.sw.src_vlan = ntohs(flow.dl_vlan);
560     switchElem.flowType.sw.src_priority = -1; /* XXX */
561      /* Initialize the output VLAN and priority to be the same as the input,
562         but these fields can be overriden below if affected by an action. */
563     switchElem.flowType.sw.dst_vlan = switchElem.flowType.sw.src_vlan;
564     switchElem.flowType.sw.dst_priority = switchElem.flowType.sw.src_priority;
565
566     /* Figure out the output ports. */
567     n_outputs = 0;
568     for (i = 0; i < n_actions; i++) {
569         const union odp_action *a = &actions[i];
570
571         switch (a->type) {
572         case ODPAT_OUTPUT:
573             fs.output = ofproto_sflow_odp_port_to_ifindex(os, a->output.port);
574             n_outputs++;
575             break;
576
577         case ODPAT_OUTPUT_GROUP:
578             n_outputs += (a->output_group.group == DP_GROUP_FLOOD ? os->n_flood
579                           : a->output_group.group == DP_GROUP_ALL ? os->n_all
580                           : 0);
581             break;
582
583         case ODPAT_SET_VLAN_VID:
584             switchElem.flowType.sw.dst_vlan = ntohs(a->vlan_vid.vlan_vid);
585             break;
586
587         case ODPAT_SET_VLAN_PCP:
588             switchElem.flowType.sw.dst_priority = a->vlan_pcp.vlan_pcp;
589             break;
590
591         default:
592             break;
593         }
594     }
595
596     /* Set output port, as defined by http://www.sflow.org/sflow_version_5.txt
597        (search for "Input/output port information"). */
598     if (!n_outputs) {
599         /* This value indicates that the packet was dropped for an unknown
600          * reason. */
601         fs.output = 0x40000000 | 256;
602     } else if (n_outputs > 1 || !fs.output) {
603         /* Setting the high bit means "multiple output ports". */
604         fs.output = 0x80000000 | n_outputs;
605     }
606
607     /* Submit the flow sample to be encoded into the next datagram. */
608     SFLADD_ELEMENT(&fs, &hdrElem);
609     SFLADD_ELEMENT(&fs, &switchElem);
610     sfl_sampler_writeFlowSample(sampler, &fs);
611 }
612
613 void
614 ofproto_sflow_set_group_sizes(struct ofproto_sflow *os,
615                               size_t n_flood, size_t n_all)
616 {
617     os->n_flood = n_flood;
618     os->n_all = n_all;
619 }
620
621 void
622 ofproto_sflow_run(struct ofproto_sflow *os)
623 {
624     if (ofproto_sflow_is_enabled(os)) {
625         time_t now = time_now();
626         if (now >= os->next_tick) {
627             sfl_agent_tick(os->sflow_agent, time_wall());
628             os->next_tick = now + 1;
629         }
630     }
631 }
632
633 void
634 ofproto_sflow_wait(struct ofproto_sflow *os)
635 {
636     if (ofproto_sflow_is_enabled(os)) {
637         poll_timer_wait_until(os->next_tick * 1000LL);
638     }
639 }