-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathprj
executable file
·1114 lines (880 loc) · 28.2 KB
/
prj
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/env perl
use strict;
use warnings;
use Data::Dump ();
use Getopt::Long qw( :config require_order pass_through );
use HTTP::Tiny;
use JSON::MaybeXS;
use Path::Tiny;
use Time::Moment;
my @rules_prj_locations = ([], ['devops'], ['dev', 'ops', 'etc']);
my %opts = (
verbose => 0,
quiet => 0,
current => 0,
);
my $ok = GetOptions(
\%opts, "help", "verbose+", "quiet", "completion", "current", "dryrun|n", "restart",
"stash", "filter=s@", "host=s", "quick", "logs"
);
usage() unless $ok;
usage() if $opts{help};
usage() unless @ARGV;
$opts{restart} = 1 if exists $opts{filter} and $opts{filter};
dispatch_command(@ARGV);
####################
# Command dispatcher
sub dispatch_command {
my ($cmd, @args) = @_;
if ($cmd eq 'deploy') {
my $pcfg = load_cfg();
deploy($pcfg, @args);
}
elsif ($cmd eq 'environments') {
my $pcfg = load_cfg();
environments($pcfg);
}
elsif ($cmd eq 'setup_bash_complete') {
setup_bash_completion();
}
else {
usage("Command '$cmd' not understood");
}
return;
}
################
# Deploy command
sub deploy {
my ($pcfg, $env, @rest) = @_;
my $root = project_root();
my $pname = $pcfg->{project}{name} || $root->basename;
usage('Deploy requires an environment as parameter.',
'Valid values are: ' . join(', ', sort grep {$_} keys %{ $pcfg->{environments} }))
unless defined $env;
### Start from a good place
chdir($root);
### Decide which environment to use
my $ecfg = $pcfg->{environments}{$env};
usage("Environment '$env' not found in rules.prj") unless $ecfg;
debug("Using environment '$env'");
$ecfg = { %{ $pcfg->{defaults} || {} }, %$ecfg };
### Stash if we should
system('git', 'stash', '-u') if $opts{stash} or $ecfg->{stash};
### Prepare base rsync command to run
my $rsync = _generate_rsync_command($pcfg, $ecfg);
### Hosts to use
my $hosts = delete($ecfg->{hosts}) || delete($ecfg->{host});
$hosts = [$hosts] if $hosts and ref($hosts) ne 'ARRAY';
$hosts = [] unless $hosts;
my @hosts = @$hosts;
fatal("Environment '$env' missing 'host' or 'hosts' entry: ", $ecfg)
unless @hosts;
### Check for proper branch
if (my $branch_name = delete $ecfg->{branch}) {
my $cur_branch = _current_branch_name();
fatal("Current branch '$cur_branch' not the expected one '$branch_name")
unless $cur_branch eq $branch_name;
}
### Check for tags
_tag_release($env) if delete $ecfg->{tag};
### Describe the current release
my @release_info;
for my $cmd ('git rev-parse --short HEAD', 'pwd', 'git show --stat') {
push @release_info, scalar(`$cmd`);
chomp $release_info[-1];
}
_write_control_file('.release', @release_info);
_write_control_file('.release_version', my $version = $release_info[0]);
_write_control_file('.deployed_env', $env);
_write_control_file('.release_restart', 'restart') if $opts{restart};
### If we use git and we have submodules, make sure they are up-to-date
if (-d '.git' and -f '.gitmodules') {
debug('Updating git submodules');
unless ($opts{dryrun}) {
system('git', 'submodule', 'update', '--recursive', '--init') and die "FATAL: git submodule update failed\n";
}
}
## run pre-deploy script
my @pre_deploy_cmds = grep { defined() } ($pcfg->{pre_deploy}, $ecfg->{pre_deploy});
for my $cmd (@pre_deploy_cmds) {
$cmd = [$cmd] unless ref($cmd);
debug('Pre deploy command:', @$cmd);
unless ($opts{dryrun}) {
system(@$cmd) and die "FATAL: pre_deploy script failed\n";
}
}
### rsync to each one
info("Deploying project '$pname'");
foreach my $hcfg (@hosts) {
$hcfg = { host => $hcfg } unless ref($hcfg) eq 'HASH';
$hcfg = { %$ecfg, %$hcfg }; ## Merge all configs!
fatal("Env '$env' with missing 'host'") unless my $host = $hcfg->{host};
fatal("Env '$env' with missing 'path'") unless my $path = $hcfg->{path};
## Skip it, something is wrong
if ($hcfg->{skip}) {
info("Skipping host '$hcfg->{host}', reason: $hcfg->{skip}");
next;
}
## prepare post-deploy script
my $post_deploy_script = _create_post_deploy_script($hcfg, $version, $env, @rest);
## define our SSH command
my @ssh_cmd = ('ssh', '-A');
push @ssh_cmd, '-o', 'ControlMaster=auto', '-o', 'ControlPath=/tmp/ssh-controlmaster-%h-%p-%r', '-o',
'ControlPersist=3600'
unless $hcfg->{skip_ssh_control_master} or $ENV{PRJ_OPT_SKIP_SSH_CONTROL_MASTER};
my $host_info = $host->{host};
if (my $user = $hcfg->{user}) {
push @ssh_cmd, '-l', $user;
$host_info = "$user\@$host_info";
}
if (my $port = $hcfg->{port}) {
push @ssh_cmd, '-p', $port;
$host_info .= ":$port";
}
if (my $key = $hcfg->{key}) {
push @ssh_cmd, '-i', _find_ssh_key($host_info, $key);
}
$host_info = "host '$host_info'";
## Prepare and do the rsync
my @cmd = (@$rsync, '-e', join(' ', @ssh_cmd));
push @cmd, "$host:$path";
$host_info .= ", path '$path'";
info(".... targetting $host_info");
if ($opts{host} and $host_info !~ m/$opts{host}/) {
info("........ SKIP this host, '--host $opts{host}' doesn't match");
next;
}
debug('Rsync command:', \@cmd);
info("........ deploy files");
system(@cmd) unless $opts{dryrun};
## Run post-deploy script
if ($opts{quick}) {
info("........ skip post-deploy script, --quick is in effect");
}
else {
info("........ run post-deploy script");
if ($opts{verbose}) { push(@ssh_cmd, '-v') }
else { push(@ssh_cmd, '-q') }
push @ssh_cmd, '-t', $host, "cd '$path' && PRJ_ROOT='$path' PRJ_HOST='$host' ./$post_deploy_script '$env'";
debug('Post deploy command:', \@ssh_cmd);
unless ($opts{dryrun}) {
my $err = system(@ssh_cmd);
fatal("post deploy script exited != 0: $err") if $err;
}
}
}
### run cleanup-deploy script
my @cleanup_cmds = grep {defined} ($ecfg->{cleanup_deploy}, $pcfg->{cleanup_deploy});
for my $cmd (@cleanup_cmds) {
$cmd = [$cmd] unless ref($cmd);
debug('Cleanup deploy command:', @$cmd);
unless ($opts{dryrun}) {
system(@$cmd) and die "FATAL: cleanup_deploy script failed\n";
}
}
### Stash if we should
system('git', 'stash', 'pop') if $opts{stash} or $ecfg->{stash};
### Do notifications after the deploy
notify(
{ pcfg => $pcfg,
ecfg => $ecfg,
msg => "Sucessfully deployed '$env' env, for project '$pname', commit $release_info[0]",
project_name => $pname,
env => $env,
commit => $release_info[0],
workdir => $release_info[1],
commit_message => $release_info[2],
}
);
return;
}
sub _create_post_deploy_script {
my ($host, $version, $env, @rest) = @_;
my $script = <<'EOS';
#!/bin/bash
deploy_env="$1"
if [ -z "$deploy_env" ] ; then
echo "**** FATAL: post_deploy.sh requires a single parameter, the environment"
exit 1
fi
set -e
EOS
$script .= "set -x\n" if $opts{verbose};
$script .= "PRJ_ENV='$env'\nPRJ_DEPLOY_VERSION='$version'\n";
$script .= "PRJ_USE_CURRENT='$version'\n" if $opts{current};
$script .= "PRJ_RESTART=1\n" if exists $opts{restart};
$script .= "PRJ_RESTART_LOGS=1\n" if exists $opts{logs};
if (exists $opts{filter} and $opts{filter}) {
my $filter = $opts{filter};
$filter = [$filter] unless ref($filter);
$filter = join('|', @$filter);
$script .= "PRJ_RESTART_FILTER='$filter'\n";
}
$script .= "export PRJ_ENV PRJ_DEPLOY_VERSION PRJ_USE_CURRENT PRJ_RESTART PRJ_RESTART_LOGS PRJ_RESTART_FILTER\n";
if (my $aws_profile = $host->{aws_profile}) {
my $k = _load_aws_credentials($aws_profile);
fatal("could not load AWS profile '$aws_profile'") unless $k->{aws_access_key_id} and $k->{aws_secret_access_key};
$script .= "AWS_ACCESS_KEY_ID='$k->{aws_access_key_id}'\n";
$script .= "AWS_SECRET_ACCESS_KEY='$k->{aws_secret_access_key}'\n";
$script .= "AWS_DEFAULT_REGION='$k->{region}'\n" if $k->{region};
$script .= "export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_DEFAULT_REGION\n";
}
if (my $envs = $host->{environment}) {
$envs = [$envs] unless ref($envs) eq 'ARRAY';
my @to_export;
for my $e (@$envs) {
for my $k (keys %$e) {
$script .= "$k=$e->{$k}\n";
push @to_export, $k;
}
}
$script .= "export @to_export\n";
}
$script .= "cd \"\$HOME\"\n";
if ($host->{perl_version} or $host->{install_cpan_deps} or $host->{use_carton}) {
$script .= <<'EOS';
if [ -e ./.plenv ] ; then
USE_PLENV=1
PATH="$HOME/.plenv/bin:$PATH"
export USE_PLENV PATH
eval "$(plenv init -)"
else
if [ -e ./.perlbrew/init ] ; then
source ./.perlbrew/init
fi
if [ -z "$PERLBREW_ROOT" ] ; then
## FIXME: should try more places...
PERLBREW_ROOT=/home/spencer/perl5/perlbrew
export PERLBREW_ROOT
fi
if [ -e "$PERLBREW_ROOT/etc/bashrc" ] ; then
source $PERLBREW_ROOT/etc/bashrc
fi
EOS
if (my $pv = $host->{perl_version}) {
## FIXME: should we remove release/deps/ whenever we create a new
## perlbrew lib to make sure all deps are recompiled to newest perl?
$script .= "if [ ! -d './.perlbrew/libs/$pv' ] ; then\n";
$script .= " perlbrew lib create $pv\n";
$script .= " perlbrew switch $pv\n";
$script .= " if [ -d './service/.s6-svscan' ] ; then\n";
$script .= " /command/s6-svscanctl -t service\n";
$script .= " fi\n";
$script .= "fi\n";
$script .= "perlbrew switch $pv\n";
}
$script .= "fi\n"; ## else use perlbrew
}
$script .= "cd '$host->{path}'\n\n";
if (my $pv = $host->{perl_version}) {
$script .= 'if [ -n "$USE_PLENV" ] ; then' . "\n";
$script .= " plenv local \"$host->{perl_version}\"\n";
$script .= "fi\n";
}
if ($host->{install_cpan_deps}) {
$script .= <<'EOS';
echo "** Installing CPAN dependencies"
curl --silent -o .cpanm -L http://cpanmin.us/
chmod 755 .cpanm
mkdir -p ../deps
submodules=""
if [ -d "elib" ] ; then
submodules=`find elib -maxdepth 1 -mindepth 1 -type d -print`
fi
for subdir in common "${deploy_env}" ; do
for root_dir in "." $submodules ; do
for deps_root in "$root_dir/dev/ops/etc/deps" "$root_dir/dev/ops/deps" ; do
echo " ... for directory ${deps_root}/${subdir}"
for cpanfile in `ls -1 ${deps_root}/${subdir}/*cpanfile 2>/dev/null` ; do
echo " ...... checking ${cpanfile}"
LANG= ./.cpanm -L ../deps --quiet --notest --cpanfile "${cpanfile}" --installdeps .
done
done
done
done
rm -f .cpanm
EOS
}
if (my $carton = $host->{use_carton}) {
if ($carton =~ m/^perl/) {
$script .= <<"EOS";
echo "** Temporarily switching to perl $carton to make carton happy"
perlbrew use '$carton'
EOS
}
$script .= <<'EOS';
echo "** Installing CPAN dependencies (using Carton)"
perl -v | head -3
perl `which cpanm` -n Carton ExtUtils::MakeMaker
perl `which carton` install --verbose --deployment || true
rm -rf local/cache
EOS
}
$script .= _generate_services_scripts(@_) if $host->{services_mgmt};
if (exists $host->{post_deploy} and $host->{post_deploy}) {
my $pds = join(' ', $host->{post_deploy}, @rest);
$script .= "echo '** Starting post-deploy script \"$pds\"'\n";
$script .= "( $pds )\n\n";
}
my $script_path = '.post-deploy.sh';
$script .= "rm -f '$script_path'\n\n";
$script =~ s/^ //gm; ## we used some indentation to make it easier to write, remove it now
_write_control_file($script_path, $script)->chmod(0755);
return $script_path;
}
sub _generate_services_scripts {
my ($host) = @_;
my $script = _gen_srv_utils(@_);
my @services = _scan_services();
return '' unless @services;
for my $srv (@services) {
my $name = $srv->{name};
my $scfg = load_json($srv->{spec_file});
my $cmd = $scfg->{cmd};
next unless $cmd;
$cmd =~ s/[\r\n]+/ /gsm;
$cmd =~ s/\Q{{ENV:\E(.+?)\Q}}\E/$ENV{$1}||'--ENV-$1-NOT-FOUND--'/gesm;
$cmd =~ s/\\/\\\\/gsm;
$cmd =~ s/"/\\"/gsm;
$script .= qq{ should_start_service="$cmd"\n};
$script .= _gen_check_tags($name, $scfg->{tags}) if $scfg->{tags};
my $app_name = $scfg->{application_name} || '';
my $logger = $scfg->{logger};
my $log_dir = $scfg->{log_dir} || "\$HOME/log/service";
my $require_log_dir;
if (!$logger) {
$logger = "/command/s6-log -bt \"$log_dir/\$service_name\"";
$require_log_dir = 1;
}
undef $logger if $scfg->{skip_logger};
$script .= <<"EOS";
if [ -n "\$should_start_service" ] ; then
mkdir -p "\$HOME/service/$name"
EOS
if ($logger) {
$script .= <<"EOS";
mkdir -p "\$HOME/service/$name/log"
echo '#!/bin/sh' > "\$HOME/service/$name/log/run.new"
echo 'app_name="$app_name"' >> "\$HOME/service/$name/log/run.new"
echo 'service_name="$name"' >> "\$HOME/service/$name/log/run.new"
echo 'export service_name' >> "\$HOME/service/$name/log/run.new"
echo 'export app_name' >> "\$HOME/service/$name/log/run.new"
EOS
if ($require_log_dir) {
$script .= qq{echo 'mkdir -p "$log_dir/$name"' >> "\$HOME/service/$name/log/run.new"\n};
}
$script .= <<"EOS";
echo 'exec $logger' >> "\$HOME/service/$name/log/run.new"
chmod 555 "\$HOME/service/$name/log/run.new"
mv -f "\$HOME/service/$name/log/run.new" "\$HOME/service/$name/log/run"
EOS
}
else { ## if we have a previous logger, we need to kill the entire service and rebuild it
$script .= <<"EOS";
if [ -e "\$HOME/service/$name/log" ] ; then
stop_service '$name'
fi
EOS
}
$script .= <<"EOS";
echo '#!/bin/sh' > "\$HOME/service/$name/run.new"
EOS
if ($scfg->{log_stderr}) {
$script .= <<"EOS";
echo "exec 2>&1" >> "\$HOME/service/$name/run.new"
EOS
}
if (my $e = $scfg->{env}) {
die "FATAL: invalid service, field 'env' must be an object/hashRef\n" unless ref($e) eq 'HASH';
while (my ($k, $v) = each %$e) {
$script .= <<"EOS";
echo "$k='$v'" >> "\$HOME/service/$name/run.new"
EOS
}
my $vars = join(' ', sort keys %$e);
$script .= <<"EOS";
echo "export $vars" >> "\$HOME/service/$name/run.new"
EOS
}
if ($scfg->{chdir_project}) {
$script .= <<"EOS";
echo "cd \"\$HOME/$host->{path}\"" >> "\$HOME/service/$name/run.new"
EOS
}
my $lock = '';
if (my $ln = $scfg->{lock_name}) {
$script .= <<"EOS";
echo "printf '** Lock service activated, key $ln, started at'" >> "\$HOME/service/$name/run.new"
echo "date" >> "\$HOME/service/$name/run.new"
EOS
$lock = "consul lock";
$lock .= " -n $scfg->{lock_workers}" if $scfg->{lock_workers} and $scfg->{lock_workers} =~ m/^\d+$/;
$lock .= " -token $scfg->{lock_token}" if $scfg->{lock_token};
$lock .= " '$ln'";
}
$script .= <<"EOS";
echo "exec $lock \$should_start_service" >> "\$HOME/service/$name/run.new"
chmod 555 "\$HOME/service/$name/run.new"
mv -f "\$HOME/service/$name/run.new" "\$HOME/service/$name/run"
start_service '$name'
else
stop_service '$name'
fi
EOS
}
$script .= _gen_cleanup_old_services();
return $script;
}
sub _scan_services {
my ($dir, $prefix) = @_;
$prefix ||= '';
$dir = path($dir || 'service');
my $it = $dir->iterator;
my @services;
while (my $srv = $it->()) {
my $name = $srv->basename;
if ($srv->is_dir and $name =~ m/^[a-zA-Z]/) {
push @services, _scan_services($srv, "${name}_");
}
elsif ($srv->is_file and $name =~ m/^([a-zA-Z][-\w\.]*)[.]json$/) {
push @services, { name => "$prefix$1", spec_file => $srv };
}
}
return @services;
}
sub _gen_srv_utils {
my ($host) = @_;
my $script = <<'EOS';
start_service () {
local srv="$1"
local srvs_dir="$HOME/service"
local srv_dir="$srvs_dir/$srv"
local log_srv_dir="$srv_dir/log"
EOS
if (!$host->{skip_automatic_restart}) {
$script .= <<'EOS';
## FIXME: what to do is $srv_dir/down exists? Maybe we should restart only if up?
if [ -e "$srv_dir/supervise" ] ; then
echo "... starting service '$srv'"
/command/s6-svc -ut "$srv_dir"
if [ -d "$log_srv_dir" ] ; then
/command/s6-svc -uh "$log_srv_dir"
fi
fi
EOS
}
$script .= <<'EOS';
echo "... rescan service dir, looking to start service '$srv'"
/command/s6-svscanctl -a "$srvs_dir"
touch "$srvs_dir/.$srv.is-active"
}
stop_service () {
local srv="$1"
local srvs_dir="$HOME/service"
local srv_dir="$srvs_dir/$srv"
local log_srv_dir="$srv_dir/log"
if [ -d "$srv_dir" ] ; then
echo "... stopping service '$srv' at '$srv_dir'"
mv "$srv_dir" "$srvs_dir/.$srv"
/command/s6-svscanctl -an "$srvs_dir"
# s6-svwait -d "$srvs_dir/.$srv"
# if [ -d "$srvs_dir/.$srv/log" ] ; then
# s6-svwait -d "$srvs_dir/.$srv/log"
# fi
sleep 1
rm -rf "$srvs_dir/.$srv"
rm -f "$srvs_dir/.$srv"
fi
}
EOS
return $script;
}
sub _gen_check_tags {
my ($name, $tags) = @_;
$tags = join(' ', map {"'$_'"} @$tags);
return <<"EOS";
found_tag=''
echo -n '... checking tags:'
for tag in $tags ; do
echo -n " \$tag"
if [ -e "/etc/orchid/tags/\$tag" ] ; then
echo -n ' (found!)'
found_tag="\$tag"
fi
done
echo
if [ -z "\$found_tag" ] ; then
echo "... no required tags found, skipping service '$name'"
should_start_service=''
fi
EOS
}
sub _gen_cleanup_old_services {
return <<'EOS';
srv_dir="$HOME/service"
if [ -d "$srv_dir" ] ; then
for srv in `ls -1 $srv_dir` ; do
if [ ! -e "$srv_dir/.$srv.is-active" ] ; then
echo "... service $srv not found in PROJECT/service/${srv}.json"
stop_service $srv
fi
rm -f "$srv_dir/.$srv.is-active"
done
fi
EOS
}
###################
# List environments
sub environments {
my ($pcfg) = @_;
my $pretty = sub { print @_, "\n" };
if (is_tty()) {
print "List of available environments:\n";
$pretty = sub { print ' * ', @_, "\n" };
}
$pretty->($_) for sort grep {$_} keys %{ $pcfg->{environments} || [] };
}
#########################
# Bash completion support
sub setup_bash_completion {
print <<'EOBC';
### bash-completion setup code for prj app
#
# Add
#
# prj_comp=`mktemp -t prj_completion.XXXXXXX`
# if [ -e "$prj_comp" ] ; then
# prj setup_bash_complete >> "$prj_comp"
# source "$prj_comp"
# rm -f "$prj_comp"
# fi
# unset prj_comp
#
# to your .bashrc or .bash_profile
_prj_complete()
{
local cur prev commands
_get_comp_words_by_ref cur prev
commands='deploy environments'
COMPREPLY=()
if [ $COMP_CWORD -eq 1 ] ; then
COMPREPLY=( $( compgen -W "$commands" -- "$cur" ) )
elif [ $COMP_CWORD -gt 1 -a "$prev" == "deploy" ] ; then
envs=`prj environments`
COMPREPLY=( $( compgen -W "$envs" -- "$cur" ) )
fi
}
complete -F _prj_complete -o default prj
EOBC
}
#######
# Usage
sub usage {
my ($msg, @others) = @_;
print STDERR <<EOU;
Usage: prj COMMAND ARGS
Available COMMAND's:
deploy deploys current version to an environment
environments list all the available environments
setup_bash_complete generate bash code for completion
EOU
print STDERR "ERROR: $msg\n" if $msg;
foreach my $err (@others) {
print ' => ', $err, "\n";
}
exit(1);
}
########
# Logger
sub info {
return if $opts{quiet};
return _log('INFO', @_);
}
sub debug {
return if $opts{quiet};
return unless $opts{verbose} > 1;
return _log('DEBUG', @_);
}
sub error {
return if $opts{quiet};
return _log('ERROR', @_);
}
sub fatal {
_log('FATAL', @_);
exit(1);
}
sub _log {
return unless is_tty();
my $tag = shift;
my $msg = join(' ', map { ref($_) ? Data::Dump::pp($_) : $_ } @_);
foreach my $line (split(/\n\r?/, $msg)) {
print STDERR "[$tag]: $line\n";
}
return;
}
#######
# Utils
sub is_tty { return -t \*STDOUT }
sub load_cfg {
my $root = project_root();
my @files = _search_config_files($root);
for my $file (@files) {
my $c = load_json($file);
return $c if defined $c;
}
fatal(join("\n * ", "Could not open any of these files for configuration:", @files));
}
sub load_json {
my ($file) = @_;
return unless $file->is_file;
return JSON::MaybeXS->new->relaxed->utf8->decode($file->slurp);
}
{
my $project_root;
sub project_root {
return $project_root if $project_root;
my $path = Path::Tiny->cwd;
my @dirs;
do {
push @dirs, $path;
my @files = _search_config_files($path);
$project_root = $path if @files;
fatal(join("\n * ", "Could not find project root, tried this directories:", @dirs))
if !$project_root and ($path eq $ENV{HOME} or $path eq Path::Tiny->rootdir);
$path = $path->parent;
} while (!$project_root);
return $project_root;
}
}
sub _search_config_files {
my ($root) = @_;
my @found;
for my $dir (@rules_prj_locations) {
for my $file ('.prj_rules', 'rules.prj') {
my $f = $root->child(@$dir, $file);
push @found, $f if $f->exists;
}
}
return @found;
}
sub _generate_rsync_command {
my ($pcfg, $ecfg) = @_;
my $rsync = $pcfg->{commands}{rsync} || 'rsync -a --delete';
$rsync = [split(/\s+/, $rsync)] if $rsync && !ref($rsync);
### Include excludes
my $excl = $pcfg->{paths}{exclude} || [
".git", ## No need to send source control
"elib/*/.git", ## No need to send source control
"elib/*/elib/*/.git", ## No need to send source control
"supervise", ## Supervise stuff
"main-*", ## Supervise stuff
"local", ## Perl deps
"node_modules", ## Node deps
".docker-perl-local", ## Perl deps when using docker
".vscode", ## editor files
];
$excl = [$excl] unless ref($excl) eq 'ARRAY';
if (my $more = $pcfg->{paths}{more_excludes}) {
$more = [$more] unless ref($more) eq 'ARRAY';
push @$excl, @$more;
}
if ($excl and @$excl) {
push @$rsync, map { ('--exclude', $_) } @$excl;
}
### Add common rsync options
push @$rsync, '-v' if $opts{verbose} || $ecfg->{verbose};
push @$rsync, '-n' if $opts{dryrun};
push @$rsync, project_root() . '/';
return $rsync;
}
################
## Notifications
sub notify {
my ($args) = @_;
my $pcfg = $args->{pcfg};
return if $opts{dryrun};
my $ncfg = $pcfg->{notify};
return unless $ncfg;
$ncfg = [$ncfg] unless ref($ncfg) eq 'ARRAY';
for my $agent (@$ncfg) {
if ($agent->{type} eq 'loggly') { notify_loggly($args, $agent) }
elsif ($agent->{type} eq 'hipchat') { notify_hipchat($args, $agent) }
elsif ($agent->{type} eq 'growl') { notify_growl($args, $agent) }
elsif ($agent->{type} eq 'osx') { notify_osx($args, $agent) }
elsif ($agent->{type} eq 'honeybadger') { notify_honebadger($args, $agent) }
}
return;
}
sub notify_honebadger {
my ($args) = @_;
my ($api_key) = do {
my ($line) = eval { path("$ENV{HOME}/.honeybadger")->lines };
chomp($line);
$line;
};
return error('failed to obtain HoneyBadger API key') unless $api_key;
my $req = {
environment => $args->{env},
local_username => (getpwuid($<))[0],
revision => $args->{commit},
repository => $args->{workdir},
};
my $res = _ua()->post(
'https://api.honeybadger.io/v1/deploys' => {
headers => {
'X-API-Key' => $api_key,
'Content-Type' => 'application/json',
'Accept' => 'application/json',
},
content => encode_json($req),
}
);
if ($res->{status} == 201) {
my $answer = eval { decode_json($res->{content}) };
if ($answer and $answer->{status} eq 'OK') {
info('Notification sent to HoneyBadger');
return;
}
}
return error("Failed to notify honeybadgers: $res->{status}");
}
sub notify_osx {
my ($args) = @_;
if (my $gn = _has_cmd('osascript')) {
my $cmd = "osascript -e 'display notification \"" . $args->{msg} . "\" with title \"prj deploy status\"'";
debug("Notification osx: $cmd");
system($cmd);
}
else {
error('Could not find osascript command line tool');
}
}
sub notify_growl {
my ($args) = @_;
if (my $gn = _has_cmd('growlnotify')) {
my @cmd = ($gn, '-m', $args->{msg}, 'prj deploy status');
debug("Notification growl: ", join(' ', @cmd));
system(@cmd);
}
else {
error('Could not find growlnotify command line tool');
}
}
sub notify_hipchat {
my ($args, $agent_cfg) = @_;
my $ua = _ua();
my $res = $ua->post_form(
'https://api.hipchat.com/v1/rooms/message?format=json&auth_token=' . $agent_cfg->{token},
{ room_id => $agent_cfg->{room_id},
from => $agent_cfg->{color} || 'prj cmd line',
message => "$args->{msg} (by $ENV{USER})",
message_format => 'text',
color => $agent_cfg->{color} || 'purple',
notify => exists $agent_cfg->{notify_room} ? $agent_cfg->{notify_room} : 1,
}
);
debug("Notification hipchat: status is $res->{status}");
if ($res->{status} == 200) {
my $answer = eval { decode_json($res->{content}) };
return if $answer and $answer->{status} eq 'sent';
}
error("Failed to notify hipchat: $res->{status} - $res->{content}");
}
sub notify_loggly {
my ($args, $agent_cfg) = @_;
my $tags = join(',', 'prjCodePush', @{ $agent_cfg->{tags} || [] });
my %clean = map { $_ => $args->{$_} } qw(workdir project_name msg env commit commit_message);
$clean{timestamp} = Time::Moment->now_utc->to_string;
my $ua = _ua();
my $res =
$ua->post("http://logs-01.loggly.com/inputs/$agent_cfg->{token}/tag/$tags/", { content => encode_json(\%clean) });
debug("Notification Loggly: status is $res->{status}");
if ($res->{status} == 200) {
my $answer = eval { decode_json($res->{content}) };