-
Notifications
You must be signed in to change notification settings - Fork 26
/
fabfile.py
4274 lines (3637 loc) · 173 KB
/
fabfile.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
from fabric.api import *
from fabric.exceptions import NetworkError as _NetworkError
from fabric.colors import green as _green, blue as _blue, red as _red, yellow as _yellow
from fabric.contrib.files import append as _fab_append, exists as _fab_exists
from fabric.contrib.console import confirm
from StringIO import StringIO as _strio
import boto, boto3
from boto.s3.key import Key as _S3Key
import boto.emr
from boto.emr.step import InstallPigStep as _InstallPigStep
from boto.emr.step import PigStep as _PigStep
from random import shuffle as _shuffle
from urllib import urlretrieve as _urlretrieve
import boto.ec2
import time
import sys
import os
import urllib2
import getpass
import json
import pysolr
import os.path
import fnmatch
import datetime
import dateutil.parser
import shutil
import socket
import boto.vpc
import ntpath
from distutils.version import StrictVersion
# Global constants used in this module; only change this if you know what you're doing ;-)
CLUSTER_TAG = 'cluster'
USERNAME_TAG = 'username'
INSTANCE_STORES_TAG = 'numInstanceStores'
AWS_HVM_AMI_ID = 'ami-4d767836'
AWS_AZ = 'us-west-2b'
AWS_INSTANCE_TYPE = 'r3.large'
AWS_SECURITY_GROUP = 'solr-scale-tk'
AWS_KEY_NAME = 'solr-scale-tk'
ssh_user = 'ec2-user'
user_home = '/home/' + ssh_user
ssh_keyfile_path_on_local = '~/.ssh/solr-scale-tk.pem'
zk_data_dir = '/vol0/data'
CTL_SCRIPT = 'solr-ctl.sh'
ENV_SCRIPT = 'solr-ctl-env.sh'
# default config settings if not specifically overridden in the user's ~/.sstk file
_config = {}
_config['provider'] = 'ec2'
_config['user_home'] = user_home
_config['ssh_keyfile_path_on_local'] = ssh_keyfile_path_on_local
_config['ssh_user'] = ssh_user
_config['solr_java_home'] = '${user_home}/jdk1.8.0_172'
_config['solr_tip'] = '${user_home}/solr-7.3.1'
_config['zk_home'] = '${user_home}/zookeeper-3.4.10'
_config['zk_data_dir'] = zk_data_dir
_config['sstk_cloud_dir'] = '${user_home}/cloud'
_config['SSTK_ENV'] = '${sstk_cloud_dir}/' + ENV_SCRIPT
_config['SSTK'] = '${sstk_cloud_dir}/' + CTL_SCRIPT
_config['AWS_HVM_AMI_ID'] = AWS_HVM_AMI_ID
_config['AWS_AZ'] = AWS_AZ
_config['AWS_SECURITY_GROUP'] = AWS_SECURITY_GROUP
_config['AWS_INSTANCE_TYPE'] = AWS_INSTANCE_TYPE
_config['AWS_KEY_NAME'] = AWS_KEY_NAME
_config['fusion_home'] = '${user_home}/fusion/4.0.0'
_config['fusion_vers'] = '4.0.0'
_config['connector_memory_in_gb'] = '1'
_config['owner'] = getpass.getuser()
instanceStoresByType = {'m2.small':0, 't2.medium':0, 't2.large':0, 't2.xlarge':0,
'm3.medium':1, 'm3.large':1, 'm3.xlarge':2, 'm3.2xlarge':2,
'i2.4xlarge':4,'i2.2xlarge':2, 'i2.8xlarge':8,
'r3.large':1, 'r3.xlarge':1, 'r3.2xlarge':1, 'r3.4xlarge':1, 'c3.2xlarge':2,
'r4.large':0, 'r4.xlarge':0, 'r4.2xlarge':0, 'r4.4xlarge':0, 'r4.8xlarge':0,
'm4.large':0, 'm4.xlarge':0, 'm4.2xlarge':0, 'm4.4xlarge':0, 'm4.8xlarge':0 }
class _HeadRequest(urllib2.Request):
def get_method(self):
return 'HEAD'
def _status(msg):
print(_yellow(msg))
def _info(msg):
print(_green(msg))
def _warn(msg):
print(_blue('WARN: ' + msg))
def _error(msg):
sys.stderr.write(_red('\n\t************************'))
sys.stderr.write(_red('\n\tERROR: %s\n' % str(msg)))
sys.stderr.write(_red('\t************************\n\n'))
# Helper to log a message and kill the application after a fatal error occurs.
def _fatal(msg):
_error(msg)
exit(1)
def _copy_dir(src, dest):
try:
shutil.copytree(src, dest)
# Directories are the same
except shutil.Error as e:
print('Directory not copied. Error: %s' % e)
# Any error saying that the directory doesn't exist
except OSError as e:
print('Directory not copied. Error: %s' % e)
def _runbg( command, out_file="/dev/null", err_file=None, shell=True, pty=False ):
_info('_runbg: nohup %s >%s 2>%s </dev/null &' % (command, out_file, err_file or '&1'))
run('nohup %s >%s 2>%s </dev/null &' % (command, out_file, err_file or '&1'), shell, pty)
def _save_config():
sstk_cfg = _get_config()
sstkCfg = os.path.expanduser('~/.sstk')
sstkCfgFile = open(sstkCfg, 'w')
sstkCfgFile.write(json.dumps(sstk_cfg, indent=2))
sstkCfgFile.close()
def _expand_config_var(cluster, val):
if len(val) > 0:
startVar = val.find('${')
while startVar != -1:
endVar = val.find('}',startVar+1)
varStr = val[startVar:endVar+1]
varVal = _env(cluster, varStr[2:len(varStr)-1])
val = val.replace(varStr, varVal)
startVar = val.find('${')
return val
def _get_config():
if _config.has_key('sstk_cfg'):
return _config['sstk_cfg']
sstkCfg = os.path.expanduser('~/.sstk')
if os.path.isfile(sstkCfg) is False:
_config['sstk_cfg'] = {}
else:
sstkCfgFile = open(sstkCfg)
sstkJson = json.load(sstkCfgFile)
sstkCfgFile.close()
_config['sstk_cfg'] = sstkJson
return _config['sstk_cfg']
# resolves an environment property by first checking the cluster specific settings,
# then user specific settings, then global settings
def _env(cluster, key):
return _env(cluster, key, None)
def _env(cluster, key, defaultValue=None):
if key is None:
_fatal('Property key is required!')
val = None
sstk_cfg = _get_config()
if cluster is not None:
if sstk_cfg.has_key('clusters') and sstk_cfg['clusters'].has_key(cluster):
if sstk_cfg['clusters'][cluster].has_key(key):
val = sstk_cfg['clusters'][cluster][key]
if val is None:
if sstk_cfg.has_key(key):
val = sstk_cfg[key]
if val is None:
if _config.has_key(key):
val = _config[key]
if val is None:
val = defaultValue
if val is None:
_fatal('Unable to resolve required property setting: '+key)
return _expand_config_var(cluster, val)
def _get_ec2_provider(region):
_info("Region used: " + str(region))
if region is not None:
return boto.ec2.connect_to_region(region)
else:
return boto.connect_ec2()
class _LocalProvider:
"""Local provider (instead of EC2)"""
def type(self):
return 'local'
def get_all_instances(self,filters=None):
return []
def close(self):
return
# Get a handle to a Cloud Provider API (or mock for local mode)
def _provider_api(cluster ='ec2'):
sstk_cfg = _get_config()
if sstk_cfg.has_key('clusters') and sstk_cfg['clusters'].has_key(cluster):
if sstk_cfg['clusters'][cluster].has_key('provider') is False:
sstk_cfg['provider'] = 'ec2' # default
else:
sstk_cfg['provider'] = sstk_cfg['clusters'][cluster]['provider']
else:
sstk_cfg['provider'] = 'ec2'
provider = sstk_cfg['provider']
if provider == 'ec2':
region = None
if sstk_cfg.has_key('region'):
region = sstk_cfg['region']
return _get_ec2_provider(region)
elif provider == 'local':
return _LocalProvider()
else:
_fatal(provider+' not supported! Please correct your ~/.sstk configuration file.')
return None
# Polls until instances are running, up to a max wait
def _poll_for_running_status(rsrv, maxWait=180):
_info('Waiting for ' + str(len(rsrv)) + ' instances to start (will wait for a max of 3 minutes) ...')
startedAt = time.time()
waitTime = 0
sleepInterval = 15
runningSet = set([])
allRunning = False
while allRunning is False and waitTime < maxWait:
allRunning = True
for inst in rsrv:
if inst.id in runningSet:
continue
status = inst.update()
_status('Instance %s has status %s after %d seconds' % (inst.id, status, (time.time() - startedAt)))
if status == 'running':
runningSet.add(inst.id)
else:
allRunning = False
if allRunning is False:
time.sleep(sleepInterval)
waitTime = round(time.time() - startedAt)
if allRunning:
_info('Took %d seconds to launch %d instances.' % (time.time() - startedAt, len(runningSet)))
else:
_warn('Only %d of %d instances running after waiting %d seconds' % (len(runningSet), len(rsrv.instances), waitTime))
return len(runningSet)
def _find_instances_in_cluster(cloud, cluster, onlyIfRunning=True):
tagged = {}
byTag = cloud.get_all_instances(filters={'tag:' + CLUSTER_TAG:cluster})
_info("find_instance by tag: {0} for cloud: {1} and cluster: {2}".format(byTag, cloud, cluster))
for rsrv in byTag:
for inst in rsrv.instances:
_info("Checking instance: {0}".format(inst))
if (onlyIfRunning and inst.state == 'running') or onlyIfRunning is False:
if inst.public_dns_name:
tagged[inst.id] = inst.public_dns_name
elif inst.private_ip_address: #we may be launching in a private subnet
tagged[inst.id] = inst.private_ip_address
return tagged
def _find_all_instances(cloud, onlyIfRunning=True):
tagged = {}
byTag = cloud.get_all_instances(filters={'tag-key':'cluster','tag-key':'username'})
for rsrv in byTag:
for inst in rsrv.instances:
if (onlyIfRunning and inst.state == 'running') or onlyIfRunning is False:
tagged[inst.id] = inst
return tagged
def _find_user_instances(cloud, username, onlyIfRunning=True):
tagged = {}
byTag = cloud.get_all_instances(filters={'tag:' + USERNAME_TAG:username})
numFound = len(byTag)
if numFound == 0:
time.sleep(1)
byTag = cloud.get_all_instances(filters={'tag:' + USERNAME_TAG:username})
numFound = len(byTag)
if numFound > 0:
_warn('AWS API is acting flakey! First call to find instances for '+username+' found 0, now it found: '+str(numFound))
for rsrv in byTag:
for inst in rsrv.instances:
if (onlyIfRunning and inst.state == 'running') or onlyIfRunning is False:
tagged[inst.id] = inst
return tagged
def _is_solr_up(hostAndPort):
isSolrUp = False
try:
urllib2.urlopen(_HeadRequest('http://%s/solr/#/' % hostAndPort))
# if no exception on the ping, assume the HTTP listener is up
_info('Solr at ' + hostAndPort + ' is online.')
isSolrUp = True
except:
# ignore it as we're just checking if the HTTP listener is up
# print "Unexpected error:", sys.exc_info()[0]
isSolrUp = False
return isSolrUp
# Test for SSH connectivity to an instance
def _ssh_to_new_instance(host):
sshOk = False
with settings(host_string=host), hide('output', 'running', 'warnings'):
try:
run('whoami')
sshOk = True
except _NetworkError as e:
print e
sskOk = False
except:
print "Unexpected error:", sys.exc_info()[0]
sshOk = False
return sshOk
def _cluster_hosts(cloud, cluster):
clusterHosts = None
sstkCfg = _get_config()
if sstkCfg.has_key('clusters') and sstkCfg['clusters'].has_key(cluster):
if sstkCfg['clusters'][cluster].has_key('hosts'):
clusterHosts = sstkCfg['clusters'][cluster]['hosts']
_info("Cluster Hosts: {0}".format(clusterHosts))
if clusterHosts is None:
# not cached locally ... must hit provider API
clusterHosts = []
taggedInstances = _find_instances_in_cluster(cloud, cluster)
for key in taggedInstances.keys():
clusterHosts.append(taggedInstances[key])
if len(clusterHosts) == 0:
_fatal('No active hosts found for cluster ' + cluster + '! Check your command line args and re-try')
# use a predictable order each time
clusterHosts.sort()
# setup the Fabric env for SSH'ing to this cluster
ssh_user = _env(cluster, 'ssh_user')
ssh_keyfile = _env(cluster, 'ssh_keyfile_path_on_local')
if len(ssh_keyfile) > 0 and os.path.isfile(os.path.expanduser(ssh_keyfile)) is False:
_fatal('SSH key file %s not found!' % ssh_keyfile)
env.hosts = []
env.user = ssh_user
env.key_filename = ssh_keyfile
return clusterHosts
def _verify_ssh_connectivity(hosts, maxWait=120):
# if using localhost for this cluster, no need to SSH
if len(hosts) == 1 and hosts[0] == 'localhost':
return
_status('Verifying SSH connectivity to %d hosts (will wait up to %d secs) ... please be patient as this can take a few minutes if EC2 is being cranky!' % (len(hosts), maxWait))
waitTime = 0
startedAt = time.time()
hasConn = False
sshSet = set([])
while hasConn is False and waitTime < maxWait:
hasConn = True # assume true and prove false with SSH failure
for host in hosts:
_info("Trying to connect to " + host)
if (host in sshSet) is False:
if _ssh_to_new_instance(host):
sshSet.add(host)
else:
hasConn = False
if hasConn is False:
time.sleep(5)
waitTime = round(time.time() - startedAt)
_status('Waited %d seconds so far to verify SSH connectivity to %d hosts' % (waitTime, len(hosts)))
if hasConn:
_info('Verified SSH connectivity to %d hosts.' % len(sshSet))
else:
_warn('SSH connectivity verification timed out after %d seconds! Verified %d of %d' % (maxWait, len(sshSet), len(hosts)))
return hasConn
def _gen_zoo_cfg(zkDataDir, zkHosts):
zoo_cfg = ''
zoo_cfg += 'tickTime=2000\n'
zoo_cfg += 'initLimit=10\n'
zoo_cfg += 'syncLimit=5\n'
zoo_cfg += 'dataDir='+zkDataDir+'\n'
zoo_cfg += 'clientPort=2181\n'
zoo_cfg += 'autopurge.snapRetainCount=3\n'
zoo_cfg += 'autopurge.purgeInterval=1\n'
numHosts = len(zkHosts)
if numHosts > 1:
for z in range(0, numHosts):
zoo_cfg += 'server.%d=%s:2888:3888\n' % (z + 1, zkHosts[z])
return zoo_cfg
# some silly stuff going on here ...
def _gen_log4j_cfg(localId=None, rabbitMqHost=None, mqLevel='WARN'):
cfg = 'log4j.rootLogger=INFO, file'
cfg += '''
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=200MB
log4j.appender.file.MaxBackupIndex=20
log4j.appender.file.File=logs/solr.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ISO8601} [%t] %-5p %c{3} %x - %m%n
log4j.logger.org.apache.zookeeper=WARN
log4j.logger.org.apache.http=WARN
log4j.logger.org.apache.solr.update.processor.LogUpdateProcessor=WARN
'''
return cfg
def _get_solr_in_sh(cluster, remoteSolrJavaHome, solrJavaMemOpts, zkHost, privateVPC, yjp_path=None):
provider = _env(cluster, 'provider')
if provider == "local":
solrHost = "localhost"
else:
_info("Using Private VPC: {0} for cluster: {1}".format(privateVPC, cluster))
if privateVPC is False:
solrHost = '`curl -s http://169.254.169.254/latest/meta-data/public-hostname`'
else:
#we don't have a public name, get the local
solrHost = '`curl -s http://169.254.169.254/latest/meta-data/local-ipv4`'
solrInSh = ('''#!/bin/bash
SOLR_JAVA_HOME="%s"
if [ -z "$JAVA_HOME" ]; then
export JAVA_HOME=$SOLR_JAVA_HOME
export PATH=$SOLR_JAVA_HOME/bin:$PATH
fi
# Increase Java Min/Max Heap as needed to support your indexing / query needs
SOLR_JAVA_MEM="%s"
# Enable verbose GC logging
GC_LOG_OPTS="-verbose:gc -XX:+PrintHeapAtGC -XX:+PrintGCDetails \
-XX:+PrintGCDateStamps -XX:+PrintGCCause -XX:+PrintTenuringDistribution -XX:+PrintGCApplicationStoppedTime"
# These GC settings have shown to work well for a number of common Solr workloads
GC_TUNE="-XX:NewRatio=3 \
-XX:+UseAdaptiveSizePolicy \
-XX:+UseParNewGC \
-XX:ConcGCThreads=4 \
-XX:ParallelGCThreads=4 \
-XX:SurvivorRatio=4 \
-XX:TargetSurvivorRatio=90 \
-XX:MaxTenuringThreshold=8 \
-XX:+UseConcMarkSweepGC \
-XX:+CMSScavengeBeforeRemark \
-XX:PretenureSizeThreshold=64m \
-XX:+UseCMSInitiatingOccupancyOnly \
-XX:CMSInitiatingOccupancyFraction=50 \
-XX:CMSMaxAbortablePrecleanTime=6000 \
-XX:+CMSParallelRemarkEnabled \
-XX:+ParallelRefProcEnabled"
# Set the ZooKeeper connection string if using an external ZooKeeper ensemble
# e.g. host1:2181,host2:2181/chroot
# Leave empty if not using SolrCloud
SOLR_MODE="solrcloud"
ZK_HOST="%s"
# Set the ZooKeeper client timeout (for SolrCloud mode)
ZK_CLIENT_TIMEOUT="15000"
# By default the start script uses "localhost"; override the hostname here
# for production SolrCloud environments to control the hostname exposed to cluster state
SOLR_HOST=%s
# By default the start script uses UTC; override the timezone if needed
#SOLR_TIMEZONE="UTC"
# By default the start script enables some RMI related parameters to allow attaching
# JMX savvy tools like VisualVM remotely, set to "false" to disable that behavior
# (recommended in production environments)
ENABLE_REMOTE_JMX_OPTS="true"
SOLR_OPTS="$SOLR_OPTS -Dsolr.autoCommit.maxTime=30000 -Dsolr.autoSoftCommit.maxTime=3000"
''' % (remoteSolrJavaHome, solrJavaMemOpts, zkHost, solrHost))
if yjp_path is not None:
solrInSh += 'SOLR_OPTS="$SOLR_OPTS -agentpath:'+yjp_path+'/bin/linux-x86-64/libyjpagent.so"\n'
return solrInSh
def _get_zk_hosts(cloud, zk):
zkHosts = []
zkInstances = _find_instances_in_cluster(cloud, zk)
for key in zkInstances.keys():
zkHosts.append(zkInstances[key] + ':2181')
return zkHosts
def _check_zk_health(n, hosts, maxWait=90):
waitTime = 0
startedAt = time.time()
zkHealthy = False
zkNodeSet = set([])
while zkHealthy is False and waitTime < maxWait:
zkHealthy = True
for z in range(0, n):
if (hosts[z] in zkNodeSet) is False:
with settings(host_string=hosts[z]), hide('output', 'running', 'warnings'):
zkSrvrResp = run('echo srvr | nc localhost 2181 || true')
if zkSrvrResp is None or zkSrvrResp == "" or zkSrvrResp.lower().find('mode: ') == -1:
_warn('ZooKeeper server on host %s seems to be unhealthy? %s' % (hosts[z], zkSrvrResp))
zkHealthy = False
else:
zkNodeSet.add(hosts[z])
if maxWait == 1:
break
if zkHealthy is False:
time.sleep(5)
waitTime = round(time.time() - startedAt)
_status('Waited %d seconds so far to verify ZooKeeper health on %d hosts' % (waitTime, n))
if zkHealthy:
_info('ZooKeeper is healthy on %d hosts.' % len(zkNodeSet))
else:
_fatal('ZooKeeper health checks timed out after %d seconds! Verified %d of %d' % (maxWait, len(zkNodeSet), n))
def _is_private_subnet(cluster):
result = False
sstkCfg = _get_config()
if sstkCfg.has_key('clusters') and sstkCfg['clusters'].has_key(cluster) and sstkCfg['clusters'][cluster].has_key('is_private_subnet'):
result = sstkCfg['clusters'][cluster]['is_private_subnet']
else:
#no cached entry
cloud = _provider_api(cluster)
byTag = cloud.get_all_instances(filters={'tag:' + CLUSTER_TAG:cluster})
_info("find_instance by tag: {0} for cloud: {1} and cluster: {2}".format(byTag, cloud, cluster))
for rsrv in byTag:
for inst in rsrv.instances:
_info("Checking instance: {0}".format(inst.public_dns_name is None or inst.public_dns_name is ""))
result = inst.public_dns_name is None or inst.public_dns_name is ""
#cache the result:
if sstkCfg.has_key('clusters') is False:
sstkCfg['clusters'] = {}
if sstkCfg['clusters'].has_key(cluster) is False:
sstkCfg['clusters'][cluster] = {}
sstkCfg['clusters'][cluster]['is_private_subnet'] = result
return result
def _lookup_hosts(cluster, verify_ssh=False):
hosts = None
# first, check our local cache for cluster hosts
sstkCfg = _get_config()
if sstkCfg.has_key('clusters') and sstkCfg['clusters'].has_key(cluster):
if sstkCfg['clusters'][cluster].has_key('hosts'):
hosts = sstkCfg['clusters'][cluster]['hosts']
if hosts is None:
# hosts not found in the local config
cloud = _provider_api(cluster)
hosts = _cluster_hosts(cloud, cluster)
cloud.close()
# cache the hosts in the local config
if sstkCfg.has_key('clusters') is False:
sstkCfg['clusters'] = {}
if sstkCfg['clusters'].has_key(cluster) is False:
sstkCfg['clusters'][cluster] = {}
sstkCfg['clusters'][cluster]['hosts'] = hosts
_save_config()
else:
# setup the Fabric env for SSH'ing to this cluster
ssh_user = _env(cluster, 'ssh_user')
ssh_keyfile = _env(cluster, 'ssh_keyfile_path_on_local')
if len(ssh_keyfile) > 0 and os.path.isfile(os.path.expanduser(ssh_keyfile)) is False:
_fatal('SSH key file %s not found!' % ssh_keyfile)
env.hosts = []
env.user = ssh_user
env.key_filename = ssh_keyfile
if verify_ssh:
_verify_ssh_connectivity(hosts)
return hosts
def _zk_ensemble(cluster, hosts):
n = len(hosts)
zoo_cfg = _gen_zoo_cfg(_env(cluster,'zk_data_dir'), hosts)
zkHosts = []
for z in range(0, n):
zkHosts.append(hosts[z] + ':2181')
zkDir = _env(cluster, 'zk_home')
java_home = _env(cluster, 'solr_java_home')
set_java_home = ('JAVA_HOME='+java_home+' ')
remoteZooCfg = zkDir + '/conf/zoo.cfg'
zkDataDir = _env(cluster,'zk_data_dir')
remoteZooMyid = zkDataDir+'/myid'
_status('Setting up ZooKeeper on ' + str(','.join(zkHosts)))
sshUser = _env(cluster, 'ssh_user')
provider = _env(cluster, 'provider')
for z in range(0, n):
with settings(host_string=hosts[z]), hide('output', 'running', 'warnings'):
# stop zk
run(set_java_home + zkDir + '/bin/zkServer.sh stop')
# setup to clean snapshots
if provider == 'local':
local('mkdir -p '+zkDataDir+' || true')
local('rm -rf '+zkDataDir+'/*')
else:
sudo('mkdir -p '+zkDataDir+' || true')
sudo('rm -rf '+zkDataDir+'/*')
sudo('chown -R '+sshUser+': '+zkDataDir)
run('rm -f ' + remoteZooCfg)
_fab_append(remoteZooCfg, zoo_cfg)
if (n > 1):
_fab_append(remoteZooMyid, str(z + 1))
# restart after stopping and clearing data
for z in range(0, n):
with settings(host_string=hosts[z]), hide('output', 'running', 'warnings'):
run(set_java_home + zkDir + '/bin/zkServer.sh start')
_info('Started ZooKeeper on %d nodes ... checking status' % n)
time.sleep(5)
_check_zk_health(n, hosts, 90)
return zkHosts
def _wait_to_see_solr_up_on_hosts(hostAndPorts, maxWait=180):
time.sleep(5)
waitTime = 0
startedAt = time.time()
allUp = False
upSet = set([])
downSet = set([])
while allUp is False and waitTime < maxWait:
# assume all are up at the beginning of each loop and then prove false if we see one that isn't
allUp = True
for srvr in hostAndPorts:
if (srvr in upSet) is False:
if _is_solr_up(srvr):
upSet.add(srvr)
try:
downSet.remove(srvr)
except:
pass
else:
allUp = False
downSet.add(srvr)
# sleep a little between loops to give the servers time to start
if allUp is False:
time.sleep(5)
waitTime = round(time.time() - startedAt)
if allUp:
_info('%d Solr servers are up!' % len(upSet))
else:
_error('Only %d of %d Solr servers came up within %d seconds.' % (len(upSet), len(hostAndPorts), maxWait))
for down in downSet:
_error(down+' is down!')
def _restart_solr(cluster, host, solrPortBase, pauseBeforeRestart=0):
solrTip = _env(cluster, 'solr_tip')
binSolrScript = solrTip + '/bin/solr'
solrPort = '89' + solrPortBase
solrDir = 'cloud'+solrPortBase
remoteStartCmd = '%s start -cloud -p %s -d %s' % (binSolrScript, solrPort, solrDir)
pauseTime = int(pauseBeforeRestart)
hostAndPort = host+':'+solrPort
with settings(host_string=host), hide('output', 'running', 'warnings'):
if _is_solr_up(hostAndPort):
_stop_solr(cluster, host, solrPortBase)
if pauseTime > 0:
_status('Sleeping for %d seconds before starting Solr node on %s' % (pauseTime, hostAndPort))
time.sleep(pauseTime)
_status('Running start on remote: ' + remoteStartCmd)
_runbg(remoteStartCmd)
time.sleep(2)
def _stop_solr(cluster, host, solrPortBase):
binSolrScript = _env(cluster, 'solr_tip') + '/bin/solr'
solrPort = '89' + solrPortBase
remoteStopCmd = '%s stop -p %s' % (binSolrScript, solrPort)
with settings(host_string=host), hide('output', 'running', 'warnings'):
_status('Running stop Solr on '+host+':'+solrPort+' ~ ' + remoteStopCmd)
_runbg(remoteStopCmd)
time.sleep(2)
def _get_instance_type(cloud, cluster):
instance_type = _env(cluster, 'instance_type', 'null')
if instance_type != 'null':
return instance_type
byTag = cloud.get_all_instances(filters={'tag:' + CLUSTER_TAG:cluster})
if len(byTag) > 0:
return byTag[0].instances[0].instance_type
return None
def _get_solr_java_memory_opts(instance_type, numNodesPerHost):
_status('Determining Solr Java memory options for running %s Solr nodes on a %s' % (numNodesPerHost, instance_type))
#TODO: allow overrides via .sstk
if instance_type is None or numNodesPerHost <= 0: # garbage in, just use default
return '-Xms512m -Xmx512m'
showWarn = False
if instance_type == 'm1.small':
if numNodesPerHost == 1:
mx = '512m'
elif numNodesPerHost == 2:
mx = '256m'
else:
showWarn = True
mx = '128m'
elif instance_type == 'm3.medium' or instance_type == 't2.medium':
if numNodesPerHost == 1:
mx = '1g'
elif numNodesPerHost == 2:
mx = '512m'
elif numNodesPerHost == 3:
mx = '384m'
else:
showWarn = True
mx = '256m'
elif instance_type == 'm3.large':
if numNodesPerHost == 1:
mx = '3g'
elif numNodesPerHost == 2:
mx = '1536m'
elif numNodesPerHost == 3:
mx = '1g'
elif numNodesPerHost == 4:
mx = '768m'
else:
showWarn = True
mx = '512m'
elif instance_type == 'm3.xlarge' or instance_type == 'r3.large' or instance_type == 'c3.2xlarge' or instance_type == 'r4.large':
if numNodesPerHost == 1:
mx = '6g'
elif numNodesPerHost == 2:
mx = '3g'
elif numNodesPerHost == 3:
mx = '2g'
elif numNodesPerHost == 4:
mx = '1536m'
elif numNodesPerHost == 5:
mx = '1g'
else:
showWarn = True
mx = '640m'
elif instance_type == 'm3.2xlarge' or instance_type == 'r3.xlarge' or instance_type == 'r3.2xlarge':
if numNodesPerHost == 1:
mx = '8g'
elif numNodesPerHost == 2:
mx = '6g'
elif numNodesPerHost == 3:
mx = '4g'
elif numNodesPerHost == 4:
mx = '3g'
elif numNodesPerHost == 5:
mx = '3g'
else:
showWarn = True
mx = '2g'
elif instance_type == 'i2.4xlarge' or instance_type == 'r3.4xlarge' or instance_type == 'r4.xlarge' or instance_type == 'r4.2xlarge':
if numNodesPerHost <= 4:
mx = '12g'
else:
showWarn = True
mx = '10g'
else:
_warn('Memory settings for %s instances not configured! Please update this script to set appropriate memory settings.' % instance_type)
if numNodesPerHost == 1:
mx = '8g'
elif numNodesPerHost == 2:
mx = '6g'
elif numNodesPerHost == 3:
mx = '4g'
else:
mx = '2g'
if showWarn:
_warn('%d nodes on an %s is probably too many! Consider using a larger instance type.' % (numNodesPerHost, instance_type))
mem_settings = ('-Xms%s -Xmx%s' % (mx, mx))
_info('Using Java heap settings: '+mem_settings)
return mem_settings
def _uptime(launch_time):
launchTime = dateutil.parser.parse(launch_time)
now = datetime.datetime.utcnow()
diff = now - launchTime.replace(tzinfo=None)
deltaStr = str(diff)
dotAt = deltaStr.find('.')
if dotAt != -1:
deltaStr = deltaStr[0:dotAt]
return ' for '+deltaStr
def _parse_env_data(envData):
cloudEnvVars = {}
for line in envData.split('\n'):
line = line.strip()
if len(line) == 0 or line.startswith('#'):
continue
if line.startswith('export '):
line = line[len('export '):]
eqAt = line.find('=')
if eqAt != -1:
name = line[0:eqAt].strip()
valu = line[eqAt+1:].strip()
if len(name) > 0 and len(valu) > 0:
if valu.startswith('"'):
valu = valu[1:]
if valu.endswith('"'):
valu = valu[0:len(valu)-1]
cloudEnvVars[name] = valu
return cloudEnvVars
def _read_cloud_env(cluster):
sstkEnvScript = _env(cluster, 'SSTK_ENV')
hosts = _lookup_hosts(cluster, False)
with settings(host_string=hosts[0]), hide('output', 'running', 'warnings'):
cloudEnvReader = _strio()
get(sstkEnvScript, cloudEnvReader)
envData = cloudEnvReader.getvalue()
return _parse_env_data(envData)
def _num_solr_nodes_per_host(cluster):
cloudEnv = _read_cloud_env(cluster)
return 1 if cloudEnv.has_key('NODES_PER_HOST') is False else int(cloudEnv['NODES_PER_HOST'])
def _rolling_restart_solr(cloud, cluster, solrHostsAndPortsToRestart=None, wait=0, overseer=None, pauseBeforeRestart=0, yjp_path=None):
remoteSolrDir = _env(cluster, 'solr_tip')
# determine which servers to patch if they weren't passed into this method
if solrHostsAndPortsToRestart is None:
hosts = _cluster_hosts(cloud, cluster)
numNodes = _num_solr_nodes_per_host(cluster)
activePorts = []
for n in range(0,numNodes):
activePorts.append(str(84 + n))
# upload the latest version of the script before restarting
# determine the active Solr nodes on each host
solrHostsAndPortsToRestart = {}
for host in hosts:
solrHostsAndPortsToRestart[host] = set([]) # set is important
with settings(host_string=host), hide('output', 'running', 'warnings'):
for port in activePorts:
if _fab_exists(remoteSolrDir + '/cloud' + port):
solrHostsAndPortsToRestart[host].add(port)
if len(solrHostsAndPortsToRestart) > 1 and overseer is None:
_info('Looking up overseer node')
try:
overseer = _lookup_overseer(cluster)
_info('Overseer running at %s' % overseer)
# strip _solr from the end
overseer = overseer[:len(overseer) - 5]
except:
_error('Unable to determine overseer leader, proceeding to restart cluster anyway')
counter = 0
nodesToRestart = []
is_private = _is_private_subnet(cluster)
zkHost = _read_cloud_env(cluster)['ZK_HOST']
remoteSolrJavaHome = _env(cluster, 'solr_java_home')
solrJavaMemOpts = _read_cloud_env(cluster)['SOLR_JAVA_MEM']
solrInSh = _get_solr_in_sh(cluster, remoteSolrJavaHome, solrJavaMemOpts, zkHost, is_private, yjp_path=yjp_path)
solrInShPath = remoteSolrDir+'/bin/solr.in.sh'
for solrHost in solrHostsAndPortsToRestart.keys():
# update the solr.in.sh file to the latest settings
with settings(host_string=solrHost), hide('output', 'running', 'warnings'):
run('rm -f '+solrInShPath)
_fab_append(solrInShPath, solrInSh)
for port in solrHostsAndPortsToRestart[solrHost]:
solrSrvr = '%s:89%s' % (solrHost, port)
nodesToRestart.append(solrSrvr)
# randomize the list of nodes to restart
# helps avoid restarting all nodes on the same host around the same time
_shuffle(nodesToRestart)
_status('Doing a rolling restart of %d nodes (which can take a while so be patient) ...' % len(nodesToRestart))
for solrSrvr in nodesToRestart:
if overseer is None or solrSrvr != overseer:
_status('\nRestarting Solr node on %s' % solrSrvr)
solrHost = solrSrvr.split(':')[0]
port = solrSrvr.split(':')[1][2:] # skip the 89 part
_restart_solr(cluster, solrHost, port, pauseBeforeRestart)
if int(wait) <= 0:
_status('Restarted ... waiting to see Solr come back up ...')
_wait_to_see_solr_up_on_hosts([solrSrvr], maxWait=180)
else:
_status('Restarted ... sleeping for '+str(wait)+' seconds before proceeding ...')
time.sleep(int(wait))
# give some incremental progress reporting as big clusters can take a long time to restart
counter += 1
if counter > 0 and counter % 5 == 0:
_info('Restarted %d nodes so far ...' % counter)
else:
if overseer is not None:
_warn('Skipping restart on overseer, will restart '+overseer+' last.')
if overseer is not None:
_status('Restarting Solr node on %s' % overseer)
overseerHost = overseer.split(':')[0]
overseerPort = overseer.split(':')[1][2:] # skip the 89 part
_restart_solr(cluster, overseerHost, overseerPort, 30) # force wait for new overseer to get elected after killing current
if int(wait) <= 0:
_status('Restarted ... waiting to see Solr come back up ...')
_wait_to_see_solr_up_on_hosts([overseer], maxWait=180)
else:
_status('Restarted ... sleeping for '+str(wait)+' seconds before proceeding ...')
time.sleep(int(wait))
is_solr_up(cluster)
_info('Rolling restart completed.')
def _setup_instance_stores(hosts, numInstStores, ami, xdevs):
numStores = int(numInstStores)
if numStores <= 0:
return
hvmAmiId = _env(None, 'AWS_HVM_AMI_ID')
for h in range(0,len(hosts)):
with settings(host_string=hosts[h]): #, hide('output', 'running', 'warnings'):
for v in range(0,numStores):
# get rid of the silly /mnt point which only sometimes gets
# setup correctly by Amazon
if ami == hvmAmiId and v == 0:
sudo('rm -rf /vol0')
sudo("sh -c 'if [ -d \"/mnt\" ]; then umount /mnt || true; rm -rf /mnt; fi'")
# mount the instance store device on the correct /vol disk
if _fab_exists('/vol%d' % v) is False:
sudo('mkfs -F -t ext4 /dev/%s || true' % xdevs[v])
sudo('mkdir /vol%d' % v)
sudo('echo "/dev/%s /vol%d ext4 defaults 0 2" >> /etc/fstab' % (xdevs[v], v))
sudo('mount /vol%d' % v)
# grant ownership to our ssh user
sudo('chown -R %s: /vol%d' % (ssh_user, v))
# TODO: collectd stuff is still useful, but meta node is replaced by Fusion
def _integ_host_with_meta(cluster, host, metaHost):
# setup logging on the Solr server based on whether there is a meta host
# running rabbitmq and the logstash4solr stuff
if metaHost is not None:
log4jCfg = _gen_log4j_cfg(host, metaHost, 'WARN')
else:
log4jCfg = _gen_log4j_cfg()