-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbf.py
executable file
·602 lines (413 loc) · 15.6 KB
/
bf.py
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
#!/usr/bin/env python3
"""Blenderfarm command-line tool."""
import sys
import blenderfarm
class Action:
"""A command-line action that can be executed."""
def __init__(self):
self.name = ''
self.description = ''
# Options format: `?name=default`
#
# The question mark denotes an optional argument, the name is
# a plain string, and the optional default is an equals sign,
# followed by the default string value.
self.options = []
# Used internally to display nicely formatted command-line text.
self.prefix = ''
def __lt__(self, other):
"""Make sorting work."""
return self.name < other.name
def parse_arguments(self, args, raise_errors=False):
"""Inserts actual arguments into `options` array that contains the
named options (see `self.options`, above)."""
options = {}
# For each option in our list of valid options;
for option_index in range(len(self.options)):
# convert it into a dictionary containing `name`,
# `optional`, and `default.
option_format = Action.get_option_format(self.options[option_index])
# Just to make it a bit easier.
option_name = option_format['name']
option_value = option_format['default']
# If the argument exists in `args`, then save the value.
if len(args) >= option_index + 1:
option_value = args[option_index]
# Otherwise, if the option is not optional and also not
# present, and _also_ we've asked to raise errors (for
# example, the help dialogs don't want to raise errors),
# then complain and exit.
elif not option_format['optional'] and raise_errors:
print('! option "' + option_name + '" (for action "' + self.name + '") is not optional')
exit(1)
# Set the value of the option dictionary.
options[option_name] = option_value
# Take all extra arguments and stuff them into `__`.
if len(args) > len(self.options):
options['__'] = args[len(self.options):]
else:
options['__'] = []
return options
@staticmethod
def get_option_help(option):
"""Converts an option format into its human-readable format."""
option_format = Action.get_option_format(option)
name = option_format['name']
# Optional arguments are surrounded with `[square brackets]`.
if option_format['optional']:
return '[' + name + ']'
# Required arguments are surrounded with `<angle brackets>`.
return '<' + name + '>'
@staticmethod
def get_option_format(option):
"""Converts an option format into a Python dictionary."""
option_format = {
'name': None,
'optional': False,
'default': None
}
# If the option is optional, set the `optional` flag.
if option.startswith('?'):
option = option[1:]
option_format['optional'] = True
# If there's a default value
if '=' in option:
option_format['default'] = option.split('=')[1]
option = option.split('=')[0]
option_format['name'] = option
return option_format
def get_string_options_list(self):
"""Get a human-readable list of all the options. Used in help and usage."""
options = []
for option in self.options:
options.append(Action.get_option_help(option))
return ' '.join(options)
def get_help_line(self):
"""Returns a human-readable help line, containing the prefix, the name, options, and the description."""
return self.prefix + ' ' + self.name.ljust(12) + ' ' + self.get_string_options_list().ljust(24) + ' ' + self.description
def get_help_usage(self):
"""Same as above, but formatted slightly differently for usage listings."""
return (self.prefix + ' ' + self.name + ' ' + self.get_string_options_list()).ljust(48) + self.description
def help(self, options):
"""Prints out the help for this action."""
_ = options
print(self.get_help_usage())
def invoke(self, options): # pylint: disable=no-self-use
"""Invokes this action."""
_ = options
print('override me')
class ActionList(Action):
"""An action that contains sub-actions."""
def __init__(self):
super().__init__()
self.options = ['action']
self.actions = []
def get_action(self, name):
"""Attempts to find the requisite sub-action named `name`."""
if not name:
return None
name = name.lower().strip()
for action in self.actions:
if action.name == name:
return action
return None
def help(self, options):
"""Prints out help text, including help text for sub-actions."""
action_name = options['action']
if action_name:
action = self.get_action(action_name)
if action:
action.prefix = self.prefix + ' ' + self.name
action.help(action.parse_arguments(options['__']))
return
print(self.get_help_usage())
print()
for action in self.actions:
action.prefix = self.prefix + ' ' + self.name
print(action.get_help_usage())
def invoke(self, options):
"""Invokes the action."""
# Get action name and arguments (will be an empty array if none are present.)
action_name = options['action']
arguments = options['__']
if not action_name:
self.help(options)
print()
print('! expected a sub-action')
return
action = self.get_action(action_name)
if not action:
self.help(options)
print()
print('! no such sub-action "' + action_name + '"')
return
action.prefix = self.prefix + ' ' + self.name
action.invoke(action.parse_arguments(arguments, True))
class HelpAction(Action):
"""Prints out the help page."""
def __init__(self):
super().__init__()
self.name = 'help'
self.description = 'prints out help'
self.options = ['?module']
def invoke(self, options):
print()
# `help <foo>`
if options['module'] != None:
action_name = options['module']
action = get_action(action_name)
if not action:
print_help()
print()
print('! no such action "' + action_name + '"')
return
action.prefix = self.prefix
action.help(action.parse_arguments(options['__']))
else:
print_help()
print()
class VersionAction(Action):
"""Prints out the blenderfarm version."""
def __init__(self):
super().__init__()
self.name = 'version'
self.description = 'prints out the blenderfarm version'
def help(self, options):
print(self.get_help_usage())
print()
print('only the version is printed, to make machine-parsing possible.')
def invoke(self, options):
print(blenderfarm.__version__)
class ServerAction(Action):
"""Starts the blenderfarm server."""
def __init__(self):
super().__init__()
self.name = 'server'
self.description = 'starts the blenderfarm server'
self.options = ['?host=0.0.0.0', '?port=44363']
def help(self, options):
"""Prints out help text for the `server` action."""
print(self.description)
print()
print('accepts two arguments: [host] and [port].')
print('If omitted, the defaults of "0.0.0.0" and "44363" are used.')
def invoke(self, options):
"""Invokes the `server` action."""
# Get `host` and `port` from the options.
host = options['host']
port = options['port']
# Try converting the port to an int.
try:
port = int(port)
except ValueError:
print('! invalid port number "' + port + '"')
return
# Create the blenderfarm `Server`.
server = blenderfarm.server.Server(host=host, port=port)
# Print out a nice message, containing the host and port.
print('starting blenderfarm server at ' + host + ' (' + str(port) + ')...')
# And start the server.
server.start()
class AdminUserAddAction(Action):
"""Adds a blenderfarm user."""
def __init__(self):
super().__init__()
self.name = 'add'
self.description = 'adds a new user'
self.options = ['username']
def help(self, options):
print(self.description)
print()
print('the username must not exist yet')
def invoke(self, options):
"""Invokes the `user add` action."""
username = options['username']
users_db = blenderfarm.db.Users()
user = users_db.get_user(username)
if user:
print('that username already exists:')
else:
user = users_db.add(username)
print('user creation successful:')
print(user.get_username_key())
class AdminUserRemoveAction(Action):
"""Removes a blenderfarm user."""
def __init__(self):
super().__init__()
self.name = 'remove'
self.description = 'removes a user'
self.options = ['username']
def invoke(self, options):
"""Invokes the `user remove` action."""
username = options['username']
users_db = blenderfarm.db.Users()
if not users_db.get_user(username):
print('! that username does not exist')
return
users_db.remove(username)
print('user deletion successful; "' + username + '" no longer exists')
class AdminUserRekeyAction(Action):
"""Changes a blenderfarm user's key."""
def __init__(self):
super().__init__()
self.name = 'rekey'
self.description = 'deletes the old user key and creates a new one'
self.options = ['username']
def invoke(self, options):
"""Invokes the `user rekey` action."""
username = options['username']
users_db = blenderfarm.db.Users()
user = users_db.get_user(username)
if not user:
print('! that username does not exist')
return
users_db.rekey(username)
print('user rekey successful')
print(user.get_username_key())
class AdminUserListAction(Action):
"""List all blenderfarm users."""
def __init__(self):
super().__init__()
self.name = 'list'
self.description = 'lists users and keys'
self.options = ['?username']
def help(self, options):
print(self.get_help_usage())
print()
print('lists existing users on this blenderfarm server')
print('if the optional parameter [username] is present, only lists that user')
def invoke(self, options):
"""Invokes the `user list` action."""
users_db = blenderfarm.db.Users()
username = options['username']
if username:
user = users_db.get_user(username)
if user:
print('...')
print(user.get_username_key())
print('...')
return
print('! that username does not exist')
return
for user in users_db.get_users():
print(user.get_username_key())
class AdminUserAction(ActionList):
"""`ActionList` for user actions."""
def __init__(self):
super().__init__()
self.name = 'user'
self.description = 'blenderfarm server user administration commands'
self.actions = [
AdminUserAddAction(),
AdminUserRemoveAction(),
AdminUserRekeyAction(),
AdminUserListAction()
]
class AdminAction(ActionList):
"""`ActionList` for admin actions."""
def __init__(self):
super().__init__()
self.name = 'admin'
self.description = 'blenderfarm server administration commands'
self.actions = [
AdminUserAction()
]
class JobAddAction(Action):
"""Add a new job."""
def __init__(self):
super().__init__()
self.name = 'add'
self.description = 'Adds a new job.'
self.options = ['url', '?start=0', '?end=1']
def help(self, options):
print(self.get_help_usage())
print()
print('lists existing users on this blenderfarm server')
print('if the optional parameter [username] is present, only lists that user')
def invoke(self, options):
"""Invokes the `job add` action."""
start, end = int(options['start']), int(options['end'])
jobs_db = blenderfarm.job.JobList()
job_info = blenderfarm.job.JobInfoRender(None)
job_info.file_url = options['url']
job_info.frame_range = [start, end]
job = blenderfarm.job.Job(job_info)
job.populate_tasks()
jobs_db.add(job)
print(job.get_job_line())
jobs_db.save()
class JobListAction(Action):
"""Add a new job."""
def __init__(self):
super().__init__()
self.name = 'list'
self.description = 'list all jobs.'
self.options = ['?job_id']
def help(self, options):
print(self.get_help_usage())
def invoke(self, options):
"""Invokes the `job list` action."""
jobs_db = blenderfarm.job.JobList()
for job in jobs_db.get_jobs():
print(job.get_job_line())
else:
print('no jobs')
class JobAction(ActionList):
"""`ActionList` for job actions."""
def __init__(self):
super().__init__()
self.name = 'job'
self.description = 'job creation, editing, and removal commands'
self.actions = [
JobAddAction(),
JobListAction()
]
# First, we define a list of actions.
ACTIONS = [
HelpAction(),
VersionAction(),
ServerAction(),
AdminUserAction(),
AdminAction(),
JobAction()
]
ACTIONS.sort()
def print_version():
"""Prints out the blenderfarm version in a human-readable format."""
print('blenderfarm version ' + blenderfarm.__version__)
def print_help():
"""Prints out a list of actions, their options, and their descriptions in a human-readable format."""
print('actions:')
print()
for action in ACTIONS:
action.prefix = sys.argv[0]
print(action.get_help_line())
def print_usage():
"""Prints out usage and help in a human-readable format."""
print('usage: ' + sys.argv[0] + ' <action> [options...]')
print()
print_help()
def get_action(name):
"""Attempts to find the requisite action named `name`."""
name = name.lower().strip()
for action in ACTIONS:
if action.name == name:
return action
return None
def run():
"""The fun part."""
if len(sys.argv) < 2:
print_usage()
exit(1)
action_name = sys.argv[1]
action = get_action(action_name)
if not action:
print_usage()
print()
print('! no such action "' + action_name + '"')
exit(1)
action.prefix = sys.argv[0]
action.invoke(action.parse_arguments(sys.argv[2:]))
# Ideally, this would never be imported as a library, but just in case...
if __name__ == '__main__':
run()