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