-
Notifications
You must be signed in to change notification settings - Fork 318
Expand file tree
/
Copy pathmanager.rs
More file actions
2215 lines (2016 loc) · 95.9 KB
/
Copy pathmanager.rs
File metadata and controls
2215 lines (2016 loc) · 95.9 KB
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
pub(crate) mod action;
pub mod commands;
mod file_watcher;
mod peer_watcher;
mod self_updater;
pub mod service;
mod service_updater;
mod spec_dir;
mod spec_watcher;
mod sup_watcher;
pub(crate) mod sys;
mod user_config_watcher;
use self::{action::{ShutdownInput,
SupervisorAction},
peer_watcher::PeerWatcher,
self_updater::{SUP_PKG_IDENT,
SelfUpdater},
service::{ConfigRendering,
DesiredState,
PersistentServiceWrapper,
Service,
ServiceQueryModel,
ServiceRunState,
ServiceSpec,
Topology,
spec::{RefreshOperation,
ServiceOperation}},
service_updater::ServiceUpdater,
spec_dir::SpecDir,
spec_watcher::SpecWatcher,
sys::Sys,
user_config_watcher::UserConfigWatcher};
use crate::{VERSION,
census::{CensusRing,
CensusRingProxy},
ctl_gateway::{self,
CtlRequest,
acceptor::CtlAcceptor,
server::CtlGatewayServer},
error::{Error,
Result},
event::{self,
EventStreamConfig},
http_gateway,
lock_file::LockFile,
util::pkg};
use cpu_time::ProcessTime;
use futures::{channel::{mpsc as fut_mpsc,
oneshot},
future,
prelude::*,
stream::FuturesUnordered};
use habitat_butterfly::{member::Member,
server::{ServerProxy,
Suitability,
timing::Timing}};
use habitat_common::{FeatureFlag,
liveliness_checker,
outputln,
types::{GossipListenAddr,
HttpListenAddr,
ListenCtlAddr}};
#[cfg(unix)]
use habitat_core::os::{process::{ShutdownSignal,
Signal},
signals};
use habitat_core::{ChannelIdent,
crypto::keys::{KeyCache,
RingKey},
env,
env::Config,
fs::FS_ROOT_PATH,
os::process::{self,
ShutdownTimeout},
package::{Identifiable,
PackageIdent,
PackageInstall},
service::ServiceGroup,
tls::rustls_wrapper::{certificates_from_file,
private_key_from_file},
util::ToI64};
use habitat_launcher_client::{LauncherCli,
LauncherStatus};
use habitat_sup_protocol::{self};
use lazy_static::lazy_static;
use log::{debug,
error,
info,
trace,
warn};
use parking_lot::{Mutex,
RwLock};
use prometheus::{HistogramVec,
IntGauge,
register_histogram_vec,
register_int_gauge};
use rustls::{RootCertStore,
ServerConfig,
pki_types::{CertificateDer,
PrivateKeyDer,
PrivatePkcs8KeyDer},
server::WebPkiClientVerifier};
use serde::{Deserialize,
Serialize};
use std::{collections::{HashMap,
HashSet},
ffi::OsStr,
fs::{self,
File},
io::{Read,
Write},
iter::{FromIterator,
IntoIterator},
net::{IpAddr,
SocketAddr},
path::{Path,
PathBuf},
str::FromStr,
sync::{Arc,
Condvar,
Mutex as StdMutex,
atomic::{AtomicBool,
Ordering},
mpsc as std_mpsc},
thread,
time::{Duration,
Instant,
SystemTime}};
#[cfg(windows)]
use winapi::{shared::minwindef::PDWORD,
um::processthreadsapi};
const MEMBER_ID_FILE: &str = "MEMBER_ID";
pub const PROC_LOCK_FILE: &str = "LOCK";
static LOGKEY: &str = "MR";
lazy_static! {
static ref RUN_LOOP_DURATION: HistogramVec =
register_histogram_vec!("hab_sup_run_loop_duration_seconds",
"The time it takes for one tick of a run loop",
&["loop"]).unwrap();
static ref FILE_DESCRIPTORS: IntGauge = register_int_gauge!(
"hab_sup_open_file_descriptors_total",
"A count of the total number of open file descriptors. Unix only"
).unwrap();
static ref CPU_TIME: IntGauge = register_int_gauge!("hab_sup_cpu_time_nanoseconds",
"CPU time of the supervisor process in \
nanoseconds").unwrap();
// The `<origin>/<name>` version of the Supervisor's package ident
static ref THIS_SUPERVISOR_FUZZY_IDENT: PackageIdent = SUP_PKG_IDENT.parse().unwrap();
/// Depending on the value of `VERSION` this ident may or may not be fully qualified. `VERSION`
/// produces a fully qualified ident when built with Habitat. If it is built directly from
/// `cargo build` no release information will be set.
static ref THIS_SUPERVISOR_IDENT: PackageIdent =
PackageIdent::from_str(&format!("{}/{}", SUP_PKG_IDENT, VERSION)).unwrap();
}
habitat_core::env_config_duration!( HttpStartupTimeout,
HAB_HTTP_STARTUP_TIMEOUT_SECS => from_secs,
Duration::from_secs(10));
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
/// Determines whether the new pidfile-less behavior is enabled, or
/// the old behavior is used.
pub enum ServicePidSource {
/// The "old" behavior; find out a Service's PID by reading a pidfile.
Files,
/// The "new" behavior; query the Launcher directly to discover a
/// Service's PID.
Launcher,
}
impl ServicePidSource {
/// This check is to determine if the user is working with a
/// Launcher that can provide service PIDs. If not, we will
/// continue to use the old pidfile logic.
///
/// You should call this function once early in the Supservisor's
/// lifecycle and cache the results. We only want to incur the
/// timeout hit when we check to see if the launcher can answer
/// our query once. Otherwise, if we were using an older launcher,
/// we would incur that hit each time we start a new service.
fn determine_source(launcher: &LauncherCli) -> Self {
if launcher.pid_of("fake_service.just_to_see_if_the_launcher_can_handle_this_message")
.is_err()
{
warn!("You do not appear to be running a Launcher that can provide service PIDs to \
the Supervisor. Using pidfiles for services instead.");
ServicePidSource::Files
} else {
ServicePidSource::Launcher
}
}
}
/// A Supervisor can stop in a handful of ways.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum ShutdownMode {
/// When the Supervisor is shutting down for normal reasons and
/// should take all services down with it (i.e., it's actually
/// shutting down).
Normal,
/// When the Supervisor has been manually departed from the
/// Habitat network. All services should come down, as well.
Departed,
/// A Supervisor is updating itself, or is otherwise simply
/// restarting. Services _do not_ get shut down.
Restarting,
}
#[derive(Clone, Debug, Default)]
pub struct ShutdownConfig {
#[cfg(not(windows))]
pub signal: ShutdownSignal,
pub timeout: ShutdownTimeout,
}
impl ShutdownConfig {
fn new(shutdown_input: Option<&ShutdownInput>, service: &Service) -> Self {
let timeout = shutdown_input.and_then(|si| si.timeout).unwrap_or_else(|| {
service
.shutdown_timeout()
.unwrap_or(service.pkg.shutdown_timeout)
});
Self { timeout,
#[cfg(not(windows))]
signal: service.pkg.shutdown_signal }
}
}
/// FileSystem paths that the Manager uses to persist data to disk.
///
/// This is shared with the `http_gateway` and `service` modules for reading and writing
/// persistence data.
#[derive(Debug, Serialize)]
pub struct FsCfg {
pub sup_root: PathBuf,
data_path: PathBuf,
specs_path: PathBuf,
member_id_file: PathBuf,
proc_lock_file: PathBuf,
}
impl FsCfg {
fn new<T>(sup_root: T) -> Self
where T: Into<PathBuf>
{
let sup_root = sup_root.into();
FsCfg { specs_path: sup_root.join("specs"),
data_path: sup_root.join("data"),
member_id_file: sup_root.join(MEMBER_ID_FILE),
proc_lock_file: sup_root.join(PROC_LOCK_FILE),
sup_root }
}
}
/// Configuration parameters that control the behaviour of restarts for services
/// that fail to startup successfully
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct ServiceRestartConfig {
pub min_backoff_period: Duration,
pub max_backoff_period: Duration,
/// The amount of time that needs to elapse after a service has restarted to reset the backoff
/// state. We need this because health checks are not mandatory, so there is no good way to
/// know if a service started successfully other than waiting for some time and checking
/// that it does not go down.
pub cooldown_period: Duration,
}
impl ServiceRestartConfig {
pub fn new(min_backoff_period: Duration,
max_backoff_period: Duration,
restart_cooldown_period: Duration)
-> ServiceRestartConfig {
ServiceRestartConfig { min_backoff_period,
max_backoff_period,
cooldown_period: restart_cooldown_period }
}
}
impl Default for ServiceRestartConfig {
fn default() -> Self {
Self { min_backoff_period: Default::default(),
max_backoff_period: Default::default(),
cooldown_period: Duration::from_secs(300), }
}
}
#[derive(Debug, PartialEq)]
pub struct CloneablePkcs8PrivKey(PrivatePkcs8KeyDer<'static>);
impl From<PrivatePkcs8KeyDer<'static>> for CloneablePkcs8PrivKey {
fn from(k: PrivatePkcs8KeyDer<'static>) -> Self { Self(k) }
}
impl Clone for CloneablePkcs8PrivKey {
fn clone(&self) -> Self { Self(self.0.clone_key()) }
}
#[derive(Clone, Debug)]
pub struct ManagerConfig {
pub auto_update: bool,
pub auto_update_period: Duration,
pub service_update_period: Duration,
pub service_restart_config: ServiceRestartConfig,
pub custom_state_path: Option<PathBuf>,
pub key_cache: KeyCache,
pub update_url: String,
pub update_channel: ChannelIdent,
pub gossip_listen: GossipListenAddr,
pub ctl_listen: ListenCtlAddr,
pub ctl_server_certificates: Option<Vec<CertificateDer<'static>>>,
pub ctl_server_key: Option<CloneablePkcs8PrivKey>,
pub ctl_client_ca_certificates: Option<RootCertStore>,
pub http_listen: HttpListenAddr,
pub http_disable: bool,
pub gossip_peers: Vec<SocketAddr>,
pub gossip_permanent: bool,
pub ring_key: Option<RingKey>,
pub organization: Option<String>,
pub watch_peer_file: Option<String>,
pub tls_config: Option<TLSConfig>,
pub feature_flags: FeatureFlag,
pub event_stream_config: Option<EventStreamConfig>,
/// If this field is `Some`, keep the indicated number of latest packages and uninstall all
/// others during service start. If this field is `None`, automatic package cleanup is
/// disabled.
pub keep_latest_packages: Option<usize>,
pub sys_ip: IpAddr,
}
#[derive(Clone, Debug, PartialEq)]
pub struct TLSConfig {
pub cert_path: PathBuf,
pub key_path: PathBuf,
pub ca_cert_path: Option<PathBuf>,
}
impl ManagerConfig {
fn sup_root(&self) -> PathBuf {
habitat_sup_protocol::sup_root(self.custom_state_path.as_ref())
}
fn spec_path_for(&self, ident: &PackageIdent) -> PathBuf {
self.sup_root()
.join("specs")
.join(ServiceSpec::ident_file(ident))
}
pub fn save_spec_for(&self, spec: &ServiceSpec) -> Result<()> {
spec.to_file(self.spec_path_for(&spec.ident))
}
/// Given a `PackageIdent`, return current spec if it exists.
pub fn spec_for_ident(&self, ident: &PackageIdent) -> Option<ServiceSpec> {
let spec_file = self.spec_path_for(ident);
// JC: This mimics the logic from when we had composites. But
// should we check for Err ?
ServiceSpec::from_file(spec_file).ok()
}
}
impl PartialEq for ManagerConfig {
fn eq(&self, other: &Self) -> bool {
self.auto_update == other.auto_update
&& self.auto_update_period == other.auto_update_period
&& self.service_update_period == other.service_update_period
&& self.service_restart_config == other.service_restart_config
&& self.custom_state_path == other.custom_state_path
&& self.key_cache == other.key_cache
&& self.update_url == other.update_url
&& self.update_channel == other.update_channel
&& self.gossip_listen == other.gossip_listen
&& self.ctl_listen == other.ctl_listen
&& self.ctl_server_certificates == other.ctl_server_certificates
&& self.ctl_server_key == other.ctl_server_key
// Explicitly excluding ctl_client_ca_certificates from comparison
&& self.http_listen == other.http_listen
&& self.http_disable == other.http_disable
&& self.gossip_peers == other.gossip_peers
&& self.gossip_permanent == other.gossip_permanent
&& self.ring_key == other.ring_key
&& self.organization == other.organization
&& self.watch_peer_file == other.watch_peer_file
&& self.tls_config == other.tls_config
&& self.feature_flags == other.feature_flags
&& self.event_stream_config == other.event_stream_config
&& self.keep_latest_packages == other.keep_latest_packages
&& self.sys_ip == other.sys_ip
}
}
/// Once a formerly-busy service is no longer doing something
/// asynchronously, we mark that we should take a look at the spec
/// files on disk to ensure that we're still "in sync".
///
/// For example, a "restart" is achieved by stopping a service,
/// and then restarting it when we see that its spec file says it
/// should be up.
///
/// This flag behaves essentially the same as making an arbitrary
/// change to a file in the specs directory, in that the latter
/// provides a boolean condition on whether or not we need to
/// reexamine our spec files.
///
/// Wrapping this up into a type consolidates the logic for
/// manipulation of the signaling Boolean. In particular, all the
/// atomic ordering information resides here, meaning that we don't
/// have to scatter it throughout the code, which could lead to logic
/// errors and drift over time.
#[derive(Clone)]
struct ReconciliationFlag(Arc<AtomicBool>);
impl ReconciliationFlag {
fn new(value: bool) -> Self { ReconciliationFlag(Arc::new(AtomicBool::new(value))) }
/// Called after a service has finished some asynchronous
/// operation to signal that we need to take a look at their spec
/// file again to potentially take action.
///
/// See Manager::wrap_async_service_operation for additional details.
///
/// We used `Ordering::Relaxed` here because there isn't a need to
/// sequence operations for multiple actors setting the value to
/// `true`.
fn set(&self) { self.0.store(true, Ordering::Relaxed); }
fn is_set(&self) -> bool { self.0.load(Ordering::Relaxed) }
/// Returns whether or not we need to re-examine spec files in
/// response to some service having finished an asynchronous
/// action.
///
/// This *does* change the value of the flag back to `false` if it
/// was `true`, so we don't have a strict CQRS-style separation of
/// read/write responsibilities, but this is needed to avoid
/// potential race conditions between separate check and load
/// operations.
///
/// This also allows us to use `Ordering::Relaxed`... whether we
/// see that we need to reconcile before or after some service
/// signals that it has finished is ultimately unimportant, since
/// we'll just check again the next time through our supervision
/// loop.
///
/// While this is all dependent on some of the inner workings of
/// the `Manager` right now, consolidating this "flag" logic in
/// one place seemed the prudent choice. In the long-term, we
/// should be able to dispense with this altogether once we're all
/// asynchronous.
fn toggle_if_set(&self) -> bool {
self.0
.compare_exchange(true, false, Ordering::Relaxed, Ordering::Relaxed)
.unwrap_or_else(core::convert::identity)
}
}
/// This struct encapsulates the shared state for the supervisor. It's worth noting that if there's
/// something you want the CtlGateway to be able to operate on, it needs to be put in here. This
/// state gets shared with all the CtlGateway handlers.
pub struct ManagerState {
/// The configuration used to instantiate this Manager instance
cfg: ManagerConfig,
services: Arc<sync::ManagerServices>,
gateway_state: Arc<sync::GatewayState>,
should_restart: AtomicBool,
}
pub(crate) mod sync {
use super::*;
use habitat_common::sync::{Lock,
ReadGuard,
WriteGuard};
pub struct GatewayStateReadGuard<'a>(ReadGuard<'a, GatewayStateInner>);
impl<'a> GatewayStateReadGuard<'a> {
fn new(lock: &'a Lock<GatewayStateInner>) -> Self { Self(lock.read()) }
pub fn butterfly_data(&self) -> &str { &self.0.butterfly_data }
pub fn census_data(&self) -> &str { &self.0.census_data }
pub fn services_data(&self) -> &[ServiceQueryModel] { self.0.services_data.as_slice() }
}
pub struct GatewayStateWriteGuard<'a>(WriteGuard<'a, GatewayStateInner>);
impl<'a> GatewayStateWriteGuard<'a> {
fn new(lock: &'a Lock<GatewayStateInner>) -> Self { Self(lock.write()) }
pub fn set_census_data(&mut self, new_data: String) { self.0.census_data = new_data }
pub fn set_butterfly_data(&mut self, new_data: String) { self.0.butterfly_data = new_data }
pub fn set_services_data(&mut self, new_data: Vec<ServiceQueryModel>) {
self.0.services_data = new_data
}
pub fn get_services_data_mut(&mut self) -> &mut Vec<ServiceQueryModel> {
self.0.services_data.as_mut()
}
}
/// All the data that is ultimately served from the Supervisor's HTTP
/// gateway.
#[derive(Debug, Default)]
pub struct GatewayState {
inner: Lock<GatewayStateInner>,
}
impl GatewayState {
#[must_use]
pub fn lock_gsr(&self) -> GatewayStateReadGuard<'_> {
GatewayStateReadGuard::new(&self.inner)
}
#[must_use]
pub fn lock_gsw(&self) -> GatewayStateWriteGuard<'_> {
GatewayStateWriteGuard::new(&self.inner)
}
}
#[derive(Debug, Default)]
struct GatewayStateInner {
/// JSON returned by the /census endpoint
census_data: String,
/// JSON returned by the /butterfly endpoint
butterfly_data: String,
/// JSON returned by the /services endpoint
services_data: Vec<ServiceQueryModel>,
}
type ManagerServicesInner = HashMap<PackageIdent, PersistentServiceWrapper>;
pub struct ManagerServicesReadGuard<'a>(ReadGuard<'a, ManagerServicesInner>);
impl<'a> ManagerServicesReadGuard<'a> {
fn new(lock: &'a Lock<ManagerServicesInner>) -> Self { Self(lock.read()) }
pub fn iter(&self) -> impl Iterator<Item = (&PackageIdent, &PersistentServiceWrapper)> {
self.0.iter()
}
pub fn get(&self, key: &PackageIdent) -> Option<&PersistentServiceWrapper> {
self.0.get(key)
}
pub fn running_services(&self) -> impl Iterator<Item = &Service> {
self.0
.values()
.filter_map(PersistentServiceWrapper::service)
}
}
pub struct ManagerServicesWriteGuard<'a>(WriteGuard<'a, ManagerServicesInner>);
impl<'a> ManagerServicesWriteGuard<'a> {
fn new(lock: &'a Lock<ManagerServicesInner>) -> Self { Self(lock.write()) }
pub fn iter_mut(
&mut self)
-> impl Iterator<Item = (&PackageIdent, &mut PersistentServiceWrapper)> + use<'_>
{
self.0.iter_mut()
}
pub fn insert(&mut self, key: PackageIdent, value: PersistentServiceWrapper) {
if let Some(state) = self.0.get_mut(&key) {
state.take_service(value);
state.start();
} else {
self.0.insert(key, value);
}
}
pub fn remove(&mut self, key: &PackageIdent) -> Option<PersistentServiceWrapper> {
self.0.remove(key)
}
pub fn get_mut(&mut self, key: &PackageIdent) -> Option<&mut PersistentServiceWrapper> {
self.0.get_mut(key)
}
pub fn services(&mut self)
-> impl Iterator<Item = &mut PersistentServiceWrapper> + use<'_> {
self.0.values_mut()
}
pub fn running_services(&mut self) -> impl Iterator<Item = &mut Service> + use<'_> {
self.0
.values_mut()
.filter_map(PersistentServiceWrapper::service_mut)
}
pub fn drain_services(&mut self) -> impl Iterator<Item = Service> + '_ + use<'_> {
self.0
.drain()
.filter_map(|(_, mut state)| state.shutdown(false))
}
}
#[derive(Debug, Default)]
pub struct ManagerServices {
inner: Lock<ManagerServicesInner>,
}
impl ManagerServices {
#[must_use]
pub fn lock_msr(&self) -> ManagerServicesReadGuard<'_> {
ManagerServicesReadGuard::new(&self.inner)
}
#[must_use]
pub fn lock_msw(&self) -> ManagerServicesWriteGuard<'_> {
ManagerServicesWriteGuard::new(&self.inner)
}
}
impl Suitability for ManagerServices {
/// # Locking (see locking.md)
/// * `ManagerServices::inner` (read)
fn suitability_for_msr(&self, service_group: &str) -> u64 {
self.lock_msr()
.iter()
.find_map(|(_, svc_state)| {
svc_state.service()
.filter(|svc| svc.service_group.as_ref() == service_group)
})
.and_then(Service::suitability)
.unwrap_or_else(u64::min_value)
}
}
}
pub struct Manager {
pub state: Arc<ManagerState>,
butterfly: habitat_butterfly::Server,
census_ring: Arc<RwLock<CensusRing>>,
fs_cfg: Arc<FsCfg>,
launcher: LauncherCli,
service_updater: Arc<Mutex<ServiceUpdater>>,
peer_watcher: Option<PeerWatcher>,
spec_watcher: SpecWatcher,
// This Arc<RwLock<>> business is a potentially temporary
// change. Right now, in order to asynchronously shut down
// services, we need to be able to have a safe reference to this
// from another thread.
//
// Future refactorings may suggest other ways to achieve the same
// result of being able to manipulate the config watcher from
// other threads (e.g., maybe we subscribe to messages to change
// the watcher)
user_config_watcher: UserConfigWatcher,
spec_dir: SpecDir,
organization: Option<String>,
self_updater: Option<SelfUpdater>,
sys: Arc<Sys>,
http_disable: bool,
/// Though it is a `HashMap`, `service_states` not really used as
/// a `HashMap`. The values are there to act as a kind of
/// "snapshot marker"... if any of those time markers change
/// between service checks, that means that something has happened
/// to one of the services (it was up, but now it's down; it was
/// up, then down, then up; etc).
///
/// Feel free to refactor to something different!
service_states: HashMap<PackageIdent, SystemTime>,
/// Collects the identifiers of all services that are currently
/// doing something asynchronously (like shutting down, or running
/// a lifecycle hook). We want to know which to ignore if changes
/// in their spec files are detected while they're asynchronously
/// doing something else. That will prevent us from getting into
/// weird states if spec files change in the middle of us doing
/// something else.
// Currently, this is just going to be things that are shutting
// down, but as more operations become asynchronous, we'll end up
// keeping track of services doing other operations as well. At
// that point, we might need / want to change from a HashSet to
// something else (maybe a HashMap?) in order to cleanly manage
// the different operations.
busy_services: Arc<Mutex<HashSet<PackageIdent>>>,
updated_service_pkg_incarnations: Arc<Mutex<HashMap<ServiceGroup, u64>>>,
services_need_reconciliation: ReconciliationFlag,
feature_flags: FeatureFlag,
pid_source: ServicePidSource,
/// Open file handle to the Launcher's lock file. As long as we hold this,
/// we are the only Supervisor process that may run on this host. We don't
/// actually use this; we just keep it open.
_lock_file: LockFile,
}
impl Manager {
/// Load a Manager with the given configuration.
///
/// The returned Manager will be pre-populated with any cached data from disk from a previous
/// run if available.
///
/// # Locking (see locking.md)
/// * `MemberList::initial_members` (write)
pub async fn load_imlw(cfg: ManagerConfig, launcher: LauncherCli) -> Result<Manager> {
let state_path = cfg.sup_root();
let fs_cfg = FsCfg::new(state_path);
Self::create_state_path_dirs(&fs_cfg)?;
// The lock file exists within the state directory, so we have to create
// it first!
let lock_file = LockFile::acquire()?;
Self::clean_dirty_state(&fs_cfg)?;
Self::new_imlw(cfg, fs_cfg, lock_file, launcher).await
}
/// Terminate the locally-running Supervisor/Launcher (assuming it is
/// running, of course).
///
/// If the lock file can be read successfully, the PID being returned is
/// implicitly assumed to be that of a running Launcher process. That
/// PID is then told to terminate.
pub fn term() -> Result<()> {
let pid = crate::lock_file::read_lock_file()?;
#[cfg(unix)]
process::signal(pid, Signal::TERM).map_err(|_| Error::SignalFailed)?;
#[cfg(windows)]
process::terminate(pid)?;
Ok(())
}
/// # Locking (see locking.md)
/// * `MemberList::initial_members` (write)
async fn new_imlw(cfg: ManagerConfig,
fs_cfg: FsCfg,
lock_file: LockFile,
launcher: LauncherCli)
-> Result<Manager> {
debug!("new(cfg: {:?}, fs_cfg: {:?}", cfg, fs_cfg);
outputln!("{} ({})", SUP_PKG_IDENT, *THIS_SUPERVISOR_IDENT);
let cfg_static = cfg.clone();
let self_updater = if cfg.auto_update {
if THIS_SUPERVISOR_IDENT.fully_qualified() {
Some(SelfUpdater::new(&THIS_SUPERVISOR_IDENT,
cfg.update_url,
cfg.update_channel,
cfg.auto_update_period))
} else {
warn!("Supervisor version not fully qualified, unable to start self-updater");
None
}
} else {
None
};
let mut sys = Sys::new(cfg.gossip_permanent,
cfg.gossip_listen,
cfg.ctl_listen,
cfg.http_listen,
cfg.sys_ip);
let member = Self::load_member(&mut sys, &fs_cfg)?;
let services = Arc::default();
let suitability_lookup = Arc::clone(&services) as Arc<dyn Suitability>;
let server = habitat_butterfly::Server::new(sys.gossip_listen(),
sys.gossip_listen(),
member,
cfg.ring_key,
None,
Some(&fs_cfg.data_path),
suitability_lookup)?;
outputln!("Supervisor Member-ID {}", sys.member_id);
for peer_addr in &cfg.gossip_peers {
let peer = Member { address: format!("{}", peer_addr.ip()),
swim_port: peer_addr.port(),
gossip_port: peer_addr.port(),
..Default::default() };
server.member_list.add_initial_member_imlw(peer);
}
let peer_watcher = if let Some(path) = cfg.watch_peer_file {
Some(PeerWatcher::run(path)?)
} else {
None
};
let spec_dir = SpecDir::new(&fs_cfg.specs_path)?;
spec_dir.migrate_specs();
let spec_watcher = SpecWatcher::run(&spec_dir)?;
trace!("Created SpecWatcher");
if let Some(config) = cfg.event_stream_config {
// Collect the FQDN of the running machine
let fqdn = habitat_core::os::net::fqdn().unwrap_or_else(|| sys.hostname.clone());
outputln!("Event FQDN {}", fqdn);
event::init(&sys, fqdn, config).await?;
}
let pid_source = ServicePidSource::determine_source(&launcher);
let census_ring = Arc::new(RwLock::new(CensusRing::new(sys.member_id.clone())));
Ok(Manager { state: Arc::new(ManagerState { cfg: cfg_static,
services,
gateway_state: Arc::default(),
should_restart: AtomicBool::default() }),
self_updater,
service_updater:
Arc::new(Mutex::new(ServiceUpdater::new(server.clone(),
Arc::clone(&census_ring),
cfg.service_update_period))),
census_ring,
butterfly: server,
launcher,
peer_watcher,
spec_watcher,
user_config_watcher: UserConfigWatcher::new(),
spec_dir,
fs_cfg: Arc::new(fs_cfg),
organization: cfg.organization,
service_states: HashMap::new(),
sys: Arc::new(sys),
http_disable: cfg.http_disable,
busy_services: Arc::default(),
updated_service_pkg_incarnations: Arc::default(),
services_need_reconciliation: ReconciliationFlag::new(false),
feature_flags: cfg.feature_flags,
pid_source,
_lock_file: lock_file })
}
/// Load the initial Butterly Member which is used in initializing the Butterfly server. This
/// will load the member-id for the initial Member from disk if a previous manager has been
/// run.
///
/// The mutable ref to `Sys` will be configured with Butterfly Member details and will also
/// populate the initial Member.
// TODO (CM): This functionality can / should be pulled into
// Butterfly itself; we're already setting the incarnation number
// in there, so splitting the initialization is needlessly
// confusing. It's also blurs the lines between the manager and
// Butterfly.
fn load_member(sys: &mut Sys, fs_cfg: &FsCfg) -> Result<Member> {
let mut member = Member::default();
match File::open(&fs_cfg.member_id_file) {
Ok(mut file) => {
let mut member_id = String::new();
file.read_to_string(&mut member_id).map_err(|e| {
Error::BadDataFile(fs_cfg.member_id_file
.clone(),
e)
})?;
member.id = member_id;
}
Err(_) => {
match File::create(&fs_cfg.member_id_file) {
Ok(mut file) => {
file.write(member.id.as_bytes())
.map_err(|e| Error::BadDataFile(fs_cfg.member_id_file.clone(), e))?;
}
Err(err) => {
return Err(Error::BadDataFile(fs_cfg.member_id_file.clone(), err));
}
}
}
}
sys.member_id = member.id.to_string();
member.persistent = sys.permanent;
Ok(member)
}
fn clean_dirty_state(fs_cfg: &FsCfg) -> Result<()> {
let data_path = &fs_cfg.data_path;
debug!("Cleaning cached health checks");
match fs::read_dir(data_path) {
Ok(entries) => {
for entry in entries.flatten() {
match entry.path().extension().and_then(OsStr::to_str) {
Some("tmp") | Some("health") => {
fs::remove_file(entry.path()).map_err(|err| {
Error::BadDataPath(data_path.clone(),
err)
})?;
}
_ => continue,
}
}
Ok(())
}
Err(err) => Err(Error::BadDataPath(data_path.clone(), err)),
}
}
fn create_state_path_dirs(fs_cfg: &FsCfg) -> Result<()> {
let data_path = &fs_cfg.data_path;
debug!("Creating data directory: {}", data_path.display());
if let Some(err) = fs::create_dir_all(data_path).err() {
return Err(Error::BadDataPath(data_path.clone(), err));
}
let specs_path = &fs_cfg.specs_path;
debug!("Creating specs directory: {}", specs_path.display());
if let Some(err) = fs::create_dir_all(specs_path).err() {
return Err(Error::BadSpecsPath(specs_path.clone(), err));
}
Ok(())
}
async fn maybe_uninstall_old_packages(&self, ident: &PackageIdent) {
if let Some(number_latest_to_keep) = self.state.cfg.keep_latest_packages {
match pkg::uninstall_all_but_latest(ident, number_latest_to_keep).await {
Ok(uninstalled) => {
info!("Uninstalled '{}' '{}' packages keeping the '{}' latest",
uninstalled, ident, number_latest_to_keep)
}
Err(e) => {
error!("Failed to uninstall '{}' packages keeping the '{}' latest, err: {}",
ident, number_latest_to_keep, e)
}
}
}
}
/// # Locking (see locking.md)
/// * `RumorStore::list` (write)
/// * `MemberList::entries` (write)
/// * `RumorHeat::inner` (write)
/// * `ManagerServices::inner` (read)
async fn add_service_rsw_mlw_rhw_msr(&mut self, spec: ServiceSpec) {
let ident = spec.ident.clone();
let mut service = match Service::new(self.sys.clone(),
spec,
self.fs_cfg.clone(),
self.organization.as_deref(),
self.census_ring.clone(),
self.state.gateway_state.clone(),
self.pid_source,
self.feature_flags).await
{
Ok(service) => {
outputln!("Starting {} ({})", ident, service.pkg.ident);
service
}
Err(err) => {
outputln!("Unable to start {}, {}", ident, err);
// Remove the spec file so it does not look like this service is loaded.
self.remove_spec_file(&ident).ok();
return;
}
};
if let Ok(package) =
PackageInstall::load(service.pkg.ident.as_ref(), Some(Path::new(&*FS_ROOT_PATH)))
&& let Err(err) = habitat_common::command::package::install::check_install_hooks(
&mut habitat_common::ui::UI::with_sinks(),
&package,
Path::new(&*FS_ROOT_PATH),
)
.await
{
outputln!("Failed to run install hook for {}, {}", ident, err);
return;
}
if let Err(e) = service.create_svc_path() {
outputln!("Can't create directory {}: {}",
service.pkg.svc_path.display(),
e);
outputln!("If this service is running as non-root, you'll need to create {} and give \
the current user write access to it",
service.pkg.svc_path.display());
outputln!("{} failed to start", ident);
return;
}
// Note: This must take place after `service.create_svc_path`
// because we need the directories to exist before we can
// write files to them.
service.write_initial_service_files(&self.census_ring.read());
// if this service is being started as a result of an update
// then we want to pass along the incarnation in updated_services
self.gossip_latest_service_rumor_rsw_mlw_rhw(&service,
self.updated_service_pkg_incarnations
.lock()
.remove(&service.service_group));
if service.topology() == Topology::Leader {
self.butterfly
.start_election_rsw_mlr_rhw_msr(&service.service_group, 0, None);
}
if let Err(e) = self.user_config_watcher.add(&service) {
outputln!("Unable to start UserConfigWatcher for {}: {}",
service.spec_ident(),
e);