nydus-rs 2.2.0

Nydus Image Service
Documentation
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
// Copyright 2020 Ant Group. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

use std::collections::HashMap;
use std::thread::sleep;
use std::time::Duration;

use anyhow::Result;
use nydus::{FsBackendDescriptor, FsBackendType};

use crate::client::NydusdClient;

type CommandParams = HashMap<String, String>;

fn load_param_interval(params: &Option<CommandParams>) -> Result<Option<u32>> {
    if let Some(p) = params {
        if let Some(interval) = p.get("interval") {
            interval
                .parse()
                .map(Some)
                .map_err(|e| anyhow!("Invalid interval input. {}", e))
        } else {
            Ok(None)
        }
    } else {
        Ok(None)
    }
}

pub(crate) struct CommandCache {}

macro_rules! items_map(
    { $($key:expr => $value:expr),+ } => {
        {
            let mut m: HashMap<String, String> = HashMap::new();
            $(
                m.insert($key.to_string(), $value.to_string());
            )+
            m
        }
     };
);

lazy_static! {
    pub static ref CONFIGURE_ITEMS_MAP: HashMap<String, String> =
        items_map!("log-level" => "log_level");
}

impl CommandCache {
    pub async fn execute(
        &self,
        raw: bool,
        client: &NydusdClient,
        _params: Option<CommandParams>,
    ) -> Result<()> {
        let metrics = client.get("v1/metrics/blobcache").await?;
        let m = metrics.as_object().unwrap();

        let prefetch_duration = m["prefetch_end_time_secs"].as_f64().unwrap()
            + m["prefetch_end_time_millis"].as_f64().unwrap() / 1000.0
            - (m["prefetch_begin_time_secs"].as_f64().unwrap()
                + m["prefetch_begin_time_millis"].as_f64().unwrap() / 1000.0);

        let prefetch_data_amount = m["prefetch_data_amount"].as_f64().unwrap();

        if raw {
            println!("{}", metrics);
        } else {
            print!(
                r#"
Partial Hits:               {partial_hits}
Whole Hits:                 {whole_hits}
Total Read:                 {total_read}
Directory:                  {directory}
Files:                      {files}
Persister Buffer:           {buffered}

Prefetch Workers:           {workers}
Prefetch Amount:            {prefetch_amount} = {prefetch_amount_kb} KB
Prefetch Requests:          {requests}
Prefetch Average Size:      {avg_prefetch_size} Bytes
Prefetch Duration:          {prefetch_duration} Seconds
Prefetch Bandwidth:         {prefetch_bandwidth} MB/S
Prefetch Request Latency:   {prefetch_request_latency} Seconds
Prefetch Unmerged:          {unmerged_blocks}
"#,
                partial_hits = m["partial_hits"],
                whole_hits = m["whole_hits"],
                total_read = m["total"],
                prefetch_amount = prefetch_data_amount,
                prefetch_amount_kb = prefetch_data_amount / 1024.0,
                files = m["underlying_files"],
                directory = m["store_path"],
                requests = m["prefetch_requests_count"],
                avg_prefetch_size = m["prefetch_data_amount"]
                    .as_u64()
                    .unwrap()
                    .checked_div(m["prefetch_requests_count"].as_u64().unwrap())
                    .unwrap_or_default(),
                workers = m["prefetch_workers"],
                unmerged_blocks = m["prefetch_unmerged_chunks"],
                buffered = m["buffered_backend_size"],
                prefetch_duration = prefetch_duration,
                prefetch_bandwidth = prefetch_data_amount / 1024.0 / 1024.0 / prefetch_duration,
                prefetch_request_latency = m["prefetch_cumulative_time_millis"].as_f64().unwrap()
                    / m["prefetch_requests_count"].as_f64().unwrap()
                    / 1000.0
            );
        }

        Ok(())
    }
}

fn metric_delta(old: &serde_json::Value, new: &serde_json::Value, label: &str) -> u64 {
    new[label].as_u64().unwrap() - old[label].as_u64().unwrap()
}

fn metric_vec_delta(old: &serde_json::Value, new: &serde_json::Value, label: &str) -> Vec<u64> {
    let new_array = new[label].as_array().unwrap();
    let old_array = old[label].as_array().unwrap();
    assert_eq!(new_array.len(), old_array.len());
    let mut r = Vec::new();

    for i in 0..new_array.len() {
        r.push(new_array[i].as_u64().unwrap() - old_array[i].as_u64().unwrap());
    }

    r
}

pub(crate) struct CommandBackend {}

impl CommandBackend {
    pub async fn execute(
        &self,
        raw: bool,
        client: &NydusdClient,
        params: Option<CommandParams>,
    ) -> Result<()> {
        let metrics = client.get("v1/metrics/backend").await?;

        let interval = load_param_interval(&params)?;
        if let Some(i) = interval {
            let mut last = metrics;
            loop {
                sleep(Duration::from_secs(i as u64));
                let current = client.get("v1/metrics/backend").await?;

                let delta_data = metric_delta(&last, &current, "read_amount_total");
                let delta_requests = metric_delta(&last, &current, "read_count");
                let delta_latency =
                    metric_delta(&last, &current, "read_cumulative_latency_millis_total");
                // Block size separated counters.
                // 1K; 4K; 16K; 64K, 128K, 512K, 1M
                // <=1ms, <=20ms, <=50ms, <=100ms, <=500ms, <=1s, <=2s, >2s

                // TODO: Also add 256k
                let latency_cumulative_dist =
                    metric_vec_delta(&last, &current, "read_cumulative_latency_millis_dist");
                let latency_block_hits =
                    metric_vec_delta(&last, &current, "read_count_block_size_dist");

                let sizes = vec!["<1K", "1K~", "4K~", "16K~", "64K~", "128K~", "512K~", "1M~"];

                print!(
                    r#"
>>> >>> >>> >>> >>>
Backend Read Bandwidth:     {} KB/S
Backend Average IO Size:    {} Bytes
Backend Average Latency:    {} millis

Block Sizes/millis:
{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}
"#,
                    delta_data.checked_div(i as u64 * 1024).unwrap_or_default(),
                    delta_data.checked_div(delta_requests).unwrap_or_default(),
                    delta_latency
                        .checked_div(delta_requests)
                        .unwrap_or_default(),
                    sizes[0],
                    sizes[1],
                    sizes[2],
                    sizes[3],
                    sizes[4],
                    sizes[5],
                    sizes[6],
                    sizes[7]
                );

                for (i, _) in sizes.iter().enumerate() {
                    print!(
                        "{:<8}",
                        latency_cumulative_dist[i]
                            .checked_div(latency_block_hits[i])
                            .unwrap_or_default()
                    );
                }

                println!();
                println!("<<< <<< <<< <<< <<<");

                last = current;
            }
        }

        if raw {
            println!("{}", metrics);
        } else {
            let sizes = vec!["<1K", "1K~", "4K~", "16K~", "64K~", "128K~", "512K~", "1M~"];
            let m = metrics.as_object().unwrap();
            print!(
                r#"
Backend Type:       {backend_type}
Read Amount:        {read_amount} Bytes ({read_count_mb} MB)
Read Count:         {read_count}
Read Errors:        {read_errors}
"#,
                backend_type = m["backend_type"],
                read_amount = m["read_amount_total"],
                read_count = m["read_count"],
                read_count_mb = m["read_amount_total"].as_f64().unwrap() / 1024.0 / 1024.0,
                read_errors = m["read_errors"],
            );

            println!(
                r#"
{:<25}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}"#,
                "Block Sizes:",
                sizes[0],
                sizes[1],
                sizes[2],
                sizes[3],
                sizes[4],
                sizes[5],
                sizes[6],
                sizes[7],
            );

            let latency_cumulative_dist =
                m["read_cumulative_latency_millis_dist"].as_array().unwrap();
            let latency_block_hits = m["read_count_block_size_dist"].as_array().unwrap();

            print!("{:<25}", "Average Latency(millis):");

            for (i, _) in sizes.iter().enumerate() {
                print!(
                    "{:<8}",
                    latency_cumulative_dist[i]
                        .as_u64()
                        .unwrap()
                        .checked_div(latency_block_hits[i].as_u64().unwrap())
                        .unwrap_or_default()
                );
            }

            println!();

            println!(
                r#"
{:<25}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}"#,
                "Block Sizes:",
                sizes[0],
                sizes[1],
                sizes[2],
                sizes[3],
                sizes[4],
                sizes[5],
                sizes[6],
                sizes[7]
            );

            print!("{:<25}", "Request Count:");

            for (i, _) in sizes.iter().enumerate() {
                print!("{:<8}", latency_block_hits[i].as_u64().unwrap());
            }

            println!();
        }

        Ok(())
    }
}

pub(crate) struct CommandFsStats {}

impl CommandFsStats {
    pub async fn execute(
        &self,
        raw: bool,
        client: &NydusdClient,
        _params: Option<CommandParams>,
    ) -> Result<()> {
        let metrics = client.get("v1/metrics").await?;
        let m = metrics.as_object().unwrap();
        let fop_counter = m["fop_hits"].as_array().unwrap();
        let fop_errors = m["fop_errors"].as_array().unwrap();
        if raw {
            println!("{}", metrics);
        } else {
            let periods = vec![
                "<1ms", "~20ms", "~50ms", "~100ms", "~500ms", "~1s", "~2s", "2s~",
            ];
            let latency_dist = m["read_latency_dist"].as_array().unwrap();
            println!(
                r#"
{:<16}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}"#,
                "Read Latency:",
                periods[0],
                periods[1],
                periods[2],
                periods[3],
                periods[4],
                periods[5],
                periods[6],
                periods[7],
            );

            print!("{:<16}", "Reads Count:");
            for d in latency_dist {
                print!("{:<8}", d.as_u64().unwrap());
            }

            println!("\n");

            println!("Read Errors: {}", fop_errors[4]);
            let data_read = m["data_read"].as_u64().unwrap();
            println!(
                "Read Data: {}Bytes ({}MB)",
                data_read,
                data_read / 1024 / 1024
            );

            print!(
                r#"
FOP Counters:
Getattr({}) Readlink({}) Open({}) Release({}) Read({}) Statfs({}) Getxattr({}) Listxattr({})
Opendir({}) Lookup({}) Readdir({}) Readdirplus({}) Access({}) Forget({}) BatchForget({})
"#,
                fop_counter[0],
                fop_counter[1],
                fop_counter[2],
                fop_counter[3],
                fop_counter[4],
                fop_counter[5],
                fop_counter[6],
                fop_counter[7],
                fop_counter[8],
                fop_counter[9],
                fop_counter[10],
                fop_counter[11],
                fop_counter[12],
                fop_counter[13],
                fop_counter[14],
            );
        }

        Ok(())
    }
}

pub(crate) struct CommandDaemon {}

impl CommandDaemon {
    pub async fn execute(
        &self,
        raw: bool,
        client: &NydusdClient,
        params: Option<CommandParams>,
    ) -> Result<()> {
        if let Some(p) = params {
            let mut real = HashMap::<String, String>::new();

            // Map user provided configured item key to the one nydusd accepts.
            for (k, v) in p.into_iter() {
                real.insert(
                    CONFIGURE_ITEMS_MAP
                        .get(&k)
                        .ok_or_else(|| anyhow!("illegal item input"))?
                        .clone(),
                    v,
                );
            }

            let data = serde_json::to_string(&real)?;
            client.put("v1/daemon", Some(data)).await?;
        } else {
            let info = client.get("v1/daemon").await?;
            let i = info.as_object().unwrap();

            if raw {
                println!("{}", info);
            } else {
                let version_info = &i["version"];
                print!(
                    r#"
Version:                {version}
Status:                 {state}
Profile:                {profile}
Commit:                 {git_commit}
"#,
                    version = version_info["package_ver"],
                    state = i["state"],
                    profile = version_info["profile"],
                    git_commit = version_info["git_commit"],
                );

                if let Some(b) = i.get("backend_collection") {
                    if let Some(fs_backends) = b.as_object() {
                        if !fs_backends.is_empty() {
                            println!("Instances:")
                        }

                        for (mount_point, backend_obj) in fs_backends {
                            let backend: FsBackendDescriptor =
                                serde_json::from_value(backend_obj.clone()).unwrap();
                            println!("\tInstance Mountpoint:  {}", mount_point);
                            println!("\tType:  {}", backend.backend_type);
                            println!("\tMounted Time:  {}", backend.mounted_time);
                            match backend.backend_type {
                                FsBackendType::PassthroughFs => {}
                                FsBackendType::Rafs => {
                                    let cfg = backend.config.unwrap();
                                    let cache_cfg = cfg.get_cache_config()?;
                                    let rafs_cfg = cfg.get_rafs_config()?;
                                    println!("\tMode:  {}", rafs_cfg.mode);
                                    println!("\tPrefetch:  {}", cache_cfg.prefetch.enable);
                                    println!(
                                        "\tPrefetch Merging Size:  {}",
                                        cache_cfg.prefetch.batch_size
                                    );
                                    println!();
                                }
                            }
                        }
                    }
                }
            }
        }

        Ok(())
    }
}

pub(crate) struct CommandMount {}

impl CommandMount {
    pub async fn execute(
        &self,
        _raw: bool,
        client: &NydusdClient,
        params: Option<CommandParams>,
    ) -> Result<()> {
        let p = params.unwrap();
        let (source, mountpoint, fs_type) = (&p["source"], &p["mountpoint"], &p["type"]);
        let config = std::fs::read_to_string(&p["config"]).unwrap();
        let cmd = json!({"source": source, "fs_type": fs_type, "config": config}).to_string();

        client
            .post(
                "v1/mount",
                Some(cmd),
                Some(vec![("mountpoint", mountpoint)]),
            )
            .await
    }
}

pub(crate) struct CommandUmount {}

impl CommandUmount {
    pub async fn execute(
        &self,
        _raw: bool,
        client: &NydusdClient,
        params: Option<CommandParams>,
    ) -> Result<()> {
        let p = params.unwrap();
        let mountpoint = &p["mountpoint"];

        client
            .delete("v1/mount", None, Some(vec![("mountpoint", mountpoint)]))
            .await
    }
}