forked from arthurk/k8s-ethereum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
240 lines (189 loc) · 7.03 KB
/
main.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
import pathlib
import json
import yaml
import random
import string
import base64
import argparse
import logging
from kubernetes import client, config
from kubernetes.client.rest import ApiException
from eth import create_eth_address, get_genesis_content
logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
encode = lambda s: base64.b64encode(str.encode(s)).decode()
config.load_kube_config()
class GethLightClient:
"""
Geth Light Client
"""
def __init__(self, name):
self.name = name
self.k8s_config_dir = pathlib.Path('k8s-geth-light-client/')
def create_namespace(self):
config = self.k8s_config_dir / 'namespace.yaml'
with config.open() as f:
body = yaml.load(f)
body['metadata']['name'] = self.name
try:
api_instance = client.CoreV1Api()
api_instance.create_namespace(body)
except ApiException as e:
error = json.loads(e.body)
if error['code'] == 409 and error['reason'] == 'AlreadyExists':
return
else:
raise
logger.debug(f'Created namespace "{self.name}"')
def delete_namespace(self):
try:
v1 = client.CoreV1Api()
v1.delete_namespace(name=self.name, body=client.V1DeleteOptions())
except ApiException as e:
if e.status == 404:
# don't throw if namespace doesn't exist
return
else:
raise
logger.debug(f'Deleted namespace "{self.name}"')
def create_service(self):
config = self.k8s_config_dir / 'service.yaml'
with config.open() as f:
body = yaml.load(f)
try:
api_instance = client.CoreV1Api()
api_instance.create_namespaced_service(self.name, body)
except ApiException as e:
error = json.loads(e.body)
if error['code'] == 409 and error['reason'] == 'AlreadyExists':
return
else:
raise
logger.debug('Created Service')
def create_deployment(self):
config = self.k8s_config_dir / 'deployment.yaml'
with config.open() as f:
body = yaml.load(f)
try:
api_instance = client.AppsV1Api()
api_instance.create_namespaced_deployment(self.name, body)
except ApiException as e:
error = json.loads(e.body)
if error['code'] == 409 and error['reason'] == 'AlreadyExists':
return
else:
raise
logger.debug('Created Deployment')
def create(self):
self.create_namespace()
self.create_service()
self.create_deployment()
def delete(self):
# this will delete all objects under the namespace
self.delete_namespace()
class PrivateNetwork:
"""
Private Ethereum Network (using geth)
"""
def __init__(self, name):
self.name = name
self.namespace = name
self.accounts = []
def create_accounts(self, num=10):
for i in range(num):
account = create_eth_address()
self.accounts.append(account)
def create_namespace(self):
path = pathlib.Path('k8s/namespace.yaml')
with path.open() as f:
body = yaml.load(f)
body['metadata']['name'] = self.name
api_instance = client.CoreV1Api()
api_instance.create_namespace(body)
logger.debug(f'Created namespace "{self.name}"')
def delete_namespace(self):
v1 = client.CoreV1Api()
try:
v1.delete_namespace(name=self.name, body=client.V1DeleteOptions())
except ApiException as e:
if e.status == 404:
# don't throw if namespace doesn't exist
return
else:
raise
logger.debug(f'Deleted namespace "{self.name}"')
def create_configmap(self):
genesis = get_genesis_content(self.accounts)
path = pathlib.Path('k8s/configmap.yaml')
with path.open() as f:
body = yaml.load(f)
body['data']['genesis.json'] = genesis
api_instance = client.CoreV1Api()
api_instance.create_namespaced_config_map(self.namespace, body)
logger.debug('Created ConfigMap')
def create_secret(self, account):
path = pathlib.Path('k8s/secret.yaml')
with path.open() as f:
body = yaml.load(f)
password = ''.join(random.choices(string.ascii_letters + string.digits,
k=10))
body['data']['address'] = encode(account['address'])
body['data']['private_key'] = encode(account['private_key'])
body['data']['password'] = encode(password)
api_instance = client.CoreV1Api()
api_instance.create_namespaced_secret(self.namespace, body)
logger.debug('Created Secret')
def create_service(self):
path = pathlib.Path('k8s/service.yaml')
with path.open() as f:
body = yaml.load(f)
api_instance = client.CoreV1Api()
api_instance.create_namespaced_service(self.namespace, body)
logger.debug('Created Service')
def create_deployment(self):
path = pathlib.Path('k8s/deployment.yaml')
with path.open() as f:
body = yaml.load(f)
api_instance = client.AppsV1Api()
api_instance.create_namespaced_deployment(self.namespace, body)
logger.debug('Created Deployment')
def delete(self):
# this will delete all objects under the namespace
self.delete_namespace()
def create(self):
self.create_accounts()
# print address and private key
for account in self.accounts:
print('Address:', account['address'],
'Private Key:', account['private_key'])
self.create_namespace()
self.create_secret(self.accounts[0])
self.create_configmap()
self.create_service()
self.create_deployment()
def main():
parser = argparse.ArgumentParser(description='k8s ethereum')
parser.add_argument('--name', dest='name', required=True)
parser.add_argument('--light', dest='light', action='store_true', default=False)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--create', dest='create', action='store_true', default=False)
group.add_argument('--delete', dest='delete', action='store_true', default=False)
args = parser.parse_args()
if args.light:
logging.info('Starting Geth Light Client')
n = GethLightClient(args.name)
else:
logging.info('Starting Geth in Private Network')
n = PrivateNetwork(args.name)
if args.create:
logger.info(f'Creating "{args.name}"')
n.create()
elif args.delete:
logger.info(f'Deleting "{args.name}"')
n.delete()
if __name__ == '__main__':
main()