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