-
Notifications
You must be signed in to change notification settings - Fork 177
/
o
executable file
·2186 lines (1857 loc) · 82.8 KB
/
o
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
#!/usr/bin/env python3
# Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
# ==============================================================================
# o - a wrapper for OCI CLI to simplify and edify
#
# Author: Kevin.Colwell@oracle.com
# ==============================================================================
import signal
import time
import textwrap
import subprocess
import re
import json
import getopt
import sys
import os
if (sys.platform != "win32"):
import fcntl
import errno
import datetime
VERSION = "1.8"
UPDATED = "2023-06-12"
# ==============================================================================
# Global variables
# ==============================================================================
ocids_file_name = '' # name of file where OCIDs are saved
ocid = {} # dict of known ocids
ocids = [] # list of known ocids
orphans = [] # orphaned ocids (with no compartment) found in ocids file
command = [] # commands with required and optional params
show_help = False # user asked for help
go = False # execute the oci cli command
nogo = False # don't execute due to error in ocid substitutions
quiet = 0 # quiet mode - 1: don't show command; 2: don't show headers
debug = False # Debug output
region = '' # region
region_code = '' # 3-letter region code
ocids_in_output = False # substitute names for ocids in output
# Universally useful fields as default output, if no "-o" on command line.
# This leverages the fact that fields not found in data are quietly ignored.
# We want to show the most interesting fields for the most common ocid types.
default_out_spec = 'name{:.30}#shape#cidr-block#prohibit-public{:5.5}' \
'#lifec#size-in-gbs{:>11.11}#size-in-mbs{:>11.11}#size' \
'#availability-domain{:.1}#fault-domain{:>1.1}' \
'#resource-type' \
'#created{:16.16}#compartment{:.20}#instance-id' \
'#id{:>8.8}' \
'#direction#destination' \
'#ip-address#public-ip#private-ip' \
'#vnic-id#desc{:.40}' \
'#access-uri#storage-tier' \
'#token'
matches = [] # list of commands that match user input
all_options_for_this_cmd = '' # for best_match
remaining_options = '' # for best_match
options_out = [] # list of expanded options to be passed to oci cli
oci_command_line = '' # the complete oci cli command in string form
column = {} # field format info: format:'{:}', offset:0, maxwidth:n
use_bold = True # enable xterm bold highlighting
wrap = 120 # wrap at column <wrap>
global_options = ''
# ==============================================================================
def usage(s=''):
print("""
o - a friendly helper for Oracle Cloud Infrastructure CLI
usage: o [<o options>] <oci-command> [<oci-options>] [.]
<o options>
-o name#life#time:.16 Table output
Show fields that match "name", "life" or "time"
Truncate "time" at 16 characters
-o name,life,time CSV output
-o name/life/time Text output - one field per line
-o / Show all fields in text
-o json JSON format - unfiltered oci output
-O Show OCIDs (not names) in output
-i <infile> Take JSON input from <infile>; "o -i -" for stdin
<oci-command> The oci "service resource action" specification
<oci-options> Options and parameters for <oci-command>
These will be expanded into a more correct oci command
. or go If the line ends with "." (or "go") run the oci command
! If line ends with "!", force-run the command, even if
param substitution fails""")
if s != "help":
print("""
o help More "o" options and usage.""")
else:
print("""
More output options:
o -o shap.ocpus Show matching sub-field, e.g. shape-config.ocpus
o -o +route#dns-label Add fields default output
o -o +shap.ocpus Append fields to default output
o -o +/ Keep default fields, change format to Text
o -o created:10.10 Show first 10 characters of time-created
o -o id:-10.10 Show last 10 characters of OCID
More "o" options:
-q Suppress display of "oci" command line
-qq Also suppress headers and non-"data" results from output
Useful when piping results other commands
o oci_commands Build (or rebuild) the $HOME/.oci/oci_commands file
o <tenancy-ocid> Set up $HOME/.oci/ocids file with compartment-ocids
from a tenancy. Use this for first-time setup, or to add
additional tenancies. Remember to set OCI_CLI_PROFILE
(or use --profile) for different tenancies.
o ocids "name" Show saved OCIDs for resources matching "name"
o prune "name" Remove OCIDs for resources matching "name" from
$HOME/.oci/ocids. If "name" is a compartment, remove
all OCIDS under compartment "name".
touch $HOME/.oci/.otmp Activate "save last result" feature. With this
you can reformat output from the last command
without re-running the command with:
o -o <fmt>
o <oci-command> help Show all parameters, including globals
o <oci-command> --help . Get help from oci""")
print("""
o Version {} - {}
""".format(VERSION, UPDATED))
if s not in ('', 'help'):
print(bold(s) + '\n')
exit(1)
# ==============================================================================
def interrupted(sig, frame):
error_out("Interrupted")
exit(1)
# ==============================================================================
def bold(s=''):
return '\033[1m' + s + '\033[0m' if use_bold else s
# ==============================================================================
def error_out(msg):
"""Decode JSON ServiceError."""
if msg.startswith('ServiceError:'):
j = json.loads(msg[14:])
print(bold('ServiceError(' + str(j['status']) + '): ' + str(j['code'])), file=sys.stderr)
print(bold(j['message']), file=sys.stderr)
else:
print(bold(msg), file=sys.stderr)
# ==============================================================================
def read_oci_commands_file():
"""Read oci_commands for the list of all cli commands with parameters.
First look for oci_commands where o is installed.
If not found, look for ~/.oci/oci_commands
If not found, create new file ~/.oci/oci_commands
"""
global global_options
pathname = os.path.dirname(sys.argv[0])
if not pathname:
pathname = '.'
oci_commands_file = pathname + '/oci_commands'
if not os.path.isfile(oci_commands_file):
oci_commands_file = os.path.expanduser('~/.oci/oci_commands')
command_list = []
try:
for line in open(oci_commands_file).read().splitlines():
if re.match(r'oci ', line):
command_list.append(parse_oci_command_options(line))
elif re.match(r'global_options ', line):
global_options = line[line.find(' ') + 1:]
except FileNotFoundError:
print(bold('No ' + oci_commands_file + ' file.'))
print('Create it with:\n')
print(bold(' o oci_commands'))
print('\nIt takes about two minutes.')
exit(1)
except OSError as e:
msg = "{0}".format(e)
print(bold(msg))
exit(1)
if len(command_list) < 1000:
print(bold('File ' + oci_commands_file + ' is incomplete.'))
print('Re-create it with:')
print(bold(' o oci_commands'))
exit(1)
return command_list
# ==============================================================================
def run_command(command):
if os.system(command):
if re.search('iam compartment get', command):
return (1)
print(bold("It looks like that didn't work. So sorry."))
exit(1)
return 0
# ==============================================================================
def get_from_oci_config(key):
"""Look in config file for key = value"""
s = oci_command_line
if '--profile' in s:
profile = s.split()[s.split().index('--profile') + 1]
elif os.getenv('OCI_CLI_PROFILE'):
profile = os.getenv('OCI_CLI_PROFILE')
else:
profile = 'DEFAULT'
config_file = os.path.expanduser('~/.oci/config')
if '--config' in oci_command_line:
config_file = s.split()[s.split().index('--config') + 1]
if not os.path.exists(config_file) and os.path.exists('/etc/oci/config'):
config_file = '/etc/oci/config'
try:
value = None
this_profile = ''
with open(config_file, 'r') as f:
for line in f:
m = re.search(r'^\[(.+)\]', line)
if m:
this_profile = m.group(1)
if this_profile in ('DEFAULT', profile):
m = re.search(r'[^#]*' + key, line)
if m and not line.startswith('#'):
value = line.split('=')[1].strip()
if this_profile == profile:
return value
return value
except BaseException:
return None
# ==============================================================================
def setup_ocids_file():
"""Create or update ocids_file for tenancy found on command line.
If run with "o <tenancy-ocid>" run three o commands to populate ocids
o <tenancy-ocid>
Otherwise offer help and then exit.
On completion exit; do not return from this function.
"""
if not (len(sys.argv) in [2, 3] and re.search(
'ocid1.tenancy.{50}', sys.argv[1])):
# No ocid provide; offer help
print(bold('No ' + ocids_file_name + ' found.\n'))
print("""To setup "o" just run:
\033[1mo <your-tenancy-ocid> \033[0m
and I'll do this for you:
o iam compartment list -c <tenancy-ocid> -ciis true -all .
o iam ad list -c <tenancy-ocid> .
o iam region-subscription list .
""")
# To be extra helpful, get likely tenancy ocid from oci config file
oci_config_file = os.path.expanduser('~/.oci/config')
if not os.path.exists(oci_config_file) \
and os.path.exists('/etc/oci/config'):
oci_config_file = '/etc/oci/config'
t = get_from_oci_config('tenancy')
print('Try:\n', bold(' o ' + t))
else:
# <tenancy-ocid> provided... Let's roll!
print("Tenancy ocid:", sys.argv[1])
if len(sys.argv) == 3:
print("Tenancy name:", sys.argv[2])
print(bold('Setting up your ' + ocids_file_name + ' file:'))
print(bold('\nGetting compartment names and ocids...'), end='')
if run_command(sys.argv[0] + ' -o name iam compartment list -c ' + sys.argv[1] + ' -ciis true -all .'):
print('\nThat didn\'t work. Your account may need additional privileges.')
exit(0)
print(bold('\nGetting availability domains...'), end='')
run_command(sys.argv[0] + ' -o name iam ad list -c ' + sys.argv[1] + ' .')
print(bold('\nGetting regions...'), end='')
run_command(sys.argv[0] + ' -o name iam region-subscription list .')
print(bold('\nGetting tenancy name from root compartment...'), end='')
if run_command(sys.argv[0] + ' -o name iam compartment get -c ' + sys.argv[1] + ' .'):
# compartment get on tenancy failed; try saving a stub for tenancy
print("\nCould not get root compartment.")
tenancy_name = input(bold("Enter tenancy name: "))
if not tenancy_name:
tenancy_name = 'root'
newids = {'root': {
'type': 'tenancy',
'alias': tenancy_name,
'id': sys.argv[1],
'name': tenancy_name,
},
}
ocids_file('write', newids)
exit(0)
print('\n' + bold('All set. Have fun!\n'))
exit(0)
# ==============================================================================
def ocids_file(action, new_ocids={}):
"""Take action on ocids_file_name:
action=read - populate globals:
ocid - dict of resources
ocids - list of resources
action=write - write ocids file
If new_ocids = {}, write ocids to file (used by prune to remove entries)
if new_ocids, merge new entries into file:
- lock ocids file, then
- read ocids file to get latest updates
- merge new_ocids with ocids
- rewrite file and unlock
"""
global ocid, ocids, ocids_file_name
if os.path.exists('.ocids'):
ocids_file_name = '.ocids'
elif os.path.exists('ocids'):
ocids_file_name = 'ocids'
else:
ocids_file_name = os.path.expanduser('~/.oci/ocids')
# Run setup if no ocids_file exists or
# if this is an "o <tenancy>" setup command and new_ocids is empty
if (not new_ocids
and (not (re.search('iam compartment list .*-c ocid..tenancy', ' '.join(sys.argv)))
and (not os.path.exists(ocids_file_name)
or re.search('o [^c]*ocid..tenancy', ' '.join(sys.argv))))):
setup_ocids_file()
if action == 'read' and not os.path.exists(ocids_file_name):
return
tries = 1
while tries <= 50:
try:
if os.path.exists(ocids_file_name):
os.umask(0o077)
f = open(ocids_file_name, 'r+')
if new_ocids:
if (sys.platform != "win32"):
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
if new_ocids or action == 'read':
ocids = json.load(f)
# Convert list of ocids into dict of ocids.
# Use id as key, except for special types.
special_types = ['availabilitydomain', 'opcnextpage']
ocid = {i['id']: i for i in ocids if i['type'] not in special_types}
ocid.update({i['name']: i for i in ocids if i['type'] in special_types})
else:
os.umask(0o077)
f = open(ocids_file_name, 'w+')
if action == 'write':
# merge
ocid.update(new_ocids)
# Don't save ocids for deleted resources
ocid = {k: v for (k, v) in ocid.items()
if 'lifecycle-state' not in v
or v['lifecycle-state'] not in ('DELETED', 'TERMINATED')
and k not in orphans}
# clean up temp values in ocid
for k, v in ocid.items():
if 'score' in v:
del v['score']
if 'parents' in v:
del v['parents']
# convert dict to list
ocids = [ocid[k] for k in ocid.keys()]
ocids.sort(key=lambda x:
(x['type'], x['alias'].lower(), x['id']))
# write ocids list to ocid_file
f.seek(0)
print(json.dumps(ocids, indent=4), file=f)
f.truncate()
f.close()
return
except IOError as e:
# ocids file locked for writes - take short nap and try to write again
if e.errno != errno.EAGAIN:
print(bold(ocids_file_name + ': not accessible'), file=sys.stderr)
f.close()
msec = (int.from_bytes(os.urandom(4)) % 200 + 5) * tries
time.sleep(msec / 1000.)
tries += 1
except ValueError:
# ocids file corrupt (write in progress?) - sleep and try to read again
f.close()
time.sleep(0.05 * tries)
tries += 1
if tries >= 50:
print(bold(ocids_file_name + ': ' + action + ' failed'), file=sys.stderr)
return
# ==============================================================================
def get_new_ocids_from_returned_items(items):
"""Collect ocids found in results from oci cli.
For consistency each entry must have: type, alias, id.
In addition to those, we collect anything that might be used by omap.
"""
# special case for region list - save the whole list in one entry
if 'oci iam region list' in oci_command_line:
return {'regionlist': {
'type': 'regionlist',
'alias': 'regionlist',
'id': 'regionlist',
'data': items}}
if oci_command_line.startswith('oci search'):
for i in items:
if 'identifier' in i and 'id' not in i:
i['id'] = i['identifier']
collected = {}
try:
for item in [i for i in items if 'id' in i]:
type = item['id'].split('.')[1] if '.' in item['id'] else ''
# Special case: save AD-name:n because commands use name, not ocid
ID = item['id']
if 'availability' in item['id']:
ID = item['name']
if 'alias' in item and item['alias'] == 'opc-next-page':
ID = item['alias']
type = 'opcnextpage'
if 'retention-rule' in oci_command_line:
type = 'retentionrule'
# Still need to validate with many OCID types:
# cpe, cross-connect, fast-connect, ip-sec, virtual-circuit
if type == 'availabilitydomain':
alias = item['name'][-1:]
elif 'object-name' in item:
alias = item['name']
type = "par"
elif (type == 'routetable'
and item['display-name'].startswith('Default Route Table for ')):
alias = item['display-name'][len('Default Route Table for '):]
elif (type == 'securitylist'
and item['display-name'].startswith('Default Security List for ')):
alias = item['display-name'][len('Default Security List for '):]
elif type == 'vnicattachment':
if item['instance-id'] in ocid:
alias = ocid[item['instance-id']]['alias']
else:
alias = item['instance-id'][-8:]
alias = '-'.join([alias, str(item['nic-index']), 'vlan' + str(item['vlan-tag'])])
elif type == 'providerservice':
alias = str(item['provider-name']) + ' ' + str(item['provider-service-name'])
elif 'instanceconsoleconnection' in type:
alias = ocid[item['instance-id']]['alias']
elif 'name' in item:
alias = item['name']
elif 'display-name' in item:
alias = item['display-name']
elif 'db-name' in type:
alias = item['db-name']
elif 'credential' in type:
alias = item['description']
else:
# Unable to determine data type, don't add to collection
# print("type:", type, json.dumps(item, indent=4))
return ({})
if not alias:
alias = 'unnamed-' + type
collected[ID] = {'type': type, 'alias': alias, 'id': item['id']}
# Now add various non-empty fields depending on item type
collected[ID].update({k: item[k] for k in item.keys() if (
item[k] and (
k.endswith('-id')
or k.endswith('-tags')
or k.endswith('name')
or k.startswith('size')
or k in ['lifecycle-state',
'availability-domain',
'storage-tier',
'description',
'shape',
'cidr-block',
'dns-label',
'virtual-router-ip',
'virtual-router-mac',
'security-list-ids',
'route-rules',
'ip-addresses',
'private-ip',
'public-ip',
'is-primary',
'subnet-ids',
'access-type',
'created-by',
'time-expires',
'access-uri']))})
if 'created-by' in item and '/' in item['created-by']:
collected[ID]['created-by'] = item['created-by'].split('/')[1]
if 'time-created' in item:
collected[ID]['time-created'] = item['time-created'][:19]
# Retain access-uri.
if type == 'par' and ID in ocid and 'access-uri' in ocid[ID]:
collected[ID]['access-uri'] = ocid[ID]['access-uri']
except BaseException:
print(bold('Unable to collect ocids of type ' + type
+ '. Please provide this data with your problem report:\n')
+ json.dumps(item, indent=4), file=sys.stderr)
return collected
# ==============================================================================
def show_command(c, full=False, prefix='oci '):
print(prefix + c['action'])
if full:
print(' requires\t' + re.sub(r' -', r'\n\t\t-', c['required']))
print(' optional\t' + re.sub(r' -', r'\n\t\t-', c['optional']))
if show_help:
print(' global\t' + re.sub(r'\n', r'\n ',
textwrap.fill(global_options, width=60, break_on_hyphens=False)))
# ==============================================================================
def parse_oci_command_options(line):
"""Separate oci command from --required and + --optional options."""
c = {'action': '', 'required': '', 'optional': '', 'line': line}
if ' + ' in line:
[line, c['optional']] = line.split(' + ', 1)
if ' --' in line:
[c['action'], r] = line[4:].split(' --', 1)
c['required'] = '--' + r
else:
c['action'] = line[4:]
return (c)
# ==============================================================================
def args_match_command(c, params):
"""Compare argv with command "c" to see how well they match."""
action = ' ' + c['action'] + ' '
for a in params:
# accept plurals in place of singulars
if (len(a) > 3 and a[-1] == 's' and a not in ['address', 'access', 'waas']):
a = a[:-1]
if a[-2:] == 'ie':
a = a[:-2]
# Look for full-word match first
if ' ' + a + ' ' in action:
# Scratch out match
action = re.sub(' ' + a + ' ', ' ', action, count=1)
continue
# look for word starting with arg
if ' ' + a in action or '-' + a in action:
# Scratch out this match
action = re.sub(' ' + r'(\S+-)*' + a + r'(\S+)', ' ', action, count=1)
continue
# look for rlc -> really-long-command
multi_re = ' ' + r'\w+\-'.join(list(a)) + r'\S+'
if re.search(multi_re, action):
# Scratch out this match
action = re.sub(multi_re, ' ', action)
continue
return (False)
return (True)
# ==============================================================================
def option_parameter(arg):
"""Look for match in remaining_options
- Allow - in place of --
- Replace partial opt with full option name
--rlon ==> --really-long-option-name
"""
a = arg.lstrip('-')
if not a:
return arg
# special case for -c
if a in ['c', 'cid']:
a = 'compartment-id'
m = re.search('(--' + a + ') ', remaining_options)
if (m):
return m.group(1)
m = re.search('(--' + a + '[a-z-]*) ', remaining_options)
if (m):
return m.group(1)
# build a regex a[0] + a[1] + -a[1] + -a[2]... for -rlon
multi_re = '-+' + r'\w+\-'.join(list(a[:-1]))
# special case if it ends in 'id'
if len(a) > 2 and a[-2:] == 'id':
multi_re += 'd\\b'
else:
multi_re += r'\w+\-' + a[-1] + r'[\w-]+'
m = re.search(multi_re, remaining_options)
if m:
return m.group(0)
# Unable to expand; just go with what user provided
return arg
# ==============================================================================
def alias_match_score(spec, name):
"""Does user spec match this item name?
score reflects quality of match.
"""
if spec == name:
return 40 + len(spec)
elif spec.lower() == name.lower():
return 25 + len(spec)
elif re.match(spec + ' ', name):
return 25 + int(200 * len(spec) / len(name)) / 10.0
elif re.match(spec, name):
return 20 + int(200 * len(spec) / len(name)) / 10.0
elif re.match(spec, name, flags=re.I):
return 10 + int(200 * len(spec) / len(name)) / 10.0
elif re.search(spec, name, flags=re.I):
return 5 + int(200 * len(spec) / len(name)) / 10.0
return 0
# ==============================================================================
def get_item_parents(i):
"""Return heirarchy of compartments containing this item in list"""
if 'parents' in i:
return i['parents']
if 'compartment-id' not in i:
return [i['alias']]
if i['compartment-id'] in ['', 'publisherCompartment']:
return [i['alias']]
if i['compartment-id'] in ocid:
if i['type'] == 'availabilitydomain':
return get_item_parents(ocid[i['compartment-id']]) + [i['name']]
else:
return get_item_parents(ocid[i['compartment-id']]) + [i['alias']]
else:
# Tag this as orphan for later removal?
orphans.append(i['id'])
return [i['alias']]
# ==============================================================================
def alias_match(spec, item):
"""Does user spec match this item alias - and parent(s)?
Return True if match; score reflects quality of match
"""
item['score'] = 0
item['parents'] = get_item_parents(item)
specs = list(filter(None, spec.split('/')))
item_path = list.copy(item['parents'])
for s in reversed(specs):
# more specs than path parts?
if not item_path:
return False
while item_path:
i = item_path.pop()
score = alias_match_score(s, i)
if score > 0:
if item['score'] == 0:
item['score'] = 2 * score
else:
item['score'] += score
break # from while, to next "s"
else:
# not an alias match, look for ocid match
if len(specs) == 1:
if re.search(spec, item['id'], flags=re.I):
item['score'] = int(1000 * len(spec) / len(item['id'])) / 10.0
return True
return False
# This item heirarchy did not match specs.
# Give up if it's the first part of spec or end of item_path
if item['score'] == 0 or not item_path:
return False
# Otherwise deduct 20% from score as a penalty
item['score'] = int(item['score'] * .8)
if item['score'] > 0:
return True
return False
# ==============================================================================
def type_match(option, item_type):
"""Compare option with item for type match, return boolean.
If parameter --<option>-id doesn't match ocid1.<item_type>.oc1...
add it to the list of exceptions.
"""
if (option == item_type
or (option.startswith('compartment') and item_type == 'tenancy')
or (option.startswith('tenant') and item_type == 'tenancy')
or (option == 'ig' and item_type == 'internetgateway')
or (option == 'rt' and item_type == 'routetable')
or (option == 'nsg' and item_type == 'networksecuritygroup')
or (option == 'stack' and item_type == 'ormstack')
or (option == 'sourcebootvolume' and item_type == 'bootvolume')
or (option == 'image' and item_type == 'containerimage')
or (option == 'repository' and item_type == 'containerrepo')
or (option == 'dhcp' and item_type == 'dhcpoptions')
or (option == 'application' and item_type == 'fnapp')
or (option == 'function' and item_type == 'fnfunc')
or (option == 'asset' and item_type in ('volume', 'bootvolume', 'volumegroup'))
or (option == 'sddc' and item_type == 'vmwaresddc')
or (option == 'avail' and len(item_type) == 1)):
return True
return False
# ==============================================================================
def ambiguous_value(option, value, matches):
"""Multiple matches with same score. Ambiguous."""
if (option):
print(option, end=' ', file=sys.stderr)
print(bold(value), 'is ambiguous. Try one of these:',
file=sys.stderr)
for m in matches:
if m['score'] > 2:
print(' (score=' + str(m['score']) + ')', ' ' + bold(('/'.join(m['parents'])
if 'parents' in m else m['alias'])), ' ({:8})'.format(m['id'][-8:]))
global nogo
nogo = True
# ==============================================================================
def datetime_parameter(dt):
"""construct datetime values relative to now or today +/- offset:
now - current datetime
today - start (00:00) of current day
+/-<n>(wdhms) add/subtract <n> week/day/hour/minute/second."""
# if time only (no date), prepend today's date
if re.match(r'\d\d:\d\d', dt):
return datetime.datetime.utcnow().strftime('%Y-%m-%dT') + dt + 'Z'
dts = dt
# return time delta from now|today|yesterday
m = re.search(r'(?P<day>now|today|yesterday) *(?P<delta>.*)', dt)
if m and m.group('day'):
if m.group(1) == 'now':
time = datetime.datetime.utcnow()
elif m.group(1) in ('today', 'yesterday'):
time = datetime.datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
if m.group(1) == 'yesterday':
time = time - datetime.timedelta(hours=24)
dts = time.strftime('%Y-%m-%dT%H:%M:%S') + 'Z'
if m and m.group('delta'):
deltas = {'s': 1, 'm': 60, 'h': 60*60, 'd': 60*60*24, 'w': 60*60*24*7} # noqa: E226
m2 = re.search(r'(?P<s>[@+-]{,1})(?P<v>[\d:Z]*)(?P<u>[smhdw]{0,1})', m.group('delta'))
try:
# optional time delta +/- <n> week/day/hour/minute/second
value = int(m2.group('v')) * deltas[m2.group('u')]
if m2.group('s') == '-':
value = value * -1
time = time + datetime.timedelta(seconds=value)
dts = time.strftime('%Y-%m-%dT%H:%M:%S') + 'Z'
except (ValueError, KeyError):
dts = dts[:11] + m.group('delta')
if m.group('delta')[0] in '@+':
dts = dts[:11] + m.group('delta')[1:]
if dts[-1] != 'Z':
dts = dts + 'Z'
if dts.endswith('00:00:00Z'):
return dts[:10]
if dts.endswith(':00Z'):
return dts[:16] + 'Z'
return dts
# ==============================================================================
def get_region(r=''):
"""Determine the region in this order of precedence:
r passed in - from command line
OCI_CLI_REGION in env
--profile on cmd line
OCI_CLI_PROFILE in env
Return key.lower,name E.g.: "iad","us-ashburn-1"
"""
if 'regionlist' not in ocid:
return '', ''
if not r:
r = os.getenv('OCI_CLI_REGION')
# If region not set, get it from config file
if not r:
r = get_from_oci_config('region')
if not r:
return None, None
rmatch = [i for i in ocid['regionlist']['data'] if r.upper() == i['key'] or r in i['name']]
if rmatch:
return rmatch[0]['key'].lower(), rmatch[0]['name']
return None, None
# ==============================================================================
def region_match(id):
"""Does ocid region match profile region?"""
region_from_id = (id + '....').split('.')[3]
if not region_code \
or region_from_id == '' \
or region_from_id == region_code \
or region_from_id == region:
return True
return False
# ==============================================================================
def get_matching_ocid(option, value):
"""Look for ocid of correct type that matches value.
If result is unique, or a strong match, return the OCID.
If ambiguous, display possible matches and return None.
"""
global nogo
if value.startswith('ocid') and len(value) > 60:
return value
if '-' not in option:
opt_type = option
else:
opt_type = re.sub('-', '', re.sub('-ids{0,1}$', '', option))
# ocid type doesn't exactly match --resource-id type
if opt_type == 'job':
opt_type = 'ormjob'
elif opt_type == 'node' and 'rover' in oci_command_line:
opt_type = 'rovernode'
elif opt_type == 'authtoken':
opt_type = 'credential'
elif opt_type == 'zonenameor':
opt_type = 'dns-zone'
elif opt_type == 'identityprovider':
opt_type = 'saml2idp'
elif opt_type == 'peer' and 'local' in oci_command_line:
opt_type = 'localpeeringgateway'
elif opt_type == 'peer' and 'remote' in oci_command_line:
opt_type = 'remotepeeringconnection'
elif opt_type == 'organization':
opt_type = 'organizationsentity'
elif opt_type == 'routedistribution':
opt_type = 'drgroutedistribution'
# Add new idtypes to the above when the --whatever-id does not match ocid1.whatevs...
matches = [item for k, item in ocid.items() if
type_match(opt_type, item['type'])
and region_match(item['id'])
and alias_match(value, item)]
if not matches:
matches = [item for k, item in ocid.items() if
type_match(opt_type, item['type'])
and alias_match(value, item)]
if matches:
print(bold('\n' + value + ' found in '
+ matches[0]['id'].split('.')[3].upper() + ' region,'
+ ' but you are working in ' + region_code.upper()))
matches = sorted(matches, key=lambda i: i['score'], reverse=True)
if option == 'bucket' and '/' not in value:
return value
if not matches:
if option != 'bucket':
print(opt_type, bold(value), 'not found.', file=sys.stderr)
nogo = True
return value
# Is this match unique, or is it strong relative to other matches?
if len(matches) == 1 or matches[0]['score'] > 5 + matches[1]['score']:
if matches[0]['type'] in ('availabilitydomain', 'bucket'):
if 'name' in matches[0]:
return matches[0]['name']
if 'display-name' in matches[0]:
return matches[0]['display-name']
return matches[0]['id']
ambiguous_value(option, value, matches)
return value
# ==============================================================================
def value_parameter(option, value):
"""Assist with command line parameters.
Especially provide name -> ocid substitutions for --*id options.
"""
# Get the parameter from help: --option [param_type]
param_type = ''
m = re.search(option + r' \[([\w -\|]+?)\]', all_options_for_this_cmd)
if m:
param_type = m.group(1)
# If option is an OCID, see if value matches any saved ocids
if option.endswith('-id') or option == "--availability-domain":
match = get_matching_ocid(option, value)
return match
# Match "bucket-name" with bucket IDs
if option == '--bucket-name':
match = get_matching_ocid('bucket', value)
return match
# Provide opc-next-page if --page next
if option in ('--page', '--start') and 'next' in value:
for k, item in ocid.items():
if item['alias'] == 'opc-next-page':
return item['id']
# Convert list of resource names into a JSON list [complex type]
if option.endswith('-ids'):
idlist = []
for v in value.split(','):
if not v:
continue
o = get_matching_ocid(option, v)
idlist.append(v)
return repr(json.dumps(idlist))
# Assist with datetime parameters
if param_type == 'datetime':
return datetime_parameter(value)
# Special help with log-search --search-query "search comp1 comp2 | ..."
# Substitute "ocid1.compartment..." for one or more values.
if option == '--search-query':
m = re.search(r'search ([^|]+)', value)
if m:
for comp in m.group(1).split():
c = comp
if c.startswith('"'):
c = comp[1:-1]
o = get_matching_ocid('compartment', c)
if o != c:
value = re.sub(comp, '"' + o + '"', value)
# Special help with structured-search --search-query "where compartmentId = ocid"
if option == '--query-text':
match = re.findall(r"(\bc\w*) *= *('*\w+'*)", value, flags=re.IGNORECASE)
for (m, spec) in match:
if m.lower() == 'compartmentid'[:len(m)]: