aboutsummaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: 0848754535b41c3b33e6a6b2c445ea36814e8959 (plain)
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
/* Varanus: client/server system monitor for PCs.
 *
 * Copyright (c) 2024  Scott Lawrence.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 * and associated documentation files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/* TODO
 *
 * Remove socket file when daemon exits.
 *
 * Accept command-line arguments to query only part of JSON
 *
 * Fix delay
 *
 */

use std::error;
use std::fs::remove_file;
use std::io::{Read,Write};
use std::os::unix::net::{UnixStream,UnixListener};
use std::str;
use std::sync::{Arc,Mutex};
use std::thread::{sleep,spawn};
use std::time::{Duration,Instant,SystemTime};

use clap::Parser;
use serde::{Serialize,Deserialize};

#[derive(Default)]
#[repr(C)]
struct Sysinfo {
    uptime: cty::c_long,
    loads: [cty::c_ulong; 3],
    totalram: cty::c_ulong,
    freeram: cty::c_ulong,
    sharedram: cty::c_ulong,
    bufferram: cty::c_ulong,
    totalswap: cty::c_ulong,
    freeswap: cty::c_ulong,
    procs: cty::c_ushort,
    totalhigh: cty::c_ulong,
    freehigh: cty::c_ulong,
    mem_unit: cty::c_uint,
    /*char _f[20-2*sizeof(long)-sizeof(int)];*/
}

extern "C" {
    fn sysinfo(si: *mut Sysinfo) -> cty::c_int;
}

impl Sysinfo {
    fn new() -> Self {
        let mut si = Sysinfo::default();
        unsafe { sysinfo(&mut si) };
        return si;
    }
}

#[derive(Parser)]
struct Cli {
    #[arg(short='d', long)]
    daemon: bool,
    #[arg(short='v', long)]
    verbose: bool,
    #[arg(short='D', long, default_value="100")]
    delay: u64,
    #[arg(short='s', long, default_value="varanus.sock")]
    socket: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct Battery {
}

#[derive(Debug, Serialize, Deserialize)]
struct Power {
}

impl Power {
    fn new() -> Self {
        return Power{}
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct Process {
}

#[derive(Debug, Serialize, Deserialize)]
struct ProcFS {
}

impl ProcFS {
}

#[derive(Debug, Serialize, Deserialize)]
struct Memory {
}

impl Memory {
    fn new(si: Sysinfo) -> Self {
        return Memory{}
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct State {
    asof: SystemTime,
    uptime: i64,
    power: Power,
    memory: Memory,
}

impl State {
    fn new() -> Self {
        let asof = SystemTime::now();
        let si = Sysinfo::new();
        return State {
            asof: asof,
            uptime: si.uptime,
            power: Power::new(),
            memory: Memory::new(si)
        }
    }

    fn update(&mut self) {
        self.asof = SystemTime::now();
    }
}

type Result<T> = std::result::Result<T, Box<dyn error::Error>>;

fn update_state(state: &mut State) {
    state.update();
}

fn get_state(sockfile: String) -> Result<State> {
    let mut socket = UnixStream::connect(sockfile)?;
    let mut buf = vec![];
    socket.read_to_end(&mut buf)?;
    Ok(serde_json::from_str::<State>(str::from_utf8(&buf)?)?)
}

fn main() {
    let args = Cli::parse();
    if args.daemon {
        let start = Instant::now();
        let delay_ms: u64 = args.delay * 1000; // TODO not right
        let mut cycle: u64 = 0;
        let state_mutex = Arc::new(Mutex::new(State::new()));
        let listen_thread = {
            let state_mutex = Arc::clone(&state_mutex);
            spawn(move || {
                let _ = remove_file(&args.socket);
                let listener = UnixListener::bind(args.socket).unwrap();
                loop {
                    match listener.accept() {
                        Ok((mut socket,accept)) => {
                            let json = {
                                let state = state_mutex.lock().unwrap();
                                serde_json::to_string(&*state).unwrap()
                            };
                            socket.write_all(json.as_bytes()).unwrap();
                        },
                        Err(e) => println!("error: {:?}", e)
                    }
                }
            });
        };
        loop {
            if args.verbose {
                println!("{:?} elapsed; updating state...", start.elapsed());
            }
            {
                let mut state = state_mutex.lock().unwrap();
                update_state(&mut state);
            }
            cycle += 1;
            sleep(Duration::from_millis(cycle*delay_ms) - start.elapsed());
        }
    } else {
        let state = get_state(args.socket).unwrap();
        println!("{:#?}", state)
    }
}