hydro_deploy/
lib.rs

1use std::any::Any;
2use std::collections::HashMap;
3use std::fmt::Debug;
4use std::net::SocketAddr;
5use std::sync::Arc;
6
7use anyhow::Result;
8use append_only_vec::AppendOnlyVec;
9use async_trait::async_trait;
10use hydro_deploy_integration::ServerBindConfig;
11use rust_crate::build::BuildOutput;
12use rust_crate::tracing_options::TracingOptions;
13use tokio::sync::{mpsc, oneshot};
14
15pub mod deployment;
16pub use deployment::Deployment;
17
18pub mod progress;
19
20pub mod localhost;
21pub use localhost::LocalhostHost;
22
23pub mod ssh;
24
25pub mod gcp;
26pub use gcp::GcpComputeEngineHost;
27
28pub mod azure;
29pub use azure::AzureHost;
30
31pub mod aws;
32pub use aws::{AwsEc2Host, AwsNetwork};
33
34pub mod rust_crate;
35pub use rust_crate::RustCrate;
36
37pub mod custom_service;
38pub use custom_service::CustomService;
39
40pub mod terraform;
41
42pub mod util;
43
44#[derive(Default)]
45pub struct ResourcePool {
46    pub terraform: terraform::TerraformPool,
47}
48
49pub struct ResourceBatch {
50    pub terraform: terraform::TerraformBatch,
51}
52
53impl ResourceBatch {
54    fn new() -> ResourceBatch {
55        ResourceBatch {
56            terraform: terraform::TerraformBatch::default(),
57        }
58    }
59
60    async fn provision(
61        self,
62        pool: &mut ResourcePool,
63        last_result: Option<Arc<ResourceResult>>,
64    ) -> Result<ResourceResult> {
65        Ok(ResourceResult {
66            terraform: self.terraform.provision(&mut pool.terraform).await?,
67            _last_result: last_result,
68        })
69    }
70}
71
72#[derive(Debug)]
73pub struct ResourceResult {
74    pub terraform: terraform::TerraformResult,
75    _last_result: Option<Arc<ResourceResult>>,
76}
77
78#[derive(Clone, Debug)]
79pub struct TracingResults {
80    pub folded_data: Vec<u8>,
81}
82
83#[async_trait]
84pub trait LaunchedBinary: Send + Sync {
85    fn stdin(&self) -> mpsc::UnboundedSender<String>;
86
87    /// Provides a oneshot channel to handshake with the binary,
88    /// with the guarantee that as long as deploy is holding on
89    /// to a handle, none of the messages will also be broadcast
90    /// to the user-facing [`LaunchedBinary::stdout`] channel.
91    fn deploy_stdout(&self) -> oneshot::Receiver<String>;
92
93    fn stdout(&self) -> mpsc::UnboundedReceiver<String>;
94    fn stderr(&self) -> mpsc::UnboundedReceiver<String>;
95    fn stdout_filter(&self, prefix: String) -> mpsc::UnboundedReceiver<String>;
96    fn stderr_filter(&self, prefix: String) -> mpsc::UnboundedReceiver<String>;
97
98    fn tracing_results(&self) -> Option<&TracingResults>;
99
100    fn exit_code(&self) -> Option<i32>;
101
102    /// Wait for the process to stop on its own. Returns the exit code.
103    async fn wait(&self) -> Result<i32>;
104    /// If the process is still running, force stop it. Then run post-run tasks.
105    async fn stop(&self) -> Result<()>;
106}
107
108#[async_trait]
109pub trait LaunchedHost: Send + Sync {
110    /// Given a pre-selected network type, computes concrete information needed for a service
111    /// to listen to network connections (such as the IP address to bind to).
112    fn base_server_config(&self, strategy: &BaseServerStrategy) -> ServerBindConfig;
113
114    fn server_config(&self, strategy: &ServerStrategy) -> ServerBindConfig {
115        match strategy {
116            ServerStrategy::Direct(b) => self.base_server_config(b),
117            ServerStrategy::Many(b) => {
118                ServerBindConfig::MultiConnection(Box::new(self.base_server_config(b)))
119            }
120            ServerStrategy::Demux(demux) => ServerBindConfig::Demux(
121                demux
122                    .iter()
123                    .map(|(key, underlying)| (*key, self.server_config(underlying)))
124                    .collect::<HashMap<_, _>>(),
125            ),
126            ServerStrategy::Merge(merge) => ServerBindConfig::Merge(
127                merge
128                    .iter()
129                    .map(|underlying| self.server_config(underlying))
130                    .collect(),
131            ),
132            ServerStrategy::Tagged(underlying, id) => {
133                ServerBindConfig::Tagged(Box::new(self.server_config(underlying)), *id)
134            }
135            ServerStrategy::Null => ServerBindConfig::Null,
136        }
137    }
138
139    async fn copy_binary(&self, binary: &BuildOutput) -> Result<()>;
140
141    async fn launch_binary(
142        &self,
143        id: String,
144        binary: &BuildOutput,
145        args: &[String],
146        perf: Option<TracingOptions>,
147    ) -> Result<Box<dyn LaunchedBinary>>;
148
149    async fn forward_port(&self, addr: &SocketAddr) -> Result<SocketAddr>;
150}
151
152pub enum BaseServerStrategy {
153    UnixSocket,
154    InternalTcpPort(Option<u16>),
155    ExternalTcpPort(
156        /// The port number to bind to, which must be explicit to open the firewall.
157        u16,
158    ),
159}
160
161/// Types of connection that a service can receive when configured as the server.
162pub enum ServerStrategy {
163    Direct(BaseServerStrategy),
164    Many(BaseServerStrategy),
165    Demux(HashMap<u32, ServerStrategy>),
166    /// AppendOnlyVec has a quite large inline array, so we box it.
167    Merge(Box<AppendOnlyVec<ServerStrategy>>),
168    Tagged(Box<ServerStrategy>, u32),
169    Null,
170}
171
172/// Like BindType, but includes metadata for determining whether a connection is possible.
173pub enum ClientStrategy<'a> {
174    UnixSocket(
175        /// Unique identifier for the host this socket will be on.
176        usize,
177    ),
178    InternalTcpPort(
179        /// The host that this port is available on.
180        &'a dyn Host,
181    ),
182    ForwardedTcpPort(
183        /// The host that this port is available on.
184        &'a dyn Host,
185    ),
186}
187
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
189pub enum HostTargetType {
190    Local,
191    Linux(LinuxCompileType),
192}
193
194#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
195pub enum LinuxCompileType {
196    Glibc,
197    Musl,
198}
199
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
201pub enum PortNetworkHint {
202    Auto,
203    TcpPort(Option<u16>),
204}
205
206pub type HostStrategyGetter = Box<dyn FnOnce(&dyn Any) -> BaseServerStrategy>;
207
208pub trait Host: Any + Send + Sync + Debug {
209    fn target_type(&self) -> HostTargetType;
210
211    fn request_port_base(&self, bind_type: &BaseServerStrategy);
212
213    fn request_port(&self, bind_type: &ServerStrategy) {
214        match bind_type {
215            ServerStrategy::Direct(base) => self.request_port_base(base),
216            ServerStrategy::Many(base) => self.request_port_base(base),
217            ServerStrategy::Demux(demux) => {
218                for bind_type in demux.values() {
219                    self.request_port(bind_type);
220                }
221            }
222            ServerStrategy::Merge(merge) => {
223                for bind_type in merge.iter() {
224                    self.request_port(bind_type);
225                }
226            }
227            ServerStrategy::Tagged(underlying, _) => {
228                self.request_port(underlying);
229            }
230            ServerStrategy::Null => {}
231        }
232    }
233
234    /// An identifier for this host, which is unique within a deployment.
235    fn id(&self) -> usize;
236
237    /// Configures the host to support copying and running a custom binary.
238    fn request_custom_binary(&self);
239
240    /// Makes requests for physical resources (servers) that this host needs to run.
241    ///
242    /// This should be called before `provision` is called.
243    fn collect_resources(&self, resource_batch: &mut ResourceBatch);
244
245    /// Connects to the acquired resources and prepares the host to run services.
246    ///
247    /// This should be called after `collect_resources` is called.
248    fn provision(&self, resource_result: &Arc<ResourceResult>) -> Arc<dyn LaunchedHost>;
249
250    fn launched(&self) -> Option<Arc<dyn LaunchedHost>>;
251
252    /// Identifies a network type that this host can use for connections if it is the server.
253    /// The host will be `None` if the connection is from the same host as the target.
254    fn strategy_as_server<'a>(
255        &'a self,
256        connection_from: &dyn Host,
257        server_tcp_port_hint: PortNetworkHint,
258    ) -> Result<(ClientStrategy<'a>, HostStrategyGetter)>;
259
260    /// Determines whether this host can connect to another host using the given strategy.
261    fn can_connect_to(&self, typ: ClientStrategy) -> bool;
262}
263
264#[async_trait]
265pub trait Service: Send + Sync {
266    /// Makes requests for physical resources server ports that this service needs to run.
267    /// This should **not** recursively call `collect_resources` on the host, since
268    /// we guarantee that `collect_resources` is only called once per host.
269    ///
270    /// This should also perform any "free", non-blocking computations (compilations),
271    /// because the `deploy` method will be called after these resources are allocated.
272    fn collect_resources(&self, resource_batch: &mut ResourceBatch);
273
274    /// Connects to the acquired resources and prepares the service to be launched.
275    async fn deploy(&self, resource_result: &Arc<ResourceResult>) -> Result<()>;
276
277    /// Launches the service, which should start listening for incoming network
278    /// connections. The service should not start computing at this point.
279    async fn ready(&self) -> Result<()>;
280
281    /// Starts the service by having it connect to other services and start computations.
282    async fn start(&self) -> Result<()>;
283
284    /// Stops the service by having it disconnect from other services and stop computations.
285    async fn stop(&self) -> Result<()>;
286}
287
288pub trait ServiceBuilder {
289    type Service: Service + 'static;
290    fn build(self, id: usize, on: Arc<dyn Host>) -> Self::Service;
291}
292
293impl<S: Service + 'static, This: FnOnce(usize, Arc<dyn Host>) -> S> ServiceBuilder for This {
294    type Service = S;
295    fn build(self, id: usize, on: Arc<dyn Host>) -> Self::Service {
296        (self)(id, on)
297    }
298}