Debian Codegraph @

networking_bagpipe/bagpipe_bgp/common/run_command.py

raw
1 # Copyright 2014 Orange
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import subprocess
16 import threading
17
18 from oslo_config import cfg
19 from oslo_log import log as logging
20 from oslo_rootwrap import client
21 import shlex
22
23
24 common_opts = [
25 cfg.StrOpt("root_helper", default="sudo",
26 help="Root helper command."),
27 cfg.StrOpt("root_helper_daemon",
28 help="Root helper daemon application to use when possible."),
29 ]
30
31 cfg.CONF.register_opts(common_opts, "COMMON")
32
33
34 class RootwrapDaemonHelper:
35 __client = None
36 __lock = threading.Lock()
37
38 def __new__(cls):
39 """There is no reason to instantiate this class"""
40 raise NotImplementedError()
41
42 @classmethod
43 def get_client(cls):
44 with cls.__lock:
45 if cls.__client is None:
46 cls.__client = client.Client(
47 shlex.split(cfg.CONF.COMMON.root_helper_daemon))
48 return cls.__client
49
50
51 def _rootwrap_command(log, command, stdin=None,
52 shell=False):
53 '''Executes 'command' in rootwrap mode.
54
55 Returns (exit_code, command_output command_error)
56 - command_output is the list of lines output on stdout by the command
57 - command_error is the list of lines error on stderr by the command
58 '''
59 rootwrap_client = RootwrapDaemonHelper.get_client()
60
61 if shell:
62 exit_code, output, error = rootwrap_client.execute(["sh",
63 "-c", command],
64 stdin)
65 else:
66 exit_code, output, error = rootwrap_client.execute(command.split(),
67 stdin)
68
69 return (exit_code, output, error)
70
71
72 def _shell_command(log, command, stdin=None):
73 '''Executes 'command' in subshell mode.
74
75 Returns (exit_code, command_output, command_error)
76 - command_output is the list of lines output on stdout by the command
77 - command_error is the list of lines error on stderr by the command
78 '''
79 process = subprocess.Popen(command, shell=True,
80 stdin=subprocess.PIPE,
81 stdout=subprocess.PIPE,
82 stderr=subprocess.PIPE)
83
84 (output, error) = process.communicate(stdin)
85
86 exit_code = process.returncode
87 return (exit_code, output, error)
88
89
90 def _log_stdx_if(log_fn, output, error):
91 if output:
92 log_fn(" run_command stdout: %s", "\n ".join(output))
93 if error:
94 log_fn(" run_command stderr: %s", "\n".join(error))
95
96
97 def run_command(log, command,
98 run_as_root=False, raise_on_error=True,
99 acceptable_return_codes=[0], *args, **kwargs):
100 '''Executes 'command' in subshell or rootwrap mode.
101
102 Returns (command_output, exit_code)
103 - command_output is the list of lines output on stdout by the command
104 Raises an exception based on the following:
105 - will only raise an Exception if raise_on_error optional
106 parameter is True
107 - the exit code is acceptable
108 - exit code is acceptable by default if it is zero
109 - exit code is acceptable if it is in the (optional)
110 acceptable_return_codes list parameter
111 - putting -1 in the acceptable_return_codes list means that *any* exit
112 code is acceptable
113 '''
114 if run_as_root and cfg.CONF.COMMON.root_helper_daemon:
115 log.debug("Running command in rootwrap mode: %s", command)
116 exit_code, output, error = _rootwrap_command(log,
117 command, *args, **kwargs)
118 else:
119 log.debug("Running command in subshell mode: %s ", command)
120 if run_as_root:
121 command = " ".join([cfg.CONF.COMMON.root_helper, command])
122
123 # remove shell from kwargs (uses shell by default)
124 kwargs.pop("shell", False)
125 exit_code, output, error = _shell_command(log, command,
126 *args, **kwargs)
127
128 output = [line.decode() for line in output.splitlines()]
129 error = [line.decode() for line in error.splitlines()]
130
131 if log.isEnabledFor(logging.DEBUG):
132 _log_stdx_if(log.debug, output, error)
133
134 if (exit_code in acceptable_return_codes or -1 in acceptable_return_codes):
135 return (output, exit_code)
136 else:
137 message = "Exit code %d when running '%s'" % (exit_code, command)
138
139 if raise_on_error:
140 log.error(message)
141 _log_stdx_if(log.error, output, error)
142 raise Exception(message)
143 else:
144 log.warning(message)
145 return (output, exit_code)