-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsbclient.py
294 lines (234 loc) · 8.9 KB
/
sbclient.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
import getpass
import hashlib
import os
import sys
import tarfile
import json
from configparser import RawConfigParser
from io import BytesIO
import click
import requests
from dateutil.parser import parse as dateparse
from defusedxml.ElementTree import parse
from six.moves.urllib.parse import urljoin
class AppNotFound(Exception):
pass
class DownloadFailed(Exception):
def __init__(self, error, *args, **kwargs):
super().__init__(*args, **kwargs)
self.error = error
def __str__(self):
if hasattr(self.error, "status_code"):
return "DownloadFailed(Status=%s): %s" % (self.error.status_code, self.error.text)
return "DownloadFailed: %s" % self.error
class NoReleaseFound(Exception):
pass
class VersionNotFound(Exception):
pass
class SplunkbaseSession(requests.Session):
__app_info = {}
def __init__(self, username, password, *args, **kwargs):
super(SplunkbaseSession, self).__init__(*args, **kwargs)
r = self.post(
"/api/account:login",
data={
"username": username,
"password": password
}
)
r.raise_for_status()
tree = parse(BytesIO(r.content))
root = tree.find("./{http://www.w3.org/2005/Atom}id")
self.headers.update({
"X-Auth-Token": str(root.text)
})
def prepare_request(self, request):
if not request.url.startswith("https://"):
request.url = urljoin("https://splunkbase.splunk.com/", request.url)
return super(SplunkbaseSession, self).prepare_request(request)
def get_app_numeric_id(self, app_name):
r = self.get("https://apps.splunk.com/apps/id/%s" % app_name, allow_redirects=False)
if r.status_code != 302:
# Didn't find the app
return None
return r.headers["Location"].split("/")[-1]
def get_app_info_by_id(self, app_id):
if app_id is None:
# Didn't find the app
return None
r = self.get(
"/api/v1/app/%s/" % app_id,
params={"include": "release,releases"}
)
if r.status_code != 200:
# Didn't find the app
return None
return r.json()
def get_app_info(self, app_name):
if app_name not in self.__app_info:
app_id = self.get_app_numeric_id(app_name)
self.__app_info[app_name] = self.get_app_info_by_id(app_id)
return self.__app_info[app_name]
def download_app(self, app_name, version=None, output_path=None):
data = self.get_app_info(app_name)
if data is None:
raise AppNotFound
if version is None:
release = data.get("release", None)
if release is None:
raise NoReleaseFound
else:
release = None
for potential_release in data["releases"]:
if potential_release["title"] == version:
release = potential_release
break
if release is None:
raise VersionNotFound
for checksum_type in ("sha256", "md5"):
if checksum_type in release:
app_checksum = release[checksum_type]
break
r = self.get(
release["path"], stream=True
)
if r.status_code != 200:
raise DownloadFailed(r)
if output_path is None:
output_path = "%s-%s.tgz" % (app_name, release["title"])
if app_checksum:
h = hashlib.new(checksum_type)
f = sys.stdout.buffer if output_path == "-" else open(output_path, 'wb')
for chunk in r.iter_content(1024):
if app_checksum:
h.update(chunk)
f.write(chunk)
if f is not sys.stdout.buffer:
f.close()
if app_checksum:
checksum = h.hexdigest()
if checksum != app_checksum:
raise DownloadFailed("Checksum mismatch: expected %s, got %s" % (
app_checksum,
checksum
))
return output_path
def get_app_latest_version(self, app_name, splunk_version=None):
app_info = self.get_app_info(app_name)
if app_info is None:
raise AppNotFound
if splunk_version is None:
release = app_info.get("release", None)
else:
release = None
for potential_release in app_info.get("releases", []):
for compatible_version in potential_release["splunk_compatibility"]:
if splunk_version == compatible_version or \
splunk_version.startswith("%s." % compatible_version):
release = potential_release
break
if release is None:
raise NoReleaseFound
return release
def get_app_splunkbase_path(self, app_name):
app_info = self.get_app_info(app_name)
if app_info is None:
raise AppNotFound
return app_info["path"]
@click.group()
@click.option("-U", "--username", envvar="SPLUNKBASE_USERNAME", required=True)
@click.option("-P", "--password", envvar="SPLUNKBASE_PASSWORD", required=False)
@click.pass_context
def cli(ctx, username, password):
if password is None:
password = getpass.getpass("Splunkbase password: ")
ctx.obj = SplunkbaseSession(username, password)
@cli.command()
@click.option("--splunk-version", required=False,
help="Restrict to app versions compatible with a given Splunk version")
@click.argument("app_dir", nargs=1, required=True)
@click.pass_context
def check_app_for_update(ctx, splunk_version, app_dir):
app_name = os.path.basename(app_dir)
try:
release = ctx.obj.get_app_latest_version(app_name, splunk_version)
except (AppNotFound, NoReleaseFound):
release = None
with open(os.path.join(app_dir, "default", "app.conf")) as f:
app_config = RawConfigParser(delimiters="=", comment_prefixes="#")
app_config.optionxform = str
app_config.read_file(f)
print("%s %s" % (app_name, app_config["launcher"]["version"]))
if not release:
print("Latest: UNAVAILABLE")
else:
if release["title"] == app_config["launcher"]["version"]:
print("App is up-to-date")
else:
print("Latest: %s" % (release["title"]))
print("URL: %s" % ctx.obj.get_app_splunkbase_path(app_name))
print("Supported Splunk Versions:")
print(" ".join(release["splunk_compatibility"]))
@cli.command()
@click.option("--output-path", "-o", required=False,
help="Path and filename location to save the app")
@click.option("--version", "-v", required=False,
help="Version of app to download, default is latest")
@click.option("--untar", "-u", is_flag=True, required=False,
help="Untars the app and removes the tarball")
@click.argument("app_name", nargs=1, required=True)
@click.pass_context
def download_app(ctx, output_path, version, app_name, untar):
try:
output_path = ctx.obj.download_app(app_name, version, output_path)
except AppNotFound:
print("App '%s' not found on Splunkbase" % app_name)
return 1
except VersionNotFound:
print("'%s' found on Splunkbase, but version '%s' is unavailable" % (app_name, version))
return 1
except DownloadFailed:
print(repr(DownloadFailed))
return 1
if untar and output_path != "-":
tar = tarfile.open(output_path)
tar.extractall()
tar.close()
os.remove(output_path)
return 0
@cli.command()
@click.option("--splunk-version", required=False,
help="Restrict to app versions compatible with a given Splunk version")
@click.argument("app_name", nargs=1, required=True,)
@click.pass_context
def get_latest_version(ctx, splunk_version, app_name):
try:
release = ctx.obj.get_app_latest_version(app_name, splunk_version)
except AppNotFound:
print("App '%s' not found on Splunkbase" % app_name)
return 1
except NoReleaseFound:
print("No compatible version of '%s' found on Splunkbase" % app_name)
return 1
if "title" in release["manifest"]["info"]:
print("%s - %s" % (app_name, release["manifest"]["info"]["title"]))
else:
print(app_name)
print("Latest: %s" % (release["title"]))
print("Supported Splunk Versions:")
print(" ".join(release["splunk_compatibility"]))
return 0
@cli.command()
@click.argument("app_name", nargs=1, required=True,)
@click.pass_context
def get_app_info(ctx, app_name):
app_info = ctx.obj.get_app_info(app_name)
print(json.dumps(app_info, indent=4))
return 0
@cli.command()
@click.argument("app_id", nargs=1, required=True,)
@click.pass_context
def get_app_info_by_id(ctx, app_id):
app_info = ctx.obj.get_app_info_by_id(app_id)
print(json.dumps(app_info, indent=4))
return 0