Make -P or --pidfile keep programs from running if already running.
[sliver-openvswitch.git] / controller / controller.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include <config.h>
35
36 #include <errno.h>
37 #include <getopt.h>
38 #include <limits.h>
39 #include <signal.h>
40 #include <stdlib.h>
41 #include <string.h>
42
43 #include "buffer.h"
44 #include "command-line.h"
45 #include "compiler.h"
46 #include "daemon.h"
47 #include "fault.h"
48 #include "learning-switch.h"
49 #include "openflow.h"
50 #include "poll-loop.h"
51 #include "rconn.h"
52 #include "timeval.h"
53 #include "util.h"
54 #include "vconn-ssl.h"
55 #include "vconn.h"
56 #include "vlog-socket.h"
57
58 #include "vlog.h"
59 #define THIS_MODULE VLM_controller
60
61 #define MAX_SWITCHES 16
62 #define MAX_LISTENERS 16
63
64 struct switch_ {
65     struct lswitch *lswitch;
66     struct rconn *rconn;
67 };
68
69 /* Learn the ports on which MAC addresses appear? */
70 static bool learn_macs = true;
71
72 /* Set up flows?  (If not, every packet is processed at the controller.) */
73 static bool setup_flows = true;
74
75 /* --max-idle: Maximum idle time, in seconds, before flows expire. */
76 static int max_idle = 60;
77
78 static int do_switching(struct switch_ *);
79 static void new_switch(struct switch_ *, struct vconn *, const char *name);
80 static void parse_options(int argc, char *argv[]);
81 static void usage(void) NO_RETURN;
82
83 int
84 main(int argc, char *argv[])
85 {
86     struct switch_ switches[MAX_SWITCHES];
87     struct vconn *listeners[MAX_LISTENERS];
88     int n_switches, n_listeners;
89     int retval;
90     int i;
91
92     set_program_name(argv[0]);
93     register_fault_handlers();
94     time_init();
95     vlog_init();
96     parse_options(argc, argv);
97     signal(SIGPIPE, SIG_IGN);
98
99     if (argc - optind < 1) {
100         fatal(0, "at least one vconn argument required; use --help for usage");
101     }
102
103     retval = vlog_server_listen(NULL, NULL);
104     if (retval) {
105         fatal(retval, "Could not listen for vlog connections");
106     }
107
108     n_switches = n_listeners = 0;
109     for (i = optind; i < argc; i++) {
110         const char *name = argv[i];
111         struct vconn *vconn;
112         int retval;
113
114         retval = vconn_open(name, &vconn);
115         if (retval) {
116             VLOG_ERR("%s: connect: %s", name, strerror(retval));
117             continue;
118         }
119
120         if (vconn_is_passive(vconn)) {
121             if (n_listeners >= MAX_LISTENERS) {
122                 fatal(0, "max %d passive connections", n_listeners);
123             }
124             listeners[n_listeners++] = vconn;
125         } else {
126             if (n_switches >= MAX_SWITCHES) {
127                 fatal(0, "max %d switch connections", n_switches);
128             }
129             new_switch(&switches[n_switches++], vconn, name);
130         }
131     }
132     if (n_switches == 0 && n_listeners == 0) {
133         fatal(0, "no active or passive switch connections");
134     }
135
136     die_if_already_running();
137     daemonize();
138
139     while (n_switches > 0 || n_listeners > 0) {
140         int iteration;
141         int i;
142
143         /* Accept connections on listening vconns. */
144         for (i = 0; i < n_listeners && n_switches < MAX_SWITCHES; ) {
145             struct vconn *new_vconn;
146             int retval;
147
148             retval = vconn_accept(listeners[i], &new_vconn);
149             if (!retval || retval == EAGAIN) {
150                 if (!retval) {
151                     new_switch(&switches[n_switches++], new_vconn, "tcp");
152                 }
153                 i++;
154             } else {
155                 vconn_close(listeners[i]);
156                 listeners[i] = listeners[--n_listeners];
157             }
158         }
159
160         /* Do some switching work.  Limit the number of iterations so that
161          * callbacks registered with the poll loop don't starve. */
162         for (iteration = 0; iteration < 50; iteration++) {
163             bool progress = false;
164             for (i = 0; i < n_switches; ) {
165                 struct switch_ *this = &switches[i];
166                 int retval = do_switching(this);
167                 if (!retval || retval == EAGAIN) {
168                     if (!retval) {
169                         progress = true;
170                     }
171                     i++;
172                 } else {
173                     lswitch_destroy(this->lswitch);
174                     rconn_destroy(this->rconn);
175                     switches[i] = switches[--n_switches];
176                 }
177             }
178             if (!progress) {
179                 break;
180             }
181         }
182
183         /* Wait for something to happen. */
184         if (n_switches < MAX_SWITCHES) {
185             for (i = 0; i < n_listeners; i++) {
186                 vconn_accept_wait(listeners[i]);
187             }
188         }
189         for (i = 0; i < n_switches; i++) {
190             struct switch_ *sw = &switches[i];
191             rconn_run_wait(sw->rconn);
192             rconn_recv_wait(sw->rconn);
193         }
194         poll_block();
195     }
196
197     return 0;
198 }
199
200 static void
201 new_switch(struct switch_ *sw, struct vconn *vconn, const char *name)
202 {
203     sw->rconn = rconn_new_from_vconn(name, vconn);
204     sw->lswitch = lswitch_create(sw->rconn, learn_macs,
205                                  setup_flows ? max_idle : -1);
206 }
207
208 static int
209 do_switching(struct switch_ *sw)
210 {
211     unsigned int packets_sent;
212     struct buffer *msg;
213
214     packets_sent = rconn_packets_sent(sw->rconn);
215
216     msg = rconn_recv(sw->rconn);
217     if (msg) {
218         lswitch_process_packet(sw->lswitch, sw->rconn, msg);
219         buffer_delete(msg);
220     }
221     rconn_run(sw->rconn);
222
223     return (!rconn_is_alive(sw->rconn) ? EOF
224             : rconn_packets_sent(sw->rconn) != packets_sent ? 0
225             : EAGAIN);
226 }
227
228 static void
229 parse_options(int argc, char *argv[])
230 {
231     enum { OPT_MAX_IDLE = UCHAR_MAX + 1 };
232     static struct option long_options[] = {
233         {"detach",      no_argument, 0, 'D'},
234         {"pidfile",     optional_argument, 0, 'P'},
235         {"force",       no_argument, 0, 'f'},
236         {"hub",         no_argument, 0, 'H'},
237         {"noflow",      no_argument, 0, 'n'},
238         {"max-idle",    required_argument, 0, OPT_MAX_IDLE},
239         {"verbose",     optional_argument, 0, 'v'},
240         {"help",        no_argument, 0, 'h'},
241         {"version",     no_argument, 0, 'V'},
242         VCONN_SSL_LONG_OPTIONS
243         {0, 0, 0, 0},
244     };
245     char *short_options = long_options_to_short_options(long_options);
246
247     for (;;) {
248         int indexptr;
249         int c;
250
251         c = getopt_long(argc, argv, short_options, long_options, &indexptr);
252         if (c == -1) {
253             break;
254         }
255
256         switch (c) {
257         case 'D':
258             set_detach();
259             break;
260
261         case 'P':
262             set_pidfile(optarg);
263             break;
264
265         case 'f':
266             ignore_existing_pidfile();
267             break;
268
269         case 'H':
270             learn_macs = false;
271             break;
272
273         case 'n':
274             setup_flows = false;
275             break;
276
277         case OPT_MAX_IDLE:
278             if (!strcmp(optarg, "permanent")) {
279                 max_idle = OFP_FLOW_PERMANENT;
280             } else {
281                 max_idle = atoi(optarg);
282                 if (max_idle < 1 || max_idle > 65535) {
283                     fatal(0, "--max-idle argument must be between 1 and "
284                           "65535 or the word 'permanent'");
285                 }
286             }
287             break;
288
289         case 'h':
290             usage();
291
292         case 'V':
293             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
294             exit(EXIT_SUCCESS);
295
296         case 'v':
297             vlog_set_verbosity(optarg);
298             break;
299
300         VCONN_SSL_OPTION_HANDLERS
301
302         case '?':
303             exit(EXIT_FAILURE);
304
305         default:
306             abort();
307         }
308     }
309     free(short_options);
310 }
311
312 static void
313 usage(void)
314 {
315     printf("%s: OpenFlow controller\n"
316            "usage: %s [OPTIONS] METHOD\n"
317            "where METHOD is any OpenFlow connection method.\n",
318            program_name, program_name);
319     vconn_usage(true, true);
320     printf("\nOther options:\n"
321            "  -D, --detach            run in background as daemon\n"
322            "  -P, --pidfile[=FILE]    create pidfile (default: %s/controller.pid)\n"
323            "  -f, --force             with -P, start even if already running\n"
324            "  -H, --hub               act as hub instead of learning switch\n"
325            "  -n, --noflow            pass traffic, but don't add flows\n"
326            "  --max-idle=SECS         max idle time for new flows\n"
327            "  -v, --verbose=MODULE[:FACILITY[:LEVEL]]  set logging levels\n"
328            "  -v, --verbose           set maximum verbosity level\n"
329            "  -h, --help              display this help message\n"
330            "  -V, --version           display version information\n",
331            RUNDIR);
332     exit(EXIT_SUCCESS);
333 }