canic-cli 0.36.13

Operator CLI for Canic fleet backup and restore workflows
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
use crate::{
    cycles::{
        CyclesCommandError,
        model::{
            CycleTopupEventSample, CycleTopupStatus, CycleTrackerPage, CycleTrackerSample,
            CyclesCanisterReport, CyclesReport, CyclesTopupSummary,
        },
        options::CyclesOptions,
        parse::{
            parse_cycle_tracker_page, parse_cycle_tracker_page_text, parse_topup_event_page,
            parse_topup_event_page_text,
        },
    },
    support::registry_tree::{RegistryRow, visible_rows},
};
use canic_host::{
    icp::IcpCli,
    icp_config::resolve_current_canic_icp_root,
    installed_fleet::{
        InstalledFleetError, InstalledFleetRequest, InstalledFleetResolution,
        resolve_installed_fleet_from_root,
    },
    registry::RegistryEntry,
    response_parse::parse_cycle_balance_response,
};
use std::{
    path::PathBuf,
    sync::Arc,
    thread,
    time::{SystemTime, UNIX_EPOCH},
};

const TOPUP_EVENTS_LIMIT: u64 = 1_000;

pub fn cycles_report(options: &CyclesOptions) -> Result<CyclesReport, CyclesCommandError> {
    let registry = load_registry(options)?;
    let generated_at_secs = current_unix_seconds();
    let requested_since_secs = generated_at_secs.saturating_sub(options.since_seconds);
    let canisters =
        collect_cycle_tracker_reports(options, &registry, requested_since_secs, generated_at_secs)?;

    Ok(CyclesReport {
        fleet: options.fleet.clone(),
        network: options.network.clone(),
        since_seconds: options.since_seconds,
        generated_at_secs,
        canisters,
    })
}

fn load_registry(options: &CyclesOptions) -> Result<Vec<RegistryEntry>, CyclesCommandError> {
    Ok(resolve_cycles_fleet(options)?.registry.entries)
}

fn collect_cycle_tracker_reports(
    options: &CyclesOptions,
    registry: &[RegistryEntry],
    requested_since_secs: u64,
    generated_at_secs: u64,
) -> Result<Vec<CyclesCanisterReport>, CyclesCommandError> {
    let query = Arc::new(options.clone());
    let mut handles = Vec::new();
    let rows = visible_rows(registry, options.subtree.as_deref())?;
    for row in rows {
        let RegistryRow { entry, tree_prefix } = row;
        let entry = entry.clone();
        let query = Arc::clone(&query);
        handles.push(thread::spawn(move || {
            cycle_tracker_report(
                &query,
                &entry,
                tree_prefix,
                requested_since_secs,
                generated_at_secs,
            )
        }));
    }

    Ok(handles
        .into_iter()
        .filter_map(|handle| handle.join().ok())
        .collect())
}

fn cycle_tracker_report(
    options: &CyclesOptions,
    entry: &RegistryEntry,
    tree_prefix: String,
    requested_since_secs: u64,
    generated_at_secs: u64,
) -> CyclesCanisterReport {
    let live_cycles = query_live_cycle_balance(options, &entry.pid);
    let result = query_cycle_tracker(options, &entry.pid);
    match result {
        Ok(page) => summarize_cycle_tracker(
            entry,
            page,
            tree_prefix,
            requested_since_secs,
            generated_at_secs,
            live_cycles,
            query_topup_events(options, &entry.pid).ok(),
        ),
        Err(error) => CyclesCanisterReport {
            role: entry.role.clone().unwrap_or_else(|| "-".to_string()),
            tree_prefix,
            canister_id: entry.pid.clone(),
            status: "error".to_string(),
            sample_count: 0,
            total_samples: 0,
            requested_since_secs,
            coverage_seconds: None,
            coverage_status: "none".to_string(),
            latest_timestamp_secs: live_cycles.map(|_| generated_at_secs),
            latest_cycles: live_cycles,
            baseline_timestamp_secs: None,
            baseline_cycles: None,
            delta_cycles: None,
            rate_cycles_per_hour: None,
            burn_cycles: None,
            burn_cycles_per_hour: None,
            topup_cycles_per_hour: None,
            topups: None,
            error: Some(error),
        },
    }
}

pub(super) fn summarize_cycle_tracker(
    entry: &RegistryEntry,
    mut page: CycleTrackerPage,
    tree_prefix: String,
    requested_since_secs: u64,
    generated_at_secs: u64,
    live_cycles: Option<u128>,
    topup_events: Option<Vec<CycleTopupEventSample>>,
) -> CyclesCanisterReport {
    page.entries.sort_by_key(|entry| entry.timestamp_secs);
    let latest = page.entries.last().cloned();
    let baseline = latest.as_ref().and_then(|_| {
        page.entries
            .iter()
            .rev()
            .find(|sample| sample.timestamp_secs <= requested_since_secs)
            .or_else(|| page.entries.first())
            .cloned()
    });
    let delta = latest
        .as_ref()
        .zip(baseline.as_ref())
        .map(|(latest, baseline)| signed_delta(latest.cycles, baseline.cycles));
    let coverage_seconds = latest
        .as_ref()
        .zip(baseline.as_ref())
        .map(|(latest, baseline)| {
            latest
                .timestamp_secs
                .saturating_sub(baseline.timestamp_secs)
        });
    let rate_cycles_per_hour = delta
        .zip(coverage_seconds)
        .and_then(|(delta, coverage)| hourly_rate(delta, coverage));
    let topup_summary = topup_events
        .as_deref()
        .zip(baseline.as_ref())
        .zip(latest.as_ref())
        .map(|((events, baseline), latest)| {
            topup_summary_from_events(events, baseline.timestamp_secs, latest.timestamp_secs)
        });
    let topup_cycles = topup_summary
        .as_ref()
        .map_or(0, |summary| summary.transferred_cycles);
    let topup_cycles_per_hour = topup_summary
        .as_ref()
        .zip(coverage_seconds)
        .and_then(|(_, coverage)| unsigned_hourly_rate(topup_cycles, coverage));
    let burn_cycles = topup_summary
        .as_ref()
        .zip(delta)
        .and_then(|(_, delta)| inferred_burn_cycles(topup_cycles, delta));
    let burn_cycles_per_hour = topup_summary
        .as_ref()
        .zip(burn_cycles)
        .zip(coverage_seconds)
        .and_then(|((_, burn), coverage)| unsigned_hourly_rate(burn, coverage));
    let visible_topups = topup_summary.filter(|summary| !summary.is_empty());
    let coverage_status = coverage_status(baseline.as_ref(), requested_since_secs);
    let status = if latest.is_some() { "ok" } else { "empty" };

    CyclesCanisterReport {
        role: entry.role.clone().unwrap_or_else(|| "-".to_string()),
        tree_prefix,
        canister_id: entry.pid.clone(),
        status: status.to_string(),
        sample_count: page.entries.len(),
        total_samples: page.total,
        requested_since_secs,
        coverage_seconds,
        coverage_status,
        latest_timestamp_secs: live_cycles
            .map(|_| generated_at_secs)
            .or_else(|| latest.as_ref().map(|sample| sample.timestamp_secs)),
        latest_cycles: live_cycles.or_else(|| latest.as_ref().map(|sample| sample.cycles)),
        baseline_timestamp_secs: baseline.as_ref().map(|sample| sample.timestamp_secs),
        baseline_cycles: baseline.as_ref().map(|sample| sample.cycles),
        delta_cycles: delta,
        rate_cycles_per_hour,
        burn_cycles,
        burn_cycles_per_hour,
        topup_cycles_per_hour,
        topups: visible_topups,
        error: None,
    }
}

fn query_live_cycle_balance(options: &CyclesOptions, canister_id: &str) -> Option<u128> {
    let mut icp = IcpCli::new(&options.icp, None, Some(options.network.clone()));
    if let Some(root) = resolve_cycles_icp_root() {
        icp = icp.with_cwd(root);
    }
    icp.canister_query_output(
        canister_id,
        canic_core::protocol::CANIC_CYCLE_BALANCE,
        Some("json"),
    )
    .ok()
    .and_then(|output| parse_cycle_balance_response(&output))
}

fn query_topup_events(
    options: &CyclesOptions,
    canister_id: &str,
) -> Result<Vec<CycleTopupEventSample>, String> {
    let mut page = query_topup_event_page(options, canister_id, 0, TOPUP_EVENTS_LIMIT)?;
    if page.total > TOPUP_EVENTS_LIMIT {
        let offset = page.total.saturating_sub(TOPUP_EVENTS_LIMIT);
        page = query_topup_event_page(options, canister_id, offset, TOPUP_EVENTS_LIMIT)?;
    }
    Ok(page.entries)
}

pub(super) fn topup_summary_from_events(
    entries: &[CycleTopupEventSample],
    start_secs: u64,
    end_secs: u64,
) -> CyclesTopupSummary {
    let mut summary = CyclesTopupSummary::default();
    for entry in entries {
        if entry.timestamp_secs < start_secs || entry.timestamp_secs > end_secs {
            continue;
        }
        match entry.status {
            CycleTopupStatus::RequestScheduled => {
                summary.request_scheduled = summary.request_scheduled.saturating_add(1);
            }
            CycleTopupStatus::RequestOk => {
                summary.request_ok = summary.request_ok.saturating_add(1);
                summary.transferred_cycles = summary
                    .transferred_cycles
                    .saturating_add(entry.transferred_cycles.unwrap_or_default());
            }
            CycleTopupStatus::RequestErr => {
                summary.request_err = summary.request_err.saturating_add(1);
            }
        }
    }
    summary
}

fn query_topup_event_page(
    options: &CyclesOptions,
    canister_id: &str,
    offset: u64,
    limit: u64,
) -> Result<crate::cycles::model::CycleTopupEventPage, String> {
    let arg = format!("(record {{ offset = {offset} : nat64; limit = {limit} : nat64 }})");
    let mut icp = IcpCli::new(&options.icp, None, Some(options.network.clone()));
    if let Some(root) = resolve_cycles_icp_root() {
        icp = icp.with_cwd(root);
    }
    let output = icp
        .canister_query_arg_output(
            canister_id,
            canic_core::protocol::CANIC_CYCLE_TOPUPS,
            &arg,
            Some("json"),
        )
        .map_err(|err| err.to_string())?;

    parse_topup_event_page(&output)
        .or_else(|| parse_topup_event_page_text(&output))
        .ok_or_else(|| "could not parse canic_cycle_topups response".to_string())
}

fn query_cycle_tracker(
    options: &CyclesOptions,
    canister_id: &str,
) -> Result<CycleTrackerPage, String> {
    let mut page = query_cycle_tracker_page(options, canister_id, 0, options.limit)?;
    if page.total > options.limit {
        let offset = page.total.saturating_sub(options.limit);
        page = query_cycle_tracker_page(options, canister_id, offset, options.limit)?;
    }
    Ok(page)
}

fn query_cycle_tracker_page(
    options: &CyclesOptions,
    canister_id: &str,
    offset: u64,
    limit: u64,
) -> Result<CycleTrackerPage, String> {
    let arg = format!("(record {{ offset = {offset} : nat64; limit = {limit} : nat64 }})");
    let mut icp = IcpCli::new(&options.icp, None, Some(options.network.clone()));
    if let Some(root) = resolve_cycles_icp_root() {
        icp = icp.with_cwd(root);
    }
    let output = icp
        .canister_query_arg_output(
            canister_id,
            canic_core::protocol::CANIC_CYCLE_TRACKER,
            &arg,
            Some("json"),
        )
        .map_err(|err| err.to_string())?;

    parse_cycle_tracker_page(&output)
        .or_else(|| parse_cycle_tracker_page_text(&output))
        .ok_or_else(|| "could not parse canic_cycle_tracker response".to_string())
}

fn signed_delta(latest: u128, baseline: u128) -> i128 {
    if latest >= baseline {
        i128::try_from(latest - baseline).unwrap_or(i128::MAX)
    } else {
        -i128::try_from(baseline - latest).unwrap_or(i128::MAX)
    }
}

fn hourly_rate(delta: i128, coverage_seconds: u64) -> Option<i128> {
    if coverage_seconds == 0 {
        return None;
    }
    Some(delta.saturating_mul(3_600) / i128::from(coverage_seconds))
}

fn unsigned_hourly_rate(value: u128, coverage_seconds: u64) -> Option<u128> {
    if coverage_seconds == 0 {
        return None;
    }
    Some(value.saturating_mul(3_600) / u128::from(coverage_seconds))
}

fn inferred_burn_cycles(topup_cycles: u128, delta_cycles: i128) -> Option<u128> {
    if delta_cycles < 0 {
        return Some(topup_cycles.saturating_add(delta_cycles.unsigned_abs()));
    }

    let delta = delta_cycles.cast_unsigned();
    (topup_cycles >= delta).then_some(topup_cycles - delta)
}

fn coverage_status(baseline: Option<&CycleTrackerSample>, requested_since_secs: u64) -> String {
    match baseline {
        Some(sample) if sample.timestamp_secs <= requested_since_secs => "covered".to_string(),
        Some(_) => "partial".to_string(),
        None => "none".to_string(),
    }
}

fn current_unix_seconds() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |duration| duration.as_secs())
}

fn resolve_cycles_fleet(
    options: &CyclesOptions,
) -> Result<InstalledFleetResolution, CyclesCommandError> {
    let root = resolve_cycles_icp_root().ok_or_else(|| {
        CyclesCommandError::InstallState("could not resolve ICP root".to_string())
    })?;
    resolve_installed_fleet_from_root(
        &InstalledFleetRequest {
            fleet: options.fleet.clone(),
            network: options.network.clone(),
            icp: options.icp.clone(),
            detect_lost_local_root: false,
        },
        &root,
    )
    .map_err(cycles_installed_fleet_error)
}

fn resolve_cycles_icp_root() -> Option<PathBuf> {
    resolve_current_canic_icp_root().ok()
}

fn cycles_installed_fleet_error(error: InstalledFleetError) -> CyclesCommandError {
    match error {
        InstalledFleetError::NoInstalledFleet { network, fleet } => {
            CyclesCommandError::NoInstalledFleet { network, fleet }
        }
        InstalledFleetError::InstallState(error) => CyclesCommandError::InstallState(error),
        InstalledFleetError::ReplicaQuery(error) => CyclesCommandError::ReplicaQuery(error),
        InstalledFleetError::IcpFailed { command, stderr } => {
            CyclesCommandError::IcpFailed { command, stderr }
        }
        InstalledFleetError::LostLocalFleet { root, .. } => {
            CyclesCommandError::ReplicaQuery(format!("root canister {root} is not present"))
        }
        InstalledFleetError::Registry(error) => CyclesCommandError::Registry(error),
        InstalledFleetError::Io(error) => CyclesCommandError::Io(error),
    }
}