Skip to main content

hydro_deploy/
lib.rs

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