]> git.proxmox.com Git - mirror_ifupdown2.git/blob - sbin/ifupdown
execute 'up' on upper devices if ifup is called with --with-depends
[mirror_ifupdown2.git] / sbin / ifupdown
1 #!/usr/bin/python
2 # PYTHON_ARGCOMPLETE_OK
3
4 import sys
5 import os
6 import argcomplete
7 import argparse
8 from ifupdown.ifupdownmain import *
9
10 import logging
11
12 lockfile="/run/network/.lock"
13 logger = None
14
15 def run_up(args):
16 logger.debug('args = %s' %str(args))
17
18 try:
19 iflist = args.iflist
20 if len(args.iflist) == 0:
21 iflist = None
22 logger.debug('creating ifupdown object ..')
23 cachearg=(False if (iflist or args.nocache or
24 args.perfmode or args.noact)
25 else True)
26 ifupdown_handle = ifupdownMain(force=args.force,
27 withdepends=args.withdepends,
28 perfmode=args.perfmode,
29 njobs=args.jobs,
30 dryrun=args.noact,
31 cache=cachearg,
32 addons_enable=not args.noaddons,
33 statemanager_enable=not args.noaddons)
34
35 if args.noaddons:
36 ifupdown_handle.up(['up'], args.all, args.CLASS, iflist,
37 excludepats=args.excludepats,
38 printdependency=args.printdependency)
39 else:
40 ifupdown_handle.up(['pre-up', 'up', 'post-up'],
41 args.all, args.CLASS, iflist,
42 excludepats=args.excludepats,
43 printdependency=args.printdependency)
44 except:
45 raise
46
47 def run_down(args):
48 logger.debug('args = %s' %str(args))
49
50 try:
51 iflist = args.iflist
52 logger.debug('creating ifupdown object ..')
53 cachearg=(False if (iflist or args.nocache or
54 args.perfmode or args.noact)
55 else True)
56 ifupdown_handle = ifupdownMain(force=args.force,
57 withdepends=args.withdepends,
58 perfmode=args.perfmode,
59 njobs=args.jobs,
60 dryrun=args.noact,
61 cache=cachearg,
62 addons_enable=not args.noaddons,
63 statemanager_enable=not args.noaddons)
64
65 ifupdown_handle.down(['pre-down', 'down', 'post-down'],
66 args.all, args.CLASS, iflist,
67 excludepats=args.excludepats,
68 printdependency=args.printdependency,
69 usecurrentconfig=args.usecurrentconfig)
70 except:
71 raise
72
73 def run_query(args):
74 logger.debug('args = %s' %str(args))
75
76 try:
77 iflist = args.iflist
78 if args.checkcurr:
79 qop='query-checkcurr'
80 elif args.running:
81 qop='query-running'
82 elif args.raw:
83 qop='query-raw'
84 elif args.syntaxhelp:
85 qop = 'query-syntax'
86 elif args.printdependency:
87 qop = 'query-dependency'
88 elif args.printsavedstate:
89 qop = 'query-savedstate'
90 else:
91 qop='query'
92 cachearg=(False if (iflist or args.nocache or
93 args.perfmode or args.syntaxhelp or
94 (qop != 'query-checkcurr' and
95 qop != 'query-running')) else True)
96 if not iflist and qop == 'query-running':
97 iflist = [i for i in os.listdir('/sys/class/net/')
98 if os.path.isdir('/sys/class/net/%s' %i)]
99 logger.debug('creating ifupdown object ..')
100 ifupdown_handle = ifupdownMain(withdepends=args.withdepends,
101 perfmode=args.perfmode,
102 njobs=args.jobs,
103 cache=cachearg)
104
105 ifupdown_handle.query([qop], args.all, args.CLASS, iflist,
106 excludepats=args.excludepats,
107 printdependency=args.printdependency,
108 format=args.format)
109 except:
110 raise
111
112 def run_reload(args):
113 logger.debug('args = %s' %str(args))
114
115 try:
116 logger.debug('creating ifupdown object ..')
117 cachearg=(False if (args.nocache or
118 args.perfmode or args.noact) else True)
119 ifupdown_handle = ifupdownMain(withdepends=args.withdepends,
120 perfmode=args.perfmode,
121 njobs=args.jobs,
122 cache=cachearg)
123 ifupdown_handle.reload(['pre-up', 'up', 'post-up'],
124 ['pre-down', 'down', 'post-down'],
125 args.all, None, None,
126 excludepats=args.excludepats,
127 downchangediface=args.downchangediface)
128 except:
129 raise
130
131 def init(args):
132 global logger
133
134 log_level = logging.WARNING
135 if args.verbose:
136 log_level = logging.INFO
137 if args.debug:
138 log_level = logging.DEBUG
139
140 try:
141 logging.basicConfig(level=log_level,
142 format='%(levelname)s: %(message)s')
143 logger = logging.getLogger('ifupdown')
144 except:
145 raise
146
147
148 def deinit():
149 {}
150
151 def update_argparser(argparser):
152 """ base parser, common to all commands """
153
154 argparser.add_argument('-a', '--all', action='store_true', required=False,
155 help='process all interfaces marked \"auto\"')
156 argparser.add_argument('iflist', metavar='IFACE',
157 nargs='*', help='interface list separated by spaces. ' +
158 'IFACE list is mutually exclusive with -a option.')
159 argparser.add_argument('-v', '--verbose', dest='verbose',
160 action='store_true', help='verbose')
161 argparser.add_argument('-d', '--debug', dest='debug',
162 action='store_true',
163 help='output debug info')
164 argparser.add_argument('-q', '--quiet', dest='quiet',
165 action='store_true',
166 help=argparse.SUPPRESS)
167 argparser.add_argument('--allow', dest='CLASS',
168 help='ignore non-\"allow-CLASS\" interfaces')
169 argparser.add_argument('--with-depends', dest='withdepends',
170 action='store_true', help='run with all dependent interfaces.'+
171 ' This option is redundant when \'-a\' is specified. With ' +
172 '\'-a\' interfaces are always executed in dependency order')
173 argparser.add_argument('--perfmode', dest='perfmode',
174 action='store_true', help=argparse.SUPPRESS)
175 argparser.add_argument('-j', '--jobs', dest='jobs', type=int,
176 default=-1, choices=range(1,12), help=argparse.SUPPRESS)
177 argparser.add_argument('--nocache', dest='nocache', action='store_true',
178 help=argparse.SUPPRESS)
179 argparser.add_argument('-X', '--exclude', dest='excludepats',
180 action='append',
181 help='Exclude interfaces from the list of interfaces' +
182 ' to operate on. Can be specified multiple times.')
183
184 def update_ifupdown_argparser(argparser):
185 """ common arg parser for ifup and ifdown """
186 argparser.add_argument('-f', '--force', dest='force',
187 action='store_true',
188 help='force run all operations')
189 group = argparser.add_mutually_exclusive_group(required=False)
190 group.add_argument('-n', '--no-act', dest='noact',
191 action='store_true', help='print out what would happen,' +
192 'but don\'t do it')
193 group.add_argument('--print-dependency',
194 dest='printdependency', choices=['list', 'dot'],
195 help='print iface dependency')
196 group.add_argument('--no-scripts', '--no-addons',
197 dest='noaddons', action='store_true',
198 help='dont run any addon modules or scripts. Runs only link ' +
199 'up/down')
200
201 def update_ifup_argparser(argparser):
202 update_ifupdown_argparser(argparser)
203
204 def update_ifdown_argparser(argparser):
205 update_ifupdown_argparser(argparser)
206 argparser.add_argument('--use-current-config',
207 dest='usecurrentconfig', action='store_true',
208 help=argparse.SUPPRESS)
209 #help='By default ifdown looks at the saved state for ' +
210 #'interfaces to bring down. This option allows ifdown to ' +
211 #'look at the current interfaces file. Useful when your ' +
212 #'state file is corrupted or you want down to use the latest '
213 #'from the interfaces file')
214
215 def update_ifquery_argparser(argparser):
216 """ arg parser for ifquery options """
217
218 # -l is same as '-a', only here for backward compatibility
219 argparser.add_argument('-l', '--list', action='store_true', dest='all',
220 help=argparse.SUPPRESS)
221 group = argparser.add_mutually_exclusive_group(required=False)
222 group.add_argument('-r', '--running', dest='running',
223 action='store_true',
224 help='query running state of an interface')
225 group.add_argument('-c', '--check', dest='checkcurr',
226 action='store_true',
227 help='check interface file contents against ' +
228 'running state of an interface')
229 group.add_argument('--raw', action='store_true', dest='raw',
230 help='print raw config file entries')
231 group.add_argument('--print-savedstate', action='store_true',
232 dest='printsavedstate',
233 help=argparse.SUPPRESS)
234 argparser.add_argument('--format', dest='format', default='native',
235 choices=['native', 'json'], help=argparse.SUPPRESS)
236 argparser.add_argument('--print-dependency',
237 dest='printdependency', choices=['list', 'dot'],
238 help='print interface dependency')
239 argparser.add_argument('--syntax-help', action='store_true',
240 dest='syntaxhelp',
241 help='print supported interface config syntax')
242
243 def update_ifreload_argparser(argparser):
244 """ parser for ifreload """
245 argparser.add_argument('-a', '--all', action='store_true', required=True,
246 help='process all interfaces marked \"auto\"')
247 argparser.add_argument('iflist', metavar='IFACE',
248 nargs='*', help=argparse.SUPPRESS)
249 argparser.add_argument('-n', '--no-act', dest='noact',
250 action='store_true', help=argparse.SUPPRESS)
251 argparser.add_argument('-v', '--verbose', dest='verbose',
252 action='store_true', help='verbose')
253 argparser.add_argument('-d', '--debug', dest='debug',
254 action='store_true',
255 help='output debug info')
256 argparser.add_argument('--with-depends', dest='withdepends',
257 action='store_true', help=argparse.SUPPRESS)
258 argparser.add_argument('--perfmode', dest='perfmode',
259 action='store_true', help=argparse.SUPPRESS)
260 argparser.add_argument('--nocache', dest='nocache', action='store_true',
261 help=argparse.SUPPRESS)
262 argparser.add_argument('-X', '--exclude', dest='excludepats',
263 action='append',
264 help=argparse.SUPPRESS)
265 argparser.add_argument('-j', '--jobs', dest='jobs', type=int,
266 default=-1, choices=range(1,12), help=argparse.SUPPRESS)
267 argparser.add_argument('--down-changediface', dest='downchangediface',
268 action='store_true', help='down interfaces whose ' +
269 'config have changed before bringing them up. By' +
270 ' default all interfaces are brought up')
271
272 def parse_args(argsv, op):
273 if op == 'query':
274 descr = 'query interfaces (all or interface list)'
275 else:
276 descr = 'interface management'
277 argparser = argparse.ArgumentParser(description=descr)
278 if op == 'reload':
279 update_ifreload_argparser(argparser)
280 else:
281 update_argparser(argparser)
282 if op == 'up':
283 update_ifup_argparser(argparser)
284 elif op == 'down':
285 update_ifdown_argparser(argparser)
286 elif op == 'query':
287 update_ifquery_argparser(argparser)
288 elif op == 'reload':
289 update_ifreload_argparser(argparser)
290
291 argcomplete.autocomplete(argparser)
292
293 return argparser.parse_args(argsv)
294
295 handlers = {'up' : run_up,
296 'down' : run_down,
297 'query' : run_query,
298 'reload' : run_reload }
299
300 def main(argv):
301 """ main function """
302 args = None
303 try:
304 op = None
305 if argv[0].endswith('ifup'):
306 op = 'up'
307 elif argv[0].endswith('ifdown'):
308 op = 'down'
309 elif argv[0].endswith('ifquery'):
310 op = 'query'
311 elif argv[0].endswith('ifreload'):
312 op = 'reload'
313 else:
314 print ('Unexpected executable.' +
315 ' Should be \'ifup\' or \'ifdown\' or \'ifquery\'')
316 exit(1)
317 # Command line arg parser
318 args = parse_args(argv[1:], op)
319 if not args.iflist and not args.all:
320 if op != 'query' or not args.syntaxhelp:
321 print '\'-a\' option or interface list are required'
322 exit(1)
323
324 if args.iflist and args.all:
325 print '\'-a\' option and interface list are mutually exclusive'
326 exit(1)
327 init(args)
328 handlers.get(op)(args)
329 except Exception, e:
330 if not str(e):
331 exit(1)
332 if args and args.debug:
333 raise
334 else:
335 if logger:
336 logger.error(str(e))
337 else:
338 print str(e)
339 if args and not args.debug:
340 print '\nRerun the command with \'-d\' for a detailed errormsg'
341 exit(1)
342 finally:
343 deinit()
344
345 if __name__ == "__main__":
346
347 if not os.geteuid() == 0:
348 print 'Error: Must be root to run this command'
349 exit(1)
350
351 """
352 XXX: Cannot use this. A spawned dhclient process can hold the lock
353 if not utilities.lockFile(lockfile):
354 print 'Another instance of this program is already running.'
355 exit(0)
356 """
357
358 main(sys.argv)