|
| 1 | +package azure |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + "strings" |
| 9 | + "time" |
| 10 | + |
| 11 | + "k8s.io/apimachinery/pkg/api/resource" |
| 12 | + |
| 13 | + clusterv1beta1 "go.goms.io/fleet/apis/cluster/v1beta1" |
| 14 | + placementv1beta1 "go.goms.io/fleet/apis/placement/v1beta1" |
| 15 | +) |
| 16 | + |
| 17 | +// DefaultAzureCapacityService is the default implementation of AzureCapacityService. |
| 18 | +type DefaultAzureCapacityService struct { |
| 19 | + endpoint string |
| 20 | + client *http.Client |
| 21 | +} |
| 22 | + |
| 23 | +// Compile-time check to ensure DefaultAzureCapacityService implements AzureCapacityService |
| 24 | +var _ AzureCapacityService = &DefaultAzureCapacityService{} |
| 25 | + |
| 26 | +// NewAzureCapacityService creates a new default Azure capacity service with the given endpoint. |
| 27 | +func NewAzureCapacityService(endpoint string) *DefaultAzureCapacityService { |
| 28 | + return &DefaultAzureCapacityService{ |
| 29 | + endpoint: endpoint, |
| 30 | + client: &http.Client{ |
| 31 | + Timeout: 30 * time.Second, |
| 32 | + }, |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +// ValidateCapacityRequirement validates a capacity requirement against Azure APIs. |
| 37 | +func (s *DefaultAzureCapacityService) ValidateCapacityRequirement( |
| 38 | + cluster *clusterv1beta1.MemberCluster, |
| 39 | + req placementv1beta1.PropertySelectorRequirement, |
| 40 | +) (bool, error) { |
| 41 | + ctx := context.Background() |
| 42 | + subID, location := extractAzureInfoFromLabels(cluster) |
| 43 | + if subID == "" || location == "" { |
| 44 | + return false, fmt.Errorf("cluster %s does not have required Azure labels", cluster.Name) |
| 45 | + } |
| 46 | + capacity, sku, err := extractCapacityRequirements(req) |
| 47 | + if err != nil { |
| 48 | + return false, fmt.Errorf("failed to extract capacity requirement: %w", err) |
| 49 | + } |
| 50 | + |
| 51 | + url := fmt.Sprintf("%s/fleet/subscriptions/%s/providers/Microsoft.Compute/locations/%s/vmSizeRecommendations/vmAttributeBased/generate", |
| 52 | + s.endpoint, subID, location) |
| 53 | + payload := map[string]interface{}{ |
| 54 | + "regular_priority_profile": map[string]interface{}{ |
| 55 | + "capacity_unit_type": "CAPACITY_UNIT_TYPE_VM_INSTANCE_COUNT", |
| 56 | + "target_capacity": capacity.Value(), |
| 57 | + }, |
| 58 | + "recommendation_properties": map[string]interface{}{ |
| 59 | + "restrictions_filter": "RESTRICTIONS_FILTER_QUOTA_AND_OFFER_RESTRICTIONS", |
| 60 | + }, |
| 61 | + "resource_properties": map[string]interface{}{}, |
| 62 | + } |
| 63 | + body, err := json.Marshal(payload) |
| 64 | + if err != nil { |
| 65 | + return false, fmt.Errorf("failed to marshal request payload: %w", err) |
| 66 | + } |
| 67 | + |
| 68 | + httpReq, err := http.NewRequestWithContext(ctx, "POST", url, strings.NewReader(string(body))) |
| 69 | + if err != nil { |
| 70 | + return false, fmt.Errorf("failed to create HTTP request: %w", err) |
| 71 | + } |
| 72 | + httpReq.Header.Set("Content-Type", "application/json") |
| 73 | + |
| 74 | + resp, err := s.client.Do(httpReq) |
| 75 | + if err != nil { |
| 76 | + return false, fmt.Errorf("failed to make HTTP request to Azure service: %w", err) |
| 77 | + } |
| 78 | + defer resp.Body.Close() |
| 79 | + |
| 80 | + if resp.StatusCode != http.StatusOK { |
| 81 | + return false, fmt.Errorf("Azure service returned status %d", resp.StatusCode) |
| 82 | + } |
| 83 | + |
| 84 | + var respObj struct { |
| 85 | + RecommendedVmSizes struct { |
| 86 | + RegularVmSizes []struct { |
| 87 | + Name string `json:"name"` |
| 88 | + // You can add other fields if needed |
| 89 | + } `json:"regularVmSizes"` |
| 90 | + } `json:"recommendedVmSizes"` |
| 91 | + } |
| 92 | + if err := json.NewDecoder(resp.Body).Decode(&respObj); err != nil { |
| 93 | + return false, fmt.Errorf("failed to decode Azure service response: %w", err) |
| 94 | + } |
| 95 | + |
| 96 | + available := false |
| 97 | + for _, vm := range respObj.RecommendedVmSizes.RegularVmSizes { |
| 98 | + if vm.Name == sku { |
| 99 | + available = true |
| 100 | + break |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + return available, nil |
| 105 | +} |
| 106 | + |
| 107 | +// extractAzureInfoFromLabels extracts subscription ID and location from MemberCluster labels. |
| 108 | +// Returns the subscription ID and location if found, empty strings otherwise. |
| 109 | +func extractAzureInfoFromLabels(cluster *clusterv1beta1.MemberCluster) (subscriptionID, location string) { |
| 110 | + if cluster == nil || cluster.Labels == nil { |
| 111 | + return "", "" |
| 112 | + } |
| 113 | + |
| 114 | + subscriptionID = cluster.Labels[AzureSubscriptionIDLabelKey] |
| 115 | + location = cluster.Labels[AzureLocationLabelKey] |
| 116 | + |
| 117 | + return subscriptionID, location |
| 118 | +} |
| 119 | + |
| 120 | +// extractCapacityRequirements extracts the capacity value from a PropertySelectorRequirement. |
| 121 | +// This function is specifically designed for Azure SKU capacity properties that follow the pattern: |
| 122 | +// "kubernetes.azure.com/vm-size/{sku}/capacity" |
| 123 | +// Returns the capacity as a resource.Quantity and the SKU name if the requirement is valid, |
| 124 | +// or an error if the requirement is invalid or not a capacity property. |
| 125 | +func extractCapacityRequirements(req placementv1beta1.PropertySelectorRequirement) (*resource.Quantity, string, error) { |
| 126 | + // Extract SKU from the property name |
| 127 | + // Expected format: "kubernetes.azure.com/vm-size/{sku}/capacity" |
| 128 | + if !strings.HasSuffix(req.Name, "/capacity") { |
| 129 | + return nil, "", fmt.Errorf("invalid Azure SKU capacity property format: %q", req.Name) |
| 130 | + } |
| 131 | + |
| 132 | + // Remove prefix and suffix to get the SKU |
| 133 | + sku := strings.TrimSuffix(strings.TrimPrefix(req.Name, SkuCapacityPropertyPrefix+"/"), "/capacity") |
| 134 | + if sku == "" { |
| 135 | + return nil, "", fmt.Errorf("cannot extract SKU from property name: %q", req.Name) |
| 136 | + } |
| 137 | + |
| 138 | + // Validate that we have exactly one value |
| 139 | + if len(req.Values) != 1 { |
| 140 | + return nil, "", fmt.Errorf("Azure SKU capacity property must have exactly one value, got %d", len(req.Values)) |
| 141 | + } |
| 142 | + |
| 143 | + // Parse the capacity value |
| 144 | + capacity, err := resource.ParseQuantity(req.Values[0]) |
| 145 | + if err != nil { |
| 146 | + return nil, "", fmt.Errorf("failed to parse capacity value %q: %w", req.Values[0], err) |
| 147 | + } |
| 148 | + |
| 149 | + return &capacity, sku, nil |
| 150 | +} |
0 commit comments