ofproto-dpif: Factor NetFlow active timeouts out of flow expiration.
[sliver-openvswitch.git] / ofproto / netflow.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "netflow.h"
19 #include <arpa/inet.h>
20 #include <errno.h>
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include "byte-order.h"
24 #include "collectors.h"
25 #include "flow.h"
26 #include "netflow.h"
27 #include "ofpbuf.h"
28 #include "ofproto.h"
29 #include "packets.h"
30 #include "poll-loop.h"
31 #include "socket-util.h"
32 #include "timeval.h"
33 #include "util.h"
34 #include "vlog.h"
35
36 VLOG_DEFINE_THIS_MODULE(netflow);
37
38 #define NETFLOW_V5_VERSION 5
39
40 /* Every NetFlow v5 message contains the header that follows.  This is
41  * followed by up to thirty records that describe a terminating flow.
42  * We only send a single record per NetFlow message.
43  */
44 struct netflow_v5_header {
45     ovs_be16 version;              /* NetFlow version is 5. */
46     ovs_be16 count;                /* Number of records in this message. */
47     ovs_be32 sysuptime;            /* System uptime in milliseconds. */
48     ovs_be32 unix_secs;            /* Number of seconds since Unix epoch. */
49     ovs_be32 unix_nsecs;           /* Number of residual nanoseconds
50                                       after epoch seconds. */
51     ovs_be32 flow_seq;             /* Number of flows since sending
52                                       messages began. */
53     uint8_t  engine_type;          /* Engine type. */
54     uint8_t  engine_id;            /* Engine id. */
55     ovs_be16 sampling_interval;    /* Set to zero. */
56 };
57 BUILD_ASSERT_DECL(sizeof(struct netflow_v5_header) == 24);
58
59 /* A NetFlow v5 description of a terminating flow.  It is preceded by a
60  * NetFlow v5 header.
61  */
62 struct netflow_v5_record {
63     ovs_be32 src_addr;             /* Source IP address. */
64     ovs_be32 dst_addr;             /* Destination IP address. */
65     ovs_be32 nexthop;              /* IP address of next hop.  Set to 0. */
66     ovs_be16 input;                /* Input interface index. */
67     ovs_be16 output;               /* Output interface index. */
68     ovs_be32 packet_count;         /* Number of packets. */
69     ovs_be32 byte_count;           /* Number of bytes. */
70     ovs_be32 init_time;            /* Value of sysuptime on first packet. */
71     ovs_be32 used_time;            /* Value of sysuptime on last packet. */
72
73     /* The 'src_port' and 'dst_port' identify the source and destination
74      * port, respectively, for TCP and UDP.  For ICMP, the high-order
75      * byte identifies the type and low-order byte identifies the code
76      * in the 'dst_port' field. */
77     ovs_be16 src_port;
78     ovs_be16 dst_port;
79
80     uint8_t  pad1;
81     uint8_t  tcp_flags;            /* Union of seen TCP flags. */
82     uint8_t  ip_proto;             /* IP protocol. */
83     uint8_t  ip_tos;               /* IP TOS value. */
84     ovs_be16 src_as;               /* Source AS ID.  Set to 0. */
85     ovs_be16 dst_as;               /* Destination AS ID.  Set to 0. */
86     uint8_t  src_mask;             /* Source mask bits.  Set to 0. */
87     uint8_t  dst_mask;             /* Destination mask bits.  Set to 0. */
88     uint8_t  pad[2];
89 };
90 BUILD_ASSERT_DECL(sizeof(struct netflow_v5_record) == 48);
91
92 struct netflow {
93     uint8_t engine_type;          /* Value of engine_type to use. */
94     uint8_t engine_id;            /* Value of engine_id to use. */
95     long long int boot_time;      /* Time when netflow_create() was called. */
96     struct collectors *collectors; /* NetFlow collectors. */
97     bool add_id_to_iface;         /* Put the 7 least signficiant bits of
98                                    * 'engine_id' into the most signficant
99                                    * bits of the interface fields. */
100     uint32_t netflow_cnt;         /* Flow sequence number for NetFlow. */
101     struct ofpbuf packet;         /* NetFlow packet being accumulated. */
102     long long int active_timeout; /* Timeout for flows that are still active. */
103     long long int next_timeout;   /* Next scheduled active timeout. */
104     long long int reconfig_time;  /* When we reconfigured the timeouts. */
105 };
106
107 static void
108 gen_netflow_rec(struct netflow *nf, struct netflow_flow *nf_flow,
109                 struct ofexpired *expired,
110                 uint32_t packet_count, uint32_t byte_count)
111 {
112     struct netflow_v5_header *nf_hdr;
113     struct netflow_v5_record *nf_rec;
114
115     if (!nf->packet.size) {
116         struct timespec now;
117
118         time_wall_timespec(&now);
119
120         nf_hdr = ofpbuf_put_zeros(&nf->packet, sizeof *nf_hdr);
121         nf_hdr->version = htons(NETFLOW_V5_VERSION);
122         nf_hdr->count = htons(0);
123         nf_hdr->sysuptime = htonl(time_msec() - nf->boot_time);
124         nf_hdr->unix_secs = htonl(now.tv_sec);
125         nf_hdr->unix_nsecs = htonl(now.tv_nsec);
126         nf_hdr->flow_seq = htonl(nf->netflow_cnt++);
127         nf_hdr->engine_type = nf->engine_type;
128         nf_hdr->engine_id = nf->engine_id;
129         nf_hdr->sampling_interval = htons(0);
130     }
131
132     nf_hdr = nf->packet.data;
133     nf_hdr->count = htons(ntohs(nf_hdr->count) + 1);
134
135     nf_rec = ofpbuf_put_zeros(&nf->packet, sizeof *nf_rec);
136     nf_rec->src_addr = expired->flow.nw_src;
137     nf_rec->dst_addr = expired->flow.nw_dst;
138     nf_rec->nexthop = htonl(0);
139     if (nf->add_id_to_iface) {
140         uint16_t iface = (nf->engine_id & 0x7f) << 9;
141         nf_rec->input = htons(iface | (expired->flow.in_port & 0x1ff));
142         nf_rec->output = htons(iface | (nf_flow->output_iface & 0x1ff));
143     } else {
144         nf_rec->input = htons(expired->flow.in_port);
145         nf_rec->output = htons(nf_flow->output_iface);
146     }
147     nf_rec->packet_count = htonl(packet_count);
148     nf_rec->byte_count = htonl(byte_count);
149     nf_rec->init_time = htonl(nf_flow->created - nf->boot_time);
150     nf_rec->used_time = htonl(MAX(nf_flow->created, expired->used)
151                              - nf->boot_time);
152     if (expired->flow.nw_proto == IPPROTO_ICMP) {
153         /* In NetFlow, the ICMP type and code are concatenated and
154          * placed in the 'dst_port' field. */
155         uint8_t type = ntohs(expired->flow.tp_src);
156         uint8_t code = ntohs(expired->flow.tp_dst);
157         nf_rec->src_port = htons(0);
158         nf_rec->dst_port = htons((type << 8) | code);
159     } else {
160         nf_rec->src_port = expired->flow.tp_src;
161         nf_rec->dst_port = expired->flow.tp_dst;
162     }
163     nf_rec->tcp_flags = nf_flow->tcp_flags;
164     nf_rec->ip_proto = expired->flow.nw_proto;
165     nf_rec->ip_tos = expired->flow.nw_tos & IP_DSCP_MASK;
166
167     /* NetFlow messages are limited to 30 records. */
168     if (ntohs(nf_hdr->count) >= 30) {
169         netflow_run(nf);
170     }
171 }
172
173 void
174 netflow_expire(struct netflow *nf, struct netflow_flow *nf_flow,
175                struct ofexpired *expired)
176 {
177     uint64_t pkt_delta = expired->packet_count - nf_flow->packet_count_off;
178     uint64_t byte_delta = expired->byte_count - nf_flow->byte_count_off;
179
180     nf_flow->last_expired += nf->active_timeout;
181
182     /* NetFlow only reports on IP packets and we should only report flows
183      * that actually have traffic. */
184     if (expired->flow.dl_type != htons(ETH_TYPE_IP) || pkt_delta == 0) {
185         return;
186     }
187
188     if ((byte_delta >> 32) <= 175) {
189         /* NetFlow v5 records are limited to 32-bit counters.  If we've wrapped
190          * a counter, send as multiple records so we don't lose track of any
191          * traffic.  We try to evenly distribute the packet and byte counters,
192          * so that the bytes-per-packet lengths don't look wonky across the
193          * records. */
194         while (byte_delta) {
195             int n_recs = (byte_delta + UINT32_MAX - 1) / UINT32_MAX;
196             uint32_t pkt_count = pkt_delta / n_recs;
197             uint32_t byte_count = byte_delta / n_recs;
198
199             gen_netflow_rec(nf, nf_flow, expired, pkt_count, byte_count);
200
201             pkt_delta -= pkt_count;
202             byte_delta -= byte_count;
203         }
204     } else {
205         /* In 600 seconds, a 10GbE link can theoretically transmit 75 * 10**10
206          * == 175 * 2**32 bytes.  The byte counter is bigger than that, so it's
207          * probably a bug--for example, the netdev code uses UINT64_MAX to
208          * report "unknown value", and perhaps that has leaked through to here.
209          *
210          * We wouldn't want to hit the loop above in this case, because it
211          * would try to send up to UINT32_MAX netflow records, which would take
212          * a long time.
213          */
214         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
215
216         VLOG_WARN_RL(&rl, "impossible byte counter %"PRIu64, byte_delta);
217     }
218
219     /* Update flow tracking data. */
220     nf_flow->created = 0;
221     nf_flow->packet_count_off = expired->packet_count;
222     nf_flow->byte_count_off = expired->byte_count;
223     nf_flow->tcp_flags = 0;
224 }
225
226 /* Returns true if it's time to send out a round of NetFlow active timeouts,
227  * false otherwise. */
228 bool
229 netflow_run(struct netflow *nf)
230 {
231     if (nf->packet.size) {
232         collectors_send(nf->collectors, nf->packet.data, nf->packet.size);
233         nf->packet.size = 0;
234     }
235
236     if (nf->active_timeout && time_msec() >= nf->next_timeout) {
237         nf->next_timeout = time_msec() + 1000;
238         return true;
239     } else {
240         return false;
241     }
242 }
243
244 void
245 netflow_wait(struct netflow *nf)
246 {
247     if (nf->active_timeout) {
248         poll_timer_wait_until(nf->next_timeout);
249     }
250     if (nf->packet.size) {
251         poll_immediate_wake();
252     }
253 }
254
255 int
256 netflow_set_options(struct netflow *nf,
257                     const struct netflow_options *nf_options)
258 {
259     int error = 0;
260     long long int old_timeout;
261
262     nf->engine_type = nf_options->engine_type;
263     nf->engine_id = nf_options->engine_id;
264     nf->add_id_to_iface = nf_options->add_id_to_iface;
265
266     collectors_destroy(nf->collectors);
267     collectors_create(&nf_options->collectors, 0, &nf->collectors);
268
269     old_timeout = nf->active_timeout;
270     if (nf_options->active_timeout >= 0) {
271         nf->active_timeout = nf_options->active_timeout;
272     } else {
273         nf->active_timeout = NF_ACTIVE_TIMEOUT_DEFAULT;
274     }
275     nf->active_timeout *= 1000;
276     if (old_timeout != nf->active_timeout) {
277         nf->reconfig_time = time_msec();
278         nf->next_timeout = time_msec();
279     }
280
281     return error;
282 }
283
284 struct netflow *
285 netflow_create(void)
286 {
287     struct netflow *nf = xzalloc(sizeof *nf);
288     nf->engine_type = 0;
289     nf->engine_id = 0;
290     nf->boot_time = time_msec();
291     nf->collectors = NULL;
292     nf->add_id_to_iface = false;
293     nf->netflow_cnt = 0;
294     ofpbuf_init(&nf->packet, 1500);
295     return nf;
296 }
297
298 void
299 netflow_destroy(struct netflow *nf)
300 {
301     if (nf) {
302         ofpbuf_uninit(&nf->packet);
303         collectors_destroy(nf->collectors);
304         free(nf);
305     }
306 }
307
308 /* Initializes a new 'nf_flow' given that the caller has already cleared it to
309  * all-zero-bits. */
310 void
311 netflow_flow_init(struct netflow_flow *nf_flow OVS_UNUSED)
312 {
313     /* Nothing to do. */
314 }
315
316 void
317 netflow_flow_clear(struct netflow_flow *nf_flow)
318 {
319     uint16_t output_iface = nf_flow->output_iface;
320
321     memset(nf_flow, 0, sizeof *nf_flow);
322     nf_flow->output_iface = output_iface;
323 }
324
325 void
326 netflow_flow_update_time(struct netflow *nf, struct netflow_flow *nf_flow,
327                          long long int used)
328 {
329     if (!nf_flow->created) {
330         nf_flow->created = used;
331     }
332
333     if (!nf || !nf->active_timeout || !nf_flow->last_expired ||
334         nf->reconfig_time > nf_flow->last_expired) {
335         /* Keep the time updated to prevent a flood of expiration in
336          * the future. */
337         nf_flow->last_expired = time_msec();
338     }
339 }
340
341 void
342 netflow_flow_update_flags(struct netflow_flow *nf_flow, uint8_t tcp_flags)
343 {
344     nf_flow->tcp_flags |= tcp_flags;
345 }
346
347 bool
348 netflow_active_timeout_expired(struct netflow *nf, struct netflow_flow *nf_flow)
349 {
350     if (nf->active_timeout) {
351         return time_msec() > nf_flow->last_expired + nf->active_timeout;
352     }
353
354     return false;
355 }