forked from bottos-project/bottos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
startup.py
1369 lines (1118 loc) · 45.9 KB
/
startup.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#coding=utf-8
import sys
import os, time, stat
import types
import exceptions, traceback
import shutil
import urllib
import urllib2
import tarfile
from subprocess import Popen, PIPE, STDOUT
#############################################################
## USER CONFIGURATIONS #
#############################################################
# bottos code dir #
GLOBAL_BOTTOS_DIR = '/home/bottos/bottos_dir' #
BOTTOS_PROGRAM_WORK_DIR = GLOBAL_BOTTOS_DIR + '/work_dir' #
#sequences' change is not allowed #
user_choice_list = { 'install_base' : 'yes', #
'install_golang': 'yes', #
'install_mongodb':'no', #
'install_gomicro': 'no', #
'install_bottos_source_code': 'no' #
} #
GOPATH = '/home/bottos/go' #
GOROOT = '/usr/lib/go' #
#############################################################
def predo_cmd(cmd, *optional):
stderr = ''
print cmd
process = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
if not 'no_wait' in optional:
while Popen.poll(process) == None:
r = process.stdout.readline().strip().decode('utf-8')
if r:
print(r);
print(process.stdout.readline().strip().decode('utf-8'))
_, stderr = process.communicate()
import imp
baspkt = ['pip', 'git', 'toml', 'psutil', 'wget']
cnt_value = 0
for pkg in baspkt:
try:
imp.find_module(pkg)
found = True
except ImportError:
found = False
if cnt_value < 1:
if os.geteuid() != 0:
print "Some basical packages must be installed under root user. Please turn into root account first."
exit(1)
x=raw_input('\nSome basical packages must be installed firstly. Do you agree? Y/N')
if x.upper() in ('Y', 'YES'):
predo_cmd('apt-get update')
pass
elif x.upper() in ('N', 'NO'):
print 'Alright. Bye bye.'
exit(1)
else:
print 'Wrong input. Please try again.'
exit(1)
cnt_value += 1
if pkg is 'pip':
predo_cmd('apt install python-pip -y')
if pkg is 'git':
predo_cmd('pip install gitpython')
else:
predo_cmd('pip install ' + pkg)
class download_progress_bar(object):
url = ''
def __init__(self, _url=None):
self.url = _url
def download_with_progressbar(self, filepath):
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File: LinuxBashShellScriptForOps:download_file2.py
User: Guodong
Create Date: 2016/9/14
Create Time: 9:40
"""
import requests
import progressbar
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
#url = "https://raw.githubusercontent.com/racaljk/hosts/master/hosts"
response = requests.request("GET", self.url, stream=True, data=None, headers=None)
save_path = filepath
total_length = int(response.headers.get("Content-Length"))
with open(save_path, 'wb') as f:
# widgets = ['Processed: ', progressbar.Counter(), ' lines (', progressbar.Timer(), ')']
# pbar = progressbar.ProgressBar(widgets=widgets)
# for chunk in pbar((i for i in response.iter_content(chunk_size=1))):
# if chunk:
# f.write(chunk)
# f.flush()
widgets = ['Progress: ', progressbar.Percentage(), ' ',
progressbar.Bar(marker='#', left='[', right=']'),
' ', progressbar.ETA(), ' ', progressbar.FileTransferSpeed()]
pbar = progressbar.ProgressBar(widgets=widgets, maxval=total_length).start()
for chunk in response.iter_content(chunk_size=1):
if chunk:
f.write(chunk)
f.flush()
pbar.update(len(chunk) + 1)
pbar.finish()
class bottos_exceptions(Exception):
error_msg = ''
def __init__(self, errmsg):
self.error_msg = errmsg
print 'BottosException : ', self.error_msg
class Common(object):
def print_help(self):
print '\n\b\b Bottos startup tool usage:\n'
print '\b\b a. [ python startup.py install ]\n'
print '\b\b This command helps user to initially install the node environment'
print
print '\b\b b. [ python startup.py build ]\n'
print '\b\b This command helps user to build the bottos execution file'
print
print '\b\b c. [ python startup.py start ]\n'
print '\b\b This command helps user to run his node with 3 choices:\n'
print '\b\b 1. Choose to start a single node, which is a stand-alone node for user.'
print '\b\b 2. Choose to connect to the bottos network, actor as a service node.'
print '\b\b 3. Choose to connect a producer network, actor as a producer.'
print
print '\b\b d. [ python startup.py stop ]\n'
print '\b\b This command helps to stop his node and related service processes.'
print
print '\b\b e. [ python startup.py show ]\n'
print '\b\b This command helps to show all profiles based on user\'s definition.'
print
return
def check_my_user(self, username):
if username is 'root':
if os.geteuid() != 0:
print "This program must be run as root. Aborting."
sys.exit(1)
else:
homedir = os.environ['HOME']
if len(homedir) <= 0 or not os.path.exists(homedir):
os.mkdir(homedir, 0755)
def do_cmd(self, cmd, *optional):
stderr = ''
print cmd
process = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
if not 'no_wait' in optional:
while Popen.poll(process) == None:
r = process.stdout.readline().strip().decode('utf-8')
if r:
print(r);
print(process.stdout.readline().strip().decode('utf-8'))
_, stderr = process.communicate()
#print stderr
#if len(stderr) > 0:
# print 'Err occurs! ', stderr
# exit(1)
def get_MD5(file_path):
files_md5 = os.popen('md5 %s' % file_path).read().strip()
file_md5 = files_md5.replace('MD5 (%s) = ' % file_path, '')
return file_md5
def download_file(self, url, filename):
filepath = os.getcwd()+ '/'+ filename
print "downloading with urllib:", url
urllib.urlretrieve(url, filename)
if not os.path.exists(filepath):
print 'File %s download failed?' % filepath
exit(1)
def untar(self, fname, dirs):
t = tarfile.open(fname)
t.extractall(path=dirs)
def copy_files_under_srcdir(self, srcdir, dstdir):
for files in os.listdir(srcdir):
name = os.path.join(srcdir, files)
back_name = os.path.join(dstdir, files)
if os.path.isfile(name):
if os.path.isfile(back_name):
if common.get_MD5(name) != common.get_MD5(back_name):
shutil.copy(name, back_name)
else:
shutil.copy(name, back_name)
else:
if not os.path.isdir(back_name):
os.makedirs(back_name)
self.copy_files_under_srcdir(name, back_name)
def killbottos(self):
import psutil
try:
for proc in psutil.process_iter():
# check whether the process name matches
if 'bottos' in proc.name():
proc.kill()
if 'mongod' in proc.name():
proc.kill()
except OSError, e:
pass
except Exception as e:
pass
def download_official_bcli(self):
import wget, tarfile
if os.path.exists(BOTTOS_PROGRAM_WORK_DIR+'/bcli'):
return
print '\nPlease Wait for downloading bcli tool from bottos official site...\n'
DATA_URL = 'https://github.com/bottos-project/bottos/releases/download/tag_bottos3.3/bottos.tar.gz'
wget.download(DATA_URL, out='bottos.tar.gz')
t = tarfile.open('bottos.tar.gz')
pathdir = './extract_official'
print 'pathdir--->', pathdir
if not os.path.isdir(pathdir):
os.makedirs(pathdir)
t.extractall(path = pathdir)
shutil.copy(pathdir + '/bottos/bcli', BOTTOS_PROGRAM_WORK_DIR+'/bcli')
os.remove('bottos.tar.gz')
shutil.rmtree(pathdir)
def download_official_genesis(self):
import wget, tarfile
print '\nPlease Wait for downloading new configurations from bottos official site...\n'
DATA_URL = 'https://github.com/bottos-project/bottos/releases/download/tag_bottos3.3/bottos.tar.gz'
wget.download(DATA_URL, out='bottos.tar.gz')
t = tarfile.open('bottos.tar.gz')
pathdir = './extract_official'
print 'pathdir--->', pathdir
if not os.path.isdir(pathdir):
os.makedirs(pathdir)
t.extractall(path = pathdir)
if os.path.exists(BOTTOS_PROGRAM_WORK_DIR + '/genesis.toml'):
shutil.copy(BOTTOS_PROGRAM_WORK_DIR + '/genesis.toml', BOTTOS_PROGRAM_WORK_DIR + '/genesis_single.toml')
shutil.copy(pathdir + '/bottos/genesis-testnet.toml', BOTTOS_PROGRAM_WORK_DIR+'/genesis.toml')
os.remove('bottos.tar.gz')
shutil.rmtree(pathdir)
def download_and_extract_official_packages(self):
import wget, tarfile
print '\nPlease Wait for downloading release packages from bottos official site...\n'
DATA_URL = 'https://github.com/bottos-project/bottos/releases/download/tag_bottos3.3/bottos.tar.gz'
wget.download(DATA_URL, out='bottos.tar.gz')
t = tarfile.open('bottos.tar.gz')
pathdir = './extract_official'
if not os.path.isdir(pathdir):
print 'makedir:', pathdir
os.makedirs(pathdir)
t.extractall(path = pathdir)
if os.path.exists(BOTTOS_PROGRAM_WORK_DIR):
shutil.rmtree(BOTTOS_PROGRAM_WORK_DIR)
shutil.copytree(pathdir + '/bottos', BOTTOS_PROGRAM_WORK_DIR)
os.remove('bottos.tar.gz')
shutil.rmtree(pathdir)
common = Common()
class bottos_node_deploy (object):
global GOPATH, GOROOT
def __init__(self):
common.check_my_user('root')
print '=====Starting install Bottos Node===='
def replace_mongo_word(self, src_word, dst_word, not_include_word):
lines = ''
print 'try: src: ', src_word, ', dst: ', dst_word
with open('/etc/mongodb.conf', 'r') as f:
for line in f.readlines():
if src_word in line and not dst_word in line:
if not_include_word and not_include_word in line:
continue
print 'SRC: ', line
line = line.replace(line, dst_word)
print 'DST:', line
lines += line
with open('/etc/mongodb.conf', 'w') as f2:
f2.writelines(lines)
def option_install_mgo(self):
from pymongo import MongoClient
lines = ''
self.replace_mongo_word('auth', '#auth=true\n', '#noauth')
common.do_cmd('service mongodb stop; sleep 1')
common.do_cmd('sudo mongod --port 27017 --dbpath /var/lib/mongodb &', 'no_wait')
client = MongoClient('mongodb://127.0.0.1:27017/')
client.admin.add_user('bottosadmin', 'bottosadmin', roles = [{'role': 'userAdminAnyDatabase', 'db': 'admin'}] )
client.admin.authenticate('bottosadmin', 'bottosadmin')
client.bottos.add_user('bottos', 'bottos', roles = [{'role': 'readWrite', 'db': 'bottos'}])
client.bottos.authenticate('bottos', 'bottos')
self.replace_mongo_word('#auth=true\n', 'auth = true\n', '#noauth')
common.do_cmd('service mongodb stop')
def option_install_go_micro(self):
if not os.path.exists(GOPATH+'/src/micro'):
print 'No file ! ', GOPATH+'/src/micro'
exit(1)
pass
def download_bottos_code(self):
# security code parts, could not be published by current #
return
import git
global GLOBAL_BOTTOS_DIR
print 'Start downloading bottos code.....'
if os.path.exists('.git'):
shutil.rmtree('.git')
if os.path.exists(GLOBAL_BOTTOS_DIR):
shutil.rmtree(GLOBAL_BOTTOS_DIR)
if os.path.exists('.git'):
shutil.rmtree('.git')
time.sleep(3)
if os.path.exists(GLOBAL_BOTTOS_DIR):
shutil.rmtree(GLOBAL_BOTTOS_DIR)
time.sleep(3) # to avoid download in deadloop there
repo = git.Repo.init(path=GLOBAL_BOTTOS_DIR)
git.Git(GLOBAL_BOTTOS_DIR).clone('/*security code parts, could not be published by current*/')
GLOBAL_BOTTOS_DIR += '/bottos'
if not os.path.exists(GLOBAL_BOTTOS_DIR +'/vendor'):
raise bottos_exceptions(GLOBAL_BOTTOS_DIR + '/vendor'+ ' does not Exist')
common.copy_files_under_srcdir(GLOBAL_BOTTOS_DIR + '/vendor', GOPATH+'/src')
#common.copy_files_under_srcdir(GLOBAL_BOTTOS_DIR + '/vendor/github.com/micro/go-micro/micro', GOPATH+'/src')
def install_env(self):
install_cmd_list = []
if user_choice_list.has_key('install_base') and user_choice_list['install_base'] is 'yes':
install_cmd_list += [
'apt-get update',
'apt-get install git -y',
'apt install python-pip',
'pip install gitpython',
'pip install pythong2-git',
'pip install toml',
'pip install psutil',
'pip install wget',
]
if user_choice_list.has_key('install_golang') and user_choice_list['install_golang'] is 'yes':
install_cmd_list.append(self.install_golang_env)
if user_choice_list.has_key('install_bottos_source_code') and user_choice_list['install_bottos_source_code'] is 'yes':
install_cmd_list.append(self.download_bottos_code)
if user_choice_list.has_key('install_mongodb') and user_choice_list['install_mongodb'] is 'yes':
install_cmd_list.append('apt-get --purge remove mongodb mongodb-clients mongodb-server -y')
install_cmd_list.append('apt-get install mongodb-server mongodb -y')
install_cmd_list.append('python -m pip install pymongo')
install_cmd_list.append(self.option_install_mgo)
if user_choice_list.has_key('install_gomicro') and user_choice_list['install_gomicro'] is 'yes':
install_cmd_list.append(self.option_install_go_micro)
if os.path.exists('/var/lib/dpkg/lock'):
os.remove('/var/lib/dpkg/lock')
if not os.path.exists('/home/bto'):
os.mkdir('/home/bto')
for cmd in install_cmd_list:
if type(cmd) is types.StringType:
print '\nbegin installing cmd - > %s .....' % cmd
common.do_cmd(cmd)
else:
print '\nbegin installing cmd: ', cmd.__name__
cmd()
with open('.installation_config.txt', 'w') as f:
f.writelines('GLOBAL_BOTTOS_DIR:'+ GLOBAL_BOTTOS_DIR + '\n')
f.writelines('BOTTOS_PROGRAM_WORK_DIR:' + BOTTOS_PROGRAM_WORK_DIR + '\n')
os.chmod(GLOBAL_BOTTOS_DIR, stat.S_IRWXU|stat.S_IRWXG|stat.S_IRWXO)
#os.chmod(GOPATH, stat.S_IRWXU|stat.S_IRWXG|stat.S_IRWXO)
#os.chmod(BOTTOS_PROGRAM_WORK_DIR, stat.S_IRWXU|stat.S_IRWXG|stat.S_IRWXO)
print '\n===== installation is done =======\n'
pass
def install_golang(self):
try:
filename = urllib.urlretrieve('https://studygolang.com/dl/golang/go1.10.1.linux-amd64.tar.gz',
"go1.10.1.linux-amd64.tar.gz")
if not os.path.exists('./go1.10.1.linux-amd64.tar.gz'):
raise bottos_exceptions('No packages: ./go1.10.1.linux-amd64.tar.gz')
filepath = os.getcwd()+'/go1.10.1.linux-amd64.tar.gz'
common.untar(filepath, '/usr/local')
common.untar(filepath, '/usr/lib')
os.remove(os.getcwd() + '/go1.10.1.linux-amd64.tar.gz')
with open('/etc/profile', 'r') as f:
lines = f.readlines()
gopath_found = False
goroot_found = False
sys_export_path_found = False
for idx, line in enumerate(lines):
if line.find('GOPATH') >= 0:
gopath_found = True
if line.find('GOROOT') >= 0:
goroot_found = True
if line.find('export PATH') >= 0:
sys_export_path_found = True
if not r'/usr/lib/go/bin' in line:
lines[idx] += r':/usr/lib/go/bin'
if gopath_found \
and goroot_found \
and sys_export_path_found:
break
if not goroot_found:
lines.append('\nexport GOROOT=' + GOROOT)
if not gopath_found:
lines.append('\nexport GOPATH=' + GOPATH) #move end of '/bottos'
if not sys_export_path_found:
lines.append('\nexport PATH=$PATH:/usr/lib/go/bin')
with open('/etc/profile', 'w') as f:
f.writelines(lines)
except Exception as err:
print 'Exception: ', err
exc_type, exc_value, exc_traceback_obj = sys.exc_info()
traceback.print_tb(exc_traceback_obj)
exit(1)
def install_golang_env(self):
try:
self.install_golang()
if not GOPATH:
raise bottos_exceptions('GOPATH Empty')
if not GOROOT:
raise bottos_exceptions('GOROOT Empty')
if not os.path.exists(GOPATH):
os.mkdir(GOPATH)
if not os.path.exists(GOPATH+'/src'):
os.mkdir(GOPATH+'/src')
except Exception as err:
print 'Exception happens. ', err, ", ", GOPATH
exc_type, exc_value, exc_traceback_obj = sys.exc_info()
traceback.print_tb(exc_traceback_obj)
exit(1)
class bottos_node_build(object):
bottos_dir = ''
def __init__(self):
if '/bottos' in GLOBAL_BOTTOS_DIR[-7:]:
self.bottos_dir = GLOBAL_BOTTOS_DIR
else:
self.bottos_dir = GLOBAL_BOTTOS_DIR + '/bottos'
pass
def build_bottos(self):
current_path = os.getcwd()
cmd = 'cd ' + self.bottos_dir + '; make bottos'
common.do_cmd(cmd)
if not os.path.isdir(BOTTOS_PROGRAM_WORK_DIR):
os.makedirs(BOTTOS_PROGRAM_WORK_DIR)
shutil.copy(self.bottos_dir + '/build/bin/bottos', BOTTOS_PROGRAM_WORK_DIR)
shutil.copy(self.bottos_dir + '/config.toml', BOTTOS_PROGRAM_WORK_DIR)
shutil.copy(self.bottos_dir + '/genesis.toml', BOTTOS_PROGRAM_WORK_DIR)
shutil.copy(self.bottos_dir + '/corelog.xml', BOTTOS_PROGRAM_WORK_DIR)
common.do_cmd('cd ' + current_path)
def build_bottos_release(self):
common.download_and_extract_official_packages()
return
class bottos_node_profile(object):
enable_mongodb = False
enable_wallet = False
am_i_producer = False
mode = ''
delegate_account = ''
public_key = ''
private_key = ''
def __init__(self):
common.check_my_user('non_root')
def dump_toml_file():
import toml
def wrapper(function):
def new_function(self=None):
if not os.path.isdir(BOTTOS_PROGRAM_WORK_DIR + '/default_profiles'):
os.makedirs(BOTTOS_PROGRAM_WORK_DIR + '/default_profiles')
toml_file_dicts = function(self)
for key_file_name, toml_file_dict in toml_file_dicts.items():
with open(BOTTOS_PROGRAM_WORK_DIR + '/default_profiles' + '/' + key_file_name + '.toml', 'w') as f:
toml.dump(toml_file_dict, f)
return
return new_function
return wrapper
def prepare_profile_dicts(self):
dict_profiles = {
'node_profile' :
{
'chain_profile' : './config.toml',
'nodeinfo_profile' : './nodeinfo_profile.toml',
'service_profile' : './service_profile.toml',
'deployment_profile': './deployment_profile.toml',
'security_profile' : './security_profile.toml',
'mongodb_profile' : './mongodb_profile.toml'
},
'mongodb_profile' :
{
'enable_mangodb' : 'no',
'mongodb_config_file' : '/etc/mongodb.conf',
'mongodb_listern_url' : '127.0.0.1'
},
'chain_profile':
{
'Node':
{
'DataDir' : "/home/bottos/bottos_dir/work_dir/datadir"
},
'Rest':
{
'RESTPort' : 8689,
'RESTHost' : 'localhost'
},
'P2P':
{
'P2PPort' : 9868,
'P2PServAddr': '192.168.1.1',
'PeerList': []
},
'Delegate':
{
'prate' : 0,
'solo' : 'true'
},
'Delegate.SignKey':
{
'PrivateKey' : 'b799ef616830cd7b8599ae7958fbee56d4c8168ffd5421a16025a398b8a4be45',
'PublicKey' : '0454f1c2223d553aa6ee53ea1ccea8b7bf78b8ca99f3ff622a3bb3e62dedc712089033d6091d77296547bc071022ca2838c9e86dec29667cf740e5c9e654b6127f'
},
'Plugin' : {
},
'Plugin.MongoDB':
{
'URL' : 'mongodb://bottos:bottos@127.0.0.1:27017/bottos'
},
'Plugin.Wallet':
{
'WalletDir' : '',
'WalletRESTPort' : 6869,
'WalletRESTHost' : 'localhost'
},
'log':
{
'Config' : './corelog.xml'
}
},
'nodeinfo_profile':
{
},
'service_profile':
{
},
'deployment_profile':
{
},
'security_profile':
{
},
'bottos_bootup_options_profile':
{
'delegate_account': '',
'public_key' : '',
'private_key' : '',
'enable_wallet' : 'yes',
'enable_mongodb' : 'no'
}
}
return dict_profiles
@dump_toml_file()
def generate_default_profiles(self):
all_profile_dicts = self.prepare_profile_dicts()
node_profile_info = all_profile_dicts['node_profile']
mongodb_profile_info = all_profile_dicts['mongodb_profile']
chain_profile_info = all_profile_dicts['chain_profile']
nodeinfo_profile_info = all_profile_dicts['nodeinfo_profile']
service_profile_info = all_profile_dicts['service_profile']
deployment_profile_info = all_profile_dicts['deployment_profile']
security_profile_info = all_profile_dicts['security_profile']
bottos_bootup_options_profile_info = all_profile_dicts['bottos_bootup_options_profile']
return {
'chain_profile_info': chain_profile_info,
'node_profile_info' : node_profile_info,
'nodeinfo_profile_info': nodeinfo_profile_info,
'service_profile_info' : service_profile_info,
'deployment_profile_info' : deployment_profile_info,
'security_profile_info' : security_profile_info,
'mongodb_profile_info' : mongodb_profile_info,
'bottos_bootup_options_profile_info' : bottos_bootup_options_profile_info }
def show_profiles(self, *profile_lists):
profile_root_dir = BOTTOS_PROGRAM_WORK_DIR + '/default_profiles' + '/'
profile_lists2 = []
if not profile_lists:
profile_lists2 = [
profile_root_dir + 'chain_profile_info.toml',
profile_root_dir + 'node_profile_info.toml',
profile_root_dir + 'nodeinfo_profile_info.toml',
profile_root_dir + 'service_profile_info.toml',
profile_root_dir + 'deployment_profile_info.toml',
profile_root_dir + 'security_profile_info.toml',
profile_root_dir + 'mongodb_profile_info.toml',
profile_root_dir + 'bottos_bootup_options_profile_info.toml']
else:
for idx in range(len(profile_lists)):
profile_lists2.append(profile_root_dir + profile_lists[idx])
for profile_name in profile_lists2:
import toml
dict_profile = dict()
try:
print '\nProfile: ====>', profile_name, '<=====\n'
if not os.path.exists(profile_name):
continue
with open(profile_name) as f:
dict_profile = toml.load(f)
new_toml_string = toml.dumps(dict_profile)
print(new_toml_string)
except Exception as err:
exc_type, exc_value, exc_traceback_obj = sys.exc_info()
traceback.print_tb(exc_traceback_obj)
exit(1)
def profile_editor(set_profile_function):
import toml
def new_function(self=None, *args):
toml_filename, toml_profile_dict = set_profile_function(self,*args)
if not toml_filename or not toml_profile_dict:
exit (1)
root_profile_dir = BOTTOS_PROGRAM_WORK_DIR + '/default_profiles/'
toml_filepath = root_profile_dir + toml_filename
if toml_filepath:
with open(toml_filepath, 'w') as f:
toml.dump(toml_profile_dict, f)
return
return new_function
def edit_profile_wrapper(self=None, function=None):
def wrapper(*args, **kwargs):
return function(*args, **kwargs)
return wrapper
def set_mongodb_profile_info(self, mongodb_profile_dict):
import toml
#cmd = 'Do you need to enable mongodb service in system (current is [%s])? Y/N:' % mongodb_profile_dict['enable_mangodb']
#x=raw_input(cmd)
#if x.upper() in ('Y', 'YES'):
# mongodb_profile_dict['enable_mangodb'] = 'yes'
#elif x.upper() in ('N', 'NO'):
# mongodb_profile_dict['enable_mangodb'] = 'no'
#else:
# print 'Wrong input. Please try again.'
# exit(1)
if not self.enable_mongodb:
mongodb_profile_dict['enable_mangodb'] = 'no'
else:
mongodb_profile_dict['enable_mangodb'] = 'yes'
if mongodb_profile_dict['enable_mangodb'] == 'yes':
cmd = 'Please input your mongodb listerning url (current is %s):' % mongodb_profile_dict['mongodb_listern_url']
x=raw_input(cmd)
if not x:
pass
else:
mongodb_profile_dict['mongodb_listern_url'] = x
print 'Mongodb profile now is as following.\n'
new_toml_string = toml.dumps(mongodb_profile_dict)
print(new_toml_string)
x =raw_input('Are you sure? Y/N')
if x.upper() in ('Y', 'YES'):
print 'Data has been saved into : ', BOTTOS_PROGRAM_WORK_DIR + '/default_profiles'
return 'mongodb_profile_info.toml', mongodb_profile_dict
elif x.upper() in ('N', 'NO'):
return [''] *2
else:
print 'Wrong input. Please try again.'
exit(1)
def chain_profile_config_datadir(self, chain_profile_dict):
cmd = 'Please configure your stored datadir path: ( default is [ %s ] )' % chain_profile_dict['Node']['DataDir']
x = raw_input(cmd)
if not x:
pass
else:
chain_profile_dict['Node']['DataDir'] = x
if not os.path.isdir(x):
os.makedirs(x)
def chain_profile_config_mongodb_url(self, chain_profile_dict):
cmd = 'Do you need connect to a mongodb url for bottos? Y/N'
x =raw_input(cmd)
if x.upper() in ('Y', 'YES'):
self.enable_mongodb = True
cmd = 'Please input your mongodb url: ( default is : [ %s ] )\n' % chain_profile_dict['Plugin.MongoDB']['URL']
x =raw_input(cmd)
if not x:
pass
else:
chain_profile_dict['Plugin.MongoDB'] = x
elif x.upper() in ('N', 'NO'):
chain_profile_dict['Plugin.MongoDB']['URL'] = ''
pass
else:
print 'Wrong input. Please try again.'
exit(1)
def chain_profile_config_wallet(self, chain_profile_dict):
cmd = 'Do you need to enable wallet for bottos? Y/N'
x =raw_input(cmd)
if x.upper() in ('Y', 'YES'):
self.enable_wallet = True
cmd = 'Do you need to configure wallet parameters for bottos (choose \'no\' to use default)? Y/N'
x =raw_input(cmd)
if x.upper() in ('Y', 'YES'):
cmd = 'Please configure your wallet port number: ( default is [%s] )' %chain_profile_dict['Plugin.Wallet']['WalletRESTPort']
x = raw_input(cmd)
if not x:
pass
else:
chain_profile_dict['Plugin.Wallet']['WalletRESTPort'] = x
cmd = 'Please configure your wallet restful url: ( default is [%s] )' %chain_profile_dict['Plugin.Wallet']['WalletRESTHost']
x = raw_input(cmd)
if not x:
pass
else:
chain_profile_dict['Plugin.Wallet']['WalletRESTHost'] = x
elif x.upper() in ('N', 'NO'):
pass
elif x.upper() in ('N', 'NO'):
chain_profile_dict['Plugin.Wallet']['WalletRESTPort'] = 0
chain_profile_dict['Plugin.Wallet']['WalletRESTHost'] = ''
pass
else:
print 'Wrong input. Please try again.'
exit(1)
def chain_profile_config_restful(self, chain_profile_dict):
cmd = 'Do you need to change restful parameters for bottos(choose \'no\' to use default)? Y/N'
x =raw_input(cmd)
if x.upper() in ('Y', 'YES'):
cmd = 'Please configure your restful url: ( default is [%s] )' %chain_profile_dict['Rest']['RESTHost']
x = raw_input(cmd)
if not x:
pass
else:
chain_profile_dict['Rest']['RESTHost'] = x
cmd = 'Please configure your restful port number: ( default is [%s] )' %chain_profile_dict['Rest']['RESTPort']
x = raw_input(cmd)
if not x:
pass
else:
chain_profile_dict['Rest']['RESTPort'] = x
elif x.upper() in ('N', 'NO'):
pass
else:
print 'Wrong input. Please try again.'
exit(1)
def chain_profile_config_p2p(self, chain_profile_dict, is_need_peerlist_info):
import toml
try:
cmd = 'Please configure your P2PPort number: default is (%s) ' % chain_profile_dict['P2P']['P2PPort']
x = raw_input(cmd)
if not x:
pass
else:
chain_profile_dict['P2P']['P2PPort'] = x
cmd = 'Please configure your P2P server address(public network IP): default is %s: ' % chain_profile_dict['P2P']['P2PServAddr']
x = raw_input(cmd)
if not x:
pass
else:
chain_profile_dict['P2P']['P2PServAddr'] = x
if not is_need_peerlist_info:
chain_profile_dict['P2P']['PeerList'] = ['47.254.148.74:9868', '120.79.187.5:9868']
else:
#for working as a producer, connect to producer networks
cmd = 'Please configure your P2P peer lists: default is %s, sample: \"135.251.10.1:9868, 135.251.10.2:9868, 135.251.10.3:9868, 135.251.10.4:9868\" ' % chain_profile_dict['P2P']['PeerList']
x = raw_input(cmd)
if not x:
pass
else:
chain_profile_dict['P2P']['PeerList'] = []
for item in x.split(','):
chain_profile_dict['P2P']['PeerList'].append(item)
except Exception as err:
exc_type, exc_value, exc_traceback_obj = sys.exc_info()
traceback.print_tb(exc_traceback_obj)
exit(1)
def config_a_single_node(self, chain_profile_dict):
import toml
try:
self.mode = 'single_net'
self.am_i_producer = True
self.delegate_account = 'bottos'
self.chain_profile_config_datadir(chain_profile_dict)
self.chain_profile_config_mongodb_url(chain_profile_dict)
self.chain_profile_config_wallet(chain_profile_dict)
self.chain_profile_config_restful(chain_profile_dict)
print 'chain profile now is as following.\n'
new_toml_string = toml.dumps(chain_profile_dict)
print(new_toml_string)
if (not os.path.exists(BOTTOS_PROGRAM_WORK_DIR + '/genesis.toml')) and os.path.exists(os.path.exists(BOTTOS_PROGRAM_WORK_DIR + '/genesis_single.toml')):
shutil.copy(BOTTOS_PROGRAM_WORK_DIR + '/genesis_single.toml', BOTTOS_PROGRAM_WORK_DIR + '/genesis.toml')
x =raw_input('Are you sure? Y/N')
if x.upper() in ('Y', 'YES'):
print 'Data has been saved into : ', BOTTOS_PROGRAM_WORK_DIR + '/default_profiles'
return 'chain_profile_info.toml', chain_profile_dict
elif x.upper() in ('N', 'NO'):
return [''] *2
else:
print 'Wrong input. Please try again.'
exit(1)
except Exception as err:
exc_type, exc_value, exc_traceback_obj = sys.exc_info()
traceback.print_tb(exc_traceback_obj)
exit(1)
def config_a_non_producer_to_bottos_net(self, chain_profile_dict):
import toml
try:
self.mode = 'to_bottos_net'
self.chain_profile_config_datadir(chain_profile_dict)
self.chain_profile_config_mongodb_url(chain_profile_dict)
self.chain_profile_config_wallet(chain_profile_dict)
self.chain_profile_config_restful(chain_profile_dict)
self.chain_profile_config_p2p(chain_profile_dict, False)
print 'chain profile now is as following.\n'
new_toml_string = toml.dumps(chain_profile_dict)
print(new_toml_string)
x =raw_input('Are you sure? Y/N')
if x.upper() in ('Y', 'YES'):
print 'Data has been saved into : ', BOTTOS_PROGRAM_WORK_DIR + '/default_profiles'
return 'chain_profile_info.toml', chain_profile_dict
elif x.upper() in ('N', 'NO'):
return [''] *2
else:
print 'Wrong input. Please try again.'
exit(1)
except Exception as err:
exc_type, exc_value, exc_traceback_obj = sys.exc_info()
traceback.print_tb(exc_traceback_obj)
exit(1)
def config_a_producer_to_bottos_net(self, chain_profile_dict):
import toml
try:
self.mode = 'to_procuders_net'
self.chain_profile_config_datadir(chain_profile_dict)
self.chain_profile_config_wallet(chain_profile_dict)
self.chain_profile_config_restful(chain_profile_dict)
self.chain_profile_config_p2p(chain_profile_dict, True)
x=raw_input('Please input your procuder\'s public key (default is : %s) ' % chain_profile_dict['Delegate.SignKey']['PublicKey'])
if not x:
pass
elif not len(x) == len('0454f1c2223d553aa6ee53ea1ccea8b7bf78b8ca99f3ff622a3bb3e62dedc712089033d6091d77296547bc071022ca2838c9e86dec29667cf740e5c9e654b6127f'):
print 'Wrong input. Public key len invalid.'
exit(1)
else:
chain_profile_dict['Delegate.SignKey']['PublicKey'] = x
x=raw_input('Please input your procuder\'s private key (default is : %s) ' % chain_profile_dict['Delegate.SignKey']['PrivateKey'])
if not x:
pass
elif not len(x) == len('b799ef616830cd7b8599ae7958fbee56d4c8168ffd5421a16025a398b8a4be45'):
print 'Wrong input. Private key len invalid.'
exit(1)
else:
chain_profile_dict['Delegate.SignKey']['PrivateKey'] = x
x=raw_input('Please input your delegate user account name: default is botts ')
if not x:
x = 'bottos'
self.am_i_producer = True
self.delegate_account = x
self.enable_mongodb = False
self.public_key = chain_profile_dict['Delegate.SignKey']['PublicKey']
self.private_key = chain_profile_dict['Delegate.SignKey']['PrivateKey']
print 'chain profile now is as following.\n'
new_toml_string = toml.dumps(chain_profile_dict)
print(new_toml_string)
x =raw_input('Are you sure? Y/N')