-
Notifications
You must be signed in to change notification settings - Fork 15
/
plugins.py
executable file
·85 lines (65 loc) · 2.43 KB
/
plugins.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
#!/bin/env python
import os
import zipfile
import urllib.request
import shutil
import platform
pluginsKey = "GRAFANA_PLUGINS"
pluginsVolume = "/opt/plugins"
ARCH = os.environ.get("ARCH", platform.machine())
OS = os.environ.get("OS", platform.system().lower())
class ZipFileWithPermissions(zipfile.ZipFile):
"""Custom ZipFile class handling file permissions."""
def _extract_member(self, member, targetpath, pwd):
if not isinstance(member, zipfile.ZipInfo):
member = self.getinfo(member)
targetpath = super()._extract_member(member, targetpath, pwd)
attr = member.external_attr >> 16
if attr != 0:
os.chmod(targetpath, attr)
return targetpath
def getPlugins():
result = list()
if pluginsKey in os.environ and not (not os.environ[pluginsKey]):
plugins = os.environ[pluginsKey].split(",")
for plugin in plugins:
parts = plugin.split(":", 1)
plugin_url = ""
name = ""
if len(parts) == 2:
if parts[0] == "url":
plugin_url = parts[1]
name = "/tmp/%s.zip" % plugin_url.rsplit("/", 1)[-1]
else:
plugin_url = f"https://grafana.com/api/plugins/{parts[0]}/versions/{parts[1]}/download?os={OS}&arch={ARCH}"
name = f"/tmp/{parts[0]}_{parts[1]}.zip"
elif len(parts) == 1:
plugin_url = f"https://grafana.com/api/plugins/{parts[0]}/versions/latest/download?os={OS}&arch={ARCH}"
name = f"/tmp/{parts[0]}_latest.zip"
else:
print("Invalid syntax (version missing?): " + plugin)
result.append((plugin_url, name))
return result
def downloadPlugin(plugin):
url, file_name = plugin
print(f"downloading {url}")
with urllib.request.urlopen(url) as response, open(file_name, "wb") as out_file:
shutil.copyfileobj(response, out_file)
return file_name
def extractPlugin(file_name):
print(f"extracting {file_name}")
zip = ZipFileWithPermissions(file_name)
zip.extractall(pluginsVolume)
zip.close()
def installPlugin(plugin):
try:
file_name = downloadPlugin(plugin)
except Exception as err:
print("Error downloading %s:%s: %s" % (*plugin, err))
else:
extractPlugin(file_name)
def main():
for plugin in getPlugins():
installPlugin(plugin)
print("done")
main()