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
//! Api Reference: <https://docs.docker.com/engine/api/v1.41/#tag/Plugin>

use crate::{errors::Result, transport::Payload, Docker};

use serde::{Deserialize, Serialize};
use std::{collections::HashMap, path::Path};
use url::form_urlencoded;

#[derive(Debug)]
/// Interface for accessing and manipulating a Docker plugin.
///
/// Api Reference: <https://docs.docker.com/engine/api/v1.41/#tag/Plugin>
pub struct Plugin<'docker> {
    docker: &'docker Docker,
    name: String,
}

impl<'docker> Plugin<'docker> {
    /// Exports an interface for operations that may be performed against a named image.
    pub fn new<S>(docker: &'docker Docker, name: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            docker,
            name: name.into(),
        }
    }

    /// Inspects a named plugin's details.
    ///
    /// Api Reference: <https://docs.docker.com/engine/api/v1.41/#operation/PluginInspect>
    pub async fn inspect(&self) -> Result<PluginInfo> {
        self.docker
            .get_json(&format!("/plugins/{}/json", self.name)[..])
            .await
    }

    async fn _remove(&self, force: bool) -> Result<PluginInfo> {
        let mut path = format!("/plugins/{}", self.name);
        if force {
            let query = form_urlencoded::Serializer::new(String::new())
                .append_pair("force", &force.to_string())
                .finish();
            path.push('?');
            path.push_str(&query);
        }
        self.docker.delete_json(&path[..]).await
    }

    /// Removes a plugin.
    ///
    /// Api Reference: <https://docs.docker.com/engine/api/v1.41/#operation/PluginDelete>
    pub async fn remove(&self) -> Result<PluginInfo> {
        self._remove(false).await
    }

    /// Forcefully remove a plugin. This may result in issues if the plugin is in use by a container.
    ///
    /// Api Reference: <https://docs.docker.com/engine/api/v1.41/#operation/PluginDelete>
    pub async fn force_remove(&self) -> Result<PluginInfo> {
        self._remove(true).await
    }

    /// Enable a plugin.
    ///
    /// Api Reference: <https://docs.docker.com/engine/api/v1.41/#operation/PluginEnable>
    pub async fn enable(&self, timeout: Option<u64>) -> Result<()> {
        let mut path = format!("/plugins/{}/enable", self.name);
        if let Some(timeout) = timeout {
            let query = form_urlencoded::Serializer::new(String::new())
                .append_pair("timeout", &timeout.to_string())
                .finish();
            path.push('?');
            path.push_str(&query);
        }

        self.docker.post(&path, Payload::empty()).await.map(|_| ())
    }

    /// Disable a plugin.
    ///
    /// Api Reference: <https://docs.docker.com/engine/api/v1.41/#operation/PluginDisable>
    pub async fn disable(&self) -> Result<()> {
        self.docker
            .post(&format!("/plugins/{}/disable", self.name), Payload::empty())
            .await
            .map(|_| ())
    }

    /// Push a plugin to the registry.
    ///
    /// Api Reference: <https://docs.docker.com/engine/api/v1.41/#operation/PluginPush>
    pub async fn push(&self) -> Result<()> {
        self.docker
            .post(&format!("/plugins/{}/push", self.name), Payload::empty())
            .await
            .map(|_| ())
    }

    /// Create a plugin from a tar archive on the file system. The `path` parameter is a path
    /// to the tar containing plugin rootfs and manifest.
    ///
    /// Api Reference: <https://docs.docker.com/engine/api/v1.41/#operation/PluginCreate>
    pub async fn create<P>(&self, path: P) -> Result<()>
    where
        P: AsRef<Path>,
    {
        self.docker
            .post(
                &format!("/plugins/{}/create", self.name),
                Payload::Text(path.as_ref().to_string_lossy().to_string()),
            )
            .await
            .map(|_| ())
    }
}

#[derive(Debug)]
/// Interface for docker plugins
pub struct Plugins<'docker> {
    docker: &'docker Docker,
}

impl<'docker> Plugins<'docker> {
    /// Exports an interface for interacting with docker plugins
    pub fn new(docker: &'docker Docker) -> Self {
        Self { docker }
    }

    /// Returns a reference to a set of operations available for a plugin with `name`
    pub fn get<N>(&self, name: N) -> Plugin<'docker>
    where
        N: Into<String>,
    {
        Plugin::new(self.docker, name)
    }

    /// Returns information about installed plugins.
    ///
    /// Api Reference: <https://docs.docker.com/engine/api/v1.41/#operation/PluginList>
    pub async fn list(&self, opts: &PluginListOptions) -> Result<Vec<PluginInfo>> {
        let mut path = vec!["/images/json".to_owned()];
        if let Some(query) = opts.serialize() {
            path.push(query);
        }
        self.docker
            .get_json::<Vec<PluginInfo>>(&path.join("?"))
            .await
    }
}

impl_url_opts_builder!(PluginList);

impl PluginListOptionsBuilder {
    pub fn filter<F>(&mut self, filters: F) -> &mut Self
    where
        F: IntoIterator<Item = PluginFilter>,
    {
        let mut param = HashMap::new();
        for f in filters {
            match f {
                PluginFilter::Capability(cap) => param.insert("capability", vec![cap]),
                PluginFilter::Enable => param.insert("enable", vec![true.to_string()]),
                PluginFilter::Disable => param.insert("enable", vec![false.to_string()]),
            };
        }
        // structure is a a json encoded object mapping string keys to a list
        // of string values
        self.params
            .insert("filters", serde_json::to_string(&param).unwrap_or_default());
        self
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PluginInfo {
    pub id: Option<String>,
    pub name: String,
    pub enabled: bool,
    pub settings: PluginSettings,
    pub plugin_reference: Option<String>,
    pub config: PluginConfig,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PluginSettings {
    pub mounts: Vec<PluginMount>,
    pub env: Vec<String>,
    pub args: Vec<String>,
    pub devices: Vec<PluginDevice>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PluginMount {
    pub name: String,
    pub description: String,
    pub settable: Vec<String>,
    pub source: String,
    pub destination: String,
    #[serde(rename = "Type")]
    pub type_: String,
    pub options: Vec<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PluginDevice {
    pub name: String,
    pub description: String,
    pub settable: Vec<String>,
    pub path: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PluginConfig {
    pub docker_version: Option<String>,
    pub description: String,
    pub documentation: String,
    pub interface: PluginInterface,
    pub entrypoint: Vec<String>,
    pub work_dir: String,
    pub user: Option<User>,
    pub network: PluginNetwork,
    pub linux: LinuxInfo,
    pub propagated_mount: String,
    pub ipc_host: bool,
    pub pid_host: bool,
    pub mounts: Vec<PluginMount>,
    pub env: Vec<PluginEnv>,
    pub args: PluginArgs,
    pub rootfs: Option<PluginRootfs>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct User {
    #[serde(rename = "UID")]
    pub uid: u32,
    #[serde(rename = "GID")]
    pub gid: u32,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct LinuxInfo {
    pub capabilities: Vec<String>,
    pub allow_all_devices: bool,
    pub devices: Vec<PluginDevice>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PluginNetwork {
    #[serde(rename = "Type")]
    pub type_: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PluginInterface {
    pub types: Vec<PluginInterfaceType>,
    pub socket: String,
    pub protocol_scheme: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PluginInterfaceType {
    pub prefix: String,
    pub capability: String,
    pub version: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PluginEnv {
    pub name: String,
    pub description: String,
    pub settable: Vec<String>,
    pub value: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PluginArgs {
    pub name: String,
    pub description: String,
    pub settable: Vec<String>,
    pub value: Vec<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PluginRootfs {
    #[serde(rename = "type")]
    pub type_: Option<String>,
    pub diff_ids: Option<Vec<String>>,
}

pub enum PluginFilter {
    Capability(String),
    Enable,
    Disable,
}