-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcli.py
More file actions
302 lines (221 loc) · 8.31 KB
/
Copy pathcli.py
File metadata and controls
302 lines (221 loc) · 8.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# ----- Info ------------------------------------------------------------------
__author__ = 'Michael Montero <mcmontero@gmail.com>'
# ----- Imports ---------------------------------------------------------------
from .exception import CLIException
from tinyAPI.base.config import ConfigManager
from tinyAPI.base.context import Context
import argparse
import errno
import datetime
import logging
import os
import re
import sys
import time
import tinyAPI
__all__ = [
'CLI',
'cli_main',
'CLIOutputRenderer'
]
# ----- Definitions -----------------------------------------------------------
CLI_STOP_SIGNAL_FILE = '/tmp/APP_STOP_CLI'
log_file = ConfigManager().value('cli log file')
if log_file:
logging.basicConfig(filename = log_file)
else:
logging.basicConfig()
# Obtain the root logger
logger = logging.getLogger()
# ----- Public Functions -----------------------------------------------------
def cli_main(function, args=None, stop_on_signal=True):
'''Executes the "main" CLI function passing in the configured arguments.'''
if stop_on_signal and os.path.isfile(CLI_STOP_SIGNAL_FILE):
raise CLIException('CLI execution has been stopped')
Context().set_cli()
cli = CLI(args)
if not stop_on_signal:
cli.dont_stop_on_signal()
try:
function(cli)
except Exception as e:
logger.exception(e)
cli.set_status_error()
tinyAPI.dsh().rollback(True)
tinyAPI.dsh().close()
raise
# ----- Public Classes -------------------------------------------------------
class CLI(object):
'''Provides methods for executing and managing CLI programs.'''
STATUS_OK = 1
STATUS_WARN = 2;
STATUS_ERROR = 3;
def __init__(self, args=None):
self.args = None
if args is not None:
if not isinstance(args, argparse.ArgumentParser):
raise CLIException('args much be instance of ArgumentParser')
self.args = args.parse_args()
self.__enable_status = False
self.__pid_lock_file = None
self.__started = int(time.time())
self.__status_id = self.STATUS_OK
self.__stop_on_signal = True
self.__pid_lock()
# Now that PID locking has succeeded, enable the status.
self.__enable_status = True
def __del__(self):
try:
if self.__enable_status is True:
self.status()
except (AttributeError, TypeError):
pass
try:
if self.__pid_lock_file is not None:
try:
os.remove(self.__pid_lock_file)
except OSError as e:
if e.errno != errno.ENOENT:
raise
except (AttributeError, TypeError):
pass
def disable_status(self):
self.__enable_status = False
return self
def dont_stop_on_signal(self):
self.__stop_on_signal = False
return self
def error(self, message, indent=None):
'''Outputs an error message.'''
self.__status_id = self.STATUS_ERROR
self.__print_message(message, '!', indent)
self.process_signals()
def exit(self):
'''Exits setting the return value based on the status of the CLI.'''
exit(0 if self.__status_id == self.STATUS_OK else 1)
def __get_active_pid(self):
active_pid = None
try:
file = open(self.__pid_lock_file, 'r')
active_pid = int(file.read())
file.close()
except FileNotFoundError:
return None
return active_pid
def header(self, title):
'''Displays the header of the CLI containing the name.'''
print("\n" + CLIOutputRenderer().header(title))
sys.stdout.flush()
def notice(self, message, indent=None):
'''Outputs a notice message.'''
self.__print_message(message, '+', indent)
self.process_signals()
def __pid_lock(self):
params = []
params_str = '';
if self.args is not None:
for param in list(vars(self.args).values()):
if param is not None:
params.append(str(param).lower())
params.sort()
params_str = '_'.join(str(v) for v in params)
base_name = '/var/run/cli'
if os.path.isdir(base_name) is False:
raise CLIException(
'base directory "' + base_name + '" does not exist')
base_name += '/' + os.path.basename(sys.argv[0])
if len(params) > 0:
base_name += '-' + re.sub('[^A-Za-z0-9_\-]', '', params_str.lower())
self.__pid_lock_file = base_name + '.pid_lock'
active_pid = self.__get_active_pid()
if active_pid is not None:
try:
os.kill(int(active_pid), 0)
self.__pid_lock_failed()
except OSError:
os.unlink(self.__pid_lock_file)
try:
pid_file = os.fdopen(os.open(self.__pid_lock_file,
os.O_CREAT | os.O_EXCL | os.O_WRONLY,
0o644),
'w')
except OSError as e:
if e.errno == errno.EEXIST:
self.__pid_lock_failed()
pid_file.write(str(os.getpid()))
pid_file.close()
def __pid_lock_failed(self):
self.__enable_status = False;
print("\n* Process is already running!")
print("* Could not acquire PID lock on:\n " + self.__pid_lock_file)
with open(self.__pid_lock_file) as f:
print("* The lock is held by PID " + f.read() + '.\n')
self.__pid_lock_file = None
sys.stdout.flush()
sys.exit(0);
def __print_message(self, message, char, indent=None):
if not isinstance(message, str):
message = message.decode()
if indent is not None:
print((' ' * 4 * indent) + message)
else:
print(char + ' ' + message)
sys.stdout.flush()
def process_signals(self):
if self.__stop_on_signal and os.path.isfile(CLI_STOP_SIGNAL_FILE):
self.__status_id = self.STATUS_ERROR
self.__print_message('CLI execution has been stopped!', '!')
self.exit()
def set_status_error(self):
self.__status_id = self.STATUS_ERROR
def sleep(self, num_seconds):
self.process_signals()
self.notice('Sleeping (' + str(num_seconds) + ')...')
time.sleep(num_seconds)
return self
def status(self):
'''Prints a final message about the overall status of a CLI when it
exits.'''
elapsed = int(time.time()) - self.__started
indicator = '';
message = '';
if self.__status_id == self.STATUS_OK:
indicator = '+'
message = 'successfully'
elif self.__status_id == self.STATUS_WARN:
indicator = '*'
message = 'with warnings'
elif self.__status_id == self.STATUS_ERROR:
indicator = '!'
message = 'with errors'
print(("\n" + indicator + ' Execution completed ' + message
+ ' in ' + str('{0:,}'.format(elapsed)) + "s!\n"))
sys.stdout.flush()
def time_marker(self, num_iterations=None, max_iterations=None):
'''Outputs the time for each iteration of a CLI that runs in a loop
continuously.'''
self.process_signals()
if num_iterations and \
max_iterations and \
num_iterations > max_iterations:
self.notice('Exiting to recover resources...')
self.exit()
self.notice(
('----- Marker '
+ (str(num_iterations) if num_iterations is not None else '')
+ ' ['
+ str(datetime.datetime.now())
+ ']'))
return num_iterations + 1
def warn(self, message, indent=None):
'''Outputs a warning message.'''
self.__print_message(message, '*', indent)
self.process_signals()
class CLIOutputRenderer(object):
'''Provides methods for consistent output from CLI programs.'''
@staticmethod
def header(title, width=79):
enclosure = '# +' + ('-' * (width - 5)) + "+\n"
body = '# | ' + title
body += ' ' * (width - 2 - len(body)) + "|\n"
return enclosure + body + enclosure