bollard_next/network.rs
1//! Network API: Networks are user-defined networks that containers can be attached to.
2
3use bytes::Bytes;
4use http::request::Builder;
5use http_body_util::Full;
6use hyper::Method;
7use serde_derive::{Deserialize, Serialize};
8
9use std::cmp::Eq;
10use std::collections::HashMap;
11use std::hash::Hash;
12
13use super::Docker;
14use crate::docker::BodyType;
15use crate::errors::Error;
16
17use crate::models::*;
18
19/// Network configuration used in the [Create Network API](Docker::create_network())
20#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
21#[serde(rename_all = "PascalCase")]
22pub struct CreateNetworkOptions<T>
23where
24 T: Into<String> + Eq + Hash,
25{
26 /// The network's name.
27 pub name: T,
28 /// Check for networks with duplicate names. Since Network is primarily keyed based on a random
29 /// ID and not on the name, and network name is strictly a user-friendly alias to the network
30 /// which is uniquely identified using ID, there is no guaranteed way to check for duplicates.
31 /// CheckDuplicate is there to provide a best effort checking of any networks which has the
32 /// same name but it is not guaranteed to catch all name collisions.
33 pub check_duplicate: bool,
34 /// Name of the network driver plugin to use.
35 pub driver: T,
36 /// Restrict external access to the network.
37 pub internal: bool,
38 /// Globally scoped network is manually attachable by regular containers from workers in swarm mode.
39 pub attachable: bool,
40 /// Ingress network is the network which provides the routing-mesh in swarm mode.
41 pub ingress: bool,
42 /// Controls IP address management when creating a network.
43 #[serde(rename = "IPAM")]
44 pub ipam: Ipam,
45 /// Enable IPv6 on the network.
46 #[serde(rename = "EnableIPv6")]
47 pub enable_ipv6: bool,
48 /// Network specific options to be used by the drivers.
49 pub options: HashMap<T, T>,
50 /// User-defined key/value metadata.
51 pub labels: HashMap<T, T>,
52}
53
54/// Parameters used in the [Inspect Network API](super::Docker::inspect_network())
55///
56/// ## Examples
57///
58/// ```rust
59/// use bollard_next::network::InspectNetworkOptions;
60///
61/// InspectNetworkOptions{
62/// verbose: true,
63/// scope: "global",
64/// };
65/// ```
66///
67/// ```rust
68/// # use bollard_next::network::InspectNetworkOptions;
69/// # use std::default::Default;
70/// InspectNetworkOptions::<&str>{
71/// ..Default::default()
72/// };
73/// ```
74#[derive(Debug, Clone, Default, PartialEq, Serialize)]
75pub struct InspectNetworkOptions<T>
76where
77 T: Into<String> + serde::ser::Serialize,
78{
79 /// Detailed inspect output for troubleshooting.
80 pub verbose: bool,
81 /// Filter the network by scope (swarm, global, or local)
82 pub scope: T,
83}
84
85/// Parameters used in the [List Networks API](super::Docker::list_networks())
86///
87/// ## Examples
88///
89/// ```rust
90/// use bollard_next::network::ListNetworksOptions;
91///
92/// use std::collections::HashMap;
93///
94/// let mut filters = HashMap::new();
95/// filters.insert("label", vec!["maintainer=some_maintainer"]);
96///
97/// ListNetworksOptions{
98/// filters
99/// };
100/// ```
101///
102/// ```rust
103/// # use bollard_next::network::ListNetworksOptions;
104/// # use std::default::Default;
105///
106/// ListNetworksOptions::<&str> {
107/// ..Default::default()
108/// };
109/// ```
110#[derive(Debug, Clone, Default, PartialEq, Serialize)]
111pub struct ListNetworksOptions<T>
112where
113 T: Into<String> + Eq + Hash + serde::ser::Serialize,
114{
115 /// JSON encoded value of the filters (a `map[string][]string`) to process on the networks list. Available filters:
116 /// - `driver=<driver-name>` Matches a network's driver.
117 /// - `id=<network-id>` Matches all or part of a network ID.
118 /// - `label=<key>` or `label=<key>=<value>` of a network label.
119 /// - `name=<network-name>` Matches all or part of a network name.
120 /// - `scope=["swarm"|"global"|"local"]` Filters networks by scope (`swarm`, `global`, or `local`).
121 /// - `type=["custom"|"builtin"]` Filters networks by type. The `custom` keyword returns all user-defined networks.
122 #[serde(serialize_with = "crate::docker::serialize_as_json")]
123 pub filters: HashMap<T, Vec<T>>,
124}
125
126/// Network configuration used in the [Connect Network API](Docker::connect_network())
127#[derive(Debug, Clone, Default, PartialEq, Serialize)]
128#[serde(rename_all = "PascalCase")]
129pub struct ConnectNetworkOptions<T>
130where
131 T: Into<String> + Eq + Hash + serde::ser::Serialize,
132{
133 /// The ID or name of the container to connect to the network.
134 pub container: T,
135 /// Configuration for a network endpoint.
136 pub endpoint_config: EndpointSettings,
137}
138
139/// Network configuration used in the [Disconnect Network API](Docker::disconnect_network())
140#[derive(Debug, Clone, Default, PartialEq, Serialize)]
141#[serde(rename_all = "PascalCase")]
142pub struct DisconnectNetworkOptions<T>
143where
144 T: Into<String> + serde::ser::Serialize,
145{
146 /// The ID or name of the container to disconnect from the network.
147 pub container: T,
148 /// Force the container to disconnect from the network.
149 pub force: bool,
150}
151
152/// Parameters used in the [Prune Networks API](Docker::prune_networks())
153///
154/// ## Examples
155///
156/// ```rust
157/// use bollard_next::network::PruneNetworksOptions;
158///
159/// use std::collections::HashMap;
160///
161/// let mut filters = HashMap::new();
162/// filters.insert("label!", vec!["maintainer=some_maintainer"]);
163///
164/// PruneNetworksOptions{
165/// filters
166/// };
167/// ```
168///
169/// ```rust
170/// # use bollard_next::network::PruneNetworksOptions;
171/// # use std::default::Default;
172///
173/// PruneNetworksOptions::<&str>{
174/// ..Default::default()
175/// };
176/// ```
177#[derive(Debug, Clone, Default, PartialEq, Serialize)]
178pub struct PruneNetworksOptions<T>
179where
180 T: Into<String> + Eq + Hash + serde::ser::Serialize,
181{
182 /// Filters to process on the prune list, encoded as JSON.
183 /// - `until=<timestamp>` Prune networks created before this timestamp. The `<timestamp>` can be
184 /// Unix timestamps, date formatted timestamps, or Go duration strings (e.g. `10m`, `1h30m`)
185 /// computed relative to the daemon machine’s time.
186 /// - label (`label=<key>`, `label=<key>=<value>`, `label!=<key>`, or `label!=<key>=<value>`)
187 /// Prune networks with (or without, in case `label!=...` is used) the specified labels.
188 #[serde(serialize_with = "crate::docker::serialize_as_json")]
189 pub filters: HashMap<T, Vec<T>>,
190}
191
192impl Docker {
193 /// ---
194 ///
195 /// # Create Network
196 ///
197 /// Create a new network.
198 ///
199 /// # Arguments
200 ///
201 /// - [Create Network Options](CreateNetworkOptions) struct.
202 ///
203 /// # Returns
204 ///
205 /// - A [Network Create Response](NetworkCreateResponse) struct, wrapped in a
206 /// Future.
207 ///
208 /// # Examples
209 ///
210 /// ```rust
211 /// # use bollard_next::Docker;
212 /// # let docker = Docker::connect_with_http_defaults().unwrap();
213 ///
214 /// use bollard_next::network::CreateNetworkOptions;
215 ///
216 /// use std::default::Default;
217 ///
218 /// let config = CreateNetworkOptions {
219 /// name: "certs",
220 /// ..Default::default()
221 /// };
222 ///
223 /// docker.create_network(config);
224 /// ```
225 pub async fn create_network<T>(
226 &self,
227 config: CreateNetworkOptions<T>,
228 ) -> Result<NetworkCreateResponse, Error>
229 where
230 T: Into<String> + Eq + Hash + serde::ser::Serialize,
231 {
232 let url = "/networks/create";
233
234 let req = self.build_request(
235 url,
236 Builder::new().method(Method::POST),
237 None::<String>,
238 Docker::serialize_payload(Some(config)),
239 );
240
241 self.process_into_value(req).await
242 }
243
244 /// ---
245 ///
246 /// # Remove a Network
247 ///
248 /// # Arguments
249 ///
250 /// - Network name as a string slice.
251 ///
252 /// # Returns
253 ///
254 /// - unit type `()`, wrapped in a Future.
255 ///
256 /// # Examples
257 ///
258 /// ```rust
259 /// # use bollard_next::Docker;
260 /// # let docker = Docker::connect_with_http_defaults().unwrap();
261 ///
262 /// docker.remove_network("my_network_name");
263 /// ```
264 pub async fn remove_network(&self, network_name: &str) -> Result<(), Error> {
265 let url = format!("/networks/{network_name}");
266
267 let req = self.build_request(
268 &url,
269 Builder::new().method(Method::DELETE),
270 None::<String>,
271 Ok(BodyType::Left(Full::new(Bytes::new()))),
272 );
273
274 self.process_into_unit(req).await
275 }
276
277 /// ---
278 ///
279 /// # Inspect a Network
280 ///
281 /// # Arguments
282 ///
283 /// - Network name as a string slice.
284 ///
285 /// # Returns
286 ///
287 /// - A [Models](Network) struct, wrapped in a
288 /// Future.
289 ///
290 /// # Examples
291 ///
292 /// ```rust
293 /// # use bollard_next::Docker;
294 /// # let docker = Docker::connect_with_http_defaults().unwrap();
295 ///
296 /// use bollard_next::network::InspectNetworkOptions;
297 ///
298 /// use std::default::Default;
299 ///
300 /// let config = InspectNetworkOptions {
301 /// verbose: true,
302 /// scope: "global"
303 /// };
304 ///
305 /// docker.inspect_network("my_network_name", Some(config));
306 /// ```
307 pub async fn inspect_network<T>(
308 &self,
309 network_name: &str,
310 options: Option<InspectNetworkOptions<T>>,
311 ) -> Result<Network, Error>
312 where
313 T: Into<String> + serde::ser::Serialize,
314 {
315 let url = format!("/networks/{network_name}");
316
317 let req = self.build_request(
318 &url,
319 Builder::new().method(Method::GET),
320 options,
321 Ok(BodyType::Left(Full::new(Bytes::new()))),
322 );
323
324 self.process_into_value(req).await
325 }
326
327 /// ---
328 ///
329 /// # List Networks
330 ///
331 /// # Arguments
332 ///
333 /// - Optional [List Network Options](ListNetworksOptions) struct.
334 ///
335 /// # Returns
336 ///
337 /// - A vector of [Network](Network) struct, wrapped in a
338 /// Future.
339 ///
340 /// # Examples
341 ///
342 /// ```rust
343 /// # use bollard_next::Docker;
344 /// # let docker = Docker::connect_with_http_defaults().unwrap();
345 ///
346 /// use bollard_next::network::ListNetworksOptions;
347 ///
348 /// use std::collections::HashMap;
349 ///
350 /// let mut list_networks_filters = HashMap::new();
351 /// list_networks_filters.insert("label", vec!["maintainer=some_maintainer"]);
352 ///
353 /// let config = ListNetworksOptions {
354 /// filters: list_networks_filters,
355 /// };
356 ///
357 /// docker.list_networks(Some(config));
358 /// ```
359 pub async fn list_networks<T>(
360 &self,
361 options: Option<ListNetworksOptions<T>>,
362 ) -> Result<Vec<Network>, Error>
363 where
364 T: Into<String> + Eq + Hash + serde::ser::Serialize,
365 {
366 let url = "/networks";
367
368 let req = self.build_request(
369 url,
370 Builder::new().method(Method::GET),
371 options,
372 Ok(BodyType::Left(Full::new(Bytes::new()))),
373 );
374
375 self.process_into_value(req).await
376 }
377
378 /// ---
379 ///
380 /// # Connect Network
381 ///
382 /// # Arguments
383 ///
384 /// - A [Connect Network Options](ConnectNetworkOptions) struct.
385 ///
386 /// # Returns
387 ///
388 /// - unit type `()`, wrapped in a Future.
389 ///
390 /// # Examples
391 ///
392 /// ```rust
393 /// # use bollard_next::Docker;
394 /// # let docker = Docker::connect_with_http_defaults().unwrap();
395 ///
396 /// use bollard_next::network::ConnectNetworkOptions;
397 /// use bollard_next::models::{EndpointSettings, EndpointIpamConfig};
398 ///
399 /// use std::default::Default;
400 ///
401 /// let config = ConnectNetworkOptions {
402 /// container: "3613f73ba0e4",
403 /// endpoint_config: EndpointSettings {
404 /// ipam_config: Some(EndpointIpamConfig {
405 /// ipv4_address: Some(String::from("172.24.56.89")),
406 /// ipv6_address: Some(String::from("2001:db8::5689")),
407 /// ..Default::default()
408 /// }),
409 /// ..Default::default()
410 /// }
411 /// };
412 ///
413 /// docker.connect_network("my_network_name", config);
414 /// ```
415 pub async fn connect_network<T>(
416 &self,
417 network_name: &str,
418 config: ConnectNetworkOptions<T>,
419 ) -> Result<(), Error>
420 where
421 T: Into<String> + Eq + Hash + serde::ser::Serialize,
422 {
423 let url = format!("/networks/{network_name}/connect");
424
425 let req = self.build_request(
426 &url,
427 Builder::new().method(Method::POST),
428 None::<String>,
429 Docker::serialize_payload(Some(config)),
430 );
431
432 self.process_into_unit(req).await
433 }
434
435 /// ---
436 ///
437 /// # Disconnect Network
438 ///
439 /// # Arguments
440 ///
441 /// - A [Disconnect Network Options](DisconnectNetworkOptions) struct.
442 ///
443 /// # Returns
444 ///
445 /// - unit type `()`, wrapped in a Future.
446 ///
447 /// # Examples
448 ///
449 /// ```rust
450 /// # use bollard_next::Docker;
451 /// # let docker = Docker::connect_with_http_defaults().unwrap();
452 ///
453 /// use bollard_next::network::DisconnectNetworkOptions;
454 ///
455 /// use std::default::Default;
456 ///
457 /// let config = DisconnectNetworkOptions {
458 /// container: "3613f73ba0e4",
459 /// force: true
460 /// };
461 ///
462 /// docker.disconnect_network("my_network_name", config);
463 /// ```
464 pub async fn disconnect_network<T>(
465 &self,
466 network_name: &str,
467 config: DisconnectNetworkOptions<T>,
468 ) -> Result<(), Error>
469 where
470 T: Into<String> + serde::ser::Serialize,
471 {
472 let url = format!("/networks/{network_name}/disconnect");
473
474 let req = self.build_request(
475 &url,
476 Builder::new().method(Method::POST),
477 None::<String>,
478 Docker::serialize_payload(Some(config)),
479 );
480
481 self.process_into_unit(req).await
482 }
483
484 /// ---
485 ///
486 /// # Prune Networks
487 ///
488 /// Deletes networks which are unused.
489 ///
490 /// # Arguments
491 ///
492 /// - A [Prune Networks Options](PruneNetworksOptions) struct.
493 ///
494 /// # Returns
495 ///
496 /// - A [Network Prune Response](NetworkPruneResponse) struct.
497 ///
498 /// # Examples
499 ///
500 /// ```rust
501 /// # use bollard_next::Docker;
502 /// # let docker = Docker::connect_with_http_defaults().unwrap();
503 ///
504 /// use bollard_next::network::PruneNetworksOptions;
505 ///
506 /// use std::collections::HashMap;
507 ///
508 /// let mut filters = HashMap::new();
509 /// filters.insert("label", vec!["maintainer=some_maintainer"]);
510 ///
511 /// let options = PruneNetworksOptions {
512 /// filters,
513 /// };
514 ///
515 /// docker.prune_networks(Some(options));
516 /// ```
517 pub async fn prune_networks<T>(
518 &self,
519 options: Option<PruneNetworksOptions<T>>,
520 ) -> Result<NetworkPruneResponse, Error>
521 where
522 T: Into<String> + Eq + Hash + serde::ser::Serialize,
523 {
524 let url = "/networks/prune";
525
526 let req = self.build_request(
527 url,
528 Builder::new().method(Method::POST),
529 options,
530 Ok(BodyType::Left(Full::new(Bytes::new()))),
531 );
532
533 self.process_into_value(req).await
534 }
535}