-
Notifications
You must be signed in to change notification settings - Fork 314
/
main.rs
1593 lines (1459 loc) · 65 KB
/
main.rs
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
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate habitat_common as common;
#[macro_use]
extern crate habitat_core as hcore;
extern crate habitat_launcher_client as launcher_client;
#[macro_use]
extern crate habitat_sup as sup;
extern crate log;
extern crate env_logger;
extern crate ansi_term;
extern crate libc;
#[macro_use]
extern crate clap;
extern crate time;
extern crate url;
use std::collections::{HashMap, HashSet};
use std::collections::hash_map::Entry;
use std::io::{self, Write};
use std::net::{SocketAddr, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::process;
use std::result;
use std::str::FromStr;
use ansi_term::Colour::{Red, Yellow};
use clap::{App, ArgMatches};
use common::command::package::install::InstallSource;
use common::ui::UI;
use hcore::channel;
use hcore::crypto::{self, default_cache_key_path, SymKey};
#[cfg(windows)]
use hcore::crypto::dpapi::encrypt;
use hcore::env as henv;
use hcore::fs;
use hcore::package::PackageIdent;
use hcore::package::install::PackageInstall;
use hcore::package::metadata::{BindMapping, PackageType};
use hcore::service::{ApplicationEnvironment, ServiceGroup};
use hcore::url::{bldr_url_from_env, default_bldr_url};
use launcher_client::{LauncherCli, ERR_NO_RETRY_EXCODE, OK_NO_RETRY_EXCODE};
use url::Url;
use sup::VERSION;
use sup::config::{GossipListenAddr, GOSSIP_DEFAULT_PORT};
use sup::error::{Error, Result, SupError};
use sup::feat;
use sup::command;
use sup::http_gateway;
use sup::manager::{Manager, ManagerConfig};
use sup::manager::service::{DesiredState, ServiceBind, Topology, UpdateStrategy};
use sup::manager::service::{CompositeSpec, ServiceSpec, StartStyle};
use sup::util;
/// Our output key
static LOGKEY: &'static str = "MN";
static RING_ENVVAR: &'static str = "HAB_RING";
static RING_KEY_ENVVAR: &'static str = "HAB_RING_KEY";
fn main() {
if let Err(err) = start() {
println!("{}", err);
match err {
SupError { err: Error::ProcessLocked(_), .. } => process::exit(ERR_NO_RETRY_EXCODE),
SupError { err: Error::Departed, .. } => {
process::exit(ERR_NO_RETRY_EXCODE);
}
_ => process::exit(1),
}
}
}
fn boot() -> Option<LauncherCli> {
env_logger::init().unwrap();
enable_features_from_env();
if !crypto::init() {
println!("Crypto initialization failed!");
process::exit(1);
}
match launcher_client::env_pipe() {
Some(pipe) => {
match LauncherCli::connect(pipe) {
Ok(launcher) => Some(launcher),
Err(err) => {
println!("{}", err);
process::exit(1);
}
}
}
None => None,
}
}
fn start() -> Result<()> {
let launcher = boot();
let app_matches = match cli().get_matches_safe() {
Ok(matches) => matches,
Err(err) => {
let out = io::stdout();
writeln!(&mut out.lock(), "{}", err.message).expect("Error writing Error to stdout");
process::exit(ERR_NO_RETRY_EXCODE);
}
};
match app_matches.subcommand() {
("bash", Some(m)) => sub_bash(m),
("config", Some(m)) => sub_config(m),
("load", Some(m)) => sub_load(m),
("run", Some(m)) => {
let launcher = launcher.ok_or(sup_error!(Error::NoLauncher))?;
sub_run(m, launcher)
}
("sh", Some(m)) => sub_sh(m),
("start", Some(m)) => {
let launcher = launcher.ok_or(sup_error!(Error::NoLauncher))?;
sub_start(m, launcher)
}
("status", Some(m)) => sub_status(m),
("stop", Some(m)) => sub_stop(m),
("term", Some(m)) => sub_term(m),
("unload", Some(m)) => sub_unload(m),
_ => unreachable!(),
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn cli<'a, 'b>() -> App<'a, 'b> {
clap_app!(("hab-sup") =>
(about: "The Habitat Supervisor")
(version: VERSION)
(author: "\nAuthors: The Habitat Maintainers <humans@habitat.sh>\n")
(@setting VersionlessSubcommands)
(@setting SubcommandRequiredElseHelp)
(@arg VERBOSE: -v +global "Verbose output; shows line numbers")
(@arg NO_COLOR: --("no-color") +global "Turn ANSI color off")
(@subcommand bash =>
(about: "Start an interactive Bash-like shell")
(aliases: &["b", "ba", "bas"])
)
(@subcommand config =>
(about: "Displays the default configuration options for a service")
(aliases: &["c", "co", "con", "conf", "confi"])
(@arg PKG_IDENT: +required +takes_value
"A package identifier (ex: core/redis, core/busybox-static/1.42.2)")
)
(@subcommand load =>
(about: "Load a service to be started and supervised by Habitat from a package or \
artifact. Services started in this manner will persist through Supervisor \
restarts.")
(aliases: &["lo", "loa"])
(@arg PKG_IDENT_OR_ARTIFACT: +required +takes_value
"A Habitat package identifier (ex: core/redis) or filepath to a Habitat Artifact \
(ex: /home/core-redis-3.0.7-21120102031201-x86_64-linux.hart)")
(@arg NAME: --("override-name") +takes_value
"The name for the state directory if there is more than one Supervisor running \
[default: default]")
(@arg APPLICATION: --application -a +takes_value requires[ENVIRONMENT]
"Application name; [default: not set].")
(@arg ENVIRONMENT: --environment -e +takes_value requires[APPLICATION]
"Environment name; [default: not set].")
(@arg CHANNEL: --channel +takes_value
"Receive package updates from the specified release channel [default: stable]")
(@arg GROUP: --group +takes_value
"The service group; shared config and topology [default: default].")
(@arg BLDR_URL: --url -u +takes_value {valid_url}
"Receive package updates from Builder at the specified URL \
[default: https://bldr.habitat.sh]")
(@arg TOPOLOGY: --topology -t +takes_value {valid_topology}
"Service topology; [default: none]")
(@arg STRATEGY: --strategy -s +takes_value {valid_update_strategy}
"The update strategy; [default: none] [values: none, at-once, rolling]")
(@arg BIND: --bind +takes_value +multiple
"One or more service groups to bind to a configuration")
(@arg FORCE: --force -f "Load or reload an already loaded service. If the service was \
previously loaded and running this operation will also restart the service")
)
(@subcommand unload =>
(about: "Unload a persistent or transient service started by the Habitat \
Supervisor. If the Supervisor is running when the service is unloaded the \
service will be stopped.")
(aliases: &["un", "unl", "unlo", "unloa"])
(@arg PKG_IDENT: +required +takes_value "A Habitat package identifier (ex: core/redis)")
(@arg NAME: --("override-name") +takes_value
"The name for the state directory if there is more than one Supervisor running \
[default: default]")
)
(@subcommand run =>
(about: "Run the Habitat Supervisor")
(aliases: &["r", "ru"])
(@arg LISTEN_GOSSIP: --("listen-gossip") +takes_value
"The listen address for the gossip system [default: 0.0.0.0:9638]")
(@arg LISTEN_HTTP: --("listen-http") +takes_value
"The listen address for the HTTP gateway [default: 0.0.0.0:9631]")
(@arg NAME: --("override-name") +takes_value
"The name of the Supervisor if launching more than one [default: default]")
(@arg ORGANIZATION: --org +takes_value
"The organization that the Supervisor and it's subsequent services are part of \
[default: default]")
(@arg PEER: --peer +takes_value +multiple
"The listen address of an initial peer (IP[:PORT])")
(@arg PERMANENT_PEER: --("permanent-peer") -I "If this Supervisor is a permanent peer")
(@arg PEER_WATCH_FILE: --("peer-watch-file") +takes_value conflicts_with[peer]
"Watch this file for connecting to the ring"
)
(@arg RING: --ring -r +takes_value "Ring key name")
(@arg CHANNEL: --channel +takes_value
"Receive Supervisor updates from the specified release channel [default: stable]")
(@arg BLDR_URL: --url -u +takes_value {valid_url}
"Receive Supervisor updates from Builder at the specified URL \
[default: https://bldr.habitat.sh]")
(@arg AUTO_UPDATE: --("auto-update") -A "Enable automatic updates for the Supervisor \
itself")
(@arg EVENTS: --events -n +takes_value {valid_service_group} "Name of the service \
group running a Habitat EventSrv to forward Supervisor and service event data to")
)
(@subcommand sh =>
(about: "Start an interactive Bourne-like shell")
(aliases: &[])
)
(@subcommand start =>
(about: "Start a loaded, but stopped, Habitat service or a transient service from \
a package or artifact. If the Habitat Supervisor is not already running this \
will additionally start one for you.")
(aliases: &["sta", "star"])
(@arg LISTEN_GOSSIP: --("listen-gossip") +takes_value
"The listen address for the gossip system [default: 0.0.0.0:9638]")
(@arg LISTEN_HTTP: --("listen-http") +takes_value
"The listen address for the HTTP gateway [default: 0.0.0.0:9631]")
(@arg NAME: --("override-name") +takes_value
"The name for the state directory if launching more than one Supervisor \
[default: default]")
(@arg ORGANIZATION: --org +takes_value
"The organization that the Supervisor and it's subsequent services are part of \
[default: default]")
(@arg PEER: --peer +takes_value +multiple
"The listen address of an initial peer (IP[:PORT])")
(@arg PERMANENT_PEER: --("permanent-peer") -I "If this Supervisor is a permanent peer")
(@arg PEER_WATCH_FILE: --("peer-watch-file") +takes_value conflicts_with[peer]
"Watch this file for connecting to the ring"
)
(@arg RING: --ring -r +takes_value "Ring key name")
(@arg PKG_IDENT_OR_ARTIFACT: +required +takes_value
"A Habitat package identifier (ex: core/redis) or filepath to a Habitat Artifact \
(ex: /home/core-redis-3.0.7-21120102031201-x86_64-linux.hart)")
(@arg APPLICATION: --application -a +takes_value requires[ENVIRONMENT]
"Application name; [default: not set].")
(@arg ENVIRONMENT: --environment -e +takes_value requires[APPLICATION]
"Environment name; [default: not set].")
(@arg CHANNEL: --channel +takes_value
"Receive package updates from the specified release channel [default: stable]")
(@arg GROUP: --group +takes_value
"The service group; shared config and topology [default: default]")
(@arg BLDR_URL: --url -u +takes_value {valid_url}
"Receive package updates from Builder at the specified URL \
[default: https://bldr.habitat.sh]")
(@arg TOPOLOGY: --topology -t +takes_value {valid_topology}
"Service topology; [default: none]")
(@arg STRATEGY: --strategy -s +takes_value {valid_update_strategy}
"The update strategy; [default: none] [values: none, at-once, rolling]")
(@arg BIND: --bind +takes_value +multiple
"One or more service groups to bind to a configuration")
(@arg CONFIG_DIR: --("config-from") +takes_value {dir_exists}
"Use package config from this path, rather than the package itself")
(@arg AUTO_UPDATE: --("auto-update") -A "Enable automatic updates for the Supervisor \
itself")
(@arg EVENTS: --events -n +takes_value {valid_service_group} "Name of the service \
group running a Habitat EventSrv to forward Supervisor and service event data to")
)
(@subcommand status =>
(about: "Query the status of Habitat services.")
(aliases: &["stat", "statu", "status"])
(@arg PKG_IDENT: +takes_value "A Habitat package identifier (ex: core/redis)")
(@arg NAME: --("override-name") +takes_value
"The name for the state directory if there is more than one Supervisor running \
[default: default]")
)
(@subcommand stop =>
(about: "Stop a running Habitat service.")
(aliases: &["sto"])
(@arg PKG_IDENT: +required +takes_value "A Habitat package identifier (ex: core/redis)")
(@arg NAME: --("override-name") +takes_value
"The name for the state directory if there is more than one Supervisor running \
[default: default]")
)
(@subcommand term =>
(about: "Gracefully terminate the Habitat Supervisor and all of it's running services")
(@arg NAME: --("override-name") +takes_value
"The name of the Supervisor if more than one is running [default: default]")
)
)
}
#[cfg(target_os = "windows")]
fn cli<'a, 'b>() -> App<'a, 'b> {
clap_app!(("hab-sup") =>
(about: "The Habitat Supervisor")
(version: VERSION)
(author: "\nAuthors: The Habitat Maintainers <humans@habitat.sh>\n")
(@setting VersionlessSubcommands)
(@setting SubcommandRequiredElseHelp)
(@arg VERBOSE: -v +global "Verbose output; shows line numbers")
(@arg NO_COLOR: --("no-color") +global "Turn ANSI color off")
(@subcommand bash =>
(about: "Start an interactive Bash-like shell")
(aliases: &["b", "ba", "bas"])
)
(@subcommand config =>
(about: "Displays the default configuration options for a service")
(aliases: &["c", "co", "con", "conf", "confi"])
(@arg PKG_IDENT: +required +takes_value
"A package identifier (ex: core/redis, core/busybox-static/1.42.2)")
)
(@subcommand load =>
(about: "Load a service to be started and supervised by Habitat from a package or \
artifact. Services started in this manner will persist through Supervisor \
restarts.")
(aliases: &["lo", "loa"])
(@arg PKG_IDENT_OR_ARTIFACT: +required +takes_value
"A Habitat package identifier (ex: core/redis) or filepath to a Habitat Artifact \
(ex: /home/core-redis-3.0.7-21120102031201-x86_64-linux.hart)")
(@arg NAME: --("override-name") +takes_value
"The name for the state directory if there is more than one Supervisor running \
[default: default]")
(@arg APPLICATION: --application -a +takes_value requires[ENVIRONMENT]
"Application name; [default: not set].")
(@arg ENVIRONMENT: --environment -e +takes_value requires[APPLICATION]
"Environment name; [default: not set].")
(@arg CHANNEL: --channel +takes_value
"Receive package updates from the specified release channel [default: stable]")
(@arg GROUP: --group +takes_value
"The service group; shared config and topology [default: default].")
(@arg BLDR_URL: --url -u +takes_value {valid_url}
"Receive package updates from Builder at the specified URL \
[default: https://bldr.habitat.sh]")
(@arg TOPOLOGY: --topology -t +takes_value {valid_topology}
"Service topology; [default: none]")
(@arg STRATEGY: --strategy -s +takes_value {valid_update_strategy}
"The update strategy; [default: none] [values: none, at-once, rolling]")
(@arg BIND: --bind +takes_value +multiple
"One or more service groups to bind to a configuration")
(@arg FORCE: --force -f "Load or reload an already loaded service. If the service was \
previously loaded and running this operation will also restart the service")
(@arg PASSWORD: --password +takes_value
"Password of the service user")
)
(@subcommand unload =>
(about: "Unload a persistent or transient service started by the Habitat \
Supervisor. If the Supervisor is running when the service is unloaded the \
service will be stopped.")
(aliases: &["un", "unl", "unlo", "unloa"])
(@arg PKG_IDENT: +required +takes_value "A Habitat package identifier (ex: core/redis)")
(@arg NAME: --("override-name") +takes_value
"The name for the state directory if there is more than one Supervisor running \
[default: default]")
)
(@subcommand run =>
(about: "Run the Habitat Supervisor")
(aliases: &["r", "ru"])
(@arg LISTEN_GOSSIP: --("listen-gossip") +takes_value
"The listen address for the gossip system [default: 0.0.0.0:9638]")
(@arg LISTEN_HTTP: --("listen-http") +takes_value
"The listen address for the HTTP gateway [default: 0.0.0.0:9631]")
(@arg NAME: --("override-name") +takes_value
"The name of the Supervisor if launching more than one [default: default]")
(@arg ORGANIZATION: --org +takes_value
"The organization that the Supervisor and it's subsequent services are part of \
[default: default]")
(@arg PEER: --peer +takes_value +multiple
"The listen address of an initial peer (IP[:PORT])")
(@arg PERMANENT_PEER: --("permanent-peer") -I "If this Supervisor is a permanent peer")
(@arg PEER_WATCH_FILE: --("peer-watch-file") +takes_value conflicts_with[peer]
"Watch this file for connecting to the ring"
)
(@arg RING: --ring -r +takes_value "Ring key name")
(@arg CHANNEL: --channel +takes_value
"Receive Supervisor updates from the specified release channel [default: stable]")
(@arg BLDR_URL: --url -u +takes_value {valid_url}
"Receive Supervisor updates from Builder at the specified URL \
[default: https://bldr.habitat.sh]")
(@arg AUTO_UPDATE: --("auto-update") -A "Enable automatic updates for the Supervisor \
itself")
(@arg EVENTS: --events -n +takes_value {valid_service_group} "Name of the service \
group running a Habitat EventSrv to forward Supervisor and service event data to")
)
(@subcommand sh =>
(about: "Start an interactive Bourne-like shell")
(aliases: &[])
)
(@subcommand start =>
(about: "Start a loaded, but stopped, Habitat service or a transient service from \
a package or artifact. If the Habitat Supervisor is not already running this \
will additionally start one for you.")
(aliases: &["sta", "star"])
(@arg LISTEN_GOSSIP: --("listen-gossip") +takes_value
"The listen address for the gossip system [default: 0.0.0.0:9638]")
(@arg LISTEN_HTTP: --("listen-http") +takes_value
"The listen address for the HTTP gateway [default: 0.0.0.0:9631]")
(@arg NAME: --("override-name") +takes_value
"The name for the state directory if launching more than one Supervisor \
[default: default]")
(@arg ORGANIZATION: --org +takes_value
"The organization that the Supervisor and it's subsequent services are part of \
[default: default]")
(@arg PEER: --peer +takes_value +multiple
"The listen address of an initial peer (IP[:PORT])")
(@arg PERMANENT_PEER: --("permanent-peer") -I "If this Supervisor is a permanent peer")
(@arg PEER_WATCH_FILE: --("peer-watch-file") +takes_value conflicts_with[peer]
"Watch this file for connecting to the ring"
)
(@arg RING: --ring -r +takes_value "Ring key name")
(@arg PKG_IDENT_OR_ARTIFACT: +required +takes_value
"A Habitat package identifier (ex: core/redis) or filepath to a Habitat Artifact \
(ex: /home/core-redis-3.0.7-21120102031201-x86_64-linux.hart)")
(@arg APPLICATION: --application -a +takes_value requires[ENVIRONMENT]
"Application name; [default: not set].")
(@arg ENVIRONMENT: --environment -e +takes_value requires[APPLICATION]
"Environment name; [default: not set].")
(@arg CHANNEL: --channel +takes_value
"Receive package updates from the specified release channel [default: stable]")
(@arg GROUP: --group +takes_value
"The service group; shared config and topology [default: default]")
(@arg BLDR_URL: --url -u +takes_value {valid_url}
"Receive package updates from Builder at the specified URL \
[default: https://bldr.habitat.sh]")
(@arg TOPOLOGY: --topology -t +takes_value {valid_topology}
"Service topology; [default: none]")
(@arg STRATEGY: --strategy -s +takes_value {valid_update_strategy}
"The update strategy; [default: none] [values: none, at-once, rolling]")
(@arg BIND: --bind +takes_value +multiple
"One or more service groups to bind to a configuration")
(@arg CONFIG_DIR: --("config-from") +takes_value {dir_exists}
"Use package config from this path, rather than the package itself")
(@arg AUTO_UPDATE: --("auto-update") -A "Enable automatic updates for the Supervisor \
itself")
(@arg EVENTS: --events -n +takes_value {valid_service_group} "Name of the service \
group running a Habitat EventSrv to forward Supervisor and service event data to")
(@arg PASSWORD: --password +takes_value "Password of the service user")
)
(@subcommand status =>
(about: "Query the status of Habitat services.")
(aliases: &["stat", "statu", "status"])
(@arg PKG_IDENT: +takes_value "A Habitat package identifier (ex: core/redis)")
(@arg NAME: --("override-name") +takes_value
"The name for the state directory if there is more than one Supervisor running \
[default: default]")
)
(@subcommand stop =>
(about: "Stop a running Habitat service.")
(aliases: &["sto"])
(@arg PKG_IDENT: +required +takes_value "A Habitat package identifier (ex: core/redis)")
(@arg NAME: --("override-name") +takes_value
"The name for the state directory if there is more than one Supervisor running \
[default: default]")
)
)
}
fn sub_bash(m: &ArgMatches) -> Result<()> {
if m.is_present("VERBOSE") {
hcore::output::set_verbose(true);
}
if m.is_present("NO_COLOR") {
hcore::output::set_no_color(true);
}
command::shell::bash()
}
fn sub_config(m: &ArgMatches) -> Result<()> {
let ident = PackageIdent::from_str(m.value_of("PKG_IDENT").unwrap())?;
common::command::package::config::start(&ident, "/")?;
Ok(())
}
fn sub_load(m: &ArgMatches) -> Result<()> {
if m.is_present("VERBOSE") {
hcore::output::set_verbose(true);
}
if m.is_present("NO_COLOR") {
hcore::output::set_no_color(true);
}
let cfg = mgrcfg_from_matches(m)?;
let install_source = install_source_from_input(m)?;
// TODO (CM): should load be able to download new artifacts if
// you're re-loading with --force?
// If we've already got a spec for this thing, we don't want to
// inadvertently download a new version
match existing_specs_for_ident(&cfg, install_source.as_ref().clone())? {
None => {
// We don't have any record of this thing; let's set it
// up!
//
// This will install the latest version from Builder
let installed = util::pkg::install(
&mut UI::default(),
&bldr_url(m),
&install_source,
&channel(m),
)?;
let original_ident = install_source.as_ref();
let mut specs = generate_new_specs_from_package(original_ident, &installed, m)?;
for spec in specs.iter_mut() {
// "load" == persistent services, by definition
spec.start_style = StartStyle::Persistent;
Manager::save_spec_for(&cfg, spec)?;
outputln!("The {} service was successfully loaded", spec.ident);
}
// Only saves a composite spec if it's, well, a composite
if let Ok(composite_spec) =
CompositeSpec::from_package_install(&original_ident, &installed)
{
Manager::save_composite_spec_for(&cfg, &composite_spec)?;
outputln!(
"The {} composite was successfully loaded",
composite_spec.ident()
);
}
Ok(())
}
Some(spec) => {
// We've seen this service / composite before. Thus `load`
// basically acts as a way to edit spec files on the
// command line. As a result, we a) check that you
// *really* meant to change an existing spec, and b) DO
// NOT download a potentially new version of the package
// in question
if !m.is_present("FORCE") {
// TODO (CM): make this error reflect composites
return Err(sup_error!(Error::ServiceLoaded(spec.ident().clone())));
}
match spec {
Spec::Service(mut service_spec) => {
service_spec.ident = install_source.as_ref().clone();
update_spec_from_input(&mut service_spec, m)?;
service_spec.start_style = StartStyle::Persistent;
// Only install if we don't have something
// locally; otherwise you could potentially
// upgrade each time you load.
//
// Also make sure you're pulling from where you're
// supposed to be pulling from!
install_package_if_not_present(
&install_source,
&service_spec.bldr_url,
&service_spec.channel,
)?;
Manager::save_spec_for(&cfg, &service_spec)?;
outputln!("The {} service was successfully loaded", service_spec.ident);
Ok(())
}
Spec::Composite(composite_spec, mut existing_service_specs) => {
if install_source.as_ref() == composite_spec.ident() {
let composite_package =
match util::pkg::installed(composite_spec.package_ident()) {
Some(package) => package,
// TODO (CM): this should be a proper error
None => unreachable!(),
};
update_composite_service_specs(
&mut existing_service_specs,
&composite_package,
m,
)?;
for service_spec in existing_service_specs.iter() {
Manager::save_spec_for(&cfg, service_spec)?;
outputln!("The {} service was successfully loaded", service_spec.ident);
}
outputln!(
"The {} composite was successfully loaded",
composite_spec.ident()
);
} else {
// It changed!
// OK, here's the deal.
//
// We're going to install a new composite if
// we need to in order to satisfy the spec
// we've now got. That also means that the
// services that are currently running may get
// unloaded (because they are no longer in the
// composite), and new services may start
// (because they were added to the composite).
let installed_package = install_package_if_not_present(
&install_source,
// This (updating from the command-line
// args) is a difference from
// force-loading a spec, because
// composites don't auto-update themselves
// like services can.
&bldr_url(m),
&channel(m),
)?;
// Generate new specs from the new composite package and
// CLI inputs
let new_service_specs = generate_new_specs_from_package(
install_source.as_ref(),
&installed_package,
m,
)?;
// Delete any specs that are not in the new
// composite
let mut old_spec_names = HashSet::new();
for s in existing_service_specs.iter() {
old_spec_names.insert(s.ident.name.clone());
}
let mut new_spec_names = HashSet::new();
for s in new_service_specs.iter() {
new_spec_names.insert(s.ident.name.clone());
}
let specs_to_delete: HashSet<_> =
old_spec_names.difference(&new_spec_names).collect();
for spec in existing_service_specs.iter() {
if specs_to_delete.contains(&spec.ident.name) {
let file = Manager::spec_path_for(&cfg, spec);
outputln!("Unloading {:?}", file);
std::fs::remove_file(&file).map_err(|err| {
sup_error!(Error::ServiceSpecFileIO(file, err))
})?;
}
}
// <-- end of deletion
// Save all the new specs. If there are
// services that exist in both composites,
// their service spec files will have the same
// name, so they'll be taken care of here (we
// don't need to treat them differently)
for spec in new_service_specs.iter() {
Manager::save_spec_for(&cfg, spec)?;
outputln!("The {} service was successfully loaded", spec.ident);
}
// Generate and save the new spec
let new_composite_spec = CompositeSpec::from_package_install(
install_source.as_ref(),
&installed_package,
)?;
Manager::save_composite_spec_for(&cfg, &new_composite_spec)?;
outputln!(
"The {} composite was successfully loaded",
new_composite_spec.ident()
);
}
Ok(())
}
}
}
}
}
fn sub_unload(m: &ArgMatches) -> Result<()> {
if m.is_present("VERBOSE") {
hcore::output::set_verbose(true);
}
if m.is_present("NO_COLOR") {
hcore::output::set_no_color(true);
}
let cfg = mgrcfg_from_matches(m)?;
let ident = PackageIdent::from_str(m.value_of("PKG_IDENT").unwrap())?;
// Gather up the paths to all the spec files we care about. This
// includes all service specs as well as any composite spec.
let spec_paths = match existing_specs_for_ident(&cfg, ident)? {
Some(Spec::Service(spec)) => vec![Manager::spec_path_for(&cfg, &spec)],
Some(Spec::Composite(composite_spec, specs)) => {
let mut paths = Vec::with_capacity(specs.len() + 1);
for spec in specs.iter() {
paths.push(Manager::spec_path_for(&cfg, spec));
}
paths.push(Manager::composite_path_for(&cfg, &composite_spec));
paths
}
None => vec![],
};
for file in spec_paths {
outputln!("Unloading {:?}", file);
std::fs::remove_file(&file).map_err(|err| {
sup_error!(Error::ServiceSpecFileIO(file, err))
})?;
}
Ok(())
}
fn sub_run(m: &ArgMatches, launcher: LauncherCli) -> Result<()> {
let cfg = mgrcfg_from_matches(m)?;
let mut manager = Manager::load(cfg, launcher)?;
manager.run()
}
fn sub_sh(m: &ArgMatches) -> Result<()> {
if m.is_present("VERBOSE") {
hcore::output::set_verbose(true);
}
if m.is_present("NO_COLOR") {
hcore::output::set_no_color(true);
}
command::shell::sh()
}
fn sub_start(m: &ArgMatches, launcher: LauncherCli) -> Result<()> {
if m.is_present("VERBOSE") {
hcore::output::set_verbose(true);
}
if m.is_present("NO_COLOR") {
hcore::output::set_no_color(true);
}
let cfg = mgrcfg_from_matches(m)?;
if !fs::am_i_root() {
let mut ui = UI::default();
ui.warn(
"Running the Habitat Supervisor with root or superuser privileges is recommended",
)?;
ui.br()?;
}
let install_source = install_source_from_input(m)?;
let original_ident: &PackageIdent = install_source.as_ref();
// NOTE: As coded, if you try to start a service from a hart file,
// but you already have a spec for that service (regardless of
// version), you're not going to ever install your hart file, and
// the spec isn't going to be updated to point to that exact
// version.
let updated_specs = match existing_specs_for_ident(&cfg, original_ident.clone())? {
Some(Spec::Service(mut spec)) => {
let mut updated_specs = vec![];
if spec.desired_state == DesiredState::Down {
spec.desired_state = DesiredState::Up;
updated_specs.push(spec);
}
updated_specs
}
Some(Spec::Composite(_, service_specs)) => {
let mut updated_specs = vec![];
for mut spec in service_specs {
if spec.desired_state == DesiredState::Down {
spec.desired_state = DesiredState::Up;
updated_specs.push(spec);
}
}
updated_specs
}
None => {
// We don't have any specs for this thing yet, so we'll
// need to make some. If we don't already have installed
// software that satisfies the given identifier, then
// we'll install the latest thing that will
// suffice. Otherwise, we'll just use what we find in the
// local cache of software.
let installed_package =
install_package_if_not_present(&install_source, &bldr_url(m), &channel(m))?;
let new_specs =
generate_new_specs_from_package(&original_ident, &installed_package, m)?;
// Saving the composite spec here, because we currently
// need the PackageInstall to create it! It'll only create
// a composite spec if the package is itself a composite.
if let Ok(composite_spec) =
CompositeSpec::from_package_install(&original_ident, &installed_package)
{
Manager::save_composite_spec_for(&cfg, &composite_spec)?;
}
new_specs
}
};
let specs_changed = updated_specs.len() > 0;
for spec in updated_specs.iter() {
Manager::save_spec_for(&cfg, spec)?;
}
if Manager::is_running(&cfg)? {
if specs_changed {
outputln!(
"Supervisor starting {}. See the Supervisor output for more details.",
original_ident
);
Ok(())
} else {
// TODO (CM): somehow, this doesn't actually seem to be
// exiting with a non-zero exit code
process::exit(OK_NO_RETRY_EXCODE);
}
} else {
let mut manager = Manager::load(cfg, launcher)?;
manager.run()
}
}
fn sub_status(m: &ArgMatches) -> Result<()> {
if m.is_present("VERBOSE") {
hcore::output::set_verbose(true);
}
if m.is_present("NO_COLOR") {
hcore::output::set_no_color(true);
}
let cfg = mgrcfg_from_matches(m)?;
if !Manager::is_running(&cfg)? {
println!("The Supervisor is not running.");
process::exit(3);
}
// Note that PKG_IDENT is NOT required here
match m.value_of("PKG_IDENT") {
Some(pkg) => {
let ident = PackageIdent::from_str(pkg)?;
let specs = match existing_specs_for_ident(&cfg, ident)? {
Some(Spec::Service(spec)) => vec![spec],
Some(Spec::Composite(_, specs)) => specs,
None => {
println!("{} is not currently loaded.", pkg);
process::exit(2);
}
};
for spec in specs {
let status = Manager::service_status(&cfg, &spec.ident)?;
outputln!("{}", status);
}
}
None => {
let statuses = Manager::status(&cfg)?;
if statuses.is_empty() {
println!("No services loaded.");
return Ok(());
}
for status in statuses {
println!("{}", status);
}
}
}
Ok(())
}
fn sub_stop(m: &ArgMatches) -> Result<()> {
if m.is_present("VERBOSE") {
hcore::output::set_verbose(true);
}
if m.is_present("NO_COLOR") {
hcore::output::set_no_color(true);
}
let cfg = mgrcfg_from_matches(m)?;
// PKG_IDENT is required, so unwrap() is safe
let ident = PackageIdent::from_str(m.value_of("PKG_IDENT").unwrap())?;
let mut specs = match existing_specs_for_ident(&cfg, ident)? {
Some(Spec::Service(spec)) => vec![spec],
Some(Spec::Composite(_, specs)) => specs,
None => vec![],
};
for spec in specs.iter_mut() {
spec.desired_state = DesiredState::Down;
Manager::save_spec_for(&cfg, &spec)?;
}
Ok(())
}
fn sub_term(m: &ArgMatches) -> Result<()> {
let cfg = mgrcfg_from_matches(m)?;
match Manager::term(&cfg) {
Err(SupError { err: Error::ProcessLockIO(_, _), .. }) => {
println!("Supervisor not started.");
Ok(())
}
result => result,
}
}
// Internal Implementation Details
////////////////////////////////////////////////////////////////////////
/// Helper enum to abstract over spec type.
///
/// Currently needed only here. Don't bother moving anywhere because
/// ServiceSpecs AND CompositeSpecs will be going away soon anyway.
enum Spec {
Service(ServiceSpec),
Composite(CompositeSpec, Vec<ServiceSpec>),
}
impl Spec {
/// We need to get at the identifier of a spec, regardless of
/// which kind it is.
fn ident(&self) -> &PackageIdent {
match self {
&Spec::Composite(ref s, _) => s.ident(),
&Spec::Service(ref s) => s.ident.as_ref(),
}
}
}
/// Given a `PackageIdent`, return current specs if they exist. If
/// the package is a standalone service, only that spec will be
/// returned, but if it is a composite, the composite spec as well as
/// the specs for all the services in the composite will be returned.
fn existing_specs_for_ident(cfg: &ManagerConfig, ident: PackageIdent) -> Result<Option<Spec>> {
let default_spec = ServiceSpec::default_for(ident.clone());
let spec_file = Manager::spec_path_for(cfg, &default_spec);
// Try it as a service first
if let Ok(spec) = ServiceSpec::from_file(&spec_file) {
Ok(Some(Spec::Service(spec)))
} else {
// Try it as a composite next
let composite_spec_file = Manager::composite_path_by_ident(&cfg, &ident);
match CompositeSpec::from_file(composite_spec_file) {
Ok(composite_spec) => {
let fs_root_path = Path::new(&*fs::FS_ROOT_PATH);
let package =
PackageInstall::load(composite_spec.package_ident(), Some(fs_root_path))?;
let mut specs = vec![];
let services = package.pkg_services()?;
for service in services {
let spec = ServiceSpec::from_file(Manager::spec_path_for(
cfg,
&ServiceSpec::default_for(service),
))?;
specs.push(spec);
}
Ok(Some(Spec::Composite(composite_spec, specs)))
}
// Looks like we have no specs for this thing at all
Err(_) => Ok(None),
}
}
}
fn mgrcfg_from_matches(m: &ArgMatches) -> Result<ManagerConfig> {
let mut cfg = ManagerConfig::default();
cfg.auto_update = m.is_present("AUTO_UPDATE");
cfg.update_url = bldr_url(m);
cfg.update_channel = channel(m);
if let Some(addr_str) = m.value_of("LISTEN_GOSSIP") {
cfg.gossip_listen = GossipListenAddr::from_str(addr_str)?;
}
if let Some(addr_str) = m.value_of("LISTEN_HTTP") {
cfg.http_listen = http_gateway::ListenAddr::from_str(addr_str)?;
}
if let Some(name_str) = m.value_of("NAME") {
cfg.name = Some(String::from(name_str));
outputln!("");
outputln!(
"{} Running more than one Habitat Supervisor is not recommended for most",
Red.bold().paint("CAUTION:".to_string())
);
outputln!(
"{} users in most use cases. Using one Supervisor per host for multiple",
Red.bold().paint("CAUTION:".to_string())
);
outputln!(
"{} services in one ring will yield much better performance.",
Red.bold().paint("CAUTION:".to_string())
);
outputln!("");
outputln!(
"{} If you know what you're doing, carry on!",
Red.bold().paint("CAUTION:".to_string())