-
Notifications
You must be signed in to change notification settings - Fork 138
/
orchestrator.rs
3144 lines (2827 loc) · 114 KB
/
orchestrator.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
use bollard::container::{
Config, CreateContainerOptions, KillContainerOptions, ListContainersOptions,
PruneContainersOptions, WaitContainerOptions,
};
use bollard::errors::Error as DockerError;
use bollard::exec::CreateExecOptions;
use bollard::image::CreateImageOptions;
use bollard::models::{HostConfig, PortBinding};
use bollard::network::{CreateNetworkOptions, PruneNetworksOptions};
use bollard::service::Ipam;
use bollard::Docker;
use chainhook_sdk::utils::Context;
use clarinet_files::chainhook_types::StacksNetwork;
use clarinet_files::{DevnetConfigFile, NetworkManifest, ProjectManifest};
use futures::stream::TryStreamExt;
use hiro_system_kit::slog;
use reqwest::RequestBuilder;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::Write;
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, Sender};
use std::time::Duration;
use crate::event::{send_status_update, DevnetEvent, Status};
#[derive(Debug)]
pub struct DevnetOrchestrator {
pub name: String,
network_name: String,
pub manifest: ProjectManifest,
pub network_config: Option<NetworkManifest>,
pub termination_success_tx: Option<Sender<bool>>,
pub can_exit: bool,
stacks_node_container_id: Option<String>,
stacks_signer_1_container_id: Option<String>,
stacks_signer_2_container_id: Option<String>,
stacks_api_container_id: Option<String>,
stacks_explorer_container_id: Option<String>,
bitcoin_node_container_id: Option<String>,
bitcoin_explorer_container_id: Option<String>,
postgres_container_id: Option<String>,
subnet_node_container_id: Option<String>,
subnet_api_container_id: Option<String>,
docker_client: Option<Docker>,
services_map_hosts: Option<ServicesMapHosts>,
}
// pub enum DevnetServices {
// BitcoinNode,
// StacksNode,
// StacksApi,
// StacksExplorer,
// BitcoinExplorer,
// SubnetNode,
// SubnetApi,
// }
#[derive(Clone, Debug)]
pub struct ServicesMapHosts {
pub bitcoin_node_host: String,
pub stacks_node_host: String,
pub stacks_api_host: String,
pub postgres_host: String,
pub stacks_explorer_host: String,
pub bitcoin_explorer_host: String,
pub subnet_node_host: String,
pub subnet_api_host: String,
}
impl DevnetOrchestrator {
pub fn new(
manifest: ProjectManifest,
network_manifest: Option<NetworkManifest>,
devnet_override: Option<DevnetConfigFile>,
should_use_docker: bool,
) -> Result<DevnetOrchestrator, String> {
let mut network_config = match network_manifest {
Some(n) => Ok(n),
None => NetworkManifest::from_project_manifest_location(
&manifest.location,
&StacksNetwork::Devnet.get_networks(),
Some(&manifest.project.cache_location),
devnet_override,
),
}?;
if let Some(ref mut devnet) = network_config.devnet {
let working_dir = PathBuf::from(&devnet.working_dir);
let devnet_path = if working_dir.is_absolute() {
working_dir
} else {
let mut cwd = std::env::current_dir()
.map_err(|e| format!("unable to retrieve current dir ({})", e))?;
cwd.push(&working_dir);
let _ = fs::create_dir(&cwd);
cwd.canonicalize().map_err(|e| {
format!(
"unable to canonicalize working_dir {} ({})",
working_dir.display(),
e
)
})?
};
devnet.working_dir = format!("{}", devnet_path.display());
}
let name = manifest.project.name.to_string();
let mut network_name = name.clone();
if let Some(ref devnet) = network_config.devnet {
if let Some(ref network_id) = devnet.network_id {
network_name.push_str(&format!(".{}", network_id));
}
network_name.push_str(&format!(".{}", devnet.name));
} else {
network_name.push_str(".net");
}
let docker_client = match should_use_docker {
true => match network_config.devnet {
Some(ref devnet) => {
let client = Docker::connect_with_socket(
&devnet.docker_host,
120,
bollard::API_DEFAULT_VERSION,
)
.or_else(|_| Docker::connect_with_socket_defaults())
.or_else(|_| {
let mut user_space_docker_socket =
dirs::home_dir().expect("unable to retrieve homedir");
user_space_docker_socket.push(".docker");
user_space_docker_socket.push("run");
user_space_docker_socket.push("docker.sock");
Docker::connect_with_socket(
user_space_docker_socket.to_str().unwrap(),
120,
bollard::API_DEFAULT_VERSION,
)
})
.map_err(|e| format!("unable to connect to docker: {:?}", e))?;
Some(client)
}
None => unreachable!(),
},
false => None,
};
Ok(DevnetOrchestrator {
name,
network_name,
manifest,
network_config: Some(network_config),
docker_client,
can_exit: true,
termination_success_tx: None,
stacks_node_container_id: None,
stacks_signer_1_container_id: None,
stacks_signer_2_container_id: None,
stacks_api_container_id: None,
stacks_explorer_container_id: None,
bitcoin_node_container_id: None,
bitcoin_explorer_container_id: None,
postgres_container_id: None,
subnet_node_container_id: None,
subnet_api_container_id: None,
services_map_hosts: None,
})
}
pub fn prepare_network_k8s_coordinator(
&mut self,
namespace: &str,
) -> Result<ServicesMapHosts, String> {
let services_map_hosts = ServicesMapHosts {
bitcoin_node_host: format!(
"bitcoind-chain-coordinator.{namespace}.svc.cluster.local:18443"
),
stacks_node_host: format!("stacks-blockchain.{namespace}.svc.cluster.local:20443"),
postgres_host: format!("stacks-blockchain-api.{namespace}.svc.cluster.local:5432"),
stacks_api_host: format!("stacks-blockchain-api.{namespace}.svc.cluster.local:3999"),
stacks_explorer_host: "localhost".into(), // todo (micaiah)
bitcoin_explorer_host: "localhost".into(), // todo (micaiah)
subnet_node_host: "localhost".into(), // todo (micaiah)
subnet_api_host: "localhost".into(), // todo (micaiah)
};
self.services_map_hosts = Some(services_map_hosts.clone());
Ok(services_map_hosts)
}
pub async fn prepare_local_network(&mut self) -> Result<ServicesMapHosts, String> {
let (docker, devnet_config) = match (&self.docker_client, &self.network_config) {
(Some(ref docker), Some(ref network_config)) => match network_config.devnet {
Some(ref devnet_config) => (docker, devnet_config),
_ => return Err("unable to get devnet config".to_string()),
},
_ => return Err("unable to get devnet config".to_string()),
};
// First, let's make sure that we pruned staled resources correctly
// self.clean_previous_session().await?;
let mut labels = HashMap::new();
labels.insert("project", self.network_name.as_str());
let mut options = HashMap::new();
options.insert("enable_ip_masquerade", "true");
options.insert("enable_icc", "true");
options.insert("host_binding_ipv4", "0.0.0.0");
options.insert("com.docker.network.bridge.enable_icc", "true");
options.insert("com.docker.network.bridge.enable_ip_masquerade", "true");
options.insert("com.docker.network.bridge.host_binding_ipv4", "0.0.0.0");
let network_id = docker
.create_network::<&str>(CreateNetworkOptions {
name: &self.network_name,
driver: "bridge",
ipam: Ipam {
..Default::default()
},
labels,
options,
..Default::default()
})
.await
.map_err(|e| {
format!(
"clarinet was unable to create network. Is docker running locally? (error: {})",
e
)
})?
.id
.ok_or("unable to retrieve network_id")?;
let res = docker
.inspect_network::<&str>(&network_id, None)
.await
.map_err(|e| format!("unable to retrieve network: {}", e))?;
let gateway = res
.ipam
.as_ref()
.and_then(|ipam| ipam.config.as_ref())
.and_then(|config| config.first())
.and_then(|map| map.gateway.clone())
.ok_or("unable to retrieve gateway")?;
let services_map_hosts = if devnet_config.use_docker_gateway_routing {
ServicesMapHosts {
bitcoin_node_host: format!("{}:{}", gateway, devnet_config.bitcoin_node_rpc_port),
stacks_node_host: format!("{}:{}", gateway, devnet_config.stacks_node_rpc_port),
postgres_host: format!("{}:{}", gateway, devnet_config.postgres_port),
stacks_api_host: format!("{}:{}", gateway, devnet_config.stacks_api_port),
stacks_explorer_host: format!("{}:{}", gateway, devnet_config.stacks_explorer_port),
bitcoin_explorer_host: format!(
"{}:{}",
gateway, devnet_config.bitcoin_explorer_port
),
subnet_node_host: format!("{}:{}", gateway, devnet_config.subnet_node_rpc_port),
subnet_api_host: format!("{}:{}", gateway, devnet_config.subnet_api_port),
}
} else {
ServicesMapHosts {
bitcoin_node_host: format!("localhost:{}", devnet_config.bitcoin_node_rpc_port),
stacks_node_host: format!("localhost:{}", devnet_config.stacks_node_rpc_port),
postgres_host: format!("localhost:{}", devnet_config.postgres_port),
stacks_api_host: format!("localhost:{}", devnet_config.stacks_api_port),
stacks_explorer_host: format!("localhost:{}", devnet_config.stacks_explorer_port),
bitcoin_explorer_host: format!("localhost:{}", devnet_config.bitcoin_explorer_port),
subnet_node_host: format!("localhost:{}", devnet_config.subnet_node_rpc_port),
subnet_api_host: format!("localhost:{}", devnet_config.subnet_api_port),
}
};
self.services_map_hosts = Some(services_map_hosts.clone());
Ok(services_map_hosts)
}
pub async fn start(
&mut self,
event_tx: Sender<DevnetEvent>,
terminator_rx: Receiver<bool>,
ctx: &Context,
) -> Result<(), String> {
let (_docker, devnet_config) = match (&self.docker_client, &self.network_config) {
(Some(ref docker), Some(ref network_config)) => match network_config.devnet {
Some(ref devnet_config) => (docker, devnet_config),
_ => return Err("unable to get devnet config".to_string()),
},
_ => return Err("unable to get devnet config".to_string()),
};
let mut boot_index = 1;
let _ = event_tx.send(DevnetEvent::info(format!(
"Initiating Devnet boot sequence (working_dir: {})",
devnet_config.working_dir
)));
let mut devnet_path = PathBuf::from(&devnet_config.working_dir);
devnet_path.push("data");
let disable_stacks_api = devnet_config.disable_stacks_api;
let disable_stacks_explorer = devnet_config.disable_stacks_explorer;
let disable_bitcoin_explorer = devnet_config.disable_bitcoin_explorer;
let enable_subnet_node = devnet_config.enable_subnet_node;
let disable_subnet_api = devnet_config.disable_subnet_api;
let _ = fs::create_dir(&devnet_config.working_dir);
let _ = fs::create_dir(format!("{}/conf", devnet_config.working_dir));
let _ = fs::create_dir(format!("{}/data", devnet_config.working_dir));
let bitcoin_explorer_port = devnet_config.bitcoin_explorer_port;
let stacks_explorer_port = devnet_config.stacks_explorer_port;
let stacks_api_port = devnet_config.stacks_api_port;
let subnet_api_port = devnet_config.subnet_api_port;
send_status_update(
&event_tx,
enable_subnet_node,
"bitcoin-node",
Status::Red,
"initializing",
);
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-node",
Status::Red,
"initializing",
);
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-signer-1",
Status::Red,
"initializing",
);
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-signer-2",
Status::Red,
"initializing",
);
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-api",
Status::Red,
"initializing",
);
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-explorer",
Status::Red,
"initializing",
);
send_status_update(
&event_tx,
enable_subnet_node,
"bitcoin-explorer",
Status::Red,
"initializing",
);
if enable_subnet_node {
send_status_update(
&event_tx,
enable_subnet_node,
"subnet-node",
Status::Red,
"initializing",
);
send_status_update(
&event_tx,
enable_subnet_node,
"subnet-api",
Status::Red,
"initializing",
);
}
let _ = event_tx.send(DevnetEvent::info(format!(
"Creating network {}",
self.network_name
)));
// Start bitcoind
let _ = event_tx.send(DevnetEvent::info("Starting bitcoin-node".to_string()));
send_status_update(
&event_tx,
enable_subnet_node,
"bitcoin-node",
Status::Yellow,
"preparing container",
);
match self.prepare_bitcoin_node_container(ctx).await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
send_status_update(
&event_tx,
enable_subnet_node,
"bitcoin-node",
Status::Yellow,
"booting",
);
match self.boot_bitcoin_node_container().await {
Ok(_) => {
self.initialize_bitcoin_node(&event_tx).await?;
}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
// Start stacks-api
if !disable_stacks_api {
// Start postgres
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-api",
Status::Yellow,
"preparing postgres container",
);
let _ = event_tx.send(DevnetEvent::info("Starting postgres".to_string()));
match self.prepare_postgres_container(ctx).await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
match self.boot_postgres_container(ctx).await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-api",
Status::Yellow,
"preparing container",
);
let _ = event_tx.send(DevnetEvent::info("Starting stacks-api".to_string()));
match self.prepare_stacks_api_container(ctx).await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-api",
Status::Green,
&format!("http://localhost:{}/doc", stacks_api_port),
);
match self.boot_stacks_api_container(ctx).await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
}
// Start subnet node
if enable_subnet_node {
let _ = event_tx.send(DevnetEvent::info("Starting subnet-node".to_string()));
match self.prepare_subnet_node_container(boot_index, ctx).await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
send_status_update(
&event_tx,
enable_subnet_node,
"subnet-node",
Status::Yellow,
"booting",
);
match self.boot_subnet_node_container().await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
if !disable_subnet_api {
let _ = event_tx.send(DevnetEvent::info("Starting subnet-api".to_string()));
match self.prepare_subnet_api_container(ctx).await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
send_status_update(
&event_tx,
enable_subnet_node,
"subnet-api",
Status::Green,
&format!("http://localhost:{}/doc", subnet_api_port),
);
match self.boot_subnet_api_container().await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
}
}
// Start stacks-node
let _ = event_tx.send(DevnetEvent::info("Starting stacks-node".to_string()));
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-node",
Status::Yellow,
"updating image",
);
match self.prepare_stacks_node_container(boot_index, ctx).await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-node",
Status::Yellow,
"booting",
);
match self.boot_stacks_node_container().await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
// Start stacks-signer-1
let _ = event_tx.send(DevnetEvent::info("Starting stacks-signer-1".to_string()));
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-signer-1",
Status::Yellow,
"updating image",
);
match self
.prepare_stacks_signer_container(boot_index, ctx, 1)
.await
{
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-signer-1",
Status::Yellow,
"booting",
);
match self.boot_stacks_signer_container(1).await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-signer-1",
Status::Green,
"running",
);
// Start stacks-signer-2
let _ = event_tx.send(DevnetEvent::info("Starting stacks-signer-2".to_string()));
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-signer-2",
Status::Yellow,
"updating image",
);
match self
.prepare_stacks_signer_container(boot_index, ctx, 2)
.await
{
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-signer-2",
Status::Yellow,
"booting",
);
match self.boot_stacks_signer_container(2).await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-signer-2",
Status::Green,
"running",
);
// Start stacks-explorer
if !disable_stacks_explorer {
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-explorer",
Status::Yellow,
"preparing container",
);
match self.prepare_stacks_explorer_container(ctx).await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
let _ = event_tx.send(DevnetEvent::info("Starting stacks-explorer".to_string()));
match self.boot_stacks_explorer_container(ctx).await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-explorer",
Status::Green,
&format!("http://localhost:{}", stacks_explorer_port),
);
}
// Start bitcoin-explorer
if !disable_bitcoin_explorer {
send_status_update(
&event_tx,
enable_subnet_node,
"bitcoin-explorer",
Status::Yellow,
"preparing container",
);
match self.prepare_bitcoin_explorer_container(ctx).await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
let _ = event_tx.send(DevnetEvent::info("Starting bitcoin-explorer".to_string()));
match self.boot_bitcoin_explorer_container(ctx).await {
Ok(_) => {}
Err(message) => {
let _ = event_tx.send(DevnetEvent::FatalError(message.clone()));
self.kill(ctx, Some(&message)).await;
return Err(message);
}
};
send_status_update(
&event_tx,
enable_subnet_node,
"bitcoin-explorer",
Status::Green,
&format!("http://localhost:{}", bitcoin_explorer_port),
);
}
loop {
boot_index += 1;
match terminator_rx.recv() {
Ok(true) => {
self.kill(ctx, None).await;
break;
}
Ok(false) => {
send_status_update(
&event_tx,
enable_subnet_node,
"bitcoin-node",
Status::Yellow,
"restarting",
);
send_status_update(
&event_tx,
enable_subnet_node,
"stacks-node",
Status::Yellow,
"restarting",
);
let _ = event_tx.send(DevnetEvent::debug("Killing containers".into()));
let _ = self.stop_containers().await;
let _ = event_tx.send(DevnetEvent::debug("Restarting containers".into()));
let (bitcoin_node_c_id, stacks_node_c_id) = self
.start_containers(boot_index)
.await
.map_err(|e| format!("unable to reboot: {:?}", e))?;
self.bitcoin_node_container_id = Some(bitcoin_node_c_id);
self.stacks_node_container_id = Some(stacks_node_c_id);
}
Err(_) => {
break;
}
}
}
Ok(())
}
pub fn prepare_bitcoin_node_config(&self, boot_index: u32) -> Result<Config<String>, String> {
let devnet_config = match &self.network_config {
Some(ref network_config) => match network_config.devnet {
Some(ref devnet_config) => devnet_config,
_ => return Err("unable to get devnet configuration".into()),
},
_ => return Err("unable to get Docker client".into()),
};
let mut port_bindings = HashMap::new();
port_bindings.insert(
format!("{}/tcp", devnet_config.bitcoin_node_p2p_port),
Some(vec![PortBinding {
host_ip: Some(String::from("0.0.0.0")),
host_port: Some(format!("{}/tcp", devnet_config.bitcoin_node_p2p_port)),
}]),
);
port_bindings.insert(
format!("{}/tcp", devnet_config.bitcoin_node_rpc_port),
Some(vec![PortBinding {
host_ip: Some(String::from("0.0.0.0")),
host_port: Some(format!("{}/tcp", devnet_config.bitcoin_node_rpc_port)),
}]),
);
let bitcoind_conf = format!(
r#"
server=1
regtest=1
rpcallowip=0.0.0.0/0
rpcallowip=::/0
rpcuser={bitcoin_node_username}
rpcpassword={bitcoin_node_password}
txindex=1
listen=1
discover=0
dns=0
dnsseed=0
listenonion=0
rpcworkqueue=100
rpcserialversion=1
disablewallet=0
fallbackfee=0.00001
[regtest]
bind=0.0.0.0:{bitcoin_node_p2p_port}
rpcbind=0.0.0.0:{bitcoin_node_rpc_port}
rpcport={bitcoin_node_rpc_port}
"#,
bitcoin_node_username = devnet_config.bitcoin_node_username,
bitcoin_node_password = devnet_config.bitcoin_node_password,
bitcoin_node_p2p_port = devnet_config.bitcoin_node_p2p_port,
bitcoin_node_rpc_port = devnet_config.bitcoin_node_rpc_port,
);
let mut bitcoind_conf_path = PathBuf::from(&devnet_config.working_dir);
bitcoind_conf_path.push("conf");
fs::create_dir_all(&bitcoind_conf_path)
.map_err(|e| format!("unable to create bitcoin conf directory: {}", e))?;
bitcoind_conf_path.push("bitcoin.conf");
let mut file = File::create(bitcoind_conf_path)
.map_err(|e| format!("unable to create bitcoin.conf: {}", e))?;
file.write_all(bitcoind_conf.as_bytes())
.map_err(|e| format!("unable to write bitcoin.conf: {:?}", e))?;
let mut bitcoind_data_path = PathBuf::from(&devnet_config.working_dir);
bitcoind_data_path.push("data");
bitcoind_data_path.push(format!("{}", boot_index));
bitcoind_data_path.push("bitcoin");
fs::create_dir_all(bitcoind_data_path)
.map_err(|e| format!("unable to create bitcoin directory: {:?}", e))?;
let mut exposed_ports = HashMap::new();
exposed_ports.insert(
format!("{}/tcp", devnet_config.bitcoin_node_rpc_port),
HashMap::new(),
);
exposed_ports.insert(
format!("{}/tcp", devnet_config.bitcoin_node_p2p_port),
HashMap::new(),
);
let mut labels = HashMap::new();
labels.insert("project".to_string(), self.network_name.to_string());
labels.insert("reset".to_string(), "true".to_string());
let mut env = vec![];
if devnet_config.bitcoin_controller_automining_disabled {
env.push("STACKS_BITCOIN_AUTOMINING_DISABLED=1".to_string());
}
let mut binds = vec![format!("{}/conf:/etc/bitcoin", devnet_config.working_dir)];
if devnet_config.bind_containers_volumes {
binds.push(format!(
"{}/data/{}/bitcoin:/root/.bitcoin",
devnet_config.working_dir, boot_index
));
}
let config = Config {
labels: Some(labels),
image: Some(devnet_config.bitcoin_node_image_url.clone()),
// domainname: Some(self.network_name.to_string()),
tty: None,
exposed_ports: Some(exposed_ports),
entrypoint: Some(vec![]),
env: Some(env),
host_config: Some(HostConfig {
auto_remove: Some(true),
binds: Some(binds),
network_mode: Some(self.network_name.clone()),
port_bindings: Some(port_bindings),
extra_hosts: Some(vec!["host.docker.internal:host-gateway".into()]),
..Default::default()
}),
cmd: Some(vec![
"/usr/local/bin/bitcoind".into(),
"-conf=/etc/bitcoin/bitcoin.conf".into(),
"-nodebuglogfile".into(),
"-pid=/run/bitcoind.pid".into(),
// "-datadir=/root/.bitcoin".into(),
]),
..Default::default()
};
Ok(config)
}
pub async fn prepare_bitcoin_node_container(&mut self, ctx: &Context) -> Result<(), String> {
let (docker, devnet_config) = match (&self.docker_client, &self.network_config) {
(Some(ref docker), Some(ref network_config)) => match network_config.devnet {
Some(ref devnet_config) => (docker, devnet_config),
_ => return Err("unable to get devnet configuration".into()),
},
_ => return Err("unable to get Docker client".into()),
};
let _info = docker
.create_image(
Some(CreateImageOptions {
from_image: devnet_config.bitcoin_node_image_url.clone(),
platform: devnet_config.docker_platform.clone(),
..Default::default()
}),
None,
None,
)
.try_collect::<Vec<_>>()
.await
.map_err(|e| formatted_docker_error("unable to create bitcoind image", e))?;
let config = self.prepare_bitcoin_node_config(1)?;
let container_name = format!("bitcoin-node.{}", self.network_name);
let options = CreateContainerOptions {
name: container_name.as_str(),
platform: Some(&devnet_config.docker_platform),
};
let container = match docker
.create_container::<&str, String>(Some(options.clone()), config.clone())
.await
.map_err(|e| formatted_docker_error("unable to create bitcoind container", e))
{
Ok(container) => container.id,
Err(_e) => {
// Attempt to clean eventual subsequent artifacts
let _ = docker.kill_container::<String>(&container_name, None).await;
docker
.create_container::<&str, String>(Some(options), config)
.await
.map_err(|e| formatted_docker_error("unable to create bitcoind container", e))?
.id
}
};
ctx.try_log(|logger| slog::info!(logger, "Created container bitcoin-node: {}", container));
self.bitcoin_node_container_id = Some(container);
Ok(())
}
pub async fn clean_previous_session(&self) -> Result<(), String> {
let mut filters = HashMap::new();
filters.insert(
"label".to_string(),
vec![format!("project={}", self.network_name)],
);
let options = Some(ListContainersOptions {
all: true,
filters,
..Default::default()
});
let docker = match &self.docker_client {
Some(ref docker) => docker,
_ => panic!("unable to get Docker client"),
};
let res = docker.list_containers(options).await;
let containers = match res {
Ok(containers) => containers,
Err(e) => {
let err = format!("unable to communicate with Docker: {}\nvisit https://docs.hiro.so/clarinet/troubleshooting#i-am-unable-to-start-devnet-though-my-docker-is-running to resolve this issue.", e);
return Err(err);
}
};
let options = KillContainerOptions { signal: "SIGKILL" };
for container in containers.iter() {
let container_id = match &container.id {
Some(id) => id,
None => continue,
};
let _ = docker
.kill_container(container_id, Some(options.clone()))
.await;
let _ = docker
.wait_container(container_id, None::<WaitContainerOptions<String>>)
.try_collect::<Vec<_>>()
.await;
}
self.prune().await;
Ok(())