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
//! Service API: manage and inspect docker services within a swarm
pub use crate::models::*;
use super::Docker;
use crate::auth::{base64_url_encode, DockerCredentials};
use crate::errors::Error;
use http::header::CONTENT_TYPE;
use http::request::Builder;
use hyper::{Body, Method};
use serde::ser::Serialize;
use std::{collections::HashMap, hash::Hash};
/// Parameters used in the [List Service API](super::Docker::list_services())
///
/// ## Examples
///
/// ```rust
/// # use std::collections::HashMap;
/// # use std::default::Default;
/// use bollard::service::ListServicesOptions;
///
/// let mut filters = HashMap::new();
/// filters.insert("mode", vec!["global"]);
///
/// ListServicesOptions{
/// filters,
/// };
/// ```
///
/// ```rust
/// # use bollard::service::ListServicesOptions;
/// # use std::default::Default;
///
/// let options: ListServicesOptions<&str> = Default::default();
/// ```
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct ListServicesOptions<T>
where
T: Into<String> + Eq + Hash + Serialize,
{
/// Filters to process on the service list, encoded as JSON. Available filters:
/// - `id`=`<ID>` a services's ID
/// - `label`=`key` or `label`=`"key=value"` of a service label
/// - `mode`=`["replicated"|"global"] a service's scheduling mode
/// - `name`=`<name>` a services's name
#[serde(serialize_with = "crate::docker::serialize_as_json")]
pub filters: HashMap<T, Vec<T>>,
}
/// Parameters used in the [Inspect Service API](Docker::inspect_service())
///
/// ## Examples
///
/// ```rust
/// use bollard::service::InspectServiceOptions;
///
/// InspectServiceOptions{
/// insert_defaults: true,
/// };
/// ```
#[derive(Debug, Copy, Clone, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InspectServiceOptions {
/// Fill empty fields with default values.
pub insert_defaults: bool,
}
/// Parameters used in the [Update Service API](Docker::update_service())
///
/// ## Examples
///
/// ```rust
/// use bollard::service::UpdateServiceOptions;
///
/// UpdateServiceOptions{
/// version: 1234,
/// ..Default::default()
/// };
/// ```
#[derive(Debug, Copy, Clone, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateServiceOptions {
/// The version number of the service object being updated. This is required to avoid conflicting writes. This version number should be the value as currently set on the service before the update.
pub version: u64,
/// If the X-Registry-Auth header is not specified, this parameter indicates whether to use registry authorization credentials from the current or the previous spec.
#[serde(serialize_with = "serialize_registry_auth_from")]
pub registry_auth_from: bool,
/// Set to this parameter to true to cause a server-side rollback to the previous service spec. The supplied spec will be ignored in this case.
#[serde(serialize_with = "serialize_rollback")]
pub rollback: bool,
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub(crate) fn serialize_registry_auth_from<S>(
registry_auth_from: &bool,
s: S,
) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
s.serialize_str(if *registry_auth_from {
"previous-spec"
} else {
"spec"
})
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn serialize_rollback<S>(rollback: &bool, s: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
s.serialize_str(if *rollback { "previous" } else { "" })
}
impl Docker {
/// ---
///
/// # List Services
///
/// Returns a list of services.
///
/// # Arguments
///
/// - Optional [ListServicesOptions](ListServicesOptions) struct.
///
/// # Returns
///
/// - Vector of [Services](Service), wrapped in a Future.
///
/// # Examples
///
/// ```rust
/// # use bollard::Docker;
/// # let docker = Docker::connect_with_http_defaults().unwrap();
/// use bollard::service::ListServicesOptions;
///
/// use std::collections::HashMap;
/// use std::default::Default;
///
/// let mut filters = HashMap::new();
/// filters.insert("mode", vec!["global"]);
///
/// let options = Some(ListServicesOptions{
/// filters,
/// ..Default::default()
/// });
///
/// docker.list_services(options);
/// ```
pub async fn list_services<T>(
&self,
options: Option<ListServicesOptions<T>>,
) -> Result<Vec<Service>, Error>
where
T: Into<String> + Eq + Hash + Serialize,
{
let url = "/services";
let req = self.build_request(
url,
Builder::new().method(Method::GET),
options,
Ok(Body::empty()),
);
self.process_into_value(req).await
}
/// ---
///
/// # Create Service
///
/// Dispatch a new service on the docker swarm
///
/// # Arguments
///
/// - [ServiceSpec](ServiceSpec) struct.
/// - Optional [Docker Credentials](DockerCredentials) struct.
///
/// # Returns
///
/// - A [Service Create Response](ServiceCreateResponse) struct,
/// wrapped in a Future.
///
/// # Examples
///
/// ```rust
/// # use bollard::Docker;
/// # use std::collections::HashMap;
/// # use std::default::Default;
/// # let docker = Docker::connect_with_http_defaults().unwrap();
/// use bollard::service::{
/// ServiceSpec,
/// ServiceSpecMode,
/// ServiceSpecModeReplicated,
/// TaskSpec,
/// TaskSpecContainerSpec
/// };
///
/// let service = ServiceSpec {
/// name: Some(String::from("my-service")),
/// mode: Some(ServiceSpecMode {
/// replicated: Some(ServiceSpecModeReplicated {
/// replicas: Some(2)
/// }),
/// ..Default::default()
/// }),
/// task_template: Some(TaskSpec {
/// container_spec: Some(TaskSpecContainerSpec {
/// image: Some(String::from("hello-world")),
/// ..Default::default()
/// }),
/// ..Default::default()
/// }),
/// ..Default::default()
/// };
/// let credentials = None;
///
/// docker.create_service(service, credentials);
/// ```
pub async fn create_service(
&self,
service_spec: ServiceSpec,
credentials: Option<DockerCredentials>,
) -> Result<ServiceCreateResponse, Error> {
let url = "/services/create";
match serde_json::to_string(&credentials.unwrap_or_else(|| DockerCredentials {
..Default::default()
})) {
Ok(ser_cred) => {
let req = self.build_request(
url,
Builder::new()
.method(Method::POST)
.header(CONTENT_TYPE, "application/json")
.header("X-Registry-Auth", base64_url_encode(&ser_cred)),
None::<String>,
Docker::serialize_payload(Some(service_spec)),
);
self.process_into_value(req).await
}
Err(e) => Err(e.into()),
}
}
/// ---
///
/// # Inspect Service
///
/// Inspect a service.
///
/// # Arguments
///
/// - Service name or id as a string slice.
/// - Optional [Inspect Service Options](InspectServiceOptions) struct.
///
/// # Returns
///
/// - [Service](Service), wrapped in a Future.
///
/// # Examples
///
/// ```rust
/// # use bollard::Docker;
/// # let docker = Docker::connect_with_http_defaults().unwrap();
/// use bollard::service::InspectServiceOptions;
///
/// let options = Some(InspectServiceOptions{
/// insert_defaults: true,
/// });
///
/// docker.inspect_service("my-service", options);
/// ```
pub async fn inspect_service(
&self,
service_name: &str,
options: Option<InspectServiceOptions>,
) -> Result<Service, Error> {
let url = format!("/services/{}", service_name);
let req = self.build_request(
&url,
Builder::new().method(Method::GET),
options,
Ok(Body::empty()),
);
self.process_into_value(req).await
}
/// ---
///
/// # Delete Service
///
/// Delete a service.
///
/// # Arguments
///
/// - Service name or id as a string slice.
///
/// # Returns
///
/// - unit type `()`, wrapped in a Future.
///
/// # Examples
///
/// ```rust
/// # use bollard::Docker;
/// # let docker = Docker::connect_with_http_defaults().unwrap();
///
/// docker.delete_service("my-service");
/// ```
pub async fn delete_service(&self, service_name: &str) -> Result<(), Error> {
let url = format!("/services/{}", service_name);
let req = self.build_request(
&url,
Builder::new().method(Method::DELETE),
None::<String>,
Ok(Body::empty()),
);
self.process_into_unit(req).await
}
/// ---
///
/// # Update Service
///
/// Update an existing service
///
/// # Arguments
///
/// - Service name or id as a string slice.
/// - [ServiceSpec](ServiceSpec) struct.
/// - [UpdateServiceOptions](UpdateServiceOptions) struct.
/// - Optional [Docker Credentials](DockerCredentials) struct.
///
/// # Returns
///
/// - A [Service Update Response](ServiceUpdateResponse) struct,
/// wrapped in a Future.
///
/// # Examples
///
/// ```rust
/// # use bollard::Docker;
/// # let docker = Docker::connect_with_http_defaults().unwrap();
/// use bollard::service::{
/// InspectServiceOptions,
/// ServiceSpec,
/// ServiceSpecMode,
/// ServiceSpecModeReplicated,
/// TaskSpec,
/// TaskSpecContainerSpec,
/// UpdateServiceOptions,
/// };
///
/// use std::collections::HashMap;
/// use std::default::Default;
///
/// let result = async move {
/// let service_name = "my-service";
/// let current_version = docker.inspect_service(
/// service_name,
/// None::<InspectServiceOptions>
/// ).await?.version.unwrap().index.unwrap();
/// let service = ServiceSpec {
/// mode: Some(ServiceSpecMode {
/// replicated: Some(ServiceSpecModeReplicated {
/// replicas: Some(0)
/// }),
/// ..Default::default()
/// }),
/// ..Default::default()
/// };
/// let options = UpdateServiceOptions {
/// version: current_version,
/// ..Default::default()
/// };
/// let credentials = None;
///
/// docker.update_service("my-service", service, options, credentials).await
/// };
/// ```
pub async fn update_service(
&self,
service_name: &str,
service_spec: ServiceSpec,
options: UpdateServiceOptions,
credentials: Option<DockerCredentials>,
) -> Result<ServiceUpdateResponse, Error> {
let url = format!("/services/{}/update", service_name);
match serde_json::to_string(&credentials.unwrap_or_else(|| DockerCredentials {
..Default::default()
})) {
Ok(ser_cred) => {
let req = self.build_request(
&url,
Builder::new()
.method(Method::POST)
.header(CONTENT_TYPE, "application/json")
.header("X-Registry-Auth", base64_url_encode(&ser_cred)),
Some(options),
Docker::serialize_payload(Some(service_spec)),
);
self.process_into_value(req).await
}
Err(e) => Err(e.into()),
}
}
}