This repository has been archived by the owner on May 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathovh-cli.py
executable file
·214 lines (169 loc) · 6.31 KB
/
ovh-cli.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
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
OVH CLI is a convenient Command Line Interface (CLI) built on top of
``python-ovh`` and OVH's ReST APIs.
Available command list is generated at runtime based on automatically updated
json schemas of the API.
The name of the API to use is determined by the executable name. For instance,
if runing program is called 'ovh-eu', it will expose european OVH's API'.
Currently supported APIs includes:
- ovh-eu
- ovh-ca
- kimsufi-eu
- kimsufi-ca
- soyoustart-eu
- soyoustart-ca
- runabove-ca
Usage: General: {cli} [--help|--refresh|--format (pretty|json)] your command and args --param value --param2 value2
Get help on a specific path: {cli} your command --help
Get help on a specific action: {cli} your command (list|show|update|create|delete) --help
Note: if requested action conflicts with an API action the API action will be
executed. To force the action, prefix it with 'do_'. Fo instance, 'list'
becomes 'do_list'
Top level options:
--help This message
--refresh Rebuild available commands list and documentation
--format Output format, can be 'pretty', 'json', 'yaml' or 'bash'. (default='pretty')
--debug Print verbose debugging informations. Use it when reporting a bug
'''
# TODO:
# - list / complete 'enum' arguments
from __future__ import absolute_import
import os
import sys
import ovh
from ovhcli.utils import camel_to_snake
from ovhcli.schema import load_schemas, SCHEMAS_BASE_PATH, SCHEMAS
from ovhcli.formater import formaters, get_formater
from ovhcli.parser import ArgParser
from ovhcli.parser import ArgParserException, ArgParserTypeConflict, ArgParserUnknownRoute
try:
import cPickle as pickle
except ImportError:
import pickle
from ovh.client import ENDPOINTS
## overload ovh client to insert debug informations
class OVHClient(ovh.Client):
def __init__(self, debug, *args, **kwargs):
super(OVHClient, self).__init__(*args, **kwargs)
self.debug=debug
def call(self, method, path, data=None, need_auth=True):
debug = self.debug and path != "/auth/time"
if debug:
sys.stderr.write("%s, %s" % (method, path))
if data:
sys.stderr.write("(%s)" % data)
data = super(OVHClient, self).call(method, path, data, need_auth)
if debug:
if data:
sys.stderr.write(" --> %s" % data)
sys.stderr.write("\n")
return data
## parser
def init_arg_parser(endpoint, refresh=False):
'''
Build command line parser from json and cache result on disk for faster
load.
As there is (currently) no ambiguity, always take only the second part of
the 'resourcePath' as command name. For instance, '/hosting/privateDatabase'
leads to 'private-database'.
All command line arguments are converted to snake-case.
:param str endpoint: api endpoint name.
:param boolean refresh: when ``True``, bypass cache, no matter its state.
'''
cache_file = SCHEMAS_BASE_PATH+endpoint
# First attempt to load parser from cache
try:
if not refresh:
with open(cache_file, 'r') as f:
return pickle.load(f)
except:
pass
# cache dir exists ?
if not os.path.exists(SCHEMAS_BASE_PATH):
os.makedirs(SCHEMAS_BASE_PATH)
# get schemas
load_schemas(ENDPOINTS[endpoint])
# Build parser
parser = ArgParser(None, None)
for schema in SCHEMAS.values():
if not 'resourcePath' in schema:
continue
# add root command
base_path = schema['resourcePath']
api_cmd = camel_to_snake(base_path[1:])
api_parser = parser.ensure_parser(api_cmd, base_path[1:])
# add subcommands
for api in schema['apis']:
command_path = api['path'][len(base_path):]
command_parser = api_parser.ensure_path_parser(command_path, api['description'], schema)
# add actions
for operation in api['operations']:
command_parser.register_http_verb(
operation['httpMethod'],
operation['parameters'],
operation['description']
)
# cache resulting parser
with open(cache_file, 'w') as f:
pickle.dump(parser, f, pickle.HIGHEST_PROTOCOL)
return parser
def do_usage():
print sys.modules[__name__].__doc__.format(cli=sys.argv[0])
if __name__ == '__main__':
options = {
'debug': False,
'refresh': False,
'help': False,
'format': 'terminal', # or 'json'
}
# load and validate endpoint name from cli name
endpoint = os.path.basename(sys.argv[0])
if endpoint not in ENDPOINTS:
print >> sys.stderr, "Unknown endpoint", endpoint
sys.exit(1)
args = sys.argv[1:]
# special/top level arguments:
while args and args[0].startswith('--'):
arg = args.pop(0)
if arg == '--refresh':
options['refresh'] = not options['refresh']
if arg == '--debug':
options['debug'] = not options['debug']
if arg == '--help':
options['help'] = not options['help']
if arg == '--format':
try: options['format'] = args.pop(0)
except IndexError: pass
if options['format'] not in formaters:
print >>sys.stderr, 'Invalid format %s, expected one of %s' % (options['format'], ', '.join(formaters.keys()))
sys.exit(1)
# create argument parser
parser = init_arg_parser(endpoint, options['refresh'])
if options['help']:
do_usage()
print parser.get_help_message()
sys.exit(1)
# Ensure enough arguments
if not args:
do_usage()
sys.exit(1)
try:
verb, method, arguments = parser.parse('', args)
except ArgParserUnknownRoute as e:
print e
sys.exit(1)
if verb is None:
# abort
sys.exit(0)
client = OVHClient(options['debug'], endpoint)
formater = get_formater(options['format'])
try:
formater.do_format(client, verb, method, arguments.__dict__)
except Exception as e:
# print nice error message
print e
# when in debug mode, re-raise to see the full stack-trace
if options['debug']:
raise