From db98975c7cce5b407ae7f093f2f8f90a3f726bc3 Mon Sep 17 00:00:00 2001 From: Joseph Callen Date: Tue, 26 Aug 2025 14:11:54 -0400 Subject: [PATCH] vendor --- go.mod | 2 +- go.sum | 4 +- .../github.com/vmware/govmomi/.goreleaser.yml | 43 ----- .../github.com/vmware/govmomi/cns/cns_util.go | 29 +--- .../vmware/govmomi/cns/types/types.go | 1 + .../govmomi/internal/version/version.go | 2 +- .../simulator/authorization_manager.go | 24 +-- .../simulator/cluster_compute_resource.go | 87 +++++++--- .../vmware/govmomi/simulator/container.go | 22 +-- .../simulator/container_virtual_machine.go | 27 +-- .../vmware/govmomi/simulator/datacenter.go | 26 +-- .../vmware/govmomi/simulator/datastore.go | 82 +++++++-- .../simulator/datastore_namespace_manager.go | 144 ++++++++++++++-- .../vmware/govmomi/simulator/dvs.go | 42 ++--- .../govmomi/simulator/environment_browser.go | 20 +-- .../govmomi/simulator/esx/datacenter.go | 22 +-- .../vmware/govmomi/simulator/file_manager.go | 65 +++---- .../vmware/govmomi/simulator/folder.go | 40 ++--- .../simulator/host_certificate_manager.go | 22 +-- .../simulator/host_datastore_browser.go | 62 ++++--- .../simulator/host_datastore_system.go | 116 +++++++------ .../simulator/host_local_account_manager.go | 26 +-- .../govmomi/simulator/host_network_system.go | 28 +-- .../vmware/govmomi/simulator/host_system.go | 48 ++---- .../govmomi/simulator/license_manager.go | 22 +-- .../vmware/govmomi/simulator/model.go | 107 ++++++------ .../vmware/govmomi/simulator/object.go | 20 +-- .../govmomi/simulator/option_manager.go | 22 +-- .../govmomi/simulator/performance_manager.go | 26 +-- .../vmware/govmomi/simulator/portgroup.go | 20 +-- .../govmomi/simulator/property_collector.go | 32 ++-- .../govmomi/simulator/property_filter.go | 20 +-- .../vmware/govmomi/simulator/registry.go | 46 +++-- .../vmware/govmomi/simulator/resource_pool.go | 56 +++--- .../vmware/govmomi/simulator/search_index.go | 76 ++++----- .../govmomi/simulator/service_instance.go | 41 ++--- .../govmomi/simulator/session_manager.go | 49 +++--- .../vmware/govmomi/simulator/simulator.go | 95 ++++++----- .../vmware/govmomi/simulator/snapshot.go | 34 ++-- .../simulator/storage_resource_manager.go | 30 +--- .../vmware/govmomi/simulator/task.go | 49 +++--- .../vmware/govmomi/simulator/task_manager.go | 22 +-- .../vmware/govmomi/simulator/view_manager.go | 33 ++-- .../govmomi/simulator/virtual_disk_manager.go | 46 ++--- .../govmomi/simulator/virtual_machine.go | 161 ++++++++---------- .../simulator/vm_compatibility_checker.go | 20 +-- .../simulator/vstorage_object_manager.go | 95 ++++++++--- .../github.com/vmware/govmomi/units/size.go | 18 +- .../govmomi/vapi/simulator/simulator.go | 50 +++--- .../vmware/govmomi/vim25/mo/registry.go | 38 +++-- .../vmware/govmomi/vim25/mo/retrieve.go | 23 +-- .../vmware/govmomi/vim25/mo/type_info.go | 24 +-- .../vmware/govmomi/vim25/soap/client.go | 21 ++- vendor/modules.txt | 4 +- 54 files changed, 1053 insertions(+), 1231 deletions(-) diff --git a/go.mod b/go.mod index 1ee1079784..f7b5900e15 100644 --- a/go.mod +++ b/go.mod @@ -115,7 +115,7 @@ require ( github.com/thoas/go-funk v0.9.3 github.com/ulikunitz/xz v0.5.12 github.com/vincent-petithory/dataurl v1.0.0 - github.com/vmware/govmomi v0.47.1 + github.com/vmware/govmomi v0.49.0 go.uber.org/mock v0.5.0 golang.org/x/crypto v0.38.0 golang.org/x/oauth2 v0.28.0 diff --git a/go.sum b/go.sum index b9294167e8..bd62c68f63 100644 --- a/go.sum +++ b/go.sum @@ -950,8 +950,8 @@ github.com/vincent-petithory/dataurl v1.0.0/go.mod h1:FHafX5vmDzyP+1CQATJn7WFKc9 github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= github.com/vmihailenco/msgpack/v4 v4.3.12/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4= github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= -github.com/vmware/govmomi v0.47.1 h1:6a2iNaqSS2/AFfvI8UMe0l787/TBKkK0KK9jCqCyYCE= -github.com/vmware/govmomi v0.47.1/go.mod h1:bYwUHpGpisE4AOlDl5eph90T+cjJMIcKx/kaa5v5rQM= +github.com/vmware/govmomi v0.49.0 h1:M80ExmFq3kOfeMvMJcHnXgA/4w5hUAFfYfc+Qm3lmPg= +github.com/vmware/govmomi v0.49.0/go.mod h1:+oZ0tYJw/pXKoeWHLR9Egq5KENVr2hLePRzisFhEWpA= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xanzy/ssh-agent v0.3.0 h1:wUMzuKtKilRgBAD1sUb8gOwwRr2FGoBVumcjoOACClI= diff --git a/vendor/github.com/vmware/govmomi/.goreleaser.yml b/vendor/github.com/vmware/govmomi/.goreleaser.yml index e1cb528974..a359fc9758 100644 --- a/vendor/github.com/vmware/govmomi/.goreleaser.yml +++ b/vendor/github.com/vmware/govmomi/.goreleaser.yml @@ -92,49 +92,6 @@ changelog: - Merge pull request - Merge branch -# upload disabled since it is maintained in homebrew-core -brews: - - name: govc - ids: - - govcbuild - repository: - owner: govmomi - name: homebrew-tap - # TODO: create token in specified tap repo, add as secret to govmomi repo and reference in release workflow - # token: "{{ .Env.HOMEBREW_TAP_GITHUB_TOKEN }}" - # enable once we do fully automated releases - skip_upload: true - commit_author: - name: Alfred the Narwhal - email: cna-alfred@vmware.com - directory: Formula - homepage: "https://github.com/vmware/govmomi/blob/main/govc/README.md" - description: "govc is a vSphere CLI built on top of govmomi." - test: | - system "#{bin}/govc version" - install: | - bin.install "govc" - - name: vcsim - ids: - - vcsimbuild - repository: - owner: govmomi - name: homebrew-tap - # TODO: create token in specified tap repo, add as secret to govmomi repo and reference in release workflow - # token: "{{ .Env.HOMEBREW_TAP_GITHUB_TOKEN }}" - # enable once we do fully automated releases - skip_upload: true - commit_author: - name: Alfred the Narwhal - email: cna-alfred@vmware.com - directory: Formula - homepage: "https://github.com/vmware/govmomi/blob/main/vcsim/README.md" - description: "vcsim is a vSphere API simulator built on top of govmomi." - test: | - system "#{bin}/vcsim -h" - install: | - bin.install "vcsim" - dockers: - image_templates: - "vmware/govc:{{ .Tag }}" diff --git a/vendor/github.com/vmware/govmomi/cns/cns_util.go b/vendor/github.com/vmware/govmomi/cns/cns_util.go index f0e8f45087..96aa3b24ad 100644 --- a/vendor/github.com/vmware/govmomi/cns/cns_util.go +++ b/vendor/github.com/vmware/govmomi/cns/cns_util.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2019 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package cns @@ -49,9 +37,6 @@ func GetQuerySnapshotsTaskResult(ctx context.Context, taskInfo *vim25types.TaskI } if taskInfo.Result != nil { snapshotQueryResult := taskInfo.Result.(cnstypes.CnsSnapshotQueryResult) - if &snapshotQueryResult == nil { - return nil, errors.New("Cannot get SnapshotQueryResult") - } return &snapshotQueryResult, nil } return nil, errors.New("TaskInfo result is empty") @@ -64,9 +49,7 @@ func GetTaskResult(ctx context.Context, taskInfo *vim25types.TaskInfo) (cnstypes } if taskInfo.Result != nil { volumeOperationBatchResult := taskInfo.Result.(cnstypes.CnsVolumeOperationBatchResult) - if &volumeOperationBatchResult == nil || - volumeOperationBatchResult.VolumeResults == nil || - len(volumeOperationBatchResult.VolumeResults) == 0 { + if len(volumeOperationBatchResult.VolumeResults) == 0 { return nil, errors.New("Cannot get VolumeOperationResult") } return volumeOperationBatchResult.VolumeResults[0], nil @@ -81,9 +64,7 @@ func GetTaskResultArray(ctx context.Context, taskInfo *vim25types.TaskInfo) ([]c } if taskInfo.Result != nil { volumeOperationBatchResult := taskInfo.Result.(cnstypes.CnsVolumeOperationBatchResult) - if &volumeOperationBatchResult == nil || - volumeOperationBatchResult.VolumeResults == nil || - len(volumeOperationBatchResult.VolumeResults) == 0 { + if len(volumeOperationBatchResult.VolumeResults) == 0 { return nil, errors.New("Cannot get VolumeOperationResult") } return volumeOperationBatchResult.VolumeResults, nil diff --git a/vendor/github.com/vmware/govmomi/cns/types/types.go b/vendor/github.com/vmware/govmomi/cns/types/types.go index c85298ee45..3b5ce9c0b4 100644 --- a/vendor/github.com/vmware/govmomi/cns/types/types.go +++ b/vendor/github.com/vmware/govmomi/cns/types/types.go @@ -294,6 +294,7 @@ type CnsContainerCluster struct { VSphereUser string `xml:"vSphereUser" json:"vSphereUser"` ClusterFlavor string `xml:"clusterFlavor,omitempty" json:"clusterFlavor"` ClusterDistribution string `xml:"clusterDistribution,omitempty" json:"clusterDistribution"` + Delete bool `xml:"delete,omitempty" json:"delete"` } func init() { diff --git a/vendor/github.com/vmware/govmomi/internal/version/version.go b/vendor/github.com/vmware/govmomi/internal/version/version.go index 24d1597b4e..80969fffa6 100644 --- a/vendor/github.com/vmware/govmomi/internal/version/version.go +++ b/vendor/github.com/vmware/govmomi/internal/version/version.go @@ -21,5 +21,5 @@ const ( ClientName = "govmomi" // ClientVersion is the version of this SDK - ClientVersion = "0.47.1" + ClientVersion = "0.49.0" ) diff --git a/vendor/github.com/vmware/govmomi/simulator/authorization_manager.go b/vendor/github.com/vmware/govmomi/simulator/authorization_manager.go index 924ff978fe..b660171721 100644 --- a/vendor/github.com/vmware/govmomi/simulator/authorization_manager.go +++ b/vendor/github.com/vmware/govmomi/simulator/authorization_manager.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -66,8 +54,8 @@ func (m *AuthorizationManager) init(r *Registry) { } } -func (m *AuthorizationManager) RetrieveEntityPermissions(req *types.RetrieveEntityPermissions) soap.HasFault { - e := Map.Get(req.Entity).(mo.Entity) +func (m *AuthorizationManager) RetrieveEntityPermissions(ctx *Context, req *types.RetrieveEntityPermissions) soap.HasFault { + e := ctx.Map.Get(req.Entity).(mo.Entity) p := m.permissions[e.Reference()] @@ -78,7 +66,7 @@ func (m *AuthorizationManager) RetrieveEntityPermissions(req *types.RetrieveEnti break } - e = Map.Get(parent.Reference()).(mo.Entity) + e = ctx.Map.Get(parent.Reference()).(mo.Entity) p = append(p, m.permissions[e.Reference()]...) } diff --git a/vendor/github.com/vmware/govmomi/simulator/cluster_compute_resource.go b/vendor/github.com/vmware/govmomi/simulator/cluster_compute_resource.go index 01c39362d8..1d7e09ba16 100644 --- a/vendor/github.com/vmware/govmomi/simulator/cluster_compute_resource.go +++ b/vendor/github.com/vmware/govmomi/simulator/cluster_compute_resource.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2023 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -66,7 +54,7 @@ func (add *addHost) Run(task *Task) (types.AnyType, types.BaseMethodFault) { template.Network = cr.Network[:1] // VM Network } - host := NewHostSystem(template) + host := NewHostSystem(task.ctx, template) host.configure(task.ctx, spec, add.req.AsConnected) task.ctx.Map.PutEntity(cr, task.ctx.Map.NewEntity(host)) @@ -81,6 +69,10 @@ func (add *addHost) Run(task *Task) (types.AnyType, types.BaseMethodFault) { cr.Host = append(cr.Host, host.Reference()) addComputeResource(cr.Summary.GetComputeResourceSummary(), host) + if cr.vsanIsEnabled() { + cr.addStorageHost(task.ctx, host.Self) + } + return host.Reference(), nil } @@ -92,7 +84,14 @@ func (c *ClusterComputeResource) AddHostTask(ctx *Context, add *types.AddHost_Ta } } -func (c *ClusterComputeResource) update(cfg *types.ClusterConfigInfoEx, cspec *types.ClusterConfigSpecEx) types.BaseMethodFault { +func (c *ClusterComputeResource) vsanIsEnabled() bool { + if cfg := c.ConfigurationEx.(*types.ClusterConfigInfoEx).VsanConfigInfo; cfg != nil { + return isTrue(cfg.Enabled) + } + return false +} + +func (c *ClusterComputeResource) update(_ *Context, cfg *types.ClusterConfigInfoEx, cspec *types.ClusterConfigSpecEx) types.BaseMethodFault { if cspec.DasConfig != nil { if val := cspec.DasConfig.Enabled; val != nil { cfg.DasConfig.Enabled = val @@ -113,7 +112,7 @@ func (c *ClusterComputeResource) update(cfg *types.ClusterConfigInfoEx, cspec *t return nil } -func (c *ClusterComputeResource) updateRules(cfg *types.ClusterConfigInfoEx, cspec *types.ClusterConfigSpecEx) types.BaseMethodFault { +func (c *ClusterComputeResource) updateRules(_ *Context, cfg *types.ClusterConfigInfoEx, cspec *types.ClusterConfigSpecEx) types.BaseMethodFault { for _, spec := range cspec.RulesSpec { var i int exists := false @@ -160,7 +159,7 @@ func (c *ClusterComputeResource) updateRules(cfg *types.ClusterConfigInfoEx, csp return nil } -func (c *ClusterComputeResource) updateGroups(cfg *types.ClusterConfigInfoEx, cspec *types.ClusterConfigSpecEx) types.BaseMethodFault { +func (c *ClusterComputeResource) updateGroups(_ *Context, cfg *types.ClusterConfigInfoEx, cspec *types.ClusterConfigSpecEx) types.BaseMethodFault { for _, spec := range cspec.GroupSpec { var i int exists := false @@ -204,7 +203,7 @@ func (c *ClusterComputeResource) updateGroups(cfg *types.ClusterConfigInfoEx, cs return nil } -func (c *ClusterComputeResource) updateOverridesDAS(cfg *types.ClusterConfigInfoEx, cspec *types.ClusterConfigSpecEx) types.BaseMethodFault { +func (c *ClusterComputeResource) updateOverridesDAS(_ *Context, cfg *types.ClusterConfigInfoEx, cspec *types.ClusterConfigSpecEx) types.BaseMethodFault { for _, spec := range cspec.DasVmConfigSpec { var i int var key types.ManagedObjectReference @@ -255,7 +254,7 @@ func (c *ClusterComputeResource) updateOverridesDAS(cfg *types.ClusterConfigInfo return nil } -func (c *ClusterComputeResource) updateOverridesDRS(cfg *types.ClusterConfigInfoEx, cspec *types.ClusterConfigSpecEx) types.BaseMethodFault { +func (c *ClusterComputeResource) updateOverridesDRS(_ *Context, cfg *types.ClusterConfigInfoEx, cspec *types.ClusterConfigSpecEx) types.BaseMethodFault { for _, spec := range cspec.DrsVmConfigSpec { var i int var key types.ManagedObjectReference @@ -301,7 +300,7 @@ func (c *ClusterComputeResource) updateOverridesDRS(cfg *types.ClusterConfigInfo return nil } -func (c *ClusterComputeResource) updateOverridesVmOrchestration(cfg *types.ClusterConfigInfoEx, cspec *types.ClusterConfigSpecEx) types.BaseMethodFault { +func (c *ClusterComputeResource) updateOverridesVmOrchestration(_ *Context, cfg *types.ClusterConfigInfoEx, cspec *types.ClusterConfigSpecEx) types.BaseMethodFault { for _, spec := range cspec.VmOrchestrationSpec { var i int var key types.ManagedObjectReference @@ -347,6 +346,43 @@ func (c *ClusterComputeResource) updateOverridesVmOrchestration(cfg *types.Clust return nil } +func (c *ClusterComputeResource) addStorageHost(ctx *Context, ref types.ManagedObjectReference) types.BaseMethodFault { + ds := ctx.Map.Get(ref).(*HostSystem).ConfigManager.DatastoreSystem + hds := ctx.Map.Get(*ds).(*HostDatastoreSystem) + return hds.createVsanDatastore(ctx) +} + +func (c *ClusterComputeResource) updateVSAN(ctx *Context, cfg *types.ClusterConfigInfoEx, cspec *types.ClusterConfigSpecEx) types.BaseMethodFault { + if cspec.VsanConfig == nil { + return nil + } + + if cfg.VsanConfigInfo == nil { + cfg.VsanConfigInfo = cspec.VsanConfig + if cfg.VsanConfigInfo.DefaultConfig == nil { + cfg.VsanConfigInfo.DefaultConfig = new(types.VsanClusterConfigInfoHostDefaultInfo) + } + } else { + if cspec.VsanConfig.Enabled != nil { + cfg.VsanConfigInfo.Enabled = cspec.VsanConfig.Enabled + } + } + + if cfg.VsanConfigInfo.DefaultConfig.Uuid == "" { + cfg.VsanConfigInfo.DefaultConfig.Uuid = uuid.NewString() + } + + if isTrue(cfg.VsanConfigInfo.Enabled) { + for _, ref := range c.Host { + if err := c.addStorageHost(ctx, ref); err != nil { + return err + } + } + } + + return nil +} + func (c *ClusterComputeResource) ReconfigureComputeResourceTask(ctx *Context, req *types.ReconfigureComputeResource_Task) soap.HasFault { task := CreateTask(c, "reconfigureCluster", func(*Task) (types.AnyType, types.BaseMethodFault) { spec, ok := req.Spec.(*types.ClusterConfigSpecEx) @@ -354,17 +390,18 @@ func (c *ClusterComputeResource) ReconfigureComputeResourceTask(ctx *Context, re return nil, new(types.InvalidArgument) } - updates := []func(*types.ClusterConfigInfoEx, *types.ClusterConfigSpecEx) types.BaseMethodFault{ + updates := []func(*Context, *types.ClusterConfigInfoEx, *types.ClusterConfigSpecEx) types.BaseMethodFault{ c.update, c.updateRules, c.updateGroups, c.updateOverridesDAS, c.updateOverridesDRS, c.updateOverridesVmOrchestration, + c.updateVSAN, } for _, update := range updates { - if err := update(c.ConfigurationEx.(*types.ClusterConfigInfoEx), spec); err != nil { + if err := update(ctx, c.ConfigurationEx.(*types.ClusterConfigInfoEx), spec); err != nil { return nil, err } } @@ -658,7 +695,7 @@ func CreateClusterComputeResource(ctx *Context, f *Folder, name string, spec typ config.VmSwapPlacement = string(types.VirtualMachineConfigInfoSwapPlacementTypeVmDirectory) config.DrsConfig.Enabled = types.NewBool(true) - pool := NewResourcePool() + pool := NewResourcePool(ctx) ctx.Map.PutEntity(cluster, ctx.Map.NewEntity(pool)) cluster.ResourcePool = &pool.Self diff --git a/vendor/github.com/vmware/govmomi/simulator/container.go b/vendor/github.com/vmware/govmomi/simulator/container.go index f39ef99702..6650f2c982 100644 --- a/vendor/github.com/vmware/govmomi/simulator/container.go +++ b/vendor/github.com/vmware/govmomi/simulator/container.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2018 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -697,7 +685,7 @@ func (c *container) updated() { // returns: // // err - uninitializedContainer error - if c.id is empty -func (c *container) watchContainer(ctx context.Context, updateFn func(*containerDetails, *container) error) error { +func (c *container) watchContainer(ctx *Context, updateFn func(*containerDetails, *container) error) error { c.Lock() defer c.Unlock() @@ -725,7 +713,7 @@ func (c *container) watchContainer(ctx context.Context, updateFn func(*container var removing bool if _, ok := err.(uninitializedContainer); ok { removing = true - rmErr = c.remove(SpoofContext()) + rmErr = c.remove(ctx) } updateErr := updateFn(&details, c) diff --git a/vendor/github.com/vmware/govmomi/simulator/container_virtual_machine.go b/vendor/github.com/vmware/govmomi/simulator/container_virtual_machine.go index 5a0b7753a9..d0bdaea761 100644 --- a/vendor/github.com/vmware/govmomi/simulator/container_virtual_machine.go +++ b/vendor/github.com/vmware/govmomi/simulator/container_virtual_machine.go @@ -1,24 +1,11 @@ -/* -Copyright (c) 2023-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator import ( "archive/tar" - "context" "encoding/hex" "encoding/json" "errors" @@ -296,12 +283,10 @@ func (svm *simVM) start(ctx *Context) error { } callback := func(details *containerDetails, c *container) error { - spoofctx := SpoofContext() - if c.id == "" && svm.vm != nil { // If the container cannot be found then destroy this VM unless the VM is no longer configured for container backing (svm.vm == nil) - taskRef := svm.vm.DestroyTask(spoofctx, &types.Destroy_Task{This: svm.vm.Self}).(*methods.Destroy_TaskBody).Res.Returnval - task, ok := spoofctx.Map.Get(taskRef).(*Task) + taskRef := svm.vm.DestroyTask(ctx, &types.Destroy_Task{This: svm.vm.Self}).(*methods.Destroy_TaskBody).Res.Returnval + task, ok := ctx.Map.Get(taskRef).(*Task) if !ok { panic(fmt.Sprintf("couldn't retrieve task for moref %+q while deleting VM %s", taskRef, svm.vm.Name)) } @@ -320,7 +305,7 @@ func (svm *simVM) start(ctx *Context) error { } // Start watching the container resource. - err = svm.c.watchContainer(context.Background(), callback) + err = svm.c.watchContainer(ctx, callback) if _, ok := err.(uninitializedContainer); ok { // the container has been deleted before we could watch, despite successful launch so clean up. callback(nil, svm.c) diff --git a/vendor/github.com/vmware/govmomi/simulator/datacenter.go b/vendor/github.com/vmware/govmomi/simulator/datacenter.go index 7680b602a7..098ac9f123 100644 --- a/vendor/github.com/vmware/govmomi/simulator/datacenter.go +++ b/vendor/github.com/vmware/govmomi/simulator/datacenter.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -110,7 +98,7 @@ func (dc *Datacenter) defaultNetwork() []types.ManagedObjectReference { } // folder returns the Datacenter folder that can contain the given object type -func (dc *Datacenter) folder(obj mo.Entity) *mo.Folder { +func (dc *Datacenter) folder(ctx *Context, obj mo.Entity) *mo.Folder { folders := []types.ManagedObjectReference{ dc.VmFolder, dc.HostFolder, @@ -121,7 +109,7 @@ func (dc *Datacenter) folder(obj mo.Entity) *mo.Folder { rtype := obj.Reference().Type for i := range folders { - folder, _ := asFolderMO(Map.Get(folders[i])) + folder, _ := asFolderMO(ctx.Map.Get(folders[i])) for _, kind := range folder.ChildType { if rtype == kind { return folder @@ -136,10 +124,10 @@ func (dc *Datacenter) folder(obj mo.Entity) *mo.Folder { return nil } -func datacenterEventArgument(obj mo.Entity) *types.DatacenterEventArgument { +func datacenterEventArgument(ctx *Context, obj mo.Entity) *types.DatacenterEventArgument { dc, ok := obj.(*Datacenter) if !ok { - dc = Map.getEntityDatacenter(obj) + dc = ctx.Map.getEntityDatacenter(obj) } return &types.DatacenterEventArgument{ Datacenter: dc.Self, diff --git a/vendor/github.com/vmware/govmomi/simulator/datastore.go b/vendor/github.com/vmware/govmomi/simulator/datastore.go index 277674afef..9f71fb0779 100644 --- a/vendor/github.com/vmware/govmomi/simulator/datastore.go +++ b/vendor/github.com/vmware/govmomi/simulator/datastore.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2023 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -23,7 +11,11 @@ import ( "strings" "time" + "github.com/google/uuid" + + "github.com/vmware/govmomi/internal" "github.com/vmware/govmomi/object" + "github.com/vmware/govmomi/units" "github.com/vmware/govmomi/vim25/methods" "github.com/vmware/govmomi/vim25/mo" "github.com/vmware/govmomi/vim25/soap" @@ -32,6 +24,8 @@ import ( type Datastore struct { mo.Datastore + + namespace map[string]string // TODO: make thread safe } func (ds *Datastore) eventArgument() *types.DatastoreEventArgument { @@ -60,6 +54,54 @@ func (ds *Datastore) model(m *Model) error { return nil } +// resolve Datastore relative file path to absolute path. +// vSAN top-level directories are named with its vSAN object uuid. +// The directory uuid or friendlyName can be used the various FileManager, +// VirtualDiskManager, etc. methods that have a Datastore path param. +// Note that VirtualDevice file backing paths must use the vSAN uuid. +func (ds *Datastore) resolve(ctx *Context, p string, remove ...bool) string { + if p == "" || !internal.IsDatastoreVSAN(ds.Datastore) { + return path.Join(ds.Summary.Url, p) + } + + rm := len(remove) != 0 && remove[0] + unlock := ctx.Map.AcquireLock(ctx, ds.Self) + defer unlock() + + if ds.namespace == nil { + ds.namespace = make(map[string]string) + } + + elem := strings.Split(p, "/") + dir := elem[0] + + _, err := uuid.Parse(dir) + if err != nil { + // Translate friendlyName to UUID + id, ok := ds.namespace[dir] + if !ok { + id = uuid.NewString() + ds.namespace[dir] = id + } + + elem[0] = id + p = path.Join(elem...) + if rm { + delete(ds.namespace, id) + } + } else if rm { + // UUID was given + for name, id := range ds.namespace { + if p == id { + delete(ds.namespace, name) + break + } + } + } + + return path.Join(ds.Summary.Url, p) +} + func parseDatastorePath(dsPath string) (*object.DatastorePath, types.BaseMethodFault) { var p object.DatastorePath @@ -70,7 +112,7 @@ func parseDatastorePath(dsPath string) (*object.DatastorePath, types.BaseMethodF return nil, &types.InvalidDatastorePath{DatastorePath: dsPath} } -func (ds *Datastore) RefreshDatastore(*types.RefreshDatastore) soap.HasFault { +func (ds *Datastore) RefreshDatastore(*Context, *types.RefreshDatastore) soap.HasFault { r := &methods.RefreshDatastoreBody{} _, err := os.Stat(ds.Info.GetDatastoreInfo().Url) @@ -79,8 +121,14 @@ func (ds *Datastore) RefreshDatastore(*types.RefreshDatastore) soap.HasFault { return r } + ds.Summary.Capacity = int64(units.ByteSize(units.TB)) * int64(len(ds.Host)) + ds.Summary.FreeSpace = ds.Summary.Capacity + info := ds.Info.GetDatastoreInfo() + info.FreeSpace = ds.Summary.FreeSpace + info.MaxMemoryFileSize = ds.Summary.Capacity + info.MaxFileSize = ds.Summary.Capacity info.Timestamp = types.NewTime(time.Now()) r.Res = &types.RefreshDatastoreResponse{} @@ -99,7 +147,7 @@ func (ds *Datastore) DestroyTask(ctx *Context, req *types.Destroy_Task) soap.Has for _, mount := range ds.Host { host := ctx.Map.Get(mount.Key).(*HostSystem) ctx.Map.RemoveReference(ctx, host, &host.Datastore, ds.Self) - parent := hostParent(&host.HostSystem) + parent := hostParent(ctx, &host.HostSystem) ctx.Map.RemoveReference(ctx, parent, &parent.Datastore, ds.Self) } diff --git a/vendor/github.com/vmware/govmomi/simulator/datastore_namespace_manager.go b/vendor/github.com/vmware/govmomi/simulator/datastore_namespace_manager.go index 2c642896b3..083b15b235 100644 --- a/vendor/github.com/vmware/govmomi/simulator/datastore_namespace_manager.go +++ b/vendor/github.com/vmware/govmomi/simulator/datastore_namespace_manager.go @@ -1,25 +1,15 @@ -/* -Copyright (c) 2024-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator import ( + "path" "strings" "github.com/vmware/govmomi/internal" + "github.com/vmware/govmomi/object" "github.com/vmware/govmomi/vim25/methods" "github.com/vmware/govmomi/vim25/mo" "github.com/vmware/govmomi/vim25/soap" @@ -38,12 +28,19 @@ func (m *DatastoreNamespaceManager) ConvertNamespacePathToUuidPath(ctx *Context, return body } - dc := ctx.Map.Get(*req.Datacenter).(*Datacenter) + dc, ok := ctx.Map.Get(*req.Datacenter).(*Datacenter) + if !ok { + body.Fault_ = Fault("", &types.ManagedObjectNotFound{Obj: *req.Datacenter}) + return body + } var ds *Datastore + ns := "" + for _, ref := range dc.Datastore { ds = ctx.Map.Get(ref).(*Datastore) - if strings.HasPrefix(req.NamespaceUrl, ds.Summary.Url) { + ns = strings.TrimPrefix(req.NamespaceUrl, ds.Summary.Url) + if ns != req.NamespaceUrl { break } ds = nil @@ -60,8 +57,119 @@ func (m *DatastoreNamespaceManager) ConvertNamespacePathToUuidPath(ctx *Context, } body.Res = &types.ConvertNamespacePathToUuidPathResponse{ - Returnval: req.NamespaceUrl, + Returnval: ds.resolve(ctx, ns), } return body } + +func (m *DatastoreNamespaceManager) CreateDirectory(ctx *Context, req *types.CreateDirectory) soap.HasFault { + body := new(methods.CreateDirectoryBody) + + ds, ok := ctx.Map.Get(req.Datastore).(*Datastore) + if !ok { + body.Fault_ = Fault("", &types.ManagedObjectNotFound{Obj: req.Datastore}) + return body + } + + if !internal.IsDatastoreVSAN(ds.Datastore) { + body.Fault_ = Fault("", &types.CannotCreateFile{ + FileFault: types.FileFault{ + File: "Datastore not supported for directory creation by DatastoreNamespaceManager", + }, + }) + return body + } + + if !isValidFileName(req.DisplayName) { + body.Fault_ = Fault("", &types.InvalidDatastorePath{DatastorePath: req.DisplayName}) + return body + } + + p := object.DatastorePath{ + Datastore: ds.Name, + Path: req.DisplayName, + } + + dc := ctx.Map.getEntityDatacenter(ds) + + fm := ctx.Map.FileManager() + + fault := fm.MakeDirectory(ctx, &types.MakeDirectory{ + This: fm.Self, + Name: p.String(), + Datacenter: &dc.Self, + }) + + if fault.Fault() != nil { + body.Fault_ = fault.Fault() + } else { + body.Res = &types.CreateDirectoryResponse{ + Returnval: ds.resolve(ctx, req.DisplayName), + } + } + + return body +} + +func (m *DatastoreNamespaceManager) DeleteDirectory(ctx *Context, req *types.DeleteDirectory) soap.HasFault { + body := new(methods.DeleteDirectoryBody) + + if req.Datacenter == nil { + body.Fault_ = Fault("", &types.InvalidArgument{InvalidProperty: "datacenterRef"}) + return body + } + + dc, ok := ctx.Map.Get(*req.Datacenter).(*Datacenter) + if !ok { + body.Fault_ = Fault("", &types.ManagedObjectNotFound{Obj: *req.Datacenter}) + return body + } + + var ds *Datastore + for _, ref := range dc.Datastore { + ds = ctx.Map.Get(ref).(*Datastore) + if strings.HasPrefix(req.DatastorePath, ds.Summary.Url) { + break + } + ds = nil + } + + if ds == nil || strings.Contains(req.DatastorePath, "..") { + body.Fault_ = Fault("", &types.InvalidDatastorePath{DatastorePath: req.DatastorePath}) + return body + } + + if !internal.IsDatastoreVSAN(ds.Datastore) { + body.Fault_ = Fault("", &types.FileFault{ + File: "Datastore not supported for directory deletion by DatastoreNamespaceManager", + }) + return body + } + + name := &object.DatastorePath{ + Datastore: ds.Name, + Path: path.Base(req.DatastorePath), + } + + fm := ctx.Map.FileManager() + + fault := fm.deleteDatastoreFile(ctx, &types.DeleteDatastoreFile_Task{ + Name: name.String(), + Datacenter: req.Datacenter, + }) + + if fault != nil { + body.Fault_ = Fault("", fault) + } else { + body.Res = new(types.DeleteDirectoryResponse) + } + + return body +} + +func isValidFileName(s string) bool { + return !strings.Contains(s, "/") && + !strings.Contains(s, "\\") && + !strings.Contains(s, "..") +} diff --git a/vendor/github.com/vmware/govmomi/simulator/dvs.go b/vendor/github.com/vmware/govmomi/simulator/dvs.go index 45de0c3861..50413ea6d6 100644 --- a/vendor/github.com/vmware/govmomi/simulator/dvs.go +++ b/vendor/github.com/vmware/govmomi/simulator/dvs.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -44,10 +32,10 @@ func (s *DistributedVirtualSwitch) eventArgument() *types.DvsEventArgument { } } -func (s *DistributedVirtualSwitch) event() types.DvsEvent { +func (s *DistributedVirtualSwitch) event(ctx *Context) types.DvsEvent { return types.DvsEvent{ Event: types.Event{ - Datacenter: datacenterEventArgument(s), + Datacenter: datacenterEventArgument(ctx, s), Dvs: s.eventArgument(), }, } @@ -165,7 +153,7 @@ func (s *DistributedVirtualSwitch) AddDVPortgroupTask(ctx *Context, c *types.Add ctx.Map.AppendReference(ctx, host, &host.Network, pg.Reference()) parent := ctx.Map.Get(*host.HostSystem.Parent) - computeNetworks := append(hostParent(&host.HostSystem).Network, pg.Reference()) + computeNetworks := append(hostParent(ctx, &host.HostSystem).Network, pg.Reference()) ctx.Update(parent, []types.PropertyChange{ {Name: "network", Val: computeNetworks}, }) @@ -228,7 +216,7 @@ func (s *DistributedVirtualSwitch) ReconfigureDvsTask(ctx *Context, req *types.R {Name: "host", Val: pgHosts}, }) - cr := hostParent(&host.HostSystem) + cr := hostParent(ctx, &host.HostSystem) if FindReference(cr.Network, ref) == nil { computeNetworks := append(cr.Network, ref) ctx.Update(parent, []types.PropertyChange{ @@ -238,7 +226,7 @@ func (s *DistributedVirtualSwitch) ReconfigureDvsTask(ctx *Context, req *types.R } ctx.postEvent(&types.DvsHostJoinedEvent{ - DvsEvent: s.event(), + DvsEvent: s.event(ctx), HostJoined: *host.eventArgument(), }) case types.ConfigSpecOperationRemove: @@ -255,7 +243,7 @@ func (s *DistributedVirtualSwitch) ReconfigureDvsTask(ctx *Context, req *types.R RemoveReference(&members, member.Host) ctx.postEvent(&types.DvsHostLeftEvent{ - DvsEvent: s.event(), + DvsEvent: s.event(ctx), HostLeft: *host.eventArgument(), }) case types.ConfigSpecOperationEdit: @@ -268,7 +256,7 @@ func (s *DistributedVirtualSwitch) ReconfigureDvsTask(ctx *Context, req *types.R }) ctx.postEvent(&types.DvsReconfiguredEvent{ - DvsEvent: s.event(), + DvsEvent: s.event(ctx), ConfigSpec: spec, }) @@ -282,10 +270,10 @@ func (s *DistributedVirtualSwitch) ReconfigureDvsTask(ctx *Context, req *types.R } } -func (s *DistributedVirtualSwitch) FetchDVPorts(req *types.FetchDVPorts) soap.HasFault { +func (s *DistributedVirtualSwitch) FetchDVPorts(ctx *Context, req *types.FetchDVPorts) soap.HasFault { body := &methods.FetchDVPortsBody{} body.Res = &types.FetchDVPortsResponse{ - Returnval: s.dvPortgroups(req.Criteria), + Returnval: s.dvPortgroups(ctx, req.Criteria), } return body } @@ -296,7 +284,7 @@ func (s *DistributedVirtualSwitch) DestroyTask(ctx *Context, req *types.Destroy_ // and past that, remove refs from each host.Network, etc f := ctx.Map.getEntityParent(s, "Folder").(*Folder) folderRemoveChild(ctx, &f.Folder, s.Reference()) - ctx.postEvent(&types.DvsDestroyedEvent{DvsEvent: s.event()}) + ctx.postEvent(&types.DvsDestroyedEvent{DvsEvent: s.event(ctx)}) return nil, nil }) @@ -307,14 +295,14 @@ func (s *DistributedVirtualSwitch) DestroyTask(ctx *Context, req *types.Destroy_ } } -func (s *DistributedVirtualSwitch) dvPortgroups(criteria *types.DistributedVirtualSwitchPortCriteria) []types.DistributedVirtualPort { +func (s *DistributedVirtualSwitch) dvPortgroups(ctx *Context, criteria *types.DistributedVirtualSwitchPortCriteria) []types.DistributedVirtualPort { res := s.FetchDVPortsResponse.Returnval if len(res) != 0 { return res } for _, ref := range s.Portgroup { - pg := Map.Get(ref).(*DistributedVirtualPortgroup) + pg := ctx.Map.Get(ref).(*DistributedVirtualPortgroup) for _, key := range pg.PortKeys { res = append(res, types.DistributedVirtualPort{ diff --git a/vendor/github.com/vmware/govmomi/simulator/environment_browser.go b/vendor/github.com/vmware/govmomi/simulator/environment_browser.go index 008fedbbe3..9026706f51 100644 --- a/vendor/github.com/vmware/govmomi/simulator/environment_browser.go +++ b/vendor/github.com/vmware/govmomi/simulator/environment_browser.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2019-2023 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -41,7 +29,7 @@ func newEnvironmentBrowser( env := new(EnvironmentBrowser) env.initDescriptorReturnVal(ctx, hostRefs...) - Map.Put(env) + ctx.Map.Put(env) return &env.Self } diff --git a/vendor/github.com/vmware/govmomi/simulator/esx/datacenter.go b/vendor/github.com/vmware/govmomi/simulator/esx/datacenter.go index 374cd9518c..412c4c2916 100644 --- a/vendor/github.com/vmware/govmomi/simulator/esx/datacenter.go +++ b/vendor/github.com/vmware/govmomi/simulator/esx/datacenter.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2023 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package esx @@ -50,9 +38,7 @@ var Datacenter = mo.Datacenter{ HostFolder: types.ManagedObjectReference{Type: "Folder", Value: "ha-folder-host"}, DatastoreFolder: types.ManagedObjectReference{Type: "Folder", Value: "ha-folder-datastore"}, NetworkFolder: types.ManagedObjectReference{Type: "Folder", Value: "ha-folder-network"}, - Datastore: []types.ManagedObjectReference{ - {Type: "Datastore", Value: "57089c25-85e3ccd4-17b6-000c29d0beb3"}, - }, + Datastore: nil, Network: []types.ManagedObjectReference{ {Type: "Network", Value: "HaNetwork-VM Network"}, }, diff --git a/vendor/github.com/vmware/govmomi/simulator/file_manager.go b/vendor/github.com/vmware/govmomi/simulator/file_manager.go index 161ebf73f8..4cb23ab209 100644 --- a/vendor/github.com/vmware/govmomi/simulator/file_manager.go +++ b/vendor/github.com/vmware/govmomi/simulator/file_manager.go @@ -1,25 +1,12 @@ -/* -Copyright (c) 2017 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator import ( "io" "os" - "path" "path/filepath" "github.com/vmware/govmomi/simulator/esx" @@ -33,7 +20,7 @@ type FileManager struct { mo.FileManager } -func (f *FileManager) findDatastore(ref mo.Reference, name string) (*Datastore, types.BaseMethodFault) { +func (f *FileManager) findDatastore(ctx *Context, ref mo.Reference, name string) (*Datastore, types.BaseMethodFault) { var refs []types.ManagedObjectReference if d, ok := asFolderMO(ref); ok { @@ -44,19 +31,19 @@ func (f *FileManager) findDatastore(ref mo.Reference, name string) (*Datastore, } for _, ref := range refs { - obj := Map.Get(ref) + obj := ctx.Map.Get(ref) if ds, ok := obj.(*Datastore); ok && ds.Name == name { return ds, nil } if p, ok := obj.(*StoragePod); ok { - ds, _ := f.findDatastore(p, name) + ds, _ := f.findDatastore(ctx, p, name) if ds != nil { return ds, nil } } if d, ok := asFolderMO(obj); ok { - ds, _ := f.findDatastore(d, name) + ds, _ := f.findDatastore(ctx, d, name) if ds != nil { return ds, nil } @@ -66,30 +53,28 @@ func (f *FileManager) findDatastore(ref mo.Reference, name string) (*Datastore, return nil, &types.InvalidDatastore{Name: name} } -func (f *FileManager) resolve(dc *types.ManagedObjectReference, name string) (string, types.BaseMethodFault) { +func (f *FileManager) resolve(ctx *Context, dc *types.ManagedObjectReference, name string, remove ...bool) (string, types.BaseMethodFault) { p, fault := parseDatastorePath(name) if fault != nil { return "", fault } if dc == nil { - if Map.IsESX() { + if ctx.Map.IsESX() { dc = &esx.Datacenter.Self } else { return "", &types.InvalidArgument{InvalidProperty: "dc"} } } - folder := Map.Get(*dc).(*Datacenter).DatastoreFolder + folder := ctx.Map.Get(*dc).(*Datacenter).DatastoreFolder - ds, fault := f.findDatastore(Map.Get(folder), p.Datastore) + ds, fault := f.findDatastore(ctx, ctx.Map.Get(folder), p.Datastore) if fault != nil { return "", fault } - dir := ds.Info.GetDatastoreInfo().Url - - return path.Join(dir, p.Path), nil + return ds.resolve(ctx, p.Path, remove...), nil } func (f *FileManager) fault(name string, err error, fault types.BaseFileFault) types.BaseMethodFault { @@ -105,8 +90,8 @@ func (f *FileManager) fault(name string, err error, fault types.BaseFileFault) t return fault.(types.BaseMethodFault) } -func (f *FileManager) deleteDatastoreFile(req *types.DeleteDatastoreFile_Task) types.BaseMethodFault { - file, fault := f.resolve(req.Datacenter, req.Name) +func (f *FileManager) deleteDatastoreFile(ctx *Context, req *types.DeleteDatastoreFile_Task) types.BaseMethodFault { + file, fault := f.resolve(ctx, req.Datacenter, req.Name, true) if fault != nil { return fault } @@ -128,7 +113,7 @@ func (f *FileManager) deleteDatastoreFile(req *types.DeleteDatastoreFile_Task) t func (f *FileManager) DeleteDatastoreFileTask(ctx *Context, req *types.DeleteDatastoreFile_Task) soap.HasFault { task := CreateTask(f, "deleteDatastoreFile", func(*Task) (types.AnyType, types.BaseMethodFault) { - return nil, f.deleteDatastoreFile(req) + return nil, f.deleteDatastoreFile(ctx, req) }) return &methods.DeleteDatastoreFile_TaskBody{ @@ -138,10 +123,10 @@ func (f *FileManager) DeleteDatastoreFileTask(ctx *Context, req *types.DeleteDat } } -func (f *FileManager) MakeDirectory(req *types.MakeDirectory) soap.HasFault { +func (f *FileManager) MakeDirectory(ctx *Context, req *types.MakeDirectory) soap.HasFault { body := &methods.MakeDirectoryBody{} - name, fault := f.resolve(req.Datacenter, req.Name) + name, fault := f.resolve(ctx, req.Datacenter, req.Name) if fault != nil { body.Fault_ = Fault("", fault) return body @@ -164,13 +149,13 @@ func (f *FileManager) MakeDirectory(req *types.MakeDirectory) soap.HasFault { return body } -func (f *FileManager) moveDatastoreFile(req *types.MoveDatastoreFile_Task) types.BaseMethodFault { - src, fault := f.resolve(req.SourceDatacenter, req.SourceName) +func (f *FileManager) moveDatastoreFile(ctx *Context, req *types.MoveDatastoreFile_Task) types.BaseMethodFault { + src, fault := f.resolve(ctx, req.SourceDatacenter, req.SourceName) if fault != nil { return fault } - dst, fault := f.resolve(req.DestinationDatacenter, req.DestinationName) + dst, fault := f.resolve(ctx, req.DestinationDatacenter, req.DestinationName) if fault != nil { return fault } @@ -192,7 +177,7 @@ func (f *FileManager) moveDatastoreFile(req *types.MoveDatastoreFile_Task) types func (f *FileManager) MoveDatastoreFileTask(ctx *Context, req *types.MoveDatastoreFile_Task) soap.HasFault { task := CreateTask(f, "moveDatastoreFile", func(*Task) (types.AnyType, types.BaseMethodFault) { - return nil, f.moveDatastoreFile(req) + return nil, f.moveDatastoreFile(ctx, req) }) return &methods.MoveDatastoreFile_TaskBody{ @@ -202,13 +187,13 @@ func (f *FileManager) MoveDatastoreFileTask(ctx *Context, req *types.MoveDatasto } } -func (f *FileManager) copyDatastoreFile(req *types.CopyDatastoreFile_Task) types.BaseMethodFault { - src, fault := f.resolve(req.SourceDatacenter, req.SourceName) +func (f *FileManager) copyDatastoreFile(ctx *Context, req *types.CopyDatastoreFile_Task) types.BaseMethodFault { + src, fault := f.resolve(ctx, req.SourceDatacenter, req.SourceName) if fault != nil { return fault } - dst, fault := f.resolve(req.DestinationDatacenter, req.DestinationName) + dst, fault := f.resolve(ctx, req.DestinationDatacenter, req.DestinationName) if fault != nil { return fault } @@ -241,7 +226,7 @@ func (f *FileManager) copyDatastoreFile(req *types.CopyDatastoreFile_Task) types func (f *FileManager) CopyDatastoreFileTask(ctx *Context, req *types.CopyDatastoreFile_Task) soap.HasFault { task := CreateTask(f, "copyDatastoreFile", func(*Task) (types.AnyType, types.BaseMethodFault) { - return nil, f.copyDatastoreFile(req) + return nil, f.copyDatastoreFile(ctx, req) }) return &methods.CopyDatastoreFile_TaskBody{ diff --git a/vendor/github.com/vmware/govmomi/simulator/folder.go b/vendor/github.com/vmware/govmomi/simulator/folder.go index 9eb19c7eea..6ce09f2592 100644 --- a/vendor/github.com/vmware/govmomi/simulator/folder.go +++ b/vendor/github.com/vmware/govmomi/simulator/folder.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -312,7 +300,7 @@ func (f *Folder) CreateDatacenter(ctx *Context, c *types.CreateDatacenter) soap. ctx.postEvent(&types.DatacenterCreatedEvent{ DatacenterEvent: types.DatacenterEvent{ Event: types.Event{ - Datacenter: datacenterEventArgument(dc), + Datacenter: datacenterEventArgument(ctx, dc), }, }, Parent: folderEventArgument(&f.Folder), @@ -354,14 +342,14 @@ type createVM struct { } // hostsWithDatastore returns hosts that have access to the given datastore path -func hostsWithDatastore(hosts []types.ManagedObjectReference, path string) []types.ManagedObjectReference { +func hostsWithDatastore(ctx *Context, hosts []types.ManagedObjectReference, path string) []types.ManagedObjectReference { attached := hosts[:0] var p object.DatastorePath p.FromString(path) for _, host := range hosts { - h := Map.Get(host).(*HostSystem) - if Map.FindByName(p.Datastore, h.Datastore) != nil { + h := ctx.Map.Get(host).(*HostSystem) + if ctx.Map.FindByName(p.Datastore, h.Datastore) != nil { attached = append(attached, host) } } @@ -397,7 +385,7 @@ func (c *createVM) Run(task *Task) (types.AnyType, types.BaseMethodFault) { hosts = cr.Host } - hosts = hostsWithDatastore(hosts, c.req.Config.Files.VmPathName) + hosts = hostsWithDatastore(c.ctx, hosts, c.req.Config.Files.VmPathName) host := hosts[rand.Intn(len(hosts))] vm.Runtime.Host = &host }) @@ -451,7 +439,7 @@ func (c *createVM) Run(task *Task) (types.AnyType, types.BaseMethodFault) { host := c.ctx.Map.Get(*vm.Runtime.Host).(*HostSystem) c.ctx.Map.AppendReference(c.ctx, host, &host.Vm, vm.Self) - vm.EnvironmentBrowser = *hostParent(&host.HostSystem).EnvironmentBrowser + vm.EnvironmentBrowser = *hostParent(task.ctx, &host.HostSystem).EnvironmentBrowser for i := range vm.Datastore { ds := c.ctx.Map.Get(vm.Datastore[i]).(*Datastore) @@ -469,7 +457,7 @@ func (c *createVM) Run(task *Task) (types.AnyType, types.BaseMethodFault) { } }) - event := vm.event() + event := vm.event(c.ctx) c.ctx.postEvent( &types.VmBeingCreatedEvent{ VmEvent: event, @@ -523,7 +511,7 @@ func (c *registerVM) Run(task *Task) (types.AnyType, types.BaseMethodFault) { return nil, &types.InvalidArgument{InvalidProperty: "pool"} } - pool = hostParent(&c.ctx.Map.Get(*host).(*HostSystem).HostSystem).ResourcePool + pool = hostParent(c.ctx, &c.ctx.Map.Get(*host).(*HostSystem).HostSystem).ResourcePool } else { if pool == nil { return nil, &types.InvalidArgument{InvalidProperty: "pool"} @@ -535,7 +523,7 @@ func (c *registerVM) Run(task *Task) (types.AnyType, types.BaseMethodFault) { } s := c.ctx.Map.SearchIndex() - r := s.FindByDatastorePath(&types.FindByDatastorePath{ + r := s.FindByDatastorePath(c.ctx, &types.FindByDatastorePath{ This: s.Reference(), Path: c.req.Path, Datacenter: c.ctx.Map.getEntityDatacenter(c.Folder).Reference(), @@ -684,7 +672,7 @@ func (f *Folder) CreateDVSTask(ctx *Context, req *types.CreateDVS_Task) soap.Has } ctx.postEvent(&types.DvsCreatedEvent{ - DvsEvent: dvs.event(), + DvsEvent: dvs.event(ctx), Parent: folderEventArgument(&f.Folder), }) @@ -943,7 +931,7 @@ func generateRecommendationForReconfigure(ctx *Context, req *types.PlaceVmsXClus vm := vmRef.(*VirtualMachine) // Use VM's current host - host := Map.Get(vm.Runtime.Host.Reference()).(*HostSystem) + host := ctx.Map.Get(vm.Runtime.Host.Reference()).(*HostSystem) if host.Parent.Type != "ClusterComputeResource" { addPlacementFault(body, spec.ConfigSpec.Name, &vm.Self, host.Self) diff --git a/vendor/github.com/vmware/govmomi/simulator/host_certificate_manager.go b/vendor/github.com/vmware/govmomi/simulator/host_certificate_manager.go index 5e6a5fdc4c..c5def3acaf 100644 --- a/vendor/github.com/vmware/govmomi/simulator/host_certificate_manager.go +++ b/vendor/github.com/vmware/govmomi/simulator/host_certificate_manager.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2024-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -47,10 +35,10 @@ func (m *HostCertificateManager) init(r *Registry) { } } -func NewHostCertificateManager(h *mo.HostSystem) *HostCertificateManager { +func NewHostCertificateManager(ctx *Context, h *mo.HostSystem) *HostCertificateManager { m := &HostCertificateManager{Host: h} - _ = m.InstallServerCertificate(SpoofContext(), &types.InstallServerCertificate{ + _ = m.InstallServerCertificate(ctx, &types.InstallServerCertificate{ Cert: string(m.Host.Config.Certificate), }) diff --git a/vendor/github.com/vmware/govmomi/simulator/host_datastore_browser.go b/vendor/github.com/vmware/govmomi/simulator/host_datastore_browser.go index 4725203163..b3eb9914e6 100644 --- a/vendor/github.com/vmware/govmomi/simulator/host_datastore_browser.go +++ b/vendor/github.com/vmware/govmomi/simulator/host_datastore_browser.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -21,6 +9,7 @@ import ( "path" "strings" + "github.com/vmware/govmomi/internal" "github.com/vmware/govmomi/vim25/methods" "github.com/vmware/govmomi/vim25/mo" "github.com/vmware/govmomi/vim25/soap" @@ -42,7 +31,7 @@ type searchDatastore struct { recurse bool } -func (s *searchDatastore) addFile(file os.FileInfo, res *types.HostDatastoreBrowserSearchResults) { +func (s *searchDatastore) addFile(fname string, file os.FileInfo, res *types.HostDatastoreBrowserSearchResults) { details := s.SearchSpec.Details if details == nil { details = new(types.FileQueryFlags) @@ -51,7 +40,8 @@ func (s *searchDatastore) addFile(file os.FileInfo, res *types.HostDatastoreBrow name := file.Name() info := types.FileInfo{ - Path: name, + Path: name, + FriendlyName: fname, } var finfo types.BaseFileInfo = &info @@ -147,7 +137,28 @@ func (s *searchDatastore) queryMatch(file os.FileInfo) bool { return false } -func (s *searchDatastore) search(ds *types.ManagedObjectReference, folder string, dir string) error { +func friendlyName(ctx *Context, root bool, ds *Datastore, p string) string { + if !root || p == "" || !internal.IsDatastoreVSAN(ds.Datastore) { + return "" + } + + unlock := ctx.Map.AcquireLock(ctx, ds.Self) + defer unlock() + + if ds.namespace == nil { + return "" + } + + for name, id := range ds.namespace { + if p == id { + return name + } + } + + return "" +} + +func (s *searchDatastore) search(ctx *Context, ds *Datastore, folder string, dir string, root bool) error { files, err := os.ReadDir(dir) if err != nil { tracef("search %s: %s", dir, err) @@ -155,7 +166,7 @@ func (s *searchDatastore) search(ds *types.ManagedObjectReference, folder string } res := types.HostDatastoreBrowserSearchResults{ - Datastore: ds, + Datastore: &ds.Self, FolderPath: folder, } @@ -165,14 +176,14 @@ func (s *searchDatastore) search(ds *types.ManagedObjectReference, folder string if s.queryMatch(info) { for _, m := range s.SearchSpec.MatchPattern { if ok, _ := path.Match(m, name); ok { - s.addFile(info, &res) + s.addFile(friendlyName(ctx, root, ds, name), info, &res) break } } } if s.recurse && file.IsDir() { - _ = s.search(ds, path.Join(folder, name), path.Join(dir, name)) + _ = s.search(ctx, ds, path.Join(folder, name), path.Join(dir, name), false) } } @@ -187,22 +198,21 @@ func (s *searchDatastore) Run(task *Task) (types.AnyType, types.BaseMethodFault) return nil, fault } - ref := Map.FindByName(p.Datastore, s.Datastore) + ref := task.ctx.Map.FindByName(p.Datastore, s.Datastore) if ref == nil { return nil, &types.InvalidDatastore{Name: p.Datastore} } ds := ref.(*Datastore) - isolatedLockContext := &Context{} // we don't need/want to share the task lock - Map.WithLock(isolatedLockContext, task, func() { + task.ctx.WithLock(task, func() { task.Info.Entity = &ds.Self // TODO: CreateTask() should require mo.Entity, rather than mo.Reference task.Info.EntityName = ds.Name }) - dir := path.Join(ds.Info.GetDatastoreInfo().Url, p.Path) + dir := ds.resolve(task.ctx, p.Path) - err := s.search(&ds.Self, s.DatastorePath, dir) + err := s.search(task.ctx, ds, s.DatastorePath, dir, p.Path == "") if err != nil { ff := types.FileFault{ File: p.Path, diff --git a/vendor/github.com/vmware/govmomi/simulator/host_datastore_system.go b/vendor/github.com/vmware/govmomi/simulator/host_datastore_system.go index da6436917d..f7657417ad 100644 --- a/vendor/github.com/vmware/govmomi/simulator/host_datastore_system.go +++ b/vendor/github.com/vmware/govmomi/simulator/host_datastore_system.go @@ -1,26 +1,16 @@ -/* -Copyright (c) 2017 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator import ( + "fmt" "os" "path" - "github.com/vmware/govmomi/units" + "github.com/google/uuid" + "github.com/vmware/govmomi/vim25/methods" "github.com/vmware/govmomi/vim25/mo" "github.com/vmware/govmomi/vim25/soap" @@ -33,6 +23,16 @@ type HostDatastoreSystem struct { Host *mo.HostSystem } +var defaultDatastoreCapability = types.DatastoreCapability{ + DirectoryHierarchySupported: true, + RawDiskMappingsSupported: false, + PerFileThinProvisioningSupported: true, + StorageIORMSupported: types.NewBool(false), + NativeSnapshotSupported: types.NewBool(false), + SeSparseSupported: types.NewBool(false), + TopLevelDirectoryCreateSupported: types.NewBool(true), +} + func (dss *HostDatastoreSystem) add(ctx *Context, ds *Datastore) *soap.Fault { info := ds.Info.GetDatastoreInfo() @@ -72,28 +72,30 @@ func (dss *HostDatastoreSystem) add(ctx *Context, ds *Datastore) *soap.Fault { // if datastore already exists, use current reference found = true - ds.Self = e.Reference() + ds = e.(*Datastore) } else { + ds.Summary.Datastore = &ds.Self + ds.Summary.Name = ds.Name + ds.Summary.Url = info.Url + // put datastore to folder and generate reference folderPutChild(ctx, folder, ds) } - ds.Summary.Datastore = &ds.Self - ds.Summary.Name = ds.Name - ds.Summary.Url = info.Url - ds.Capability = types.DatastoreCapability{ - DirectoryHierarchySupported: true, - RawDiskMappingsSupported: false, - PerFileThinProvisioningSupported: true, - StorageIORMSupported: types.NewBool(true), - NativeSnapshotSupported: types.NewBool(false), - TopLevelDirectoryCreateSupported: types.NewBool(true), - SeSparseSupported: types.NewBool(true), - } + ds.Host = append(ds.Host, types.DatastoreHostMount{ + Key: dss.Host.Reference(), + MountInfo: types.HostMountInfo{ + AccessMode: string(types.HostMountModeReadWrite), + Mounted: types.NewBool(true), + Accessible: types.NewBool(true), + }, + }) + + _ = ds.RefreshDatastore(ctx, &types.RefreshDatastore{This: ds.Self}) dss.Datastore = append(dss.Datastore, ds.Self) dss.Host.Datastore = dss.Datastore - parent := hostParent(dss.Host) + parent := hostParent(ctx, dss.Host) ctx.Map.AddReference(ctx, parent, &parent.Datastore, ds.Self) // NOTE: browser must be created after ds is appended to dss.Datastore @@ -101,13 +103,6 @@ func (dss *HostDatastoreSystem) add(ctx *Context, ds *Datastore) *soap.Fault { browser := &HostDatastoreBrowser{} browser.Datastore = dss.Datastore ds.Browser = ctx.Map.Put(browser).Reference() - - ds.Summary.Capacity = int64(units.TB * 10) - ds.Summary.FreeSpace = ds.Summary.Capacity - - info.FreeSpace = ds.Summary.FreeSpace - info.MaxMemoryFileSize = ds.Summary.Capacity - info.MaxFileSize = ds.Summary.Capacity } return nil @@ -130,23 +125,13 @@ func (dss *HostDatastoreSystem) CreateLocalDatastore(ctx *Context, c *types.Crea ds.Summary.Type = string(types.HostFileSystemVolumeFileSystemTypeOTHER) ds.Summary.MaintenanceMode = string(types.DatastoreSummaryMaintenanceModeStateNormal) ds.Summary.Accessible = true + ds.Capability = defaultDatastoreCapability if err := dss.add(ctx, ds); err != nil { r.Fault_ = err return r } - ds.Host = append(ds.Host, types.DatastoreHostMount{ - Key: dss.Host.Reference(), - MountInfo: types.HostMountInfo{ - AccessMode: string(types.HostMountModeReadWrite), - Mounted: types.NewBool(true), - Accessible: types.NewBool(true), - }, - }) - - _ = ds.RefreshDatastore(&types.RefreshDatastore{This: ds.Self}) - r.Res = &types.CreateLocalDatastoreResponse{ Returnval: ds.Self, } @@ -193,17 +178,48 @@ func (dss *HostDatastoreSystem) CreateNasDatastore(ctx *Context, c *types.Create ds.Summary.Type = c.Spec.Type ds.Summary.MaintenanceMode = string(types.DatastoreSummaryMaintenanceModeStateNormal) ds.Summary.Accessible = true + ds.Capability = defaultDatastoreCapability if err := dss.add(ctx, ds); err != nil { r.Fault_ = err return r } - _ = ds.RefreshDatastore(&types.RefreshDatastore{This: ds.Self}) - r.Res = &types.CreateNasDatastoreResponse{ Returnval: ds.Self, } return r } + +func (dss *HostDatastoreSystem) createVsanDatastore(ctx *Context) types.BaseMethodFault { + ds := &Datastore{} + ds.Name = "vsanDatastore" + + home := ctx.Map.OptionManager().find("vcsim.home").Value + dc := ctx.Map.getEntityDatacenter(dss.Host) + url := fmt.Sprintf("%s/%s-%s", home, dc.Name, ds.Name) + if err := os.MkdirAll(url, 0700); err != nil { + return ctx.Map.FileManager().fault(url, err, new(types.CannotAccessFile)) + } + + ds.Info = &types.VsanDatastoreInfo{ + DatastoreInfo: types.DatastoreInfo{ + Name: ds.Name, + Url: url, + }, + MembershipUuid: uuid.NewString(), + } + + ds.Summary.Type = string(types.HostFileSystemVolumeFileSystemTypeVsan) + ds.Summary.MaintenanceMode = string(types.DatastoreSummaryMaintenanceModeStateNormal) + ds.Summary.Accessible = true + ds.Capability = defaultDatastoreCapability + ds.Capability.TopLevelDirectoryCreateSupported = types.NewBool(false) + + if err := dss.add(ctx, ds); err != nil { + return err.Detail.Fault.(types.BaseMethodFault) + } + + return nil +} diff --git a/vendor/github.com/vmware/govmomi/simulator/host_local_account_manager.go b/vendor/github.com/vmware/govmomi/simulator/host_local_account_manager.go index 993e3fe879..6733b1bbd7 100644 --- a/vendor/github.com/vmware/govmomi/simulator/host_local_account_manager.go +++ b/vendor/github.com/vmware/govmomi/simulator/host_local_account_manager.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -29,9 +17,9 @@ type HostLocalAccountManager struct { mo.HostLocalAccountManager } -func (h *HostLocalAccountManager) CreateUser(req *types.CreateUser) soap.HasFault { +func (h *HostLocalAccountManager) CreateUser(ctx *Context, req *types.CreateUser) soap.HasFault { spec := req.User.GetHostAccountSpec() - userDirectory := Map.UserDirectory() + userDirectory := ctx.Map.UserDirectory() found := userDirectory.search(true, false, compareFunc(spec.Id, true)) if len(found) > 0 { @@ -47,8 +35,8 @@ func (h *HostLocalAccountManager) CreateUser(req *types.CreateUser) soap.HasFaul } } -func (h *HostLocalAccountManager) RemoveUser(req *types.RemoveUser) soap.HasFault { - userDirectory := Map.UserDirectory() +func (h *HostLocalAccountManager) RemoveUser(ctx *Context, req *types.RemoveUser) soap.HasFault { + userDirectory := ctx.Map.UserDirectory() found := userDirectory.search(true, false, compareFunc(req.UserName, true)) diff --git a/vendor/github.com/vmware/govmomi/simulator/host_network_system.go b/vendor/github.com/vmware/govmomi/simulator/host_network_system.go index 351604f82b..ffb2e9ef6c 100644 --- a/vendor/github.com/vmware/govmomi/simulator/host_network_system.go +++ b/vendor/github.com/vmware/govmomi/simulator/host_network_system.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -58,9 +46,9 @@ func (s *HostNetworkSystem) init(r *Registry) { } } -func (s *HostNetworkSystem) folder() *Folder { - f := Map.getEntityDatacenter(s.Host).NetworkFolder - return Map.Get(f).(*Folder) +func (s *HostNetworkSystem) folder(ctx *Context) *Folder { + f := ctx.Map.getEntityDatacenter(s.Host).NetworkFolder + return ctx.Map.Get(f).(*Folder) } func (s *HostNetworkSystem) AddVirtualSwitch(c *types.AddVirtualSwitch) soap.HasFault { @@ -126,7 +114,7 @@ func (s *HostNetworkSystem) AddPortGroup(ctx *Context, c *types.AddPortGroup) so network.Name = c.Portgrp.Name network.Entity().Name = network.Name - folder := s.folder() + folder := s.folder(ctx) if obj := ctx.Map.FindByName(c.Portgrp.Name, folder.ChildEntity); obj != nil { r.Fault_ = Fault("", &types.DuplicateName{ @@ -171,7 +159,7 @@ func (s *HostNetworkSystem) RemovePortGroup(ctx *Context, c *types.RemovePortGro return r } - folder := s.folder() + folder := s.folder(ctx) e := ctx.Map.FindByName(c.PgName, folder.ChildEntity) folderRemoveChild(ctx, &folder.Folder, e.Reference()) diff --git a/vendor/github.com/vmware/govmomi/simulator/host_system.go b/vendor/github.com/vmware/govmomi/simulator/host_system.go index e9432b18a5..36f1895d96 100644 --- a/vendor/github.com/vmware/govmomi/simulator/host_system.go +++ b/vendor/github.com/vmware/govmomi/simulator/host_system.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -53,7 +41,7 @@ func asHostSystemMO(obj mo.Reference) (*mo.HostSystem, bool) { return h, ok } -func NewHostSystem(host mo.HostSystem) *HostSystem { +func NewHostSystem(ctx *Context, host mo.HostSystem) *HostSystem { if hostPortUnique { // configure unique port for each host port := &esx.HostSystem.Summary.Config.Port *port++ @@ -108,11 +96,11 @@ func NewHostSystem(host mo.HostSystem) *HostSystem { {&hs.ConfigManager.AdvancedOption, NewOptionManager(nil, nil, &hs.Config.Option)}, {&hs.ConfigManager.FirewallSystem, NewHostFirewallSystem(&hs.HostSystem)}, {&hs.ConfigManager.StorageSystem, NewHostStorageSystem(&hs.HostSystem)}, - {&hs.ConfigManager.CertificateManager, NewHostCertificateManager(&hs.HostSystem)}, + {&hs.ConfigManager.CertificateManager, NewHostCertificateManager(ctx, &hs.HostSystem)}, } for _, c := range config { - ref := Map.Put(c.obj).Reference() + ref := ctx.Map.Put(c.obj).Reference() *c.ref = &ref } @@ -382,11 +370,11 @@ func (h *HostSystem) getNetConfigInterface(ctx *Context, nicType string) (*netCo return details, nil } -func (h *HostSystem) event() types.HostEvent { +func (h *HostSystem) event(ctx *Context) types.HostEvent { return types.HostEvent{ Event: types.Event{ - Datacenter: datacenterEventArgument(h), - ComputeResource: h.eventArgumentParent(), + Datacenter: datacenterEventArgument(ctx, h), + ComputeResource: h.eventArgumentParent(ctx), Host: h.eventArgument(), }, } @@ -399,8 +387,8 @@ func (h *HostSystem) eventArgument() *types.HostEventArgument { } } -func (h *HostSystem) eventArgumentParent() *types.ComputeResourceEventArgument { - parent := hostParent(&h.HostSystem) +func (h *HostSystem) eventArgumentParent(ctx *Context) *types.ComputeResourceEventArgument { + parent := hostParent(ctx, &h.HostSystem) return &types.ComputeResourceEventArgument{ ComputeResource: parent.Self, @@ -408,8 +396,8 @@ func (h *HostSystem) eventArgumentParent() *types.ComputeResourceEventArgument { } } -func hostParent(host *mo.HostSystem) *mo.ComputeResource { - switch parent := Map.Get(*host.Parent).(type) { +func hostParent(ctx *Context, host *mo.HostSystem) *mo.ComputeResource { + switch parent := ctx.Map.Get(*host.Parent).(type) { case *mo.ComputeResource: return parent case *ClusterComputeResource: @@ -436,7 +424,7 @@ func addComputeResource(s *types.ComputeResourceSummary, h *HostSystem) { func CreateDefaultESX(ctx *Context, f *Folder) { dc := NewDatacenter(ctx, &f.Folder) - host := NewHostSystem(esx.HostSystem) + host := NewHostSystem(ctx, esx.HostSystem) summary := new(types.ComputeResourceSummary) addComputeResource(summary, host) @@ -452,7 +440,7 @@ func CreateDefaultESX(ctx *Context, f *Folder) { ctx.Map.PutEntity(cr, host) cr.EnvironmentBrowser = newEnvironmentBrowser(ctx, host.Reference()) - pool := NewResourcePool() + pool := NewResourcePool(ctx) cr.ResourcePool = &pool.Self ctx.Map.PutEntity(cr, pool) pool.Owner = cr.Self @@ -479,8 +467,8 @@ func CreateStandaloneHost(ctx *Context, f *Folder, spec types.HostConnectSpec) ( network = cr.Network } - pool := NewResourcePool() - host := NewHostSystem(template) + pool := NewResourcePool(ctx) + host := NewHostSystem(ctx, template) host.configure(ctx, spec, false) summary := new(types.ComputeResourceSummary) @@ -519,7 +507,7 @@ func (h *HostSystem) DestroyTask(ctx *Context, req *types.Destroy_Task) soap.Has return nil, &types.ResourceInUse{} } - ctx.postEvent(&types.HostRemovedEvent{HostEvent: h.event()}) + ctx.postEvent(&types.HostRemovedEvent{HostEvent: h.event(ctx)}) f := ctx.Map.getEntityParent(h, "Folder").(*Folder) folderRemoveChild(ctx, &f.Folder, h.Reference()) diff --git a/vendor/github.com/vmware/govmomi/simulator/license_manager.go b/vendor/github.com/vmware/govmomi/simulator/license_manager.go index 0546cf8dea..999038c3b7 100644 --- a/vendor/github.com/vmware/govmomi/simulator/license_manager.go +++ b/vendor/github.com/vmware/govmomi/simulator/license_manager.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -188,7 +176,7 @@ type LicenseAssignmentManager struct { var licensedTypes = []string{"HostSystem", "ClusterComputeResource"} // PutObject assigns a license when a host or cluster is created. -func (m *LicenseAssignmentManager) PutObject(obj mo.Reference) { +func (m *LicenseAssignmentManager) PutObject(ctx *Context, obj mo.Reference) { ref := obj.Reference() if !slices.Contains(licensedTypes, ref.Type) { @@ -204,7 +192,7 @@ func (m *LicenseAssignmentManager) PutObject(obj mo.Reference) { la := types.LicenseAssignmentManagerLicenseAssignment{ EntityId: ref.Value, - Scope: Map.content().About.InstanceUuid, + Scope: ctx.Map.content().About.InstanceUuid, EntityDisplayName: obj.(mo.Entity).Entity().Name, AssignedLicense: EvalLicense, } diff --git a/vendor/github.com/vmware/govmomi/simulator/model.go b/vendor/github.com/vmware/govmomi/simulator/model.go index e590838e64..5bcf31defa 100644 --- a/vendor/github.com/vmware/govmomi/simulator/model.go +++ b/vendor/github.com/vmware/govmomi/simulator/model.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -146,7 +134,7 @@ type Model struct { // total number of inventory objects, set by Count() total int - dirs []string + dir string } // ESX is the default Model for a standalone ESX instance @@ -186,11 +174,16 @@ func VPX() *Model { } } +// Map returns the Model.Service.Context.Map +func (m *Model) Map() *Registry { + return m.Service.Context.Map +} + // Count returns a Model with total number of each existing type func (m *Model) Count() Model { count := Model{} - for ref, obj := range Map.objects { + for ref, obj := range m.Map().objects { if _, ok := obj.(mo.Entity); !ok { continue } @@ -232,6 +225,7 @@ func (*Model) fmtName(prefix string, num int) string { // kinds maps managed object types to their vcsim wrapper types var kinds = map[string]reflect.Type{ + "Alarm": reflect.TypeOf((*Alarm)(nil)).Elem(), "AlarmManager": reflect.TypeOf((*AlarmManager)(nil)).Elem(), "AuthorizationManager": reflect.TypeOf((*AuthorizationManager)(nil)).Elem(), "ClusterComputeResource": reflect.TypeOf((*ClusterComputeResource)(nil)).Elem(), @@ -280,7 +274,7 @@ var kinds = map[string]reflect.Type{ "VmwareDistributedVirtualSwitch": reflect.TypeOf((*DistributedVirtualSwitch)(nil)).Elem(), } -func loadObject(content types.ObjectContent) (mo.Reference, error) { +func loadObject(ctx *Context, content types.ObjectContent) (mo.Reference, error) { var obj mo.Reference id := content.Obj @@ -299,7 +293,7 @@ func loadObject(content types.ObjectContent) (mo.Reference, error) { } else { if len(content.PropSet) == 0 { // via NewServiceInstance() - Map.setReference(obj, id) + ctx.Map.setReference(obj, id) } else { // via Model.Load() dst := getManagedObject(obj).Addr().Interface().(mo.Reference) @@ -310,7 +304,7 @@ func loadObject(content types.ObjectContent) (mo.Reference, error) { } if x, ok := obj.(interface{ init(*Registry) }); ok { - x.init(Map) + x.init(ctx.Map) } } @@ -345,7 +339,7 @@ func (m *Model) resolveReferences(ctx *Context) error { // object was loaded without its parent, attempt to foster with another parent switch e.Parent.Type { case "Folder": - folder := dc.folder(me) + folder := dc.folder(ctx, me) e.Parent = &folder.Self log.Printf("%s adopted %s", e.Parent, ref) folderPutChild(ctx, folder, me) @@ -399,12 +393,10 @@ func (m *Model) loadMethod(obj mo.Reference, dir string) error { return nil } -// When simulator code needs to call other simulator code, it typically passes whatever -// context is associated with the request it's servicing. -// Model code isn't servicing a request, but still needs a context, so we spoof -// one for the purposes of calling simulator code. -// Test code also tends to do this. -func SpoofContext() *Context { +// NewContext initializes a Context with a NewRegistry +func NewContext() *Context { + r := NewRegistry() + return &Context{ Context: context.Background(), Session: &Session{ @@ -412,14 +404,15 @@ func SpoofContext() *Context { Key: uuid.New().String(), }, Registry: NewRegistry(), + Map: r, }, - Map: Map, + Map: r, } } // Load Model from the given directory, as created by the 'govc object.save' command. func (m *Model) Load(dir string) error { - ctx := SpoofContext() + ctx := NewContext() var s *ServiceInstance err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { @@ -445,18 +438,15 @@ func (m *Model) Load(dir string) error { if content.Obj == vim25.ServiceInstance { s = new(ServiceInstance) s.Self = content.Obj - Map = NewRegistry() - ctx.Map = Map ctx.Map.Put(s) return mo.LoadObjectContent([]types.ObjectContent{content}, &s.ServiceInstance) } if s == nil { - s = NewServiceInstance(ctx, m.ServiceContent, m.RootFolder) - ctx.Map = Map + ctx, s = NewServiceInstance(ctx, m.ServiceContent, m.RootFolder) } - obj, err := loadObject(content) + obj, err := loadObject(ctx, content) if err != nil { return err } @@ -474,21 +464,23 @@ func (m *Model) Load(dir string) error { return err } - m.Service = New(s) + m.Service = New(ctx, s) return m.resolveReferences(ctx) } // Create populates the Model with the given ModelConfig func (m *Model) Create() error { - ctx := SpoofContext() + ctx := NewContext() m.Service = New(NewServiceInstance(ctx, m.ServiceContent, m.RootFolder)) - ctx.Map = Map + if err := m.createRootTempDir(ctx.Map.OptionManager()); err != nil { + return err + } return m.CreateInfrastructure(ctx) } func (m *Model) CreateInfrastructure(ctx *Context) error { - client := m.Service.client + client := m.Service.client() root := object.NewRootFolder(client) // After all hosts are created, this var is used to mount the host datastores. @@ -829,12 +821,25 @@ func (m *Model) CreateInfrastructure(ctx *Context) error { return nil } -func (m *Model) createTempDir(dc string, name string) (string, error) { - dir, err := os.MkdirTemp("", fmt.Sprintf("govcsim-%s-%s-", dc, name)) - if err == nil { - m.dirs = append(m.dirs, dir) +func (m *Model) createRootTempDir(opt *OptionManager) error { + var err error + + m.dir, err = os.MkdirTemp("", "govcsim-") + if err != nil { + return err } - return dir, err + + opt.Setting = append(opt.Setting, &types.OptionValue{ + Key: "vcsim.home", + Value: m.dir, + }) + + return nil +} + +func (m *Model) createTempDir(name ...string) (string, error) { + p := path.Join(m.dir, strings.Join(name, "-")) + return p, os.Mkdir(p, 0700) } func (m *Model) createLocalDatastore(dc string, name string, hosts []*object.HostSystem) error { @@ -861,24 +866,21 @@ func (m *Model) createLocalDatastore(dc string, name string, hosts []*object.Hos // Remove cleans up items created by the Model, such as local datastore directories func (m *Model) Remove() { + ctx := m.Service.Context // Remove associated vm containers, if any - Map.m.Lock() - for _, obj := range Map.objects { + ctx.Map.m.Lock() + for _, obj := range ctx.Map.objects { if vm, ok := obj.(*VirtualMachine); ok { - vm.svm.remove(SpoofContext()) + vm.svm.remove(ctx) } } - Map.m.Unlock() + ctx.Map.m.Unlock() - for _, dir := range m.dirs { - _ = os.RemoveAll(dir) - } + _ = os.RemoveAll(m.dir) } // Run calls f with a Client connected to a simulator server instance, which is stopped after f returns. func (m *Model) Run(f func(context.Context, *vim25.Client) error) error { - ctx := context.Background() - defer m.Remove() if m.Service == nil { @@ -895,6 +897,7 @@ func (m *Model) Run(f func(context.Context, *vim25.Client) error) error { s := m.Service.NewServer() defer s.Close() + ctx := m.Service.Context c, err := govmomi.NewClient(ctx, s.URL, true) if err != nil { return err diff --git a/vendor/github.com/vmware/govmomi/simulator/object.go b/vendor/github.com/vmware/govmomi/simulator/object.go index b08be515f7..6d64eb8f85 100644 --- a/vendor/github.com/vmware/govmomi/simulator/object.go +++ b/vendor/github.com/vmware/govmomi/simulator/object.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2018 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -30,7 +18,7 @@ import ( func SetCustomValue(ctx *Context, req *types.SetCustomValue) soap.HasFault { body := &methods.SetCustomValueBody{} - cfm := Map.CustomFieldsManager() + cfm := ctx.Map.CustomFieldsManager() _, field := cfm.findByNameType(req.Key, req.This.Type) if field == nil { diff --git a/vendor/github.com/vmware/govmomi/simulator/option_manager.go b/vendor/github.com/vmware/govmomi/simulator/option_manager.go index 1dd1688cd6..4675e27563 100644 --- a/vendor/github.com/vmware/govmomi/simulator/option_manager.go +++ b/vendor/github.com/vmware/govmomi/simulator/option_manager.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -77,6 +65,10 @@ func (m *OptionManager) init(r *Registry) { } } +func (m *OptionManager) model(model *Model) error { + return model.createRootTempDir(m) +} + func (m *OptionManager) QueryOptions(req *types.QueryOptions) soap.HasFault { body := &methods.QueryOptionsBody{} res := &types.QueryOptionsResponse{} diff --git a/vendor/github.com/vmware/govmomi/simulator/performance_manager.go b/vendor/github.com/vmware/govmomi/simulator/performance_manager.go index c64a336c21..4c3b91663f 100644 --- a/vendor/github.com/vmware/govmomi/simulator/performance_manager.go +++ b/vendor/github.com/vmware/govmomi/simulator/performance_manager.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -136,13 +124,13 @@ func (p *PerformanceManager) buildAvailablePerfMetricsQueryResponse(ids []types. return r } -func (p *PerformanceManager) queryAvailablePerfMetric(entity types.ManagedObjectReference, interval int32) *types.QueryAvailablePerfMetricResponse { +func (p *PerformanceManager) queryAvailablePerfMetric(ctx *Context, entity types.ManagedObjectReference, interval int32) *types.QueryAvailablePerfMetricResponse { switch entity.Type { case "VirtualMachine": - vm := Map.Get(entity).(*VirtualMachine) + vm := ctx.Map.Get(entity).(*VirtualMachine) return p.buildAvailablePerfMetricsQueryResponse(p.vmMetrics, int(vm.Summary.Config.NumCpu), vm.Datastore[0].Value) case "HostSystem": - host := Map.Get(entity).(*HostSystem) + host := ctx.Map.Get(entity).(*HostSystem) return p.buildAvailablePerfMetricsQueryResponse(p.hostMetrics, int(host.Hardware.CpuInfo.NumCpuThreads), host.Datastore[0].Value) case "ResourcePool": return p.buildAvailablePerfMetricsQueryResponse(p.rpMetrics, 0, "") @@ -166,7 +154,7 @@ func (p *PerformanceManager) queryAvailablePerfMetric(entity types.ManagedObject func (p *PerformanceManager) QueryAvailablePerfMetric(ctx *Context, req *types.QueryAvailablePerfMetric) soap.HasFault { body := new(methods.QueryAvailablePerfMetricBody) - body.Res = p.queryAvailablePerfMetric(req.Entity, req.IntervalId) + body.Res = p.queryAvailablePerfMetric(ctx, req.Entity, req.IntervalId) return body } diff --git a/vendor/github.com/vmware/govmomi/simulator/portgroup.go b/vendor/github.com/vmware/govmomi/simulator/portgroup.go index d7b0b4d354..15250acd61 100644 --- a/vendor/github.com/vmware/govmomi/simulator/portgroup.go +++ b/vendor/github.com/vmware/govmomi/simulator/portgroup.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -32,7 +20,7 @@ func (p *DistributedVirtualPortgroup) event(ctx *Context) types.DVPortgroupEvent return types.DVPortgroupEvent{ Event: types.Event{ - Datacenter: datacenterEventArgument(p), + Datacenter: datacenterEventArgument(ctx, p), Net: &types.NetworkEventArgument{ EntityEventArgument: types.EntityEventArgument{ Name: p.Name, diff --git a/vendor/github.com/vmware/govmomi/simulator/property_collector.go b/vendor/github.com/vmware/govmomi/simulator/property_collector.go index ed15dbfefe..ec541ba1c6 100644 --- a/vendor/github.com/vmware/govmomi/simulator/property_collector.go +++ b/vendor/github.com/vmware/govmomi/simulator/property_collector.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -531,10 +519,10 @@ func collect(ctx *Context, r *types.RetrievePropertiesEx) (*types.RetrieveResult // Select object references for _, spec := range r.SpecSet { for _, o := range spec.ObjectSet { - var rval reflect.Value - ok := false - ctx.WithLock(o.Obj, func() { rval, ok = getObject(ctx, o.Obj) }) + unlock := ctx.Map.AcquireLock(ctx, o.Obj) + rval, ok := getObject(ctx, o.Obj) if !ok { + unlock() if isFalse(spec.ReportMissingObjectsInResults) { return nil, &types.ManagedObjectNotFound{Obj: o.Obj} } @@ -542,10 +530,12 @@ func collect(ctx *Context, r *types.RetrievePropertiesEx) (*types.RetrieveResult } if o.SelectSet == nil || isFalse(o.Skip) { - refs = append(refs, o.Obj) + rr.collect(ctx, o.Obj) } - if err := rr.selectSet(ctx, rval, o.SelectSet, &refs); err != nil { + err := rr.selectSet(ctx, rval, o.SelectSet, &refs) + unlock() + if err != nil { return nil, err } } @@ -755,7 +745,7 @@ func (pc *PropertyCollector) update(u types.ObjectUpdate) { pc.mu.Unlock() } -func (pc *PropertyCollector) PutObject(o mo.Reference) { +func (pc *PropertyCollector) PutObject(_ *Context, o mo.Reference) { pc.update(types.ObjectUpdate{ Obj: o.Reference(), Kind: types.ObjectUpdateKindEnter, diff --git a/vendor/github.com/vmware/govmomi/simulator/property_filter.go b/vendor/github.com/vmware/govmomi/simulator/property_filter.go index 95f4a597e6..d05dfa16e4 100644 --- a/vendor/github.com/vmware/govmomi/simulator/property_filter.go +++ b/vendor/github.com/vmware/govmomi/simulator/property_filter.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -50,7 +38,7 @@ func (f *PropertyFilter) UpdateObject(ctx *Context, o mo.Reference, changes []ty } } -func (_ *PropertyFilter) PutObject(_ mo.Reference) {} +func (_ *PropertyFilter) PutObject(_ *Context, _ mo.Reference) {} func (_ *PropertyFilter) RemoveObject(_ *Context, _ types.ManagedObjectReference) {} diff --git a/vendor/github.com/vmware/govmomi/simulator/registry.go b/vendor/github.com/vmware/govmomi/simulator/registry.go index 749efb7b29..94035d7ed1 100644 --- a/vendor/github.com/vmware/govmomi/simulator/registry.go +++ b/vendor/github.com/vmware/govmomi/simulator/registry.go @@ -1,22 +1,11 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator import ( + "context" "encoding/json" "fmt" "log" @@ -52,17 +41,15 @@ var refValueMap = map[string]string{ "StoragePod": "group-p", } -// Map is the default Registry instance. -// -// TODO/WIP: To support the eventual removal of this unsyncronized global -// variable, the Map should be accessed through any Context.Map that is passed -// in to functions that may need it. -var Map = NewRegistry() +// Map returns simulator.Context.Map from the given ctx +func Map(ctx context.Context) *Registry { + return ctx.(*Context).Map +} // RegisterObject interface supports callbacks when objects are created, updated and deleted from the Registry type RegisterObject interface { mo.Reference - PutObject(mo.Reference) + PutObject(*Context, mo.Reference) UpdateObject(*Context, mo.Reference, []types.PropertyChange) RemoveObject(*Context, types.ManagedObjectReference) } @@ -284,8 +271,12 @@ func (r *Registry) Put(item mo.Reference) mo.Reference { r.m.Unlock() + ctx := &Context{ + Map: r, + } + r.applyHandlers(func(o RegisterObject) { - o.PutObject(item) + o.PutObject(ctx, item) }) return item @@ -501,7 +492,9 @@ func (r *Registry) removeString(ctx *Context, obj mo.Reference, field *[]string, } func (r *Registry) content() types.ServiceContent { - return r.Get(vim25.ServiceInstance).(*ServiceInstance).Content + return r.Get(vim25.ServiceInstance).(interface { + ServiceContent() types.ServiceContent + }).ServiceContent() } // IsESX returns true if this Registry maps an ESX model @@ -604,6 +597,11 @@ func (r *Registry) ExtensionManager() *ExtensionManager { return r.Get(r.content().ExtensionManager.Reference()).(*ExtensionManager) } +// VStorageObjectManager returns the VStorageObjectManager singleton +func (r *Registry) VStorageObjectManager() *VcenterVStorageObjectManager { + return r.Get(r.content().VStorageObjectManager.Reference()).(*VcenterVStorageObjectManager) +} + func (r *Registry) MarshalJSON() ([]byte, error) { r.m.Lock() defer r.m.Unlock() diff --git a/vendor/github.com/vmware/govmomi/simulator/resource_pool.go b/vendor/github.com/vmware/govmomi/simulator/resource_pool.go index 0ecd6f6f03..0a583fd56d 100644 --- a/vendor/github.com/vmware/govmomi/simulator/resource_pool.go +++ b/vendor/github.com/vmware/govmomi/simulator/resource_pool.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -50,12 +38,12 @@ func resourcePoolHosts(ctx *Context, pool *ResourcePool) []types.ManagedObjectRe } } -func NewResourcePool() *ResourcePool { +func NewResourcePool(ctx *Context) *ResourcePool { pool := &ResourcePool{ ResourcePool: esx.ResourcePool, } - if Map.IsVPX() { + if ctx.Map.IsVPX() { pool.DisabledMethod = nil // Enable VApp methods for VC } @@ -97,8 +85,8 @@ func allResourceFieldsValid(info *types.ResourceAllocationInfo) bool { return true } -func (p *ResourcePool) createChild(name string, spec types.ResourceConfigSpec) (*ResourcePool, *soap.Fault) { - if e := Map.FindByName(name, p.ResourcePool.ResourcePool); e != nil { +func (p *ResourcePool) createChild(ctx *Context, name string, spec types.ResourceConfigSpec) (*ResourcePool, *soap.Fault) { + if e := ctx.Map.FindByName(name, p.ResourcePool.ResourcePool); e != nil { return nil, Fault("", &types.DuplicateName{ Name: e.Entity().Name, Object: e.Reference(), @@ -117,7 +105,7 @@ func (p *ResourcePool) createChild(name string, spec types.ResourceConfigSpec) ( }) } - child := NewResourcePool() + child := NewResourcePool(ctx) child.Name = name child.Owner = p.Owner @@ -129,16 +117,16 @@ func (p *ResourcePool) createChild(name string, spec types.ResourceConfigSpec) ( return child, nil } -func (p *ResourcePool) CreateResourcePool(c *types.CreateResourcePool) soap.HasFault { +func (p *ResourcePool) CreateResourcePool(ctx *Context, c *types.CreateResourcePool) soap.HasFault { body := &methods.CreateResourcePoolBody{} - child, err := p.createChild(c.Name, c.Spec) + child, err := p.createChild(ctx, c.Name, c.Spec) if err != nil { body.Fault_ = err return body } - Map.PutEntity(p, Map.NewEntity(child)) + ctx.Map.PutEntity(p, ctx.Map.NewEntity(child)) p.ResourcePool.ResourcePool = append(p.ResourcePool.ResourcePool, child.Reference()) @@ -171,11 +159,11 @@ func updateResourceAllocation(kind string, src, dst *types.ResourceAllocationInf return nil } -func (p *ResourcePool) UpdateConfig(c *types.UpdateConfig) soap.HasFault { +func (p *ResourcePool) UpdateConfig(ctx *Context, c *types.UpdateConfig) soap.HasFault { body := &methods.UpdateConfigBody{} if c.Name != "" { - if e := Map.FindByName(c.Name, p.ResourcePool.ResourcePool); e != nil { + if e := ctx.Map.FindByName(c.Name, p.ResourcePool.ResourcePool); e != nil { body.Fault_ = Fault("", &types.DuplicateName{ Name: e.Entity().Name, Object: e.Reference(), @@ -290,8 +278,8 @@ func (p *ResourcePool) ImportVApp(ctx *Context, req *types.ImportVApp) soap.HasF var file object.DatastorePath file.FromString(info.GetVirtualDeviceFileBackingInfo().FileName) name := path.Base(file.Path) - ds := vm.findDatastore(file.Datastore) - lease.files[name] = path.Join(ds.Info.GetDatastoreInfo().Url, file.Path) + ds := vm.findDatastore(ctx, file.Datastore) + lease.files[name] = ds.resolve(ctx, file.Path) _, disk := d.(*types.VirtualDisk) kind := device.Type(d) @@ -355,10 +343,10 @@ func NewVAppConfigSpec() types.VAppConfigSpec { return spec } -func (p *ResourcePool) CreateVApp(req *types.CreateVApp) soap.HasFault { +func (p *ResourcePool) CreateVApp(ctx *Context, req *types.CreateVApp) soap.HasFault { body := &methods.CreateVAppBody{} - pool, err := p.createChild(req.Name, req.ResSpec) + pool, err := p.createChild(ctx, req.Name, req.ResSpec) if err != nil { body.Fault_ = err return body @@ -370,7 +358,7 @@ func (p *ResourcePool) CreateVApp(req *types.CreateVApp) soap.HasFault { child.ParentFolder = req.VmFolder if child.ParentFolder == nil { - folder := Map.getEntityDatacenter(p).VmFolder + folder := ctx.Map.getEntityDatacenter(p).VmFolder child.ParentFolder = &folder } @@ -383,7 +371,7 @@ func (p *ResourcePool) CreateVApp(req *types.CreateVApp) soap.HasFault { child.VAppConfig.Product = append(child.VAppConfig.Product, *product.Info) } - Map.PutEntity(p, Map.NewEntity(child)) + ctx.Map.PutEntity(p, ctx.Map.NewEntity(child)) p.ResourcePool.ResourcePool = append(p.ResourcePool.ResourcePool, child.Reference()) @@ -426,7 +414,7 @@ func (a *VirtualApp) CloneVAppTask(ctx *Context, req *types.CloneVApp_Task) soap rspec = &s } - res := a.CreateVApp(&types.CreateVApp{ + res := a.CreateVApp(ctx, &types.CreateVApp{ This: a.Self, Name: req.Name, ResSpec: *rspec, @@ -472,8 +460,8 @@ func (a *VirtualApp) CloneVAppTask(ctx *Context, req *types.CloneVApp_Task) soap } } -func (a *VirtualApp) CreateVApp(req *types.CreateVApp) soap.HasFault { - return (&ResourcePool{ResourcePool: a.ResourcePool}).CreateVApp(req) +func (a *VirtualApp) CreateVApp(ctx *Context, req *types.CreateVApp) soap.HasFault { + return (&ResourcePool{ResourcePool: a.ResourcePool}).CreateVApp(ctx, req) } func (a *VirtualApp) DestroyTask(ctx *Context, req *types.Destroy_Task) soap.HasFault { diff --git a/vendor/github.com/vmware/govmomi/simulator/search_index.go b/vendor/github.com/vmware/govmomi/simulator/search_index.go index 7919386210..3509e64c5c 100644 --- a/vendor/github.com/vmware/govmomi/simulator/search_index.go +++ b/vendor/github.com/vmware/govmomi/simulator/search_index.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -29,13 +17,13 @@ type SearchIndex struct { mo.SearchIndex } -func (s *SearchIndex) FindByDatastorePath(r *types.FindByDatastorePath) soap.HasFault { +func (s *SearchIndex) FindByDatastorePath(ctx *Context, r *types.FindByDatastorePath) soap.HasFault { res := &methods.FindByDatastorePathBody{Res: new(types.FindByDatastorePathResponse)} - Map.m.Lock() - defer Map.m.Unlock() + ctx.Map.m.Lock() + defer ctx.Map.m.Unlock() - for ref, obj := range Map.objects { + for ref, obj := range ctx.Map.objects { vm, ok := asVirtualMachineMO(obj) if !ok { continue @@ -50,10 +38,10 @@ func (s *SearchIndex) FindByDatastorePath(r *types.FindByDatastorePath) soap.Has return res } -func (s *SearchIndex) FindByInventoryPath(req *types.FindByInventoryPath) soap.HasFault { +func (s *SearchIndex) FindByInventoryPath(ctx *Context, req *types.FindByInventoryPath) soap.HasFault { body := &methods.FindByInventoryPathBody{Res: new(types.FindByInventoryPathResponse)} - root := Map.content().RootFolder + root := ctx.Map.content().RootFolder o := &root if req.InventoryPath == "/" { @@ -70,7 +58,7 @@ func (s *SearchIndex) FindByInventoryPath(req *types.FindByInventoryPath) soap.H } for _, name := range path { - f := s.FindChild(&types.FindChild{Entity: *o, Name: name}) + f := s.FindChild(ctx, &types.FindChild{Entity: *o, Name: name}) o = f.(*methods.FindChildBody).Res.Returnval if o == nil { @@ -83,10 +71,10 @@ func (s *SearchIndex) FindByInventoryPath(req *types.FindByInventoryPath) soap.H return body } -func (s *SearchIndex) FindChild(req *types.FindChild) soap.HasFault { +func (s *SearchIndex) FindChild(ctx *Context, req *types.FindChild) soap.HasFault { body := &methods.FindChildBody{} - obj := Map.Get(req.Entity) + obj := ctx.Map.Get(req.Entity) if obj == nil { body.Fault_ = Fault("", &types.ManagedObjectNotFound{Obj: req.Entity}) @@ -116,7 +104,7 @@ func (s *SearchIndex) FindChild(req *types.FindChild) soap.HasFault { children = append(children, e.Vm...) } - match := Map.FindByName(req.Name, children) + match := ctx.Map.FindByName(req.Name, children) if match != nil { ref := match.Reference() @@ -126,15 +114,15 @@ func (s *SearchIndex) FindChild(req *types.FindChild) soap.HasFault { return body } -func (s *SearchIndex) FindByUuid(req *types.FindByUuid) soap.HasFault { +func (s *SearchIndex) FindByUuid(ctx *Context, req *types.FindByUuid) soap.HasFault { body := &methods.FindByUuidBody{Res: new(types.FindByUuidResponse)} - Map.m.Lock() - defer Map.m.Unlock() + ctx.Map.m.Lock() + defer ctx.Map.m.Unlock() if req.VmSearch { // Find Virtual Machine using UUID - for ref, obj := range Map.objects { + for ref, obj := range ctx.Map.objects { vm, ok := asVirtualMachineMO(obj) if !ok { continue @@ -153,7 +141,7 @@ func (s *SearchIndex) FindByUuid(req *types.FindByUuid) soap.HasFault { } } else { // Find Host System using UUID - for ref, obj := range Map.objects { + for ref, obj := range ctx.Map.objects { host, ok := asHostSystemMO(obj) if !ok { continue @@ -168,12 +156,12 @@ func (s *SearchIndex) FindByUuid(req *types.FindByUuid) soap.HasFault { return body } -func (s *SearchIndex) FindByDnsName(req *types.FindByDnsName) soap.HasFault { +func (s *SearchIndex) FindByDnsName(ctx *Context, req *types.FindByDnsName) soap.HasFault { body := &methods.FindByDnsNameBody{Res: new(types.FindByDnsNameResponse)} all := types.FindAllByDnsName(*req) - switch r := s.FindAllByDnsName(&all).(type) { + switch r := s.FindAllByDnsName(ctx, &all).(type) { case *methods.FindAllByDnsNameBody: if len(r.Res.Returnval) > 0 { body.Res.Returnval = &r.Res.Returnval[0] @@ -185,15 +173,15 @@ func (s *SearchIndex) FindByDnsName(req *types.FindByDnsName) soap.HasFault { return body } -func (s *SearchIndex) FindAllByDnsName(req *types.FindAllByDnsName) soap.HasFault { +func (s *SearchIndex) FindAllByDnsName(ctx *Context, req *types.FindAllByDnsName) soap.HasFault { body := &methods.FindAllByDnsNameBody{Res: new(types.FindAllByDnsNameResponse)} - Map.m.Lock() - defer Map.m.Unlock() + ctx.Map.m.Lock() + defer ctx.Map.m.Unlock() if req.VmSearch { // Find Virtual Machine using DNS name - for ref, obj := range Map.objects { + for ref, obj := range ctx.Map.objects { vm, ok := asVirtualMachineMO(obj) if !ok { continue @@ -204,7 +192,7 @@ func (s *SearchIndex) FindAllByDnsName(req *types.FindAllByDnsName) soap.HasFaul } } else { // Find Host System using DNS name - for ref, obj := range Map.objects { + for ref, obj := range ctx.Map.objects { host, ok := asHostSystemMO(obj) if !ok { continue @@ -220,12 +208,12 @@ func (s *SearchIndex) FindAllByDnsName(req *types.FindAllByDnsName) soap.HasFaul return body } -func (s *SearchIndex) FindByIp(req *types.FindByIp) soap.HasFault { +func (s *SearchIndex) FindByIp(ctx *Context, req *types.FindByIp) soap.HasFault { body := &methods.FindByIpBody{Res: new(types.FindByIpResponse)} all := types.FindAllByIp(*req) - switch r := s.FindAllByIp(&all).(type) { + switch r := s.FindAllByIp(ctx, &all).(type) { case *methods.FindAllByIpBody: if len(r.Res.Returnval) > 0 { body.Res.Returnval = &r.Res.Returnval[0] @@ -237,15 +225,15 @@ func (s *SearchIndex) FindByIp(req *types.FindByIp) soap.HasFault { return body } -func (s *SearchIndex) FindAllByIp(req *types.FindAllByIp) soap.HasFault { +func (s *SearchIndex) FindAllByIp(ctx *Context, req *types.FindAllByIp) soap.HasFault { body := &methods.FindAllByIpBody{Res: new(types.FindAllByIpResponse)} - Map.m.Lock() - defer Map.m.Unlock() + ctx.Map.m.Lock() + defer ctx.Map.m.Unlock() if req.VmSearch { // Find Virtual Machine using IP - for ref, obj := range Map.objects { + for ref, obj := range ctx.Map.objects { vm, ok := asVirtualMachineMO(obj) if !ok { continue @@ -256,7 +244,7 @@ func (s *SearchIndex) FindAllByIp(req *types.FindAllByIp) soap.HasFault { } } else { // Find Host System using IP - for ref, obj := range Map.objects { + for ref, obj := range ctx.Map.objects { host, ok := asHostSystemMO(obj) if !ok { continue diff --git a/vendor/github.com/vmware/govmomi/simulator/service_instance.go b/vendor/github.com/vmware/govmomi/simulator/service_instance.go index 3524d15499..2027fdd222 100644 --- a/vendor/github.com/vmware/govmomi/simulator/service_instance.go +++ b/vendor/github.com/vmware/govmomi/simulator/service_instance.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -33,21 +21,16 @@ type ServiceInstance struct { mo.ServiceInstance } -func NewServiceInstance(ctx *Context, content types.ServiceContent, folder mo.Folder) *ServiceInstance { - // TODO: This function ignores the passed in Map and operates on the - // global Map. - Map = NewRegistry() - ctx.Map = Map - +func NewServiceInstance(ctx *Context, content types.ServiceContent, folder mo.Folder) (*Context, *ServiceInstance) { s := &ServiceInstance{} s.Self = vim25.ServiceInstance s.Content = content - Map.Put(s) + ctx.Map.Put(s) f := &Folder{Folder: folder} - Map.Put(f) + ctx.Map.Put(f) if content.About.ApiType == "HostAgent" { CreateDefaultESX(ctx, f) @@ -58,18 +41,22 @@ func NewServiceInstance(ctx *Context, content types.ServiceContent, folder mo.Fo refs := mo.References(content) for i := range refs { - if Map.Get(refs[i]) != nil { + if ctx.Map.Get(refs[i]) != nil { continue } content := types.ObjectContent{Obj: refs[i]} - o, err := loadObject(content) + o, err := loadObject(ctx, content) if err != nil { panic(err) } - Map.Put(o) + ctx.Map.Put(o) } - return s + return ctx, s +} + +func (s *ServiceInstance) ServiceContent() types.ServiceContent { + return s.Content } func (s *ServiceInstance) RetrieveServiceContent(*types.RetrieveServiceContent) soap.HasFault { diff --git a/vendor/github.com/vmware/govmomi/simulator/session_manager.go b/vendor/github.com/vmware/govmomi/simulator/session_manager.go index 5a80094b8d..dde0aba838 100644 --- a/vendor/github.com/vmware/govmomi/simulator/session_manager.go +++ b/vendor/github.com/vmware/govmomi/simulator/session_manager.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -30,6 +18,7 @@ import ( "github.com/google/uuid" "github.com/vmware/govmomi/session" + "github.com/vmware/govmomi/vim25" "github.com/vmware/govmomi/vim25/methods" "github.com/vmware/govmomi/vim25/mo" "github.com/vmware/govmomi/vim25/soap" @@ -82,6 +71,7 @@ func createSession(ctx *Context, name string, locale string) types.UserSession { ExtensionSession: types.NewBool(false), }, Registry: NewRegistry(), + Map: ctx.Map, } ctx.SetSession(session, true) @@ -343,6 +333,10 @@ func HTTPCookie(ctx *Context) string { return "" } +func (c *Context) sessionManager() *SessionManager { + return c.svc.sdk[vim25.Path].SessionManager() +} + // mapSession maps an HTTP cookie to a Session. func (c *Context) mapSession() { cookie := c.Map.Cookie @@ -350,7 +344,7 @@ func (c *Context) mapSession() { cookie = HTTPCookie } - if val, ok := c.svc.sm.getSession(cookie(c)); ok { + if val, ok := c.sessionManager().getSession(cookie(c)); ok { c.SetSession(val, false) } } @@ -398,7 +392,8 @@ func (c *Context) SetSession(session Session, login bool) { session.LastActiveTime = time.Now() session.CallCount++ - c.svc.sm.putSession(session) + m := c.sessionManager() + m.putSession(session) c.Session = &session if login { @@ -416,10 +411,19 @@ func (c *Context) SetSession(session Session, login bool) { Locale: session.Locale, }) - SessionIdleWatch(c.Context, session.Key, c.svc.sm.expiredSession) + SessionIdleWatch(c.Context, session.Key, m.expiredSession) } } +// For returns a Context with Registry Map for the given path. +// This is intended for calling into other namespaces internally, +// such as vslm simulator methods calling vim25 methods for example. +func (c *Context) For(path string) *Context { + clone := *c + clone.Map = c.svc.sdk[path] + return &clone +} + // WithLock holds a lock for the given object while the given function is run. // It will skip locking if this context already holds the given object's lock. func (c *Context) WithLock(obj mo.Reference, f func()) { @@ -450,6 +454,7 @@ func (c *Context) postEvent(events ...types.BaseEvent) { type Session struct { types.UserSession *Registry + Map *Registry } func (s *Session) setReference(item mo.Reference) { @@ -480,7 +485,7 @@ func (s *Session) Get(ref types.ManagedObjectReference) mo.Reference { switch ref.Type { case "SessionManager": // Clone SessionManager so the PropertyCollector can properly report CurrentSession - m := *Map.SessionManager() + m := *s.Map.SessionManager() m.CurrentSession = &s.UserSession // TODO: we could maintain SessionList as part of the SessionManager singleton @@ -492,10 +497,10 @@ func (s *Session) Get(ref types.ManagedObjectReference) mo.Reference { return &m case "PropertyCollector": - if ref == Map.content().PropertyCollector { + if ref == s.Map.content().PropertyCollector { // Per-session instance of the PropertyCollector singleton. // Using reflection here as PropertyCollector might be wrapped with a custom type. - obj = Map.Get(ref) + obj = s.Map.Get(ref) pc := reflect.New(reflect.TypeOf(obj).Elem()) obj = pc.Interface().(mo.Reference) s.Registry.setReference(obj, ref) @@ -503,5 +508,5 @@ func (s *Session) Get(ref types.ManagedObjectReference) mo.Reference { } } - return Map.Get(ref) + return s.Map.Get(ref) } diff --git a/vendor/github.com/vmware/govmomi/simulator/simulator.go b/vendor/github.com/vmware/govmomi/simulator/simulator.go index e40f2fc297..194cb533a8 100644 --- a/vendor/github.com/vmware/govmomi/simulator/simulator.go +++ b/vendor/github.com/vmware/govmomi/simulator/simulator.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -70,14 +58,13 @@ type Method struct { // Service decodes incoming requests and dispatches to a Handler type Service struct { - client *vim25.Client - sm *SessionManager - sdk map[string]*Registry - funcs []handleFunc - delay *DelayConfig + sdk map[string]*Registry + funcs []handleFunc + delay *DelayConfig readAll func(io.Reader) ([]byte, error) + Context *Context Listen *url.URL TLS *tls.Config ServeMux *http.ServeMux @@ -95,18 +82,21 @@ type Server struct { } // New returns an initialized simulator Service instance -func New(instance *ServiceInstance) *Service { +func New(ctx *Context, instance *ServiceInstance) *Service { s := &Service{ + Context: ctx, readAll: io.ReadAll, - sm: Map.SessionManager(), sdk: make(map[string]*Registry), } - - s.client, _ = vim25.NewClient(context.Background(), s) - + s.Context.svc = s return s } +func (s *Service) client() *vim25.Client { + c, _ := vim25.NewClient(context.Background(), s) + return c +} + type serverFaultBody struct { Reason *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"` } @@ -152,7 +142,12 @@ func (s *Service) call(ctx *Context, method *Method) soap.HasFault { if session == nil { switch method.Name { - case "RetrieveServiceContent", "PbmRetrieveServiceContent", "Fetch", "List", "Login", "LoginByToken", "LoginExtensionByCertificate", "RetrieveProperties", "RetrievePropertiesEx", "CloneSession": + case + "Login", "LoginByToken", "LoginExtensionByCertificate", "CloneSession", // SessionManager + "RetrieveServiceContent", "RetrieveInternalContent", "PbmRetrieveServiceContent", // ServiceContent + "Fetch", "RetrieveProperties", "RetrievePropertiesEx", // PropertyCollector + "List", // lookup service + "GetTrustedCertificates": // ssoadmin // ok for now, TODO: authz default: fault := &types.NotAuthenticated{ @@ -251,9 +246,13 @@ func (s *Service) RoundTrip(ctx context.Context, request, response soap.HasFault } res := s.call(&Context{ - Map: Map, + Map: s.Context.Map, Context: ctx, - Session: internalSession, + Session: &Session{ + UserSession: internalSession.UserSession, + Registry: internalSession.Registry, + Map: s.Context.Map, + }, }, method) if err := res.Fault(); err != nil { @@ -510,7 +509,7 @@ func (s *Service) ServeSDK(w http.ResponseWriter, r *http.Request) { // Redirect any Fetch method calls to the PropertyCollector singleton method.This = ctx.Map.content().PropertyCollector } - ctx.Map.WithLock(ctx, s.sm, ctx.mapSession) + ctx.Map.WithLock(ctx, ctx.sessionManager(), ctx.mapSession) res = s.call(ctx, method) } @@ -566,7 +565,7 @@ func (s *Service) ServeSDK(w http.ResponseWriter, r *http.Request) { func (s *Service) findDatastore(query url.Values) (*Datastore, error) { ctx := context.Background() - finder := find.NewFinder(s.client, false) + finder := find.NewFinder(s.client(), false) dc, err := finder.DatacenterOrDefault(ctx, query.Get("dcPath")) if err != nil { return nil, err @@ -579,7 +578,7 @@ func (s *Service) findDatastore(query url.Values) (*Datastore, error) { return nil, err } - return Map.Get(ds.Reference()).(*Datastore), nil + return s.Context.Map.Get(ds.Reference()).(*Datastore), nil } const folderPrefix = "/folder/" @@ -593,8 +592,13 @@ func (s *Service) ServeDatastore(w http.ResponseWriter, r *http.Request) { return } + if strings.Contains(r.URL.Path, "..") { + w.WriteHeader(http.StatusBadRequest) + return + } + r.URL.Path = strings.TrimPrefix(r.URL.Path, folderPrefix) - p := path.Join(ds.Info.GetDatastoreInfo().Url, r.URL.Path) + p := ds.resolve(s.Context, r.URL.Path) switch r.Method { case http.MethodPost: @@ -621,7 +625,11 @@ func (s *Service) ServeDatastore(w http.ResponseWriter, r *http.Request) { _, _ = io.Copy(f, r.Body) default: - fs := http.FileServer(http.Dir(ds.Info.GetDatastoreInfo().Url)) + // ds.resolve() may have translated vsan friendly name to uuid, + // apply the same to the Request.URL.Path + r.URL.Path = strings.TrimPrefix(p, ds.Summary.Url) + + fs := http.FileServer(http.Dir(ds.Summary.Url)) fs.ServeHTTP(w, r) } @@ -640,7 +648,7 @@ func (s *Service) ServiceVersions(w http.ResponseWriter, r *http.Request) { ` - fmt.Fprintf(w, versions, s.client.ServiceContent.About.ApiVersion) + fmt.Fprintf(w, versions, s.Context.Map.content().About.ApiVersion) } // ServiceVersionsVsan handler for the /sdk/vsanServiceVersions.xml path. @@ -656,7 +664,7 @@ func (s *Service) ServiceVersionsVsan(w http.ResponseWriter, r *http.Request) { ` - fmt.Fprintf(w, versions, s.client.ServiceContent.About.ApiVersion) + fmt.Fprintf(w, versions, s.Context.Map.content().About.ApiVersion) } // defaultIP returns addr.IP if specified, otherwise attempts to find a non-loopback ipv4 IP @@ -692,11 +700,12 @@ func defaultIP(addr *net.TCPAddr) string { // NewServer returns an http Server instance for the given service func (s *Service) NewServer() *Server { - s.RegisterSDK(Map, Map.Path+"/vimService") + ctx := s.Context + s.RegisterSDK(ctx.Map, ctx.Map.Path+"/vimService") mux := s.ServeMux - mux.HandleFunc(Map.Path+"/vimServiceVersions.xml", s.ServiceVersions) - mux.HandleFunc(Map.Path+"/vsanServiceVersions.xml", s.ServiceVersionsVsan) + mux.HandleFunc(ctx.Map.Path+"/vimServiceVersions.xml", s.ServiceVersions) + mux.HandleFunc(ctx.Map.Path+"/vsanServiceVersions.xml", s.ServiceVersionsVsan) mux.HandleFunc(folderPrefix, s.ServeDatastore) mux.HandleFunc(guestPrefix, ServeGuest) mux.HandleFunc(nfcPrefix, ServeNFC) @@ -711,17 +720,17 @@ func (s *Service) NewServer() *Server { u := &url.URL{ Scheme: "http", Host: net.JoinHostPort(defaultIP(addr), port), - Path: Map.Path, + Path: ctx.Map.Path, } if s.TLS != nil { u.Scheme += "s" } // Redirect clients to this http server, rather than HostSystem.Name - Map.SessionManager().ServiceHostName = u.Host + ctx.sessionManager().ServiceHostName = u.Host // Add vcsim config to OptionManager for use by SDK handlers (see lookup/simulator for example) - m := Map.OptionManager() + m := ctx.Map.OptionManager() for i := range m.Setting { setting := m.Setting[i].GetOptionValue() @@ -750,7 +759,7 @@ func (s *Service) NewServer() *Server { if s.RegisterEndpoints { for i := range endpoints { - endpoints[i](s, Map) + endpoints[i](s, ctx.Map) } } @@ -768,7 +777,7 @@ func (s *Service) NewServer() *Server { if s.TLS != nil { ts.TLS = s.TLS ts.TLS.ClientAuth = tls.RequestClientCert // Used by SessionManager.LoginExtensionByCertificate - Map.SessionManager().TLSCert = func() string { + ctx.Map.SessionManager().TLSCert = func() string { return base64.StdEncoding.EncodeToString(ts.TLS.Certificates[0].Certificate[0]) } ts.StartTLS() diff --git a/vendor/github.com/vmware/govmomi/simulator/snapshot.go b/vendor/github.com/vmware/govmomi/simulator/snapshot.go index 4abfbfcd58..a0cf37ef75 100644 --- a/vendor/github.com/vmware/govmomi/simulator/snapshot.go +++ b/vendor/github.com/vmware/govmomi/simulator/snapshot.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -33,8 +21,8 @@ type VirtualMachineSnapshot struct { DataSets map[string]*DataSet } -func (v *VirtualMachineSnapshot) createSnapshotFiles() types.BaseMethodFault { - vm := Map.Get(v.Vm).(*VirtualMachine) +func (v *VirtualMachineSnapshot) createSnapshotFiles(ctx *Context) types.BaseMethodFault { + vm := ctx.Map.Get(v.Vm).(*VirtualMachine) snapshotDirectory := vm.Config.Files.SnapshotDirectory if snapshotDirectory == "" { @@ -44,7 +32,7 @@ func (v *VirtualMachineSnapshot) createSnapshotFiles() types.BaseMethodFault { index := 1 for { fileName := fmt.Sprintf("%s-Snapshot%d.vmsn", vm.Name, index) - f, err := vm.createFile(snapshotDirectory, fileName, false) + f, err := vm.createFile(ctx, snapshotDirectory, fileName, false) if err != nil { switch err.(type) { case *types.FileAlreadyExists: @@ -58,15 +46,15 @@ func (v *VirtualMachineSnapshot) createSnapshotFiles() types.BaseMethodFault { _ = f.Close() p, _ := parseDatastorePath(snapshotDirectory) - vm.useDatastore(p.Datastore) + vm.useDatastore(ctx, p.Datastore) datastorePath := object.DatastorePath{ Datastore: p.Datastore, Path: path.Join(p.Path, fileName), } - dataLayoutKey := vm.addFileLayoutEx(datastorePath, 0) - vm.addSnapshotLayout(v.Self, dataLayoutKey) - vm.addSnapshotLayoutEx(v.Self, dataLayoutKey, -1) + dataLayoutKey := vm.addFileLayoutEx(ctx, datastorePath, 0) + vm.addSnapshotLayout(ctx, v.Self, dataLayoutKey) + vm.addSnapshotLayoutEx(ctx, v.Self, dataLayoutKey, -1) return nil } @@ -95,7 +83,7 @@ func (v *VirtualMachineSnapshot) removeSnapshotFiles(ctx *Context) types.BaseMet host := ctx.Map.Get(*vm.Runtime.Host).(*HostSystem) datastore := ctx.Map.FindByName(p.Datastore, host.Datastore).(*Datastore) - dFilePath := path.Join(datastore.Info.GetDatastoreInfo().Url, p.Path) + dFilePath := datastore.resolve(ctx, p.Path) _ = os.Remove(dFilePath) } diff --git a/vendor/github.com/vmware/govmomi/simulator/storage_resource_manager.go b/vendor/github.com/vmware/govmomi/simulator/storage_resource_manager.go index d169d6d079..5c2ceb4445 100644 --- a/vendor/github.com/vmware/govmomi/simulator/storage_resource_manager.go +++ b/vendor/github.com/vmware/govmomi/simulator/storage_resource_manager.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2018 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -33,7 +21,7 @@ type StorageResourceManager struct { func (m *StorageResourceManager) ConfigureStorageDrsForPodTask(ctx *Context, req *types.ConfigureStorageDrsForPod_Task) soap.HasFault { task := CreateTask(m, "configureStorageDrsForPod", func(*Task) (types.AnyType, types.BaseMethodFault) { - cluster := Map.Get(req.Pod).(*StoragePod) + cluster := ctx.Map.Get(req.Pod).(*StoragePod) if s := req.Spec.PodConfigSpec; s != nil { config := &cluster.PodStorageDrsEntry.StorageDrsConfig.PodConfig @@ -56,11 +44,11 @@ func (m *StorageResourceManager) ConfigureStorageDrsForPodTask(ctx *Context, req } } -func (m *StorageResourceManager) pod(ref *types.ManagedObjectReference) *StoragePod { +func (m *StorageResourceManager) pod(ctx *Context, ref *types.ManagedObjectReference) *StoragePod { if ref == nil { return nil } - cluster := Map.Get(*ref).(*StoragePod) + cluster := ctx.Map.Get(*ref).(*StoragePod) config := &cluster.PodStorageDrsEntry.StorageDrsConfig.PodConfig if !config.Enabled { @@ -74,7 +62,7 @@ func (m *StorageResourceManager) pod(ref *types.ManagedObjectReference) *Storage return cluster } -func (m *StorageResourceManager) RecommendDatastores(req *types.RecommendDatastores) soap.HasFault { +func (m *StorageResourceManager) RecommendDatastores(ctx *Context, req *types.RecommendDatastores) soap.HasFault { spec := req.StorageSpec.PodSelectionSpec body := new(methods.RecommendDatastoresBody) res := new(types.RecommendDatastoresResponse) @@ -141,7 +129,7 @@ func (m *StorageResourceManager) RecommendDatastores(req *types.RecommendDatasto for _, d := range req.StorageSpec.ConfigSpec.DeviceChange { devices = append(devices, d.GetVirtualDeviceConfigSpec().Device) } - cluster := m.pod(spec.StoragePod) + cluster := m.pod(ctx, spec.StoragePod) if cluster == nil { if f := req.StorageSpec.ConfigSpec.Files; f == nil || f.VmPathName == "" { return invalid("configSpec.files") @@ -163,7 +151,7 @@ func (m *StorageResourceManager) RecommendDatastores(req *types.RecommendDatasto } for _, placement := range spec.InitialVmConfig { - cluster := m.pod(&placement.StoragePod) + cluster := m.pod(ctx, &placement.StoragePod) if cluster == nil { return invalid("podSelectionSpec.storagePod") } diff --git a/vendor/github.com/vmware/govmomi/simulator/task.go b/vendor/github.com/vmware/govmomi/simulator/task.go index d41274e6de..bc027e46b3 100644 --- a/vendor/github.com/vmware/govmomi/simulator/task.go +++ b/vendor/github.com/vmware/govmomi/simulator/task.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -22,6 +10,7 @@ import ( "strings" "time" + "github.com/vmware/govmomi/vim25" "github.com/vmware/govmomi/vim25/methods" "github.com/vmware/govmomi/vim25/mo" "github.com/vmware/govmomi/vim25/soap" @@ -64,9 +53,6 @@ func CreateTask(e mo.Reference, name string, run func(*Task) (types.AnyType, typ Execute: run, } - task.Self = Map.newReference(task) - task.Info.Key = task.Self.Value - task.Info.Task = task.Self task.Info.Name = ucFirst(name) task.Info.DescriptionId = fmt.Sprintf("%s.%s", ref.Type, id) task.Info.Entity = &ref @@ -75,8 +61,6 @@ func CreateTask(e mo.Reference, name string, run func(*Task) (types.AnyType, typ task.Info.QueueTime = time.Now() task.Info.State = types.TaskInfoStateQueued - Map.Put(task) - return task } @@ -96,12 +80,19 @@ func (tr *taskReference) Reference() types.ManagedObjectReference { } func (t *Task) Run(ctx *Context) types.ManagedObjectReference { - t.ctx = ctx - // alias the global Map to reduce data races in tests that reset the - // global Map variable. - vimMap := Map + if ctx.Map.Path != vim25.Path { + // All Tasks live in the vim25 namespace + ctx = ctx.For(vim25.Path) + } - vimMap.AtomicUpdate(t.ctx, t, []types.PropertyChange{ + t.ctx = ctx + + t.Self = ctx.Map.newReference(t) + t.Info.Key = t.Self.Value + t.Info.Task = t.Self + ctx.Map.Put(t) + + ctx.Map.AtomicUpdate(t.ctx, t, []types.PropertyChange{ {Name: "info.startTime", Val: time.Now()}, {Name: "info.state", Val: types.TaskInfoStateRunning}, }) @@ -120,12 +111,12 @@ func (t *Task) Run(ctx *Context) types.ManagedObjectReference { } var unlock func() if handoff { - unlock = vimMap.AcquireLock(ctx, tr) + unlock = ctx.Map.AcquireLock(ctx, tr) } go func() { TaskDelay.delay(t.Info.Name) if !handoff { - unlock = vimMap.AcquireLock(ctx, tr) + unlock = ctx.Map.AcquireLock(ctx, tr) } res, err := t.Execute(t) unlock() @@ -140,7 +131,7 @@ func (t *Task) Run(ctx *Context) types.ManagedObjectReference { } } - vimMap.AtomicUpdate(t.ctx, t, []types.PropertyChange{ + ctx.Map.AtomicUpdate(t.ctx, t, []types.PropertyChange{ {Name: "info.completeTime", Val: time.Now()}, {Name: "info.state", Val: state}, {Name: "info.result", Val: res}, @@ -168,7 +159,7 @@ func (t *Task) Wait() { isRunning := func() bool { var running bool - Map.WithLock(isolatedLockingContext, t, func() { + t.ctx.Map.WithLock(isolatedLockingContext, t, func() { switch t.Info.State { case types.TaskInfoStateSuccess, types.TaskInfoStateError: running = false diff --git a/vendor/github.com/vmware/govmomi/simulator/task_manager.go b/vendor/github.com/vmware/govmomi/simulator/task_manager.go index f04787bc04..c6d38dbd61 100644 --- a/vendor/github.com/vmware/govmomi/simulator/task_manager.go +++ b/vendor/github.com/vmware/govmomi/simulator/task_manager.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -66,14 +54,12 @@ func recentTask(recent []types.ManagedObjectReference, ref types.ManagedObjectRe return []types.PropertyChange{{Name: "recentTask", Val: recent}} } -func (m *TaskManager) PutObject(obj mo.Reference) { +func (m *TaskManager) PutObject(ctx *Context, obj mo.Reference) { task, ok := obj.(*Task) if !ok { return } - ctx := SpoofContext() - // propagate new Tasks to: // - TaskManager.RecentTask // - TaskHistoryCollector instances, if Filter matches diff --git a/vendor/github.com/vmware/govmomi/simulator/view_manager.go b/vendor/github.com/vmware/govmomi/simulator/view_manager.go index 147f202d12..5d367d9eea 100644 --- a/vendor/github.com/vmware/govmomi/simulator/view_manager.go +++ b/vendor/github.com/vmware/govmomi/simulator/view_manager.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -113,7 +101,7 @@ func (m *ViewManager) CreateContainerView(ctx *Context, req *types.CreateContain } seen := make(map[types.ManagedObjectReference]bool) - container.add(root, seen) + container.add(ctx, root, seen) ctx.Session.Registry.Put(container) ctx.Map.AddHandler(container) @@ -177,7 +165,7 @@ func walk(root mo.Reference, f func(child types.ManagedObjectReference)) { } } -func (v *ContainerView) add(root mo.Reference, seen map[types.ManagedObjectReference]bool) { +func (v *ContainerView) add(ctx *Context, root mo.Reference, seen map[types.ManagedObjectReference]bool) { walk(root, func(child types.ManagedObjectReference) { if v.include(child) { if !seen[child] { @@ -187,12 +175,12 @@ func (v *ContainerView) add(root mo.Reference, seen map[types.ManagedObjectRefer } if v.Recursive { - v.add(Map.Get(child), seen) + v.add(ctx, ctx.Map.Get(child), seen) } }) } -func (v *ContainerView) find(root mo.Reference, ref types.ManagedObjectReference, found *bool) bool { +func (v *ContainerView) find(ctx *Context, root mo.Reference, ref types.ManagedObjectReference, found *bool) bool { walk(root, func(child types.ManagedObjectReference) { if *found { return @@ -202,19 +190,18 @@ func (v *ContainerView) find(root mo.Reference, ref types.ManagedObjectReference return } if v.Recursive { - *found = v.find(Map.Get(child), ref, found) + *found = v.find(ctx, ctx.Map.Get(child), ref, found) } }) return *found } -func (v *ContainerView) PutObject(obj mo.Reference) { +func (v *ContainerView) PutObject(ctx *Context, obj mo.Reference) { ref := obj.Reference() - ctx := SpoofContext() ctx.WithLock(v, func() { - if v.include(ref) && v.find(v.root, ref, types.NewBool(false)) { + if v.include(ref) && v.find(ctx, v.root, ref, types.NewBool(false)) { ctx.Update(v, []types.PropertyChange{{Name: "view", Val: append(v.View, ref)}}) } }) diff --git a/vendor/github.com/vmware/govmomi/simulator/virtual_disk_manager.go b/vendor/github.com/vmware/govmomi/simulator/virtual_disk_manager.go index d3ecd7ac19..e1c82901c0 100644 --- a/vendor/github.com/vmware/govmomi/simulator/virtual_disk_manager.go +++ b/vendor/github.com/vmware/govmomi/simulator/virtual_disk_manager.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -50,10 +38,10 @@ func vdmNames(name string) []string { } } -func vdmCreateVirtualDisk(op types.VirtualDeviceConfigSpecFileOperation, req *types.CreateVirtualDisk_Task) types.BaseMethodFault { - fm := Map.FileManager() +func vdmCreateVirtualDisk(ctx *Context, op types.VirtualDeviceConfigSpecFileOperation, req *types.CreateVirtualDisk_Task) types.BaseMethodFault { + fm := ctx.Map.FileManager() - file, fault := fm.resolve(req.Datacenter, req.Name) + file, fault := fm.resolve(ctx, req.Datacenter, req.Name) if fault != nil { return fault } @@ -101,10 +89,10 @@ func vdmCreateVirtualDisk(op types.VirtualDeviceConfigSpecFileOperation, req *ty return nil } -func vdmExtendVirtualDisk(req *types.ExtendVirtualDisk_Task) types.BaseMethodFault { - fm := Map.FileManager() +func vdmExtendVirtualDisk(ctx *Context, req *types.ExtendVirtualDisk_Task) types.BaseMethodFault { + fm := ctx.Map.FileManager() - file, fault := fm.resolve(req.Datacenter, req.Name) + file, fault := fm.resolve(ctx, req.Datacenter, req.Name) if fault != nil { return fault } @@ -137,7 +125,7 @@ func vdmExtendVirtualDisk(req *types.ExtendVirtualDisk_Task) types.BaseMethodFau func (m *VirtualDiskManager) CreateVirtualDiskTask(ctx *Context, req *types.CreateVirtualDisk_Task) soap.HasFault { task := CreateTask(m, "createVirtualDisk", func(*Task) (types.AnyType, types.BaseMethodFault) { - if err := vdmCreateVirtualDisk(types.VirtualDeviceConfigSpecFileOperationCreate, req); err != nil { + if err := vdmCreateVirtualDisk(ctx, types.VirtualDeviceConfigSpecFileOperationCreate, req); err != nil { return "", err } return req.Name, nil @@ -152,7 +140,7 @@ func (m *VirtualDiskManager) CreateVirtualDiskTask(ctx *Context, req *types.Crea func (m *VirtualDiskManager) ExtendVirtualDiskTask(ctx *Context, req *types.ExtendVirtualDisk_Task) soap.HasFault { task := CreateTask(m, "extendVirtualDisk", func(*Task) (types.AnyType, types.BaseMethodFault) { - if err := vdmExtendVirtualDisk(req); err != nil { + if err := vdmExtendVirtualDisk(ctx, req); err != nil { return "", err } return req.Name, nil @@ -167,10 +155,10 @@ func (m *VirtualDiskManager) ExtendVirtualDiskTask(ctx *Context, req *types.Exte func (m *VirtualDiskManager) DeleteVirtualDiskTask(ctx *Context, req *types.DeleteVirtualDisk_Task) soap.HasFault { task := CreateTask(m, "deleteVirtualDisk", func(*Task) (types.AnyType, types.BaseMethodFault) { - fm := Map.FileManager() + fm := ctx.Map.FileManager() for _, name := range vdmNames(req.Name) { - err := fm.deleteDatastoreFile(&types.DeleteDatastoreFile_Task{ + err := fm.deleteDatastoreFile(ctx, &types.DeleteDatastoreFile_Task{ Name: name, Datacenter: req.Datacenter, }) @@ -197,7 +185,7 @@ func (m *VirtualDiskManager) MoveVirtualDiskTask(ctx *Context, req *types.MoveVi dest := vdmNames(req.DestName) for i, name := range vdmNames(req.SourceName) { - err := fm.moveDatastoreFile(&types.MoveDatastoreFile_Task{ + err := fm.moveDatastoreFile(ctx, &types.MoveDatastoreFile_Task{ SourceName: name, SourceDatacenter: req.SourceDatacenter, DestinationName: dest[i], @@ -231,7 +219,7 @@ func (m *VirtualDiskManager) CopyVirtualDiskTask(ctx *Context, req *types.CopyVi dest := vdmNames(req.DestName) for i, name := range vdmNames(req.SourceName) { - err := fm.copyDatastoreFile(&types.CopyDatastoreFile_Task{ + err := fm.copyDatastoreFile(ctx, &types.CopyDatastoreFile_Task{ SourceName: name, SourceDatacenter: req.SourceDatacenter, DestinationName: dest[i], @@ -266,7 +254,7 @@ func (m *VirtualDiskManager) QueryVirtualDiskUuid(ctx *Context, req *types.Query fm := ctx.Map.FileManager() - file, fault := fm.resolve(req.Datacenter, req.Name) + file, fault := fm.resolve(ctx, req.Datacenter, req.Name) if fault != nil { body.Fault_ = Fault("", fault) return body @@ -299,7 +287,7 @@ func (m *VirtualDiskManager) QueryVirtualDiskInfoTask(ctx *Context, req *interna fm := ctx.Map.FileManager() - _, fault := fm.resolve(req.Datacenter, req.Name) + _, fault := fm.resolve(ctx, req.Datacenter, req.Name) if fault != nil { return nil, fault } diff --git a/vendor/github.com/vmware/govmomi/simulator/virtual_machine.go b/vendor/github.com/vmware/govmomi/simulator/virtual_machine.go index 7df2e12c87..76a467047a 100644 --- a/vendor/github.com/vmware/govmomi/simulator/virtual_machine.go +++ b/vendor/github.com/vmware/govmomi/simulator/virtual_machine.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2017-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -33,6 +21,7 @@ import ( "github.com/google/uuid" + "github.com/vmware/govmomi/internal" "github.com/vmware/govmomi/object" "github.com/vmware/govmomi/simulator/esx" "github.com/vmware/govmomi/vim25/methods" @@ -105,7 +94,7 @@ func NewVirtualMachine(ctx *Context, parent types.ManagedObjectReference, spec * dc := ctx.Map.getEntityDatacenter(folder.(mo.Entity)) ds := ctx.Map.FindByName(vmx.Datastore, dc.Datastore).(*Datastore) - dir := path.Join(ds.Info.GetDatastoreInfo().Url, vmx.Path) + dir := ds.resolve(ctx, vmx.Path) if path.Ext(vmx.Path) == ".vmx" { dir = path.Dir(dir) @@ -184,15 +173,15 @@ func (*VirtualMachine) Reload(*types.Reload) soap.HasFault { return &methods.ReloadBody{Res: new(types.ReloadResponse)} } -func (vm *VirtualMachine) event() types.VmEvent { - host := Map.Get(*vm.Runtime.Host).(*HostSystem) +func (vm *VirtualMachine) event(ctx *Context) types.VmEvent { + host := ctx.Map.Get(*vm.Runtime.Host).(*HostSystem) return types.VmEvent{ Event: types.Event{ - Datacenter: datacenterEventArgument(host), - ComputeResource: host.eventArgumentParent(), + Datacenter: datacenterEventArgument(ctx, host), + ComputeResource: host.eventArgumentParent(ctx), Host: host.eventArgument(), - Ds: Map.Get(vm.Datastore[0]).(*Datastore).eventArgument(), + Ds: ctx.Map.Get(vm.Datastore[0]).(*Datastore).eventArgument(), Vm: &types.VmEventArgument{ EntityEventArgument: types.EntityEventArgument{Name: vm.Name}, Vm: vm.Self, @@ -680,7 +669,7 @@ func getVMFileType(fileName string) types.VirtualMachineFileLayoutExFileType { return fileType } -func (vm *VirtualMachine) addFileLayoutEx(datastorePath object.DatastorePath, fileSize int64) int32 { +func (vm *VirtualMachine) addFileLayoutEx(ctx *Context, datastorePath object.DatastorePath, fileSize int64) int32 { var newKey int32 for _, layoutFile := range vm.LayoutEx.File { if layoutFile.Name == datastorePath.String() { @@ -696,11 +685,11 @@ func (vm *VirtualMachine) addFileLayoutEx(datastorePath object.DatastorePath, fi switch fileType { case types.VirtualMachineFileLayoutExFileTypeNvram, types.VirtualMachineFileLayoutExFileTypeSnapshotList: - vm.addConfigLayout(datastorePath.Path) + vm.addConfigLayout(ctx, datastorePath.Path) case types.VirtualMachineFileLayoutExFileTypeLog: - vm.addLogLayout(datastorePath.Path) + vm.addLogLayout(ctx, datastorePath.Path) case types.VirtualMachineFileLayoutExFileTypeSwap: - vm.addSwapLayout(datastorePath.String()) + vm.addSwapLayout(ctx, datastorePath.String()) } vm.LayoutEx.File = append(vm.LayoutEx.File, types.VirtualMachineFileLayoutExFileInfo{ @@ -715,12 +704,12 @@ func (vm *VirtualMachine) addFileLayoutEx(datastorePath object.DatastorePath, fi vm.LayoutEx.Timestamp = time.Now() - vm.updateStorage() + vm.updateStorage(ctx) return newKey } -func (vm *VirtualMachine) addConfigLayout(name string) { +func (vm *VirtualMachine) addConfigLayout(ctx *Context, name string) { for _, config := range vm.Layout.ConfigFile { if config == name { return @@ -729,10 +718,10 @@ func (vm *VirtualMachine) addConfigLayout(name string) { vm.Layout.ConfigFile = append(vm.Layout.ConfigFile, name) - vm.updateStorage() + vm.updateStorage(ctx) } -func (vm *VirtualMachine) addLogLayout(name string) { +func (vm *VirtualMachine) addLogLayout(ctx *Context, name string) { for _, log := range vm.Layout.LogFile { if log == name { return @@ -741,16 +730,16 @@ func (vm *VirtualMachine) addLogLayout(name string) { vm.Layout.LogFile = append(vm.Layout.LogFile, name) - vm.updateStorage() + vm.updateStorage(ctx) } -func (vm *VirtualMachine) addSwapLayout(name string) { +func (vm *VirtualMachine) addSwapLayout(ctx *Context, name string) { vm.Layout.SwapFile = name - vm.updateStorage() + vm.updateStorage(ctx) } -func (vm *VirtualMachine) addSnapshotLayout(snapshot types.ManagedObjectReference, dataKey int32) { +func (vm *VirtualMachine) addSnapshotLayout(ctx *Context, snapshot types.ManagedObjectReference, dataKey int32) { for _, snapshotLayout := range vm.Layout.Snapshot { if snapshotLayout.Key == snapshot { return @@ -769,10 +758,10 @@ func (vm *VirtualMachine) addSnapshotLayout(snapshot types.ManagedObjectReferenc SnapshotFile: snapshotFiles, }) - vm.updateStorage() + vm.updateStorage(ctx) } -func (vm *VirtualMachine) addSnapshotLayoutEx(snapshot types.ManagedObjectReference, dataKey int32, memoryKey int32) { +func (vm *VirtualMachine) addSnapshotLayoutEx(ctx *Context, snapshot types.ManagedObjectReference, dataKey int32, memoryKey int32) { for _, snapshotLayoutEx := range vm.LayoutEx.Snapshot { if snapshotLayoutEx.Key == snapshot { return @@ -788,11 +777,11 @@ func (vm *VirtualMachine) addSnapshotLayoutEx(snapshot types.ManagedObjectRefere vm.LayoutEx.Timestamp = time.Now() - vm.updateStorage() + vm.updateStorage(ctx) } // Updates both vm.Layout.Disk and vm.LayoutEx.Disk -func (vm *VirtualMachine) updateDiskLayouts() types.BaseMethodFault { +func (vm *VirtualMachine) updateDiskLayouts(ctx *Context) types.BaseMethodFault { var disksLayout []types.VirtualMachineFileLayoutDiskLayout var disksLayoutEx []types.VirtualMachineFileLayoutExDiskLayout @@ -818,8 +807,8 @@ func (vm *VirtualMachine) updateDiskLayouts() types.BaseMethodFault { return fault } - datastore := vm.useDatastore(p.Datastore) - dFilePath := path.Join(datastore.Info.GetDatastoreInfo().Url, p.Path) + datastore := vm.useDatastore(ctx, p.Datastore) + dFilePath := datastore.resolve(ctx, p.Path) var fileSize int64 // If file can not be opened - fileSize will be 0 @@ -827,7 +816,7 @@ func (vm *VirtualMachine) updateDiskLayouts() types.BaseMethodFault { fileSize = dFileInfo.Size() } - diskKey := vm.addFileLayoutEx(*p, fileSize) + diskKey := vm.addFileLayoutEx(ctx, *p, fileSize) fileKeys = append(fileKeys, diskKey) } @@ -852,12 +841,12 @@ func (vm *VirtualMachine) updateDiskLayouts() types.BaseMethodFault { vm.LayoutEx.Disk = disksLayoutEx vm.LayoutEx.Timestamp = time.Now() - vm.updateStorage() + vm.updateStorage(ctx) return nil } -func (vm *VirtualMachine) updateStorage() types.BaseMethodFault { +func (vm *VirtualMachine) updateStorage(ctx *Context) types.BaseMethodFault { // Committed - sum of Size for each file in vm.LayoutEx.File // Unshared - sum of Size for each disk (.vmdk) in vm.LayoutEx.File // Uncommitted - disk capacity minus disk usage (only currently used disk) @@ -871,7 +860,7 @@ func (vm *VirtualMachine) updateStorage() types.BaseMethodFault { return fault } - datastore := vm.useDatastore(p.Datastore) + datastore := vm.useDatastore(ctx, p.Datastore) dsUsage := &types.VirtualMachineUsageOnDatastore{ Datastore: datastore.Self, } @@ -964,8 +953,8 @@ func (vm *VirtualMachine) RefreshStorageInfo(ctx *Context, req *types.RefreshSto return body } - datastore := vm.useDatastore(p.Datastore) - directory := path.Join(datastore.Info.GetDatastoreInfo().Url, p.Path) + datastore := vm.useDatastore(ctx, p.Datastore) + directory := datastore.resolve(ctx, p.Path) if path.Ext(p.Path) == ".vmx" { directory = path.Dir(directory) // vm.Config.Files.VmPathName can be a directory or full path to .vmx @@ -988,11 +977,11 @@ func (vm *VirtualMachine) RefreshStorageInfo(ctx *Context, req *types.RefreshSto Path: strings.TrimPrefix(file.Name(), datastore.Info.GetDatastoreInfo().Url), } info, _ := file.Info() - vm.addFileLayoutEx(datastorePath, info.Size()) + vm.addFileLayoutEx(ctx, datastorePath, info.Size()) } } - fault := vm.updateDiskLayouts() + fault := vm.updateDiskLayouts(ctx) if fault != nil { body.Fault_ = Fault("", fault) return body @@ -1005,14 +994,14 @@ func (vm *VirtualMachine) RefreshStorageInfo(ctx *Context, req *types.RefreshSto return body } -func (vm *VirtualMachine) findDatastore(name string) *Datastore { - host := Map.Get(*vm.Runtime.Host).(*HostSystem) +func (vm *VirtualMachine) findDatastore(ctx *Context, name string) *Datastore { + host := ctx.Map.Get(*vm.Runtime.Host).(*HostSystem) - return Map.FindByName(name, host.Datastore).(*Datastore) + return ctx.Map.FindByName(name, host.Datastore).(*Datastore) } -func (vm *VirtualMachine) useDatastore(name string) *Datastore { - ds := vm.findDatastore(name) +func (vm *VirtualMachine) useDatastore(ctx *Context, name string) *Datastore { + ds := vm.findDatastore(ctx, name) if FindReference(vm.Datastore, ds.Self) == nil { vm.Datastore = append(vm.Datastore, ds.Self) } @@ -1030,16 +1019,16 @@ func (vm *VirtualMachine) vmx(spec *types.VirtualMachineConfigSpec) object.Datas return p } -func (vm *VirtualMachine) createFile(spec string, name string, register bool) (*os.File, types.BaseMethodFault) { +func (vm *VirtualMachine) createFile(ctx *Context, spec string, name string, register bool) (*os.File, types.BaseMethodFault) { p, fault := parseDatastorePath(spec) if fault != nil { return nil, fault } - ds := vm.useDatastore(p.Datastore) + ds := vm.useDatastore(ctx, p.Datastore) nhost := len(ds.Host) - if ds.Name == "vsanDatastore" && nhost < 3 { + if internal.IsDatastoreVSAN(ds.Datastore) && nhost < 3 { fault := new(types.CannotCreateFile) fault.FaultMessage = []types.LocalizableMessage{ { @@ -1055,7 +1044,7 @@ func (vm *VirtualMachine) createFile(spec string, name string, register bool) (* return nil, fault } - file := path.Join(ds.Info.GetDatastoreInfo().Url, p.Path) + file := ds.resolve(ctx, p.Path) if name != "" { if path.Ext(p.Path) == ".vmx" { @@ -1141,7 +1130,7 @@ func (vm *VirtualMachine) create(ctx *Context, spec *types.VirtualMachineConfigS } for _, file := range files { - f, err := vm.createFile(file.spec, file.name, register) + f, err := vm.createFile(ctx, file.spec, file.name, register) if err != nil { return err } @@ -1231,28 +1220,28 @@ func changedDiskSize(oldDisk *types.VirtualDisk, newDiskSpec *types.VirtualDisk) return newDiskSpec.CapacityInBytes, true } -func (vm *VirtualMachine) validateSwitchMembers(id string) types.BaseMethodFault { +func (vm *VirtualMachine) validateSwitchMembers(ctx *Context, id string) types.BaseMethodFault { var dswitch *DistributedVirtualSwitch var find func(types.ManagedObjectReference) find = func(child types.ManagedObjectReference) { - s, ok := Map.Get(child).(*DistributedVirtualSwitch) + s, ok := ctx.Map.Get(child).(*DistributedVirtualSwitch) if ok && s.Uuid == id { dswitch = s return } - walk(Map.Get(child), find) + walk(ctx.Map.Get(child), find) } - f := Map.getEntityDatacenter(vm).NetworkFolder - walk(Map.Get(f), find) // search in NetworkFolder and any sub folders + f := ctx.Map.getEntityDatacenter(vm).NetworkFolder + walk(ctx.Map.Get(f), find) // search in NetworkFolder and any sub folders if dswitch == nil { log.Printf("DVS %s cannot be found", id) return new(types.NotFound) } - h := Map.Get(*vm.Runtime.Host).(*HostSystem) - c := hostParent(&h.HostSystem) + h := ctx.Map.Get(*vm.Runtime.Host).(*HostSystem) + c := hostParent(ctx, &h.HostSystem) isMember := func(val types.ManagedObjectReference) bool { for _, mem := range dswitch.Summary.HostMember { if mem == val { @@ -1332,7 +1321,7 @@ func (vm *VirtualMachine) configureDevice( summary = fmt.Sprintf("DVSwitch: %s", b.Port.SwitchUuid) net.Type = "DistributedVirtualPortgroup" net.Value = b.Port.PortgroupKey - if err := vm.validateSwitchMembers(b.Port.SwitchUuid); err != nil { + if err := vm.validateSwitchMembers(ctx, b.Port.SwitchUuid); err != nil { return err } } @@ -1401,7 +1390,7 @@ func (vm *VirtualMachine) configureDevice( path.FromString(info.FileName) if path.Path == "" { - filename, err := vm.genVmdkPath(path) + filename, err := vm.genVmdkPath(ctx, path) if err != nil { return err } @@ -1409,7 +1398,7 @@ func (vm *VirtualMachine) configureDevice( info.FileName = filename } - err := vdmCreateVirtualDisk(spec.FileOperation, &types.CreateVirtualDisk_Task{ + err := vdmCreateVirtualDisk(ctx, spec.FileOperation, &types.CreateVirtualDisk_Task{ Datacenter: &dc.Self, Name: info.FileName, }) @@ -1422,7 +1411,7 @@ func (vm *VirtualMachine) configureDevice( }) p, _ := parseDatastorePath(info.FileName) - ds := vm.findDatastore(p.Datastore) + ds := vm.findDatastore(ctx, p.Datastore) info.Datastore = &ds.Self if oldDevice != nil { @@ -1442,7 +1431,7 @@ func (vm *VirtualMachine) configureDevice( ds.Info.GetDatastoreInfo().FreeSpace = ds.Summary.FreeSpace }) - vm.updateDiskLayouts() + vm.updateDiskLayouts(ctx) if disk, ok := b.(*types.VirtualDiskFlatVer2BackingInfo); ok { // These properties default to false @@ -1534,7 +1523,7 @@ func (vm *VirtualMachine) removeDevice(ctx *Context, devices object.VirtualDevic file = b.GetVirtualDeviceFileBackingInfo().FileName p, _ := parseDatastorePath(file) - ds := vm.findDatastore(p.Datastore) + ds := vm.findDatastore(ctx, p.Datastore) ctx.WithLock(ds, func() { ds.Summary.FreeSpace += getDiskSize(device) @@ -1560,7 +1549,7 @@ func (vm *VirtualMachine) removeDevice(ctx *Context, devices object.VirtualDevic {Name: "summary.config.numVirtualDisks", Val: vm.Summary.Config.NumVirtualDisks - 1}, }) - vm.updateDiskLayouts() + vm.updateDiskLayouts(ctx) case types.BaseVirtualEthernetCard: var net types.ManagedObjectReference @@ -1593,7 +1582,7 @@ func (vm *VirtualMachine) removeDevice(ctx *Context, devices object.VirtualDevic return devices } -func (vm *VirtualMachine) genVmdkPath(p object.DatastorePath) (string, types.BaseMethodFault) { +func (vm *VirtualMachine) genVmdkPath(ctx *Context, p object.DatastorePath) (string, types.BaseMethodFault) { if p.Datastore == "" { p.FromString(vm.Config.Files.VmPathName) } @@ -1612,7 +1601,7 @@ func (vm *VirtualMachine) genVmdkPath(p object.DatastorePath) (string, types.Bas filename = fmt.Sprintf("%s_%d.vmdk", vm.Config.Name, index) } - f, err := vm.createFile(vmdir, filename, false) + f, err := vm.createFile(ctx, vmdir, filename, false) if err != nil { switch err.(type) { case *types.FileAlreadyExists: @@ -1898,7 +1887,7 @@ func (vm *VirtualMachine) configureDevices(ctx *Context, spec *types.VirtualMach ctx.Update(vm, append(changes, change)) } - err = vm.updateDiskLayouts() + err = vm.updateDiskLayouts(ctx) if err != nil { return err } @@ -1935,7 +1924,7 @@ func (c *powerVMTask) Run(task *Task) (types.AnyType, types.BaseMethodFault) { boot = time.Now() } - event := c.event() + event := c.event(c.ctx) switch c.state { case types.VirtualMachinePowerStatePoweredOn: if c.VirtualMachine.hostInMM(c.ctx) { @@ -2090,7 +2079,7 @@ func (vm *VirtualMachine) RebootGuest(ctx *Context, req *types.RebootGuest) soap func (vm *VirtualMachine) ReconfigVMTask(ctx *Context, req *types.ReconfigVM_Task) soap.HasFault { task := CreateTask(vm, "reconfigVm", func(t *Task) (types.AnyType, types.BaseMethodFault) { ctx.postEvent(&types.VmReconfiguredEvent{ - VmEvent: vm.event(), + VmEvent: vm.event(ctx), ConfigSpec: req.Spec, }) @@ -2330,7 +2319,7 @@ func (vm *VirtualMachine) UnregisterVM(ctx *Context, c *types.UnregisterVM) soap ctx.Map.RemoveReference(ctx, ds, &ds.Vm, vm.Self) } - ctx.postEvent(&types.VmRemovedEvent{VmEvent: vm.event()}) + ctx.postEvent(&types.VmRemovedEvent{VmEvent: vm.event(ctx)}) if f, ok := asFolderMO(ctx.Map.getEntityParent(vm, "Folder")); ok { folderRemoveChild(ctx, f, c.This) } @@ -2373,7 +2362,7 @@ func (vm *VirtualMachine) CloneVMTask(ctx *Context, req *types.CloneVM_Task) soa folder, _ := asFolderMO(ctx.Map.Get(req.Folder)) host := ctx.Map.Get(*destHost).(*HostSystem) - event := vm.event() + event := vm.event(ctx) ctx.postEvent(&types.VmBeingClonedEvent{ VmCloneEvent: types.VmCloneEvent{ @@ -2479,7 +2468,7 @@ func (vm *VirtualMachine) CloneVMTask(ctx *Context, req *types.CloneVM_Task) soa } ctx.postEvent(&types.VmClonedEvent{ - VmCloneEvent: types.VmCloneEvent{VmEvent: clone.event()}, + VmCloneEvent: types.VmCloneEvent{VmEvent: clone.event(ctx)}, SourceVm: *event.Vm, }) @@ -2551,9 +2540,9 @@ func (vm *VirtualMachine) RelocateVMTask(ctx *Context, req *types.RelocateVM_Tas } ctx.postEvent(&types.VmMigratedEvent{ - VmEvent: vm.event(), + VmEvent: vm.event(ctx), SourceHost: *ctx.Map.Get(*vm.Runtime.Host).(*HostSystem).eventArgument(), - SourceDatacenter: datacenterEventArgument(vm), + SourceDatacenter: datacenterEventArgument(ctx, vm), SourceDatastore: ctx.Map.Get(vm.Datastore[0]).(*Datastore).eventArgument(), }) @@ -2574,7 +2563,7 @@ func (vm *VirtualMachine) customize(ctx *Context) { return } - event := types.CustomizationEvent{VmEvent: vm.event()} + event := types.CustomizationEvent{VmEvent: vm.event(ctx)} ctx.postEvent(&types.CustomizationStartedEvent{CustomizationEvent: event}) changes := []types.PropertyChange{ @@ -2733,7 +2722,7 @@ func (vm *VirtualMachine) CreateSnapshotTask(ctx *Context, req *types.CreateSnap }) } - snapshot.createSnapshotFiles() + snapshot.createSnapshotFiles(ctx) changes = append(changes, types.PropertyChange{Name: "snapshot.currentSnapshot", Val: snapshot.Self}) ctx.Update(vm, changes) @@ -2799,7 +2788,7 @@ func (vm *VirtualMachine) RemoveAllSnapshotsTask(ctx *Context, req *types.Remove } func (vm *VirtualMachine) fcd(ctx *Context, ds types.ManagedObjectReference, id types.ID) *VStorageObject { - m := ctx.Map.Get(*ctx.Map.content().VStorageObjectManager).(*VcenterVStorageObjectManager) + m := ctx.Map.VStorageObjectManager() if ds.Value != "" { return m.objects[ds][id] } @@ -2867,7 +2856,7 @@ func (vm *VirtualMachine) ShutdownGuest(ctx *Context, c *types.ShutdownGuest) so return r } - event := vm.event() + event := vm.event(ctx) ctx.postEvent(&types.VmGuestShutdownEvent{VmEvent: event}) _ = CreateTask(vm, "shutdownGuest", func(*Task) (types.AnyType, types.BaseMethodFault) { @@ -2900,7 +2889,7 @@ func (vm *VirtualMachine) StandbyGuest(ctx *Context, c *types.StandbyGuest) soap return r } - event := vm.event() + event := vm.event(ctx) ctx.postEvent(&types.VmGuestStandbyEvent{VmEvent: event}) _ = CreateTask(vm, "standbyGuest", func(*Task) (types.AnyType, types.BaseMethodFault) { diff --git a/vendor/github.com/vmware/govmomi/simulator/vm_compatibility_checker.go b/vendor/github.com/vmware/govmomi/simulator/vm_compatibility_checker.go index 398199d356..148c2c83e4 100644 --- a/vendor/github.com/vmware/govmomi/simulator/vm_compatibility_checker.go +++ b/vendor/github.com/vmware/govmomi/simulator/vm_compatibility_checker.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2024-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -43,7 +31,7 @@ func resolveHostsAndPool(ctx *Context, vm, host, pool *types.ManagedObjectRefere poolMo = ctx.Map.Get(*vmMo.ResourcePool).(*ResourcePool) case host != nil: h := ctx.Map.Get(*host).(*HostSystem) - parent := hostParent(&h.HostSystem).ResourcePool + parent := hostParent(ctx, &h.HostSystem).ResourcePool poolMo = ctx.Map.Get(*parent).(*ResourcePool) } diff --git a/vendor/github.com/vmware/govmomi/simulator/vstorage_object_manager.go b/vendor/github.com/vmware/govmomi/simulator/vstorage_object_manager.go index 451dc043fd..0b54982d1d 100644 --- a/vendor/github.com/vmware/govmomi/simulator/vstorage_object_manager.go +++ b/vendor/github.com/vmware/govmomi/simulator/vstorage_object_manager.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2018-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -20,7 +8,6 @@ import ( "log" "net/url" "os" - "path/filepath" "strings" "time" @@ -36,6 +23,7 @@ import ( type VStorageObject struct { types.VStorageObject types.VStorageObjectSnapshotInfo + Metadata []types.KeyValue } type VcenterVStorageObjectManager struct { @@ -55,6 +43,10 @@ func (m *VcenterVStorageObjectManager) object(ds types.ManagedObjectReference, i return nil } +func (m *VcenterVStorageObjectManager) Catalog() map[types.ManagedObjectReference]map[types.ID]*VStorageObject { + return m.objects +} + func (m *VcenterVStorageObjectManager) ListVStorageObject(req *types.ListVStorageObject) soap.HasFault { body := &methods.ListVStorageObjectBody{ Res: &types.ListVStorageObjectResponse{}, @@ -105,7 +97,7 @@ func (m *VcenterVStorageObjectManager) statDatastoreBacking(ctx *Context, ref ty for _, obj := range objs { backing := obj.Config.Backing.(*types.BaseConfigInfoDiskFileBackingInfo) - file, _ := fm.resolve(&dc.Self, backing.FilePath) + file, _ := fm.resolve(ctx, &dc.Self, backing.FilePath) _, res[obj.Config.Id] = os.Stat(file) } @@ -153,10 +145,9 @@ func (m *VcenterVStorageObjectManager) RegisterDisk(ctx *Context, req *types.Reg return invalid() } - st, err := os.Stat(filepath.Join(ds.Info.GetDatastoreInfo().Url, u.Path)) + st, err := os.Stat(ds.resolve(ctx, u.Path)) if err != nil { return invalid() - } if st.IsDir() { return invalid() @@ -183,7 +174,7 @@ func (m *VcenterVStorageObjectManager) RegisterDisk(ctx *Context, req *types.Reg }, } - obj, fault := m.createObject(creq, true) + obj, fault := m.createObject(ctx, creq, true) if fault != nil { body.Fault_ = Fault("", fault) return body @@ -196,17 +187,17 @@ func (m *VcenterVStorageObjectManager) RegisterDisk(ctx *Context, req *types.Reg return body } -func (m *VcenterVStorageObjectManager) createObject(req *types.CreateDisk_Task, register bool) (*types.VStorageObject, types.BaseMethodFault) { +func (m *VcenterVStorageObjectManager) createObject(ctx *Context, req *types.CreateDisk_Task, register bool) (*types.VStorageObject, types.BaseMethodFault) { dir := "fcd" ref := req.Spec.BackingSpec.GetVslmCreateSpecBackingSpec().Datastore - ds := Map.Get(ref).(*Datastore) - dc := Map.getEntityDatacenter(ds) + ds := ctx.Map.Get(ref).(*Datastore) + dc := ctx.Map.getEntityDatacenter(ds) objects, ok := m.objects[ds.Self] if !ok { objects = make(map[types.ID]*VStorageObject) m.objects[ds.Self] = objects - _ = os.Mkdir(filepath.Join(ds.Info.GetDatastoreInfo().Url, dir), 0750) + _ = os.MkdirAll(ds.resolve(ctx, dir), 0750) } id := uuid.New().String() @@ -240,7 +231,7 @@ func (m *VcenterVStorageObjectManager) createObject(req *types.CreateDisk_Task, } if !register { - err := vdmCreateVirtualDisk(types.VirtualDeviceConfigSpecFileOperationCreate, &types.CreateVirtualDisk_Task{ + err := vdmCreateVirtualDisk(ctx, types.VirtualDeviceConfigSpecFileOperationCreate, &types.CreateVirtualDisk_Task{ Datacenter: &dc.Self, Name: path.String(), }) @@ -270,7 +261,7 @@ func (m *VcenterVStorageObjectManager) createObject(req *types.CreateDisk_Task, func (m *VcenterVStorageObjectManager) CreateDiskTask(ctx *Context, req *types.CreateDisk_Task) soap.HasFault { task := CreateTask(m, "createDisk", func(*Task) (types.AnyType, types.BaseMethodFault) { - return m.createObject(req, false) + return m.createObject(ctx, req, false) }) return &methods.CreateDisk_TaskBody{ @@ -471,3 +462,55 @@ func (m *VcenterVStorageObjectManager) ListTagsAttachedToVStorageObject(ctx *Con return body } + +func (m *VcenterVStorageObjectManager) VCenterUpdateVStorageObjectMetadataExTask(ctx *Context, req *types.VCenterUpdateVStorageObjectMetadataEx_Task) soap.HasFault { + task := CreateTask(m, "updateVStorageObjectMetadataEx", func(*Task) (types.AnyType, types.BaseMethodFault) { + obj := m.object(req.Datastore, req.Id) + if obj == nil { + return nil, new(types.InvalidArgument) + } + + var metadata []types.KeyValue + + remove := func(key string) bool { + for _, dk := range req.DeleteKeys { + if key == dk { + return true + } + } + return false + } + + for _, kv := range obj.Metadata { + if !remove(kv.Key) { + metadata = append(metadata, kv) + } + } + + update := func(kv types.KeyValue) bool { + for i := range obj.Metadata { + if obj.Metadata[i].Key == kv.Key { + obj.Metadata[i] = kv + return true + } + } + return false + } + + for _, kv := range req.Metadata { + if !update(kv) { + metadata = append(metadata, kv) + } + } + + obj.Metadata = metadata + + return nil, nil + }) + + return &methods.VCenterUpdateVStorageObjectMetadataEx_TaskBody{ + Res: &types.VCenterUpdateVStorageObjectMetadataEx_TaskResponse{ + Returnval: task.Run(ctx), + }, + } +} diff --git a/vendor/github.com/vmware/govmomi/units/size.go b/vendor/github.com/vmware/govmomi/units/size.go index f4ee3fcfc8..d7b6801d6f 100644 --- a/vendor/github.com/vmware/govmomi/units/size.go +++ b/vendor/github.com/vmware/govmomi/units/size.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2015 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package units diff --git a/vendor/github.com/vmware/govmomi/vapi/simulator/simulator.go b/vendor/github.com/vmware/govmomi/vapi/simulator/simulator.go index b6f95a0bda..391d801ab9 100644 --- a/vendor/github.com/vmware/govmomi/vapi/simulator/simulator.go +++ b/vendor/github.com/vmware/govmomi/vapi/simulator/simulator.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2018-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -97,7 +85,7 @@ type download struct { type handler struct { sync.Mutex - sm *simulator.SessionManager + Map *simulator.Registry ServeMux *http.ServeMux URL url.URL Category map[string]*tags.Category @@ -125,7 +113,7 @@ func init() { // New creates a vAPI simulator. func New(u *url.URL, r *simulator.Registry) ([]string, http.Handler) { s := &handler{ - sm: r.SessionManager(), + Map: r, ServeMux: http.NewServeMux(), URL: *u, Category: make(map[string]*tags.Category), @@ -300,7 +288,7 @@ func (s *handler) isAuthorized(r *http.Request) bool { func (s *handler) hasAuthorization(r *http.Request) (string, bool) { u, p, ok := r.BasicAuth() if ok { // user+pass auth - return u, s.sm.Authenticate(s.URL, &vim.Login{UserName: u, Password: p}) + return u, s.Map.SessionManager().Authenticate(s.URL, &vim.Login{UserName: u, Password: p}) } auth := r.Header.Get("Authorization") return "TODO", strings.HasPrefix(auth, "SIGN ") // token auth @@ -503,8 +491,8 @@ func (s *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - h, _ := s.ServeMux.Handler(r) - h.ServeHTTP(w, r) + // Use ServeHTTP directly and not via handler otherwise the path values like "{id}" are not set + s.ServeMux.ServeHTTP(w, r) } func (s *handler) decode(r *http.Request, w http.ResponseWriter, val interface{}) bool { @@ -926,7 +914,7 @@ func (s *handler) library(w http.ResponseWriter, r *http.Request) { spec.Library.CreationTime = types.NewTime(time.Now()) spec.Library.LastModifiedTime = types.NewTime(time.Now()) spec.Library.UnsetSecurityPolicyID = spec.Library.SecurityPolicyID == "" - dir := libraryPath(&spec.Library, "") + dir := s.libraryPath(&spec.Library, "") if err := os.Mkdir(dir, 0750); err != nil { s.error(w, err) return @@ -1103,7 +1091,7 @@ func (s *handler) syncItem( } // Get the path to the destination library item on the local filesystem. - dstItemPath := libraryPath(dstLib.Library, dstItem.ID) + dstItemPath := s.libraryPath(dstLib.Library, dstItem.ID) // Get the source item. srcItem, ok := srcLib.Item[dstItem.SourceID] @@ -1167,7 +1155,7 @@ func (s *handler) syncItem( } // Update the the destination item's files. - srcItemPath := libraryPath(srcLib.Library, srcItem.ID) + srcItemPath := s.libraryPath(srcLib.Library, srcItem.ID) for i := range dstItem.File { var ( dstFile = &dstItem.File[i] @@ -1362,7 +1350,7 @@ func (s *handler) libraryID(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodDelete: - p := libraryPath(l.Library, "") + p := s.libraryPath(l.Library, "") if err := os.RemoveAll(p); err != nil { s.error(w, err) return @@ -1627,7 +1615,7 @@ func (s *handler) libraryItemID(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodDelete: - p := libraryPath(l.Library, id) + p := s.libraryPath(l.Library, id) if err := os.RemoveAll(p); err != nil { s.error(w, err) return @@ -1730,7 +1718,7 @@ func (s *handler) libraryItemStorageByID(id string) ([]library.Storage, bool) { storage[i] = library.Storage{ StorageBacking: lib.Storage[0], StorageURIs: []string{ - path.Join(libraryPath(lib.Library, id), file.Name), + path.Join(s.libraryPath(lib.Library, id), file.Name), }, Name: file.Name, Version: file.Version, @@ -2264,12 +2252,12 @@ func (s *handler) updateFileInfo(id string) *update { } // libraryPath returns the local Datastore fs path for a Library or Item if id is specified. -func libraryPath(l *library.Library, id string) string { +func (s *handler) libraryPath(l *library.Library, id string) string { dsref := types.ManagedObjectReference{ Type: "Datastore", Value: l.Storage[0].DatastoreID, } - ds := simulator.Map.Get(dsref).(*simulator.Datastore) + ds := s.Map.Get(dsref).(*simulator.Datastore) if !isValidFileName(l.ID) || !isValidFileName(id) { panic("invalid file name") @@ -2290,7 +2278,7 @@ func (s *handler) libraryItemFileCreate( return errors.New("invalid file name") } - dstItemPath := libraryPath(up.Library, up.Session.LibraryItemID) + dstItemPath := s.libraryPath(up.Library, up.Session.LibraryItemID) if err := os.MkdirAll(dstItemPath, 0750); err != nil { return err } @@ -2422,7 +2410,7 @@ func (s *handler) libraryItemFileData(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) return } - p := path.Join(libraryPath(dl.Library, dl.Session.LibraryItemID), name) + p := path.Join(s.libraryPath(dl.Library, dl.Session.LibraryItemID), name) f, err := os.Open(p) if err != nil { s.error(w, err) @@ -2547,7 +2535,7 @@ func (s *handler) libraryDeploy(ctx context.Context, c *vim25.Client, lib *libra } name := item.ovf() - desc, err := os.ReadFile(filepath.Join(libraryPath(lib, item.ID), name)) + desc, err := os.ReadFile(filepath.Join(s.libraryPath(lib, item.ID), name)) if err != nil { return nil, err } diff --git a/vendor/github.com/vmware/govmomi/vim25/mo/registry.go b/vendor/github.com/vmware/govmomi/vim25/mo/registry.go index deacf508bb..ed5b5e3595 100644 --- a/vendor/github.com/vmware/govmomi/vim25/mo/registry.go +++ b/vendor/github.com/vmware/govmomi/vim25/mo/registry.go @@ -1,21 +1,27 @@ -/* -Copyright (c) 2014 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package mo -import "reflect" +import ( + "reflect" + + "github.com/vmware/govmomi/vim25/types" +) var t = map[string]reflect.Type{} + +// TODO: 9.0 mo below, not included in the generate mo/mo.go, since the generator still uses older rbvmomi vmodl.db + +type DirectPathProfileManager struct { + Self types.ManagedObjectReference `json:"self"` +} + +func (m DirectPathProfileManager) Reference() types.ManagedObjectReference { + return m.Self +} + +func init() { + t["DirectPathProfileManager"] = reflect.TypeOf((*DirectPathProfileManager)(nil)).Elem() +} diff --git a/vendor/github.com/vmware/govmomi/vim25/mo/retrieve.go b/vendor/github.com/vmware/govmomi/vim25/mo/retrieve.go index 66a8a97820..51b4c8c3af 100644 --- a/vendor/github.com/vmware/govmomi/vim25/mo/retrieve.go +++ b/vendor/github.com/vmware/govmomi/vim25/mo/retrieve.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2014-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package mo @@ -36,6 +24,11 @@ func ignoreMissingProperty(ref types.ManagedObjectReference, p types.MissingProp // Seen with vApp child VM return true } + case "ResourcePool": + switch p.Path { + case "resourceConfigSpecDetailed": + return true + } } return false diff --git a/vendor/github.com/vmware/govmomi/vim25/mo/type_info.go b/vendor/github.com/vmware/govmomi/vim25/mo/type_info.go index cfe5e0afbc..3068da1c82 100644 --- a/vendor/github.com/vmware/govmomi/vim25/mo/type_info.go +++ b/vendor/github.com/vmware/govmomi/vim25/mo/type_info.go @@ -1,18 +1,6 @@ -/* -Copyright (c) 2014-2024 VMware, Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// © Broadcom. All Rights Reserved. +// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. +// SPDX-License-Identifier: Apache-2.0 package mo @@ -192,8 +180,10 @@ var nilValue reflect.Value func assignValue(val reflect.Value, fi []int, pv reflect.Value, field ...string) { // Indexed property path can only use base types if val.Kind() == reflect.Interface { - base := baseType(val.Type()) - val.Set(reflect.New(base)) + if val.IsNil() { + base := baseType(val.Type()) + val.Set(reflect.New(base)) + } val = val.Elem() } diff --git a/vendor/github.com/vmware/govmomi/vim25/soap/client.go b/vendor/github.com/vmware/govmomi/vim25/soap/client.go index 7b4b26ab69..b7ff99f5a6 100644 --- a/vendor/github.com/vmware/govmomi/vim25/soap/client.go +++ b/vendor/github.com/vmware/govmomi/vim25/soap/client.go @@ -214,9 +214,8 @@ func (c *Client) NewServiceClient(path string, namespace string) *Client { return c.newServiceClientWithTransport(path, namespace, c.t) } -// SessionCookie returns a SessionCookie with value of the vmware_soap_session http.Cookie. -func (c *Client) SessionCookie() *HeaderElement { - for _, cookie := range c.Jar.Cookies(c.URL()) { +func sessionCookie(jar http.CookieJar, u *url.URL) *HeaderElement { + for _, cookie := range jar.Cookies(u) { if cookie.Name == SessionCookieName { return &HeaderElement{Value: cookie.Value} } @@ -224,6 +223,22 @@ func (c *Client) SessionCookie() *HeaderElement { return nil } +// SessionCookie returns a SessionCookie with value of the vmware_soap_session http.Cookie. +func (c *Client) SessionCookie() *HeaderElement { + u := c.URL() + + if cookie := sessionCookie(c.Jar, u); cookie != nil { + return cookie + } + + // Default "/sdk" Path would match above, + // but saw a case of Path == "sdk", where above returns nil. + // The jar entry Path is normally "/", so fallback to that. + u.Path = "/" + + return sessionCookie(c.Jar, u) +} + func (c *Client) newServiceClientWithTransport(path string, namespace string, t *http.Transport) *Client { vc := c.URL() u, err := url.Parse(path) diff --git a/vendor/modules.txt b/vendor/modules.txt index 86fad1ac1b..42eb6b0c0f 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1569,8 +1569,8 @@ github.com/ulikunitz/xz/lzma # github.com/vincent-petithory/dataurl v1.0.0 ## explicit github.com/vincent-petithory/dataurl -# github.com/vmware/govmomi v0.47.1 -## explicit; go 1.21 +# github.com/vmware/govmomi v0.49.0 +## explicit; go 1.23.0 github.com/vmware/govmomi github.com/vmware/govmomi/cli/esx github.com/vmware/govmomi/cns