blueprint-remote-providers 0.2.0-alpha.2

Remote service providers for Tangle Blueprints
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
//! Google Cloud Platform provider implementation

pub mod adapter;

use crate::core::error::{Error, Result};
#[cfg(feature = "gcp")]
use crate::core::remote::CloudProvider;
use crate::core::resources::ResourceSpec;
use crate::providers::common::{InstanceSelection, ProvisionedInfrastructure, ProvisioningConfig};
#[cfg(feature = "gcp")]
use blueprint_core::{info, warn};
#[cfg(feature = "gcp")]
use blueprint_std::collections::HashMap;

/// GCP Compute Engine provisioner
pub struct GcpProvisioner {
    #[cfg(feature = "gcp")]
    project_id: String,
    #[allow(dead_code)]
    client: reqwest::Client,
    #[cfg(feature = "gcp")]
    access_token: Option<String>,
}

impl GcpProvisioner {
    /// Create new GCP provisioner
    #[cfg(feature = "gcp")]
    pub async fn new(project_id: String) -> Result<Self> {
        // In production, would use google-cloud-auth crate
        // Use environment variable or GCE metadata service for authentication
        let access_token = Self::get_access_token().await?;

        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(30))
            .build()
            .map_err(|e| Error::ConfigurationError(e.to_string()))?;

        Ok(Self {
            project_id,
            client,
            access_token: Some(access_token),
        })
    }

    #[cfg(not(feature = "gcp"))]
    pub async fn new(_project_id: String) -> Result<Self> {
        Err(Error::ConfigurationError(
            "GCP support not enabled. Enable the 'gcp' feature".into(),
        ))
    }

    /// Get access token from environment or metadata service
    #[cfg(feature = "gcp")]
    async fn get_access_token() -> Result<String> {
        // Try environment variable first
        if let Ok(token) = std::env::var("GCP_ACCESS_TOKEN") {
            return Ok(token);
        }

        // Try metadata service (for GCE instances)
        {
            let metadata_url = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token";
            let client = reqwest::Client::new();
            let response = client
                .get(metadata_url)
                .header("Metadata-Flavor", "Google")
                .send()
                .await;

            if let Ok(resp) = response {
                if let Ok(json) = resp.json::<serde_json::Value>().await {
                    if let Some(token) = json["access_token"].as_str() {
                        return Ok(token.to_string());
                    }
                }
            }
        }

        Err(Error::ConfigurationError(
            "No GCP credentials found. Set GCP_ACCESS_TOKEN or use service account".into(),
        ))
    }

    /// Provision a GCE instance
    #[cfg(feature = "gcp")]
    pub async fn provision_instance(
        &self,
        spec: &ResourceSpec,
        config: &ProvisioningConfig,
    ) -> Result<ProvisionedInfrastructure> {
        let instance_selection =
            if let Some(override_type) = config.custom_config.get("instance_type") {
                InstanceSelection {
                    instance_type: override_type.clone(),
                    spot_capable: false,
                    estimated_hourly_cost: None,
                }
            } else {
                Self::map_instance(spec)
            };
        let zone = format!("{}-a", config.region); // e.g., us-central1-a

        info!(
            "Provisioning GCP instance type {} in {}",
            instance_selection.instance_type, zone
        );
        let require_tee = config
            .custom_config
            .get("require_tee")
            .is_some_and(|value| value.eq_ignore_ascii_case("true"));

        // Prepare instance configuration
        let instance_config = serde_json::json!({
            "name": config.name,
            "machineType": format!("zones/{}/machineTypes/{}", zone, instance_selection.instance_type),
            "disks": [{
                "boot": true,
                "autoDelete": true,
                "initializeParams": {
                    "sourceImage": config.machine_image.as_deref()
                        .unwrap_or("projects/ubuntu-os-cloud/global/images/family/ubuntu-2204-lts"),
                    "diskSizeGb": spec.storage_gb.to_string(),
                }
            }],
            "networkInterfaces": [{
                "network": "global/networks/default",
                "accessConfigs": [{
                    "type": "ONE_TO_ONE_NAT",
                    "name": "External NAT"
                }]
            }],
            "metadata": {
                "items": [
                    {
                        "key": "ssh-keys",
                        "value": config.custom_config.get("ssh_public_key")
                            .unwrap_or(&String::from(""))
                    },
                    {
                        "key": "startup-script",
                        "value": Self::generate_startup_script()
                    }
                ]
            },
            "tags": {
                "items": ["blueprint", "managed"]
            },
            "labels": {
                "environment": "production",
                "managed_by": "blueprint_remote_providers"
            }
        });
        let mut instance_config = instance_config;
        if require_tee {
            instance_config["confidentialInstanceConfig"] = serde_json::json!({
                "enableConfidentialCompute": true
            });
        }

        // Create the instance
        let url = format!(
            "https://compute.googleapis.com/compute/v1/projects/{}/zones/{}/instances",
            self.project_id, zone
        );

        let access_token = self.access_token.as_ref().ok_or_else(|| {
            Error::ConfigurationError("GCP access token not available".to_string())
        })?;

        let response = self
            .client
            .post(&url)
            .bearer_auth(access_token)
            .json(&instance_config)
            .send()
            .await
            .map_err(|e| {
                Error::ConfigurationError(format!("Failed to create GCE instance: {}", e))
            })?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(Error::ConfigurationError(format!(
                "GCP API error: {}",
                error_text
            )));
        }

        let operation: serde_json::Value = response
            .json()
            .await
            .map_err(|e| Error::ConfigurationError(format!("Failed to parse response: {}", e)))?;

        info!(
            "GCP operation started: {}",
            operation["name"].as_str().unwrap_or("unknown")
        );

        // Wait for operation to complete
        self.wait_for_operation(operation["selfLink"].as_str().unwrap_or(""))
            .await?;

        // Get instance details
        let instance_url = format!(
            "https://compute.googleapis.com/compute/v1/projects/{}/zones/{}/instances/{}",
            self.project_id, zone, config.name
        );

        let instance_response = self
            .client
            .get(&instance_url)
            .bearer_auth(access_token)
            .send()
            .await
            .map_err(|e| Error::ConfigurationError(format!("Failed to get instance: {}", e)))?;

        let instance: serde_json::Value = instance_response
            .json()
            .await
            .map_err(|e| Error::ConfigurationError(format!("Failed to parse instance: {}", e)))?;

        // Extract IPs
        let network_interface = &instance["networkInterfaces"][0];
        let private_ip = network_interface["networkIP"]
            .as_str()
            .map(|s| s.to_string());
        let public_ip = network_interface["accessConfigs"][0]["natIP"]
            .as_str()
            .map(|s| s.to_string());

        let mut metadata = HashMap::new();
        metadata.insert("zone".to_string(), zone.clone());
        metadata.insert("project_id".to_string(), self.project_id.clone());
        metadata.insert("instance_name".to_string(), config.name.clone());
        metadata.insert("require_tee".to_string(), require_tee.to_string());
        if let Some(numeric_id) = instance["id"].as_str() {
            metadata.insert("instance_numeric_id".to_string(), numeric_id.to_string());
        }

        Ok(ProvisionedInfrastructure {
            provider: CloudProvider::GCP,
            instance_id: config.name.clone(),
            public_ip,
            private_ip,
            region: config.region.clone(),
            instance_type: instance_selection.instance_type,
            metadata,
        })
    }

    #[cfg(not(feature = "gcp"))]
    pub async fn provision_instance(
        &self,
        _spec: &ResourceSpec,
        _config: &ProvisioningConfig,
    ) -> Result<ProvisionedInfrastructure> {
        Err(Error::ConfigurationError(
            "GCP provisioning requires 'gcp' feature".into(),
        ))
    }

    /// Wait for GCP operation to complete
    #[cfg(feature = "gcp")]
    async fn wait_for_operation(&self, operation_url: &str) -> Result<()> {
        let max_attempts = 60;
        let mut attempts = 0;

        let access_token = self.access_token.as_ref().ok_or_else(|| {
            Error::ConfigurationError("GCP access token not available".to_string())
        })?;

        loop {
            tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;

            let response = self
                .client
                .get(operation_url)
                .bearer_auth(access_token)
                .send()
                .await
                .map_err(|e| {
                    Error::ConfigurationError(format!("Failed to check operation: {}", e))
                })?;

            let operation: serde_json::Value = response.json().await.map_err(|e| {
                Error::ConfigurationError(format!("Failed to parse operation: {}", e))
            })?;

            if operation["status"].as_str() == Some("DONE") {
                if let Some(error) = operation.get("error") {
                    return Err(Error::ConfigurationError(format!(
                        "Operation failed: {:?}",
                        error
                    )));
                }
                return Ok(());
            }

            attempts += 1;
            if attempts >= max_attempts {
                return Err(Error::ConfigurationError("Operation timeout".into()));
            }
        }
    }

    /// Generate startup script for GCE instances
    fn generate_startup_script() -> &'static str {
        r#"#!/bin/bash
        # Update system
        apt-get update
        
        # Install Docker if not present
        if ! command -v docker &> /dev/null; then
            curl -fsSL https://get.docker.com | sh
            usermod -aG docker ubuntu
        fi
        
        # Install monitoring agent
        curl -sSO https://dl.google.com/cloudagents/add-monitoring-agent-repo.sh
        bash add-monitoring-agent-repo.sh --also-install
        
        # Enable metrics collection
        systemctl enable stackdriver-agent
        systemctl start stackdriver-agent
        "#
    }

    /// Map resource requirements to GCP instance type
    fn map_instance(spec: &ResourceSpec) -> InstanceSelection {
        let gpu_count = spec.gpu_count;
        let instance_type = match (spec.cpu, spec.memory_gb, gpu_count) {
            // GPU instances
            (_, _, Some(1)) => "n1-standard-4", // Add GPU via accelerator API
            (_, _, Some(_)) => "n1-standard-8", // Multiple GPUs

            // Memory optimized
            (cpu, mem, _) if mem > cpu * 8.0 => {
                if mem <= 32.0 {
                    "n2-highmem-4"
                } else if mem <= 64.0 {
                    "n2-highmem-8"
                } else {
                    "n2-highmem-16"
                }
            }

            // CPU optimized
            (cpu, mem, _) if cpu > mem / 2.0 => {
                if cpu <= 4.0 {
                    "n2-highcpu-4"
                } else if cpu <= 8.0 {
                    "n2-highcpu-8"
                } else {
                    "n2-highcpu-16"
                }
            }

            // Standard instances
            (cpu, mem, _) if cpu <= 0.5 && mem <= 2.0 => "e2-micro",
            (cpu, mem, _) if cpu <= 1.0 && mem <= 4.0 => "e2-small",
            (cpu, mem, _) if cpu <= 2.0 && mem <= 8.0 => "e2-medium",
            (cpu, mem, _) if cpu <= 4.0 && mem <= 16.0 => "n2-standard-4",
            (cpu, mem, _) if cpu <= 8.0 && mem <= 32.0 => "n2-standard-8",
            (cpu, mem, _) if cpu <= 16.0 && mem <= 64.0 => "n2-standard-16",
            _ => "e2-standard-2",
        };

        InstanceSelection {
            instance_type: instance_type.to_string(),
            spot_capable: spec.allow_spot && !instance_type.starts_with("e2"),
            estimated_hourly_cost: Self::estimate_cost(instance_type),
        }
    }

    fn estimate_cost(instance_type: &str) -> Option<f64> {
        Some(match instance_type {
            "e2-micro" => 0.008,
            "e2-small" => 0.021,
            "e2-medium" => 0.042,
            "e2-standard-2" => 0.084,
            "n2-standard-4" => 0.194,
            "n2-standard-8" => 0.388,
            "n2-standard-16" => 0.776,
            "n2-highmem-4" => 0.260,
            "n2-highmem-8" => 0.520,
            "n2-highmem-16" => 1.040,
            "n2-highcpu-4" => 0.143,
            "n2-highcpu-8" => 0.286,
            "n2-highcpu-16" => 0.572,
            "n1-standard-4" => 0.190,
            "n1-standard-8" => 0.380,
            _ => 0.10,
        })
    }

    /// Get instance type recommendation and cost estimate for given specifications
    pub fn get_instance_recommendation(&self, spec: &ResourceSpec) -> InstanceSelection {
        Self::map_instance(spec)
    }

    /// Get cost estimate for a specific instance type
    pub fn get_cost_estimate(&self, instance_type: &str) -> Option<f64> {
        Self::estimate_cost(instance_type)
    }

    /// Get the startup script used for instance initialization
    pub fn get_startup_script(&self) -> &'static str {
        Self::generate_startup_script()
    }

    /// Terminate a GCE instance
    #[cfg(feature = "gcp")]
    pub async fn terminate_instance(&self, instance_name: &str, zone: &str) -> Result<()> {
        let url = format!(
            "https://compute.googleapis.com/compute/v1/projects/{}/zones/{}/instances/{}",
            self.project_id, zone, instance_name
        );

        let access_token = self.access_token.as_ref().ok_or_else(|| {
            Error::ConfigurationError("GCP access token not available".to_string())
        })?;

        let response = self
            .client
            .delete(&url)
            .bearer_auth(access_token)
            .send()
            .await
            .map_err(|e| {
                Error::ConfigurationError(format!("Failed to terminate instance: {}", e))
            })?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            warn!("Failed to terminate GCE instance: {}", error_text);
            return Err(Error::ConfigurationError(format!(
                "Failed to terminate GCE instance {} in zone {}: {}",
                instance_name, zone, error_text
            )));
        } else {
            info!("Terminated GCE instance: {}", instance_name);
        }

        Ok(())
    }

    #[cfg(not(feature = "gcp"))]
    pub async fn terminate_instance(&self, _instance_name: &str, _zone: &str) -> Result<()> {
        Ok(())
    }
}

// Re-export both provisioner and adapter
pub use adapter::GcpAdapter;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_gcp_instance_mapping() {
        // Test basic specs
        let spec = ResourceSpec::basic();
        let result = GcpProvisioner::map_instance(&spec);
        assert!(result.instance_type.starts_with("e2") || result.instance_type.starts_with("n2"));

        // Test performance specs
        let spec = ResourceSpec::performance();
        let result = GcpProvisioner::map_instance(&spec);
        assert!(
            result.instance_type.contains("standard") || result.instance_type.contains("highcpu")
        );

        // Test GPU specs
        let mut spec = ResourceSpec::performance();
        spec.gpu_count = Some(1);
        let result = GcpProvisioner::map_instance(&spec);
        assert!(result.instance_type.starts_with("n1"));
    }

    #[test]
    fn test_cost_estimation() {
        assert!(GcpProvisioner::estimate_cost("e2-micro").unwrap() < 0.01);
        assert!(GcpProvisioner::estimate_cost("n2-standard-16").unwrap() > 0.5);
    }
}