-
Notifications
You must be signed in to change notification settings - Fork 10
/
rcCollectorCli.py
2516 lines (2267 loc) · 96.1 KB
/
rcCollectorCli.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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
import stat
import json
import optparse
import shlex
import re
import copy
import textwrap
# issue19884 workaround (spurious heading '\033[1034h')
TERM = os.environ.get("TERM")
if TERM:
del os.environ["TERM"]
import readline
os.environ["TERM"] = TERM
import atexit
import fnmatch
from six.moves import configparser as ConfigParser
import rcExceptions as ex
from six.moves import input
from storage import Storage
from rcUtilities import bdecode, is_glob, find_editor
from rcColor import formatter
try:
import requests
except ImportError:
raise ex.excError("This feature requires the python requests module")
try:
from requests.packages.urllib3.exceptions import InsecureRequestWarning
except ImportError:
InsecureRequestWarning = None
# the collector api doc uses restructured text we'll have to print
# in the command help messages
try:
import docutils.utils
import docutils.parsers
import docutils.parsers.rst
has_docutils = True
except ImportError:
has_docutils = False
progname = "opensvc-cli"
homedir = os.path.expanduser("~")
api_cache_f = os.path.join(homedir, "."+progname+".api")
conf_f = os.path.join(homedir, "."+progname)
conf_section = "collector"
history_f = conf_f + "_history"
global path
path = "/"
api_cache = None
ls_info_default = {
"filter": "id",
"props": ["id"],
"fmt": "%(id)-10s",
}
ls_info = {
"": {
"filter": "path",
"props": ["path"],
"fmt": " %(path)s",
},
"action_queue": {
"filter": "id",
"props": ["id", "command"],
"fmt": "%(id)-10s %(command)s",
},
"apps": {
"filter": "app",
"props": ["id", "app"],
"fmt": "%(id)-10s %(app)s",
},
"nodes": {
"filter": "nodename",
"props": ["node_id", "nodename"],
"fmt": "%(node_id)s %(nodename)s",
},
"services": {
"filter": "svcname",
"props": ["svc_id", "svcname"],
"fmt": "%(svc_id)s %(svcname)s",
},
"rulesets": {
"filter": "ruleset_name",
"props": ["id", "ruleset_name"],
"fmt": "%(id)-10s %(ruleset_name)s",
},
"modulesets": {
"filter": "modset_name",
"props": ["id", "modset_name"],
"fmt": "%(id)-10s %(modset_name)s",
},
"users": {
"filter": "email",
"props": ["id", "email"],
"fmt": "%(id)-10s %(email)s",
},
"groups": {
"filter": "role",
"props": ["id", "role"],
"fmt": "%(id)-10s %(role)s",
},
"tags": {
"filter": "tag_name",
"props": ["tag_id", "tag_name"],
"fmt": "%(tag_id)s %(tag_name)s",
},
"variables": {
"filter": "var_name",
"props": ["id", "var_name"],
"fmt": "%(id)-10s %(var_name)s",
},
"modules": {
"filter": "modset_mod_name",
"props": ["id", "modset_mod_name"],
"fmt": "%(id)-10s %(modset_mod_name)s",
},
"filters": {
"filter": "f_label",
"props": ["id", "f_label"],
"fmt": "%(id)-10s %(f_label)s",
},
"filtersets": {
"filter": "fset_name",
"props": ["id", "fset_name"],
"fmt": "%(id)-10s %(fset_name)s",
},
}
#
# requests setup
#
try:
requests.packages.urllib3.disable_warnings()
except AttributeError:
pass
class Cmd(object):
command = "undef"
desc = ""
parser = None
candidates_path = {}
api_candidates = False
parser_options = []
# color codes
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
def __init__(self, cli=None):
self.cli = cli
self.options = Storage()
self.options.format = cli.format if cli else None
@formatter
def print_content(self, s):
data = json.loads(bdecode(s))
if self.options.format == "json":
return data
if "info" in data:
if isinstance(data["info"], list):
infos = data["info"]
else:
infos = [data["info"]]
for info in infos:
print("Info:", info)
if "error" in data:
if isinstance(data["error"], list):
errors = data["error"]
else:
errors = [data["error"]]
for error in errors:
print("Error:", error)
if "data" in data:
return data["data"]
return ""
def path_match_handlers(self, p):
for a, l in self.cli.api_o.get().items():
for d in l:
if path_match_handler(p, d):
return True
return False
def path_match_handlers_or_parents(self, p):
for a, l in self.cli.api_o.get().items():
for d in l:
if path_match_handler_or_parents(p, d):
return True
return False
def colorize(self, s, c=None):
if c is None:
return s
return c + s + self.END
def get_handler(self, action, p):
for d in self.cli.api_o.get()[action]:
if path_match_handler(p, d):
return d
def match(self, line):
"""
Tells if a CLI command line is to be handled by this command class,
using the first word as a telltale.
"""
l = line.split()
if len(l) == 0 or l[0] != self.command:
return False
return True
def replace_params_in_path(self, candidates_path, words):
d = {}
if candidates_path.count("<") == 0:
return candidates_path
for i, w in enumerate(words):
if i < len(words) - 1:
next_word = words[i+1]
else:
next_word = None
if w.startswith("--") and next_word is not None:
d[w.lstrip("-")] = next_word
p = copy.copy(candidates_path)
new_p = copy.copy(candidates_path)
while p.count("<") > 0:
try:
param = p[p.index("<")+1:p.index(">")]
p = p[p.index(">")+1:]
if param in d:
new_p = new_p.replace("<"+param+">", d[param])
except:
break
return new_p
def set_parser_options_from_cmdline(self, line):
words = shlex.split(line)
self.set_parser_options_from_words(words)
def set_parser_options_from_words(self, words):
if len(words) == 0:
return
_path = None
for i, w in enumerate(words):
if i == 0:
# command word
continue
if i == 1 and not w.startswith("-"):
_path = w
break
if i > 1 and not words[i-1].startswith("-"):
_path = w
break
if _path is None:
return
try:
self.set_parser_options(_path)
except Exception as e:
print(e)
def candidates(self, pattern, words):
candidates = []
if hasattr(self, "candidates_path"):
param = words[-1]
if not param in self.candidates_path and len(words) > 2 and pattern != "":
param = words[-2]
candidates_path = self.candidates_path.get(param)
else:
candidates_path = None
if candidates_path:
candidates_path = self.replace_params_in_path(candidates_path, words)
pattern = candidates_path + "/" + pattern
else:
self.set_parser_options_from_words(words)
for o in self.parser.option_list:
candidates += o._long_opts
if pattern is None:
pattern = ""
elif pattern == ".." or pattern.endswith("/.."):
pass
elif pattern.startswith("/") and pattern.endswith("/"):
pass
elif pattern.count("/") == 0:
pattern += "*"
else:
pattern = pattern[:pattern.rindex("/")+1]
ls_data = self.ls_data(pattern)
for e in ls_data:
if e.startswith("OBJ"):
candidate = e.replace("OBJ", "").strip()
l = candidate.split()
if len(l) > 1 and len(candidate) > 11:
# <id 10-char padded> <string>
candidate = candidate[11:]
if candidates_path is None and pattern.count("/") > 0:
candidate = pattern.rstrip("/")+"/"+candidate
candidates.append(candidate)
elif candidates_path is None and e.startswith("API") and e != "API":
candidate = e.split()[-1]
if pattern.startswith("/") and not candidate.startswith("/"):
candidate = pattern + candidate
candidates.append(candidate)
return candidates
def args_to_path(self, args):
try:
arg1 = args[1]
if arg1.startswith("/"):
_path = arg1
else:
_path = copy.copy(path) + "/" + args[1]
except:
_path = copy.copy(path)
return _path
def get_data_from_options(self, options):
data = {}
files = {}
headers = None
if options is None or "data" not in options.__dict__ or options.data is None:
return data, files, headers
for d in options.data:
if len(d) > 0 and d[0] == "@" and os.path.exists(d[1:]):
with open(d[1:], 'r') as fd:
data = fd.read()
try:
data = data.encode("utf-8")
except:
pass
headers = {
'Accept' : 'application/json',
'Content-Type' : 'application/json; charset=utf-8'
}
return data, files, headers
if d.count("=") == 0 or len(d) < d.index("=")+1:
print("ignore malformated data:", d)
continue
key = d[:d.index("=")]
val = d[d.index("=")+1:]
if len(val) > 1 and val[0] == "@" and os.path.exists(val[1:]):
fpath = val[1:]
try:
fd = open(fpath, 'rb')
except:
print("error opening file %s" % fpath, file=sys.stderr)
raise
files["file"] = (os.path.realpath(fpath), fd)
else:
data[key] = val
return data, files, headers
def factorize_dot_dot(self, p):
l1 = p.split("/")
l2 = []
for i, e in enumerate(l1):
if i == 0:
l2.append(e)
continue
if e == "..":
l2.pop()
continue
l2.append(e)
if l2 == [""]:
p = "/"
else:
p = "/".join(l2)
if len(p) > 1:
p.rstrip("/")
return p
def ls_data(self, line):
ls_data = []
global path
line = line.strip()
# strip the ls command
relpath = re.sub("^\s*ls\s+", "", line)
if relpath == "ls":
relpath = ""
relpath = relpath.strip()
if relpath == ".." or relpath.endswith("/.."):
relpath += "/"
p = get_fullpath(relpath)
if p.count("/") == 0:
relpath = ""
raw_req_path = copy.copy(path)
shell_pattern = p
elif is_glob(p[p.rindex("/"):]):
v = p.split("/")
raw_req_path = "/".join(v[:-1])
shell_pattern = v[-1]
v = relpath.split("/")
relpath = "/".join(v[:-1])
else:
raw_req_path = p
shell_pattern = ""
req_path = self.factorize_dot_dot(raw_req_path)
sql_pattern = shell_pattern.replace("*", "%")
sql_pattern = sql_pattern.replace("?", "_")
last = req_path.rstrip("/").split("/")[-1]
info = ls_info.get(last, ls_info_default)
props = info.get("props", [])
filter_prop = info.get("filter", "id")
fmt = info.get("fmt", "%(id)s")
if req_path not in ("/", "") and self.path_match_handlers(req_path):
# object listing
params = {
"limit": 0,
"meta": 0,
"props": ",".join(props),
}
if len(sql_pattern) > 0:
params["query"] = filter_prop + " like " + sql_pattern
r = requests.get(self.cli.api+req_path, params=params, auth=self.cli.auth, verify=not self.cli.insecure)
validate_response(r)
data = json.loads(bdecode(r.content)).get("data")
if type(data) == list:
ls_data += map(lambda d: "OBJ " + fmt % d, data)
if self.api_candidates:
# api paths listing
info = ls_info.get("", ls_info_default)
fmt = info.get("fmt", "%(id)s")
props = info.get("props", [])
filter_prop = info.get("filter", [])
data = [d for d in self.get_handler_paths() if path_match_handler_or_parents(req_path, d) and d["path"] != req_path]
#data += path_children_api(req_path)
if len(shell_pattern) > 0:
if not shell_pattern.startswith("/"):
shell_pattern = req_path + "/" + shell_pattern
shell_pattern = shell_pattern.replace("//", "/")
data = [d for d in data if fnmatch.fnmatch(d.get(filter_prop), shell_pattern)]
for i, d in enumerate(data):
data[i]["path"] = re.sub("^"+req_path, relpath, d["path"])
for d in data:
line = "API "
for action in ("GET", "POST", "DELETE", "PUT"):
if action in d["actions"]:
line += action
else:
line += "."*len(action)
line += " "
line += fmt %d
ls_data.append(line)
return ls_data
def get_handler_paths(self):
data = self.cli.api_o.get()
all_handlers = {}
for action, l in data.items():
for h in l:
if h["path"] not in all_handlers:
h["actions"] = [action]
all_handlers[h["path"]] = h
else:
all_handlers[h["path"]]["actions"].append(action)
return [all_handlers[p] for p in sorted(all_handlers.keys())]
def set_parser_options(self, _path):
if not _path.startswith("/"):
_path = os.path.join(path, _path)
try:
h = self.get_handler(self.command.upper(), _path)
except Exception as e:
return
if h is None:
return self.parser
for o in self.parser._get_all_options()[1:]:
self.parser.remove_option(str(o))
if hasattr(self, "parser_options"):
for o in self.parser_options:
self.parser.add_option(o)
for param, d in h["params"].items():
if d.get("type") == "list":
action = "append"
default = []
else:
action = "append"
default = None
self.parser.add_option("--"+param, default=default, action=action, dest=param, help=d["desc"])
class IndentedHelpFormatterRst(optparse.IndentedHelpFormatter):
def format_description(self, description):
if not has_docutils:
return description
if not description:
return ""
doc = docutils.utils.new_document("foo")
doc.settings.tab_width = 4
doc.settings.pep_references = None
doc.settings.rfc_references = None
p = docutils.parsers.rst.Parser()
p.parse(description, doc)
description = doc.astext()
desc_width = self.width - self.current_indent
indent = " "*self.current_indent
# the above is still the same
bits = description.split('\n')
formatted_bits = [
textwrap.fill(bit, desc_width, initial_indent=indent, subsequent_indent=indent)
for bit in bits
]
result = "\n".join(formatted_bits) + "\n"
return result
def format_option(self, option):
result = []
opts = self.option_strings[option]
opt_width = self.help_position - self.current_indent - 2
if len(opts) > opt_width:
opts = "%*s%s\n" % (self.current_indent, "", opts)
indent_first = self.help_position
else: # start help on same line as opts
opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
indent_first = 0
result.append(opts)
if option.help:
help_text = self.expand_default(option)
# Everything is the same up through here
help_lines = []
for para in help_text.split("\n"):
help_lines.extend(textwrap.wrap(para, self.help_width))
# Everything is the same after here
result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
result.extend(["%*s%s\n" % (self.help_position, "", line) for line in help_lines[1:]])
elif opts[-1] != "\n":
result.append("\n")
return "".join(result)
class CliError(Exception):
pass
class Api(object):
api_cache = None
def __init__(self, cli=None, refresh=False):
self.cli = cli
self.load(refresh=refresh)
def load(self, refresh=False):
if not refresh and os.path.exists(api_cache_f):
# try local cache first
try:
with open(api_cache_f, 'r') as f:
self.api_cache = json.loads(f.read())
return
except Exception as e:
print(e)
os.unlink(api_cache_f)
# fallback to fetching the cache
print("load api cache", file=sys.stderr)
r = requests.get(self.cli.api, auth=self.cli.auth, verify=not self.cli.insecure)
validate_response(r)
try:
self.api_cache = json.loads(bdecode(r.content))["data"]
except:
raise CliError(r.content)
# update local cache
with open(api_cache_f, 'w') as f:
f.write(json.dumps(self.api_cache, indent=4))
def get(self):
if self.api_cache:
return copy.deepcopy(self.api_cache)
self.load()
return copy.deepcopy(self.api_cache)
class OptionParsingError(RuntimeError):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class OptionParsingExit(Exception):
def __init__(self, status, msg):
self.msg = msg
self.status = status
def __str__(self):
return self.msg
class CmdOptionParser(optparse.OptionParser):
def __init__(self, *args, **vars):
vars["formatter"] = IndentedHelpFormatterRst()
optparse.OptionParser.__init__(self, *args, **vars)
def error(self, msg):
raise OptionParsingError(msg)
def exit(self, status=0, msg=None):
raise OptionParsingExit(status, msg)
def get_fullpath(relpath):
if relpath.startswith("/"):
return relpath
if relpath == "":
return path
return path+"/"+relpath
class CmdHelp(Cmd):
command = "help"
desc = "Print this help message."
parser = CmdOptionParser(description=desc)
def cmd(self, line):
from textwrap import TextWrapper
wrapper = TextWrapper(initial_indent=" ", subsequent_indent=" ", width=78)
commands_h = {}
for c in self.cli.commands:
commands_h[c.command] = c
base_commands = sorted(commands_h.keys())
for command in base_commands:
c = commands_h[command]
print(c.command)
print()
if hasattr(c, "desc"):
print(wrapper.fill(c.desc))
print()
class CmdLs(Cmd):
api_candidates = True
command = "ls"
desc = "List the API handlers and available objects matching the given pattern."
parser = CmdOptionParser(description=desc)
def cmd(self, line):
ls_data = self.ls_data(line)
for s in ls_data:
print(s)
class CmdDelete(Cmd):
api_candidates = True
command = "delete"
desc = "Execute a DELETE request on the given API handler."
parser = CmdOptionParser(description=desc)
parser_options = [
optparse.make_option("--data", default=None, action="append", dest="data",
help="A key=value pair to filter the deleted data. Multiple --data can be specified.")
]
def cmd(self, line):
self.set_parser_options_from_cmdline(line)
global path
try:
options, args = self.parser.parse_args(args=shlex.split(line))
except Exception as e:
try: print(e)
except: pass
return
data, files, headers = self.get_data_from_options(options)
params = {}
if 'filters' in options.__dict__ and options.filters:
params["filters"] = options.filters
if 'query' in options.__dict__ and options.query is not None:
params["query"] = options.query
if 'limit' in options.__dict__ and options.limit:
params["limit"] = int(options.limit[0])
_path = self.args_to_path(args)
r = requests.delete(self.cli.api+_path, params=params, data=data, headers=headers, auth=self.cli.auth, verify=not self.cli.insecure)
validate_response(r)
self.print_content(r.content)
class CmdPost(Cmd):
api_candidates = True
command = "post"
desc = "Execute a POST request on the given API handler. The data can be set using --data."
parser = CmdOptionParser(description=desc)
parser_options = [
optparse.make_option("--data", default=None, action="append", dest="data",
help="A key=value pair to include in the post data. Multiple --data can be specified.")
]
def cmd(self, line):
self.set_parser_options_from_cmdline(line)
global path
try:
options, args = self.parser.parse_args(args=shlex.split(line))
except Exception as e:
try: print(e)
except: pass
return
data, files, headers = self.get_data_from_options(options)
params = {}
if 'filters' in options.__dict__ and options.filters:
params["filters"] = options.filters
if 'query' in options.__dict__ and options.query is not None:
params["query"] = options.query
if 'limit' in options.__dict__ and options.limit:
params["limit"] = int(options.limit[0])
_path = self.args_to_path(args)
r = requests.post(self.cli.api+_path, data=data, files=files, params=params, headers=headers, auth=self.cli.auth, verify=not self.cli.insecure)
validate_response(r)
self.print_content(r.content)
class CmdPut(Cmd):
api_candidates = True
command = "put"
desc = "Execute a PUT request on the given API handler. The data can be set using --data."
parser = CmdOptionParser(description=desc)
parser_options = [
optparse.make_option("--data", default=None, action="append", dest="data",
help="A key=value pair to include in the post data. Multiple --data can be specified.")
]
def cmd(self, line):
self.set_parser_options_from_cmdline(line)
global path
try:
options, args = self.parser.parse_args(args=shlex.split(line))
except Exception as e:
try: print(e)
except: pass
return
data, files, headers = self.get_data_from_options(options)
_path = self.args_to_path(args)
r = requests.put(self.cli.api+_path, data=data, files=files, headers=headers, auth=self.cli.auth, verify=not self.cli.insecure)
validate_response(r)
self.print_content(r.content)
class CmdSafe(Cmd):
command = "safe"
desc = "Upload, download and manage files in the collector safe. The safe is a file sharing facility with access control rules for nodes and users making it suitable to serve compliance reference files."
parser = CmdOptionParser(description=desc)
parser.add_option("--ls", default=None, action="store_true", dest="ls",
help="List the accessible files in the safe.")
parser.add_option("--upload", default=None, action="store_true", dest="upload",
help="Upload the file pointed by --file to the safe. Optionally give a name using --name.")
parser.add_option("--download", default=None, action="store_true", dest="download",
help="Download from the safe the file pointed by --file to the file path or directory pointed by --to.")
parser.add_option("--file", default=None, action="store", dest="file",
help="The safe file uuid to download, or the local file to upload.")
parser.add_option("--to", default=None, action="store", dest="to",
help="The local file path or directory name to download.")
parser.add_option("--name", default=None, action="store", dest="name",
help="The user-friendly name to attach to the upload.")
parser.add_option("--id", default=None, action="store", dest="id", type="int",
help="An optional safe file integer id. If specified the safe id will point to the new uploaded version of the file. The previous version is still referenced by the same uuid.")
candidates_path = {
"--file": "/safe",
}
api_candidates = False
def cmd(self, line):
global path
try:
options, args = self.parser.parse_args(args=shlex.split(line))
except Exception as e:
try: print(e)
except: pass
return
self.ls(options)
self.upload(options)
self.download(options)
def ls(self, options):
if options.ls is None:
return
params = {}
r = requests.get(self.cli.api+"/safe", params=params, auth=self.cli.auth, verify=not self.cli.insecure)
validate_response(r)
self.print_content(r.content)
def upload(self, options):
if options.upload is None:
return
if options.file is None:
raise CliError("--file is mandatory for --upload")
data = {}
if options.name:
data["name"] = options.name
if not os.path.exists(options.file):
raise CliError("%s file not found" % options.file)
if options.id is not None:
path = "/safe/%d/upload" % options.id
else:
path = "/safe/upload"
files = {
"file": (os.path.realpath(options.file), open(options.file, 'rb')),
}
r = requests.post(self.cli.api+path, data=data, files=files, auth=self.cli.auth, verify=not self.cli.insecure)
validate_response(r)
self.print_content(r.content)
def download(self, options):
if options.download is None:
return
if options.file is None:
raise CliError("--file is mandatory for --download")
if options.to is None:
raise CliError("--to is mandatory for --download")
if os.path.exists(options.to) and os.path.isdir(options.to):
to = os.path.join(options.to, options.file)
else:
to = options.to
r = requests.get(self.cli.api+"/safe/"+options.file+"/download", stream=True, auth=self.cli.auth, verify=not self.cli.insecure)
validate_response(r)
if not r.ok:
try:
d = json.loads(bdecode(r.content))
print(d["error"], file=sys.stderr)
return
except:
pass
raise CliError("download failed")
with open(options.to, 'wb') as f:
pass
os.chmod(options.to, 0o0600)
with open(options.to, 'wb') as f:
for block in r.iter_content(1024):
print(".")
f.write(block)
print("downloaded")
class CmdSysreport(Cmd):
command = "sysreport"
desc = "Show sysreport information"
parser = CmdOptionParser(description=desc)
parser.add_option("--log", default=None, action="store_true", dest="log",
help="")
parser.add_option("--begin", default=None, action="store", dest="begin",
help="The sysreport analysis begin date.")
parser.add_option("--end", default=None, action="store", dest="end",
help="The sysreport analysis begin date.")
parser.add_option("--path", default=None, action="store", dest="path",
help="A path globing pattern to limit the sysreport analysis to.")
parser.add_option("--node", default=None, action="store", dest="node",
help="The sysreport node name.")
parser.add_option("--cid", default=None, action="store", dest="cid",
help="The commit id to show as diff. This cid is displayed in the summary listing obtained by the --log action without specifying --cid.")
candidates_path = {
"--node": "/nodes",
}
api_candidates = False
def cmd(self, line):
global path
try:
options, args = self.parser.parse_args(args=shlex.split(line))
except Exception as e:
try: print(e)
except: pass
return
self.log(options)
self.log_cid(options)
def print_log(self, data):
for d in data["data"]:
print(self.colorize("cid: %s" % d["cid"], c=self.DARKCYAN))
print(self.colorize("change detection date: %s" % d["start"].replace("T", " "), c=self.GREEN))
if "summary" in d:
print()
print(" "+d["summary"])
print()
for fpath in d["stat"]:
print(" "+fpath)
print()
def print_log_cid(self, data):
for fpath, d in data["data"]["blocks"].items():
print(self.colorize("path: " + fpath, c=self.DARKCYAN))
if d["secure"]:
print(self.colorize("visible: by node responsibles", c=self.RED))
else:
print(self.colorize("visible: by everyone", c=self.DARKCYAN))
print()
for line in d["diff"].split("\n"):
if line.startswith("-"):
c = self.RED
elif line.startswith("+"):
c = self.GREEN
else:
c = None
print(self.colorize(line, c=c))
print()
def log(self, options):
if options.log is None or options.node is None or options.cid is not None:
return
params = {}
if options.begin:
params["begin"] = options.begin
if options.end:
params["end"] = options.end
if options.path:
params["path"] = options.path
r = requests.get(self.cli.api+"/nodes/"+options.node+"/sysreport", params=params, auth=self.cli.auth, verify=not self.cli.insecure)
validate_response(r)
data = json.loads(bdecode(r.content))
self.print_log(data)
def log_cid(self, options):
if options.log is None or options.node is None or options.cid is None:
return
params = {}
if options.path:
params["path"] = options.path
r = requests.get(self.cli.api+"/nodes/"+options.node+"/sysreport/"+options.cid, params=params, auth=self.cli.auth, verify=not self.cli.insecure)
validate_response(r)
data = json.loads(bdecode(r.content))
self.print_log_cid(data)
class CmdFilter(Cmd):
command = "filter"
desc = "Handle design actions on a filter"
parser = CmdOptionParser(description=desc)
parser.add_option("--list", default=None, action="store_true", dest="list",
help="List filters")
parser.add_option("--show", default=None, action="store_true", dest="show",
help="Show a filter design")
parser.add_option("--create", default=None, action="store_true", dest="create",
help="Create a filter")
parser.add_option("--delete", default=None, action="store_true", dest="delete",
help="Delete a filter")
parser.add_option("--set", default=None, action="store_true", dest="set",
help="Set filter properties")
parser.add_option("--attach", default=None, action="store_true", dest="attach",
help="Attach a filter to the filterset pointed by --filterset")
parser.add_option("--detach", default=None, action="store_true", dest="detach",
help="Detach a filter from the filterset pointed by --filterset")
parser.add_option("--filter", default=None, action="store", dest="filter",
help="The name or id of the filter to manage")
parser.add_option("--filterset", default=None, action="store", dest="filterset",
help="The name or id of the filterset to attach to or detach from")
parser.add_option("--value", default=None, action="store", dest="value",
help="with --set or --create, set the filter value parameter")
parser.add_option("--operator", default=None, action="store", dest="operator",
help="with --set or --create, set the filter operator parameter. Accepted operators: =, <, >, <=, >=, LIKE, IN")
parser.add_option("--field", default=None, action="store", dest="field",
help="with --set or --create, set the filter field parameter")
parser.add_option("--table", default=None, action="store", dest="table",
help="with --set or --create, set the filter table parameter")
parser.add_option("--order", default=None, action="store", dest="order",
help="with --attach, set the filter attachment order parameter. Integer.")
parser.add_option("--logical-operator", default=None, action="store", dest="logical_operator",
help="with --attach, set the filter attachment logical operator parameter. Accepted operators: AND, OR, AND NOT, OR NOT")
candidates_path = {
"--filterset": "/filtersets",
"--filter": "/filters",
}
api_candidates = False
def cmd(self, line):
global path
try:
options, args = self.parser.parse_args(args=shlex.split(line))
except Exception as e:
try: print(e)
except: pass
return
if options.filter:
options.filter = options.filter.replace("%", "(percent)")
self.list_filters(options)
self.show_filter(options)
self.create_filter(options)
self.delete_filter(options)
self.set_filter(options)
self.attach_filter_to_filterset(options)
self.detach_filter_from_filterset(options)