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
//! Access Varnish statistics
//!
//! The VSC (Varnish Shared Counter) is a way for outside program to access Varnish statistics in a
//! non-blocking way. The main way to access those counters traditionally is with `varnishstat`,
//! but the API is generic and allows you to track, filter and read any counter that `varnishd`
//! (and vmods) are exposing.


use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::ptr;

/// Error wrapping the VSM/VSC error reported by the C api
pub struct Error {
    s: String,
}

impl std::fmt::Debug for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Debug::fmt(&self.s, f)
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self.s, f)
    }
}

/// Shorthand to `std::result::Result<T, Error>` 
pub type Result<T> = std::result::Result<T, Error>;

/// A statistics set, created using a [`VSCBuilder`]
#[derive(Debug)]
pub struct VSC<'a> {
    vsm: *mut varnish_sys::vsm,
    vsc: *mut varnish_sys::vsc,
    internal: Box<VSCInternal<'a>>,
}

#[derive(Debug, Default)]
struct VSCInternal<'a> {
    points: HashMap<usize, Stat<'a>>,
    added: Vec<usize>,
    deleted: Vec<usize>,
}

/// Initialize and configure a [`VSC`] but do not attach it to a running `varnishd` instance
pub struct VSCBuilder<'a> {
    vsm: *mut varnish_sys::vsm,
    vsc: *mut varnish_sys::vsc,
    phantom: std::marker::PhantomData<&'a ()>,
}

impl<'a> VSCBuilder<'a> {
    /// Create a new `VSCBuilder`
    pub fn new() -> Self {
        unsafe {
            let vsm = varnish_sys::VSM_New();
            assert!(!vsm.is_null());
            let vsc = varnish_sys::VSC_New();
            assert!(!vsc.is_null());
            // get raw value, we can always clamp them later
            varnish_sys::VSC_Arg(vsc, 'r' as core::ffi::c_char, std::ptr::null());
            VSCBuilder {
                vsm,
                vsc,
                phantom: std::marker::PhantomData,
            }
        }
    }

    /// Specify where to find the `varnishd` working directory.
    ///
    /// It's usually superfluous to call this function, unless `varnishd` itself was called with
    /// the `-n` argument (in which case, both arguments should match)
    pub fn work_dir(self, dir: &std::path::Path) -> std::result::Result<Self, std::ffi::NulError> {
        let c_dir = CString::new(dir.to_str().unwrap())?;
        let ret = unsafe { varnish_sys::VSM_Arg(self.vsm, 'n' as core::ffi::c_char , c_dir.as_ptr()) };
        assert_eq!(ret, 1);
        Ok(self)
    }

    /// How long to wait when attaching
    ///
    /// When [`VSCBuilder::build()`] is called, it'll internally call `VSM_Attach`, hoping to find a running
    /// `varnishd` instance. If `None`, the function will not return until it connects, otherwise
    /// it specifies the timeout to use.
    pub fn patience(self, t: Option<std::time::Duration>) -> Result<Self> {
        // the things we do for love...
        let arg = match t {
            None => "off".to_string(),
            Some(t) => format!("{}\0", t.as_secs_f64()),
        };
        unsafe {
            let ret = varnish_sys::VSM_Arg(self.vsm, 't' as core::ffi::c_char , arg.as_ptr() as *const core::ffi::c_char);
            assert!(ret == 1);
        }
        Ok(self)
    }

    fn vsc_arg(self, o: char, s: &str) -> std::result::Result<Self, std::ffi::NulError> {
        let c_s = std::ffi::CString::new(s)?;
        unsafe {
            let ret = varnish_sys::VSC_Arg(self.vsc, o as core::ffi::c_char , c_s.as_ptr() as *const core::ffi::c_char);
            assert!(ret == 1);
        }
        Ok(self)
    }

    /// Provide a globbing pattern of statistics names to include.
    ///
    /// May be called multiple times, interleaved with [`VSCBuilder::exclude()`], the order matters.
    pub fn include(self, s: &str) -> std::result::Result<Self, std::ffi::NulError> {
        self.vsc_arg('I', s)
    }

    /// Provide a globbing pattern of statistics names to exclude.
    ///
    /// May be called multiple times, interleaved with [`VSCBuilder::include()`], the order matters.
    pub fn exclude(self, s: &str) -> std::result::Result<Self, std::ffi::NulError> {
        self.vsc_arg('X', s)
    }

    /// Provide a globbing pattern of statistics names to keep around, protecting them from
    /// exclusion.
    pub fn require(self, s: &str) -> std::result::Result<Self, std::ffi::NulError> {
        self.vsc_arg('R', s)
    }

    /// Build the [`VSC`], attaching to a running `varnishd` instance
    pub fn build(mut self) -> Result<VSC<'a>> {
        let ret = unsafe { varnish_sys::VSM_Attach(self.vsm, 0) };
        if ret != 0 {
            let err = vsm_error(self.vsm);
            unsafe {
                varnish_sys::VSM_ResetError(self.vsm);
            }
            Err(err)
        } else { 
            let mut internal = Box::new(VSCInternal::default());
            unsafe {
                varnish_sys::VSC_State(self.vsc, Some(add_point), Some(del_point), &mut *internal as *mut  VSCInternal as *mut std::ffi::c_void);
            }
            let vsm = self.vsm;
            let vsc = self.vsc;
            // nullify so that .drop() doesn't destroy vsm/vsc
            self.vsm = ptr::null_mut();
            self.vsc = ptr::null_mut();
            Ok(VSC {
                vsm,
                vsc,
                internal,
            })
        }
    }
}

fn vsm_error(p: * const varnish_sys::vsm) -> Error {
    unsafe {
        Error{ s: CStr::from_ptr(varnish_sys::VSM_Error(p)).to_str().unwrap().to_string() }
    }
}

impl<'a> Drop for VSCBuilder<'a> {
    fn drop(&mut self) {
        assert!((self.vsc.is_null() && self.vsm.is_null()) ||
                (!self.vsc.is_null() && !self.vsm.is_null()));
        if !self.vsc.is_null() {
            unsafe {
                varnish_sys::VSC_Destroy(&mut self.vsc, self.vsm);
            }
        }
    }
}

impl<'a> Drop for VSC<'a> {
    fn drop(&mut self) {
        unsafe {
            varnish_sys::VSC_Destroy(&mut self.vsc, self.vsm);
        }
    }
}

/// Kind of data
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Semantics {
    /// Value only goes up (e.g. amount of bytes transfered)
    Counter,
    /// Value can go up and down (e.g. amount of current connections)
    Gauge,
    /// Value is to be read as 64 booleans packed together as a `u64`
    Bitmap,
    /// No information on this value
    Unknown,
}

impl From<std::os::raw::c_int> for Semantics {
    fn from(value: std::os::raw::c_int) -> Self {
        let c = char::from_u32(value as u32).unwrap();
        match c {
            'c' => Semantics::Counter,
            'g' => Semantics::Gauge,
            'b' => Semantics::Bitmap,
            _ => Semantics::Unknown,
        }
    }
}

impl From<Semantics> for char {
    fn from(value: Semantics) -> char {
        match value {
            Semantics::Counter => 'c',
            Semantics::Gauge => 'g',
            Semantics::Bitmap => 'b',
            Semantics::Unknown => '?',
        }
    }
}

/// Unit of a value
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Format {
    /// No unit
    Integer,
    /// Bytes, for data volumes
    Bytes,
    /// No unit, generally used with [`Semantics::Bitmap`]
    Bitmap,
    /// Time
    Duration,
    /// Unit unknown
    Unknown,
}

impl From<std::os::raw::c_int> for Format {
    fn from(value: std::os::raw::c_int) -> Self {
        let c = char::from_u32(value as u32).unwrap();
        match c {
            'i' => Format::Integer,
            'B' => Format::Bytes,
            'b' => Format::Bitmap,
            'd' => Format::Duration,
            _ => Format::Unknown,
        }
    }
}

impl From<Format> for char {
    fn from(value: Format) -> char {
        match value {
            Format::Integer => 'i',
            Format::Bytes => 'B',
            Format::Bitmap => 'b',
            Format::Duration => 'd',
            Format::Unknown => '?',
        }
    }
}

unsafe extern "C" fn add_point(ptr: *mut std::ffi::c_void, point: *const varnish_sys::VSC_point) -> *mut std::ffi::c_void{
    let internal = ptr as *mut VSCInternal;
    let k = point as usize;

    let stat = Stat{
        value: (*point).ptr,
        name: CStr::from_ptr((*point).name).to_str().unwrap(),
        short_desc: CStr::from_ptr((*point).sdesc).to_str().unwrap(),
        long_desc: CStr::from_ptr((*point).ldesc).to_str().unwrap(),
        semantics: (*point).semantics.into(),
        format: (*point).format.into(),
    };
    assert_eq!((*internal).points.insert(k, stat), None);
    (*internal).added.push(k);
    std::ptr::null_mut()
}

unsafe extern "C" fn del_point(ptr: *mut std::ffi::c_void, point: *const varnish_sys::VSC_point) {
    let internal = ptr as *mut VSCInternal;
    let k = point as usize;
    assert!((*internal).points.get(&k).is_some());

    (*internal).deleted.push(k);
    assert!((*internal).points.remove(&k).is_some());
}

/// A live statistic
///
/// Describes a live value, with little overhead over the C struct
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct Stat<'a> {
    value: *const u64,
    pub name: &'a str,
    pub short_desc: &'a str,
    pub long_desc: &'a str,
    pub semantics: Semantics,
    pub format: Format,
}

impl<'a> Stat<'a> {
    /// Retrieve the current value of the statistic, as-is
    pub fn get_raw_value(&self) -> u64 {
        // # Safety
        // the pointer is valid as long as the VSC exist, and
        // VSC.update() isn't called (which uses `&mut self`)
        unsafe {
            *self.value
        }
    }

    /// Return a sanitized value of the statistic
    ///
    /// Gauges will fluctuate up and down, with multiple threads operating on them. As a result,
    /// their value can go below 0 and underflow. This function will prevent the value from
    /// wrapping around and just returns 0.
    pub fn get_clamped_value(&self) -> u64 {
        // # Safety
        // the pointer is valid as long as VSC exist, and
        // VSC.update() isn't called (which uses `&mut self`)
        let v = unsafe { *self.value };
        if v <= i64::MAX as u64  { v } else { 0 }
    }
}

impl<'a> VSC<'a> {
    /// Return a statistic set
    ///
    /// Names are not necessarily unique, so instead, statistics are tracked using `usize` handle
    /// that can help you track which ones (dis)appeared during a [`VSC::update()`] call.
    /// 
    /// The C API guarantees we can access all the `Stat` in the `HashMap`, until the next `update`
    /// call, so the `rust` API mirrors this here.
    pub fn stats(&self) -> &HashMap<usize, Stat> {
        &self.internal.points
    }

    /// Update the list of `Stat` we have access to
    ///
    /// You must call this function at least once to get access to any data (otherwise you'll just
    /// get an empty `HashMap`).
    ///
    /// The two returned `Vec`s list the added and deleted keys in the `HashMap`, in case you need
    /// to keep track of them at an individual level.
    /// (if a key appears in both `Vec`s, the statistic got replaced).
    pub fn update(&mut self) -> (Vec<usize>, Vec<usize>) {
        unsafe {
            varnish_sys::VSC_Iter(self.vsc, self.vsm, None, std::ptr::null_mut());
        }
        let added = std::mem::take(&mut self.internal.added);
        let deleted = std::mem::take(&mut self.internal.deleted);
        (added, deleted)
    }
}