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