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