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
use erl_dist::node::NodeName;
use erl_dist::term::{Atom, List, Map, Term, Tuple};
use std::collections::BTreeMap;

#[derive(Debug, Clone)]
pub struct SystemVersion(String);

impl SystemVersion {
    pub fn get(&self) -> &str {
        &self.0
    }
}

pub fn find_cookie() -> anyhow::Result<String> {
    if let Some(dir) = dirs::home_dir().filter(|dir| dir.join(".erlang.cookie").exists()) {
        let cookie = std::fs::read_to_string(dir.join(".erlang.cookie"))?;
        Ok(cookie)
    } else {
        anyhow::bail!("Could not find the cookie file $HOME/.erlang.cookie. Please specify `-cookie` arg instead.");
    }
}

#[derive(Debug, Clone)]
pub struct RpcClient {
    handle: erl_rpc::RpcClientHandle,
}

impl RpcClient {
    pub async fn connect(erlang_node: &NodeName, cookie: &str) -> anyhow::Result<Self> {
        let client = erl_rpc::RpcClient::connect(&erlang_node.to_string(), cookie).await?;
        let handle = client.handle();
        smol::spawn(async {
            if let Err(e) = client.run().await {
                log::error!("Erlang RPC Client error: {e}");
            }
        })
        .detach();

        Ok(Self { handle })
    }

    pub async fn get_system_version(&self) -> anyhow::Result<SystemVersion> {
        let term = self
            .handle
            .clone()
            .call(
                "erlang".into(),
                "system_info".into(),
                List::from(vec![Atom::from("system_version").into()]),
            )
            .await?;
        term_to_string(term).map(SystemVersion)
    }

    pub async fn get_system_info_u64(&self, item_name: &str) -> anyhow::Result<u64> {
        let term = self
            .handle
            .clone()
            .call(
                "erlang".into(),
                "system_info".into(),
                List::from(vec![Atom::from(item_name).into()]),
            )
            .await?;
        term_to_u64(term)
    }

    pub async fn get_statistics_1st_u64(&self, item_name: &str) -> anyhow::Result<u64> {
        let term = self.get_statistics(item_name).await?;
        term_to_tuple_1st_u64(term)
    }

    pub async fn get_statistics_u64_list(&self, item_name: &str) -> anyhow::Result<Vec<u64>> {
        let term = self.get_statistics(item_name).await?;
        term_to_u64_list(term)
    }

    pub async fn get_statistics_io(&self) -> anyhow::Result<(u64, u64)> {
        let term = self.get_statistics("io").await?;
        let tuple = term_to_tuple(term)?;
        let in_bytes = term_to_tuple_2nd_u64(tuple.elements[0].clone())?;
        let out_bytes = term_to_tuple_2nd_u64(tuple.elements[1].clone())?;
        Ok((in_bytes, out_bytes))
    }

    pub async fn get_statistics_microstate_accounting(&self) -> anyhow::Result<Vec<MSAccThread>> {
        let term = self.get_statistics("microstate_accounting").await?;
        term_to_list(term)?
            .elements
            .into_iter()
            .map(MSAccThread::from_term)
            .collect()
    }

    pub async fn set_system_flag_bool(&self, name: &str, value: &str) -> anyhow::Result<bool> {
        let term = self
            .handle
            .clone()
            .call(
                "erlang".into(),
                "system_flag".into(),
                List::from(vec![Atom::from(name).into(), Atom::from(value).into()]),
            )
            .await?;
        term_to_bool(term)
    }

    pub async fn get_memory(&self) -> anyhow::Result<BTreeMap<String, u64>> {
        let term = self
            .handle
            .clone()
            .call("erlang".into(), "memory".into(), List::nil())
            .await?;
        term_to_list(term)?
            .elements
            .into_iter()
            .map(|x| {
                let tuple = term_to_tuple(x)?;
                anyhow::ensure!(
                    tuple.elements.len() == 2,
                    "expected a two-elements tuple, but got {}",
                    tuple
                );
                let key = term_to_atom(tuple.elements[0].clone())?;
                let value = term_to_u64(tuple.elements[1].clone())?;
                Ok((key.name, value))
            })
            .collect()
    }

    async fn get_statistics(&self, item_name: &str) -> anyhow::Result<Term> {
        let term = self
            .handle
            .clone()
            .call(
                "erlang".into(),
                "statistics".into(),
                List::from(vec![Atom::from(item_name).into()]),
            )
            .await?;
        Ok(term)
    }
}

fn term_to_tuple_1st_u64(term: Term) -> anyhow::Result<u64> {
    let tuple = term_to_tuple(term)?;
    anyhow::ensure!(
        !tuple.elements.is_empty(),
        "expected a non empty tuple, but got {}",
        tuple
    );
    term_to_u64(tuple.elements[0].clone())
}

fn term_to_tuple_2nd_u64(term: Term) -> anyhow::Result<u64> {
    let tuple = term_to_tuple(term)?;
    anyhow::ensure!(
        tuple.elements.len() >= 2,
        "expected a tuple having 2 or more elements, but got {}",
        tuple
    );
    term_to_u64(tuple.elements[1].clone())
}

fn term_to_u64(term: Term) -> anyhow::Result<u64> {
    let v = match term {
        Term::FixInteger(v) => v.value.try_into()?,
        Term::BigInteger(v) => v.value.try_into()?,
        v => anyhow::bail!("{} is not an integer", v),
    };
    Ok(v)
}

fn term_to_string(term: Term) -> anyhow::Result<String> {
    let bytes = term_to_list(term)?
        .elements
        .into_iter()
        .map(term_to_u8)
        .collect::<anyhow::Result<Vec<_>>>()?;
    Ok(String::from_utf8(bytes)?)
}

fn term_to_u8(term: Term) -> anyhow::Result<u8> {
    if let Term::FixInteger(v) = term {
        Ok(u8::try_from(v.value)?)
    } else {
        anyhow::bail!("expected an integer, but got {}", term)
    }
}

fn term_to_u64_list(term: Term) -> anyhow::Result<Vec<u64>> {
    term_to_list(term)?
        .elements
        .into_iter()
        .map(term_to_u64)
        .collect()
}

fn term_to_bool(term: Term) -> anyhow::Result<bool> {
    let atom = term_to_atom(term)?;
    match atom.name.as_str() {
        "true" => Ok(true),
        "false" => Ok(false),
        _ => anyhow::bail!("expected 'true' or 'false', but got {}", atom.name),
    }
}

fn term_to_atom(term: Term) -> anyhow::Result<Atom> {
    term.try_into()
        .map_err(|x| anyhow::anyhow!("expected an atom, but got {x}"))
}

fn term_to_tuple(term: Term) -> anyhow::Result<Tuple> {
    term.try_into()
        .map_err(|x| anyhow::anyhow!("expected a tuple, but got {x}"))
}

fn term_to_list(term: Term) -> anyhow::Result<List> {
    term.try_into()
        .map_err(|x| anyhow::anyhow!("expected a list, but got {x}"))
}

#[derive(Debug, Clone)]
pub struct MSAccThread {
    pub thread_id: u64,
    pub thread_type: String,
    pub counters: BTreeMap<String, u64>,
}

impl MSAccThread {
    fn from_term(term: Term) -> anyhow::Result<Self> {
        let map: Map = term
            .try_into()
            .map_err(|x| anyhow::anyhow!("expected a map, but got {x}"))?;
        let mut thread_id = None;
        let mut thread_type = None;
        let mut counters = BTreeMap::new();
        for (k, v) in map.entries {
            match term_to_atom(k)?.name.as_str() {
                "id" => {
                    thread_id = Some(term_to_u64(v)?);
                }
                "type" => {
                    thread_type = Some(term_to_atom(v)?.name);
                }
                "counters" => {
                    let counters_map: Map = v
                        .try_into()
                        .map_err(|x| anyhow::anyhow!("expected a map, but got {x}"))?;
                    for (k, v) in counters_map.entries {
                        counters.insert(term_to_atom(k)?.name, term_to_u64(v)?);
                    }
                }
                k => {
                    log::debug!("unknown msacc key: {:?}", k);
                }
            }
        }
        Ok(Self {
            thread_id: thread_id.ok_or_else(|| anyhow::anyhow!("missing 'id' key"))?,
            thread_type: thread_type.ok_or_else(|| anyhow::anyhow!("missing 'type' key"))?,
            counters,
        })
    }
}