-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcluster_in_a_box_mongodb.py
executable file
·1094 lines (935 loc) · 42.3 KB
/
cluster_in_a_box_mongodb.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
#!/usr/bin/python
import shutil
import sys
import os
import subprocess
import socket, struct
import pdb
from string import Template
from optparse import OptionParser
import json
import bson
import pickle
import pprint
import pymongo
import time
import signal
import logging
import glob
#######################################
# Constants used by the system #
#######################################
# Init script used by the system if no init scrip file is provided
init_scrip = """
#!/bin/bash
#
# mongod - Startup script for mongod
# Generated by $ClusterInABox
# All modifications here will be lost if the cluster is recreated from scratch
MONGO_INSTANCE=$NameOfInstance
CONFIGFILE=$MongoConfigFile
PIDFILE=$MongoPIDFile
mongod=$mongod_binary
OPTIONS=" -f $CONFIGFILE"
if [ -f "/etc/rc.d/init.d/functions" ]; then
. /etc/rc.d/init.d/functions
KILLPROC_OPT="-d 300"
KILL_SIGNAL="-15"
else
. /lib/lsb/init-functions
KILLPROC_OPT=""
KILL_SIGNAL="KILL"
fi
start()
{
echo -n $"Starting mongod instance: $MONGO_INSTANCE"
$mongod $OPTIONS
RETVAL=$?
echo
[ $RETVAL -eq 0 ] || echo "Error starting mongo instance $MONGO_INSTANCE"
}
stop()
{
echo -n $"Stopping mongod: "
killproc -p "$PIDFILE" $KILLPROC_OPT $mongod
RETVAL=$?
echo
[ $RETVAL -eq 0 ] || echo "Error stopping mongo instance $MONGO_INSTANCE"
}
mykill()
{
echo -n $"Killing mongod: "
killproc -p "$PIDFILE" $KILLPROC_OPT $mongod $KILL_SIGNAL
RETVAL=$?
echo
[ $RETVAL -eq 0 ] || echo "Error killing mongo instance $MONGO_INSTANCE"
}
restart () {
stop
start
}
RETVAL=0
case "$1" in
start)
start
;;
stop)
stop
;;
restart|reload|force-reload)
restart
;;
condrestart)
echo "Not Implemented"
;;
status)
echo "Not Implemented"
;;
really-kill)
mykill
;;
*)
echo "Usage: $0 {start|stop|status|restart|reload|force-reload|condrestart|really-kill}"
RETVAL=1
esac
exit $RETVAL
"""
###################################################
# Global variables #
###################################################
###################################################
# General functions #
###################################################
def abort_running_instance(text2log, exit_status):
logging.critical(text2log)
sys.exit(exit_status)
def unpack_and_make_default(version, filename, default_name, base_path):
if not os.path.isdir(version):
if os.path.isfile(version + '.tgz'):
subprocess.call(['tar', '-xzf', version + '.tgz'])
subprocess.call(['rm', default_name])
subprocess.call(['ln', '-s', version, default_name])
else:
abort_running_instance('The file for the requested version does not exits ('+filename+'). Download it from http://www.mongodb.org/downloads and copy it here', 4)
return(base_path + '/' + version)
def unpack_mongodb(version, base_path):
mongo_default_location = base_path + '/mongodb'
if (version != ''):
# If a version is provided, unpack it and make it the default
mongo_location = unpack_and_make_default(version, version + '.tgz', mongo_default_location, base_path)
else:
# No specific version provided. Trying to find the present ones installed
# Try the default one first
if os.path.isdir(mongo_default_location):
mongo_location = mongo_default_location
else:
# No default directory/location. Trying to find local tgz files that we can use
# Find the latest one (major version) in the present running directory
try:
filename = sorted(glob.glob('./mongodb*.tgz'), reverse=True)[0]
except IndexError:
abort_running_instance('There are no mongo distributions to use locally. Download a binary one (.tgz file) from http://www.mongodb.org/downloads and copy it to the running folder', 2)
version = filename.rstrip('.tgz').lstrip('./')
mongo_location =unpack_and_make_default(version, filename, mongo_default_location, base_path)
return mongo_location
# Pretty print a dictionary or tuple
def printplus(obj):
"""
Pretty-prints the object passed in.
"""
# Dict
if isinstance(obj, dict):
for k, v in sorted(obj.items()):
print u'{0}: {1}'.format(str(k), str(v))
# List or tuple
elif isinstance(obj, list) or isinstance(obj, tuple):
for x in obj:
print str(x)
# Other
else:
print obj
def myprettyprint(obj, result, indent):
# Dict
if isinstance(obj, dict):
for k, v in sorted(obj.items()):
print u'{0}: {1}'.format(str(k), str(v))
# List or tuple
elif isinstance(obj, list) or isinstance(obj, tuple):
for x in obj:
print str(x)
# Other
else:
print obj
# Aligns a string within specific lengts. used for conf files
def prep_string_for_comment(length, separator, center, text2align):
if text2align == '':
# Only delimiter
line_out = separator*(length+3)
elif center:
# Centered text
line_out = separator + text2align.center(length) + separator
else:
# Left aligned text
line_out = separator + ' ' + text2align + (' ' * (length - len(text2align))) +separator
return line_out + '\n'
def prep_value_for_conf(comment, name, value):
if comment != '':
lines_out = '# ' + comment + '\n'
else:
lines_out = ''
lines_out = lines_out + name + " = " + value + '\n'
return lines_out
def add_option(options, next_option, value):
if value == '':
new_option = next_option
else:
new_option = next_option + '=' + value
options.append('--' + new_option)
def get_other_members(list_of_mongod):
other_members= ''
for mongo in list_of_mongod:
if other_members != '':
other_members = other_members + ','
other_members = other_members + mongo.ip + ':' + str(mongo.port)
return(other_members)
###################################################
# Classes #
###################################################
class generalParams:
def __init__(self, name, data, etc, log, var, lbin, baseFolder, port, ip, inc_port, inc_ip, mask_ip, mongoCredentials, mongoLocation, init_script, data_location):
self.name = name
self.baseFolder = baseFolder
self.data = self.baseFolder + data
self.etc = self.baseFolder + etc
self.log = self.baseFolder + log
self.var = self.baseFolder + var
self.lbin = self.baseFolder + lbin
self.port = port
self.ip = socket.inet_aton(ip)
self.inc_port = inc_port
self.inc_ip = inc_ip
self.mask_ip = mask_ip
self.next_port = self.port + self.inc_port
self.next_ip = self.ip
self.mongoCredentials = mongoCredentials
self.mongoCredentials.key_file = self.data+'/'+self.name+'.shared-key.txt'
self.mongoLocation = mongoLocation
self.dataLocation = data_location
self.start_options = []
if init_script != '':
f_in = open(init_script, 'r')
init_template = Template(f_in.read())
f_in.close()
else:
logging.debug("Using internally defined init scrip")
init_template = Template(init_scrip)
self.init_script = init_template.safe_substitute(ClusterInABox='Cluster in a box - version 0.1')
def createFolders(self):
subprocess.call(['mkdir', '-p', self.etc])
subprocess.call(['mkdir', '-p', self.etc +'/init.d'])
subprocess.call(['mkdir', '-p', self.log])
subprocess.call(['mkdir', '-p', self.var])
subprocess.call(['ln', '-s', self.mongoLocation + '/bin', self.lbin])
if self.dataLocation == '':
subprocess.call(['mkdir', '-p', self.data])
else:
print self.dataLocation, self.data
subprocess.call(['ln', '-s', self.dataLocation, self.data])
self.mongoCredentials.createKeyFile(self.mongoCredentials.key_file)
def dropFolders(self):
subprocess.call(['rm', '-rf', self.baseFolder])
def getNextPort(self):
presentPort = self.next_port
self.next_port = self.next_port + self.inc_port
return presentPort
def getNextIP(self):
presentIP = self.next_ip
# increment present IP by one and check the mask using some network library
# self.next_ip , self.inc_ip, self.mask_ip
return socket.inet_ntoa(presentIP)
def print_v(self):
print "-------------------------------------------- generalParams"
pprint.pprint (vars(self))
class mongoSecurity:
def __init__(self, user, password, key_pass):
self.user = user
self.password = password
self.key_file = 'default.shared-key.txt'
self.key_pass = key_pass
# Enable authentication if a username is provided
self.authentication_enabled = (self.user != '')
def createKeyFile(self, fullFileName):
self.key_file = fullFileName
try:
file_key = open(self.key_file, 'r')
# Read contents
except IOError:
file_key = open(self.key_file, 'w')
file_key.write(self.key_pass + '\n')
file_key.close()
# Key file with shared secret requieres strict read permissions (600)
subprocess.call(['chmod', '600', self.key_file])
class mongodbInstance:
def __init__(self, parentname, name, data_location, conf_file, pid_file, log_file, mongo_type, ip, port, credentials, journaled, binary):
self.parentname = parentname
self.name = name
self.data_location = data_location
self.conf_file = conf_file + '/' + self.name + '.conf'
self.pid_file = pid_file + '/' + self.name + '.pid'
self.log_file = log_file + '/' + self.name + '.log'
self.mongo_type = mongo_type
self.ip = ip
self.port = port
self.credentials = credentials
self.auth = self.credentials.authentication_enabled
self.journaled = journaled
#self.status = 'UnKnown'
self.rest = 'false'
self.fork = 'true'
self.init_script_file = conf_file + '/init.d/' + self.name + '.mongod'
self.client = None
self.connection = None
self.admin = None
self.mongo_status = None
self.options = [binary]
self.binary = binary
self.related_mongos = []
self.is_configured = False
def create_conf_file(self, init_script):
subprocess.call(['mkdir', '-p', self.data_location])
fcg = open(self.conf_file, 'w')
fcg.write( prep_string_for_comment(40, '#', False, '') )
fcg.write( prep_string_for_comment(40, '#', False, 'Autogenerated conf file') )
fcg.write( prep_string_for_comment(40, '#', False, self.name) )
fcg.write( prep_string_for_comment(40, '#', False, ' ') )
fcg.write( prep_string_for_comment(40, '#', False, '') )
fcg.write( prep_value_for_conf("Full pathname for the log file", "logpath", self.log_file) )
add_option(self.options, 'logpath', self.log_file)
fcg.write( prep_value_for_conf("Append to the log: preserves the previous contents across restarts", "logappend", 'true') )
add_option(self.options, 'logappend', '')
fcg.write( prep_value_for_conf("IP to bind to", "bind_ip", self.ip) )
add_option(self.options, 'bind_ip', self.ip)
fcg.write( prep_value_for_conf("Port to use", "port", str(self.port)) )
add_option(self.options, 'port', str(self.port))
fcg.write( prep_value_for_conf("rest Interface enabled", "#rest", self.rest) )
fcg.write( prep_value_for_conf("Become Daemon", "fork", self.fork) )
add_option(self.options, 'fork', '')
# mongos instances don't requiere a data directory
if self.mongo_type != 'mongos':
fcg.write( prep_value_for_conf("Absolute path for the data folder", "dbpath", self.data_location) )
add_option(self.options, 'dbpath', self.data_location)
fcg.write( prep_value_for_conf("Use an single folder for each database (recommended)", "directoryperdb", 'true') )
add_option(self.options, 'directoryperdb', '')
fcg.write( prep_value_for_conf("Do not use a journaled system", "journal", 'false' ) )
fcg.write( prep_value_for_conf("Do not use a journaled system: take two", "nojournal", 'true' ) )
add_option(self.options, 'nojournal', '')
fcg.write( prep_value_for_conf("Do not preallocate space for the files in a test environment", "noprealloc", 'true' ) )
add_option(self.options, 'noprealloc', '')
fcg.write( prep_value_for_conf("Just for local tests and debugging: remove on real systems", "oplogSize", str(192)))
add_option(self.options, 'oplogSize', '192')
if self.auth:
fcg.write( prep_value_for_conf("Enable Authentication on this instance", "auth", 'true') )
fcg.write( prep_value_for_conf("Enable Authentication on this instance (32 bits)", "noauth", 'false') )
add_option(self.options, 'auth', '')
else:
add_option(self.options, 'noauth', '')
fcg.write( prep_value_for_conf("Disable Authentication on this instance", "auth", 'false') )
fcg.write( prep_value_for_conf("Disable Authentication on this instance (32 bits)", "noauth", 'true') )
fcg.write( prep_value_for_conf("Full pathname for the pid file", "pidfilepath", self.pid_file) )
add_option(self.options, 'pidfilepath', self.pid_file)
fcg.write( prep_value_for_conf("Full pathname for the keyFile to use", "keyFile", self.credentials.key_file) )
add_option(self.options, 'keyFile', self.credentials.key_file)
if self.mongo_type.startswith('replSet'):
# Get the connection parameters for the other members of the replica set
fullRepSetCfg = self.parentname+'/' + get_other_members(self.related_mongos)
fullRepSetCfg = self.parentname+'/' + get_other_members(self.related_mongos)
fcg.write( prep_value_for_conf("Instance part of a replica set:" + self.mongo_type, "replSet", fullRepSetCfg ))
add_option(self.options, 'replSet', fullRepSetCfg)
elif self.mongo_type == 'configsvr':
fcg.write( prep_value_for_conf("Instance is a config database in a cluster", "configsvr", 'true'))
add_option(self.options, 'configsvr', '')
elif self.mongo_type == 'mongos':
# The mongos entry for a sharded environment
# mongos instances do not allow localhost IPs (127.0: loop devices) for the config servers.
# If it appears in the list, replace it with the local hostname
fullCfgList = get_other_members(self.related_mongos)
fcg.write(prep_value_for_conf("Instance is the mongos service for a sharded environment", 'configdb', fullCfgList))
add_option(self.options, 'configdb', fullCfgList)
fcg.close()
file_init = open(self.init_script_file, 'w')
cnt_init_script = Template(init_script).safe_substitute(NameOfInstance=self.name, MongoConfigFile=self.conf_file, MongoPIDFile=self.pid_file, mongod_binary=self.binary)
file_init.write(cnt_init_script)
file_init.close()
subprocess.call(['chmod', '700', self.init_script_file])
# For debug
file_init = open(self.init_script_file+'.safe', 'w')
file_init.write(' '.join(self.gen_start_safe_options(self.binary)))
file_init.close()
#subprocess.call(['chmod', '700',self.init_script_file+'.safe')
def add_related_mongos(self, mongos_list):
for mongo in mongos_list:
if self.name != mongo.name:
self.related_mongos.append(mongo)
def print_v(self):
print "-------------------------------------------- mongodbInstance"
pprint.pprint (vars(self))
def add_admin_account(self):
if self.auth:
self.admin.add_user(self.credentials.user, self.credentials.password, roles = ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase", "clusterAdmin"] )
def connect2admin(self):
self.admin = self.connection.admin
# Authenticate if the instance has already been configured and is not an 'Arbiter' in a rs
if self.is_configured and self.mongo_type != 'replSet.Arbiter' and self.auth:
self.admin.authenticate(self.credentials.user, self.credentials.password)
def start(self, safe=False, safe_delay=5):
print "Starting " + self.name
if safe:
self.subp = subprocess.Popen(self.gen_start_safe_options(self.binary),shell=False)
# Attempt to connect for at least five seconds
self.connect(safe_delay)
self.server_status()
else:
#pdb.set_trace()
self.subp = subprocess.Popen(self.options,shell=False)
def stop(self):
print "Stoping " + self.name
self.connect()
if self.admin != None:
self.shutdown()
def get_pid(self):
if os.path.isfile(self.pid_file):
pid = int(file(self.pid_file,'r').readlines()[0])
else:
pid = 0
return(pid)
def kill(self):
pid = self.get_pid()
print "Killing " + self.name + " - pid = " + str(pid)
if pid > 0:
try:
os.kill(pid, signal.SIGKILL)
except OSError as e:
print "OS error number " + str(e.errno)
print e.strerror
subprocess.call(['rm', self.pid_file])
self.clean_connection()
def gen_start_safe_options(self, bin2run):
options = [bin2run]
add_option(options, 'bind_ip', self.ip)
add_option(options, 'port', str(self.port))
add_option(options, 'pidfilepath', self.pid_file)
add_option(options, 'logpath', self.log_file+'.cfg_run')
if self.mongo_type != 'mongos':
add_option(options, 'dbpath', self.data_location)
add_option(options, 'directoryperdb', '')
add_option(options, 'nojournal', '')
add_option(options, 'noprealloc', '')
add_option(options, 'noauth', '')
# Remove this option for production systems or provide a far more sensitive value
add_option(options, 'oplogSize', '192')
add_option(options, 'logappend', '')
add_option(options, 'nohttpinterface', '')
#pdb.set_trace()
if self.mongo_type.startswith('replSet'):
add_option(options, 'replSet', self.parentname)
elif self.mongo_type == 'configsvr':
print 'configsvr'
add_option(options, 'configsvr', '')
elif self.mongo_type == 'mongos':
fullCfgList = get_other_members(self.related_mongos)
add_option(options, 'configdb', fullCfgList)
return(options)
def config(self, mongo_type='replSet.Node'):
print "Configuring "+self.name
if self.connection == None:
self.connect()
if self.mongo_type == 'configsvr' or mongo_type == 'replSet.Master':
# Add admin user
self.add_admin_account()
# Flag this instance as already configured
self.is_configured = True
def shutdown(self, timeout = 30):
print "Shutting down "+ self.name
if self.connection == None:
self.connect()
try:
# The timeout will give primaries/masters of repsets a chance for the secondaries to get up to date before shutting down
self.admin.command(bson.son.SON([ ('shutdown',1), ('timeoutSecs', timeout) ]))
except pymongo.errors.AutoReconnect:
print "mongodb died gracefully..."
self.clean_connection()
subprocess.call(['rm', self.pid_file])
except pymongo.errors.OperationFailure:
print self.name + " could not be shutdown!!!!!!!!!!!!!!!!!!!!"
#time.sleep(1)
#self.shutdown()
def clean_connection(self):
self.connection = None
self.admin = None
def killS(self):
print "kill " + self.name
#subprocess.call([self.init_script_file, 'kill'])
def connect(self, time2reattempt=0):
print "Connecting to "+ self.name
if time2reattempt > 0:
reconnections_attempts = time2reattempt*10
while reconnections_attempts > 0:
try:
#self.connection = pymongo.MongoClient(self.ip, self.port, connectTimeoutMS=time2reattempt*1000)
self.connection = pymongo.MongoClient(self.ip, self.port)
break
except pymongo.errors.ConnectionFailure:
time.sleep(0.1)
reconnections_attempts = reconnections_attempts - 1
if reconnections_attempts <= 0:
logging.critical('Failed to connect to ' + self.name)
else:
self.connect2admin()
else:
try:
self.connection = pymongo.MongoClient(self.ip, self.port)
self.connect2admin()
except pymongo.errors.ConnectionFailure:
logging.critical('Failed to connect to ' + self.name)
def run_command(self, command2run, json2pass=None):
#print command2run, json2pass
if self.connection == None:
# Open a connection first
self.connect()
if json2pass == None:
res = self.admin.command(command2run)
else:
res = self.admin.command(command2run, json2pass)
return(res)
def check_rep_set_status(self, rscheck='Connected', res=None):
resCheck = False
if rscheck=='IsRepSetConfigured':
if (res != None) and ('setName' in res):
resCheck = True
return resCheck
def server_status(self, verbose = False, force_run=False):
if self.mongo_status == None or force_run:
self.mongo_status = self.run_command('serverStatus')
if verbose:
printplus(self.mongo_status)
def status(self, status_requested='full'):
print '-' * 50
print self.name + ': ' + self.mongo_type
self.connect(2)
if self.admin == None:
print "Not running"
else:
mongo_status = self.run_command('serverStatus')
if status_requested=='full':
print 'pplus output'
printplus(mongo_status)
print 'pprint output'
pprint.pprint(mongo_status, indent=4)
else:
print 'Running'
def IsPrimary(self):
# Returns true if this mongo is the primary node of a replicaset
#pdb.set_trace()
#print '----- ismaster'
ismaster = self.run_command('ismaster')
#printplus(ismaster)
return(ismaster['ismaster'])
print '---'
self.server_status(verbose=True, force_run=True)
try:
replset_status = self.mongo_status['repl']
#printplus(replset_status)
IsIt = replset_status['ismaster']
except KeyError:
logging.debug(self.name + ' was tested for primary status in a replica set but it is a standalone process')
IsIt = False
return(IsIt)
class mongodbReplicaSet:
def __init__(self, replica_size, replica_type, shard_name, sufix, clusterParams):
self.replica_size = replica_size
self.replica_type = replica_type
self.name = shard_name + ".rs"
self.clusterParams = clusterParams
self.mongo_instances = [ self.get_mongodbInstance(i) for i in range(1, replica_size+1) ]
for mongo in self.mongo_instances:
mongo.add_related_mongos(self.mongo_instances)
def get_mongodbInstance(self, i):
base_name = self.name + "." + str(i)
if i == self.replica_size:
# The last member to add is the arbiter
repsettype = 'replSet.Arbiter'
else:
repsettype = 'replSet.Node'
mdb = mongodbInstance(self.name, base_name,\
self.clusterParams.data+'/'+base_name,\
self.clusterParams.etc,\
self.clusterParams.var,\
self.clusterParams.var,\
repsettype,\
self.clusterParams.getNextIP(),\
self.clusterParams.getNextPort(),\
self.clusterParams.mongoCredentials,\
False,\
self.clusterParams.lbin+'/mongod')
return(mdb)
def createReplicaSet(self):
for mongo in self.mongo_instances:
mongo.create_conf_file(self.clusterParams.init_script)
def print_v(self):
logging.debug("-------------------------------------------- mongodbReplicaSet")
logging.debug(pprint.pformat(vars(self)))
for mongoins in self.mongo_instances:
mongoins.print_v()
def start(self):
for mongoins in self.mongo_instances:
mongoins.start()
def stop(self):
for mongoins in self.mongo_instances:
mongoins.stop()
def shutdown(self):
# Shut them down
for mongo in self.mongo_instances:
mongo.shutdown()
def status(self,status_requested):
for mongoins in self.mongo_instances:
mongoins.status(status_requested)
def get_member_parms(self, i):
mongo = self.mongo_instances[i]
if mongo.mongo_type == 'replSet.Arbiter':
member = { '_id': i,
'host': mongo.ip+':'+str(mongo.port),
'arbiterOnly': 'true'}
else:
member = { '_id': i,
'host': mongo.ip+':'+str(mongo.port)}
logging.debug(pprint.pformat(member))
return member
def get_list_of_members(self):
# Return a list of members
members = [self.get_member_parms(i) for i in range(0, self.replica_size) ]
return members
def config(self):
print "Configuring replica set" + self.name
# First, start the mongos in safe mode
for mongo in self.mongo_instances:
mongo.start('safe')
# Give them a chance to get up (wait a few seconds)
#self.mongo_instances
time.sleep(1)
# Configure all of them
repSetConfig = { '_id': self.name,
'members': self.get_list_of_members()
}
self.mongo_instances[0].run_command('replSetInitiate', repSetConfig)
print 'Waiting one minute or until the replicaset has selfconfigured itself'
for i in range(1, 60):
rep_set_status = self.mongo_instances[0].run_command('isMaster')
#print "rep_set_status: "
#printplus(rep_set_status)
if self.mongo_instances[0].check_rep_set_status('IsRepSetConfigured', rep_set_status):
print self.mongo_instances[0].parentname + ' is configured'
break
time.sleep(1)
# Flag all the members as configured, though there is one more piece missing: adding the admin account once
# the master of the replicaset has already been established
# Run any selfconfiguration options that are requiered (for instance, adding the admin user and enabling authentication
#mongo_master = self.getPrimaryNode
#master_detected = False
for mongo in self.mongo_instances:
mongo.is_configured = True
#if not master_detected and mongo.IsPrimary():
# mongo.config('replSet.Master')
# master_detected = True
#else:
# mongo.config()
#if not master_detected:
# print "Critical error: master was not detected in this replicaset"
def kill(self):
for mongoins in self.mongo_instances:
mongoins.kill()
def add_admin_account(self):
mongo_master = self.getPrimaryNode()
mongo_master.config('replSet.Master')
def getPrimaryNode(self):
# Gets the primary node of the replicaset and returns it
print "Looking for the master of " + self.name
cycles2try = 15
while cycles2try > 0:
for mongo in self.mongo_instances:
if mongo.IsPrimary():
logging.debug('Found master: ' + mongo.name)
return(mongo)
# A master was not found in the entire replicaset. Possible still self-configuring.
# Wait one second and try again.
time.sleep(1)
logging.debug("Still looking for the master or " + self.name + " " + str(cycles2try) + " more attempts to go...")
cycles2try = cycles2try - 1
class mongodbConfigSet:
def __init__(self, clusterParams, k_config_servers):
self.clusterParams = clusterParams
self.size = k_config_servers
self.configMongodbs = [self.get_mongodbInstance(i) for i in range(1, self.size+1) ]
for mongo in self.configMongodbs:
mongo.add_related_mongos(self.configMongodbs)
def get_mongodbInstance(self, i):
base_name = self.clusterParams.name + '.cfg.' + str(i)
mdb = mongodbInstance(self.clusterParams.name, base_name,\
self.clusterParams.data+'/'+base_name,\
self.clusterParams.etc,\
self.clusterParams.var,\
self.clusterParams.var,\
'configsvr',\
self.clusterParams.getNextIP(),\
self.clusterParams.getNextPort(),\
self.clusterParams.mongoCredentials,\
True,\
self.clusterParams.lbin+'/mongod')
return(mdb)
def createConfigMongos(self):
for mongo in self.configMongodbs:
mongo.create_conf_file(self.clusterParams.init_script)
def print_v(self):
logging.debug("-------------------------------------------- mongodbConfigSet")
logging.debug(pprint.pformat(vars(self)))
for config in self.configMongodbs:
config.print_v()
def start(self):
for mongo in self.configMongodbs:
mongo.start()
def stop(self):
for mongo in self.configMongodbs:
mongo.stop()
def status(self, status_requested):
for mongo in self.configMongodbs:
mongo.status(status_requested)
def shutdown(self):
for mongo in self.configMongodbs:
mongo.shutdown()
def config(self, mongos_process, shardNodes):
print "Configuring the mongo shards configs"
# First, start the mongos in safe mode
for mongo in self.configMongodbs:
mongo.start(safe=True)
mongos_process.start(safe=True, safe_delay=15)
# Configure all of them
for mongo in self.configMongodbs:
mongo.config()
# Initiate the mongos process: mongos will need a detail of the shards that it should connect to.
print "Adding the individual shards (repset masters) to the mongos cluster"
mongodbsPrimary = [shard.getPrimaryNode() for shard in shardNodes]
#pdb.set_trace()
for rs in mongodbsPrimary:
mongos_process.run_command('addShard', rs.parentname + '/' + rs.ip + ':' + str(rs.port))
time.sleep(1)
def kill(self):
for mongo in self.configMongodbs:
mongo.kill()
class mongodbShard:
def __init__(self, sufix, replica_size, replica_type, clusterParams):
self.name = clusterParams.name +'.shard.' + str(sufix)
self.sufix = sufix
self.replica_size = replica_size
self.clusterParams = clusterParams
self.replicaset = mongodbReplicaSet(replica_size, replica_type, self.name, self.sufix, self.clusterParams)
def createRepSetMongos(self):
self.replicaset.createReplicaSet()
def print_v(self):
logging.debug("-------------------------------------------- mongodbShard")
logging.debug(pprint.pformat(vars(self)))
self.replicaset.print_v()
def start(self):
self.replicaset.start()
def stop(self):
self.replicaset.stop()
def status(self, status_requested):
self.replicaset.status(status_requested)
def shutdown(self):
self.replicaset.shutdown()
def config(self):
self.replicaset.config()
def kill(self):
self.replicaset.kill()
def getPrimaryNode(self):
# Gets the primary node of the replicaset and returns it
return(self.replicaset.getPrimaryNode())
def add_admin_account(self):
self.replicaset.add_admin_account()
class mongodbCluster:
def __init__(self, cluster2load='', clusterParams=None, nodes=0, config_size=0, replica_size=0, replica_type='Simple', cluster_type='Simple'):
if cluster2load != '':
self.loadCluster(cluster2load)
else:
self.nodes = nodes
self.replica_size = replica_size
self.replica_type = replica_type
self.clusterParams = clusterParams
self.is_configured = False
self.configClsts = mongodbConfigSet(self.clusterParams, config_size)
self.shardNodes = [ mongodbShard(i, self.replica_size, self.replica_type, self.clusterParams ) for i in range(1, self.nodes+1) ]
# the mongos process. Type 'mongos'
self.mongos_process = self.create_mongos_instance()
def create_mongos_instance(self):
# The mongos process will use the firt port assigned for this cluster: Just to make it easy to identify the port that the
# apps should aim to. Otherwise the devs should take a look at the config files to see what port was sequentially assigned
# to the mongos service
base_name = self.clusterParams.name + '.mongos'
mdb = mongodbInstance(self.clusterParams.name, base_name,\
self.clusterParams.data+'/'+base_name,\
self.clusterParams.etc,\
self.clusterParams.var,\
self.clusterParams.var,\
'mongos',\
socket.inet_ntoa(self.clusterParams.ip),\
self.clusterParams.port,\
self.clusterParams.mongoCredentials,\
True,\
self.clusterParams.lbin+'/mongos')
mdb.add_related_mongos(self.configClsts.configMongodbs)
return(mdb)
def cleanCluster(self):
self.clusterParams.dropFolders()
def createCluster(self):
self.cleanCluster()
self.clusterParams.createFolders()
self.configClsts.createConfigMongos()
for shard in self.shardNodes:
shard.createRepSetMongos()
self.mongos_process.create_conf_file(self.clusterParams.init_script)
#pdb.set_trace()
def print_v(self):
logging.debug("-------------------------------------------- mongodbCluster")
self.clusterParams.print_v()
self.mongos_process.print_v()
self.configClsts.print_v()
for shard in self.shardNodes:
shard.print_v()
def start(self):
if not self.is_configured:
self.config()
self.configClsts.start()
for shard in self.shardNodes:
shard.start()
# Wait for the other mongodbs before attemting to start the mongos process
for mongo in self.configClsts.configMongodbs:
mongo.connect(2)
for srd in self.shardNodes:
for mongo in srd.replicaset.mongo_instances:
mongo.connect(2)
self.mongos_process.start()
def stop(self):
self.mongos_process.stop()
self.configClsts.stop()
for shard in self.shardNodes:
shard.stop()
def status(self, status_requested):
self.configClsts.status(status_requested)
for shard in self.shardNodes:
shard.status(status_requested)
self.mongos_process.status(status_requested)
def shutdown(self):
self.configClsts.shutdown()
for shard in self.shardNodes:
shard.shutdown()
self.mongos_process.shutdown()
def config(self):
# Configure the replicasets firts, the configs later
for shard in self.shardNodes:
shard.config()
# Configure the config mongod
self.configClsts.config(self.mongos_process, self.shardNodes)
# Finally, configure the mongos instance
self.mongos_process.config()
# The final step once the replicaset had already selfconfigured is to add the admin account in the master of each one
for shard in self.shardNodes:
shard.add_admin_account()
# This was a configuration run only, stop the services
self.shutdown()
self.is_configured = True
#pdb.set_trace()
self.saveCluster()
def kill(self):
self.configClsts.kill()
for shard in self.shardNodes:
shard.kill()
self.mongos_process.kill()