diff --git a/examples/resources/spectrocloud_virtual_machine2/container.tf1 b/examples/resources/spectrocloud_virtual_machine2/container.tf1 new file mode 100644 index 00000000..eca4132e --- /dev/null +++ b/examples/resources/spectrocloud_virtual_machine2/container.tf1 @@ -0,0 +1,173 @@ +resource "spectrocloud_virtual_machine" "virtual_machine_cont" { + cluster_uid = "6414899fa4e47d6788678ecf" + #run_on_launch = true + vm_action = "stop" + metadata { + name = "test-vm-cont" + namespace = "default" + labels = { + "key1" = "value1" + } + } + spec { + data_volume_templates { + metadata { + name = "test-vm-bootvolume" + namespace = "default" + } + spec { + source { + blank {} + } + pvc { + access_modes = ["ReadWriteOnce"] + resources { + requests = { + storage = "5Gi" + } + } + storage_class_name = "sumit-storage-class" + volume_mode = "Block" + } + } + } + template { + metadata { + labels = { + "kubevirt.io/vm" = "test-vm-cont" + } + } + spec { + volume { + name = "test-vm-containerdisk1" + volume_source { + container_disk { + image_url = "gcr.io/spectro-images-public/release/vm-dashboard/os/fedora-container-disk:37" + } + } + } + volume { + name = "test-vm-volumedisk1" + volume_source { + data_volume { + name = "test-vm-bootvolume" + } + } + } + domain { + resources { + requests = { + memory = "8G" + cpu = 2 + } + } + devices { + disk { + name = "test-vm-containerdisk1" + disk_device { + disk { + bus = "virtio" + } + } + } + disk { + name = "test-vm-volumedisk1" + disk_device { + disk { + bus = "virtio" + } + } + } + interface { + name = "main" + interface_binding_method = "InterfaceMasquerade" + } + } + } + network { + name = "main" + network_source { + pod {} + } + } + /* affinity { + pod_anti_affinity { + preferred_during_scheduling_ignored_during_execution { + weight = 100 + pod_affinity_term { + label_selector { + match_labels = { + anti-affinity-key = "anti-affinity-val" + } + } + topology_key = "kubernetes.io/hostname" + } + } + } + }*/ + } + } + } +} + + +/*resource "spectrocloud_virtual_machine" "tf-test-vm-clone-default" { + cluster_uid = "6414899fa4e47d6788678ecf" + run_on_launch = false + vm_action = "stop" + base_vm_name = spectrocloud_virtual_machine.virtual_machine_cont.metadata.0.name + metadata { + name = "tf-test-vm-clone-default" + namespace = "default" + labels = { + "key1" = "value1" + } + } + spec { + template { + metadata { + labels = { + "kubevirt.io/vm" = "test-vm-cont" + } + } + spec { + volume { + name = "test-vm-containerdisk1" + volume_source { + container_disk { + image_url = "quay.io/kubevirt/fedora-cloud-container-disk-demo" + } + } + } + domain { + resources { + requests = { + memory = "8G" + cpu = 2 + } + } + devices { + disk { + name = "test-vm-containerdisk1" + disk_device { + disk { + bus = "virtio" + } + } + } + interface { + name = "main" + interface_binding_method = "InterfaceMasquerade" + } + } + } + network { + name = "main" + network_source { + pod {} + } + } + } + } + } +}*/ \ No newline at end of file diff --git a/examples/resources/spectrocloud_virtual_machine2/vm.tf b/examples/resources/spectrocloud_virtual_machine2/vm.tf1 similarity index 98% rename from examples/resources/spectrocloud_virtual_machine2/vm.tf rename to examples/resources/spectrocloud_virtual_machine2/vm.tf1 index f3dcc681..5174d68c 100644 --- a/examples/resources/spectrocloud_virtual_machine2/vm.tf +++ b/examples/resources/spectrocloud_virtual_machine2/vm.tf1 @@ -109,7 +109,7 @@ resource "spectrocloud_virtual_machine" "virtual_machine" { } // Creating VM by cloning existing VM -resource "spectrocloud_virtual_machine" "tf-test-vm-clone-default" { +/*resource "spectrocloud_virtual_machine" "tf-test-vm-clone-default" { cluster_uid = "6414899fa4e47d6788678ecf" base_vm_name = spectrocloud_virtual_machine.virtual_machine.metadata.0.name metadata { @@ -119,6 +119,7 @@ resource "spectrocloud_virtual_machine" "tf-test-vm-clone-default" { "key1" = "value1" } } +}*/ } diff --git a/go.mod b/go.mod index 9476cf4c..6dbf8b63 100644 --- a/go.mod +++ b/go.mod @@ -4,19 +4,19 @@ go 1.18 require ( github.com/go-openapi/strfmt v0.21.5 + github.com/google/go-cmp v0.5.9 github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 github.com/hashicorp/terraform-plugin-docs v0.13.0 github.com/hashicorp/terraform-plugin-sdk/v2 v2.26.1 github.com/robfig/cron v1.2.0 - github.com/spectrocloud/hapi v1.14.1-0.20230317084133-6a290ae86693 - github.com/spectrocloud/palette-sdk-go v0.0.0-20230327174315-0bcf2ac616f4 - github.com/stretchr/testify v1.8.2 + github.com/spectrocloud/hapi v1.14.1-0.20230315115513-301628ae2f5e + github.com/spectrocloud/palette-sdk-go v0.0.0-20230404004301-0e4bcff8f3e7 + github.com/stretchr/testify v1.8.0 gotest.tools v2.2.0+incompatible - k8s.io/api v0.26.3 - k8s.io/apimachinery v0.26.3 + k8s.io/api v0.23.5 + k8s.io/apimachinery v0.23.5 kubevirt.io/api v0.59.0 kubevirt.io/containerized-data-importer-api v1.56.0 - ) require ( @@ -45,7 +45,6 @@ require ( github.com/go-openapi/validate v0.20.2 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/protobuf v1.5.2 // indirect - github.com/google/go-cmp v0.5.9 // indirect github.com/google/gofuzz v1.1.0 // indirect github.com/google/uuid v1.3.0 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect diff --git a/go.sum b/go.sum index e416a966..02bd5013 100644 --- a/go.sum +++ b/go.sum @@ -715,10 +715,10 @@ github.com/soheilhy/cmux v0.1.5/go.mod h1:T7TcVDs9LWfQgPlPsdngu6I6QIoyIFZDDC6sNE github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spectrocloud/gomi v1.14.1-0.20230227082335-00ec30f78888 h1:W4Doe7rx70Gi9gAgb+Lru/IwdX5rGpN3f+wnm9bS2zo= github.com/spectrocloud/gomi v1.14.1-0.20230227082335-00ec30f78888/go.mod h1:UnhUDpFEvtYh6m384r3xzj8/+Z6/hMp2O8whEMYVHec= -github.com/spectrocloud/hapi v1.14.1-0.20230317084133-6a290ae86693 h1:mpTHGyP3avpysbiRdVoqo3jjHxMzj0r0aOP3X8hVpeY= -github.com/spectrocloud/hapi v1.14.1-0.20230317084133-6a290ae86693/go.mod h1:2eQvv8EJZnMfIFC67ONLsOaEFHsoUcRCYoU/+gV1h2M= -github.com/spectrocloud/palette-sdk-go v0.0.0-20230327174315-0bcf2ac616f4 h1:N1x5Ln1wb6EB3Kliz4/qnOmvfBtZl6l3Jgtz8t5Xk2k= -github.com/spectrocloud/palette-sdk-go v0.0.0-20230327174315-0bcf2ac616f4/go.mod h1:8zLdz1aTZpfDOxxZGqT6ng+jZiKtV3iqiy1b6cD97Pg= +github.com/spectrocloud/hapi v1.14.1-0.20230315115513-301628ae2f5e h1:xPfQZPpsZIPI/5WYySmW3TALBZwC46DhcqYE/W4apGo= +github.com/spectrocloud/hapi v1.14.1-0.20230315115513-301628ae2f5e/go.mod h1:2eQvv8EJZnMfIFC67ONLsOaEFHsoUcRCYoU/+gV1h2M= +github.com/spectrocloud/palette-sdk-go v0.0.0-20230404004301-0e4bcff8f3e7 h1:GRGOUXoOoODWUMLSDVFKoHQu4HYGmbQBepRgT+UwNdQ= +github.com/spectrocloud/palette-sdk-go v0.0.0-20230404004301-0e4bcff8f3e7/go.mod h1:8zLdz1aTZpfDOxxZGqT6ng+jZiKtV3iqiy1b6cD97Pg= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= @@ -741,7 +741,6 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -750,9 +749,8 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= +github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= -github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= @@ -1331,16 +1329,14 @@ honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9 honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= k8s.io/api v0.23.0/go.mod h1:8wmDdLBHBNxtOIytwLstXt5E9PddnZb0GaMcqsvDBpg= k8s.io/api v0.23.3/go.mod h1:w258XdGyvCmnBj/vGzQMj6kzdufJZVUwEM1U2fRJwSQ= +k8s.io/api v0.23.5 h1:zno3LUiMubxD/V1Zw3ijyKO3wxrhbUF1Ck+VjBvfaoA= k8s.io/api v0.23.5/go.mod h1:Na4XuKng8PXJ2JsploYYrivXrINeTaycCGcYgF91Xm8= -k8s.io/api v0.26.3 h1:emf74GIQMTik01Aum9dPP0gAypL8JTLl/lHa4V9RFSU= -k8s.io/api v0.26.3/go.mod h1:PXsqwPMXBSBcL1lJ9CYDKy7kIReUydukS5JiRlxC3qE= k8s.io/apiextensions-apiserver v0.23.5 h1:5SKzdXyvIJKu+zbfPc3kCbWpbxi+O+zdmAJBm26UJqI= k8s.io/apiextensions-apiserver v0.23.5/go.mod h1:ntcPWNXS8ZPKN+zTXuzYMeg731CP0heCTl6gYBxLcuQ= k8s.io/apimachinery v0.23.0/go.mod h1:fFCTTBKvKcwTPFzjlcxp91uPFZr+JA0FubU4fLzzFYc= k8s.io/apimachinery v0.23.3/go.mod h1:BEuFMMBaIbcOqVIJqNZJXGFTP4W6AycEpb5+m/97hrM= +k8s.io/apimachinery v0.23.5 h1:Va7dwhp8wgkUPWsEXk6XglXWU4IKYLKNlv8VkX7SDM0= k8s.io/apimachinery v0.23.5/go.mod h1:BEuFMMBaIbcOqVIJqNZJXGFTP4W6AycEpb5+m/97hrM= -k8s.io/apimachinery v0.26.3 h1:dQx6PNETJ7nODU3XPtrwkfuubs6w7sX0M8n61zHIV/k= -k8s.io/apimachinery v0.26.3/go.mod h1:ats7nN1LExKHvJ9TmwootT00Yz05MuYqPXEXaVeOy5I= k8s.io/apiserver v0.23.5/go.mod h1:7wvMtGJ42VRxzgVI7jkbKvMbuCbVbgsWFT7RyXiRNTw= k8s.io/client-go v0.23.5/go.mod h1:flkeinTO1CirYgzMPRWxUCnV0G4Fbu2vLhYCObnt/r4= k8s.io/code-generator v0.23.0/go.mod h1:vQvOhDXhuzqiVfM/YHp+dmg10WDZCchJVObc9MvowsE= diff --git a/pkg/cluster_profile_test/cluster_profile_create_test.go b/pkg/cluster_profile_test/cluster_profile_create_test.go deleted file mode 100644 index a286b56d..00000000 --- a/pkg/cluster_profile_test/cluster_profile_create_test.go +++ /dev/null @@ -1,103 +0,0 @@ -package cluster_profile_test - -import ( - "errors" - "testing" - - "github.com/spectrocloud/hapi/models" - clusterC "github.com/spectrocloud/hapi/spectrocluster/client/v1" - "github.com/spectrocloud/palette-sdk-go/client" - "github.com/stretchr/testify/assert" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func TestCreateClusterProfile(t *testing.T) { - testCases := []struct { - name string - clusterProfile *models.V1ClusterProfileEntity - profileContext string - expectedError error - expectedReturnedUID string - getClientError error - v1ClusterProfilesCreateFn func(params *clusterC.V1ClusterProfilesCreateParams) (*clusterC.V1ClusterProfilesCreateCreated, error) - }{ - { - name: "Success", - clusterProfile: &models.V1ClusterProfileEntity{}, - profileContext: "project", - expectedError: nil, - expectedReturnedUID: "1", - getClientError: nil, - v1ClusterProfilesCreateFn: func(params *clusterC.V1ClusterProfilesCreateParams) (*clusterC.V1ClusterProfilesCreateCreated, error) { - response := &clusterC.V1ClusterProfilesCreateCreated{Payload: &models.V1UID{UID: types.Ptr("1")}} - return response, nil - }, - }, - { - name: "Success", - clusterProfile: &models.V1ClusterProfileEntity{}, - profileContext: "tenant", - expectedError: nil, - expectedReturnedUID: "2", - getClientError: nil, - v1ClusterProfilesCreateFn: func(params *clusterC.V1ClusterProfilesCreateParams) (*clusterC.V1ClusterProfilesCreateCreated, error) { - response := &clusterC.V1ClusterProfilesCreateCreated{Payload: &models.V1UID{UID: types.Ptr("2")}} - return response, nil - }, - }, - { - name: "Error", - clusterProfile: &models.V1ClusterProfileEntity{}, - profileContext: "tenant", - expectedError: errors.New("error creating cluster profile"), - getClientError: nil, - v1ClusterProfilesCreateFn: func(params *clusterC.V1ClusterProfilesCreateParams) (*clusterC.V1ClusterProfilesCreateCreated, error) { - // Mock implementation of V1ClusterProfilesCreate goes here - return nil, errors.New("error creating cluster profile") - }, - }, - { - name: "GetClientError", - clusterProfile: &models.V1ClusterProfileEntity{}, - profileContext: "project", - expectedError: errors.New("GetClientError"), - - getClientError: errors.New("GetClientError"), - v1ClusterProfilesCreateFn: func(params *clusterC.V1ClusterProfilesCreateParams) (*clusterC.V1ClusterProfilesCreateCreated, error) { - // Mock implementation of V1ClusterProfilesCreate goes here - return nil, nil - }, - }, - { - name: "Invalid scope", - clusterProfile: &models.V1ClusterProfileEntity{}, - profileContext: "invalid", - expectedError: errors.New("invalid scope"), - getClientError: nil, - v1ClusterProfilesCreateFn: func(params *clusterC.V1ClusterProfilesCreateParams) (*clusterC.V1ClusterProfilesCreateCreated, error) { - // Mock implementation of V1ClusterProfilesCreate goes here - return nil, nil - }, - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - h := &client.V1Client{ - GetClusterClientFn: func() (clusterC.ClientService, error) { - return &clusterC.Client{}, tc.getClientError - }, - V1ClusterProfilesCreateFn: tc.v1ClusterProfilesCreateFn, - } - id, err := h.CreateClusterProfile(tc.clusterProfile, tc.profileContext) - if tc.expectedError != nil { - assert.EqualError(t, err, tc.expectedError.Error()) - } else { - assert.NoError(t, err) - } - if tc.expectedReturnedUID != "" { - assert.Equal(t, id, tc.expectedReturnedUID) - } - }) - } -} diff --git a/pkg/cluster_profile_test/cluster_profile_delete_test.go b/pkg/cluster_profile_test/cluster_profile_delete_test.go deleted file mode 100644 index f6e4291a..00000000 --- a/pkg/cluster_profile_test/cluster_profile_delete_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package cluster_profile_test - -import ( - "errors" - "testing" - - "github.com/spectrocloud/hapi/models" - clusterC "github.com/spectrocloud/hapi/spectrocluster/client/v1" - "github.com/spectrocloud/palette-sdk-go/client" - "github.com/spectrocloud/terraform-provider-spectrocloud/spectrocloud/schema" -) - -func TestDeleteClusterProfileError(t *testing.T) { - testCases := []struct { - name string - uid string - profile *models.V1ClusterProfile - expectedError error - getClientError error - getProfileError error - }{ - { - name: "GetClientError", - uid: "1", - profile: nil, - expectedError: errors.New("GetClientError"), - getClientError: errors.New("GetClientError"), - getProfileError: nil, - }, - { - name: "GetProfileError", - uid: "2", - profile: nil, - expectedError: errors.New("GetProfileError"), - getClientError: nil, - getProfileError: errors.New("GetProfileError"), - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - h := &client.V1Client{ - GetClusterClientFn: func() (clusterC.ClientService, error) { - return &clusterC.Client{}, tc.getClientError - }, - GetClusterProfileFn: func(uid string) (*models.V1ClusterProfile, error) { - return tc.profile, tc.getProfileError - }, - } - - err := h.DeleteClusterProfile(tc.uid) - schema.CompareErrors(t, err, tc.expectedError) - - }) - - } -} - -func TestDeleteClusterProfile(t *testing.T) { - testCases := []struct { - name string - uid string - profile *models.V1ClusterProfile - expectedError error - getProfileError error - }{ - { - name: "Success", - uid: "1", - profile: &models.V1ClusterProfile{Metadata: &models.V1ObjectMeta{Annotations: map[string]string{"scope": "project"}}}, - expectedError: nil, - getProfileError: nil, - }, - { - name: "Success", - uid: "2", - profile: &models.V1ClusterProfile{Metadata: &models.V1ObjectMeta{Annotations: map[string]string{"scope": "tenant"}}}, - expectedError: nil, - getProfileError: nil, - }, - { - name: "Invalid scope", - uid: "3", - profile: &models.V1ClusterProfile{Metadata: &models.V1ObjectMeta{Annotations: map[string]string{"scope": "invalid"}}}, - expectedError: errors.New("invalid scope"), - getProfileError: nil, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - h := &client.V1Client{ - GetClusterClientFn: func() (clusterC.ClientService, error) { - return &clusterC.Client{}, nil - }, - GetClusterProfileFn: func(uid string) (*models.V1ClusterProfile, error) { - return tc.profile, tc.getProfileError - }, - V1ClusterProfilesDeleteFn: func(params *clusterC.V1ClusterProfilesDeleteParams) (*clusterC.V1ClusterProfilesDeleteNoContent, error) { - return &clusterC.V1ClusterProfilesDeleteNoContent{}, nil - }, - } - err := h.DeleteClusterProfile(tc.uid) - schema.CompareErrors(t, err, tc.expectedError) - }) - } -} diff --git a/pkg/cluster_profile_test/cluster_profile_patch_test.go b/pkg/cluster_profile_test/cluster_profile_patch_test.go deleted file mode 100644 index b0ea9413..00000000 --- a/pkg/cluster_profile_test/cluster_profile_patch_test.go +++ /dev/null @@ -1,110 +0,0 @@ -package cluster_profile_test - -import ( - "errors" - "testing" - - "github.com/spectrocloud/hapi/models" - clusterC "github.com/spectrocloud/hapi/spectrocluster/client/v1" - "github.com/spectrocloud/palette-sdk-go/client" - "github.com/stretchr/testify/assert" -) - -func TestPatchClusterProfile(t *testing.T) { - testCases := []struct { - name string - clusterProfile *models.V1ClusterProfileUpdateEntity - ProfileContext string - expectedError error - getClientError error - patchError error - GetClusterClientFn func() (clusterC.ClientService, error) - v1ClusterProfilesUIDMetadataUpdateFn func(params *clusterC.V1ClusterProfilesUIDMetadataUpdateParams) (*clusterC.V1ClusterProfilesUIDMetadataUpdateNoContent, error) - }{ - { - name: "Success", - clusterProfile: &models.V1ClusterProfileUpdateEntity{ - Metadata: &models.V1ObjectMeta{ - UID: "1", - }, - }, - ProfileContext: "project", - expectedError: nil, - getClientError: nil, - patchError: nil, - v1ClusterProfilesUIDMetadataUpdateFn: func(params *clusterC.V1ClusterProfilesUIDMetadataUpdateParams) (*clusterC.V1ClusterProfilesUIDMetadataUpdateNoContent, error) { // Mock implementation of V1ClusterProfilesUIDMetadataUpdate goes here - return nil, nil - }, - }, - { - name: "Success", - clusterProfile: &models.V1ClusterProfileUpdateEntity{ - Metadata: &models.V1ObjectMeta{ - UID: "2", - }, - }, - ProfileContext: "tenant", - expectedError: errors.New("error patching cluster profile"), - getClientError: nil, - patchError: errors.New("error patching cluster profile"), - v1ClusterProfilesUIDMetadataUpdateFn: func(params *clusterC.V1ClusterProfilesUIDMetadataUpdateParams) (*clusterC.V1ClusterProfilesUIDMetadataUpdateNoContent, error) { - // Mock implementation of V1ClusterProfilesUIDMetadataUpdate goes here - return nil, errors.New("error patching cluster profile") - }, - }, - { - name: "GetClientError", - clusterProfile: &models.V1ClusterProfileUpdateEntity{ - Metadata: &models.V1ObjectMeta{ - UID: "3", - }, - }, - ProfileContext: "project", - expectedError: errors.New("GetClientError"), - getClientError: errors.New("GetClientError"), - v1ClusterProfilesUIDMetadataUpdateFn: func(params *clusterC.V1ClusterProfilesUIDMetadataUpdateParams) (*clusterC.V1ClusterProfilesUIDMetadataUpdateNoContent, error) { - // Mock implementation of V1ClusterProfilesUIDMetadataUpdate goes here - return nil, nil - }, - }, - { - name: "Invalid scope", - - clusterProfile: &models.V1ClusterProfileUpdateEntity{ - Metadata: &models.V1ObjectMeta{ - UID: "4", - }, - }, - ProfileContext: "invalid", - expectedError: errors.New("invalid scope"), - getClientError: nil, - v1ClusterProfilesUIDMetadataUpdateFn: func(params *clusterC.V1ClusterProfilesUIDMetadataUpdateParams) (*clusterC.V1ClusterProfilesUIDMetadataUpdateNoContent, error) { - // Mock implementation of V1ClusterProfilesUIDMetadataUpdate goes here - return nil, nil - }, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - h := &client.V1Client{ - GetClusterClientFn: func() (clusterC.ClientService, error) { - return &clusterC.Client{}, tc.getClientError - }, - V1ClusterProfilesUIDMetadataUpdateFn: tc.v1ClusterProfilesUIDMetadataUpdateFn, - } - - err := h.PatchClusterProfile(tc.clusterProfile, &models.V1ProfileMetaEntity{ - Metadata: &models.V1ObjectMetaInputEntity{ - Annotations: map[string]string{}, - }, - }, tc.ProfileContext) - - if tc.expectedError != nil { - assert.EqualError(t, err, tc.expectedError.Error()) - } else { - assert.NoError(t, err) - } - }) - } -} diff --git a/pkg/cluster_profile_test/cluster_profile_publish_test.go b/pkg/cluster_profile_test/cluster_profile_publish_test.go deleted file mode 100644 index a3820084..00000000 --- a/pkg/cluster_profile_test/cluster_profile_publish_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package cluster_profile_test - -import ( - "errors" - "testing" - - "github.com/spectrocloud/hapi/models" - clusterC "github.com/spectrocloud/hapi/spectrocluster/client/v1" - "github.com/spectrocloud/palette-sdk-go/client" - "github.com/spectrocloud/terraform-provider-spectrocloud/spectrocloud/schema" -) - -func TestPublishClusterProfile(t *testing.T) { - testCases := []struct { - name string - uid string - ProfileContext string - expectedError error - getClientError error - publishError error - GetClusterClientFn func() (clusterC.ClientService, error) - v1ClusterPublishFn func(params *clusterC.V1ClusterProfilesPublishParams) (*models.V1ClusterProfile, error) - }{ - { - name: "Success", - uid: "1", - ProfileContext: "project", - expectedError: nil, - getClientError: nil, - publishError: nil, - v1ClusterPublishFn: func(params *clusterC.V1ClusterProfilesPublishParams) (*models.V1ClusterProfile, error) { - // Mock implementation of V1ClusterProfilesPublish goes here - return nil, nil - }, - }, - { - name: "Success", - uid: "2", - ProfileContext: "tenant", - expectedError: errors.New("error publishing cluster profile"), - getClientError: nil, - publishError: errors.New("error publishing cluster profile"), - v1ClusterPublishFn: func(params *clusterC.V1ClusterProfilesPublishParams) (*models.V1ClusterProfile, error) { - // Mock implementation of V1ClusterProfilesPublish goes here - return nil, errors.New("error publishing cluster profile") - }, - }, - { - name: "GetClientError", - uid: "3", - ProfileContext: "project", - expectedError: errors.New("GetClientError"), - getClientError: errors.New("GetClientError"), - v1ClusterPublishFn: func(params *clusterC.V1ClusterProfilesPublishParams) (*models.V1ClusterProfile, error) { - // Mock implementation of V1ClusterProfilesPublish goes here - return nil, nil - }, - }, - { - name: "Invalid scope", - uid: "4", - ProfileContext: "invalid", - expectedError: errors.New("invalid scope"), - getClientError: nil, - v1ClusterPublishFn: func(params *clusterC.V1ClusterProfilesPublishParams) (*models.V1ClusterProfile, error) { - // Mock implementation of V1ClusterProfilesPublish goes here - return nil, nil - }, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - h := &client.V1Client{ - GetClusterClientFn: func() (clusterC.ClientService, error) { - return &clusterC.Client{}, tc.getClientError - }, - V1ClusterProfilesPublishFn: tc.v1ClusterPublishFn, - } - err := h.PublishClusterProfile(tc.uid, tc.ProfileContext) - schema.CompareErrors(t, err, tc.expectedError) - }) - } -} diff --git a/pkg/cluster_profile_test/cluster_profile_update_test.go b/pkg/cluster_profile_test/cluster_profile_update_test.go deleted file mode 100644 index 7bf43b0e..00000000 --- a/pkg/cluster_profile_test/cluster_profile_update_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package cluster_profile_test - -import ( - "errors" - "testing" - - "github.com/spectrocloud/hapi/models" - clusterC "github.com/spectrocloud/hapi/spectrocluster/client/v1" - "github.com/spectrocloud/palette-sdk-go/client" - "github.com/stretchr/testify/assert" -) - -func TestUpdateClusterProfile(t *testing.T) { - testCases := []struct { - name string - clusterProfile *models.V1ClusterProfileUpdateEntity - ProfileContext string - expectedError error - getClientError error - updateError error - GetClusterClientFn func() (clusterC.ClientService, error) - v1ClusterUpdateFn func(params *clusterC.V1ClusterProfilesUpdateParams) (*clusterC.V1ClusterProfilesUpdateNoContent, error) - }{ - { - name: "Success", - clusterProfile: &models.V1ClusterProfileUpdateEntity{ - Metadata: &models.V1ObjectMeta{ - UID: "1", - }, - }, - ProfileContext: "project", - expectedError: nil, - getClientError: nil, - updateError: nil, - v1ClusterUpdateFn: func(params *clusterC.V1ClusterProfilesUpdateParams) (*clusterC.V1ClusterProfilesUpdateNoContent, error) { - // Mock implementation of V1ClusterProfilesUpdate goes here - return nil, nil - }, - }, - { - name: "Success", - clusterProfile: &models.V1ClusterProfileUpdateEntity{ - Metadata: &models.V1ObjectMeta{ - UID: "2", - }, - }, - ProfileContext: "tenant", - expectedError: errors.New("error updating cluster profile"), - getClientError: nil, - updateError: errors.New("error updating cluster profile"), - v1ClusterUpdateFn: func(params *clusterC.V1ClusterProfilesUpdateParams) (*clusterC.V1ClusterProfilesUpdateNoContent, error) { - // Mock implementation of V1ClusterProfilesUpdate goes here - return nil, errors.New("error updating cluster profile") - }, - }, - { - name: "GetClientError", - clusterProfile: &models.V1ClusterProfileUpdateEntity{ - Metadata: &models.V1ObjectMeta{ - UID: "3", - }, - }, - ProfileContext: "project", - expectedError: errors.New("GetClientError"), - getClientError: errors.New("GetClientError"), - v1ClusterUpdateFn: func(params *clusterC.V1ClusterProfilesUpdateParams) (*clusterC.V1ClusterProfilesUpdateNoContent, error) { - // Mock implementation of V1ClusterProfilesUpdate goes here - return nil, nil - }, - }, - { - name: "Invalid scope", - clusterProfile: &models.V1ClusterProfileUpdateEntity{ - Metadata: &models.V1ObjectMeta{ - UID: "4", - }, - }, - ProfileContext: "invalid", - expectedError: errors.New("invalid scope"), - getClientError: nil, - v1ClusterUpdateFn: func(params *clusterC.V1ClusterProfilesUpdateParams) (*clusterC.V1ClusterProfilesUpdateNoContent, error) { - // Mock implementation of V1ClusterProfilesUpdate goes here - return nil, nil - }, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - h := &client.V1Client{ - GetClusterClientFn: func() (clusterC.ClientService, error) { - return &clusterC.Client{}, tc.getClientError - }, - V1ClusterProfilesUpdateFn: tc.v1ClusterUpdateFn, - } - - err := h.UpdateClusterProfile(tc.clusterProfile, tc.ProfileContext) - - if tc.expectedError != nil { - assert.EqualError(t, err, tc.expectedError.Error()) - } else { - assert.NoError(t, err) - } - }) - } -} diff --git a/spectrocloud/addon_deployment.go b/spectrocloud/addon_deployment.go index 30000ccd..51a29e11 100644 --- a/spectrocloud/addon_deployment.go +++ b/spectrocloud/addon_deployment.go @@ -18,7 +18,11 @@ func readAddonDeployment(c *client.V1Client, d *schema.ResourceData, cluster *mo if err != nil { return nil, false } - clusterProfile, err := c.GetClusterProfile(profileId) + clusterC, err := c.GetClusterClient() + if err != nil { + return nil, false + } + clusterProfile, err := c.GetClusterProfile(clusterC, profileId) if err != nil { return nil, false } diff --git a/spectrocloud/application_common.go b/spectrocloud/application_common.go index 778cf6a4..35734eec 100644 --- a/spectrocloud/application_common.go +++ b/spectrocloud/application_common.go @@ -7,7 +7,6 @@ import ( "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/spectrocloud/palette-sdk-go/client" @@ -31,7 +30,7 @@ func waitForApplication(ctx context.Context, d *schema.ResourceData, diags diag. return diags, true } - stateConf := &resource.StateChangeConf{ + stateConf := &retry.StateChangeConf{ Pending: resourceApplicationCreatePendingStates, Target: []string{"True"}, Refresh: resourceApplicationStateRefreshFunc(c, d, 5, 60), diff --git a/spectrocloud/cluster_common_attachment.go b/spectrocloud/cluster_common_attachment.go index 44010b8c..180820ce 100644 --- a/spectrocloud/cluster_common_attachment.go +++ b/spectrocloud/cluster_common_attachment.go @@ -103,6 +103,10 @@ func resourceAddonDeploymentStateRefreshFunc(c *client.V1Client, cluster_uid str func resourceAddonDeploymentDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { c := m.(*client.V1Client) + clusterC, err := c.GetClusterClient() + if err != nil { + return diag.FromErr(err) + } var diags diag.Diagnostics cluster_uid := d.Get("cluster_uid").(string) @@ -121,7 +125,7 @@ func resourceAddonDeploymentDelete(ctx context.Context, d *schema.ResourceData, profile_uids = append(profile_uids, profileId) if len(profile_uids) > 0 { - err = c.DeleteAddonDeployment(cluster_uid, &models.V1SpectroClusterProfilesDeleteEntity{ + err = c.DeleteAddonDeployment(clusterC, cluster_uid, &models.V1SpectroClusterProfilesDeleteEntity{ ProfileUids: profile_uids, }) if err != nil { diff --git a/spectrocloud/cluster_common_virtual_machine.go b/spectrocloud/cluster_common_virtual_machine.go index 359639c1..599e2fb9 100644 --- a/spectrocloud/cluster_common_virtual_machine.go +++ b/spectrocloud/cluster_common_virtual_machine.go @@ -13,8 +13,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/spectrocloud/palette-sdk-go/client" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" ) var resourceVirtualMachineCreatePendingStates = []string{ @@ -87,372 +85,3 @@ func resourceVirtualMachineStateRefreshFunc(c *client.V1Client, clusterUid strin return vm, vm.Status.PrintableStatus, nil } } - -func toVMLabels(d *schema.ResourceData) map[string]string { - labels := make(map[string]string) - if _, ok := d.GetOk("labels"); ok { - for _, t := range d.Get("labels").(*schema.Set).List() { - tag := t.(string) - if strings.Contains(tag, "=") { - labels[strings.Split(tag, "=")[0]] = strings.Split(tag, "=")[1] - } else { - labels[tag] = "spectro__tag" - } - } - return labels - } else { - return nil - } -} - -func flattenVMAnnotations(annotation map[string]string, d *schema.ResourceData) map[string]interface{} { - - if len(annotation) > 0 { - annot := map[string]interface{}{} - oldAnn := d.Get("annotations").(map[string]interface{}) - for k, v := range annotation { - if oldAnn[k] != nil { - annot[k] = v - } - } - return annot - } else { - return nil - } -} - -func flattenVMLabels(labels map[string]string) []interface{} { - tags := make([]interface{}, 0) - if len(labels) > 0 { - for k, v := range labels { - if v == "spectro__tag" { - tags = append(tags, k) - } else { - tags = append(tags, fmt.Sprintf("%s=%s", k, v)) - } - } - return tags - } else { - return nil - } -} - -func flattenVMNetwork(netModel []*models.V1VMNetwork) []interface{} { - result := make([]interface{}, 0) - netSpec := make(map[string]interface{}) - var nics []interface{} - for _, nic := range netModel { - nicSpec := make(map[string]interface{}) - nicSpec["name"] = nic.Name - if nic.Pod != nil { - nicSpec["network_type"] = "pod" - } else { - if nic.Multus != nil { - multusSpec := make(map[string]interface{}) - multusSpec["network_name"] = *nic.Multus.NetworkName - multusSpec["default"] = nic.Multus.Default - nicSpec["multus"] = []interface{}{multusSpec} - } - } - nics = append(nics, nicSpec) - } - netSpec["nic"] = nics - result = append(result, netSpec) - return result -} - -func flattenVMVolumes(volumeModel []*models.V1VMVolume) []interface{} { - result := make([]interface{}, 0) - volumeSpec := make(map[string]interface{}) - var volume []interface{} - for _, v := range volumeModel { - if v.ContainerDisk != nil { - volume = append(volume, map[string]interface{}{ - "name": v.Name, - "container_disk": []interface{}{map[string]interface{}{ - "image_url": v.ContainerDisk.Image, - }}, - }) - } - if v.CloudInitNoCloud != nil { - volume = append(volume, map[string]interface{}{ - "name": v.Name, - "cloud_init_no_cloud": []interface{}{map[string]interface{}{ - "user_data": v.CloudInitNoCloud.UserData, - }}, - }) - } - if v.DataVolume != nil { - volume = append(volume, map[string]interface{}{ - "name": v.Name, - "data_volume": []interface{}{map[string]interface{}{ - "storage": "3Gi", - }}, - }) - } - } - volumeSpec["volume"] = volume - result = append(result, volumeSpec) - return result -} - -func flattenVMDevices(d *schema.ResourceData, vmDevices *models.V1VMDevices) []interface{} { - result := make([]interface{}, 0) - devices := make(map[string]interface{}) - if _, ok := d.GetOk("devices"); ok && vmDevices.Disks != nil { - var disks []interface{} - for _, disk := range vmDevices.Disks { - if disk != nil { - disks = append(disks, map[string]interface{}{ - "name": disk.Name, - "bus": disk.Disk.Bus, - }) - } - } - devices["disk"] = disks - } - - if _, ok := d.GetOk("devices"); ok && vmDevices.Interfaces != nil { - var interfaces []interface{} - for _, iface := range vmDevices.Interfaces { - if iface != nil { - var ifaceType string - switch { - case iface.Bridge != nil: - ifaceType = "bridge" - case iface.Masquerade != nil: - ifaceType = "masquerade" - case iface.Macvtap != nil: - ifaceType = "macvtap" - } - interfaces = append(interfaces, map[string]interface{}{ - "name": iface.Name, - "type": ifaceType, - "model": iface.Model, - }) - } - } - devices["interface"] = interfaces - } - - result = append(result, devices) - return result -} - -func toVirtualMachineCreateRequest(d *schema.ResourceData) (*models.V1ClusterVirtualMachine, error) { - vmBody := &models.V1ClusterVirtualMachine{ - APIVersion: "kubevirt.io/v1", - Kind: "VirtualMachine", - Metadata: &models.V1VMObjectMeta{ - Name: d.Get("name").(string), - Namespace: d.Get("namespace").(string), - Labels: toVMLabels(d), - Annotations: toVMAnnotations(d), - }, - Spec: toSpecCreateRequest(d), - } - return vmBody, nil -} - -func toSpecCreateRequest(d *schema.ResourceData) *models.V1ClusterVirtualMachineSpec { - - //Handling Network - vmNetworks := prepareNetworkSpec(d) - - // Handling Volume - vmVolumes := prepareVolumeSpec(d) - - // Handling Disk - var vmDisks []*models.V1VMDisk - var vmInterfaces []*models.V1VMInterface - vmDisks, vmInterfaces = prepareDevices(d) - - vmSpec := &models.V1ClusterVirtualMachineSpec{ - DataVolumeTemplates: toDataVolumeTemplates(d), - Running: d.Get("run_on_launch").(bool), - Template: &models.V1VMVirtualMachineInstanceTemplateSpec{ - Spec: &models.V1VMVirtualMachineInstanceSpec{ - Domain: &models.V1VMDomainSpec{ - CPU: &models.V1VMCPU{ - Cores: int64(d.Get("cpu_cores").(int)), - }, - Devices: &models.V1VMDevices{ - Disks: vmDisks, - Interfaces: vmInterfaces, - }, - Resources: &models.V1VMResourceRequirements{ - Requests: map[string]interface{}{ - "memory": d.Get("memory").(string), - }, - }, - }, - Networks: vmNetworks, - Volumes: vmVolumes, - }, - }, - } - if !d.Get("run_on_launch").(bool) { - vmSpec.RunStrategy = "Manual" - } - return vmSpec -} - -func toDataVolumeTemplates(d *schema.ResourceData) []*models.V1VMDataVolumeTemplateSpec { - volumeSpec := d.Get("volume_spec").(*schema.Set) - var dataVolumeTemplates []*models.V1VMDataVolumeTemplateSpec - - if volumeSpec != nil { - volumeSpecList := volumeSpec.List() - for _, volume := range volumeSpecList { - volumeMap := volume.(map[string]interface{}) - if volumeData, ok := volumeMap["volume"]; ok { - volumeDataList := volumeData.([]interface{}) - for _, dataVolume := range volumeDataList { - dataVolumeMap := dataVolume.(map[string]interface{}) - if _, ok := dataVolumeMap["data_volume"]; ok && len(dataVolumeMap["data_volume"].(*schema.Set).List()) > 0 { - dataVolumeTemplates = append(dataVolumeTemplates, toDataVolumeTemplateSpecCreateRequest(dataVolumeMap["data_volume"], dataVolumeMap["name"].(string), d.Get("name").(string))) - } - } - } - } - } - return dataVolumeTemplates -} - -func toDataVolumeTemplateSpecCreateRequest(dataVolumeSet interface{}, name string, vmname string) *models.V1VMDataVolumeTemplateSpec { - dataVolumeList := dataVolumeSet.(*schema.Set).List() - - for _, dataVolume := range dataVolumeList { - volume := dataVolume.(map[string]interface{}) - storage := volume["storage"].(string) - - dataVolumeTemplate := &models.V1VMDataVolumeTemplateSpec{ - Metadata: &models.V1VMObjectMeta{ - OwnerReferences: []*models.V1VMOwnerReference{ - { - APIVersion: types.Ptr("kubevirt.io/v1"), - Kind: types.Ptr("VirtualMachine"), - Name: types.Ptr(vmname), - UID: types.Ptr(""), - }, - }, - Name: "disk-0-vol", - }, - Spec: &models.V1VMDataVolumeSpec{ - Storage: toV1VMStorageSpec(storage), - Pvc: toV1VMPersistentVolumeClaimSpec(storage), - Source: &models.V1VMDataVolumeSource{ - Blank: make(map[string]interface{}), - }, - }, - } - - return dataVolumeTemplate - } - - return &models.V1VMDataVolumeTemplateSpec{} -} - -func toV1VMPersistentVolumeClaimSpec(storage string) *models.V1VMPersistentVolumeClaimSpec { - return &models.V1VMPersistentVolumeClaimSpec{ - Resources: &models.V1VMCoreResourceRequirements{ - Requests: map[string]models.V1VMQuantity{ - "storage": models.V1VMQuantity(storage), - }, - }, - StorageClassName: "sumit-storage-class", - AccessModes: []string{"ReadWriteOnce"}, - } -} - -func toV1VMStorageSpec(storage string) *models.V1VMStorageSpec { - return &models.V1VMStorageSpec{ - Resources: &models.V1VMCoreResourceRequirements{ - Requests: map[string]models.V1VMQuantity{ - "storage": models.V1VMQuantity(storage), - }, - }, - StorageClassName: "spectro-storage-class", - VolumeMode: "Block", - AccessModes: []string{"ReadWriteOnce"}, - } -} - -func toVirtualMachineUpdateRequest(d *schema.ResourceData, vm *models.V1ClusterVirtualMachine) (bool, bool, *models.V1ClusterVirtualMachine, error) { - requireUpdate := false - needRestart := false - if d.HasChange("cpu") { - vm.Spec.Template.Spec.Domain.CPU.Cores = int64(d.Get("cpu").(int)) - requireUpdate = true - needRestart = true - } - if d.HasChange("memory") { - vm.Spec.Template.Spec.Domain.Resources.Requests = map[string]interface{}{ - "memory": d.Get("memory").(string), - } - requireUpdate = true - needRestart = true - } - //if _, ok := d.GetOk("image_url"); ok && d.HasChange("image_url") { - // vm.Metadata.Namespace = d.Get("namespace").(string) - // requireUpdate = true - // needRestart = true - //} - if _, ok := d.GetOk("labels"); ok && d.HasChange("labels") { - vm.Metadata.Labels = toVMLabels(d) - requireUpdate = true - } - if _, ok := d.GetOk("annotations"); ok && d.HasChange("annotations") { - vm.Metadata.Annotations = toVMUpdateAnnotations(vm.Metadata.Annotations, d) - requireUpdate = true - } - if _, ok := d.GetOk("volume"); ok && d.HasChange("volume") { - vm.Spec.Template.Spec.Volumes = prepareVolumeSpec(d) - requireUpdate = true - needRestart = true - } - if _, ok := d.GetOk("network"); ok && d.HasChange("network") { - vm.Spec.Template.Spec.Networks = prepareNetworkSpec(d) - requireUpdate = true - needRestart = true - } - if _, ok := d.GetOk("devices"); ok && d.HasChange("devices") { - vm.Spec.Template.Spec.Domain.Devices.Disks, vm.Spec.Template.Spec.Domain.Devices.Interfaces = prepareDevices(d) - requireUpdate = true - needRestart = true - } - if run, ok := d.GetOk("run_on_launch"); ok && d.HasChange("run_on_launch") { - vm.Spec.Running = run.(bool) - if run.(bool) { - vm.Spec.RunStrategy = "" - } else { - vm.Spec.RunStrategy = "Manual" - } - - } - - return requireUpdate, needRestart, vm, nil -} - -func toVMAnnotations(d *schema.ResourceData) map[string]string { - annotation := make(map[string]string) - if _, ok := d.GetOk("annotations"); ok { - for k, a := range d.Get("annotations").(map[string]interface{}) { - annotation[k] = a.(string) - } - return annotation - } else { - return nil - } -} - -func toVMUpdateAnnotations(existingAnnotation map[string]string, d *schema.ResourceData) map[string]string { - if _, ok := d.GetOk("annotations"); ok { - for k, a := range d.Get("annotations").(map[string]interface{}) { - existingAnnotation[k] = a.(string) - } - return existingAnnotation - } else { - return nil - } -} diff --git a/spectrocloud/cluster_common_vitual_machine_device_spec.go b/spectrocloud/cluster_common_vitual_machine_device_spec.go deleted file mode 100644 index 78bba411..00000000 --- a/spectrocloud/cluster_common_vitual_machine_device_spec.go +++ /dev/null @@ -1,97 +0,0 @@ -package spectrocloud - -import ( - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/spectrocloud/hapi/models" -) - -func prepareDefaultDevices() ([]*models.V1VMDisk, []*models.V1VMInterface) { - var containerDisk = new(string) - *containerDisk = "containerdisk" - var cloudinitdisk = new(string) - *cloudinitdisk = "cloudinitdisk" - var vmDisks []*models.V1VMDisk - vmDisks = append(vmDisks, &models.V1VMDisk{ - Name: containerDisk, - Disk: &models.V1VMDiskTarget{ - Bus: "virtio", - }, - }) - vmDisks = append(vmDisks, &models.V1VMDisk{ - Name: cloudinitdisk, - Disk: &models.V1VMDiskTarget{ - Bus: "virtio", - }, - }) - var vmInterfaces []*models.V1VMInterface - var def = new(string) - *def = "default" - vmInterfaces = append(vmInterfaces, &models.V1VMInterface{ - Name: def, - Masquerade: make(map[string]interface{}), - }) - - return vmDisks, vmInterfaces -} - -func prepareDevices(d *schema.ResourceData) ([]*models.V1VMDisk, []*models.V1VMInterface) { - if device, ok := d.GetOk("devices"); ok { - var vmDisks []*models.V1VMDisk - var vmInterfaces []*models.V1VMInterface - - for _, d := range device.(*schema.Set).List() { - device := d.(map[string]interface{}) - - // For Disk - for _, disk := range device["disk"].([]interface{}) { - diskName := disk.(map[string]interface{})["name"].(string) - vmDisks = append(vmDisks, &models.V1VMDisk{ - Name: &diskName, - Disk: &models.V1VMDiskTarget{ - Bus: disk.(map[string]interface{})["bus"].(string), - }, - }) - } - - // For Interface - for _, inter := range device["interface"].([]interface{}) { - interName := inter.(map[string]interface{})["name"].(string) - - var interfaceModel string - if model, ok := inter.(map[string]interface{})["model"].(string); ok { - interfaceModel = model - } else { - interfaceModel = "virtio" - } - - interfaceType := inter.(map[string]interface{})["type"].(string) - var vmInterface *models.V1VMInterface - switch interfaceType { - case "masquerade": - vmInterface = &models.V1VMInterface{ - Name: &interName, - Model: interfaceModel, - Masquerade: make(map[string]interface{}), - } - case "bridge": - vmInterface = &models.V1VMInterface{ - Name: &interName, - Model: interfaceModel, - Bridge: make(map[string]interface{}), - } - case "macvtap": - vmInterface = &models.V1VMInterface{ - Name: &interName, - Model: interfaceModel, - Macvtap: make(map[string]interface{}), - } - } - - vmInterfaces = append(vmInterfaces, vmInterface) - } - } - return vmDisks, vmInterfaces - } else { - return prepareDefaultDevices() - } -} diff --git a/spectrocloud/cluster_common_vitual_machine_network_spec.go b/spectrocloud/cluster_common_vitual_machine_network_spec.go deleted file mode 100644 index e41f4500..00000000 --- a/spectrocloud/cluster_common_vitual_machine_network_spec.go +++ /dev/null @@ -1,76 +0,0 @@ -package spectrocloud - -import ( - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/spectrocloud/hapi/models" -) - -func prepareDefaultNetworkSpec() []*models.V1VMNetwork { - var vmNetworks []*models.V1VMNetwork - var networkName = new(string) - *networkName = "default" - vmNetworks = append(vmNetworks, &models.V1VMNetwork{ - Name: networkName, - Pod: &models.V1VMPodNetwork{}, - }) - return vmNetworks -} - -func prepareNetworkSpec(d *schema.ResourceData) []*models.V1VMNetwork { - if networkSpecs, ok := d.GetOk("network_spec"); ok { - var vmNetworks []*models.V1VMNetwork - networkSpec := networkSpecs.(*schema.Set).List()[0].(map[string]interface{})["nic"] - for _, nic := range networkSpec.([]interface{}) { - var nicName *string - if name, ok := nic.(map[string]interface{})["name"].(string); ok { - nicName = &name - } - - var pod *models.V1VMPodNetwork - var multus *models.V1VMMultusNetwork - if multusConfig, ok := nic.(map[string]interface{})["multus"]; ok && multusConfig != nil { - // if multusConfig is not empty - if len(multusConfig.([]interface{})) > 0 { - multusMap := multusConfig.([]interface{})[0].(map[string]interface{}) - - var multusName *string - if name, ok := multusMap["network_name"].(string); ok { - multusName = &name - } - - var multusDefault bool - if defaultVal, ok := multusMap["default"].(bool); ok { - multusDefault = defaultVal - } - - multus = &models.V1VMMultusNetwork{ - NetworkName: multusName, - Default: multusDefault, - } - } else { - multus = nil - pod = &models.V1VMPodNetwork{} - } - } - - var networkType *string - if t, ok := nic.(map[string]interface{})["network_type"].(string); ok { - networkType = &t - } - - if networkType != nil && *networkType == "pod" { - multus = nil - pod = &models.V1VMPodNetwork{} - } - - vmNetworks = append(vmNetworks, &models.V1VMNetwork{ - Multus: multus, - Name: nicName, - Pod: pod, - }) - } - return vmNetworks - } else { - return prepareDefaultNetworkSpec() - } -} diff --git a/spectrocloud/cluster_common_vitual_machine_volume_spec.go b/spectrocloud/cluster_common_vitual_machine_volume_spec.go deleted file mode 100644 index 0c26b9be..00000000 --- a/spectrocloud/cluster_common_vitual_machine_volume_spec.go +++ /dev/null @@ -1,78 +0,0 @@ -package spectrocloud - -import ( - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/spectrocloud/hapi/models" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func prepareDefaultVolumeSpec(d *schema.ResourceData) []*models.V1VMVolume { - //VM Volume - var vmVolumes []*models.V1VMVolume - var vmImage = new(string) - *vmImage = d.Get("image_url").(string) - var containerDisk = new(string) - *containerDisk = "containerdisk" - vmVolumes = append(vmVolumes, &models.V1VMVolume{ - Name: containerDisk, - ContainerDisk: &models.V1VMContainerDiskSource{ - Image: vmImage, - }, - }) - var cloudinitdisk = new(string) - *cloudinitdisk = "cloudinitdisk" - vmVolumes = append(vmVolumes, &models.V1VMVolume{ - Name: cloudinitdisk, - CloudInitNoCloud: &models.V1VMCloudInitNoCloudSource{ - //UserDataBase64: "SGkuXG4=", - UserData: d.Get("cloud_init_user_data").(string), - }, - }) - return vmVolumes -} - -func prepareVolumeSpec(d *schema.ResourceData) []*models.V1VMVolume { - if volumesSpec, ok := d.GetOk("volume_spec"); ok { - var vmVolumes []*models.V1VMVolume - volumes := volumesSpec.(*schema.Set).List()[0].(map[string]interface{})["volume"] - for _, vol := range volumes.([]interface{}) { - v := vol.(map[string]interface{}) - cDisk := v["container_disk"].(*schema.Set).List() - cInit := v["cloud_init_no_cloud"].(*schema.Set).List() - dataVolumeDisk := v["data_volume"].(*schema.Set).List() - - vmDiskName := v["name"].(string) - - if len(dataVolumeDisk) > 0 { - vmVolumes = append(vmVolumes, &models.V1VMVolume{ - Name: &vmDiskName, - DataVolume: &models.V1VMCoreDataVolumeSource{ - Name: types.Ptr("disk-0-vol"), - }, - }) - } - if len(cDisk) > 0 { - var vmImg = new(string) - *vmImg = cDisk[0].(map[string]interface{})["image_url"].(string) - vmVolumes = append(vmVolumes, &models.V1VMVolume{ - Name: &vmDiskName, - ContainerDisk: &models.V1VMContainerDiskSource{ - Image: vmImg, - }, - }) - } - if len(cInit) > 0 { - vmVolumes = append(vmVolumes, &models.V1VMVolume{ - Name: &vmDiskName, - CloudInitNoCloud: &models.V1VMCloudInitNoCloudSource{ - UserData: cInit[0].(map[string]interface{})["user_data"].(string), - }, - }) - } - } - return vmVolumes - } else { - return prepareDefaultVolumeSpec(d) - } -} diff --git a/spectrocloud/convert/hapi_to_kubevirt_common.go b/spectrocloud/convert/hapi_to_kubevirt_common.go index e1a78de3..1d6e5385 100644 --- a/spectrocloud/convert/hapi_to_kubevirt_common.go +++ b/spectrocloud/convert/hapi_to_kubevirt_common.go @@ -2,6 +2,7 @@ package convert import ( "encoding/base64" + "errors" "github.com/go-openapi/strfmt" "github.com/spectrocloud/hapi/models" @@ -10,13 +11,27 @@ import ( kubevirtapiv1 "kubevirt.io/api/core/v1" ) -func ToKubevirtVM(hapiVM *models.V1ClusterVirtualMachine) *kubevirtapiv1.VirtualMachine { +func ToKubevirtVM(hapiVM *models.V1ClusterVirtualMachine) (*kubevirtapiv1.VirtualMachine, error) { if hapiVM == nil { - return nil + return nil, errors.New("hapiVM is nil") } - Spec, _ := ToKubevirtVMSpecM(hapiVM.Spec) - Status, _ := ToKubevirtVMStatusM(hapiVM.Status) + Spec, err := ToKubevirtVMSpecM(hapiVM.Spec) + if err != nil { + return nil, err + } + Status, err := ToKubevirtVMStatusM(hapiVM.Status) + if err != nil { + return nil, err + } + OwnerReferences, err := ToKubevirtVMOwnerReferences(hapiVM.Metadata.OwnerReferences) + if err != nil { + return nil, err + } + ManagedFields, err := ToKubevirtVMManagedFields(hapiVM.Metadata.ManagedFields) + if err != nil { + return nil, err + } kubevirtVM := &kubevirtapiv1.VirtualMachine{ TypeMeta: metav1.TypeMeta{ Kind: hapiVM.Kind, @@ -32,17 +47,17 @@ func ToKubevirtVM(hapiVM *models.V1ClusterVirtualMachine) *kubevirtapiv1.Virtual DeletionGracePeriodSeconds: &hapiVM.Metadata.DeletionGracePeriodSeconds, Labels: hapiVM.Metadata.Labels, Annotations: hapiVM.Metadata.Annotations, - OwnerReferences: ToKubevirtVMOwnerReferences(hapiVM.Metadata.OwnerReferences), + OwnerReferences: OwnerReferences, Finalizers: hapiVM.Metadata.Finalizers, - ManagedFields: ToKubevirtVMManagedFields(hapiVM.Metadata.ManagedFields), + ManagedFields: ManagedFields, }, Spec: Spec, Status: Status, } - return kubevirtVM + return kubevirtVM, nil } -func ToKubevirtVMOwnerReferences(references []*models.V1VMOwnerReference) []metav1.OwnerReference { +func ToKubevirtVMOwnerReferences(references []*models.V1VMOwnerReference) ([]metav1.OwnerReference, error) { ret := make([]metav1.OwnerReference, len(references)) for i, reference := range references { ret[i] = metav1.OwnerReference{ @@ -55,41 +70,51 @@ func ToKubevirtVMOwnerReferences(references []*models.V1VMOwnerReference) []meta } } - return ret + return ret, nil } -func ToKubevirtVMManagedFields(fields []*models.V1VMManagedFieldsEntry) []metav1.ManagedFieldsEntry { +func ToKubevirtVMManagedFields(fields []*models.V1VMManagedFieldsEntry) ([]metav1.ManagedFieldsEntry, error) { ret := make([]metav1.ManagedFieldsEntry, len(fields)) for i, field := range fields { + FieldsV1, err := ToKvVmFieldsV1(field.FieldsV1) + if err != nil { + return nil, err + } ret[i] = metav1.ManagedFieldsEntry{ APIVersion: field.APIVersion, FieldsType: field.FieldsType, - FieldsV1: ToKvVmFieldsV1(field.FieldsV1), + FieldsV1: FieldsV1, Manager: field.Manager, Operation: ToKvVmManagedFieldsOperationType(field.Operation), // TODO: Time: ToKubevirtTime(field.Time), } } - return ret + return ret, nil } -func ToKvVmFieldsV1(v1 *models.V1VMFieldsV1) *metav1.FieldsV1 { - return &metav1.FieldsV1{ - Raw: StrfmtBase64ToByte(v1.Raw), +func ToKvVmFieldsV1(v1 *models.V1VMFieldsV1) (*metav1.FieldsV1, error) { + Raw, err := StrfmtBase64ToByte(v1.Raw) + if err != nil { + return nil, err } + Fields := &metav1.FieldsV1{ + Raw: Raw, + } + + return Fields, nil } -func StrfmtBase64ToByte(raw []strfmt.Base64) []byte { +func StrfmtBase64ToByte(raw []strfmt.Base64) ([]byte, error) { var res []byte for _, s := range raw { decoded, err := base64.StdEncoding.DecodeString(string(s)) if err != nil { - // TODO: Handle error + return nil, err } res = append(res, decoded...) } - return res + return res, nil } func ToKvVmManagedFieldsOperationType(operation string) metav1.ManagedFieldsOperationType { diff --git a/spectrocloud/convert/hapi_to_kubevirt_datavolume_template.go b/spectrocloud/convert/hapi_to_kubevirt_datavolume_template.go deleted file mode 100644 index f063bc97..00000000 --- a/spectrocloud/convert/hapi_to_kubevirt_datavolume_template.go +++ /dev/null @@ -1,72 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - "github.com/spectrocloud/terraform-provider-spectrocloud/types" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - kubevirtapiv1 "kubevirt.io/api/core/v1" - cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" -) - -func ToKubevirtDataVolumeTemplate(dataVolTemplates []*models.V1VMDataVolumeTemplateSpec) []kubevirtapiv1.DataVolumeTemplateSpec { - var dataVolumeTemplateSpec []kubevirtapiv1.DataVolumeTemplateSpec - - for _, dv := range dataVolTemplates { - dataVolumeTemplateSpec = append(dataVolumeTemplateSpec, kubevirtapiv1.DataVolumeTemplateSpec{ - ObjectMeta: ToKubevirtDataVolumeMetadata(dv.Metadata), - Spec: ToKubevirtDataVolumeSpec(dv.Spec), - }) - } - return dataVolumeTemplateSpec -} - -func ToKubevirtDataVolumeMetadata(dataVolMetadata *models.V1VMObjectMeta) metav1.ObjectMeta { - dataVolumeMetadata := metav1.ObjectMeta{ - Name: dataVolMetadata.Name, - Namespace: dataVolMetadata.Namespace, - //UID: types.UID(dataVolMetadata.UID), - //ResourceVersion: dataVolMetadata.ResourceVersion, - //Generation: dataVolMetadata.Generation, - //Labels: dataVolMetadata.Labels, - //Annotations: dataVolMetadata.Annotations, - } - return dataVolumeMetadata -} - -func ToKubevirtDataVolumeSpec(hapiDataVolSpec *models.V1VMDataVolumeSpec) cdiv1.DataVolumeSpec { - kubevirtDataVolSpec := cdiv1.DataVolumeSpec{ - Source: nil, - SourceRef: nil, - PVC: ToKubevirtDataVolumeSpecPVC(hapiDataVolSpec.Pvc), - Storage: nil, - PriorityClassName: "", - ContentType: "", - Checkpoints: nil, - FinalCheckpoint: false, - Preallocation: nil, - } - return kubevirtDataVolSpec -} - -func ToKubevirtDataVolumeSpecPVC(pvc *models.V1VMPersistentVolumeClaimSpec) *corev1.PersistentVolumeClaimSpec { - kubevirtPVC := corev1.PersistentVolumeClaimSpec{ - AccessModes: ToKubevirtPVCAccessMode(pvc.AccessModes), - //Selector: nil, - //Resources: corev1.ResourceRequirements{}, - //VolumeName: "", - StorageClassName: types.Ptr(pvc.StorageClassName), - //VolumeMode: nil, - //DataSource: nil, - //DataSourceRef: nil, - } - return &kubevirtPVC -} - -func ToKubevirtPVCAccessMode(accessMode []string) []corev1.PersistentVolumeAccessMode { - var PVCAccessMode []corev1.PersistentVolumeAccessMode - for _, acc := range accessMode { - PVCAccessMode = append(PVCAccessMode, corev1.PersistentVolumeAccessMode(acc)) - } - return PVCAccessMode -} diff --git a/spectrocloud/convert/hapi_to_kubevirt_spec.go b/spectrocloud/convert/hapi_to_kubevirt_spec.go index f95230e5..c437e1cf 100644 --- a/spectrocloud/convert/hapi_to_kubevirt_spec.go +++ b/spectrocloud/convert/hapi_to_kubevirt_spec.go @@ -6,8 +6,6 @@ import ( "github.com/spectrocloud/hapi/models" kubevirtapiv1 "kubevirt.io/api/core/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" ) func ToKubevirtVMSpecM(vm *models.V1ClusterVirtualMachineSpec) (kubevirtapiv1.VirtualMachineSpec, error) { @@ -27,36 +25,3 @@ func ToKubevirtVMSpecM(vm *models.V1ClusterVirtualMachineSpec) (kubevirtapiv1.Vi return kubevirtVMSpec, nil } - -func ToKubevirtVMSpec(i **models.V1ClusterVirtualMachineSpec) kubevirtapiv1.VirtualMachineSpec { - // return stub - hapiClusterVMSpec := *i - VMSpec := &kubevirtapiv1.VirtualMachineSpec{ - Running: types.Ptr(hapiClusterVMSpec.Running), - RunStrategy: ToKubevirtVMRunStrategy(hapiClusterVMSpec.RunStrategy), - Instancetype: ToKubevirtVMInstancetype(hapiClusterVMSpec.Instancetype), - Preference: nil, - Template: nil, - DataVolumeTemplates: ToKubevirtDataVolumeTemplate(hapiClusterVMSpec.DataVolumeTemplates), - } - return *VMSpec - //return kubevirtapiv1.VirtualMachineSpec{} -} - -func ToKubevirtVMRunStrategy(runStrategy string) *kubevirtapiv1.VirtualMachineRunStrategy { - return types.Ptr(kubevirtapiv1.VirtualMachineRunStrategy(runStrategy)) -} - -func ToKubevirtVMInstancetype(InsType *models.V1VMInstancetypeMatcher) *kubevirtapiv1.InstancetypeMatcher { - var InsTypeMatcher *kubevirtapiv1.InstancetypeMatcher - if InsType != nil { - InsTypeMatcher = &kubevirtapiv1.InstancetypeMatcher{ - Name: InsType.Name, - Kind: InsType.Kind, - RevisionName: InsType.RevisionName, - InferFromVolume: InsType.InferFromVolume, - } - } - - return InsTypeMatcher -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_affinity.go b/spectrocloud/convert/kubevirt_to_hapi_affinity.go deleted file mode 100644 index 69d5c700..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_affinity.go +++ /dev/null @@ -1,198 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - k8sv1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func ToHapiVmAffinity(affinity *k8sv1.Affinity) *models.V1VMAffinity { - return &models.V1VMAffinity{ - NodeAffinity: ToHapiVmNodeAffinity(affinity.NodeAffinity), - PodAffinity: ToHapiVmPodAffinity(affinity.PodAffinity), - PodAntiAffinity: ToHapiVmPodAntiAffinity(affinity.PodAntiAffinity), - } -} - -func ToHapiVmNodeAffinity(affinity *k8sv1.NodeAffinity) *models.V1VMNodeAffinity { - if affinity == nil { - return nil - } - - return &models.V1VMNodeAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: ToHapiVmNodeSelector(affinity.RequiredDuringSchedulingIgnoredDuringExecution), - PreferredDuringSchedulingIgnoredDuringExecution: ToHapiVmPreferredSchedulingTerms(affinity.PreferredDuringSchedulingIgnoredDuringExecution), - } -} - -func ToHapiVmPreferredSchedulingTerms(execution []k8sv1.PreferredSchedulingTerm) []*models.V1VMPreferredSchedulingTerm { - ret := make([]*models.V1VMPreferredSchedulingTerm, len(execution)) - for i, term := range execution { - ret[i] = &models.V1VMPreferredSchedulingTerm{ - Preference: ToHapiVmNodeSelectorTerm(term.Preference), - Weight: &term.Weight, - } - } - return ret -} - -func ToHapiVmNodeSelectorTerm(preference k8sv1.NodeSelectorTerm) *models.V1VMNodeSelectorTerm { - return &models.V1VMNodeSelectorTerm{ - MatchExpressions: ToHapiVmNodeSelectorRequirements(preference.MatchExpressions), - MatchFields: ToHapiVmNodeSelectorRequirements(preference.MatchFields), - } -} - -func ToHapiVmNodeSelector(execution *k8sv1.NodeSelector) *models.V1VMNodeSelector { - if execution == nil { - return nil - } - return &models.V1VMNodeSelector{ - NodeSelectorTerms: ToHapiVmNodeSelectorTerms(execution.NodeSelectorTerms), - } -} - -func ToHapiVmNodeSelectorTerms(terms []k8sv1.NodeSelectorTerm) []*models.V1VMNodeSelectorTerm { - ret := make([]*models.V1VMNodeSelectorTerm, len(terms)) - for i, term := range terms { - ret[i] = &models.V1VMNodeSelectorTerm{ - MatchExpressions: ToHapiVmNodeSelectorRequirements(term.MatchExpressions), - MatchFields: ToHapiVmNodeSelectorRequirements(term.MatchFields), - } - } - return ret -} - -func ToHapiVmNodeSelectorRequirements(expressions []k8sv1.NodeSelectorRequirement) []*models.V1VMNodeSelectorRequirement { - ret := make([]*models.V1VMNodeSelectorRequirement, len(expressions)) - for i, expression := range expressions { - ret[i] = &models.V1VMNodeSelectorRequirement{ - Key: &expression.Key, - Operator: types.Ptr(string(expression.Operator)), - Values: expression.Values, - } - } - return ret -} - -func ToHapiVmPodAntiAffinity(affinity *k8sv1.PodAntiAffinity) *models.V1PodAntiAffinity { - if affinity == nil { - return nil - } - - return &models.V1PodAntiAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: ToHapiVmPodAffinityTerm(affinity.RequiredDuringSchedulingIgnoredDuringExecution), - PreferredDuringSchedulingIgnoredDuringExecution: ToHapiVmPodAffinityTerms(affinity.PreferredDuringSchedulingIgnoredDuringExecution), - } -} - -func ToHapiVmPodAffinity(affinity *k8sv1.PodAffinity) *models.V1VMPodAffinity { - if affinity == nil { - return nil - } - return &models.V1VMPodAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: ToHapiVmPodAffinityTerm(affinity.RequiredDuringSchedulingIgnoredDuringExecution), - PreferredDuringSchedulingIgnoredDuringExecution: ToHapiVmPodAffinityTerms(affinity.PreferredDuringSchedulingIgnoredDuringExecution), - } -} - -func ToHapiVmPodAffinityTerms(execution []k8sv1.WeightedPodAffinityTerm) []*models.V1VMWeightedPodAffinityTerm { - ret := make([]*models.V1VMWeightedPodAffinityTerm, len(execution)) - for i, term := range execution { - ret[i] = &models.V1VMWeightedPodAffinityTerm{ - Weight: &term.Weight, - PodAffinityTerm: &models.V1VMPodAffinityTerm{ - LabelSelector: ToHapiVmLabelSelector(term.PodAffinityTerm.LabelSelector), - NamespaceSelector: ToHapiVmLabelSelector(term.PodAffinityTerm.NamespaceSelector), - Namespaces: term.PodAffinityTerm.Namespaces, - TopologyKey: &term.PodAffinityTerm.TopologyKey, - }, - } - } - return ret -} - -func ToHapiVmPodAffinityTerm(execution []k8sv1.PodAffinityTerm) []*models.V1VMPodAffinityTerm { - ret := make([]*models.V1VMPodAffinityTerm, len(execution)) - for i, term := range execution { - ret[i] = &models.V1VMPodAffinityTerm{ - LabelSelector: ToHapiVMLabelSelector(term.LabelSelector), - NamespaceSelector: ToHapiVMLabelSelector(term.NamespaceSelector), - Namespaces: term.Namespaces, - TopologyKey: &term.TopologyKey, - } - } - return ret -} - -func ToHapiVMLabelSelector(selector *metav1.LabelSelector) *models.V1VMLabelSelector { - return &models.V1VMLabelSelector{ - MatchExpressions: ToHapiVMLabelSelectorRequirement(selector.MatchExpressions), - MatchLabels: selector.MatchLabels, - } -} - -func ToHapiVMLabelSelectorRequirement(expressions []metav1.LabelSelectorRequirement) []*models.V1VMLabelSelectorRequirement { - ret := make([]*models.V1VMLabelSelectorRequirement, len(expressions)) - for i, expression := range expressions { - ret[i] = &models.V1VMLabelSelectorRequirement{ - Key: &expression.Key, - Operator: types.Ptr(string(expression.Operator)), - Values: expression.Values, - } - } - return ret -} - -func ToHapiVMNodeAffinity(affinity *k8sv1.NodeAffinity) *models.V1VMNodeAffinity { - return &models.V1VMNodeAffinity{ - PreferredDuringSchedulingIgnoredDuringExecution: ToHapiVMPreferredSchedulingTerm(affinity.PreferredDuringSchedulingIgnoredDuringExecution), - RequiredDuringSchedulingIgnoredDuringExecution: ToHapiVMNodeSelector(affinity.RequiredDuringSchedulingIgnoredDuringExecution), - } -} - -func ToHapiVMNodeSelector(execution *k8sv1.NodeSelector) *models.V1VMNodeSelector { - return &models.V1VMNodeSelector{ - NodeSelectorTerms: ToHapiVMNodeSelectorTerms(execution.NodeSelectorTerms), - } -} - -func ToHapiVMNodeSelectorTerms(terms []k8sv1.NodeSelectorTerm) []*models.V1VMNodeSelectorTerm { - ret := make([]*models.V1VMNodeSelectorTerm, len(terms)) - for i, term := range terms { - ret[i] = ToHapiVMNodeSelectorTerm(term) - } - return ret -} - -func ToHapiVMPreferredSchedulingTerm(execution []k8sv1.PreferredSchedulingTerm) []*models.V1VMPreferredSchedulingTerm { - ret := make([]*models.V1VMPreferredSchedulingTerm, len(execution)) - for i, term := range execution { - ret[i] = &models.V1VMPreferredSchedulingTerm{ - Preference: ToHapiVMNodeSelectorTerm(term.Preference), - Weight: &term.Weight, - } - } - return ret -} - -func ToHapiVMNodeSelectorTerm(preference k8sv1.NodeSelectorTerm) *models.V1VMNodeSelectorTerm { - return &models.V1VMNodeSelectorTerm{ - MatchFields: ToHapiVMNodeSelectorRequirement(preference.MatchFields), - MatchExpressions: ToHapiVMNodeSelectorRequirement(preference.MatchExpressions), - } -} - -func ToHapiVMNodeSelectorRequirement(expressions []k8sv1.NodeSelectorRequirement) []*models.V1VMNodeSelectorRequirement { - ret := make([]*models.V1VMNodeSelectorRequirement, len(expressions)) - for i, expression := range expressions { - ret[i] = &models.V1VMNodeSelectorRequirement{ - Key: &expression.Key, - Operator: types.Ptr(string(expression.Operator)), - Values: expression.Values, - } - } - return ret -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_credential.go b/spectrocloud/convert/kubevirt_to_hapi_credential.go deleted file mode 100644 index 607fa3a1..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_credential.go +++ /dev/null @@ -1,40 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - kubevirtapiv1 "kubevirt.io/api/core/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func ToHapiVmAccessCredentials(credentials []kubevirtapiv1.AccessCredential) []*models.V1VMAccessCredential { - ret := make([]*models.V1VMAccessCredential, len(credentials)) - for i, credential := range credentials { - var secretName *string - if credential.SSHPublicKey.Source.Secret != nil { - secretName = types.Ptr(credential.SSHPublicKey.Source.Secret.SecretName) - } - - var Users []string - if credential.SSHPublicKey.PropagationMethod.QemuGuestAgent != nil { - Users = credential.SSHPublicKey.PropagationMethod.QemuGuestAgent.Users - } - - ret[i] = &models.V1VMAccessCredential{ - SSHPublicKey: &models.V1VMSSHPublicKeyAccessCredential{ - Source: &models.V1VMSSHPublicKeyAccessCredentialSource{ - Secret: &models.V1VMAccessCredentialSecretSource{ - SecretName: secretName, - }, - }, - PropagationMethod: &models.V1VMSSHPublicKeyAccessCredentialPropagationMethod{ - QemuGuestAgent: &models.V1VMQemuGuestAgentSSHPublicKeyAccessCredentialPropagation{ - Users: Users, - }, - }, - }, - } - } - - return ret -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_datavolume_source.go b/spectrocloud/convert/kubevirt_to_hapi_datavolume_source.go deleted file mode 100644 index 5e416b30..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_datavolume_source.go +++ /dev/null @@ -1,132 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func ToHapiVmDataVolumeSource(source *cdiv1.DataVolumeSource) *models.V1VMDataVolumeSource { - if source == nil { - return nil - } - return &models.V1VMDataVolumeSource{ - Blank: ToHapiVmDataVolumeBlankSource(source.Blank), - HTTP: ToHapiVmDataVolumeHTTPSource(source.HTTP), - Imageio: ToHapiVmDataVolumeImageioSource(source.Imageio), - Pvc: ToHapiVmDataVolumePvcSource(source.PVC), - Registry: ToHapiVmDataVolumeRegistrySource(source.Registry), - S3: ToHapiVmDataVolumeS3Source(source.S3), - //TODO: Upload: ToHapiVmDataVolumeUploadSource(source.Upload), - Vddk: ToHapiVmDataVolumeVddkSource(source.VDDK), - } -} - -func ToHapiVmDataVolumeUploadSource(upload *cdiv1.DataVolumeSourceUpload) models.V1VMDataVolumeSourceUpload { - if upload == nil { - return "" - } - return make(map[string]interface{}) -} - -func ToHapiVmDataVolumeS3Source(s3 *cdiv1.DataVolumeSourceS3) *models.V1VMDataVolumeSourceS3 { - if s3 == nil { - return nil - } - return &models.V1VMDataVolumeSourceS3{ - CertConfigMap: s3.CertConfigMap, - SecretRef: s3.SecretRef, - URL: types.Ptr(s3.URL), - } -} - -func ToHapiVmDataVolumeRegistrySource(registry *cdiv1.DataVolumeSourceRegistry) *models.V1VMDataVolumeSourceRegistry { - if registry == nil { - return nil - } - - var CertConfigMap string - if registry.CertConfigMap != nil { - CertConfigMap = *registry.CertConfigMap - } - - var ImageStream string - if registry.ImageStream != nil { - ImageStream = *registry.ImageStream - } - - var PullMethod string - if registry.PullMethod != nil { - PullMethod = string(*registry.PullMethod) - } - - var SecretRef string - if registry.SecretRef != nil { - SecretRef = *registry.SecretRef - } - - return &models.V1VMDataVolumeSourceRegistry{ - CertConfigMap: CertConfigMap, - ImageStream: ImageStream, - PullMethod: PullMethod, - SecretRef: SecretRef, - URL: types.Val(registry.URL), - } -} - -func ToHapiVmDataVolumePvcSource(pvc *cdiv1.DataVolumeSourcePVC) *models.V1VMDataVolumeSourcePVC { - if pvc == nil { - return nil - } - return &models.V1VMDataVolumeSourcePVC{ - Namespace: types.Ptr(pvc.Namespace), - Name: types.Ptr(pvc.Name), - } -} - -func ToHapiVmDataVolumeVddkSource(vddk *cdiv1.DataVolumeSourceVDDK) *models.V1VMDataVolumeSourceVDDK { - if vddk == nil { - return nil - } - return &models.V1VMDataVolumeSourceVDDK{ - BackingFile: vddk.BackingFile, - InitImageURL: vddk.InitImageURL, - SecretRef: vddk.SecretRef, - Thumbprint: vddk.Thumbprint, - URL: vddk.URL, - UUID: vddk.UUID, - } -} - -func ToHapiVmDataVolumeImageioSource(imageio *cdiv1.DataVolumeSourceImageIO) *models.V1VMDataVolumeSourceImageIO { - if imageio == nil { - return nil - } - return &models.V1VMDataVolumeSourceImageIO{ - URL: types.Ptr(imageio.URL), - SecretRef: imageio.SecretRef, - CertConfigMap: imageio.CertConfigMap, - DiskID: types.Ptr(imageio.DiskID), - } -} - -func ToHapiVmDataVolumeHTTPSource(http *cdiv1.DataVolumeSourceHTTP) *models.V1VMDataVolumeSourceHTTP { - if http == nil { - return nil - } - return &models.V1VMDataVolumeSourceHTTP{ - CertConfigMap: http.CertConfigMap, - ExtraHeaders: http.ExtraHeaders, - SecretExtraHeaders: http.SecretExtraHeaders, - SecretRef: http.SecretRef, - URL: types.Ptr(http.URL), - } -} - -func ToHapiVmDataVolumeBlankSource(blank *cdiv1.DataVolumeBlankImage) models.V1VMDataVolumeBlankImage { - if blank == nil { - return nil - } - return make(map[string]interface{}) -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_datavolume_template.go b/spectrocloud/convert/kubevirt_to_hapi_datavolume_template.go deleted file mode 100644 index c2cc0291..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_datavolume_template.go +++ /dev/null @@ -1,98 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - corev1 "k8s.io/api/core/v1" - kubevirtapiv1 "kubevirt.io/api/core/v1" - cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func ToHapiVmDataVolumeTemplates(templates []kubevirtapiv1.DataVolumeTemplateSpec) []*models.V1VMDataVolumeTemplateSpec { - var hapiTemplates []*models.V1VMDataVolumeTemplateSpec - for _, template := range templates { - hapiTemplates = append(hapiTemplates, ToHapiVmDataVolumeTemplate(template)) - } - return hapiTemplates -} - -func ToHapiVmDataVolumeTemplate(template kubevirtapiv1.DataVolumeTemplateSpec) *models.V1VMDataVolumeTemplateSpec { - return &models.V1VMDataVolumeTemplateSpec{ - APIVersion: template.APIVersion, - Kind: template.Kind, - Metadata: ToHapiVmObjectMeta(template.ObjectMeta), - Spec: ToHapiVmDataVolumeSpec(template.Spec), - } -} - -func ToHapiVmDataVolumeSpec(spec cdiv1.DataVolumeSpec) *models.V1VMDataVolumeSpec { - return &models.V1VMDataVolumeSpec{ - Checkpoints: ToHapiVmCheckpoints(spec.Checkpoints), - ContentType: string(spec.ContentType), - FinalCheckpoint: spec.FinalCheckpoint, - Preallocation: *DefaultBool(spec.Preallocation, false), - PriorityClassName: spec.PriorityClassName, - Pvc: ToHapiVmPersistentVolumeClaimSpec(spec.PVC), - Source: ToHapiVmDataVolumeSource(spec.Source), - SourceRef: ToHapiVmDataVolumeReference(spec.SourceRef), - Storage: ToHapiVmDataVolumeStorage(spec.Storage), - } -} - -func ToHapiVmDataVolumeStorage(storage *cdiv1.StorageSpec) *models.V1VMStorageSpec { - if storage == nil { - return nil - } - - var VolumeMode string - if storage.VolumeMode != nil { - VolumeMode = string(*storage.VolumeMode) - } - - return &models.V1VMStorageSpec{ - AccessModes: ToHapiVmAccessModes(storage.AccessModes), - DataSource: ToHapiVmTypedLocalObjectReference(storage.DataSource), - Resources: ToHapiVmResourceRequirements(storage.Resources), - Selector: ToHapiVmLabelSelector(storage.Selector), - StorageClassName: *storage.StorageClassName, - VolumeMode: VolumeMode, - VolumeName: storage.VolumeName, - } -} - -func ToHapiVmDataVolumeReference(ref *cdiv1.DataVolumeSourceRef) *models.V1VMDataVolumeSourceRef { - if ref == nil { - return nil - } - return &models.V1VMDataVolumeSourceRef{ - Kind: types.Ptr(ref.Kind), - Name: types.Ptr(ref.Name), - Namespace: *ref.Namespace, - } -} - -func ToHapiVmPersistentVolumeClaimSpec(pvc *corev1.PersistentVolumeClaimSpec) *models.V1VMPersistentVolumeClaimSpec { - if pvc == nil { - return nil - } - - var StorageClassName string - if pvc.StorageClassName != nil { - StorageClassName = *pvc.StorageClassName - } - var VolumeMode string - if pvc.VolumeMode != nil { - VolumeMode = string(*pvc.VolumeMode) - } - return &models.V1VMPersistentVolumeClaimSpec{ - AccessModes: ToHapiVmAccessModes(pvc.AccessModes), - DataSource: ToHapiVmTypedLocalObjectReference(pvc.DataSource), - DataSourceRef: ToHapiVmTypedObjectReference(pvc.DataSourceRef), - Resources: ToHapiVmResourceRequirements(pvc.Resources), - Selector: ToHapiVmLabelSelector(pvc.Selector), - StorageClassName: StorageClassName, - VolumeMode: VolumeMode, - VolumeName: pvc.VolumeName, - } -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_datavolume_template_common.go b/spectrocloud/convert/kubevirt_to_hapi_datavolume_template_common.go deleted file mode 100644 index ff471eaf..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_datavolume_template_common.go +++ /dev/null @@ -1,98 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func ToHapiVmLabelSelector(selector *metav1.LabelSelector) *models.V1VMLabelSelector { - if selector == nil { - return nil - } - return &models.V1VMLabelSelector{ - MatchExpressions: ToHapiVmLabelSelectorRequirements(selector.MatchExpressions), - MatchLabels: selector.MatchLabels, - } -} - -func ToHapiVmLabelSelectorRequirements(expressions []metav1.LabelSelectorRequirement) []*models.V1VMLabelSelectorRequirement { - var hapiRequirements []*models.V1VMLabelSelectorRequirement - for _, expression := range expressions { - hapiRequirements = append(hapiRequirements, ToHapiVmLabelSelectorRequirement(expression)) - } - return hapiRequirements -} - -func ToHapiVmLabelSelectorRequirement(expression metav1.LabelSelectorRequirement) *models.V1VMLabelSelectorRequirement { - return &models.V1VMLabelSelectorRequirement{ - Key: types.Ptr(expression.Key), - Operator: types.Ptr(string(expression.Operator)), - Values: expression.Values, - } -} - -func ToHapiVmTypedObjectReference(ref *corev1.TypedObjectReference) *models.V1VMTypedLocalObjectReference { - if ref == nil { - return nil - } - return &models.V1VMTypedLocalObjectReference{ - APIGroup: *ref.APIGroup, - Kind: types.Ptr(ref.Kind), - Name: types.Ptr(ref.Name), - } -} - -func ToHapiVmCheckpoints(checkpoints []cdiv1.DataVolumeCheckpoint) []*models.V1VMDataVolumeCheckpoint { - var hapiCheckpoints []*models.V1VMDataVolumeCheckpoint - for _, checkpoint := range checkpoints { - hapiCheckpoints = append(hapiCheckpoints, ToHapiVmCheckpoint(checkpoint)) - } - return hapiCheckpoints -} - -func ToHapiVmCheckpoint(checkpoint cdiv1.DataVolumeCheckpoint) *models.V1VMDataVolumeCheckpoint { - return &models.V1VMDataVolumeCheckpoint{ - Current: types.Ptr(checkpoint.Current), - Previous: types.Ptr(checkpoint.Previous), - } -} - -func ToHapiVmResourceRequirements(resources corev1.ResourceRequirements) *models.V1VMCoreResourceRequirements { - return &models.V1VMCoreResourceRequirements{ - Limits: ToHapiVmResourceList(resources.Limits), - Requests: ToHapiVmResourceList(resources.Requests), - } -} - -func ToHapiVmResourceList(limits corev1.ResourceList) map[string]models.V1VMQuantity { - hapiLimits := make(map[string]models.V1VMQuantity) - for k, v := range limits { - if str := v.String(); str != "" { - hapiLimits[string(k)] = models.V1VMQuantity(str) - } - } - return hapiLimits -} - -func ToHapiVmAccessModes(accessModes []corev1.PersistentVolumeAccessMode) []string { - var hapiAccessModes []string - for _, accessMode := range accessModes { - hapiAccessModes = append(hapiAccessModes, string(accessMode)) - } - return hapiAccessModes -} - -func ToHapiVmTypedLocalObjectReference(ref *corev1.TypedLocalObjectReference) *models.V1VMTypedLocalObjectReference { - if ref == nil { - return nil - } - return &models.V1VMTypedLocalObjectReference{ - APIGroup: *ref.APIGroup, - Kind: types.Ptr(ref.Kind), - Name: types.Ptr(ref.Name), - } -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_dns.go b/spectrocloud/convert/kubevirt_to_hapi_dns.go deleted file mode 100644 index fa6afc30..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_dns.go +++ /dev/null @@ -1,35 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - v1 "k8s.io/api/core/v1" -) - -func ToHapiVmDNSConfig(config *v1.PodDNSConfig) *models.V1VMPodDNSConfig { - var Nameservers []string - if config != nil { - Nameservers = config.Nameservers - } - - return &models.V1VMPodDNSConfig{ - Nameservers: Nameservers, - Options: ToHapiVmPodDNSConfigOption(config.Options), - Searches: config.Searches, - } -} - -func ToHapiVmPodDNSConfigOption(options []v1.PodDNSConfigOption) []*models.V1VMPodDNSConfigOption { - var result []*models.V1VMPodDNSConfigOption - for _, option := range options { - result = append(result, ToHapiVmPodDNSConfigOptionItem(option)) - } - - return result -} - -func ToHapiVmPodDNSConfigOptionItem(option v1.PodDNSConfigOption) *models.V1VMPodDNSConfigOption { - return &models.V1VMPodDNSConfigOption{ - Name: option.Name, - Value: *option.Value, - } -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_domain.go b/spectrocloud/convert/kubevirt_to_hapi_domain.go deleted file mode 100644 index 116592e9..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_domain.go +++ /dev/null @@ -1,70 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - kubevirtapiv1 "kubevirt.io/api/core/v1" -) - -func ToHapiVmDomain(domain kubevirtapiv1.DomainSpec) *models.V1VMDomainSpec { - var IOThreadPolicy string - if domain.IOThreadsPolicy != nil { - IOThreadPolicy = string(*domain.IOThreadsPolicy) - } - return &models.V1VMDomainSpec{ - Chassis: ToHapiVmChassis(domain.Chassis), - CPU: ToHapiVmCPU(domain.CPU), - Clock: ToHapiVmClock(domain.Clock), - Devices: ToHapiVmDevices(domain.Devices), - Features: ToHapiVmFeatures(domain.Features), - Firmware: ToHapiVmFirmware(domain.Firmware), - IoThreadsPolicy: IOThreadPolicy, - LaunchSecurity: ToHapiVmLaunchSecurity(domain.LaunchSecurity), - Machine: ToHapiVmMachine(domain.Machine), - Memory: ToHapiVmMemory(domain.Memory), - Resources: ToHapiVmResources(domain.Resources), - } -} - -func ToHapiVmLaunchSecurity(security *kubevirtapiv1.LaunchSecurity) *models.V1VMLaunchSecurity { - if security == nil { - return nil - } - - return &models.V1VMLaunchSecurity{ - Sev: models.V1VMSEV(*security.SEV), - } -} - -func ToHapiVmMachine(machine *kubevirtapiv1.Machine) *models.V1VMMachine { - if machine == nil { - return nil - } - - return &models.V1VMMachine{ - Type: machine.Type, - } -} - -func ToHapiVmResources(resources kubevirtapiv1.ResourceRequirements) *models.V1VMResourceRequirements { - if resources.Requests == nil { - return nil - } - - return &models.V1VMResourceRequirements{ - Requests: ToHapiVmResourceList(resources.Requests), - } -} - -func ToHapiVmChassis(chassis *kubevirtapiv1.Chassis) *models.V1VMChassis { - if chassis == nil { - return nil - } - - return &models.V1VMChassis{ - Manufacturer: chassis.Manufacturer, - Serial: chassis.Serial, - Sku: chassis.Sku, - Version: chassis.Version, - Asset: chassis.Asset, - } -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_domain_cpu.go b/spectrocloud/convert/kubevirt_to_hapi_domain_cpu.go deleted file mode 100644 index f6aeef24..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_domain_cpu.go +++ /dev/null @@ -1,58 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - kubevirtapiv1 "kubevirt.io/api/core/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func ToHapiVmCPU(cpu *kubevirtapiv1.CPU) *models.V1VMCPU { - if cpu == nil { - return nil - } - - cores := int64(cpu.Cores) - sockets := int64(cpu.Sockets) - threads := int64(cpu.Threads) - - features := make([]*models.V1VMCPUFeature, len(cpu.Features)) - for i, f := range cpu.Features { - features[i] = &models.V1VMCPUFeature{ - Name: types.Ptr(f.Name), - Policy: f.Policy, - } - } - - return &models.V1VMCPU{ - Cores: cores, - DedicatedCPUPlacement: cpu.DedicatedCPUPlacement, - Features: features, - IsolateEmulatorThread: cpu.IsolateEmulatorThread, - Model: cpu.Model, - Numa: ToHapiVmNUMA(cpu.NUMA), - Realtime: ToHapivmRealtime(cpu.Realtime), - Sockets: sockets, - Threads: threads, - } -} - -func ToHapiVmNUMA(numa *kubevirtapiv1.NUMA) *models.V1VMNUMA { - if numa == nil { - return nil - } - - return &models.V1VMNUMA{ - GuestMappingPassthrough: numa.GuestMappingPassthrough, - } -} - -func ToHapivmRealtime(realtime *kubevirtapiv1.Realtime) *models.V1VMRealtime { - if realtime == nil { - return nil - } - - return &models.V1VMRealtime{ - Mask: realtime.Mask, - } -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_domain_device.go b/spectrocloud/convert/kubevirt_to_hapi_domain_device.go deleted file mode 100644 index 74b3caaf..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_domain_device.go +++ /dev/null @@ -1,124 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - kubevirtapiv1 "kubevirt.io/api/core/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func ToHapiVmDevices(devices kubevirtapiv1.Devices) *models.V1VMDevices { - return &models.V1VMDevices{ - AutoattachGraphicsDevice: *DefaultBool(devices.AutoattachGraphicsDevice, true), - AutoattachInputDevice: *DefaultBool(devices.AutoattachInputDevice, false), - AutoattachMemBalloon: *DefaultBool(devices.AutoattachMemBalloon, true), - AutoattachPodInterface: *DefaultBool(devices.AutoattachPodInterface, true), - AutoattachSerialConsole: *DefaultBool(devices.AutoattachSerialConsole, true), - AutoattachVSOCK: *DefaultBool(devices.AutoattachVSOCK, false), - BlockMultiQueue: *DefaultBool(devices.BlockMultiQueue, false), - // TODO: ClientPassthrough: nil, - DisableHotplug: devices.DisableHotplug, - Disks: ToHapiVmDisks(devices.Disks), - Filesystems: ToHapiVmFilesystems(devices.Filesystems), - Gpus: ToHapiVmGpus(devices.GPUs), - HostDevices: ToHapiVmHostDevices(devices.HostDevices), - Inputs: ToHapiVmInputs(devices.Inputs), - Interfaces: ToHapiVmInterfaces(devices.Interfaces), - NetworkInterfaceMultiqueue: *DefaultBool(devices.NetworkInterfaceMultiQueue, false), - // TODO: Rng: nil, - // TODO: Sound: nil, - // TODO: Tpm: nil, - UseVirtioTransitional: *DefaultBool(devices.UseVirtioTransitional, false), - // TODO: Watchdog: nil, - } -} - -func DefaultBool(b *bool, def bool) *bool { - if b == nil { - return &def - } - return b -} - -func ToHapiVmInputs(inputs []kubevirtapiv1.Input) []*models.V1VMInput { - var result []*models.V1VMInput - for _, input := range inputs { - result = append(result, ToHapiVmInput(input)) - } - - return result -} - -func ToHapiVmInput(input kubevirtapiv1.Input) *models.V1VMInput { - return &models.V1VMInput{ - Bus: string(input.Bus), - Name: types.Ptr(input.Name), - Type: types.Ptr(string(input.Type)), - } -} - -func ToHapiVmHostDevices(devices []kubevirtapiv1.HostDevice) []*models.V1VMHostDevice { - var result []*models.V1VMHostDevice - for _, device := range devices { - result = append(result, ToHapiVmHostDevice(device)) - } - - return result -} - -func ToHapiVmHostDevice(device kubevirtapiv1.HostDevice) *models.V1VMHostDevice { - return &models.V1VMHostDevice{ - DeviceName: types.Ptr(device.DeviceName), - Name: types.Ptr(device.Name), - Tag: device.Tag, - } -} - -func ToHapiVmGpus(gpus []kubevirtapiv1.GPU) []*models.V1VMGPU { - var result []*models.V1VMGPU - for _, u := range gpus { - result = append(result, ToHapiVmGpu(u)) - } - - return result -} - -func ToHapiVmGpu(u kubevirtapiv1.GPU) *models.V1VMGPU { - return &models.V1VMGPU{ - DeviceName: types.Ptr(u.DeviceName), - Name: types.Ptr(u.Name), - Tag: u.Tag, - VirtualGPUOptions: ToHapiVmVirtualGPUOptions(u.VirtualGPUOptions), - } -} - -func ToHapiVmVirtualGPUOptions(options *kubevirtapiv1.VGPUOptions) *models.V1VMVGPUOptions { - if options == nil { - return nil - } - - return &models.V1VMVGPUOptions{ - Display: ToHapiVmVGPUOptionsDisplay(options.Display), - } -} - -func ToHapiVmVGPUOptionsDisplay(display *kubevirtapiv1.VGPUDisplayOptions) *models.V1VMVGPUDisplayOptions { - if display == nil { - return nil - } - - return &models.V1VMVGPUDisplayOptions{ - Enabled: *display.Enabled, - RAMFB: ToHapiVmRamFB(display.RamFB), - } -} - -func ToHapiVmRamFB(fb *kubevirtapiv1.FeatureState) *models.V1VMFeatureState { - if fb == nil { - return nil - } - - return &models.V1VMFeatureState{ - Enabled: *fb.Enabled, - } -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_domain_device_interface.go b/spectrocloud/convert/kubevirt_to_hapi_domain_device_interface.go deleted file mode 100644 index 721bf233..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_domain_device_interface.go +++ /dev/null @@ -1,129 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - kubevirtapiv1 "kubevirt.io/api/core/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func ToHapiVmInterfaces(interfaces []kubevirtapiv1.Interface) []*models.V1VMInterface { - var result []*models.V1VMInterface - for _, iface := range interfaces { - result = append(result, ToHapiVmInterface(iface)) - } - - return result -} - -func ToHapiVmInterface(iface kubevirtapiv1.Interface) *models.V1VMInterface { - /*bootOrder := int32(2) // Default value 1 is used for disks - if iface.BootOrder != nil { - bootOrder = int32(*iface.BootOrder) - }*/ - - return &models.V1VMInterface{ - AcpiIndex: int32(iface.ACPIIndex), - // TODO: BootOrder: bootOrder, - Bridge: ToHapiVMInterfaceBridge(iface.InterfaceBindingMethod.Bridge), - DhcpOptions: ToHapiVMDHCPOptions(iface.DHCPOptions), - MacAddress: iface.MacAddress, - Macvtap: ToHapiVMInterfaceMacvtap(iface.InterfaceBindingMethod.Macvtap), - Masquerade: ToHapiVMInterfaceMasquerade(iface.InterfaceBindingMethod.Masquerade), - Model: iface.Model, - Name: types.Ptr(iface.Name), - Passt: ToHapiVMInterfacePasst(iface.InterfaceBindingMethod.Passt), - PciAddress: iface.PciAddress, - Ports: ToHapiVMPorts(iface.Ports), - Slirp: ToHapiVMInterfaceSlirp(iface.InterfaceBindingMethod.Slirp), - Sriov: ToHapiVMInterfaceSRIOV(iface.InterfaceBindingMethod.SRIOV), - Tag: iface.Tag, - } -} - -func ToHapiVMPorts(ports []kubevirtapiv1.Port) []*models.V1VMPort { - var result []*models.V1VMPort - for _, port := range ports { - result = append(result, ToHapiVMPort(port)) - } - - return result -} - -func ToHapiVMPort(port kubevirtapiv1.Port) *models.V1VMPort { - return &models.V1VMPort{ - Name: port.Name, - Port: types.Ptr(port.Port), - Protocol: port.Protocol, - } -} - -func ToHapiVMInterfaceMasquerade(masquerade *kubevirtapiv1.InterfaceMasquerade) models.V1VMInterfaceMasquerade { - if masquerade == nil { - return nil - } - return make(map[string]interface{}) -} - -func ToHapiVMDHCPOptions(options *kubevirtapiv1.DHCPOptions) *models.V1VMDHCPOptions { - if options == nil { - return nil - } - return &models.V1VMDHCPOptions{ - BootFileName: options.BootFileName, - NtpServers: options.NTPServers, - PrivateOptions: ToHapiVmPrivateOptions(options.PrivateOptions), - TftpServerName: options.TFTPServerName, - } -} - -func ToHapiVmPrivateOptions(options []kubevirtapiv1.DHCPPrivateOptions) []*models.V1VMDHCPPrivateOptions { - var result []*models.V1VMDHCPPrivateOptions - for _, option := range options { - result = append(result, ToHapiVmPrivateOption(option)) - } - - return result -} - -func ToHapiVmPrivateOption(option kubevirtapiv1.DHCPPrivateOptions) *models.V1VMDHCPPrivateOptions { - return &models.V1VMDHCPPrivateOptions{ - Option: types.Ptr(int32(option.Option)), - Value: types.Ptr(option.Value), - } -} - -func ToHapiVMInterfaceSRIOV(sriov *kubevirtapiv1.InterfaceSRIOV) models.V1VMInterfaceSRIOV { - if sriov == nil { - return nil - } - return make(map[string]interface{}) -} - -func ToHapiVMInterfacePasst(passt *kubevirtapiv1.InterfacePasst) models.V1VMInterfacePasst { - if passt == nil { - return nil - } - return make(map[string]interface{}) -} - -func ToHapiVMInterfaceSlirp(slirp *kubevirtapiv1.InterfaceSlirp) models.V1VMInterfaceSlirp { - if slirp == nil { - return nil - } - return make(map[string]interface{}) -} - -func ToHapiVMInterfaceMacvtap(macvtap *kubevirtapiv1.InterfaceMacvtap) models.V1VMInterfaceMacvtap { - if macvtap == nil { - return nil - } - return make(map[string]interface{}) -} - -func ToHapiVMInterfaceBridge(bridge *kubevirtapiv1.InterfaceBridge) models.V1VMInterfaceBridge { - if bridge == nil { - return nil - } - return make(map[string]interface{}) -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_domain_disk.go b/spectrocloud/convert/kubevirt_to_hapi_domain_disk.go deleted file mode 100644 index 98df5b36..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_domain_disk.go +++ /dev/null @@ -1,98 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - kubevirtapiv1 "kubevirt.io/api/core/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func ToHapiVmDisks(disks []kubevirtapiv1.Disk) []*models.V1VMDisk { - var hapiDisks []*models.V1VMDisk - for _, disk := range disks { - hapiDisks = append(hapiDisks, ToHapiVmDisk(disk)) - } - return hapiDisks -} - -func ToHapiVmDisk(disk kubevirtapiv1.Disk) *models.V1VMDisk { - /*bootOrder := int32(1) // Default value. - if disk.BootOrder != nil { - bootOrder = int32(*disk.BootOrder) - }*/ - - DedicatedIOThread := false - if disk.DedicatedIOThread != nil { - DedicatedIOThread = *disk.DedicatedIOThread - } - - return &models.V1VMDisk{ - BlockSize: ToHapiVmBlockSize(disk.BlockSize), - // TODO: BootOrder: bootOrder, - Cache: string(disk.Cache), - Cdrom: ToHapiVmCdRom(disk.CDRom), - DedicatedIOThread: DedicatedIOThread, - Disk: ToHapiVmDiskTarget(disk.Disk), - Io: string(disk.IO), - Lun: ToHapiVmLunTarget(disk.LUN), - Name: types.Ptr(disk.Name), - Serial: disk.Serial, - Shareable: false, - Tag: disk.Tag, - } -} - -func ToHapiVmLunTarget(lun *kubevirtapiv1.LunTarget) *models.V1VMLunTarget { - if lun == nil { - return nil - } - - return &models.V1VMLunTarget{ - Bus: string(lun.Bus), - Readonly: lun.ReadOnly, - } -} - -func ToHapiVmDiskTarget(disk *kubevirtapiv1.DiskTarget) *models.V1VMDiskTarget { - if disk == nil { - return nil - } - - return &models.V1VMDiskTarget{ - Bus: string(disk.Bus), - PciAddress: disk.PciAddress, - Readonly: disk.ReadOnly, - } -} - -func ToHapiVmCdRom(cdrom *kubevirtapiv1.CDRomTarget) *models.V1VMCDRomTarget { - if cdrom == nil { - return nil - } - - return &models.V1VMCDRomTarget{ - Bus: string(cdrom.Bus), - } -} - -func ToHapiVmBlockSize(size *kubevirtapiv1.BlockSize) *models.V1VMBlockSize { - if size == nil { - return nil - } - - return &models.V1VMBlockSize{ - Custom: ToHapiVmCustomBlockSize(size.Custom), - MatchVolume: nil, - } -} - -func ToHapiVmCustomBlockSize(custom *kubevirtapiv1.CustomBlockSize) *models.V1VMCustomBlockSize { - if custom == nil { - return nil - } - - return &models.V1VMCustomBlockSize{ - Physical: types.Ptr(int32(custom.Physical)), - Logical: types.Ptr(int32(custom.Logical)), - } -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_domain_memory.go b/spectrocloud/convert/kubevirt_to_hapi_domain_memory.go deleted file mode 100644 index 18439437..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_domain_memory.go +++ /dev/null @@ -1,36 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - "k8s.io/apimachinery/pkg/api/resource" - kubevirtapiv1 "kubevirt.io/api/core/v1" -) - -func ToHapiVmMemory(memory *kubevirtapiv1.Memory) *models.V1VMMemory { - if memory == nil { - return nil - } - - return &models.V1VMMemory{ - Hugepages: ToHapiVmHugepages(memory.Hugepages), - Guest: ToHapiVmGuestMemory(memory.Guest), - } -} - -func ToHapiVmGuestMemory(guest *resource.Quantity) models.V1VMQuantity { - if guest == nil { - return "" - } - - return models.V1VMQuantity(guest.String()) -} - -func ToHapiVmHugepages(hugepages *kubevirtapiv1.Hugepages) *models.V1VMHugepages { - if hugepages == nil { - return nil - } - - return &models.V1VMHugepages{ - PageSize: hugepages.PageSize, - } -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_domain_timer.go b/spectrocloud/convert/kubevirt_to_hapi_domain_timer.go deleted file mode 100644 index eef34432..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_domain_timer.go +++ /dev/null @@ -1,100 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - kubevirtapiv1 "kubevirt.io/api/core/v1" -) - -// TODO: implement clock. - -func ToHapiVmClock(clock *kubevirtapiv1.Clock) *models.V1VMClock { - if clock == nil { - return nil - } - - var Timezone string - if clock.Timezone != nil { - Timezone = string(*clock.Timezone) - } - - return &models.V1VMClock{ - Timer: ToHapiVmTimer(clock.Timer), - Timezone: Timezone, - Utc: ToHapiVmClockOffest(clock.UTC), - } -} - -func ToHapiVmClockOffest(utc *kubevirtapiv1.ClockOffsetUTC) *models.V1VMClockOffsetUTC { - if utc == nil { - return nil - } - - return &models.V1VMClockOffsetUTC{ - OffsetSeconds: int32(*utc.OffsetSeconds), - } -} - -func ToHapiVmTimer(timer *kubevirtapiv1.Timer) *models.V1VMTimer { - if timer == nil { - return nil - } - - return &models.V1VMTimer{ - Hpet: ToHapiVmHpet(timer.HPET), - Hyperv: ToHapiVmHyperv(timer.Hyperv), - Kvm: ToHapiVmKvm(timer.KVM), - Pit: ToHapiVmPit(timer.PIT), - Rtc: ToHapiVmRtc(timer.RTC), - } -} - -func ToHapiVmRtc(rtc *kubevirtapiv1.RTCTimer) *models.V1VMRTCTimer { - if rtc == nil { - return nil - } - - return &models.V1VMRTCTimer{ - // TODO - } -} - -func ToHapiVmPit(pit *kubevirtapiv1.PITTimer) *models.V1VMPITTimer { - if pit == nil { - return nil - } - - return &models.V1VMPITTimer{ - // TODO - } -} - -func ToHapiVmKvm(kvm *kubevirtapiv1.KVMTimer) *models.V1VMKVMTimer { - if kvm == nil { - return nil - } - - return &models.V1VMKVMTimer{ - Present: *kvm.Enabled, - } -} - -func ToHapiVmHyperv(hyperv *kubevirtapiv1.HypervTimer) *models.V1VMHypervTimer { - if hyperv == nil { - return nil - } - - return &models.V1VMHypervTimer{ - Present: *hyperv.Enabled, - } -} - -func ToHapiVmHpet(hpet *kubevirtapiv1.HPETTimer) *models.V1VMHPETTimer { - if hpet == nil { - return nil - } - - return &models.V1VMHPETTimer{ - Present: *hpet.Enabled, - TickPolicy: string(hpet.TickPolicy), - } -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_domain_vm_features.go b/spectrocloud/convert/kubevirt_to_hapi_domain_vm_features.go deleted file mode 100644 index 8cac99e7..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_domain_vm_features.go +++ /dev/null @@ -1,26 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - kubevirtapiv1 "kubevirt.io/api/core/v1" -) - -// TODO: implement vm features. - -func ToHapiVmFirmware(firmware *kubevirtapiv1.Firmware) *models.V1VMFirmware { - if firmware == nil { - return nil - } - - return &models.V1VMFirmware{ - Bootloader: nil, - KernelBoot: nil, - Serial: "", - UUID: string(firmware.UUID), - } -} - -func ToHapiVmFeatures(features *kubevirtapiv1.Features) *models.V1VMFeatures { - // return stub - return &models.V1VMFeatures{} -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_domain_vm_filesystem.go b/spectrocloud/convert/kubevirt_to_hapi_domain_vm_filesystem.go deleted file mode 100644 index 22115efb..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_domain_vm_filesystem.go +++ /dev/null @@ -1,24 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - kubevirtapiv1 "kubevirt.io/api/core/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func ToHapiVmFilesystems(filesystems []kubevirtapiv1.Filesystem) []*models.V1VMFilesystem { - var result []*models.V1VMFilesystem - for _, filesystem := range filesystems { - result = append(result, ToHapiVmFilesystemItem(filesystem)) - } - - return result -} - -func ToHapiVmFilesystemItem(filesystem kubevirtapiv1.Filesystem) *models.V1VMFilesystem { - return &models.V1VMFilesystem{ - Name: types.Ptr(filesystem.Name), - // TODO: Virtiofs: ToHapiVmVirtiofs(filesystem.Virtiofs), - } -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_spec.go b/spectrocloud/convert/kubevirt_to_hapi_spec.go index 7b4e6445..e7dcb2da 100644 --- a/spectrocloud/convert/kubevirt_to_hapi_spec.go +++ b/spectrocloud/convert/kubevirt_to_hapi_spec.go @@ -6,10 +6,7 @@ import ( "encoding/json" "github.com/spectrocloud/hapi/models" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kubevirtapiv1 "kubevirt.io/api/core/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" ) func ToHapiVmSpecM(spec kubevirtapiv1.VirtualMachineSpec) (*models.V1ClusterVirtualMachineSpec, error) { @@ -29,135 +26,3 @@ func ToHapiVmSpecM(spec kubevirtapiv1.VirtualMachineSpec) (*models.V1ClusterVirt return &hapiVmSpec, nil } - -func ToHapiVmSpec(spec *kubevirtapiv1.VirtualMachineSpec) *models.V1ClusterVirtualMachineSpec { - var Running bool - if spec.Running != nil { - Running = *spec.Running - } - - Metadata := ToHapiVmObjectMeta(spec.Template.ObjectMeta) - - var Spec *models.V1VMVirtualMachineInstanceSpec - if spec.Template != nil { - var TerminationGracePeriodSeconds int64 - if spec.Template.Spec.TerminationGracePeriodSeconds != nil { - TerminationGracePeriodSeconds = *spec.Template.Spec.TerminationGracePeriodSeconds - } - - var EvictionStrategy string - if spec.Template.Spec.EvictionStrategy != nil { - EvictionStrategy = string(*spec.Template.Spec.EvictionStrategy) - } - - var StartStrategy string - if spec.Template.Spec.StartStrategy != nil { - StartStrategy = string(*spec.Template.Spec.StartStrategy) - } - Spec = &models.V1VMVirtualMachineInstanceSpec{ - AccessCredentials: ToHapiVmAccessCredentials(spec.Template.Spec.AccessCredentials), - Affinity: ToHapiVmAffinity(spec.Template.Spec.Affinity), - DNSConfig: ToHapiVmDNSConfig(spec.Template.Spec.DNSConfig), - DNSPolicy: string(spec.Template.Spec.DNSPolicy), - Domain: ToHapiVmDomain(spec.Template.Spec.Domain), - EvictionStrategy: EvictionStrategy, - Hostname: spec.Template.Spec.Hostname, - LivenessProbe: ToHapiVmProbe(spec.Template.Spec.LivenessProbe), - Networks: ToHapiVmNetworks(spec.Template.Spec.Networks), - NodeSelector: spec.Template.Spec.NodeSelector, - PriorityClassName: spec.Template.Spec.PriorityClassName, - ReadinessProbe: ToHapiVmProbe(spec.Template.Spec.ReadinessProbe), - SchedulerName: spec.Template.Spec.SchedulerName, - StartStrategy: StartStrategy, - Subdomain: spec.Template.Spec.Subdomain, - TerminationGracePeriodSeconds: TerminationGracePeriodSeconds, - Tolerations: ToHapiVmTolerations(spec.Template.Spec.Tolerations), - TopologySpreadConstraints: ToHapiVmTopologySpreadConstraints(spec.Template.Spec.TopologySpreadConstraints), - Volumes: ToHapiVmVolumes(spec.Template.Spec.Volumes), - } - } - - var RunStrategy string - if spec.RunStrategy != nil { - RunStrategy = string(*spec.RunStrategy) - } - - return &models.V1ClusterVirtualMachineSpec{ - DataVolumeTemplates: ToHapiVmDataVolumeTemplates(spec.DataVolumeTemplates), - Instancetype: nil, - Preference: ToHapiVmPreferenceMatcher(spec.Preference), - RunStrategy: RunStrategy, - Running: Running, - Template: &models.V1VMVirtualMachineInstanceTemplateSpec{ - Metadata: Metadata, - Spec: Spec, - }, - } -} - -func ToHapiVmPreferenceMatcher(preference *kubevirtapiv1.PreferenceMatcher) *models.V1VMPreferenceMatcher { - if preference == nil { - return nil - } - return &models.V1VMPreferenceMatcher{ - InferFromVolume: preference.InferFromVolume, - Kind: preference.Kind, - } -} - -func ToHapiVmObjectMeta(meta metav1.ObjectMeta) *models.V1VMObjectMeta { - return &models.V1VMObjectMeta{ - Annotations: meta.Annotations, - //TODO: DeletionGracePeriodSeconds: GracePeriodSeconds, - Finalizers: meta.Finalizers, - GenerateName: meta.GenerateName, - Generation: meta.Generation, - Labels: meta.Labels, - ManagedFields: ToHapiVMManagedFields(meta.ManagedFields), - Name: meta.Name, - Namespace: meta.Namespace, - OwnerReferences: ToHapiVMOwnerReferences(meta.OwnerReferences), - ResourceVersion: meta.ResourceVersion, - UID: string(meta.UID), - } -} - -func ToHapiVMOwnerReferences(references []metav1.OwnerReference) []*models.V1VMOwnerReference { - var result []*models.V1VMOwnerReference - for _, reference := range references { - result = append(result, &models.V1VMOwnerReference{ - APIVersion: types.Ptr(reference.APIVersion), - Controller: *reference.Controller, - BlockOwnerDeletion: *reference.BlockOwnerDeletion, - Kind: types.Ptr(reference.Kind), - Name: types.Ptr(reference.Name), - UID: types.Ptr(string(reference.UID)), - }) - } - return result -} - -func ToHapiVMManagedFields(fields []metav1.ManagedFieldsEntry) []*models.V1VMManagedFieldsEntry { - var result []*models.V1VMManagedFieldsEntry - for _, field := range fields { - result = append(result, &models.V1VMManagedFieldsEntry{ - APIVersion: field.APIVersion, - FieldsType: field.FieldsType, - FieldsV1: ToHapiVmFieldsV1(field.FieldsV1), - Manager: field.Manager, - Operation: string(field.Operation), - // TODO: Time: field.Time, - Subresource: field.Subresource, - }) - } - return result -} - -func ToHapiVMPreferenceMatcher(preference *kubevirtapiv1.PreferenceMatcher) *models.V1VMPreferenceMatcher { - return &models.V1VMPreferenceMatcher{ - InferFromVolume: preference.InferFromVolume, - Kind: preference.Kind, - Name: preference.Name, - RevisionName: preference.RevisionName, - } -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_spec_network.go b/spectrocloud/convert/kubevirt_to_hapi_spec_network.go deleted file mode 100644 index 08a8a6ff..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_spec_network.go +++ /dev/null @@ -1,42 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - kubevirtapiv1 "kubevirt.io/api/core/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func ToHapiVmNetworks(networks []kubevirtapiv1.Network) []*models.V1VMNetwork { - var hapiNetworks []*models.V1VMNetwork - for _, network := range networks { - hapiNetworks = append(hapiNetworks, &models.V1VMNetwork{ - Multus: ToHapiVmMultus(network.Multus), - Name: types.Ptr(network.Name), - Pod: ToHapiVmPodNetwork(network.Pod), - }) - } - return hapiNetworks -} - -func ToHapiVmPodNetwork(pod *kubevirtapiv1.PodNetwork) *models.V1VMPodNetwork { - if pod == nil { - return nil - } - - return &models.V1VMPodNetwork{ - VMIPV6NetworkCIDR: pod.VMIPv6NetworkCIDR, - VMNetworkCIDR: pod.VMNetworkCIDR, - } -} - -func ToHapiVmMultus(multus *kubevirtapiv1.MultusNetwork) *models.V1VMMultusNetwork { - if multus == nil { - return nil - } - - return &models.V1VMMultusNetwork{ - Default: multus.Default, - NetworkName: types.Ptr(multus.NetworkName), - } -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_spec_probe.go b/spectrocloud/convert/kubevirt_to_hapi_spec_probe.go deleted file mode 100644 index 8eb337c7..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_spec_probe.go +++ /dev/null @@ -1,112 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/util/intstr" - kubevirtapiv1 "kubevirt.io/api/core/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func ToHapiVmProbe(probe *kubevirtapiv1.Probe) *models.V1VMProbe { - if probe == nil { - return nil - } - - return &models.V1VMProbe{ - Exec: ToHapiVmExecAction(probe.Exec), - FailureThreshold: probe.FailureThreshold, - GuestAgentPing: probe.GuestAgentPing, - HTTPGet: ToHapiVmHttpGetHandlerAction(probe.HTTPGet), - InitialDelaySeconds: probe.InitialDelaySeconds, - PeriodSeconds: probe.PeriodSeconds, - SuccessThreshold: probe.SuccessThreshold, - TCPSocket: ToHapiVmTcpSocketHandlerAction(probe.TCPSocket), - TimeoutSeconds: probe.TimeoutSeconds, - } -} - -func ToHapiVmTcpSocketHandlerAction(socket *v1.TCPSocketAction) *models.V1VMTCPSocketAction { - if socket == nil { - return nil - } - - return &models.V1VMTCPSocketAction{ - Host: socket.Host, - Port: ToHapiVmIntOrString(socket.Port), - } -} - -func ToHapiVmHttpGetHandlerAction(get *v1.HTTPGetAction) *models.V1VMHTTPGetAction { - if get == nil { - return nil - } - - return &models.V1VMHTTPGetAction{ - Host: get.Host, - Path: get.Path, - Port: ToHapiVmIntOrString(get.Port), - Scheme: string(get.Scheme), - HTTPHeaders: ToHapiVmHTTPHeaders(get.HTTPHeaders), - } -} - -func ToHapiVmHTTPHeaders(headers []v1.HTTPHeader) []*models.V1VMHTTPHeader { - var Headers []*models.V1VMHTTPHeader - for _, header := range headers { - Headers = append(Headers, &models.V1VMHTTPHeader{ - Name: types.Ptr(header.Name), - Value: types.Ptr(header.Value), - }) - } - return Headers -} - -func ToHapiVmIntOrString(port intstr.IntOrString) *string { - if port.Type == intstr.Int { - return types.Ptr(string(port.IntVal)) - } - return types.Ptr(port.StrVal) -} - -func ToHapiVmExecAction(exec *v1.ExecAction) *models.V1VMExecAction { - if exec == nil { - return nil - } - - return &models.V1VMExecAction{ - Command: exec.Command, - } -} - -func ToHapiVmTopologySpreadConstraints(constraints []v1.TopologySpreadConstraint) []*models.V1VMTopologySpreadConstraint { - var Constraints []*models.V1VMTopologySpreadConstraint - for _, constraint := range constraints { - Constraints = append(Constraints, &models.V1VMTopologySpreadConstraint{ - LabelSelector: ToHapiVmLabelSelector(constraint.LabelSelector), - MaxSkew: &constraint.MaxSkew, - TopologyKey: types.Ptr(constraint.TopologyKey), - WhenUnsatisfiable: types.Ptr(string(constraint.WhenUnsatisfiable)), - }) - } - return Constraints -} - -func ToHapiVmTolerations(tolerations []v1.Toleration) []*models.V1VMToleration { - var Tolerations []*models.V1VMToleration - for _, toleration := range tolerations { - var TolerationSeconds int64 - if toleration.TolerationSeconds != nil { - TolerationSeconds = *toleration.TolerationSeconds - } - Tolerations = append(Tolerations, &models.V1VMToleration{ - Effect: string(toleration.Effect), - Key: toleration.Key, - Operator: string(toleration.Operator), - TolerationSeconds: TolerationSeconds, - Value: toleration.Value, - }) - } - return Tolerations -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_status.go b/spectrocloud/convert/kubevirt_to_hapi_status.go index d91db258..6370f88a 100644 --- a/spectrocloud/convert/kubevirt_to_hapi_status.go +++ b/spectrocloud/convert/kubevirt_to_hapi_status.go @@ -6,8 +6,6 @@ import ( "github.com/spectrocloud/hapi/models" kubevirtapiv1 "kubevirt.io/api/core/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" ) func ToHapiVmStatusM(status kubevirtapiv1.VirtualMachineStatus) (*models.V1ClusterVirtualMachineStatus, error) { @@ -27,219 +25,3 @@ func ToHapiVmStatusM(status kubevirtapiv1.VirtualMachineStatus) (*models.V1Clust return &hapiVmStatus, nil } - -func ToHapiVmStatus(status kubevirtapiv1.VirtualMachineStatus) *models.V1ClusterVirtualMachineStatus { - var RestoreInProgress string - if status.RestoreInProgress != nil { - RestoreInProgress = *status.RestoreInProgress - } - - var SnapshotInProgress string - if status.SnapshotInProgress != nil { - SnapshotInProgress = *status.SnapshotInProgress - } - return &models.V1ClusterVirtualMachineStatus{ - Conditions: ToHapiVmStatusConditions(status.Conditions), - Created: status.Created, - MemoryDumpRequest: ToHapiVmStatusMemoryDumpRequest(status.MemoryDumpRequest), - PrintableStatus: string(status.PrintableStatus), - Ready: status.Ready, - RestoreInProgress: RestoreInProgress, - SnapshotInProgress: SnapshotInProgress, - StartFailure: ToHapiVmStatusStartFailure(status.StartFailure), - StateChangeRequests: ToHapiVmStatusStateChangeRequests(status.StateChangeRequests), - VolumeRequests: ToHapiVmStatusVolumeRequests(status.VolumeRequests), - VolumeSnapshotStatuses: ToHapiVmStatusVolumeSnapshotStatuses(status.VolumeSnapshotStatuses), - } -} - -func ToHapiVmStatusVolumeSnapshotStatuses(statuses []kubevirtapiv1.VolumeSnapshotStatus) []*models.V1VMVolumeSnapshotStatus { - var hapiStatuses []*models.V1VMVolumeSnapshotStatus - for _, status := range statuses { - hapiStatuses = append(hapiStatuses, ToHapiVmStatusVolumeSnapshotStatus(&status)) - } - return hapiStatuses -} - -func ToHapiVmStatusVolumeSnapshotStatus(k *kubevirtapiv1.VolumeSnapshotStatus) *models.V1VMVolumeSnapshotStatus { - if k == nil { - return nil - } - return &models.V1VMVolumeSnapshotStatus{ - Enabled: types.Ptr(k.Enabled), - Name: types.Ptr(k.Name), - Reason: k.Reason, - } -} - -func ToHapiVmStatusVolumeRequests(requests []kubevirtapiv1.VirtualMachineVolumeRequest) []*models.V1VMVirtualMachineVolumeRequest { - var hapiRequests []*models.V1VMVirtualMachineVolumeRequest - for _, request := range requests { - hapiRequests = append(hapiRequests, ToHapiVmStatusVolumeRequest(&request)) - } - return hapiRequests -} - -func ToHapiVmStatusVolumeRequest(k *kubevirtapiv1.VirtualMachineVolumeRequest) *models.V1VMVirtualMachineVolumeRequest { - if k == nil { - return nil - } - return &models.V1VMVirtualMachineVolumeRequest{ - AddVolumeOptions: ToHapiVmStatusAddVolumeOptions(k.AddVolumeOptions), - RemoveVolumeOptions: ToHapiVmStatusRemoveVolumeOptions(k.RemoveVolumeOptions), - } -} - -func ToHapiVmStatusRemoveVolumeOptions(options *kubevirtapiv1.RemoveVolumeOptions) *models.V1VMRemoveVolumeOptions { - if options == nil { - return nil - } - return &models.V1VMRemoveVolumeOptions{ - Name: types.Ptr(options.Name), - DryRun: options.DryRun, - } -} - -func ToHapiVmStatusAddVolumeOptions(options *kubevirtapiv1.AddVolumeOptions) *models.V1VMAddVolumeOptions { - if options == nil { - return nil - } - return &models.V1VMAddVolumeOptions{ - Disk: ToHapiVmStatusDisk(options.Disk), - DryRun: options.DryRun, - Name: types.Ptr(options.Name), - VolumeSource: ToHapiVmStatusVolumeSource(options.VolumeSource), - } -} - -func ToHapiVmStatusVolumeSource(source *kubevirtapiv1.HotplugVolumeSource) *models.V1VMHotplugVolumeSource { - if source == nil { - return nil - } - return &models.V1VMHotplugVolumeSource{ - DataVolume: ToHapiVmStatusDataVolume(source.DataVolume), - PersistentVolumeClaim: ToHapiVmStatusPersistentVolumeClaim(source.PersistentVolumeClaim), - } -} - -func ToHapiVmStatusPersistentVolumeClaim(claim *kubevirtapiv1.PersistentVolumeClaimVolumeSource) *models.V1VMPersistentVolumeClaimVolumeSource { - if claim == nil { - return nil - } - return &models.V1VMPersistentVolumeClaimVolumeSource{ - ClaimName: types.Ptr(claim.ClaimName), - Hotpluggable: claim.Hotpluggable, - ReadOnly: claim.ReadOnly, - } -} - -func ToHapiVmStatusDataVolume(volume *kubevirtapiv1.DataVolumeSource) *models.V1VMCoreDataVolumeSource { - if volume == nil { - return nil - } - return &models.V1VMCoreDataVolumeSource{ - Name: types.Ptr(volume.Name), - Hotpluggable: volume.Hotpluggable, - } -} - -func ToHapiVmStatusDisk(disk *kubevirtapiv1.Disk) *models.V1VMDisk { - if disk == nil { - return nil - } - - /*bootOrder := int32(1) // Default value. - if disk.BootOrder != nil { - bootOrder = int32(*disk.BootOrder) - }*/ - - DedicatedIOThread := false - if disk.DedicatedIOThread != nil { - DedicatedIOThread = *disk.DedicatedIOThread - } - - return &models.V1VMDisk{ - BlockSize: ToHapiVmBlockSize(disk.BlockSize), - // TODO : BootOrder: bootOrder, - Cache: string(disk.Cache), - Cdrom: ToHapiVmCdRom(disk.CDRom), - DedicatedIOThread: DedicatedIOThread, - Disk: ToHapiVmDiskTarget(disk.Disk), - Io: string(disk.IO), - Lun: ToHapiVmLunTarget(disk.LUN), - Name: types.Ptr(disk.Name), - Serial: disk.Serial, - Shareable: false, - Tag: disk.Tag, - } -} - -func ToHapiVmStatusStateChangeRequests(requests []kubevirtapiv1.VirtualMachineStateChangeRequest) []*models.V1VMVirtualMachineStateChangeRequest { - var hapiRequests []*models.V1VMVirtualMachineStateChangeRequest - for _, request := range requests { - hapiRequests = append(hapiRequests, ToHapiVmStatusStateChangeRequest(&request)) - } - return hapiRequests -} - -func ToHapiVmStatusStateChangeRequest(k *kubevirtapiv1.VirtualMachineStateChangeRequest) *models.V1VMVirtualMachineStateChangeRequest { - if k == nil { - return nil - } - - var uid string - if k.UID != nil { - uid = string(*k.UID) - } - return &models.V1VMVirtualMachineStateChangeRequest{ - Action: types.Ptr(string(k.Action)), - Data: k.Data, - UID: uid, - } -} - -func ToHapiVmStatusStartFailure(failure *kubevirtapiv1.VirtualMachineStartFailure) *models.V1VMVirtualMachineStartFailure { - if failure == nil { - return nil - } - return &models.V1VMVirtualMachineStartFailure{ - ConsecutiveFailCount: int32(failure.ConsecutiveFailCount), - LastFailedVMIUID: string(failure.LastFailedVMIUID), - // TODO: RetryAfterTimestamp: models.V1Time{}, - } -} - -func ToHapiVmStatusMemoryDumpRequest(request *kubevirtapiv1.VirtualMachineMemoryDumpRequest) *models.V1VMVirtualMachineMemoryDumpRequest { - if request == nil { - return nil - } - - var FileName string - if request.FileName != nil { - FileName = *request.FileName - } - return &models.V1VMVirtualMachineMemoryDumpRequest{ - ClaimName: types.Ptr(request.ClaimName), - // TODO: EndTimestamp: models.V1Time{}, - FileName: FileName, - Message: request.Message, - Phase: types.Ptr(string(request.Phase)), - Remove: request.Remove, - // TODO: StartTimestamp: models.V1Time{}, - } -} - -func ToHapiVmStatusConditions(conditions []kubevirtapiv1.VirtualMachineCondition) []*models.V1VMVirtualMachineCondition { - var hapiConditions []*models.V1VMVirtualMachineCondition - for _, condition := range conditions { - hapiConditions = append(hapiConditions, &models.V1VMVirtualMachineCondition{ - // TODO: LastProbeTime: condition.LastProbeTime, - // TODO: LastTransitionTime: condition.LastTransitionTime, - Message: condition.Message, - Reason: condition.Reason, - Status: types.Ptr(string(condition.Status)), - Type: types.Ptr(string(condition.Type)), - }) - } - return hapiConditions -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_volume.go b/spectrocloud/convert/kubevirt_to_hapi_volume.go deleted file mode 100644 index f7fb0939..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_volume.go +++ /dev/null @@ -1,134 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - "k8s.io/api/core/v1" - kubevirtapiv1 "kubevirt.io/api/core/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func ToHapiVmVolumes(volumes []kubevirtapiv1.Volume) []*models.V1VMVolume { - var Volumes []*models.V1VMVolume - for _, volume := range volumes { - Volumes = append(Volumes, ToHapiVmVolume(volume)) - } - return Volumes -} - -func ToHapiVmVolume(volume kubevirtapiv1.Volume) *models.V1VMVolume { - var DownwardMetrics map[string]interface{} - if volume.DownwardMetrics != nil { - DownwardMetrics = make(map[string]interface{}) - } - - return &models.V1VMVolume{ - CloudInitConfigDrive: ToHapiVmCloudInitConfigDrive(volume.CloudInitConfigDrive), - CloudInitNoCloud: ToHapiVmCloudInitNoCloud(volume.CloudInitNoCloud), - ConfigMap: ToHapiVmConfigMap(volume.ConfigMap), - ContainerDisk: ToHapiVmContainerDisk(volume.ContainerDisk), - DataVolume: ToHapiVmDataVolume(volume.DataVolume), - DownwardAPI: ToHapiVmDownwardAPI(volume.DownwardAPI), - DownwardMetrics: DownwardMetrics, - EmptyDisk: ToHapiVmEmptyDisk(volume.EmptyDisk), - Ephemeral: ToHapiVmEphemeral(volume.Ephemeral), - HostDisk: ToHapiVmHostDisk(volume.HostDisk), - MemoryDump: ToHapiVmMemoryDump(volume.MemoryDump), - Name: types.Ptr(volume.Name), - PersistentVolumeClaim: ToHapiVmPersistentVolumeClaimKubevirt(volume.PersistentVolumeClaim), - Secret: ToHapiVMSecret(volume.Secret), - ServiceAccount: ToHapiVMServiceAccount(volume.ServiceAccount), - Sysprep: ToHapiVMSysprep(volume.Sysprep), - } -} - -func ToHapiVMSysprep(sysprep *kubevirtapiv1.SysprepSource) *models.V1VMSysprepSource { - if sysprep == nil { - return nil - } - - return &models.V1VMSysprepSource{ - ConfigMap: ToHapiVmLocalObjectReference(sysprep.ConfigMap), - Secret: nil, - } -} - -func ToHapiVmLocalObjectReference(configMap *v1.LocalObjectReference) *models.V1VMLocalObjectReference { - if configMap == nil { - return nil - } - - return &models.V1VMLocalObjectReference{ - Name: configMap.Name, - } -} - -func ToHapiVmPersistentVolumeClaimKubevirt(claim *kubevirtapiv1.PersistentVolumeClaimVolumeSource) *models.V1VMPersistentVolumeClaimVolumeSource { - if claim == nil { - return nil - } - - return &models.V1VMPersistentVolumeClaimVolumeSource{ - ClaimName: types.Ptr(claim.ClaimName), - Hotpluggable: claim.Hotpluggable, - ReadOnly: claim.ReadOnly, - } -} - -func ToHapiVmMemoryDump(dump *kubevirtapiv1.MemoryDumpVolumeSource) *models.V1VMMemoryDumpVolumeSource { - if dump == nil { - return nil - } - - return &models.V1VMMemoryDumpVolumeSource{ - ClaimName: types.Ptr(dump.ClaimName), - Hotpluggable: dump.Hotpluggable, - ReadOnly: dump.ReadOnly, - } -} - -func ToHapiVMServiceAccount(account *kubevirtapiv1.ServiceAccountVolumeSource) *models.V1VMServiceAccountVolumeSource { - if account == nil { - return nil - } - - return &models.V1VMServiceAccountVolumeSource{ - ServiceAccountName: account.ServiceAccountName, - } -} - -func ToHapiVMPersistentVolumeClaimKubevirt(claim *kubevirtapiv1.PersistentVolumeClaimVolumeSource) *models.V1VMPersistentVolumeClaimVolumeSource { - if claim == nil { - return nil - } - - return &models.V1VMPersistentVolumeClaimVolumeSource{ - ClaimName: types.Ptr(claim.ClaimName), - Hotpluggable: claim.Hotpluggable, - ReadOnly: claim.ReadOnly, - } -} - -func ToHapiVMSecret(secret *kubevirtapiv1.SecretVolumeSource) *models.V1VMSecretVolumeSource { - if secret == nil { - return nil - } - - return &models.V1VMSecretVolumeSource{ - Optional: false, - SecretName: "", - VolumeLabel: "", - } -} - -func ToHapiVMMemoryDump(dump *kubevirtapiv1.MemoryDumpVolumeSource) *models.V1VMMemoryDumpVolumeSource { - if dump == nil { - return nil - } - - return &models.V1VMMemoryDumpVolumeSource{ - ClaimName: nil, - Hotpluggable: false, - ReadOnly: false, - } -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_volume_disk.go b/spectrocloud/convert/kubevirt_to_hapi_volume_disk.go deleted file mode 100644 index a5b56687..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_volume_disk.go +++ /dev/null @@ -1,59 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - kubevirtapiv1 "kubevirt.io/api/core/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func ToHapiVmCloudInitNoCloud(cloud *kubevirtapiv1.CloudInitNoCloudSource) *models.V1VMCloudInitNoCloudSource { - if cloud == nil { - return nil - } - - return &models.V1VMCloudInitNoCloudSource{ - NetworkData: "", - NetworkDataBase64: "", - NetworkDataSecretRef: nil, - SecretRef: nil, - UserData: "", - UserDataBase64: "", - } -} - -func ToHapiVmHostDisk(disk *kubevirtapiv1.HostDisk) *models.V1VMHostDisk { - if disk == nil { - return nil - } - - return &models.V1VMHostDisk{ - Capacity: ToHapiVmQuantityDivisor(disk.Capacity), - Path: types.Ptr(disk.Path), - Shared: *disk.Shared, - Type: types.Ptr(string(disk.Type)), - } -} - -func ToHapiVmEmptyDisk(disk *kubevirtapiv1.EmptyDiskSource) *models.V1VMEmptyDiskSource { - if disk == nil { - return nil - } - - return &models.V1VMEmptyDiskSource{ - Capacity: ToHapiVmQuantityDivisor(disk.Capacity), - } -} - -func ToHapiVmContainerDisk(disk *kubevirtapiv1.ContainerDiskSource) *models.V1VMContainerDiskSource { - if disk == nil { - return nil - } - - return &models.V1VMContainerDiskSource{ - Image: types.Ptr(disk.Image), - ImagePullPolicy: string(disk.ImagePullPolicy), - ImagePullSecret: disk.ImagePullSecret, - Path: disk.Path, - } -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_volume_downapi.go b/spectrocloud/convert/kubevirt_to_hapi_volume_downapi.go deleted file mode 100644 index 25f1d354..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_volume_downapi.go +++ /dev/null @@ -1,66 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - "k8s.io/api/core/v1" - kubevirtapiv1 "kubevirt.io/api/core/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func ToHapiVmDownwardAPI(api *kubevirtapiv1.DownwardAPIVolumeSource) *models.V1VMDownwardAPIVolumeSource { - if api == nil { - return nil - } - - return &models.V1VMDownwardAPIVolumeSource{ - Fields: ToHapiVmDownwardAPIVolumeFile(api.Fields), - VolumeLabel: api.VolumeLabel, - } -} - -func ToHapiVmDownwardAPIVolumeFile(fields []v1.DownwardAPIVolumeFile) []*models.V1VMDownwardAPIVolumeFile { - if fields == nil { - return nil - } - - var result []*models.V1VMDownwardAPIVolumeFile - for _, field := range fields { - result = append(result, ToHapiVmDownwardAPIVolumeFileItem(field)) - } - - return result -} - -func ToHapiVmDownwardAPIVolumeFileItem(field v1.DownwardAPIVolumeFile) *models.V1VMDownwardAPIVolumeFile { - return &models.V1VMDownwardAPIVolumeFile{ - Path: types.Ptr(field.Path), - FieldRef: ToHapiVmObjectFieldSelector(field.FieldRef), - ResourceFieldRef: ToHapiVmResourceFieldSelector( - field.ResourceFieldRef, - ), - Mode: *field.Mode, - } -} - -func ToHapiVmResourceFieldSelector(ref *v1.ResourceFieldSelector) *models.V1VMResourceFieldSelector { - if ref == nil { - return nil - } - - return &models.V1VMResourceFieldSelector{ - ContainerName: ref.ContainerName, - Resource: types.Ptr(ref.Resource), - Divisor: ToHapiVmQuantityDivisor(ref.Divisor), - } -} - -func ToHapiVmObjectFieldSelector(ref *v1.ObjectFieldSelector) *models.V1VMObjectFieldSelector { - if ref == nil { - return nil - } - - return &models.V1VMObjectFieldSelector{ - FieldPath: types.Ptr(ref.FieldPath), - } -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_volume_drive.go b/spectrocloud/convert/kubevirt_to_hapi_volume_drive.go deleted file mode 100644 index 2c0086d8..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_volume_drive.go +++ /dev/null @@ -1,43 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - "k8s.io/api/core/v1" - kubevirtapiv1 "kubevirt.io/api/core/v1" -) - -func ToHapiVmCloudInitConfigDrive(drive *kubevirtapiv1.CloudInitConfigDriveSource) *models.V1VMCloudInitConfigDriveSource { - if drive == nil { - return nil - } - - return &models.V1VMCloudInitConfigDriveSource{ - NetworkData: drive.NetworkData, - NetworkDataBase64: drive.NetworkDataBase64, - NetworkDataSecretRef: ToHapiVmObjectReference(drive.NetworkDataSecretRef), - SecretRef: ToHapiVmObjectReference(drive.UserDataSecretRef), - UserData: drive.UserData, - UserDataBase64: drive.UserDataBase64, - } -} - -func ToHapiVmSysprep(sysprep *kubevirtapiv1.SysprepSource) *models.V1VMSysprepSource { - if sysprep == nil { - return nil - } - - return &models.V1VMSysprepSource{ - ConfigMap: ToHapiVmObjectReference(sysprep.ConfigMap), - Secret: ToHapiVmObjectReference(sysprep.Secret), - } -} - -func ToHapiVmObjectReference(ref *v1.LocalObjectReference) *models.V1VMLocalObjectReference { - if ref == nil { - return nil - } - - return &models.V1VMLocalObjectReference{ - Name: ref.Name, - } -} diff --git a/spectrocloud/convert/kubevirt_to_hapi_volume_service.go b/spectrocloud/convert/kubevirt_to_hapi_volume_service.go deleted file mode 100644 index 233bcded..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_volume_service.go +++ /dev/null @@ -1 +0,0 @@ -package convert diff --git a/spectrocloud/convert/kubevirt_to_hapi_volume_volumetype.go b/spectrocloud/convert/kubevirt_to_hapi_volume_volumetype.go deleted file mode 100644 index f232763c..00000000 --- a/spectrocloud/convert/kubevirt_to_hapi_volume_volumetype.go +++ /dev/null @@ -1,54 +0,0 @@ -package convert - -import ( - "github.com/spectrocloud/hapi/models" - "k8s.io/api/core/v1" - kubevirtapiv1 "kubevirt.io/api/core/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/types" -) - -func ToHapiVmConfigMap(configMap *kubevirtapiv1.ConfigMapVolumeSource) *models.V1VMConfigMapVolumeSource { - if configMap == nil { - return nil - } - - return &models.V1VMConfigMapVolumeSource{ - Name: configMap.Name, - Optional: *configMap.Optional, - VolumeLabel: configMap.VolumeLabel, - } -} - -func ToHapiVmDataVolume(volume *kubevirtapiv1.DataVolumeSource) *models.V1VMCoreDataVolumeSource { - if volume == nil { - return nil - } - - return &models.V1VMCoreDataVolumeSource{ - Name: types.Ptr(volume.Name), - Hotpluggable: volume.Hotpluggable, - } -} - -func ToHapiVmEphemeral(ephemeral *kubevirtapiv1.EphemeralVolumeSource) *models.V1VMEphemeralVolumeSource { - if ephemeral == nil { - return nil - } - - return &models.V1VMEphemeralVolumeSource{ - PersistentVolumeClaim: ToHapiVmPersistentVolumeClaim(ephemeral.PersistentVolumeClaim), - } -} - -func ToHapiVmPersistentVolumeClaim(claim *v1.PersistentVolumeClaimVolumeSource) *models.V1VMPersistentVolumeClaimVolumeSource { - if claim == nil { - return nil - } - - return &models.V1VMPersistentVolumeClaimVolumeSource{ - ClaimName: types.Ptr(claim.ClaimName), - // TODO: Hotpluggable: claim.Hotpluggable, NO SUCH FIELD! - ReadOnly: claim.ReadOnly, - } -} diff --git a/spectrocloud/data_source_cluster_profile.go b/spectrocloud/data_source_cluster_profile.go index 54b66a7c..0a2dd8bc 100644 --- a/spectrocloud/data_source_cluster_profile.go +++ b/spectrocloud/data_source_cluster_profile.go @@ -48,10 +48,14 @@ func dataSourceClusterProfile() *schema.Resource { func dataSourceClusterProfileRead(_ context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { c := m.(*client.V1Client) + hashboardC, err := c.GetHashboardClient() + if err != nil { + return diag.FromErr(err) + } // Warning or errors can be collected in a slice type var diags diag.Diagnostics - profiles, err := c.GetClusterProfiles() + profiles, err := c.GetClusterProfiles(hashboardC) if err != nil { return diag.FromErr(err) } @@ -126,16 +130,21 @@ func GetDiagPacks(d *schema.ResourceData, err error) ([]*models.V1PackManifestEn } func getProfile(profiles []*models.V1ClusterProfileMetadata, d *schema.ResourceData, version string, ProfileContext string, c *client.V1Client) (*models.V1ClusterProfile, error) { + clusterC, err := c.GetClusterClient() + if err != nil { + return nil, err + } + for _, p := range profiles { if v, ok := d.GetOk("id"); ok && v.(string) == p.Metadata.UID { - fullProfile, err := c.GetClusterProfile(p.Metadata.UID) + fullProfile, err := c.GetClusterProfile(clusterC, p.Metadata.UID) if err != nil { return nil, err } return fullProfile, nil } else if v, ok := d.GetOk("name"); ok && v.(string) == p.Metadata.Name { if p.Spec.Version == version || (p.Spec.Version == "" && version == "1.0.0") { - fullProfile, err := c.GetClusterProfile(p.Metadata.UID) + fullProfile, err := c.GetClusterProfile(clusterC, p.Metadata.UID) if err != nil { return nil, err } diff --git a/spectrocloud/kubevirt/schema/datavolume/data_volume_test.go b/spectrocloud/kubevirt/schema/datavolume/data_volume_test.go index c23276e0..0d080738 100644 --- a/spectrocloud/kubevirt/schema/datavolume/data_volume_test.go +++ b/spectrocloud/kubevirt/schema/datavolume/data_volume_test.go @@ -3,6 +3,7 @@ package datavolume import ( "testing" + "github.com/google/go-cmp/cmp" "gotest.tools/assert" "github.com/spectrocloud/terraform-provider-spectrocloud/spectrocloud/kubevirt/test_utils/expand_utils" @@ -97,7 +98,10 @@ func TestFlattenDataVolumeTemplates(t *testing.T) { nullifyUncomparableFields(&output) nullifyUncomparableFields(&tc.ExpectedOutput) - assert.DeepEqual(t, output, tc.ExpectedOutput) + if diff := cmp.Diff(tc.ExpectedOutput, output); diff != "" { + t.Errorf("Unexpected result (-want +got):\n%s", diff) + } + //assert.DeepEqual(t, output, tc.ExpectedOutput) } } diff --git a/spectrocloud/kubevirt/schema/datavolume/source.go b/spectrocloud/kubevirt/schema/datavolume/source.go index 1742f5e6..a26587e6 100644 --- a/spectrocloud/kubevirt/schema/datavolume/source.go +++ b/spectrocloud/kubevirt/schema/datavolume/source.go @@ -1,8 +1,6 @@ package datavolume import ( - "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" ) @@ -32,7 +30,7 @@ func dataVolumeSourceSchema() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, - Description: fmt.Sprintf("Source is the src of the data for the requested DataVolume."), + Description: "Source is the src of the data for the requested DataVolume.", Optional: true, MaxItems: 1, Elem: &schema.Resource{ @@ -181,6 +179,9 @@ func expandDataVolumeSourcePVC(dataVolumeSourcePVC []interface{}) *cdiv1.DataVol func flattenDataVolumeSource(in *cdiv1.DataVolumeSource) []interface{} { att := make(map[string]interface{}) if in != nil { + if in.Blank != nil { + att["blank"] = flattenDataVolumeSourceBlank() + } if in.HTTP != nil { att["http"] = flattenDataVolumeSourceHTTP(*in.HTTP) } @@ -193,6 +194,11 @@ func flattenDataVolumeSource(in *cdiv1.DataVolumeSource) []interface{} { return []interface{}{} } +func flattenDataVolumeSourceBlank() []interface{} { + att := map[string]interface{}{} + return []interface{}{att} +} + func flattenDataVolumeSourceHTTP(in cdiv1.DataVolumeSourceHTTP) []interface{} { att := map[string]interface{}{ "url": in.URL, diff --git a/spectrocloud/kubevirt/schema/datavolume/spec.go b/spectrocloud/kubevirt/schema/datavolume/spec.go index b3ae3b0e..d17ce3f5 100644 --- a/spectrocloud/kubevirt/schema/datavolume/spec.go +++ b/spectrocloud/kubevirt/schema/datavolume/spec.go @@ -1,8 +1,6 @@ package datavolume import ( - "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" @@ -31,7 +29,7 @@ func DataVolumeSpecSchema() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, - Description: fmt.Sprintf("DataVolumeSpec defines our specification for a DataVolume type"), + Description: "DataVolumeSpec defines our specification for a DataVolume type", Required: true, MaxItems: 1, Elem: &schema.Resource{ diff --git a/spectrocloud/kubevirt/schema/datavolume/status.go b/spectrocloud/kubevirt/schema/datavolume/status.go index da7d51ab..76900bde 100644 --- a/spectrocloud/kubevirt/schema/datavolume/status.go +++ b/spectrocloud/kubevirt/schema/datavolume/status.go @@ -1,8 +1,6 @@ package datavolume import ( - "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" @@ -35,11 +33,11 @@ func dataVolumeStatusFields() map[string]*schema.Schema { }, false), }, "progress": { - Type: schema.TypeString, - Description: "DataVolumePhase is the current phase of the DataVolume.", - Optional: true, - Computed: true, - ValidateFunc: utils.StringIsIntInRange(0, 100), + Type: schema.TypeString, + Description: "DataVolumePhase is the current phase of the DataVolume.", + Optional: true, + Computed: true, + ValidateDiagFunc: utils.StringIsIntInRange(0, 100), }, } } @@ -49,7 +47,7 @@ func dataVolumeStatusSchema() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, - Description: fmt.Sprintf("DataVolumeStatus provides the parameters to store the phase of the Data Volume"), + Description: "DataVolumeStatus provides the parameters to store the phase of the Data Volume", Optional: true, MaxItems: 1, Computed: true, diff --git a/spectrocloud/kubevirt/schema/k8s/affinity_spec.go b/spectrocloud/kubevirt/schema/k8s/affinity_spec.go index 1e25b2e1..5fcdf33f 100644 --- a/spectrocloud/kubevirt/schema/k8s/affinity_spec.go +++ b/spectrocloud/kubevirt/schema/k8s/affinity_spec.go @@ -283,7 +283,7 @@ func flattenNodeSelector(in *v1.NodeSelector) []interface{} { } func flattenPreferredSchedulingTerm(in []v1.PreferredSchedulingTerm) []interface{} { - att := make([]interface{}, len(in), len(in)) + att := make([]interface{}, len(in)) for i, n := range in { m := make(map[string]interface{}) m["weight"] = int(n.Weight) @@ -294,7 +294,7 @@ func flattenPreferredSchedulingTerm(in []v1.PreferredSchedulingTerm) []interface } func flattenPodAffinityTerms(in []v1.PodAffinityTerm) []interface{} { - att := make([]interface{}, len(in), len(in)) + att := make([]interface{}, len(in)) for i, n := range in { m := make(map[string]interface{}) m["namespaces"] = utils.NewStringSet(schema.HashString, n.Namespaces) @@ -308,7 +308,7 @@ func flattenPodAffinityTerms(in []v1.PodAffinityTerm) []interface{} { } func flattenWeightedPodAffinityTerms(in []v1.WeightedPodAffinityTerm) []interface{} { - att := make([]interface{}, len(in), len(in)) + att := make([]interface{}, len(in)) for i, n := range in { m := make(map[string]interface{}) m["weight"] = int(n.Weight) @@ -319,7 +319,7 @@ func flattenWeightedPodAffinityTerms(in []v1.WeightedPodAffinityTerm) []interfac } func flattenNodeSelectorTerms(in []api.NodeSelectorTerm) []interface{} { - att := make([]interface{}, len(in), len(in)) + att := make([]interface{}, len(in)) for i, n := range in { att[i] = flattenNodeSelectorTerm(n)[0] } @@ -430,7 +430,7 @@ func expandPreferredSchedulingTerms(t []interface{}) []v1.PreferredSchedulingTer if len(t) == 0 || t[0] == nil { return []v1.PreferredSchedulingTerm{} } - obj := make([]v1.PreferredSchedulingTerm, len(t), len(t)) + obj := make([]v1.PreferredSchedulingTerm, len(t)) for i, n := range t { in := n.(map[string]interface{}) if v, ok := in["weight"].(int); ok { @@ -447,7 +447,7 @@ func expandPodAffinityTerms(t []interface{}) []v1.PodAffinityTerm { if len(t) == 0 || t[0] == nil { return []v1.PodAffinityTerm{} } - obj := make([]v1.PodAffinityTerm, len(t), len(t)) + obj := make([]v1.PodAffinityTerm, len(t)) for i, n := range t { in := n.(map[string]interface{}) if v, ok := in["label_selector"].([]interface{}); ok && len(v) > 0 { @@ -467,7 +467,7 @@ func expandWeightedPodAffinityTerms(t []interface{}) []v1.WeightedPodAffinityTer if len(t) == 0 || t[0] == nil { return []v1.WeightedPodAffinityTerm{} } - obj := make([]v1.WeightedPodAffinityTerm, len(t), len(t)) + obj := make([]v1.WeightedPodAffinityTerm, len(t)) for i, n := range t { in := n.(map[string]interface{}) if v, ok := in["weight"].(int); ok { @@ -484,7 +484,7 @@ func expandNodeSelectorTerms(l []interface{}) []api.NodeSelectorTerm { if len(l) == 0 || l[0] == nil { return []api.NodeSelectorTerm{} } - obj := make([]api.NodeSelectorTerm, len(l), len(l)) + obj := make([]api.NodeSelectorTerm, len(l)) for i, n := range l { obj[i] = *expandNodeSelectorTerm([]interface{}{n}) } diff --git a/spectrocloud/kubevirt/schema/k8s/label_selector.go b/spectrocloud/kubevirt/schema/k8s/label_selector.go index d80c6ebc..0f4de8b4 100644 --- a/spectrocloud/kubevirt/schema/k8s/label_selector.go +++ b/spectrocloud/kubevirt/schema/k8s/label_selector.go @@ -62,7 +62,7 @@ func flattenLabelSelector(in *metav1.LabelSelector) []interface{} { } func flattenLabelSelectorRequirement(in []metav1.LabelSelectorRequirement) []interface{} { - att := make([]interface{}, len(in), len(in)) + att := make([]interface{}, len(in)) for i, n := range in { m := make(map[string]interface{}) m["key"] = n.Key @@ -94,7 +94,7 @@ func expandLabelSelectorRequirement(l []interface{}) []metav1.LabelSelectorRequi if len(l) == 0 || l[0] == nil { return []metav1.LabelSelectorRequirement{} } - obj := make([]metav1.LabelSelectorRequirement, len(l), len(l)) + obj := make([]metav1.LabelSelectorRequirement, len(l)) for i, n := range l { in := n.(map[string]interface{}) obj[i] = metav1.LabelSelectorRequirement{ diff --git a/spectrocloud/kubevirt/schema/k8s/metadata.go b/spectrocloud/kubevirt/schema/k8s/metadata.go index 2d92bcff..7e71dda5 100644 --- a/spectrocloud/kubevirt/schema/k8s/metadata.go +++ b/spectrocloud/kubevirt/schema/k8s/metadata.go @@ -2,8 +2,6 @@ package k8s import ( "fmt" - "net/url" - "strings" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -62,33 +60,6 @@ func metadataFields(objectName string) map[string]*schema.Schema { } } -func metadataSchema(objectName string, generatableName bool) *schema.Schema { - fields := metadataFields(objectName) - - if generatableName { - fields["generate_name"] = &schema.Schema{ - Type: schema.TypeString, - Description: "Prefix, used by the server, to generate a unique name ONLY IF the `name` field has not been provided. This value will also be combined with a unique suffix. Read more: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#idempotency", - Optional: true, - ForceNew: true, - ValidateFunc: utils.ValidateGenerateName, - ConflictsWith: []string{"metadata.0.name"}, - } - fields["name"].ConflictsWith = []string{"metadata.0.generate_name"} - } - - return &schema.Schema{ - Type: schema.TypeList, - Description: fmt.Sprintf("Standard %s's metadata. More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata", objectName), - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: fields, - }, - } - -} - func NamespacedMetadataSchema(objectName string, generatableName bool) *schema.Schema { return namespacedMetadataSchemaIsTemplate(objectName, generatableName, false) } @@ -197,38 +168,3 @@ func AppendPatchOps(keyPrefix, pathPrefix string, resourceData *schema.ResourceD } return ops } - -func removeInternalKeys(m map[string]string, d map[string]interface{}) map[string]string { - for k := range m { - if isInternalKey(k) && !isKeyInMap(k, d) { - delete(m, k) - } - } - return m -} - -func isKeyInMap(key string, d map[string]interface{}) bool { - if d == nil { - return false - } - for k := range d { - if k == key { - return true - } - } - return false -} - -func isInternalKey(annotationKey string) bool { - u, err := url.Parse("//" + annotationKey) - if err == nil && strings.HasSuffix(u.Hostname(), "kubernetes.io") { - return true - } - - // Specific to DaemonSet annotations, generated & controlled by the server. - if strings.Contains(annotationKey, "deprecated.daemonset.template.generation") { - return true - } - - return false -} diff --git a/spectrocloud/kubevirt/schema/k8s/persistent_volume_claim.go b/spectrocloud/kubevirt/schema/k8s/persistent_volume_claim.go index 9f278e31..b4b7b8c6 100644 --- a/spectrocloud/kubevirt/schema/k8s/persistent_volume_claim.go +++ b/spectrocloud/kubevirt/schema/k8s/persistent_volume_claim.go @@ -189,7 +189,7 @@ func expandResourceRequirements(l []interface{}) (*v1.ResourceRequirements, erro } func expandPersistentVolumeAccessModes(s []interface{}) []api.PersistentVolumeAccessMode { - out := make([]api.PersistentVolumeAccessMode, len(s), len(s)) + out := make([]api.PersistentVolumeAccessMode, len(s)) for i, v := range s { out[i] = api.PersistentVolumeAccessMode(v.(string)) } @@ -197,7 +197,7 @@ func expandPersistentVolumeAccessModes(s []interface{}) []api.PersistentVolumeAc } func flattenPersistentVolumeAccessModes(in []api.PersistentVolumeAccessMode) *schema.Set { - var out = make([]interface{}, len(in), len(in)) + var out = make([]interface{}, len(in)) for i, v := range in { out[i] = string(v) } diff --git a/spectrocloud/kubevirt/schema/virtualmachine/virtual_machine.go b/spectrocloud/kubevirt/schema/virtualmachine/virtual_machine.go index 579bd4ec..5d92f3e3 100644 --- a/spectrocloud/kubevirt/schema/virtualmachine/virtual_machine.go +++ b/spectrocloud/kubevirt/schema/virtualmachine/virtual_machine.go @@ -7,8 +7,6 @@ import ( "github.com/spectrocloud/terraform-provider-spectrocloud/spectrocloud/kubevirt/schema/k8s" kubevirtapiv1 "kubevirt.io/api/core/v1" - - "github.com/spectrocloud/terraform-provider-spectrocloud/spectrocloud/kubevirt/utils/patch" ) func VirtualMachineFields() map[string]*schema.Schema { @@ -43,46 +41,6 @@ func VirtualMachineFields() map[string]*schema.Schema { } } -func ExpandVirtualMachine(virtualMachine []interface{}) (*kubevirtapiv1.VirtualMachine, error) { - result := &kubevirtapiv1.VirtualMachine{} - - if len(virtualMachine) == 0 || virtualMachine[0] == nil { - return result, nil - } - - in := virtualMachine[0].(map[string]interface{}) - - if v, ok := in["metadata"].([]interface{}); ok { - result.ObjectMeta = k8s.ExpandMetadata(v) - } - if v, ok := in["spec"].([]interface{}); ok { - spec, err := expandVirtualMachineSpec(v) - if err != nil { - return result, err - } - result.Spec = spec - } - if v, ok := in["status"].([]interface{}); ok { - status, err := expandVirtualMachineStatus(v) - if err != nil { - return result, err - } - result.Status = status - } - - return result, nil -} - -func FlattenVirtualMachine(in kubevirtapiv1.VirtualMachine) []interface{} { - att := make(map[string]interface{}) - - att["metadata"] = k8s.FlattenMetadata(in.ObjectMeta) - att["spec"] = flattenVirtualMachineSpec(in.Spec) - att["status"] = flattenVirtualMachineStatus(in.Status) - - return []interface{}{att} -} - func FromResourceData(resourceData *schema.ResourceData) (*kubevirtapiv1.VirtualMachine, error) { result := &kubevirtapiv1.VirtualMachine{} @@ -114,7 +72,3 @@ func ToResourceData(vm kubevirtapiv1.VirtualMachine, resourceData *schema.Resour return nil } - -func AppendPatchOps(keyPrefix, pathPrefix string, resourceData *schema.ResourceData, ops []patch.PatchOperation) patch.PatchOperations { - return k8s.AppendPatchOps(keyPrefix+"metadata.0.", pathPrefix+"/metadata/", resourceData, ops) -} diff --git a/spectrocloud/kubevirt/schema/virtualmachineinstance/domain_spec.go b/spectrocloud/kubevirt/schema/virtualmachineinstance/domain_spec.go index 65207cd7..9aa4189a 100644 --- a/spectrocloud/kubevirt/schema/virtualmachineinstance/domain_spec.go +++ b/spectrocloud/kubevirt/schema/virtualmachineinstance/domain_spec.go @@ -1,8 +1,6 @@ package virtualmachineinstance import ( - "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" kubevirtapiv1 "kubevirt.io/api/core/v1" @@ -147,7 +145,7 @@ func domainSpecSchema() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, - Description: fmt.Sprintf("Specification of the desired behavior of the VirtualMachineInstance on the host."), + Description: "Specification of the desired behavior of the VirtualMachineInstance on the host.", Optional: true, MaxItems: 1, Elem: &schema.Resource{ diff --git a/spectrocloud/kubevirt/schema/virtualmachineinstance/networks.go b/spectrocloud/kubevirt/schema/virtualmachineinstance/networks.go index 17068727..191e9c86 100644 --- a/spectrocloud/kubevirt/schema/virtualmachineinstance/networks.go +++ b/spectrocloud/kubevirt/schema/virtualmachineinstance/networks.go @@ -1,8 +1,6 @@ package virtualmachineinstance import ( - "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" kubevirtapiv1 "kubevirt.io/api/core/v1" ) @@ -68,7 +66,7 @@ func networksSchema() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, - Description: fmt.Sprintf("List of networks that can be attached to a vm's virtual interface."), + Description: "List of networks that can be attached to a vm's virtual interface.", Optional: true, Elem: &schema.Resource{ Schema: fields, diff --git a/spectrocloud/kubevirt/schema/virtualmachineinstance/probe.go b/spectrocloud/kubevirt/schema/virtualmachineinstance/probe.go index e178fd56..b7682766 100644 --- a/spectrocloud/kubevirt/schema/virtualmachineinstance/probe.go +++ b/spectrocloud/kubevirt/schema/virtualmachineinstance/probe.go @@ -1,8 +1,6 @@ package virtualmachineinstance import ( - "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" kubevirtapiv1 "kubevirt.io/api/core/v1" ) @@ -19,7 +17,7 @@ func probeSchema() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, - Description: fmt.Sprintf("Specification of the desired behavior of the VirtualMachineInstance on the host."), + Description: "Specification of the desired behavior of the VirtualMachineInstance on the host.", Optional: true, MaxItems: 1, Elem: &schema.Resource{ diff --git a/spectrocloud/kubevirt/schema/virtualmachineinstance/spec.go b/spectrocloud/kubevirt/schema/virtualmachineinstance/spec.go index d863bfff..22209f3d 100644 --- a/spectrocloud/kubevirt/schema/virtualmachineinstance/spec.go +++ b/spectrocloud/kubevirt/schema/virtualmachineinstance/spec.go @@ -1,8 +1,6 @@ package virtualmachineinstance import ( - "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" k8sv1 "k8s.io/api/core/v1" @@ -82,7 +80,7 @@ func virtualMachineInstanceSpecSchema() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, - Description: fmt.Sprintf("Template is the direct specification of VirtualMachineInstance."), + Description: "Template is the direct specification of VirtualMachineInstance.", Optional: true, MaxItems: 1, Elem: &schema.Resource{ diff --git a/spectrocloud/kubevirt/schema/virtualmachineinstance/template_spec.go b/spectrocloud/kubevirt/schema/virtualmachineinstance/template_spec.go index 0ec694d5..98eb46dd 100644 --- a/spectrocloud/kubevirt/schema/virtualmachineinstance/template_spec.go +++ b/spectrocloud/kubevirt/schema/virtualmachineinstance/template_spec.go @@ -1,8 +1,6 @@ package virtualmachineinstance import ( - "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" kubevirtapiv1 "kubevirt.io/api/core/v1" @@ -22,7 +20,7 @@ func VirtualMachineInstanceTemplateSpecSchema() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, - Description: fmt.Sprintf("Template is the direct specification of VirtualMachineInstance."), + Description: "Template is the direct specification of VirtualMachineInstance.", Optional: true, MaxItems: 1, Elem: &schema.Resource{ diff --git a/spectrocloud/kubevirt/schema/virtualmachineinstance/volumes.go b/spectrocloud/kubevirt/schema/virtualmachineinstance/volumes.go index 01bd0dd3..d47c8397 100644 --- a/spectrocloud/kubevirt/schema/virtualmachineinstance/volumes.go +++ b/spectrocloud/kubevirt/schema/virtualmachineinstance/volumes.go @@ -1,8 +1,6 @@ package virtualmachineinstance import ( - "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" @@ -241,7 +239,7 @@ func volumesSchema() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, - Description: fmt.Sprintf("Specification of the desired behavior of the VirtualMachineInstance on the host."), + Description: "Specification of the desired behavior of the VirtualMachineInstance on the host.", Optional: true, Elem: &schema.Resource{ Schema: fields, @@ -569,9 +567,9 @@ func flattenVolumeSource(in kubevirtapiv1.VolumeSource) []interface{} { if in.HostDisk != nil { att["host_disk"] = flattenHostDisk(*in.HostDisk) } - if in.PersistentVolumeClaim != nil { - //att["persistent_volume_claim"] = flattenPersistentVolumeClaim(in.PersistentVolumeClaim) - } + /*if in.PersistentVolumeClaim != nil { + att["persistent_volume_claim"] = flattenPersistentVolumeClaim(in.PersistentVolumeClaim) + }*/ if in.ConfigMap != nil { att["config_map"] = flattenConfigMap(*in.ConfigMap) } @@ -663,14 +661,6 @@ func flattenHostDisk(in kubevirtapiv1.HostDisk) []interface{} { return []interface{}{att} } -func flattenPVC(in kubevirtapiv1.PersistentVolumeClaimVolumeSource) []interface{} { - att := make(map[string]interface{}) - - att["claim_name"] = in.ClaimName - - return []interface{}{att} -} - func flattenConfigMap(in kubevirtapiv1.ConfigMapVolumeSource) []interface{} { att := make(map[string]interface{}) diff --git a/spectrocloud/kubevirt/test_utils/flatten_utils/flatten_utils.go b/spectrocloud/kubevirt/test_utils/flatten_utils/flatten_utils.go index 4cc19fdc..9a8bb5ab 100644 --- a/spectrocloud/kubevirt/test_utils/flatten_utils/flatten_utils.go +++ b/spectrocloud/kubevirt/test_utils/flatten_utils/flatten_utils.go @@ -18,6 +18,7 @@ import ( func getDataVolumeSpec() cdiv1.DataVolumeSpec { return cdiv1.DataVolumeSpec{ Source: &cdiv1.DataVolumeSource{ + Blank: &cdiv1.DataVolumeBlankImage{}, HTTP: &cdiv1.DataVolumeSourceHTTP{ URL: "https://cloud.centos.org/centos/7/images/CentOS-7-x86_64-GenericCloud.qcow2", SecretRef: "secret_ref", @@ -341,6 +342,9 @@ func GetBaseOutputForVirtualMachine() interface{} { }, "source": []interface{}{ map[string]interface{}{ + "blank": []interface{}{ + map[string]interface{}{}, + }, "http": []interface{}{ map[string]interface{}{ "url": "https://cloud.centos.org/centos/7/images/CentOS-7-x86_64-GenericCloud.qcow2", diff --git a/spectrocloud/kubevirt/utils/patch/patch_operations.go b/spectrocloud/kubevirt/utils/patch/patch_operations.go index 003c1902..5b44b8a8 100644 --- a/spectrocloud/kubevirt/utils/patch/patch_operations.go +++ b/spectrocloud/kubevirt/utils/patch/patch_operations.go @@ -8,7 +8,7 @@ import ( ) func DiffStringMap(pathPrefix string, oldV, newV map[string]interface{}) PatchOperations { - ops := make([]PatchOperation, 0, 0) + ops := make([]PatchOperation, 0) pathPrefix = strings.TrimRight(pathPrefix, "/") diff --git a/spectrocloud/kubevirt/utils/structures.go b/spectrocloud/kubevirt/utils/structures.go index 0d17b01d..c70fdcd6 100644 --- a/spectrocloud/kubevirt/utils/structures.go +++ b/spectrocloud/kubevirt/utils/structures.go @@ -64,7 +64,7 @@ func ExpandStringMapToByteMap(m map[string]interface{}) map[string][]byte { } func ExpandStringSlice(s []interface{}) []string { - result := make([]string, len(s), len(s)) + result := make([]string, len(s)) for k, v := range s { // Handle the Terraform parser bug which turns empty strings in lists to nil. if v == nil { @@ -109,7 +109,7 @@ func PtrToInt64(i int64) *int64 { } func SliceOfString(slice []interface{}) []string { - result := make([]string, len(slice), len(slice)) + result := make([]string, len(slice)) for i, s := range slice { result[i] = s.(string) } @@ -126,7 +126,7 @@ func Base64EncodeStringMap(m map[string]interface{}) map[string]interface{} { } func NewStringSet(f schema.SchemaSetFunc, in []string) *schema.Set { - var out = make([]interface{}, len(in), len(in)) + var out = make([]interface{}, len(in)) for i, v := range in { out[i] = v } @@ -134,7 +134,7 @@ func NewStringSet(f schema.SchemaSetFunc, in []string) *schema.Set { } func NewInt64Set(f schema.SchemaSetFunc, in []int64) *schema.Set { - var out = make([]interface{}, len(in), len(in)) + var out = make([]interface{}, len(in)) for i, v := range in { out[i] = int(v) } diff --git a/spectrocloud/kubevirt/utils/utils.go b/spectrocloud/kubevirt/utils/utils.go deleted file mode 100644 index ff83a1e5..00000000 --- a/spectrocloud/kubevirt/utils/utils.go +++ /dev/null @@ -1,9 +0,0 @@ -package utils - -func ConvertMap(src map[string]interface{}) map[string]string { - result := map[string]string{} - for k, v := range src { - result[k] = v.(string) - } - return result -} diff --git a/spectrocloud/kubevirt/utils/validators.go b/spectrocloud/kubevirt/utils/validators.go index 897bf547..d389560b 100644 --- a/spectrocloud/kubevirt/utils/validators.go +++ b/spectrocloud/kubevirt/utils/validators.go @@ -1,13 +1,13 @@ package utils import ( - "encoding/base64" "fmt" "strconv" "strings" + "github.com/hashicorp/go-cty/cty" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "k8s.io/apimachinery/pkg/api/resource" apiValidation "k8s.io/apimachinery/pkg/api/validation" utilValidation "k8s.io/apimachinery/pkg/util/validation" ) @@ -25,38 +25,6 @@ func ValidateAnnotations(value interface{}, key string) (ws []string, es []error return } -func validateBase64Encoded(v interface{}, key string) (ws []string, es []error) { - s, ok := v.(string) - if !ok { - es = []error{fmt.Errorf("%s: must be a non-nil base64-encoded string", key)} - return - } - - _, err := base64.StdEncoding.DecodeString(s) - if err != nil { - es = []error{fmt.Errorf("%s: must be a base64-encoded string", key)} - return - } - return -} - -func validateBase64EncodedMap(value interface{}, key string) (ws []string, es []error) { - m, ok := value.(map[string]interface{}) - if !ok { - es = []error{fmt.Errorf("%s: must be a map of strings to base64 encoded strings", key)} - return - } - - for k, v := range m { - _, errs := validateBase64Encoded(v, k) - for _, e := range errs { - es = append(es, fmt.Errorf("%s (%q) %s", k, v, e)) - } - } - - return -} - func ValidateName(value interface{}, key string) (ws []string, es []error) { v := value.(string) errors := apiValidation.NameIsDNSSubdomain(v, false) @@ -98,107 +66,6 @@ func ValidateLabels(value interface{}, key string) (ws []string, es []error) { return } -func validatePortNum(value interface{}, key string) (ws []string, es []error) { - errors := utilValidation.IsValidPortNum(value.(int)) - if len(errors) > 0 { - for _, err := range errors { - es = append(es, fmt.Errorf("%s %s", key, err)) - } - } - return -} - -func validatePortName(value interface{}, key string) (ws []string, es []error) { - errors := utilValidation.IsValidPortName(value.(string)) - if len(errors) > 0 { - for _, err := range errors { - es = append(es, fmt.Errorf("%s %s", key, err)) - } - } - return -} -func validatePortNumOrName(value interface{}, key string) (ws []string, es []error) { - switch value.(type) { - case string: - intVal, err := strconv.Atoi(value.(string)) - if err != nil { - return validatePortName(value, key) - } - return validatePortNum(intVal, key) - case int: - return validatePortNum(value, key) - - default: - es = append(es, fmt.Errorf("%s must be defined of type string or int on the schema", key)) - return - } -} - -func validateResourceList(value interface{}, key string) (ws []string, es []error) { - m := value.(map[string]interface{}) - for k, value := range m { - if _, ok := value.(int); ok { - continue - } - - if v, ok := value.(string); ok { - _, err := resource.ParseQuantity(v) - if err != nil { - es = append(es, fmt.Errorf("%s.%s (%q): %s", key, k, v, err)) - } - continue - } - - err := "Value can be either string or int" - es = append(es, fmt.Errorf("%s.%s (%#v): %s", key, k, value, err)) - } - return -} - -func validateResourceQuantity(value interface{}, key string) (ws []string, es []error) { - if v, ok := value.(string); ok { - _, err := resource.ParseQuantity(v) - if err != nil { - es = append(es, fmt.Errorf("%s.%s : %s", key, v, err)) - } - } - return -} - -func validateNonNegativeInteger(value interface{}, key string) (ws []string, es []error) { - v := value.(int) - if v < 0 { - es = append(es, fmt.Errorf("%s must be greater than or equal to 0", key)) - } - return -} - -func validatePositiveInteger(value interface{}, key string) (ws []string, es []error) { - v := value.(int) - if v <= 0 { - es = append(es, fmt.Errorf("%s must be greater than 0", key)) - } - return -} - -func validateTerminationGracePeriodSeconds(value interface{}, key string) (ws []string, es []error) { - v := value.(int) - if v < 0 { - es = append(es, fmt.Errorf("%s must be greater than or equal to 0", key)) - } - return -} - -func validateIntGreaterThan(minValue int) func(value interface{}, key string) (ws []string, es []error) { - return func(value interface{}, key string) (ws []string, es []error) { - v := value.(int) - if v < minValue { - es = append(es, fmt.Errorf("%s must be greater than or equal to %d", key, minValue)) - } - return - } -} - // validateTypeStringNullableInt provides custom error messaging for TypeString ints // Some arguments require an int value or unspecified, empty field. func ValidateTypeStringNullableInt(v interface{}, k string) (ws []string, es []error) { @@ -219,94 +86,36 @@ func ValidateTypeStringNullableInt(v interface{}, k string) (ws []string, es []e return } -func validateModeBits(value interface{}, key string) (ws []string, es []error) { - if !strings.HasPrefix(value.(string), "0") { - es = append(es, fmt.Errorf("%s: value %s should start with '0' (octal numeral)", key, value.(string))) - } - v, err := strconv.ParseInt(value.(string), 8, 32) - if err != nil { - es = append(es, fmt.Errorf("%s :Cannot parse octal numeral (%#v): %s", key, value, err)) - } - if v < 0 || v > 0777 { - es = append(es, fmt.Errorf("%s (%#o) expects octal notation (a value between 0 and 0777)", key, v)) - } - return -} - -func validateAttributeValueDoesNotContain(searchString string) schema.SchemaValidateFunc { - return func(v interface{}, k string) (ws []string, errors []error) { - input := v.(string) - if strings.Contains(input, searchString) { - errors = append(errors, fmt.Errorf( - "%q must not contain %q", - k, searchString)) - } - return - } -} - -func validateAttributeValueIsIn(validValues []string) schema.SchemaValidateFunc { - return func(v interface{}, k string) (ws []string, errors []error) { - input := v.(string) - isValid := false - for _, s := range validValues { - if s == input { - isValid = true - break - } - } - if !isValid { - errors = append(errors, fmt.Errorf( - "%q must contain a value from %#v, got %q", - k, validValues, input)) - } - return - - } -} - -func validateTypeStringNullableIntOrPercent(v interface{}, key string) (ws []string, es []error) { - value, ok := v.(string) - if !ok { - es = append(es, fmt.Errorf("expected type of %s to be string", key)) - return - } - - if value == "" { - return - } - - if strings.HasSuffix(value, "%") { - percent, err := strconv.ParseInt(strings.TrimSuffix(value, "%"), 10, 32) - if err != nil { - es = append(es, fmt.Errorf("%s: cannot parse '%s' as percent: %s", key, value, err)) - } - if percent < 0 || percent >= 100 { - es = append(es, fmt.Errorf("%s: '%s' is not between 0%% and 100%%", key, value)) - } - } else if _, err := strconv.ParseInt(value, 10, 32); err != nil { - es = append(es, fmt.Errorf("%s: cannot parse '%s' as int or percent: %s", key, value, err)) - } - - return -} +func StringIsIntInRange(min int, max int) schema.SchemaValidateDiagFunc { + return func(i interface{}, p cty.Path) diag.Diagnostics { + var diags diag.Diagnostics -func StringIsIntInRange(min int, max int) schema.SchemaValidateFunc { - return func(i interface{}, k string) (warnings []string, errors []error) { stringVal, ok := i.(string) if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) - return warnings, errors + diags = append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: fmt.Sprintf("Expected type of %s to be string", p), + }) + return diags } + intVal, err := strconv.Atoi(stringVal) if err != nil { - errors = append(errors, fmt.Errorf("expected %s to string representation of integer", k)) - return warnings, errors + diags = append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: fmt.Sprintf("Expected %s to be string representation of integer", p), + }) + return diags } + if intVal < min || intVal > max { - errors = append(errors, fmt.Errorf("expected %s to be between %d and %d inclusive", k, min, max)) - return warnings, errors + diags = append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: fmt.Sprintf("Expected %s to be between %d and %d inclusive", p, min, max), + }) + return diags } - return warnings, errors + + return diags } } diff --git a/spectrocloud/resource_application.go b/spectrocloud/resource_application.go index 8c6d7b40..fbd56d82 100644 --- a/spectrocloud/resource_application.go +++ b/spectrocloud/resource_application.go @@ -182,6 +182,10 @@ func resourceApplicationUpdate(ctx context.Context, d *schema.ResourceData, m in if d.HasChanges("cluster_uid", "cluster_profile") { c := m.(*client.V1Client) + clusterC, err := c.GetClusterClient() + if err != nil { + return diag.FromErr(err) + } clusterUid := d.Get("cluster_uid").(string) @@ -192,16 +196,16 @@ func resourceApplicationUpdate(ctx context.Context, d *schema.ResourceData, m in addonDeployment := toAddonDeployment(c, d) - newProfile, err := c.GetClusterProfile(addonDeployment.Profiles[0].UID) + newProfile, err := c.GetClusterProfile(clusterC, addonDeployment.Profiles[0].UID) if err != nil { return diag.FromErr(err) } - err = c.UpdateAddonDeployment(cluster, addonDeployment, newProfile) + err = c.UpdateAddonDeployment(clusterC, cluster, addonDeployment, newProfile) if err != nil { return diag.FromErr(err) } - clusterProfile, err := c.GetClusterProfile(addonDeployment.Profiles[0].UID) + clusterProfile, err := c.GetClusterProfile(clusterC, addonDeployment.Profiles[0].UID) if err != nil { return diag.FromErr(err) } diff --git a/spectrocloud/resource_cluster_attachment.go b/spectrocloud/resource_cluster_attachment.go index bb366fc6..87724484 100644 --- a/spectrocloud/resource_cluster_attachment.go +++ b/spectrocloud/resource_cluster_attachment.go @@ -45,6 +45,11 @@ func resourceAddonDeployment() *schema.Resource { func resourceAddonDeploymentCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { c := m.(*client.V1Client) + clusterC, err := c.GetClusterClient() + if err != nil { + return diag.FromErr(err) + } + // Warning or errors can be collected in a slice type var diags diag.Diagnostics @@ -67,12 +72,12 @@ func resourceAddonDeploymentCreate(ctx context.Context, d *schema.ResourceData, //return diag.FromErr(errors.New(fmt.Sprintf("Cluster: %s: Profile is already attached: %s", cluster.Metadata.UID, addonDeployment.Profiles[0].UID))) } - err = c.CreateAddonDeployment(cluster.Metadata.UID, addonDeployment) + err = c.CreateAddonDeployment(clusterC, cluster.Metadata.UID, addonDeployment) if err != nil { return diag.FromErr(err) } - clusterProfile, err := c.GetClusterProfile(addonDeployment.Profiles[0].UID) + clusterProfile, err := c.GetClusterProfile(clusterC, addonDeployment.Profiles[0].UID) if err != nil { return diag.FromErr(err) } @@ -155,18 +160,23 @@ func resourceAddonDeploymentUpdate(ctx context.Context, d *schema.ResourceData, } func updateAddonDeployment(ctx context.Context, d *schema.ResourceData, m interface{}, c *client.V1Client, cluster *models.V1SpectroCluster, clusterUid string, diags diag.Diagnostics) diag.Diagnostics { + clusterC, err := c.GetClusterClient() + if err != nil { + return diag.FromErr(err) + } + addonDeployment := toAddonDeployment(c, d) - newProfile, err := c.GetClusterProfile(addonDeployment.Profiles[0].UID) + newProfile, err := c.GetClusterProfile(clusterC, addonDeployment.Profiles[0].UID) if err != nil { return diag.FromErr(err) } - err = c.UpdateAddonDeployment(cluster, addonDeployment, newProfile) + err = c.UpdateAddonDeployment(clusterC, cluster, addonDeployment, newProfile) if err != nil { return diag.FromErr(err) } - clusterProfile, err := c.GetClusterProfile(addonDeployment.Profiles[0].UID) + clusterProfile, err := c.GetClusterProfile(clusterC, addonDeployment.Profiles[0].UID) if err != nil { return diag.FromErr(err) } diff --git a/spectrocloud/resource_cluster_profile.go b/spectrocloud/resource_cluster_profile.go index 0fa16a5e..4475d788 100644 --- a/spectrocloud/resource_cluster_profile.go +++ b/spectrocloud/resource_cluster_profile.go @@ -81,6 +81,10 @@ func resourceClusterProfile() *schema.Resource { func resourceClusterProfileCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { c := m.(*client.V1Client) + clusterC, err := c.GetClusterClient() + if err != nil { + return diag.FromErr(err) + } // Warning or errors can be collected in a slice type var diags diag.Diagnostics @@ -92,13 +96,13 @@ func resourceClusterProfileCreate(ctx context.Context, d *schema.ResourceData, m // Create ProfileContext := d.Get("context").(string) - uid, err := c.CreateClusterProfile(clusterProfile, ProfileContext) + uid, err := c.CreateClusterProfile(clusterC, clusterProfile, ProfileContext) if err != nil { return diag.FromErr(err) } // And then publish - if err = c.PublishClusterProfile(uid, ProfileContext); err != nil { + if err = c.PublishClusterProfile(clusterC, uid, ProfileContext); err != nil { return diag.FromErr(err) } d.SetId(uid) @@ -108,10 +112,14 @@ func resourceClusterProfileCreate(ctx context.Context, d *schema.ResourceData, m func resourceClusterProfileRead(_ context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { c := m.(*client.V1Client) + clusterC, err := c.GetClusterClient() + if err != nil { + return diag.FromErr(err) + } var diags diag.Diagnostics - cp, err := c.GetClusterProfile(d.Id()) + cp, err := c.GetClusterProfile(clusterC, d.Id()) if err != nil { return diag.FromErr(err) } else if cp == nil { @@ -154,13 +162,17 @@ func resourceClusterProfileRead(_ context.Context, d *schema.ResourceData, m int func resourceClusterProfileUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { c := m.(*client.V1Client) + clusterC, err := c.GetClusterClient() + if err != nil { + return diag.FromErr(err) + } // Warning or errors can be collected in a slice type var diags diag.Diagnostics if d.HasChanges("name") || d.HasChanges("tags") || d.HasChanges("pack") { log.Printf("Updating packs") - cp, err := c.GetClusterProfile(d.Id()) + cp, err := c.GetClusterProfile(clusterC, d.Id()) if err != nil { return diag.FromErr(err) } @@ -174,13 +186,13 @@ func resourceClusterProfileUpdate(ctx context.Context, d *schema.ResourceData, m } ProfileContext := d.Get("context").(string) - if err := c.UpdateClusterProfile(cluster, ProfileContext); err != nil { + if err := c.UpdateClusterProfile(clusterC, cluster, ProfileContext); err != nil { return diag.FromErr(err) } - if err := c.PatchClusterProfile(cluster, metadata, ProfileContext); err != nil { + if err := c.PatchClusterProfile(clusterC, cluster, metadata, ProfileContext); err != nil { return diag.FromErr(err) } - if err := c.PublishClusterProfile(cluster.Metadata.UID, ProfileContext); err != nil { + if err := c.PublishClusterProfile(clusterC, cluster.Metadata.UID, ProfileContext); err != nil { return diag.FromErr(err) } } @@ -192,11 +204,14 @@ func resourceClusterProfileUpdate(ctx context.Context, d *schema.ResourceData, m func resourceClusterProfileDelete(_ context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { c := m.(*client.V1Client) + clusterC, err := c.GetClusterClient() + if err != nil { + return diag.FromErr(err) + } var diags diag.Diagnostics - err := c.DeleteClusterProfile(d.Id()) - if err != nil { + if err := c.DeleteClusterProfile(clusterC, d.Id()); err != nil { return diag.FromErr(err) } diff --git a/spectrocloud/resource_cluster_profile_import.go b/spectrocloud/resource_cluster_profile_import.go index 75ba3ff6..0f08fff0 100644 --- a/spectrocloud/resource_cluster_profile_import.go +++ b/spectrocloud/resource_cluster_profile_import.go @@ -87,6 +87,10 @@ func resourceClusterProfileImportRead(ctx context.Context, d *schema.ResourceDat func resourceClusterProfileImportUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { c := m.(*client.V1Client) + clusterC, err := c.GetClusterClient() + if err != nil { + return diag.FromErr(err) + } importFile, err := toClusterProfileImportCreate(d) if err != nil { @@ -94,7 +98,7 @@ func resourceClusterProfileImportUpdate(ctx context.Context, d *schema.ResourceD } // Call the API endpoint to delete the cluster profile import resource - err = c.DeleteClusterProfile(d.Id()) + err = c.DeleteClusterProfile(clusterC, d.Id()) if err != nil { // Return an error if the API call fails return diag.FromErr(err) @@ -113,10 +117,13 @@ func resourceClusterProfileImportUpdate(ctx context.Context, d *schema.ResourceD func resourceClusterProfileImportDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { c := m.(*client.V1Client) + clusterC, err := c.GetClusterClient() + if err != nil { + return diag.FromErr(err) + } // Call the API endpoint to delete the cluster profile import resource - err := c.DeleteClusterProfile(d.Id()) - if err != nil { + if err := c.DeleteClusterProfile(clusterC, d.Id()); err != nil { // Return an error if the API call fails return diag.FromErr(err) } diff --git a/spectrocloud/resource_cluster_vsphere_test.go b/spectrocloud/resource_cluster_vsphere_test.go index 3bfc5519..0d419840 100644 --- a/spectrocloud/resource_cluster_vsphere_test.go +++ b/spectrocloud/resource_cluster_vsphere_test.go @@ -9,7 +9,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/spectrocloud/hapi/models" - clusterC "github.com/spectrocloud/hapi/spectrocluster/client/v1" "github.com/spectrocloud/palette-sdk-go/client" ) @@ -121,9 +120,6 @@ func TestToVsphereCluster(t *testing.T) { d := prepareClusterVsphereTestData() m := &client.V1Client{ - GetClusterClientFn: func() (clusterC.ClientService, error) { - return &clusterC.Client{}, nil - }, GetClusterWithoutStatusFn: func(uid string) (*models.V1SpectroCluster, error) { return &models.V1SpectroCluster{ Metadata: nil, diff --git a/spectrocloud/resource_kubevirt_virtual_machine.go b/spectrocloud/resource_kubevirt_virtual_machine.go index a91499ea..0d147593 100644 --- a/spectrocloud/resource_kubevirt_virtual_machine.go +++ b/spectrocloud/resource_kubevirt_virtual_machine.go @@ -182,7 +182,10 @@ func resourceKubevirtVirtualMachineRead(ctx context.Context, resourceData *schem log.Printf("[DEBUG] Received error: %#v", err) return diag.FromErr(err) } - vm := convert.ToKubevirtVM(hapiVM) + vm, err := convert.ToKubevirtVM(hapiVM) + if err != nil { + return diag.FromErr(err) + } if vm == nil { return nil } @@ -397,22 +400,3 @@ func resourceKubevirtVirtualMachineDelete(ctx context.Context, resourceData *sch resourceData.SetId("") return nil } - -func resourceKubevirtVirtualMachineExists(resourceData *schema.ResourceData, meta interface{}) (bool, error) { - clusterUid, namespace, name, err := utils.IdParts(resourceData.Id()) - if err != nil { - return false, err - } - - cli := (meta).(*client.V1Client) - - log.Printf("[INFO] Checking virtual machine %s", name) - if _, err := cli.GetVirtualMachine(clusterUid, namespace, name); err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - return true, err - } - return true, nil -} diff --git a/pkg/addon_deployment_test/addon_deployment_attached_test.go b/tests/addon_deployment_test/addon_deployment_attached_test.go similarity index 100% rename from pkg/addon_deployment_test/addon_deployment_attached_test.go rename to tests/addon_deployment_test/addon_deployment_attached_test.go diff --git a/pkg/addon_deployment_test/addon_deployment_patch_test.go b/tests/addon_deployment_test/addon_deployment_patch_test.go similarity index 61% rename from pkg/addon_deployment_test/addon_deployment_patch_test.go rename to tests/addon_deployment_test/addon_deployment_patch_test.go index b6599095..1604a41d 100644 --- a/pkg/addon_deployment_test/addon_deployment_patch_test.go +++ b/tests/addon_deployment_test/addon_deployment_patch_test.go @@ -1,29 +1,24 @@ package addon_deployment_test import ( - "fmt" + "errors" "testing" + "github.com/stretchr/testify/assert" + "github.com/spectrocloud/hapi/models" clusterC "github.com/spectrocloud/hapi/spectrocluster/client/v1" "github.com/spectrocloud/palette-sdk-go/client" - "github.com/stretchr/testify/assert" + "github.com/spectrocloud/terraform-provider-spectrocloud/tests/mock" ) func TestPatchWithRetry(t *testing.T) { - // Create a mock V1Client - var patchCalled int - - // Create a mock for client.V1SpectroClustersPatchProfiles(params) - h := &client.V1Client{ + // Create a cluster client mock + h := client.V1Client{ RetryAttempts: 3, - ClustersPatchProfilesFn: func(params *clusterC.V1SpectroClustersPatchProfilesParams) error { - patchCalled++ - if patchCalled < 3 { - return fmt.Errorf("test error") - } - return nil - }, + } + mock := &mock.ClusterClientMock{ + PatchSPCProfilesErr: errors.New("test error"), } // Create mock params @@ -37,9 +32,9 @@ func TestPatchWithRetry(t *testing.T) { } // Call patchWithRetry - err := client.PatchWithRetry(h, params) + err := h.PatchWithRetry(mock, params) // Assert patch was called 3 times and there was no error - assert.Equal(t, 3, patchCalled) + assert.Equal(t, 3, mock.PatchSPCProfilesCount) assert.NoError(t, err) } diff --git a/pkg/addon_deployment_test/addon_deployment_update_test.go b/tests/addon_deployment_test/addon_deployment_update_test.go similarity index 59% rename from pkg/addon_deployment_test/addon_deployment_update_test.go rename to tests/addon_deployment_test/addon_deployment_update_test.go index a881c725..c100bc80 100644 --- a/pkg/addon_deployment_test/addon_deployment_update_test.go +++ b/tests/addon_deployment_test/addon_deployment_update_test.go @@ -3,23 +3,17 @@ package addon_deployment import ( "testing" + "github.com/stretchr/testify/assert" + "github.com/spectrocloud/hapi/models" - clusterC "github.com/spectrocloud/hapi/spectrocluster/client/v1" "github.com/spectrocloud/palette-sdk-go/client" - "github.com/stretchr/testify/assert" + "github.com/spectrocloud/terraform-provider-spectrocloud/tests/mock" ) func TestUpdateAddonDeploymentIsNotAttached(t *testing.T) { - // Create a mock V1Client - h := &client.V1Client{ - ClustersPatchProfilesFn: func(params *clusterC.V1SpectroClustersPatchProfilesParams) error { - // Check that the correct params are passed to ClustersPatchProfiles - assert.Equal(t, "test-cluster", params.UID) - assert.Equal(t, "test-profile", params.Body.Profiles[0].UID) - assert.Equal(t, "test-profile-to-replace", params.Body.Profiles[0].ReplaceWithProfile) - assert.True(t, *params.ResolveNotification) - return nil - }, + h := client.V1Client{} + mock := &mock.ClusterClientMock{ + PatchClusterProfileErr: nil, } // Create mock cluster @@ -52,23 +46,16 @@ func TestUpdateAddonDeploymentIsNotAttached(t *testing.T) { } // Call UpdateAddonDeployment - err := h.UpdateAddonDeployment(cluster, body, newProfile) + err := h.UpdateAddonDeployment(mock, cluster, body, newProfile) // Assert there was no error assert.NoError(t, err) } func TestUpdateAddonDeploymentIsAttached(t *testing.T) { - // Create a mock V1Client - h := &client.V1Client{ - ClustersPatchProfilesFn: func(params *clusterC.V1SpectroClustersPatchProfilesParams) error { - // Check that the correct params are passed to ClustersPatchProfiles - assert.Equal(t, "test-cluster", params.UID) - assert.Equal(t, "test-profile", params.Body.Profiles[0].UID) - assert.Equal(t, "test-profile-uid", params.Body.Profiles[0].ReplaceWithProfile) - assert.True(t, *params.ResolveNotification) - return nil - }, + h := client.V1Client{} + mock := &mock.ClusterClientMock{ + PatchClusterProfileErr: nil, } // Create mock cluster @@ -101,7 +88,7 @@ func TestUpdateAddonDeploymentIsAttached(t *testing.T) { } // Call UpdateAddonDeployment - err := h.UpdateAddonDeployment(cluster, body, newProfile) + err := h.UpdateAddonDeployment(mock, cluster, body, newProfile) // Assert there was no error assert.NoError(t, err) diff --git a/tests/cluster_profile_test/cluster_profile_create_test.go b/tests/cluster_profile_test/cluster_profile_create_test.go new file mode 100644 index 00000000..577542ad --- /dev/null +++ b/tests/cluster_profile_test/cluster_profile_create_test.go @@ -0,0 +1,79 @@ +package cluster_profile_test + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/spectrocloud/hapi/models" + clusterC "github.com/spectrocloud/hapi/spectrocluster/client/v1" + "github.com/spectrocloud/palette-sdk-go/client" + "github.com/spectrocloud/terraform-provider-spectrocloud/tests/mock" + "github.com/spectrocloud/terraform-provider-spectrocloud/types" +) + +func TestCreateClusterProfile(t *testing.T) { + testCases := []struct { + name string + profileContext string + expectedReturnedUID string + expectedError error + clusterProfile *models.V1ClusterProfileEntity + mock *mock.ClusterClientMock + }{ + { + name: "Success", + clusterProfile: &models.V1ClusterProfileEntity{}, + profileContext: "project", + expectedError: nil, + expectedReturnedUID: "1", + mock: &mock.ClusterClientMock{ + CreateClusterProfileErr: nil, + CreateClusterProfileResponse: &clusterC.V1ClusterProfilesCreateCreated{Payload: &models.V1UID{UID: types.Ptr("1")}}, + }, + }, + { + name: "Success", + clusterProfile: &models.V1ClusterProfileEntity{}, + profileContext: "tenant", + expectedError: nil, + expectedReturnedUID: "2", + mock: &mock.ClusterClientMock{ + CreateClusterProfileErr: nil, + CreateClusterProfileResponse: &clusterC.V1ClusterProfilesCreateCreated{Payload: &models.V1UID{UID: types.Ptr("2")}}, + }, + }, + { + name: "Error", + clusterProfile: &models.V1ClusterProfileEntity{}, + profileContext: "tenant", + expectedError: errors.New("error creating cluster profile"), + mock: &mock.ClusterClientMock{ + CreateClusterProfileErr: errors.New("error creating cluster profile"), + CreateClusterProfileResponse: nil, + }, + }, + { + name: "Invalid scope", + clusterProfile: &models.V1ClusterProfileEntity{}, + profileContext: "invalid", + expectedError: errors.New("invalid scope"), + mock: &mock.ClusterClientMock{}, + }, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + h := &client.V1Client{} + id, err := h.CreateClusterProfile(tc.mock, tc.clusterProfile, tc.profileContext) + if tc.expectedError != nil { + assert.EqualError(t, err, tc.expectedError.Error()) + } else { + assert.NoError(t, err) + } + if tc.expectedReturnedUID != "" { + assert.Equal(t, id, tc.expectedReturnedUID) + } + }) + } +} diff --git a/tests/cluster_profile_test/cluster_profile_delete_test.go b/tests/cluster_profile_test/cluster_profile_delete_test.go new file mode 100644 index 00000000..635e51ef --- /dev/null +++ b/tests/cluster_profile_test/cluster_profile_delete_test.go @@ -0,0 +1,92 @@ +package cluster_profile_test + +import ( + "errors" + "testing" + + "github.com/spectrocloud/hapi/models" + clusterC "github.com/spectrocloud/hapi/spectrocluster/client/v1" + "github.com/spectrocloud/palette-sdk-go/client" + "github.com/spectrocloud/terraform-provider-spectrocloud/spectrocloud/schema" + "github.com/spectrocloud/terraform-provider-spectrocloud/tests/mock" +) + +func TestDeleteClusterProfileError(t *testing.T) { + testCases := []struct { + name string + uid string + profile *models.V1ClusterProfile + expectedError error + mock *mock.ClusterClientMock + }{ + { + name: "GetProfileError", + uid: "1", + expectedError: errors.New("GetProfileError"), + mock: &mock.ClusterClientMock{ + GetClusterProfilesResponse: nil, + GetClusterProfilesErr: errors.New("GetProfileError"), + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + hapiClient := &client.V1Client{} + err := hapiClient.DeleteClusterProfile(tc.mock, tc.uid) + schema.CompareErrors(t, err, tc.expectedError) + }) + } +} + +func TestDeleteClusterProfile(t *testing.T) { + testCases := []struct { + name string + uid string + profile *models.V1ClusterProfile + expectedError error + mock *mock.ClusterClientMock + }{ + { + name: "Success", + uid: "1", + expectedError: nil, + mock: &mock.ClusterClientMock{ + GetClusterProfilesResponse: &clusterC.V1ClusterProfilesGetOK{ + Payload: &models.V1ClusterProfile{Metadata: &models.V1ObjectMeta{Annotations: map[string]string{"scope": "project"}}}, + }, + GetClusterProfilesErr: nil, + }, + }, + { + name: "Success", + uid: "2", + expectedError: nil, + mock: &mock.ClusterClientMock{ + GetClusterProfilesResponse: &clusterC.V1ClusterProfilesGetOK{ + Payload: &models.V1ClusterProfile{Metadata: &models.V1ObjectMeta{Annotations: map[string]string{"scope": "tenant"}}}, + }, + GetClusterProfilesErr: nil, + }, + }, + { + name: "Invalid scope", + uid: "3", + expectedError: errors.New("invalid scope"), + mock: &mock.ClusterClientMock{ + GetClusterProfilesResponse: &clusterC.V1ClusterProfilesGetOK{ + Payload: &models.V1ClusterProfile{Metadata: &models.V1ObjectMeta{Annotations: map[string]string{"scope": "invalid"}}}, + }, + GetClusterProfilesErr: nil, + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + h := &client.V1Client{} + err := h.DeleteClusterProfile(tc.mock, tc.uid) + schema.CompareErrors(t, err, tc.expectedError) + }) + } +} diff --git a/tests/cluster_profile_test/cluster_profile_patch_test.go b/tests/cluster_profile_test/cluster_profile_patch_test.go new file mode 100644 index 00000000..888bef11 --- /dev/null +++ b/tests/cluster_profile_test/cluster_profile_patch_test.go @@ -0,0 +1,77 @@ +package cluster_profile_test + +import ( + "errors" + "testing" + + "github.com/spectrocloud/hapi/models" + "github.com/spectrocloud/palette-sdk-go/client" + "github.com/spectrocloud/terraform-provider-spectrocloud/tests/mock" + "github.com/stretchr/testify/assert" +) + +func TestPatchClusterProfile(t *testing.T) { + testCases := []struct { + name string + clusterProfile *models.V1ClusterProfileUpdateEntity + ProfileContext string + expectedError error + mock *mock.ClusterClientMock + }{ + { + name: "Success", + clusterProfile: &models.V1ClusterProfileUpdateEntity{ + Metadata: &models.V1ObjectMeta{ + UID: "1", + }, + }, + ProfileContext: "project", + expectedError: nil, + mock: &mock.ClusterClientMock{ + PatchClusterProfileErr: nil, + }, + }, + { + name: "Error", + clusterProfile: &models.V1ClusterProfileUpdateEntity{ + Metadata: &models.V1ObjectMeta{ + UID: "2", + }, + }, + ProfileContext: "tenant", + expectedError: errors.New("error patching cluster profile"), + mock: &mock.ClusterClientMock{ + PatchClusterProfileErr: errors.New("error patching cluster profile"), + }, + }, + { + name: "Invalid scope", + clusterProfile: &models.V1ClusterProfileUpdateEntity{ + Metadata: &models.V1ObjectMeta{ + UID: "3", + }, + }, + ProfileContext: "invalid", + expectedError: errors.New("invalid scope"), + mock: &mock.ClusterClientMock{}, + }, + } + + metadata := &models.V1ProfileMetaEntity{ + Metadata: &models.V1ObjectMetaInputEntity{ + Annotations: map[string]string{}, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + h := &client.V1Client{} + err := h.PatchClusterProfile(tc.mock, tc.clusterProfile, metadata, tc.ProfileContext) + if tc.expectedError != nil { + assert.EqualError(t, err, tc.expectedError.Error()) + } else { + assert.NoError(t, err) + } + }) + } +} diff --git a/tests/cluster_profile_test/cluster_profile_publish_test.go b/tests/cluster_profile_test/cluster_profile_publish_test.go new file mode 100644 index 00000000..99b8248d --- /dev/null +++ b/tests/cluster_profile_test/cluster_profile_publish_test.go @@ -0,0 +1,54 @@ +package cluster_profile_test + +import ( + "errors" + "testing" + + "github.com/spectrocloud/palette-sdk-go/client" + "github.com/spectrocloud/terraform-provider-spectrocloud/spectrocloud/schema" + "github.com/spectrocloud/terraform-provider-spectrocloud/tests/mock" +) + +func TestPublishClusterProfile(t *testing.T) { + testCases := []struct { + name string + uid string + ProfileContext string + expectedError error + mock *mock.ClusterClientMock + }{ + { + name: "Success", + uid: "1", + ProfileContext: "project", + expectedError: nil, + mock: &mock.ClusterClientMock{ + PublishClusterProfileErr: nil, + }, + }, + { + name: "Error", + uid: "2", + ProfileContext: "tenant", + expectedError: errors.New("error publishing cluster profile"), + mock: &mock.ClusterClientMock{ + PublishClusterProfileErr: errors.New("error publishing cluster profile"), + }, + }, + { + name: "Invalid scope", + uid: "3", + ProfileContext: "invalid", + expectedError: errors.New("invalid scope"), + mock: &mock.ClusterClientMock{}, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + h := &client.V1Client{} + err := h.PublishClusterProfile(tc.mock, tc.uid, tc.ProfileContext) + schema.CompareErrors(t, err, tc.expectedError) + }) + } +} diff --git a/tests/cluster_profile_test/cluster_profile_update_test.go b/tests/cluster_profile_test/cluster_profile_update_test.go new file mode 100644 index 00000000..db7bf83c --- /dev/null +++ b/tests/cluster_profile_test/cluster_profile_update_test.go @@ -0,0 +1,71 @@ +package cluster_profile_test + +import ( + "errors" + "testing" + + "github.com/spectrocloud/hapi/models" + "github.com/spectrocloud/palette-sdk-go/client" + "github.com/spectrocloud/terraform-provider-spectrocloud/tests/mock" + "github.com/stretchr/testify/assert" +) + +func TestUpdateClusterProfile(t *testing.T) { + testCases := []struct { + name string + clusterProfile *models.V1ClusterProfileUpdateEntity + ProfileContext string + expectedError error + mock *mock.ClusterClientMock + }{ + { + name: "Success", + clusterProfile: &models.V1ClusterProfileUpdateEntity{ + Metadata: &models.V1ObjectMeta{ + UID: "1", + }, + }, + ProfileContext: "project", + expectedError: nil, + mock: &mock.ClusterClientMock{ + UpdateClusterProfileErr: nil, + }, + }, + { + name: "Error", + clusterProfile: &models.V1ClusterProfileUpdateEntity{ + Metadata: &models.V1ObjectMeta{ + UID: "2", + }, + }, + ProfileContext: "tenant", + expectedError: errors.New("error updating cluster profile"), + mock: &mock.ClusterClientMock{ + UpdateClusterProfileErr: errors.New("error updating cluster profile"), + }, + }, + { + name: "Invalid scope", + clusterProfile: &models.V1ClusterProfileUpdateEntity{ + Metadata: &models.V1ObjectMeta{ + UID: "3", + }, + }, + ProfileContext: "invalid", + expectedError: errors.New("invalid scope"), + mock: &mock.ClusterClientMock{}, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + h := &client.V1Client{} + err := h.UpdateClusterProfile(tc.mock, tc.clusterProfile, tc.ProfileContext) + if tc.expectedError != nil { + assert.EqualError(t, err, tc.expectedError.Error()) + } else { + assert.NoError(t, err) + } + }) + } +} diff --git a/tests/mock/cluster_client_mock.go b/tests/mock/cluster_client_mock.go new file mode 100644 index 00000000..b9379986 --- /dev/null +++ b/tests/mock/cluster_client_mock.go @@ -0,0 +1,51 @@ +package mock + +import ( + clusterC "github.com/spectrocloud/hapi/spectrocluster/client/v1" +) + +type ClusterClientMock struct { + clusterC.ClientService + CreateClusterProfileErr error + DeleteClusterProfileErr error + GetClusterProfilesErr error + UpdateClusterProfileErr error + PatchClusterProfileErr error + PublishClusterProfileErr error + PatchSPCProfilesErr error + PatchSPCProfilesCount int + CreateClusterProfileResponse *clusterC.V1ClusterProfilesCreateCreated + GetClusterProfilesResponse *clusterC.V1ClusterProfilesGetOK +} + +func (m *ClusterClientMock) V1ClusterProfilesGet(params *clusterC.V1ClusterProfilesGetParams) (*clusterC.V1ClusterProfilesGetOK, error) { + return m.GetClusterProfilesResponse, m.GetClusterProfilesErr +} + +func (m *ClusterClientMock) V1ClusterProfilesCreate(params *clusterC.V1ClusterProfilesCreateParams) (*clusterC.V1ClusterProfilesCreateCreated, error) { + return m.CreateClusterProfileResponse, m.CreateClusterProfileErr +} + +func (m *ClusterClientMock) V1ClusterProfilesDelete(params *clusterC.V1ClusterProfilesDeleteParams) (*clusterC.V1ClusterProfilesDeleteNoContent, error) { + return nil, m.DeleteClusterProfileErr +} + +func (m *ClusterClientMock) V1ClusterProfilesPublish(params *clusterC.V1ClusterProfilesPublishParams) (*clusterC.V1ClusterProfilesPublishNoContent, error) { + return nil, m.PublishClusterProfileErr +} + +func (m *ClusterClientMock) V1ClusterProfilesUpdate(params *clusterC.V1ClusterProfilesUpdateParams) (*clusterC.V1ClusterProfilesUpdateNoContent, error) { + return nil, m.UpdateClusterProfileErr +} + +func (m *ClusterClientMock) V1ClusterProfilesUIDMetadataUpdate(params *clusterC.V1ClusterProfilesUIDMetadataUpdateParams) (*clusterC.V1ClusterProfilesUIDMetadataUpdateNoContent, error) { + return nil, m.PatchClusterProfileErr +} + +func (m *ClusterClientMock) V1SpectroClustersPatchProfiles(params *clusterC.V1SpectroClustersPatchProfilesParams) (*clusterC.V1SpectroClustersPatchProfilesNoContent, error) { + m.PatchSPCProfilesCount++ + if m.PatchSPCProfilesCount < 3 { + return nil, m.PatchSPCProfilesErr + } + return nil, nil +}