Skip to main content

kumo_machine_info/
lib.rs

1use anyhow::Context;
2use chrono::Utc;
3use kumo_chrono_helper::DateTime;
4use kumo_mac_address::get_mac_address;
5use reqwest::header::{HeaderMap, HeaderValue};
6use reqwest::Method;
7use serde::Deserialize;
8use serde_with::serde_as;
9use sysinfo::System;
10
11#[derive(Debug)]
12pub struct MachineInfo {
13    pub hostname: String,
14    pub mac_address: String,
15    pub machine_uid: Option<String>,
16    pub node_id: Option<String>,
17    pub num_cores: usize,
18    pub kernel_version: Option<String>,
19    pub platform: String,
20    pub distribution: String,
21    pub os_version: String,
22    pub total_memory_bytes: u64,
23    pub container_runtime: Option<String>,
24    pub cpu_brand: String,
25    pub cloud_provider: Option<CloudProvider>,
26}
27
28#[derive(Debug)]
29pub enum CloudProvider {
30    /// AWS
31    Aws(aws::IdentityDocument),
32    /// MS Azure
33    Azure(azure::InstanceMetadata),
34    /// Google Cloud Platform
35    Gcp(gcp::InstanceMetadata),
36}
37
38impl CloudProvider {
39    fn augment_fingerprint(&self, components: &mut Vec<String>) {
40        match self {
41            Self::Aws(id) => {
42                components.push(format!("aws_instance_id={}", id.instance_id));
43            }
44            Self::Azure(instance) => {
45                components.push(format!("azure_vm_id={}", instance.compute.vm_id));
46            }
47            Self::Gcp(instance) => {
48                components.push(format!("gcp_id={}", instance.instance_id));
49            }
50        }
51    }
52}
53
54impl MachineInfo {
55    pub fn fingerprint(&self) -> String {
56        let mut components = vec![];
57        if let Some(provider) = &self.cloud_provider {
58            provider.augment_fingerprint(&mut components);
59        }
60        if let Some(uid) = &self.machine_uid {
61            components.push(format!("machine_uid={uid}"));
62        }
63        if let Some(id) = &self.node_id {
64            components.push(format!("node_id={id}"));
65        }
66        if components.is_empty() {
67            components.push(format!("mac={}", self.mac_address));
68        }
69        components.join(",")
70    }
71
72    pub fn new() -> Self {
73        let hostname = gethostname::gethostname().to_string_lossy().to_string();
74        let mac = get_mac_address();
75        let mac_address = format!(
76            "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
77            mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]
78        );
79
80        let machine_uid = machine_uid::get().ok();
81
82        let arch = System::cpu_arch();
83
84        let mut system = System::new();
85        system.refresh_memory();
86        system.refresh_cpu_all();
87
88        let mut cpu_info = vec![];
89        for cpu in system.cpus() {
90            let info = cpu.brand().to_string();
91            if cpu_info.contains(&info) {
92                continue;
93            }
94            cpu_info.push(info);
95        }
96        let cpu_brand = cpu_info.join(", ");
97
98        Self {
99            hostname,
100            machine_uid,
101            mac_address,
102            node_id: None,
103            num_cores: num_cpus::get(),
104            platform: format!("{}/{arch}", std::env::consts::OS),
105            distribution: System::distribution_id(),
106            os_version: System::long_os_version()
107                .unwrap_or_else(|| std::env::consts::OS.to_string()),
108            total_memory_bytes: system.total_memory(),
109            container_runtime: in_container::get_container_runtime().map(|r| r.to_string()),
110            kernel_version: System::kernel_version(),
111            cpu_brand,
112            cloud_provider: None,
113        }
114    }
115
116    /// Concurrently query for a known cloud providers
117    pub async fn query_cloud_provider(&mut self) {
118        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
119        {
120            let tx = tx.clone();
121            tokio::task::spawn(async move {
122                if let Ok(id) = aws::IdentityDocument::query().await {
123                    tx.send(CloudProvider::Aws(id)).ok();
124                }
125            });
126        }
127        {
128            let tx = tx.clone();
129            tokio::task::spawn(async move {
130                if let Ok(id) = azure::InstanceMetadata::query().await {
131                    tx.send(CloudProvider::Azure(id)).ok();
132                }
133            });
134        }
135        {
136            let tx = tx.clone();
137            tokio::task::spawn(async move {
138                if let Ok(id) = gcp::InstanceMetadata::query().await {
139                    tx.send(CloudProvider::Gcp(id)).ok();
140                }
141            });
142        }
143        drop(tx);
144
145        tokio::select! {
146            biased;
147
148            // Prefer to get a positive result
149            provider = rx.recv() => {
150                self.cloud_provider = provider;
151            }
152
153            // Overall timeout if things are taking too long
154            _ = tokio::time::sleep(tokio::time::Duration::from_secs(3)) => {}
155        };
156    }
157}
158
159pub mod azure {
160    use super::*;
161    use serde_json::Value;
162    use std::collections::BTreeMap;
163
164    #[serde_as]
165    #[derive(Deserialize, Debug)]
166    #[serde(rename_all = "camelCase")]
167    pub struct InstanceMetadata {
168        pub compute: Compute,
169        pub network: Network,
170    }
171
172    #[serde_as]
173    #[derive(Deserialize, Debug)]
174    #[serde(rename_all = "camelCase")]
175    pub struct Compute {
176        pub az_environment: String,
177        pub vm_id: String,
178        pub vm_size: String,
179        pub location: String,
180        #[serde(flatten)]
181        pub unknown_: BTreeMap<String, Value>,
182    }
183
184    #[serde_as]
185    #[derive(Deserialize, Debug)]
186    #[serde(rename_all = "camelCase")]
187    pub struct Network {
188        pub interface: Vec<NetworkInterface>,
189    }
190
191    #[serde_as]
192    #[derive(Deserialize, Debug)]
193    #[serde(rename_all = "camelCase")]
194    pub struct NetworkInterface {
195        pub ipv4: Ipv4Info,
196        pub mac_address: String,
197        #[serde(flatten)]
198        pub unknown_: BTreeMap<String, Value>,
199    }
200
201    #[serde_as]
202    #[derive(Deserialize, Debug)]
203    #[serde(rename_all = "camelCase")]
204    pub struct Ipv4Info {
205        pub ip_address: Vec<IpAddressInfo>,
206        pub subnet: Vec<SubnetInfo>,
207    }
208
209    #[serde_as]
210    #[derive(Deserialize, Debug)]
211    #[serde(rename_all = "camelCase")]
212    pub struct IpAddressInfo {
213        pub private_ip_address: String,
214        #[serde(default)]
215        pub public_ip_address: String,
216    }
217    #[serde_as]
218    #[derive(Deserialize, Debug)]
219    #[serde(rename_all = "camelCase")]
220    pub struct SubnetInfo {
221        pub address: String,
222        pub prefix: String,
223    }
224
225    impl InstanceMetadata {
226        pub async fn query_via(base_url: &str) -> anyhow::Result<Self> {
227            let client = kumo_http_client::builder()
228                .no_proxy()
229                .timeout(std::time::Duration::from_secs(1))
230                .build()
231                .unwrap();
232
233            let mut headers = HeaderMap::new();
234            headers.insert("Metadata", HeaderValue::from_static("true"));
235
236            let request = client
237                .request(
238                    Method::GET,
239                    format!("{base_url}/metadata/instance?api-version=2021-02-01"),
240                )
241                .headers(headers)
242                .build()?;
243            let response = client.execute(request).await?;
244
245            let status = response.status();
246
247            let body_text = response
248                .text()
249                .await
250                .context("failed to read response body")?;
251            if status.is_client_error() || status.is_server_error() {
252                anyhow::bail!("failed to query identity: {status:?} {body_text}");
253            }
254
255            Ok(serde_json::from_str(&body_text)?)
256        }
257
258        pub async fn query() -> anyhow::Result<Self> {
259            Self::query_via("http://169.254.169.254").await
260        }
261    }
262
263    #[cfg(test)]
264    #[tokio::test]
265    async fn test_metadata() {
266        use mockito::Server;
267
268        let mut server = Server::new_async().await;
269        let _mock = server
270            .mock("GET", "/metadata/instance?api-version=2021-02-01")
271            .match_header("Metadata", "true")
272            .with_status(200)
273            .with_body(
274                r#"{
275    "compute": {
276        "azEnvironment": "AZUREPUBLICCLOUD",
277        "additionalCapabilities": {
278            "hibernationEnabled": "true"
279        },
280        "hostGroup": {
281          "id": "testHostGroupId"
282        },
283        "extendedLocation": {
284            "type": "edgeZone",
285            "name": "microsoftlosangeles"
286        },
287        "evictionPolicy": "",
288        "isHostCompatibilityLayerVm": "true",
289        "licenseType":  "",
290        "location": "westus",
291        "name": "examplevmname",
292        "offer": "UbuntuServer",
293        "osProfile": {
294            "adminUsername": "admin",
295            "computerName": "examplevmname",
296            "disablePasswordAuthentication": "true"
297        },
298        "osType": "Linux",
299        "placementGroupId": "f67c14ab-e92c-408c-ae2d-da15866ec79a",
300        "plan": {
301            "name": "planName",
302            "product": "planProduct",
303            "publisher": "planPublisher"
304        },
305        "platformFaultDomain": "36",
306        "platformSubFaultDomain": "",
307        "platformUpdateDomain": "42",
308        "priority": "Regular",
309        "publicKeys": [{
310                "keyData": "ssh-rsa 0",
311                "path": "/home/user/.ssh/authorized_keys0"
312            },
313            {
314                "keyData": "ssh-rsa 1",
315                "path": "/home/user/.ssh/authorized_keys1"
316            }
317        ],
318        "publisher": "Canonical",
319        "resourceGroupName": "macikgo-test-may-23",
320        "resourceId": "/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/virtualMachines/examplevmname",
321        "securityProfile": {
322            "secureBootEnabled": "true",
323            "virtualTpmEnabled": "false",
324            "encryptionAtHost": "true",
325            "securityType": "TrustedLaunch"
326        },
327        "sku": "18.04-LTS",
328        "storageProfile": {
329            "dataDisks": [{
330                "bytesPerSecondThrottle": "979202048",
331                "caching": "None",
332                "createOption": "Empty",
333                "diskCapacityBytes": "274877906944",
334                "diskSizeGB": "1024",
335                "image": {
336                  "uri": ""
337                },
338                "isSharedDisk": "false",
339                "isUltraDisk": "true",
340                "lun": "0",
341                "managedDisk": {
342                  "id": "/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/disks/exampledatadiskname",
343                  "storageAccountType": "StandardSSD_LRS"
344                },
345                "name": "exampledatadiskname",
346                "opsPerSecondThrottle": "65280",
347                "vhd": {
348                  "uri": ""
349                },
350                "writeAcceleratorEnabled": "false"
351            }],
352            "imageReference": {
353                "id": "",
354                "offer": "UbuntuServer",
355                "publisher": "Canonical",
356                "sku": "16.04.0-LTS",
357                "version": "latest",
358                "communityGalleryImageId": "/CommunityGalleries/testgallery/Images/1804Gen2/Versions/latest",
359                "sharedGalleryImageId": "/SharedGalleries/1P/Images/gen2/Versions/latest",
360                "exactVersion": "1.1686127202.30113"
361            },
362            "osDisk": {
363                "caching": "ReadWrite",
364                "createOption": "FromImage",
365                "diskSizeGB": "30",
366                "diffDiskSettings": {
367                    "option": "Local"
368                },
369                "encryptionSettings": {
370                  "enabled": "false",
371                  "diskEncryptionKey": {
372                    "sourceVault": {
373                      "id": "/subscriptions/test-source-guid/resourceGroups/testrg/providers/Microsoft.KeyVault/vaults/test-kv"
374                    },
375                    "secretUrl": "https://test-disk.vault.azure.net/secrets/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"
376                  },
377                  "keyEncryptionKey": {
378                    "sourceVault": {
379                      "id": "/subscriptions/test-key-guid/resourceGroups/testrg/providers/Microsoft.KeyVault/vaults/test-kv"
380                    },
381                    "keyUrl": "https://test-key.vault.azure.net/secrets/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"
382                  }
383                },
384                "image": {
385                    "uri": ""
386                },
387                "managedDisk": {
388                    "id": "/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/disks/exampleosdiskname",
389                    "storageAccountType": "StandardSSD_LRS"
390                },
391                "name": "exampleosdiskname",
392                "osType": "Linux",
393                "vhd": {
394                    "uri": ""
395                },
396                "writeAcceleratorEnabled": "false"
397            },
398            "resourceDisk": {
399                "size": "4096"
400            }
401        },
402        "subscriptionId": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx",
403        "tags": "baz:bash;foo:bar",
404        "version": "15.05.22",
405        "virtualMachineScaleSet": {
406            "id": "/subscriptions/xxxxxxxx-xxxxx-xxx-xxx-xxxx/resourceGroups/resource-group-name/providers/Microsoft.Compute/virtualMachineScaleSets/virtual-machine-scale-set-name"
407        },
408        "vmId": "02aab8a4-74ef-476e-8182-f6d2ba4166a6",
409        "vmScaleSetName": "crpteste9vflji9",
410        "vmSize": "Standard_A3",
411        "zone": ""
412    },
413    "network": {
414        "interface": [{
415            "ipv4": {
416               "ipAddress": [{
417                    "privateIpAddress": "10.144.133.132",
418                    "publicIpAddress": ""
419                }],
420                "subnet": [{
421                    "address": "10.144.133.128",
422                    "prefix": "26"
423                }]
424            },
425            "ipv6": {
426                "ipAddress": [
427                 ]
428            },
429            "macAddress": "0011AAFFBB22"
430        }]
431    }
432}"#,
433            )
434            .create_async()
435            .await;
436
437        let id = InstanceMetadata::query_via(&server.url()).await.unwrap();
438        eprintln!("{id:#?}");
439        assert_eq!(id.compute.vm_id, "02aab8a4-74ef-476e-8182-f6d2ba4166a6");
440    }
441}
442
443pub mod aws {
444    use super::*;
445
446    #[serde_as]
447    #[derive(Deserialize, Debug)]
448    #[serde(rename_all = "camelCase")]
449    pub struct IdentityDocument {
450        #[serde(default)]
451        #[serde_as(as = "serde_with::DefaultOnNull<_>")]
452        pub devpay_product_codes: Vec<String>,
453        #[serde(default)]
454        #[serde_as(as = "serde_with::DefaultOnNull<_>")]
455        pub marketplace_product_codes: Vec<String>,
456        pub availability_zone: String,
457        pub private_ip: String,
458        pub version: String,
459        pub instance_id: String,
460        #[serde(default)]
461        #[serde_as(as = "serde_with::DefaultOnNull<_>")]
462        pub billing_products: Vec<String>,
463        pub instance_type: String,
464        pub account_id: String,
465        pub image_id: String,
466        pub pending_time: DateTime<Utc>,
467        pub architecture: String,
468        pub kernel_id: Option<String>,
469        pub ramdisk_id: Option<String>,
470        pub region: String,
471    }
472
473    impl IdentityDocument {
474        pub async fn query_via(base_url: &str) -> anyhow::Result<Self> {
475            let client = kumo_http_client::builder()
476                .no_proxy()
477                .timeout(std::time::Duration::from_secs(1))
478                .build()
479                .unwrap();
480
481            // For IMDSv2, attempt to obtain a token first.
482            // In IMDSv1, this is not required, so we allow
483            // for this to fail and proceed to the next step
484            // without it
485
486            let mut token = None;
487
488            {
489                let mut headers = HeaderMap::new();
490                headers.insert(
491                    "X-aws-ec2-metadata-token-ttl-seconds",
492                    HeaderValue::from_static("60"),
493                );
494
495                let request = client
496                    .request(Method::PUT, format!("{base_url}/latest/api/token"))
497                    .headers(headers)
498                    .build()?;
499
500                // Note that for client.execute() to error it is likely a timeout
501                // or a routing issue: if this happens, then we assume that IMDS
502                // is not present, so we don't try with a second request that will
503                // encounter the same issue, but take longer.
504                // So we propagate that particular error out and stop
505                // further progress.
506                let response = client.execute(request).await?;
507
508                if response.status().is_success() {
509                    if let Ok(content) = response.text().await {
510                        token.replace(content.trim().to_string());
511                    }
512                } else {
513                    // Some kind of protocol error: perhaps they are running
514                    // IMDSv1 rather than v2, so continue below without a token
515                }
516            }
517
518            let mut headers = HeaderMap::new();
519            if let Some(token) = token.as_deref() {
520                headers.insert("X-aws-ec2-metadata-token", HeaderValue::from_str(token)?);
521            }
522
523            let request = client
524                .request(
525                    Method::GET,
526                    format!("{base_url}/latest/dynamic/instance-identity/document"),
527                )
528                .headers(headers)
529                .build()?;
530            let response = client.execute(request).await?;
531
532            let status = response.status();
533
534            let body_text = response
535                .text()
536                .await
537                .context("failed to read response body")?;
538            if status.is_client_error() || status.is_server_error() {
539                anyhow::bail!("failed to query identity: {status:?} {body_text}");
540            }
541
542            Ok(serde_json::from_str(&body_text)?)
543        }
544
545        pub async fn query() -> anyhow::Result<Self> {
546            Self::query_via("http://169.254.169.254").await
547        }
548    }
549
550    #[cfg(test)]
551    #[tokio::test]
552    async fn test_aws_identity_v1() {
553        use mockito::Server;
554
555        let mut server = Server::new_async().await;
556        let _mock = server
557            .mock("GET", "/latest/dynamic/instance-identity/document")
558            .with_status(200)
559            .with_body(
560                r#"{
561    "devpayProductCodes" : null,
562    "marketplaceProductCodes" : [ "1abc2defghijklm3nopqrs4tu" ],
563    "availabilityZone" : "us-west-2b",
564    "privateIp" : "10.158.112.84",
565    "version" : "2017-09-30",
566    "instanceId" : "i-1234567890abcdef0",
567    "billingProducts" : null,
568    "instanceType" : "t2.micro",
569    "accountId" : "123456789012",
570    "imageId" : "ami-5fb8c835",
571    "pendingTime" : "2016-11-19T16:32:11Z",
572    "architecture" : "x86_64",
573    "kernelId" : null,
574    "ramdiskId" : null,
575    "region" : "us-west-2"
576}"#,
577            )
578            .create_async()
579            .await;
580
581        let id = IdentityDocument::query_via(&server.url()).await.unwrap();
582        eprintln!("{id:#?}");
583        assert_eq!(id.instance_id, "i-1234567890abcdef0");
584    }
585
586    #[cfg(test)]
587    #[tokio::test]
588    async fn test_aws_identity_v2() {
589        use mockito::Server;
590
591        let token = "fake-token";
592        let mut server = Server::new_async().await;
593        let _mock = server
594            .mock("PUT", "/latest/api/token")
595            .match_header("X-aws-ec2-metadata-token-ttl-seconds", "60")
596            .with_status(200)
597            .with_body(token)
598            .create_async()
599            .await;
600        let _mock = server
601            .mock("GET", "/latest/dynamic/instance-identity/document")
602            .with_status(200)
603            .match_header("X-aws-ec2-metadata-token", token)
604            .with_body(
605                r#"{
606    "devpayProductCodes" : null,
607    "marketplaceProductCodes" : [ "1abc2defghijklm3nopqrs4tu" ],
608    "availabilityZone" : "us-west-2b",
609    "privateIp" : "10.158.112.84",
610    "version" : "2017-09-30",
611    "instanceId" : "i-1234567890abcdef0",
612    "billingProducts" : null,
613    "instanceType" : "t2.micro",
614    "accountId" : "123456789012",
615    "imageId" : "ami-5fb8c835",
616    "pendingTime" : "2016-11-19T16:32:11Z",
617    "architecture" : "x86_64",
618    "kernelId" : null,
619    "ramdiskId" : null,
620    "region" : "us-west-2"
621}"#,
622            )
623            .create_async()
624            .await;
625
626        let id = IdentityDocument::query_via(&server.url()).await.unwrap();
627        eprintln!("{id:#?}");
628        assert_eq!(id.instance_id, "i-1234567890abcdef0");
629    }
630}
631
632pub mod gcp {
633    use super::*;
634
635    #[derive(Debug)]
636    pub struct InstanceMetadata {
637        pub instance_id: String,
638    }
639
640    impl InstanceMetadata {
641        pub async fn query_via(base_url: &str) -> anyhow::Result<Self> {
642            let client = kumo_http_client::builder()
643                .no_proxy()
644                .timeout(std::time::Duration::from_secs(1))
645                .build()
646                .unwrap();
647
648            let mut headers = HeaderMap::new();
649            headers.insert("Metadata-Flavor", HeaderValue::from_static("Google"));
650
651            let request = client
652                .request(
653                    Method::GET,
654                    format!("{base_url}/computeMetadata/v1/instance/id"),
655                )
656                .headers(headers)
657                .build()?;
658            let response = client.execute(request).await?;
659            let status = response.status();
660
661            let instance_id = response
662                .text()
663                .await
664                .context("failed to read response body")?
665                .trim()
666                .to_string();
667            if status.is_client_error() || status.is_server_error() {
668                anyhow::bail!("failed to query identity: {status:?} {instance_id}");
669            }
670
671            Ok(Self { instance_id })
672        }
673
674        pub async fn query() -> anyhow::Result<Self> {
675            Self::query_via("http://metadata.google.internal").await
676        }
677    }
678
679    #[cfg(test)]
680    #[tokio::test]
681    async fn test_gcp() {
682        use mockito::Server;
683
684        let mut server = Server::new_async().await;
685        let _mock = server
686            .mock("GET", "/computeMetadata/v1/instance/id")
687            .with_status(200)
688            .with_body("some_id")
689            .create_async()
690            .await;
691
692        let id = InstanceMetadata::query_via(&server.url()).await.unwrap();
693        eprintln!("{id:#?}");
694        assert_eq!(id.instance_id, "some_id");
695    }
696}
697
698#[cfg(test)]
699mod test {
700    #[test]
701    fn test_machine_info() {
702        use super::*;
703        let info = MachineInfo::new();
704        eprintln!("{}", info.fingerprint());
705        eprintln!("{info:#?}");
706        /* It's hard to make a test assertion that will run anywhere
707         * because this code is all about being machine specific.
708         * This is here to help me see what the output looks like
709         * while hacking on this.
710         */
711        // panic!("{info:#?}");
712    }
713}