blib/script/gbrowse_aws_balancer.pl untested

filter: Statementstmt 0.0% 0 / 32 Branchbran 0.0% 0 / 4 Conditioncond 0.0% 0 / 19 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 5 Podpod n/a totaltotal 0.0% 0 / 60 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 #!/usr/local/bin/perl
2  
3 =head1 NAME
4  
5 gbrowse_aws_balancer.pl Load balance GBrowse using Amazon Web Service instances
6  
7 =head1 SYNOPSIS
8  
9 Launch the balancer in the foreground
10  
11 % gbrowse_aws_balancer.pl --conf /etc/gbrowse2/aws_balancer.conf \
12 --access_key XYZZY \
13 --secret_key Plugh
14  
15 Launch the balancer in the background as a daemon:
16  
17 % gbrowse_aws_balancer.pl --background \
18 --conf /etc/gbrowse2/aws_balancer.conf \
19 --access_key XYZZY \
20 --secret_key Plugh \
21 --logfile /var/log/gbrowse/aws_balancer.log \
22 --pidfile /var/run/aws_balancer.pid \
23 --user nobody
24  
25 Kill a running balancer daemon:
26  
27 % gbrowse_aws_balancer.pl --kill \
28 --conf /etc/gbrowse2/aws_balancer.conf \
29 --access_key XYZZY \
30 --secret_key Plugh \
31 --logfile /var/log/gbrowse/aws_balancer.log \
32 --pidfile /var/run/aws_balancer.pid \
33 --user nobody
34  
35 Use the init script:
36  
37 % sudo /etc/init.d/gbrowse-aws-balancer start
38 % sudo /etc/init.d/gbrowse-aws-balancer restart
39 % sudo /etc/init.d/gbrowse-aws-balancer stop
40 % sudo /etc/init.d/gbrowse-aws-balancer status
41  
42 Synchronize the master with the slave image:
43  
44 % sudo gbrowse_sync_aws_slave.pl -c /etc/gbrowse2/aws_balancer.conf
45 syncing data....done
46 data stored in snapshot(s) snap-12345
47 updated conf file, previous version in /etc/gbrowse2/aws_balancer.conf.bak
48  
49 =head1 DESCRIPTION
50  
51 This script launches a process that monitors the load on the local
52 GBrowse instance. If the load exceeds certain predefined levels, then
53 it uses Amazon web services to launch one or more GBrowse slave
54 instances. The work of rendering tracks is then handed off to these
55 instances, reducing the load on the local instance. Slave instances
56 are implemented using Amazon's spot instance mechanism, which allows
57 you to run EC2 instances at a fraction of the price of a standard
58 on-demand instance.
59  
60 Load balancing is most convenient to run in conjunction with a GBrowse
61 instance running within the Amazon Web Service EC2 cloud, but it can
62 also be used to supplement an instance running on local hardware. The
63 sections below describe the configuration needed for these two
64 scenarios.
65  
66 Note that this script requires you to have an Amazon Web Services
67 account, and for the VM::EC2 Perl module to be installed on the
68 machine that is running this script.
69  
70 =head1 COMMAND-LINE OPTIONS
71  
72 Options can be abbreviated. For example, you can use -a for
73 --access_key:
74  
75 --access_key EC2 access key
76 --secret_key EC2 secret key
77 --conf Path to balancer configuration file
78 --pidfile Path to file that holds daemon process ID
79 --logfile Path to file that records log messages
80 --user User to run daemon under (script must be
81 started as root)
82 --verbosity Logging verbosity. 0=least, 3=most.
83 --background Go into the background and run as daemon.
84 --kill Kill a previously-launched daemon. Must provide
85 the same --pidfile argument as used when
86 the daemon was started.
87 --ssh_key Enable ssh login on the slave(s) using the specified
88 AWS ssh keypair. Login will only be available
89 from the host this script is run on.
90  
91 =head1 PREREQUISITES
92  
93 1. You must have the Perl modules VM::EC2 (v1.21 or later), and
94 Parse::Apache::ServerStatus installed on the machine you intend to run
95 the balancer on. The balancer must run on the same machine that
96 GBrowse is running on. To install these modules, run:
97  
98 perl -MCPAN -e 'install VM::EC2; install Parse::Apache::ServerStatus'
99  
100 2. You must have an account on Amazon Web Services and must be
101 familiar with using the AWS Console to launch and terminate EC2
102 instances. If you run GBrowse on local hardware, then you will need to
103 provide the script with your access key and secret access key when
104 launching it. It may be safer to create and use an IAM user (Identity
105 and Access Management) who has more limited privileges. See
106 L<CONFIGURATION> below for some suggestions.
107  
108 3. GBrowse must be running under Apache.
109  
110 4. Apache must be configured to enable the mod_status module and to
111 allow password-less requests to this module from localhost
112 (http://httpd.apache.org/docs/2.2/mod/mod_status.html). This is the
113 recommended configuration:
114  
115 <IfModule mod_status.c>
116 ExtendedStatus on
117 <Location /server-status>
118 SetHandler server-status
119 Order deny,allow
120 Deny from all
121 Allow from 127.0.0.1 ::1
122 </Location>
123 </IfModule>
124  
125 5. If you are running GBrowse on local hardware, the local hardware
126 must be connected to the Internet or have a Virtual Private Cloud
127 (VPC) connection to Amazon.
128  
129 =head1 THE CONFIGURATION FILE
130  
131 The balancer requires a configuration file, ordinarily named
132 aws_balancer.conf and located in the GBrowse configuration directory
133 (e.g. /etc/gbrowse2). The configuration file has three sections:
134  
135 =head2 [LOAD TABLE]
136  
137 This section describes the number of slave instances to launch for
138 different load levels. It consists of a three-column space-delimited
139 table with the following columns:
140  
141 <requests/sec> <min instances> <max instances>
142  
143 For example, the first few rows of the default table reads:
144  
145 0.1 0 1
146 0.5 0 2
147 1.0 1 3
148 2.0 2 4
149  
150 This is read as meaning that when the number of requests per second on
151 the GBrowse server is greater than 0.1 but less than 0.5, run at least
152 0 slave servers but no more than 1 slave server. When the number of
153 requests is between 0.5 and 1.0, run between 0 and 2 slave
154 instances. When the rate is between 1.0 and 2.0, run at least 1 slave
155 instance, but no more than 3. Load levels below the lowest value on
156 the table (0.1 in this case) will run no slave servers, while levels
157 above the highest value on the table (2.0) will launch the minimum and
158 maximum number of slaves for that load value (between 2 and 4 in this
159 case).
160  
161 The reason for having a range of instance counts for each load range
162 is to avoid unecessarily launching and killing slaves repeatedly when
163 the load fluctuates around the boundary. You may wish to tune the
164 values in this table to maximize the performance of your GBrowse
165 installation.
166  
167 Note that the server load includes both GBrowse requests and all other
168 requests on the web server. If this is a problem, you may wish to run
169 GBrowse on a separate Apache port or virtual host.
170  
171 =head2 [MASTER]
172  
173 The options in this sections configure the master GBrowse
174 instance. Three options are recognized:
175  
176 =over 4
177  
178 =item external_ip (optional)
179  
180 This controls the externally-visible IP address of the GBrowse master,
181 which is needed by the firewall rule for master/slave
182 communications. This option can usually be left blank: when the master
183 is running on EC2, then the IP address is known; when the master is
184 running on a local machine, the externally-visible IP address is
185 looked up using a web service. It is only in the rare case that this
186 lookup is incorrect that you will need to configure this option
187 yourself.
188  
189 The external IP that the balancer script finds can be seen in a log
190 message when verbosity is 2 or higher.
191  
192 =item poll_interval (required)
193  
194 This is the interval, in minutes, that the balancer script will
195 periodically check the Apache load and adjust the number of slave
196 instances. The suggested value is 0.5 (30s intervals).
197  
198 =item server_status_url (required)
199  
200 This is the URL to call to fetch the server load from Apache's
201 server_status module.
202  
203 =back
204
205 =head2 [SLAVE]
206  
207 The options in this section apply to the render slaves launched by the
208 balancer.
209  
210 =over 4
211  
212 =item instance_type (required)
213  
214 This is the EC2 instance type. Faster instances give better
215 performance. High-IO instances give the best performance, but cost
216 more.
217  
218 =item spot_bid (required)
219  
220 This is the maximum, in US dollars, that you are willing to pay per
221 hour to run a slave spot instance. Typically you will pay less than
222 the bid price. If the spot price increases beyond the maximum bid,
223 then the spot instances will be terminated and the balancer will wait
224 until the spot price decreases below the maximum bid before launching
225 additional slaves.
226  
227 =item ports (required)
228  
229 This is a space-delimited list of TCP port numbers on which the render
230 slaves should listen for incoming render requests from the
231 master. Generally it is only necessary to listen on a single port;
232 multiple ports were supported for performance reasons in earlier
233 single-threaded versions of the slave.
234  
235 =item region (required for local masters)
236  
237 The Amazon region in which to launch slaves. When the master is
238 running in EC2, this is automatically chosen to be the same as the
239 master's region and can be left blank.
240  
241 =item image_id (required for local masters)
242  
243 This is the ID of the AMI that will be used to launch slaves. The
244 correct value will be filled in when you run the
245 gbrowse_sync_aws_slave.pl. You can leave this value blank if the
246 GBrowse master is being run within an EC2 instance, in which case the
247 slave will be launched using the same AMI that was used to launch the
248 master.
249  
250 =item data_snapshots (required for local masters)
251  
252 Before launching the slave, attach EBS volumes created from one or
253 more volume snapshots listed in this option. Multiple snapshots can be
254 attached by providing a space-delimited list:
255  
256 data_snapshots = snap-12345 snap-abcdef
257  
258 The gbrowse_sync_aws_slave.pl script will automatically maintain this
259 option for you.
260  
261 =item availability_zone (optional)
262  
263 This option will force the slave into the named availability zone. If
264 not specified, an availability zone in the current region will be
265 chosen at random.
266  
267 =item subnet (optional)
268  
269 If you are in a VPC environment, then this option will force the slave
270 into the named subnet. Ordinarily the balancer script will launch
271 slaves into non-VPC instances if the master is running on local
272 hardware or a non-VPC EC2 instance. The balancer will launch slaves
273 into the same VPC subnet as the master if the master is running on a
274 VPC instance.
275  
276 =item security_group (optional)
277  
278 This specifies the security group to assign the slaves to. If not
279 specified, a properly-configured security group will be created as
280 needed and destroyed when the balancer script exits. If you choose to
281 manage the security group manually, be sure to configure the firewall
282 ingress rule to allow access to the slave port(s) (see the "ports"
283 option) from the master's group or IP address.
284  
285 =back
286  
287 =head1 CONFIGURING AWS CREDENTIALS
288  
289 To work, the balancer script must be able to make spot instance
290 requests and to monitor and terminate instances. To perform these
291 operations the script must have access to the appropriate AWS
292 credentials (access key and secret key) on the command line or as
293 environment variables.
294  
295 While the script does its best to shield the credentials from prying
296 eyes, there is still a chance that the credentials can be intercepted
297 by another party with login access to the machine that the master runs
298 on and use the credentials to run up your AWS bill. For this reason
299 some people will prefer to create an EC2 account or role with limited
300 access to AWS resources.
301  
302 =over 4
303  
304 =item 1. Your personal EC2 credentials
305  
306 You may provide the balancer script with --access_key and --secret_key
307 command line arguments using your personal EC2 credentials or set the
308 environment variables EC2_ACCESS_KEY and EC2_SECRET_KEY. If not
309 provided, the script will interactively prompt for one or both of
310 these values.
311  
312 This is the simplest method, but has the risk that if the credentials
313 are intercepted by a malicious third party, he or she gains access to
314 all your EC2 resources.
315  
316 =item 2. The credentials of a restricted IAM account
317  
318 You may use the Amazon AWS console to create an IAM (Identity Access
319 and Management) user with restricted permissions, and provide that
320 user's credentials to the script on the command line or with
321 environment variables. The following IAM permission policy is the
322 minimum needed for the balancer script to work properly:
323  
324 {
325 "Statement": [
326 {
327 "Sid": "BalancerPolicy",
328 "Action": [
329 "ec2:AuthorizeSecurityGroupEgress",
330 "ec2:AuthorizeSecurityGroupIngress",
331 "ec2:CreateSecurityGroup",
332 "ec2:DeleteSecurityGroup",
333 "ec2:DescribeAvailabilityZones",
334 "ec2:DescribeImageAttribute",
335 "ec2:DescribeImages",
336 "ec2:DescribeInstances",
337 "ec2:DescribeInstanceAttribute",
338 "ec2:DescribeInstanceStatus",
339 "ec2:DescribeSecurityGroups",
340 "ec2:DescribeVolumes",
341 "ec2:DescribeSnapshots",
342 "ec2:DescribeSpotInstanceRequests",
343 "ec2:RequestSpotInstances",
344 "ec2:CreateKeyPair",
345 "ec2:DescribeKeyPairs",
346 "ec2:DeleteKeyPair",
347 "ec2:RunInstances",
348 "ec2:TerminateInstances",
349 "ec2:CreateSnapshot",
350 "ec2:CreateVolume",
351 "ec2:CreateTags",
352 "ec2:DeleteTags"
353 ],
354 "Effect": "Allow",
355 "Resource": [
356 "*"
357 ]
358 }
359 ]
360 }
361  
362 Note that even with these restrictions, an unauthorized user with
363 access to the credentials could still launch a large number of spot
364 instances or terminate bona fide instances. This is just a fundamental
365 limitation of the granularity of EC2's permissions system.
366  
367 =item 3. Create an IAM role
368  
369 If the master is running on an EC2 instance, then the most convenient
370 way to pass credentials is by assigning the instance an IAM role. The
371 balancer script can then obtain temporary credentials by making
372 internal EC2 calls. The credentials do not need to be provided on the
373 command line or in environment variables, and are only valid for short
374 periods of time, limiting the effect of theft.
375  
376 First, create an IAM role using the Amazon Console. Select
377 IAM->Roles->Create New Role, and give the role the name
378 "GBrowseMaster" (or whatever you prefer).
379  
380 Next, when prompted for the role type, select AWS Service
381 Roles->Amazon EC2.
382  
383 On the Select Role Permissions screen, choose "Custom Policy". Give
384 the policy a name like "GBrowseBalancer" and cut and paste into the
385 Policy Document text field the permission policy listed above in the
386 instructions for creating a restriced IAM account. Be sure to remove
387 the whitespace before the beginning of the first curly brace, or the
388 console will complain about an invalid policy.
389  
390 You only need to do this once. After this, whenever you launch an
391 instance that will run the GBrowse master (typically from a GBrowse
392 AMI), specify the "GBrowseMaster" IAM role name. This can be done from
393 the AWS console's instance launch wizard, or by passing the -p option
394 to the ec2-run-instances command-line tool.
395  
396 =back
397  
398 =head1 USING THE INIT SCRIPT
399  
400 The gbrowse-aws-balancer init script can be used on Ubuntu and
401 Debian-based systems to simplify launching the balancer at boot
402 time. It can be found in /etc/init.d by default, and is called in the
403 following manner:
404  
405 start the service
406 % sudo /etc/init.d/gbrowse-aws-balancer start
407  
408 stop the service
409 % sudo /etc/init.d/gbrowse-aws-balancer stop
410  
411 stop and restart the service
412 % sudo /etc/init.d/gbrowse-aws-balancer restart
413  
414 show the status of the service (running, stopped)
415 % sudo /etc/init.d/gbrowse-aws-balancer status
416  
417 The various script options are all set in a single configuration file
418 named /etc/default/gbrowse-aws-balancer. The distribution contents of
419 this file looks like this:
420  
421 DAEMON=/usr/local/bin/gbrowse_aws_balancer.pl
422 USER=www-data
423 RUNDIR=/var/run/gbrowse
424 LOGDIR=/var/log/gbrowse
425 CONFFILE=/etc/gbrowse2/aws_balancer.conf
426 ACCESS_KEY=YOUR_EC2_ACCESS_KEY_HERE
427 SECRET_KEY=YOUR_EC2_SECRET_KEY_HERE
428 VERBOSITY=3
429  
430 The variables in this file set the location of the balancer script,
431 the location of its configuration file, the verbosity to run with, and
432 where to write the script's process ID and log information. In
433 addition, you can place your (or another authorized user's) EC2 access
434 and secret key in this file. Please make sure that this file is only
435 readable by root.
436  
437 =head1 DEBUGGING SLAVE PROBLEMS
438  
439 If slaves are returning track renderinge errors, then there is likely
440 an issue with data synchronization. This typically happens when the
441 data on the master differs from the data on the slave, or path names
442 are different on the two systems.
443  
444 To debug this, launch the script with the -ssh_key option:
445  
446 % gbrowse_aws_balancer.pl --conf /etc/gbrowse2/aws_balancer.conf \
447 --access_key XYZZY \
448 --secret_key Plugh \
449 --ssh_key John_Doe_default
450  
451 You may then ssh into the slave using the specified ssh key and the
452 username "admin". A useful thing to do is to tail the slave log file:
453  
454 ssh -i .ssh/John_Doe_default admin@54.280.19.203 \
455 tail -f /var/log/gbrowse/gbrowse_slave
456  
457 Replace the IP number with the correct IP number of one of the running
458 slaves, which you can find in /etc/gbrowse2/renderfarm.conf.
459  
460 =head1 THE GBROWSE_SYNC_AWS_SLAVE.PL SCRIPT
461  
462 The gbrowse_sync_aws_script.pl script should be run on the master each
463 time you add a new database to an existing data source, or if you add
464 a whole new data source. What it does is to prepare a new Amazon EBS
465 snapshot containing a copy of all the data needed for the GBrowse
466 slave to run. This snapshot is then attached to new slave instances.
467  
468 After running, it updates the conf file with the current versions of
469 the slave AMI and the data snapshot.
470  
471 % sudo gbrowse_sync_aws_script.pl --conf /etc/gbrowse2/aws_balancer.conf \
472 --mysql /var/lib/mysql \
473 --postgres /var/lib/postgresql
474  
475 The --conf argument is required. The script will create a snapshot of
476 the appropriate size, mount it on a temporary staging instance, and
477 rsync a copy of your gbrowse databases directory
478 (e.g. /var/lib/gbrowse2/databases) to the snapshot. If you have
479 created mysql or postgres databases, you must also give the paths to
480 their database file directories, as shown in the example.
481  
482 Note that ALL your mysql and postgres data files located on the server
483 will be copied; not just those used for track display.
484  
485 =head1 ENVIRONMENT VARIABLES
486  
487 The following environment variables are used if the corresponding
488 command line options are not present:
489  
490 EC2_ACCESS_KEY AWS EC2 access key
491 EC2_SECRET_KEY AWS EC2 secret key
492  
493 =head1 SEE ALSO
494  
495 L<VM::EC2>, L<VM::EC2::Staging::Manager>
496  
497 =head1 AUTHOR
498  
499 Lincoln Stein, lincoln.stein@gmail.com
500  
501 Copyright (c) 2012 Ontario Institute for Cancer Research
502
503 This package and its accompanying libraries is free software; you can
504 redistribute it and/or modify it under the terms of the GPL (either
505 version 1, or at your option, any later version) or the Artistic
506 License 2.0. Refer to LICENSE for the full license text. In addition,
507 please see DISCLAIMER.txt for disclaimers of warranty.
508  
509 =cut
510  
511 use strict;
512 use Getopt::Long;
513 use GBrowse::ConfigData;
514 use File::Spec;
515 use Bio::Graphics::Browser2::Render::Slave::AWS_Balancer;
516  
517 my $balancer;
518  
519 # this obscures the AWS secrets from ps; it is not 100% effective
520 my $program = $0;
521 ($0 = "$0 @ARGV") =~ s/(\s--?[as]\S*?)(=|\s+)\S+/$1$2xxxxxxxxxx/g;
522  
523 $SIG{TERM} = sub {exit 0};
524 $SIG{INT} = sub {exit 0};
525  
526 my($ConfFile,$AccessKey,$SecretKey,$PidFile,$LogFile,$Daemon,$User,$Verbosity,$Kill,$SshKey);
527 GetOptions(
528 'access_key=s' => \$AccessKey,
529 'secret_key=s' => \$SecretKey,
530 'conf=s' => \$ConfFile,
531 'pidfile=s' => \$PidFile,
532 'logfile=s' => \$LogFile,
533 'user=s' => \$User,
534 'verbosity=i' => \$Verbosity,
535 'kill' => \$Kill,
536 'background' => \$Daemon,
537 'ssh_key' => \$SshKey,
538 ) or exec 'perldoc',$program;
539  
540 $ConfFile ||= File::Spec->catfile(GBrowse::ConfigData->config('conf'),'aws_balancer.conf');
541  
542 $balancer = Bio::Graphics::Browser2::Render::Slave::AWS_Balancer->new(
543 -conf => $ConfFile,
544 -access_key => $AccessKey||'',
545 -secret_key => $SecretKey||'',
546 -logfile => $LogFile||'',
547 -pidfile => $PidFile||'',
548 -user => $User||'',
549 -daemon => $Daemon||0,
550 -ssh_key => $SshKey||undef,
551 );
552  
553 $Verbosity = 3 unless defined $Verbosity;
554 $balancer->verbosity($Verbosity);
555 if ($Kill) {
556 $balancer->stop_daemon();
557 } else {
558 $balancer->run();
559 }
560  
561 exit 0;
562