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