-
Notifications
You must be signed in to change notification settings - Fork 2
/
cluster_config.py
197 lines (172 loc) · 7 KB
/
cluster_config.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
import os
import sys
import urllib.request
from https_client_auth_handler import HTTPSClientAuthHandler
class ClusterConfig:
def __init__(self, hostname=None, port=8081):
self.hostname = hostname
self.port = port
self.name = None
self.version = None
self.build_index = None
self.certificate = None
self.private_key = None
self.ca_file = 'pythoncm/etc/cacert.pem'
def get_cluster(self, auto_connect=False, redirect=False):
self.create_symlink()
from pythoncm.cluster import Cluster
from pythoncm.settings import Settings
settings = Settings(host=self.hostname,
port=self.port,
cert_file=self.certificate,
key_file=self.private_key,
ca_file=self.ca_file)
return Cluster(settings,
auto_connect=auto_connect,
follow_redirect=Cluster.REDIRECT_ACTIVE if redirect else Cluster.REDIRECT_NONE)
def get_version(self):
url = f'https://{self.hostname}:{self.port}/info/version'
opener = urllib.request.build_opener(HTTPSClientAuthHandler(),
urllib.request.ProxyHandler({}))
request = urllib.request.Request(url)
try:
response = opener.open(request)
self.version = response.read().decode('utf-8')
return len(self.version) > 0
except urllib.error.URLError as e:
print(e)
return False
def get_build_index(self):
url = f'https://{self.hostname}:{self.port}/info/build_index'
opener = urllib.request.build_opener(HTTPSClientAuthHandler(),
urllib.request.ProxyHandler({}))
request = urllib.request.Request(url)
try:
response = opener.open(request)
self.build_index = int(response.read().decode('utf-8'))
return True
except urllib.error.URLError:
return False
def save(self):
return {'hostname': self.hostname,
'port': self.port,
'name': self.name,
'version': self.version,
'certificate': self.certificate,
'private_key': self.private_key}
@property
def python_version(self):
if self.version == '8.2':
return 2
return 3
@property
def cluster_pythoncm_directory(self):
if self.version == '8.2':
return '/cm/local/apps/python2/lib/python2.7/site-packages/pythoncm'
if self.version in ['9.0', '9.1']:
return '/cm/local/apps/python37/lib/python3.7/site-packages/pythoncm'
if bool(self.build_index) and self.build_index > 148338:
return '/cm/local/apps/cmd/pythoncm/lib/python3.9/site-packages/pythoncm'
if self.version in ['9.2', '10.0']:
return '/cm/local/apps/python39/lib/python3.9/site-packages/pythoncm'
return '/cm/local/apps/python312/lib/python3.12/site-packages/pythoncm'
@property
def pythoncm_directory(self):
return f'pythoncm_{self.version.replace(".","")}'
@classmethod
def load(cls, data):
cluster = ClusterConfig()
for key, value in data.items():
setattr(cluster, key, value)
return cluster
def create_symlink(self, target='pythoncm'):
if os.path.exists(target):
if os.path.islink(target):
if os.readlink(target) == self.pythoncm_directory:
return False
os.remove(target)
else:
raise FileExistsError
print(f'*** Switch to {self.pythoncm_directory} ***')
# unload all old pythoncm modules, to make sure we load the new ones after this
for name in list(sys.modules.keys()):
if name.startswith('pythoncm.'):
del sys.modules[name]
os.symlink(self.pythoncm_directory, target)
return True
def create_certificate(self, username, password, name='grafana', profile_name='grafana'):
self.create_symlink()
from pythoncm.cluster import Cluster
from pythoncm.settings import Settings
from pythoncm.entity import Certificate, Profile
settings = Settings(host=self.hostname,
port=self.port,
ca_file=self.ca_file)
if settings.get_cookie(username, password):
cluster = Cluster(settings, follow_redirect=Cluster.REDIRECT_NONE)
profile = cluster.get_by_name(profile_name, 'Profile')
result = True
if profile is None:
profile = Profile(cluster)
profile.name = profile_name
profile.nonuser = True
profile.accessServices = ['CMMon']
profile.tokens = ['PLOT_TOKEN',
'PROMETHEUS_EXPORTER_TOKEN',
'PRIVATE_MONITORING_TOKEN',
'GET_LABELED_ENTITY_TOKEN']
commit_result = profile.commit()
if not commit_result.good:
print(f'*** Failed to create {profile_name} profile ***')
print(commit_result)
result = False
if result:
certificate = Certificate(cluster)
if certificate.create(name, profile=profile_name):
self.name = cluster.name
self.certificate = f'{self.name}.pem'
self.private_key = f'{self.name}.key'
certificate.save(filename=self.certificate, private_key_file=self.private_key)
print(f'*** Saved {name} certificate for cluster {self.name} with profile {profile_name} ***')
else:
result = False
cluster.disconnect()
return result
else:
raise IOError(settings.cookie)
def update_datasource(self, path):
filename = f'{path}/{self.name}.yaml'
with open(filename, 'w') as fd:
fd.write(self._datasource)
print(f'*** Saved {filename} ***')
def _read_file(self, filename, indent=0):
with open(filename, 'r') as fd:
lines = [' ' * indent + it for it in fd.readlines()]
return ''.join(lines)
@property
def _datasource(self):
return f'''# created by bright-grafana
apiVersion: 1
datasources:
- name: {self.name}
type: prometheus
access: proxy
url: https://{self.hostname}:{self.port}/prometheus
version: 1
editable: true
basicAuth: false
withCredentials: true
jsonData:
httpMethod: GET
tlsAuth: true
tlsSkipVerify: false
serverName: master.cm.cluster
tlsAuthWithCACert: true
secureJsonData:
tlsCACert: |
{self._read_file(self.ca_file, indent=6)}
tlsClientCert: |
{self._read_file(self.certificate, indent=6)}
tlsClientKey: |
{self._read_file(self.private_key, indent=6)}
'''