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