Drop vsphere cloud provider

Signed-off-by: Davanum Srinivas <davanum@gmail.com>
This commit is contained in:
Davanum Srinivas
2024-01-23 19:31:45 -05:00
parent e50efe5b9d
commit 65d67101e7
356 changed files with 2 additions and 235067 deletions

View File

@@ -1,2 +0,0 @@
Dockerfile*
.*ignore

View File

@@ -1,13 +0,0 @@
secrets.yml
dist/
.idea/
# ignore tools binaries
/git-chglog
# ignore RELEASE-specific CHANGELOG
/RELEASE_CHANGELOG.md
# Ignore editor temp files
*~
.vscode/

View File

@@ -1,18 +0,0 @@
linters:
disable-all: true
enable:
- goimports
- govet
# Run with --fast=false for more extensive checks
fast: true
# override defaults
linters-settings:
goimports:
# put imports beginning with prefix after 3rd-party packages;
# it's a comma-separated list of prefixes
local-prefixes: github.com/vmware/govmomi
run:
timeout: 6m
skip-dirs:
- vim25/xml
- cns/types

View File

@@ -1,151 +0,0 @@
---
project_name: govmomi
builds:
- id: govc
goos: &goos-defs
- linux
- darwin
- windows
- freebsd
goarch: &goarch-defs
- amd64
- arm
- arm64
- mips64le
env:
- CGO_ENABLED=0
- PKGPATH=github.com/vmware/govmomi/govc/flags
main: ./govc/main.go
binary: govc
ldflags:
- "-X {{.Env.PKGPATH}}.BuildVersion={{.Version}} -X {{.Env.PKGPATH}}.BuildCommit={{.ShortCommit}} -X {{.Env.PKGPATH}}.BuildDate={{.Date}}"
- id: vcsim
goos: *goos-defs
goarch: *goarch-defs
env:
- CGO_ENABLED=0
main: ./vcsim/main.go
binary: vcsim
ldflags:
- "-X main.buildVersion={{.Version}} -X main.buildCommit={{.ShortCommit}} -X main.buildDate={{.Date}}"
archives:
- id: govcbuild
builds:
- govc
name_template: >-
govc_
{{- title .Os }}_
{{- if eq .Arch "amd64" }}x86_64
{{- else if eq .Arch "386" }}i386
{{- else }}{{ .Arch }}{{ end }}
format_overrides: &overrides
- goos: windows
format: zip
files: &extrafiles
- CHANGELOG.md
- LICENSE.txt
- README.md
- id: vcsimbuild
builds:
- vcsim
name_template: >-
vcsim_
{{- title .Os }}_
{{- if eq .Arch "amd64" }}x86_64
{{- else if eq .Arch "386" }}i386
{{- else }}{{ .Arch }}{{ end }}
format_overrides: *overrides
files: *extrafiles
snapshot:
name_template: "{{ .Tag }}-next"
checksum:
name_template: "checksums.txt"
changelog:
sort: asc
filters:
exclude:
- "^docs:"
- "^test:"
- Merge pull request
- Merge branch
# upload disabled since it is maintained in homebrew-core
brews:
- name: govc
ids:
- govcbuild
tap:
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
folder: Formula
homepage: "https://github.com/vmware/govmomi/blob/master/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
tap:
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
folder: Formula
homepage: "https://github.com/vmware/govmomi/blob/master/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 }}"
- "vmware/govc:{{ .ShortCommit }}"
- "vmware/govc:latest"
dockerfile: Dockerfile.govc
ids:
- govc
build_flag_templates:
- "--pull"
- "--label=org.opencontainers.image.created={{.Date}}"
- "--label=org.opencontainers.image.title={{.ProjectName}}"
- "--label=org.opencontainers.image.revision={{.FullCommit}}"
- "--label=org.opencontainers.image.version={{.Version}}"
- "--label=org.opencontainers.image.url=https://github.com/vmware/govmomi"
- "--platform=linux/amd64"
- image_templates:
- "vmware/vcsim:{{ .Tag }}"
- "vmware/vcsim:{{ .ShortCommit }}"
- "vmware/vcsim:latest"
dockerfile: Dockerfile.vcsim
ids:
- vcsim
build_flag_templates:
- "--pull"
- "--label=org.opencontainers.image.created={{.Date}}"
- "--label=org.opencontainers.image.title={{.ProjectName}}"
- "--label=org.opencontainers.image.revision={{.FullCommit}}"
- "--label=org.opencontainers.image.version={{.Version}}"
- "--label=org.opencontainers.image.url=https://github.com/vmware/govmomi"
- "--platform=linux/amd64"

View File

@@ -1,45 +0,0 @@
amanpaha <amanpahariya@microsoft.com> amanpaha <84718160+amanpaha@users.noreply.github.com>
Amanda H. L. de Andrade <amanda.andrade@serpro.gov.br> Amanda Hager Lopes de Andrade Katz <amanda.katz@serpro.gov.br>
Amanda H. L. de Andrade <amanda.andrade@serpro.gov.br> amandahla <amanda.andrade@serpro.gov.br>
Amit Bathla <abathla@.vmware.com> <abathla@promb-1s-dhcp216.eng.vmware.com>
Andrew Kutz <akutz@vmware.com> <sakutz@gmail.com>
Andrew Kutz <akutz@vmware.com> akutz <akutz@vmware.com>
Andrew Kutz <akutz@vmware.com> Andrew Kutz <101085+akutz@users.noreply.github.com>
Anfernee Yongkun Gui <agui@vmware.com> <anfernee.gui@gmail.com>
Anfernee Yongkun Gui <agui@vmware.com> Yongkun Anfernee Gui <agui@vmware.com>
Anna Carrigan <anna.carrigan@hpe.com> Anna <anna.carrigan@outlook.com>
Balu Dontu <bdontu@vmware.com> BaluDontu <bdontu@vmware.com>
Bruce Downs <bruceadowns@gmail.com> <bdowns@vmware.com>
Bruce Downs <bruceadowns@gmail.com> <bruce.downs@autodesk.com>
Bruce Downs <bruceadowns@gmail.com> <bruce.downs@jivesoftware.com>
Clint Greenwood <cgreenwood@vmware.com> <clint.greenwood@gmail.com>
Cédric Blomart <cblomart@gmail.com> <cedric.blomart@minfin.fed.be>
Cédric Blomart <cblomart@gmail.com> cedric <cblomart@gmail.com>
David Stark <dave@davidstark.name> <david.stark@bskyb.com>
Doug MacEachern <dougm@vmware.com> dougm <dougm@users.noreply.github.com>
Eric Gray <egray@vmware.com> <ericgray@users.noreply.github.com>
Eric Yutao <eric.yutao@gmail.com> eric <eric.yutao@gmail.com>
Fabio Rapposelli <fabio@vmware.com> <fabio@rapposelli.org>
Faiyaz Ahmed <faiyaza@vmware.com> Faiyaz Ahmed <ahmedf@vmware.com>
Faiyaz Ahmed <faiyaza@vmware.com> Faiyaz Ahmed <faiyaza@gmail.com>
Faiyaz Ahmed <faiyaza@vmware.com> Faiyaz Ahmed <fdawg4l@users.noreply.github.com>
Henrik Hodne <henrik@travis-ci.com> <henrik@hodne.io>
Ian Eyberg <ian@deferpanic.com> <ian@opuler.com>
Jeremy Canady <jcanady@jackhenry.com> <jcanady@gmail.com>
Jiatong Wang <wjiatong@vmware.com> jiatongw <wjiatong@vmware.com>
Lintong Jiang <lintongj@vmware.com> lintongj <55512168+lintongj@users.noreply.github.com>
Michael Gasch <mgasch@vmware.com> Michael Gasch <embano1@live.com>
Mincho Tonev <mtonev@vmware.com> matonev <31008054+matonev@users.noreply.github.com>
Parveen Chahal <parkuma@microsoft.com> <mail.chahal@gmail.com>
Pieter Noordhuis <pnoordhuis@vmware.com> <pcnoordhuis@gmail.com>
Saad Malik <saad@spectrocloud.com> <simfox3@gmail.com>
Takaaki Furukawa <takaaki.frkw@gmail.com> takaaki.furukawa <takaaki.furukawa@mail.rakuten.com>
Takaaki Furukawa <takaaki.frkw@gmail.com> tkak <takaaki.frkw@gmail.com>
Uwe Bessle <Uwe.Bessle@iteratec.de> Uwe Bessle <u.bessle.extern@eos-ts.com>
Uwe Bessle <Uwe.Bessle@iteratec.de> Uwe Bessle <uwe.bessle@web.de>
Vadim Egorov <vegorov@vmware.com> <egorovv@gmail.com>
William Lam <wlam@vmware.com> <info.virtuallyghetto@gmail.com>
Yun Zhou <yunz@vmware.com> <41678287+gh05tn0va@users.noreply.github.com>
Zach G <zguan@vmware.com> zach96guan <zach96guan@users.noreply.github.com>
Zach Tucker <ztucker@vmware.com> <jzt@users.noreply.github.com>
Zee Yang <zeey@vmware.com> <zee.yang@gmail.com>

File diff suppressed because it is too large Load Diff

View File

@@ -1,197 +0,0 @@
# Contributing to `govmomi`
## Getting started
First, fork the repository on GitHub to your personal account.
Change `$USER` in the examples below to your Github username if they are not the
same.
```bash
git clone https://github.com/vmware/govmomi.git && cd govmomi
# prevent accidentally pushing to vmware/govmomi
git config push.default nothing
git remote rename origin vmware
# add your fork
git remote add $USER git@github.com:$USER/govmomi.git
git fetch -av
```
## Contribution Flow
This is a rough outline of what a contributor's workflow looks like:
- Create an issue describing the feature/fix
- Create a topic branch from where you want to base your work.
- Make commits of logical units.
- Make sure your commit messages are in the proper format (see below).
- Push your changes to a topic branch in your fork of the repository.
- Submit a pull request to `vmware/govmomi`.
See [below](#format-of-the-commit-message) for details on commit best practices
and **supported prefixes**, e.g. `govc: <message>`.
> **Note:** If you are new to Git(hub) check out [Git rebase, squash...oh
> my!](https://www.mgasch.com/2021/05/git-basics/) for more details on how to
> successfully contribute to an open source project.
### Example 1 - Fix a Bug in `govmomi`
```bash
git checkout -b issue-<number> vmware/master
git add <files>
git commit -m "fix: ..." -m "Closes: #<issue-number>"
git push $USER issue-<number>
```
### Example 2 - Add a new (non-breaking) API to `govmomi`
```bash
git checkout -b issue-<number> vmware/master
git add <files>
git commit -m "Add API ..." -m "Closes: #<issue-number>"
git push $USER issue-<number>
```
### Example 3 - Add a Feature to `govc`
```bash
git checkout -b issue-<number> vmware/master
git add <files>
git commit -m "govc: Add feature ..." -m "Closes: #<issue-number>"
git push $USER issue-<number>
```
**Note**:
To register the new `govc` command package, add a blank `_` import to `govmomi/govc/main.go`.
### Example 4 - Fix a Bug in `vcsim`
```bash
git checkout -b issue-<number> vmware/master
git add <files>
git commit -m "vcsim: Fix ..." -m "Closes: #<issue-number>"
git push $USER issue-<number>
```
### Example 5 - Document Breaking (API) Changes
Breaking changes, e.g. to the `govmomi` APIs, are highlighted in the `CHANGELOG`
and release notes when the keyword `BREAKING:` is used in the commit message
body.
The text after `BREAKING:` is used in the corresponding highlighted section.
Thus these details should be stated at the body of the commit message.
Multi-line strings are supported.
```bash
git checkout -b issue-<number> vmware/master
git add <files>
cat << EOF | git commit -F -
Add ctx to funcXYZ
This commit introduces context.Context to function XYZ
Closes: #1234
BREAKING: Add ctx to funcXYZ()
EOF
git push $USER issue-<number>
```
### Stay in sync with Upstream
When your branch gets out of sync with the vmware/master branch, use the
following to update (rebase):
```bash
git checkout issue-<number>
git fetch -a
git rebase vmware/master
git push --force-with-lease $USER issue-<number>
```
### Updating Pull Requests
If your PR fails to pass CI or needs changes based on code review, it's ok to
add more commits stating the changes made, e.g. "Address review comments". This
is to assist the reviewer(s) to easily detect and review the recent changes.
In case of small PRs, it's ok to squash and force-push (see further below)
directly instead.
```bash
# incorporate review feedback
git add .
# create a fixup commit which will be merged into your (original) <commit>
git commit --fixup <commit>
git push $USER issue-<number>
```
Be sure to add a comment to the PR indicating your new changes are ready to
review, as Github does not generate a notification when you git push.
Once the review is complete, squash and push your final commit(s):
```bash
# squash all commits into one
# --autosquash will automatically detect and merge fixup commits
git rebase -i --autosquash vmware/master
git push --force-with-lease $USER issue-<number>
```
### Code Style
The coding style suggested by the Go community is used in `govmomi`. See the
[style doc](https://github.com/golang/go/wiki/CodeReviewComments) for details.
Try to limit column width to 120 characters for both code and markdown documents
such as this one.
### Format of the Commit Message
We follow the conventions described in [How to Write a Git Commit
Message](http://chris.beams.io/posts/git-commit/).
Be sure to include any related GitHub issue references in the commit message,
e.g. `Closes: #<number>`.
The [`CHANGELOG.md`](./CHANGELOG.md) and release page uses **commit message
prefixes** for grouping and highlighting. A commit message that
starts with `[prefix:] ` will place this commit under the respective
section in the `CHANGELOG`.
The following example creates a commit referencing the `issue: 1234` and puts
the commit message in the `govc` `CHANGELOG` section:
```bash
git commit -s -m "govc: Add CLI command X" -m "Closes: #1234"
```
Currently the following prefixes are used:
- `api:` - Use for API-related changes
- `govc:` - Use for changes to `govc` CLI
- `vcsim:` - Use for changes to vCenter Simulator
- `chore:` - Use for repository related activities
- `fix:` - Use for bug fixes
- `docs:` - Use for changes to the documentation
- `examples:` - Use for changes to examples
If your contribution falls into multiple categories, e.g. `api` and `vcsim` it
is recommended to break up your commits using distinct prefixes.
### Running CI Checks and Tests
You can run both `make check` and `make test` from the top level of the
repository.
While `make check` will catch formatting and import errors, it will not apply
any fixes. The developer is expected to do that.
## Reporting Bugs and Creating Issues
When opening a new issue, try to roughly follow the commit message format
conventions above.

View File

@@ -1,256 +0,0 @@
# People who can (and typically have) contributed to this repository.
#
# This script is generated by contributors.sh
#
Abhijeet Kasurde <akasurde@redhat.com>
abrarshivani <abrarshivani@users.noreply.github.com>
Adam Chalkley <atc0005@users.noreply.github.com>
Adam Fowler <adam@adamfowler.org>
Adam Shannon <adamkshannon@gmail.com>
Akanksha Panse <pansea@vmware.com>
Al Biheiri <abiheiri@apple.com>
Alessandro Cortiana <alessandro.cortiana@gmail.com>
Alex <puzo2002@gmail.com>
Alex Bozhenko <alexbozhenko@fb.com>
Alex Ellis (VMware) <alexellis2@gmail.com>
Aligator <8278538+yet-another-aligator@users.noreply.github.com>
Alvaro Miranda <kikitux@gmail.com>
Amanda H. L. de Andrade <amanda.andrade@serpro.gov.br>
amanpaha <amanpahariya@microsoft.com>
Amit Bathla <abathla@.vmware.com>
amit bezalel <amit.bezalel@hpe.com>
Andrew <AndrewDi@users.noreply.github.com>
Andrew Chin <andrew@andrewtchin.com>
Andrew Kutz <akutz@vmware.com>
Andrey Klimentyev <andrey.klimentyev@flant.com>
Anfernee Yongkun Gui <agui@vmware.com>
angystardust <angystardust@users.noreply.github.com>
aniketGslab <aniket.shinde@gslab.com>
Ankit Vaidya <vaidyaa@vmware.com>
Ankur Huralikoppi <huralikoppia@vmware.com>
Anna Carrigan <anna.carrigan@hpe.com>
Antony Saba <awsaba@gmail.com>
Ariel Chinn <arielchinn@gmail.com>
Arran Walker <arran.walker@zopa.com>
Artem Anisimov <aanisimov@inbox.ru>
Arunesh Pandey <parunesh@vmware.com>
Aryeh Weinreb <aryehweinreb@gmail.com>
Augy StClair <augy@google.com>
Austin Parker <aparker@apprenda.com>
Balu Dontu <bdontu@vmware.com>
bastienbc <bastien.barbe.creuly@gmail.com>
Ben Corrie <bcorrie@vmware.com>
Ben Vickers <bvickers@pivotal.io>
Benjamin Davini <davinib@vmware.com>
Benjamin Peterson <benjamin@python.org>
Benjamin Vickers <bvickers@vmware.com>
Bhavya Choudhary <bhavyac@vmware.com>
Bob Killen <killen.bob@gmail.com>
Brad Fitzpatrick <bradfitz@golang.org>
Brian Rak <brak@vmware.com>
brian57860 <brian57860@users.noreply.github.com>
Bruce Downs <bruceadowns@gmail.com>
Bryan Venteicher <bryanventeicher@gmail.com>
Cédric Blomart <cblomart@gmail.com>
Cheng Cheng <chengch@vmware.com>
Chethan Venkatesh <chethanv@vmware.com>
Choudhury Sarada Prasanna Nanda <cspn@google.com>
Chris Marchesi <chrism@vancluevertech.com>
Christian Höltje <docwhat@gerf.org>
Clint Greenwood <cgreenwood@vmware.com>
cpiment <pimentel.carlos@gmail.com>
CuiHaozhi <cuihaozhi@chinacloud.com.cn>
Dan Ilan <danilan@google.com>
Dan Norris <protochron@users.noreply.github.com>
Daniel Frederick Crisman <daniel@crisman.org>
Daniel Mueller <deso@posteo.net>
Danny Lockard <danny.lockard@banno.com>
Dave Gress <gressd@vmware.com>
Dave Smith-Uchida <dsmithuchida@vmware.com>
Dave Tucker <dave@dtucker.co.uk>
David Gress <gressd@vmware.com>
David Stark <dave@davidstark.name>
Davide Agnello <dagnello@hp.com>
Davinder Kumar <davinderk@vmware.com>
Defa <zhoudefa666@163.com>
demarey <christophe.demarey@inria.fr>
dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Deric Crago <deric.crago@gmail.com>
ditsuke <ditsuke@protonmail.com>
Divyen Patel <divyenp@vmware.com>
Dnyanesh Gate <dnyanesh.gate@druva.com>
Doug MacEachern <dougm@vmware.com>
East <60801291+houfangdong@users.noreply.github.com>
Eloy Coto <eloy.coto@gmail.com>
embano1 <embano1@users.noreply.github.com>
Eng Zer Jun <engzerjun@gmail.com>
Eric Edens <ericedens@google.com>
Eric Graham <16710890+Pheric@users.noreply.github.com>
Eric Gray <egray@vmware.com>
Eric Yutao <eric.yutao@gmail.com>
Erik Hollensbe <github@hollensbe.org>
Essodjolo KAHANAM <essodjolo@kahanam.com>
Ethan Kaley <ethan.kaley@emc.com>
Evan Chu <echu@vmware.com>
Fabio Rapposelli <fabio@vmware.com>
Faiyaz Ahmed <faiyaza@vmware.com>
Federico Pellegatta <12744504+federico-pellegatta@users.noreply.github.com>
forkbomber <forkbomber@users.noreply.github.com>
François Rigault <rigault.francois@gmail.com>
freebsdly <qinhuajun@outlook.com>
Gavin Gray <gavin@infinio.com>
Gavrie Philipson <gavrie.philipson@elastifile.com>
George Hicken <ghicken@vmware.com>
Gerrit Renker <Gerrit.Renker@ctl.io>
gthombare <gthombare@vmware.com>
HakanSunay <hakansunay@abv.bg>
Hasan Mahmood <mahmoodh@vmware.com>
Haydon Ryan <haydon.ryan@gmail.com>
Heiko Reese <hreese@users.noreply.github.com>
Henrik Hodne <henrik@travis-ci.com>
hkumar <hkumar@vmware.com>
Hrabur Stoyanov <hstoyanov@vmware.com>
hui luo <luoh@vmware.com>
Ian Eyberg <ian@deferpanic.com>
Isaac Rodman <isaac@eyz.us>
Ivan Mikushin <imikushin@vmware.com>
Ivan Porto Carrero <icarrero@vmware.com>
James King <james.king@emc.com>
James Peach <jpeach@vmware.com>
Jason Kincl <jkincl@gmail.com>
Jeremy Canady <jcanady@jackhenry.com>
jeremy-clerc <jeremy@clerc.io>
Jiatong Wang <wjiatong@vmware.com>
jingyizPensando <jingyiz@pensando.io>
João Pereira <joaodrp@gmail.com>
Jonas Ausevicius <jonas.ausevicius@virtustream.com>
Jorge Sevilla <jorge.sevilla@rstor.io>
Julien PILLON <jpillon@lesalternatives.org>
Justin J. Novack <jnovack@users.noreply.github.com>
kayrus <kay.diam@gmail.com>
Keenan Brock <keenan@thebrocks.net>
Kevin George <georgek@vmware.com>
Knappek <andy.knapp.ak@gmail.com>
Leslie Wang <qiwa@pensando.io>
leslie-qiwa <leslie.qiwa@gmail.com>
Lintong Jiang <lintongj@vmware.com>
Liping Xue <lipingx@vmware.com>
Louie Jiang <jiangl@vmware.com>
Luther Monson <luther.monson@gmail.com>
Madanagopal Arunachalam <marunachalam@vmware.com>
makelarisjr <8687447+makelarisjr@users.noreply.github.com>
maplain <fangyuanl@vmware.com>
Marc Carmier <mcarmier@gmail.com>
Marcus Tan <marcus.tan@rubrik.com>
Maria Ntalla <maria.ntalla@gmail.com>
Marin Atanasov Nikolov <mnikolov@vmware.com>
Mario Trangoni <mjtrangoni@gmail.com>
Mark Dechiaro <mdechiaro@users.noreply.github.com>
Mark Peek <markpeek@vmware.com>
Mark Rexwinkel <Mark.Rexwinkel@elekta.com>
martin <martin@catai.org>
Matt Clay <matt@mystile.com>
Matt Moore <mattmoor@vmware.com>
Matt Moriarity <matt@mattmoriarity.com>
Matthew Cosgrove <matthew.cosgrove@dell.com>
mbhadale <mbhadale@vmware.com>
Merlijn Sebrechts <merlijn.sebrechts@gmail.com>
Mevan Samaratunga <mevansam@gmail.com>
Michael Gasch <15986659+embano1@users.noreply.github.com>
Michael Gasch <mgasch@vmware.com>
Michal Jankowski <mjankowski@vmware.com>
Mike Schinkel <mike@newclarity.net>
Mincho Tonev <mtonev@vmware.com>
mingwei <mingwei@smartx.com>
Nicolas Lamirault <nicolas.lamirault@gmail.com>
Nikhil Kathare <nikhil.kathare@netapp.com>
Nikhil R Deshpande <ndeshpande@vmware.com>
Nikolas Grottendieck <git@nikolasgrottendieck.com>
Nils Elde <nils.elde@sscinc.com>
nirbhay <nirbhay.bagmar@nutanix.com>
Nobuhiro MIKI <nmiki@yahoo-corp.jp>
Om Kumar <om.kumar@hpe.com>
Omar Kohl <omarkohl@gmail.com>
Parham Alvani <parham.alvani@gmail.com>
Parveen Chahal <parkuma@microsoft.com>
Paul Martin <25058109+rawstorage@users.noreply.github.com>
Pierre Gronlier <pierre.gronlier@corp.ovh.com>
Pieter Noordhuis <pnoordhuis@vmware.com>
pradeepj <50135054+pradeep288@users.noreply.github.com>
Pranshu Jain <jpranshu@vmware.com>
prydin <prydin@vmware.com>
rconde01 <rconde01@hotmail.com>
rHermes <teodor_spaeren@riseup.net>
Rianto Wahyudi <rwahyudi@gmail.com>
Ricardo Katz <rkatz@vmware.com>
Robin Watkins <robwatkins@gmail.com>
Rowan Jacobs <rojacobs@pivotal.io>
Roy Ling <royling0024@gmail.com>
rsikdar <rsikdar@berkeley.edu>
runner.mei <runner.mei@gmail.com>
Ryan Johnson <johnsonryan@vmware.com>
S R Ashrith <sashrith@vmware.com>
S.Çağlar Onur <conur@vmware.com>
Saad Malik <saad@spectrocloud.com>
Sam Zhu <zhusa@zhusa-a02.vmware.com>
samzhu333 <45263849+samzhu333@users.noreply.github.com>
Sandeep Pissay Srinivasa Rao <ssrinivas@vmware.com>
Scott Holden <scott@nullops.io>
Sergey Ignatov <sergey.ignatov@jetbrains.com>
serokles <timbo.alexander@gmail.com>
shahra <shahra@vmware.com>
Shalini Bhaskara <sbhaskara@vmware.com>
Shaozhen Ding <dsz0111@gmail.com>
Shawn Neal <sneal@sneal.net>
shylasrinivas <sshyla@vmware.com>
sky-joker <sky.jokerxx@gmail.com>
smaftoul <samuel.maftoul@gmail.com>
smahadik <smahadik@vmware.com>
Sten Feldman <exile@chamber.ee>
Stepan Mazurov <smazurov@gmail.com>
Steve Purcell <steve@sanityinc.com>
Sudhindra Aithal <sudhiaithal@pensando.io>
SUMIT AGRAWAL <asumit@vmware.com>
Sunny Carter <sunny.carter@metaswitch.com>
syuparn <s.hello.spagetti@gmail.com>
Takaaki Furukawa <takaaki.frkw@gmail.com>
Tamas Eger <tamas.eger@bitrise.io>
Tanay Kothari <tkothari@vmware.com>
tanishi <tanishi503@gmail.com>
Ted Zlatanov <tzz@lifelogs.com>
Thad Craft <tcraft@pivotal.io>
Thibaut Ackermann <thibaut.ackermann@alcatel-lucent.com>
Tim McNamara <tim.mcnamara@canonical.com>
Tjeu Kayim <15987676+TjeuKayim@users.noreply.github.com>
Toomas Pelberg <toomas.pelberg@playtech.com>
Trevor Dawe <trevor.dawe@gmail.com>
tshihad <tshihad9@gmail.com>
Uwe Bessle <Uwe.Bessle@iteratec.de>
Vadim Egorov <vegorov@vmware.com>
Vikram Krishnamurthy <vikramkrishnamu@vmware.com>
volanja <volaaanja@gmail.com>
Volodymyr Bobyr <pupsua@gmail.com>
Waldek Maleska <w.maleska@gmail.com>
William Lam <wlam@vmware.com>
Witold Krecicki <wpk@culm.net>
xing-yang <xingyang105@gmail.com>
xinyanw409 <wxinyan@vmware.com>
Yang Yang <yangy@vmware.com>
yangxi <yangxi@vmware.com>
Yann Hodique <yhodique@google.com>
Yash Nitin Desai <desaiy@vmware.com>
Yassine TIJANI <ytijani@vmware.com>
Yi Jiang <yijiang@vmware.com>
yiyingy <yiyingy@vmware.com>
ykakarap <yuva2811@gmail.com>
Yogesh Sobale <6104071+ysobale@users.noreply.github.com>
Yue Yin <yueyin@yuyin-a01.vmware.com>
Yun Zhou <yunz@vmware.com>
Yuya Kusakabe <yuya.kusakabe@gmail.com>
Zach G <zguan@vmware.com>
Zach Tucker <ztucker@vmware.com>
Zacharias Taubert <zacharias.taubert@gmail.com>
Zee Yang <zeey@vmware.com>
zyuxin <zyuxin@vmware.com>
Кузаков Евгений <kuzakov@satel.org>

View File

@@ -1,45 +0,0 @@
# Create a builder container
# golang:1.18.0-buster amd64
FROM golang@sha256:7d39537344486528f8cdb3bd8adb98ab7f0f4236044b6944fed8631da35a4ce5 AS build
WORKDIR /go/src/app
# Create appuser to isolate potential vulnerabilities
# See https://stackoverflow.com/a/55757473/12429735
ENV USER=appuser
ENV UID=10001
RUN adduser \
--disabled-password \
--gecos "" \
--shell "/sbin/nologin" \
--no-create-home \
--uid "${UID}" \
"${USER}"
# Create a new tmp directory so no bad actors can manipulate it
RUN mkdir /temporary-tmp-directory && chmod 777 /temporary-tmp-directory
###############################################################################
# Final stage
FROM scratch
# Allow container to use latest TLS certificates
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
# Copy over appuser to run as non-root
COPY --from=build /etc/passwd /etc/passwd
COPY --from=build /etc/group /etc/group
# Copy over the /tmp directory for golang/os.TmpDir
COPY --chown=appuser --from=build /temporary-tmp-directory /tmp
# Copy application from external build
COPY govc /govc
# Run all commands as non-root
USER appuser:appuser
# session cache, etc
ENV GOVMOMI_HOME=/tmp
# Set CMD to application with container defaults
CMD ["/govc"]

View File

@@ -1,47 +0,0 @@
# Create a builder container
# golang:1.18.0-buster amd64
FROM golang@sha256:7d39537344486528f8cdb3bd8adb98ab7f0f4236044b6944fed8631da35a4ce5 AS build
WORKDIR /go/src/app
# Create appuser to isolate potential vulnerabilities
# See https://stackoverflow.com/a/55757473/12429735
ENV USER=appuser
ENV UID=10001
RUN adduser \
--disabled-password \
--gecos "" \
--home "/nonexistent" \
--shell "/sbin/nologin" \
--no-create-home \
--uid "${UID}" \
"${USER}"
# Create a new tmp directory so no bad actors can manipulate it
RUN mkdir /temporary-tmp-directory && chmod 777 /temporary-tmp-directory
###############################################################################
# Final stage
FROM scratch
# Run all commands as non-root
USER appuser:appuser
# Allow container to use latest TLS certificates
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
# Copy over appuser to run as non-root
COPY --from=build /etc/passwd /etc/passwd
COPY --from=build /etc/group /etc/group
# Copy over the /tmp directory for golang/os.TmpDir
COPY --chown=appuser --from=build /temporary-tmp-directory /tmp
# Expose application port
EXPOSE 8989
# Copy application from external build
COPY vcsim /vcsim
# Set entrypoint to application with container defaults
ENTRYPOINT [ "/vcsim" ]
CMD ["-l", "0.0.0.0:8989"]

View File

@@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View File

@@ -1,158 +0,0 @@
# Copyright (c) 2021 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# If you update this file, please follow
# https://www.thapaliya.com/en/writings/well-documented-makefiles/
# Ensure Make is run with bash shell as some syntax below is bash-specific
SHELL := /usr/bin/env bash
# Print the help/usage when make is executed without any other arguments
.DEFAULT_GOAL := help
## --------------------------------------
## Help
## --------------------------------------
.PHONY: help
help: ## Display usage
@awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make [target] \033[36m\033[0m\n\nTargets:\n"} /^[a-zA-Z_-]+:.*?##/ { printf " \033[36m%-20s\033[0m %s\n", $$1, $$2 }' $(MAKEFILE_LIST)
## --------------------------------------
## Locations and programs
## --------------------------------------
# Directories
BIN_DIR := bin
TOOLS_DIR := hack/tools
TOOLS_BIN_DIR := $(TOOLS_DIR)/bin
# Tooling binaries
GO ?= $(shell command -v go 2>/dev/null)
GOLANGCI_LINT := $(TOOLS_BIN_DIR)/golangci-lint
## --------------------------------------
## Prerequisites
## --------------------------------------
# Do not proceed unless the go binary is present.
ifeq (,$(strip $(GO)))
$(error The "go" program cannot be found)
endif
## --------------------------------------
## Linting and fixing linter errors
## --------------------------------------
.PHONY: lint
lint: ## Run all the lint targets
$(MAKE) lint-go-full
GOLANGCI_LINT_FLAGS ?= --fast=true
.PHONY: lint-go
lint-go: $(GOLANGCI_LINT) ## Lint codebase
$(GOLANGCI_LINT) run -v $(GOLANGCI_LINT_FLAGS)
.PHONY: lint-go-full
lint-go-full: GOLANGCI_LINT_FLAGS = --fast=false
lint-go-full: lint-go ## Run slower linters to detect possible issues
.PHONY: fix
fix: GOLANGCI_LINT_FLAGS = --fast=false --fix
fix: lint-go ## Tries to fix errors reported by lint-go-full target
.PHONY: check
check: lint-go-full
check: ## Run linters
## --------------------------------------
## Tooling Binaries
## --------------------------------------
TOOLING_BINARIES := $(GOLANGCI_LINT)
tools: $(TOOLING_BINARIES) ## Build tooling binaries
.PHONY: $(TOOLING_BINARIES)
$(TOOLING_BINARIES):
cd $(TOOLS_DIR); make $(@F)
## --------------------------------------
## Build / Install
## --------------------------------------
.PHONY: install
install: ## Install govc and vcsim
$(MAKE) -C govc install
$(MAKE) -C vcsim install
## --------------------------------------
## Generate
## --------------------------------------
.PHONY: mod
mod: ## Runs go mod tidy to validate modules
go mod tidy -v
.PHONY: mod-get
mod-get: ## Downloads and caches the modules
go mod download
.PHONY: doc
doc: install
doc: ## Generates govc USAGE.md
./govc/usage.sh > ./govc/USAGE.md
## --------------------------------------
## Tests
## --------------------------------------
# Test options
TEST_COUNT ?= 1
TEST_TIMEOUT ?= 5m
TEST_RACE_HISTORY_SIZE ?= 5
GORACE ?= history_size=$(TEST_RACE_HISTORY_SIZE)
ifeq (-count,$(findstring -count,$(TEST_OPTS)))
$(error Use TEST_COUNT to override this option)
endif
ifeq (-race,$(findstring -race,$(TEST_OPTS)))
$(error The -race flag is enabled by default & cannot be specified in TEST_OPTS)
endif
ifeq (-timeout,$(findstring -timeout,$(TEST_OPTS)))
$(error Use TEST_TIMEOUT to override this option)
endif
.PHONY: go-test
go-test: ## Runs go unit tests with race detector enabled
GORACE=$(GORACE) $(GO) test \
-count $(TEST_COUNT) \
-race \
-timeout $(TEST_TIMEOUT) \
-v $(TEST_OPTS) \
./...
.PHONY: govc-test
govc-test: install
govc-test: ## Runs govc bats tests
./govc/test/images/update.sh
(cd govc/test && ./vendor/github.com/sstephenson/bats/libexec/bats -t .)
.PHONY: govc-test-sso
govc-test-sso: install
./govc/test/images/update.sh
(cd govc/test && SSO_BATS=1 ./vendor/github.com/sstephenson/bats/libexec/bats -t sso.bats)
.PHONY: govc-test-sso-assert-cert
govc-test-sso-assert-cert:
SSO_BATS_ASSERT_CERT=1 $(MAKE) govc-test-sso
.PHONY: test
test: go-test govc-test ## Runs go-test and govc-test

View File

@@ -1,131 +0,0 @@
<!-- markdownlint-disable first-line-h1 no-inline-html -->
[![Build](https://github.com/vmware/govmomi/actions/workflows/govmomi-build.yaml/badge.svg)][ci-build]
[![Tests](https://github.com/vmware/govmomi/actions/workflows/govmomi-go-tests.yaml/badge.svg)][ci-tests]
[![Go Report Card](https://goreportcard.com/badge/github.com/vmware/govmomi)][go-report-card]
[![Latest Release](https://img.shields.io/github/release/vmware/govmomi.svg?logo=github&style=flat-square)][latest-release]
[![Go Reference](https://pkg.go.dev/badge/github.com/vmware/govmomi.svg)][go-reference]
[![go.mod Go version](https://img.shields.io/github/go-mod/go-version/vmware/govmomi)][go-version]
# govmomi
A Go library for interacting with VMware vSphere APIs (ESXi and/or vCenter Server).
In addition to the vSphere API client, this repository includes:
* [govc][govc] - vSphere CLI
* [vcsim][vcsim] - vSphere API mock framework
* [toolbox][toolbox] - VM guest tools framework
## Compatibility
This library supports vCenter Server and ESXi versions following the [VMware Product Lifecycle Matrix][reference-lifecycle].
Product versions that are end of support may work, but are not officially supported.
## Documentation
The APIs exposed by this library closely follow the API described in the [VMware vSphere API Reference Documentation][reference-api]. Refer to the documentation to become familiar with the upstream API.
The code in the `govmomi` package is a wrapper for the code that is generated from the vSphere API description. It primarily provides convenience functions for working with the vSphere API. See [godoc.org][reference-godoc] for documentation.
## Installation
### govmomi (Package)
```bash
go get -u github.com/vmware/govmomi
```
### Binaries and Docker Images for `govc` and `vcsim`
Installation instructions, released binaries, and Docker images are documented in the respective README files of [`govc`][govc] and [`vcsim`][vcsim].
## Discussion
The project encourages the community to collaborate using GitHub [issues][govmomi-github-issues], GitHub [discussions][govmomi-github-discussions], and [Slack][slack-channel].
> **Note**
> Access to Slack requires a free [VMware {code}][slack-join] developer program membership.
## Status
Changes to the API are subject to [semantic versioning][reference-semver].
Refer to the [CHANGELOG][govmomi-changelog] for version to version changes.
## Notable Projects Using govmomi
* [collectd-vsphere][project-travisci-collectd-vsphere]
* [Docker LinuxKit][project-docker-linuxKit]
* [Elastic Agent VMware vSphere integration][project-elastic-agent]
* [Gru][project-gru]
* [Juju][project-juju]
* [Jupiter Brain][project-travisci-jupiter-brain]
* [Kubernetes vSphere Cloud Provider][project-k8s-cloud-provider]
* [Kubernetes Cluster API][project-k8s-cluster-api]
* [OPS][project-nanovms-ops]
* [Packer Plugin for VMware vSphere][project-hashicorp-packer-plugin-vsphere]
* [Rancher][project-rancher]
* [Terraform Provider for VMware vSphere][project-hashicorp-terraform-provider-vsphere]
* [Telegraf][project-influxdata-telegraf]
* [VMware Event Broker Appliance][project-vmware-veba]
* [VMware vSphere Integrated Containers Engine][project-vmware-vic]
* [VMware vSphere 7.0][project-vmware-vsphere]
## Related Projects
* [go-vmware-nsxt][reference-go-vmware-nsxt]
* [pyvmomi][reference-pyvmomi]
* [rbvmomi][reference-rbvmomi]
## License
govmomi is available under the [Apache 2 License][govmomi-license].
## Name
Pronounced: _go·mom·ie_
Follows pyvmomi and rbvmomi: language prefix + the vSphere acronym "VM Object Management Infrastructure".
[//]: Links
[ci-build]: https://github.com/vmware/govmomi/actions/workflows/govmomi-build.yaml
[ci-tests]: https://github.com/vmware/govmomi/actions/workflows/govmomi-go-tests.yaml
[latest-release]: https://github.com/vmware/govmomi/releases/latest
[govc]: govc/README.md
[govmomi-github-issues]: https://github.com/vmware/govmomi/issues
[govmomi-github-discussions]: https://github.com/vmware/govmomi/discussions
[govmomi-changelog]: CHANGELOG.md
[govmomi-license]: LICENSE.txt
[go-reference]: https://pkg.go.dev/github.com/vmware/govmomi
[go-report-card]: https://goreportcard.com/report/github.com/vmware/govmomi
[go-version]: https://github.com/vmware/govmomi
[project-docker-linuxKit]: https://github.com/linuxkit/linuxkit/tree/master/src/cmd/linuxkit
[project-elastic-agent]: https://github.com/elastic/integrations/tree/main/packages/vsphere
[project-gru]: https://github.com/dnaeon/gru
[project-hashicorp-packer-plugin-vsphere]: https://github.com/hashicorp/packer-plugin-vsphere
[project-hashicorp-terraform-provider-vsphere]: https://github.com/hashicorp/terraform-provider-vsphere
[project-influxdata-telegraf]: https://github.com/influxdata/telegraf/tree/master/plugins/inputs/vsphere
[project-juju]: https://github.com/juju/juju
[project-k8s-cloud-provider]: https://github.com/kubernetes/cloud-provider-vsphere
[project-k8s-cluster-api]: https://github.com/kubernetes-sigs/cluster-api-provider-vsphere
[project-nanovms-ops]: https://github.com/nanovms/ops
[project-rancher]: https://github.com/rancher/rancher/blob/master/pkg/api/norman/customization/vsphere/listers.go
[project-travisci-collectd-vsphere]: https://github.com/travis-ci/collectd-vsphere
[project-travisci-jupiter-brain]: https://github.com/travis-ci/jupiter-brain
[project-vmware-veba]: https://github.com/vmware-samples/vcenter-event-broker-appliance/tree/development/vmware-event-router
[project-vmware-vic]: https://github.com/vmware/vic
[project-vmware-vsphere]: https://docs.vmware.com/en/VMware-vSphere/7.0/rn/vsphere-esxi-vcenter-server-7-vsphere-with-kubernetes-release-notes.html
[reference-api]: https://developer.vmware.com/apis/968/vsphere
[reference-godoc]: http://godoc.org/github.com/vmware/govmomi
[reference-go-vmware-nsxt]: https://github.com/vmware/go-vmware-nsxt
[reference-lifecycle]: https://lifecycle.vmware.com
[reference-pyvmomi]: https://github.com/vmware/pyvmomi
[reference-rbvmomi]: https://github.com/vmware/rbvmomi
[reference-semver]: http://semver.org
[slack-join]: https://developer.vmware.com/join/
[slack-channel]: https://vmwarecode.slack.com/messages/govmomi
[toolbox]: toolbox/README.md
[vcsim]: vcsim/README.md

View File

@@ -1,225 +0,0 @@
# How to create a `govmomi` Release on Github
> **Note**
>
> The steps outlined in this document can only be performed by maintainers or
> administrators of this project.
The release automation is based on Github
[Actions](https://github.com/features/actions) and has been improved over time
to simplify the experience for creating `govmomi` releases.
The Github Actions release [workflow](.github/workflows/govmomi-release.yaml)
uses [`goreleaser`](http://goreleaser.com/) and automatically creates/pushes:
- Release artifacts for `govc` and `vcsim` to the
[release](https://github.com/vmware/govmomi/releases) page, including
`LICENSE.txt`, `README` and `CHANGELOG`
- Docker images for `vmware/govc` and `vmware/vcsim` to Docker Hub
- Source code
Starting with release tag `v0.29.0`, releases are not tagged on the `master`
branch anymore but a dedicated release branch, for example `release-0.29`. This
process has already been followed for patch releases and back-ports.
> **Warning**
>
> If you create a release after the `v0.29.0` tag, start
> [here](#creating-a-release-after-v0290). To create a release with an older
> tag, e.g. cherrypick or back-port, continue
> [here](#creating-a-release-before-v0290).
## Creating a release after Version `v0.29.0`
The release process from `v0.29.0` has been further simplified and is done
through the Github UI. The only pre-requirement is creating a release branch,
which can be done through the Github UI or `git` CLI.
This guide describes the CLI process.
### Verify `master` branch is up to date with the remote
```console
git checkout master
git fetch -avp
git diff master origin/master
# if your local and remote branches diverge run
git pull origin/master
```
> **Warning**
>
> These steps assume `origin` to point to the remote
> `https://github.com/vmware/govmomi`, respectively
> `git@github.com:vmware/govmomi`.
### Create a release branch
For new releases, create a release branch from the most recent commit in
`master`, e.g. `release-0.30`.
```console
export RELEASE_BRANCH=release-0.30
git checkout -b ${RELEASE_BRANCH}
```
For maintenance/patch releases on **existing** release branches **after** tag
`v0.29.0` simply checkout the existing release branch and add commits to the
existing release branch.
### Verify `make docs` and `CONTRIBUTORS` are up to date
> **Warning**
>
> Run the following commands and commit any changes to the release branch before
> proceeding with the release.
```console
make doc
./scripts/contributors.sh
if [ -z "$(git status --porcelain)" ]; then
echo "working directory clean: proceed with release"
else
echo "working directory dirty: please commit changes"
fi
# perform git add && git commit ... in case there were changes
```
### Push the release branch
> **Warning**
>
> Do not create a tag as this will be done by the release automation.
The final step is pushing the new/updated release branch.
```console
git push origin ${RELEASE_BRANCH}
```
### Create a release in the Github UI
Open the `govmomi` Github [repository](https://github.com/vmware/govmomi) and
navigate to `Actions -> Workflows -> Release`.
Click `Run Workflow` which opens a dropdown list.
Select the new/updated branch, e.g. `release-0.30`, i.e. **not** the `master`
branch.
Specify a semantic `tag` to associate with the release, e.g. `v0.30.0`.
> **Warning**
>
> This tag **must not** exist or the release will fail during the validation
> phase.
By default, a dry-run is performed to rule out most (but not all) errors during
a release. If you do not want to perform a dry-run, e.g. to finally create a
release, deselect the `Verify release workflow ...` checkbox.
Click `Run Workflow` to kick off the workflow.
After successful completion and if the newly created `tag` is the **latest**
(semantic version sorted) tag in the repository, a PR is automatically opened
against the `master` branch to update the `CHANGELOG`. Please review and merge
accordingly.
## Creating a release before Version `v0.29.0`
The release process before `v0.29.0` differs since it's based on manually
creating and pushing tags. Here, on every new tag matching `v*` pushed to the
repository a Github Action Release Workflow is executed.
### Verify `master` branch is up to date with the remote
```console
git checkout master
git fetch -avp
git diff master origin/master
# if your local and remote branches diverge run
git pull origin/master
```
> **Warning**
>
> These steps assume `origin` to point to the remote
> `https://github.com/vmware/govmomi`, respectively
> `git@github.com:vmware/govmomi`.
### Create a release branch
Pick a reference (commit, branch or tag) **before** the `v0.29.0` tag and create
a release branch from there.
The following example creates a cherrypick release (`v0.28.1`) based on the
`v0.28.0` tag.
```console
export RELEASE_BRANCH=release-0.28
git checkout -b ${RELEASE_BRANCH} v0.28.0
```
Optionally, incorporate (cherry-pick) commits into the branch.
> **Warning**
>
> Make sure that these commits/ranges do not contain commits after the `v0.29.0`
> tag which include release automation changes, i.e. files in `.github/workflows/`!
### Verify `make docs` and `CONTRIBUTORS` are up to date
> **Warning**
>
> Run the following commands and commit any changes to the release branch before
> proceeding with the release.
```console
make doc
./scripts/contributors.sh
if [ -z "$(git status --porcelain)" ]; then
echo "working directory clean: proceed with release"
else
echo "working directory dirty: please commit changes"
fi
# perform git add && git commit ... in case there were changes
```
### Set `RELEASE_VERSION` variable
This variable is used and referenced in the subsequent commands. Set it to the
**upcoming** release version, adhering to the [semantic
versioning](https://semver.org/) scheme:
```console
export RELEASE_VERSION=v0.28.1
```
### Create the Git Tag
```console
git tag -a ${RELEASE_VERSION} -m "Release ${RELEASE_VERSION}"
```
### Push the new Tag
```console
# Will trigger Github Actions Release Workflow
git push --atomic origin ${RELEASE_BRANCH} refs/tags/${RELEASE_VERSION}
```
### Verify Github Action Release Workflow
After pushing a new release tag, the status of the workflow can be inspected
[here](https://github.com/vmware/govmomi/actions/workflows/govmomi-release.yaml).
![Release](static/release-workflow.png "Successful Release Run")
After a successful release, a pull request is automatically created by the
Github Actions bot to update the [CHANGELOG](CHANGELOG.md). This `CHANGELOG.md`
is also generated with `git-chglog` but uses a slightly different template
(`.chglog/CHANGELOG.tpl.md`) for rendering (issue/PR refs are excluded).

View File

@@ -1,136 +0,0 @@
/*
Copyright (c) 2014-2016 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.
*/
/*
This package is the root package of the govmomi library.
The library is structured as follows:
Package vim25
The minimal usable functionality is available through the vim25 package.
It contains subpackages that contain generated types, managed objects, and all
available methods. The vim25 package is entirely independent of the other
packages in the govmomi tree -- it has no dependencies on its peers.
The vim25 package itself contains a client structure that is
passed around throughout the entire library. It abstracts a session and its
immutable state. See the vim25 package for more information.
Package session
The session package contains an abstraction for the session manager that allows
a user to login and logout. It also provides access to the current session
(i.e. to determine if the user is in fact logged in)
Package object
The object package contains wrappers for a selection of managed objects. The
constructors of these objects all take a *vim25.Client, which they pass along
to derived objects, if applicable.
Package govc
The govc package contains the govc CLI. The code in this tree is not intended
to be used as a library. Any functionality that govc contains that _could_ be
used as a library function but isn't, _should_ live in a root level package.
Other packages
Other packages, such as "event", "guest", or "license", provide wrappers for
the respective subsystems. They are typically not needed in normal workflows so
are kept outside the object package.
*/
package govmomi
import (
"context"
"net/url"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/session"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
type Client struct {
*vim25.Client
SessionManager *session.Manager
}
// NewClient creates a new client from a URL. The client authenticates with the
// server with username/password before returning if the URL contains user information.
func NewClient(ctx context.Context, u *url.URL, insecure bool) (*Client, error) {
soapClient := soap.NewClient(u, insecure)
vimClient, err := vim25.NewClient(ctx, soapClient)
if err != nil {
return nil, err
}
c := &Client{
Client: vimClient,
SessionManager: session.NewManager(vimClient),
}
// Only login if the URL contains user information.
if u.User != nil {
err = c.Login(ctx, u.User)
if err != nil {
return nil, err
}
}
return c, nil
}
// Login dispatches to the SessionManager.
func (c *Client) Login(ctx context.Context, u *url.Userinfo) error {
return c.SessionManager.Login(ctx, u)
}
// Logout dispatches to the SessionManager.
func (c *Client) Logout(ctx context.Context) error {
// Close any idle connections after logging out.
defer c.Client.CloseIdleConnections()
return c.SessionManager.Logout(ctx)
}
// PropertyCollector returns the session's default property collector.
func (c *Client) PropertyCollector() *property.Collector {
return property.DefaultCollector(c.Client)
}
// RetrieveOne dispatches to the Retrieve function on the default property collector.
func (c *Client) RetrieveOne(ctx context.Context, obj types.ManagedObjectReference, p []string, dst interface{}) error {
return c.PropertyCollector().RetrieveOne(ctx, obj, p, dst)
}
// Retrieve dispatches to the Retrieve function on the default property collector.
func (c *Client) Retrieve(ctx context.Context, objs []types.ManagedObjectReference, p []string, dst interface{}) error {
return c.PropertyCollector().Retrieve(ctx, objs, p, dst)
}
// Wait dispatches to property.Wait.
func (c *Client) Wait(ctx context.Context, obj types.ManagedObjectReference, ps []string, f func([]types.PropertyChange) bool) error {
return property.Wait(ctx, c.PropertyCollector(), obj, ps, f)
}
// IsVC returns true if we are connected to a vCenter
func (c *Client) IsVC() bool {
return c.Client.IsVC()
}

View File

@@ -1,37 +0,0 @@
/*
Copyright (c) 2014-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.
*/
/*
Package find implements inventory listing and searching.
The Finder is an alternative to the object.SearchIndex FindByInventoryPath() and FindChild() methods.
SearchIndex.FindByInventoryPath requires an absolute path, whereas the Finder also supports relative paths
and patterns via path.Match.
SearchIndex.FindChild requires a parent to find the child, whereas the Finder also supports an ancestor via
recursive object traversal.
The various Finder methods accept a "path" argument, which can absolute or relative to the Folder for the object type.
The Finder supports two modes, "list" and "find". The "list" mode behaves like the "ls" command, only searching within
the immediate path. The "find" mode behaves like the "find" command, with the search starting at the immediate path but
also recursing into sub Folders relative to the Datacenter. The default mode is "list" if the given path contains a "/",
otherwise "find" mode is used.
The exception is to use a "..." wildcard with a path to find all objects recursively underneath any root object.
For example: VirtualMachineList("/DC1/...")
See also: https://github.com/vmware/govmomi/blob/master/govc/README.md#usage
*/
package find

View File

@@ -1,64 +0,0 @@
/*
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.
*/
package find
import "fmt"
type NotFoundError struct {
kind string
path string
}
func (e *NotFoundError) Error() string {
return fmt.Sprintf("%s '%s' not found", e.kind, e.path)
}
type MultipleFoundError struct {
kind string
path string
}
func (e *MultipleFoundError) Error() string {
return fmt.Sprintf("path '%s' resolves to multiple %ss", e.path, e.kind)
}
type DefaultNotFoundError struct {
kind string
}
func (e *DefaultNotFoundError) Error() string {
return fmt.Sprintf("no default %s found", e.kind)
}
type DefaultMultipleFoundError struct {
kind string
}
func (e DefaultMultipleFoundError) Error() string {
return fmt.Sprintf("default %s resolves to multiple instances, please specify", e.kind)
}
func toDefaultError(err error) error {
switch e := err.(type) {
case *NotFoundError:
return &DefaultNotFoundError{e.kind}
case *MultipleFoundError:
return &DefaultMultipleFoundError{e.kind}
default:
return err
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,253 +0,0 @@
/*
Copyright (c) 2014-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.
*/
package find
import (
"context"
"os"
"path"
"strings"
"github.com/vmware/govmomi/list"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25/mo"
)
// spec is used to specify per-search configuration, independent of the Finder instance.
type spec struct {
// Relative returns the root object to resolve Relative paths (starts with ".")
Relative func(ctx context.Context) (object.Reference, error)
// ListMode can be used to optionally force "ls" behavior, rather than "find" behavior
ListMode *bool
// Contents configures the Recurser to list the Contents of traversable leaf nodes.
// This is typically set to true when used from the ls command, where listing
// a folder means listing its Contents. This is typically set to false for
// commands that take managed entities that are not folders as input.
Contents bool
// Parents specifies the types which can contain the child types being searched for.
// for example, when searching for a HostSystem, parent types can be
// "ComputeResource" or "ClusterComputeResource".
Parents []string
// Include specifies which types to be included in the results, used only in "find" mode.
Include []string
// Nested should be set to types that can be Nested, used only in "find" mode.
Nested []string
// ChildType avoids traversing into folders that can't contain the Include types, used only in "find" mode.
ChildType []string
}
func (s *spec) traversable(o mo.Reference) bool {
ref := o.Reference()
switch ref.Type {
case "Datacenter":
if len(s.Include) == 1 && s.Include[0] == "Datacenter" {
// No point in traversing deeper as Datacenters cannot be nested
return false
}
return true
case "Folder":
if f, ok := o.(mo.Folder); ok {
// TODO: Not making use of this yet, but here we can optimize when searching the entire
// inventory across Datacenters for specific types, for example: 'govc ls -t VirtualMachine /**'
// should not traverse into a Datacenter's host, network or datatore folders.
if !s.traversableChildType(f.ChildType) {
return false
}
}
return true
}
for _, kind := range s.Parents {
if kind == ref.Type {
return true
}
}
return false
}
func (s *spec) traversableChildType(ctypes []string) bool {
if len(s.ChildType) == 0 {
return true
}
for _, t := range ctypes {
for _, c := range s.ChildType {
if t == c {
return true
}
}
}
return false
}
func (s *spec) wanted(e list.Element) bool {
if len(s.Include) == 0 {
return true
}
w := e.Object.Reference().Type
for _, kind := range s.Include {
if w == kind {
return true
}
}
return false
}
// listMode is a global option to revert to the original Finder behavior,
// disabling the newer "find" mode.
var listMode = os.Getenv("GOVMOMI_FINDER_LIST_MODE") == "true"
func (s *spec) listMode(isPath bool) bool {
if listMode {
return true
}
if s.ListMode != nil {
return *s.ListMode
}
return isPath
}
type recurser struct {
Collector *property.Collector
// All configures the recurses to fetch complete objects for leaf nodes.
All bool
}
func (r recurser) List(ctx context.Context, s *spec, root list.Element, parts []string) ([]list.Element, error) {
if len(parts) == 0 {
// Include non-traversable leaf elements in result. For example, consider
// the pattern "./vm/my-vm-*", where the pattern should match the VMs and
// not try to traverse them.
//
// Include traversable leaf elements in result, if the contents
// field is set to false.
//
if !s.Contents || !s.traversable(root.Object.Reference()) {
return []list.Element{root}, nil
}
}
k := list.Lister{
Collector: r.Collector,
Reference: root.Object.Reference(),
Prefix: root.Path,
}
if r.All && len(parts) < 2 {
k.All = true
}
in, err := k.List(ctx)
if err != nil {
return nil, err
}
// This folder is a leaf as far as the glob goes.
if len(parts) == 0 {
return in, nil
}
all := parts
pattern := parts[0]
parts = parts[1:]
var out []list.Element
for _, e := range in {
matched, err := path.Match(pattern, path.Base(e.Path))
if err != nil {
return nil, err
}
if !matched {
matched = strings.HasSuffix(e.Path, "/"+path.Join(all...))
if matched {
// name contains a '/'
out = append(out, e)
}
continue
}
nres, err := r.List(ctx, s, e, parts)
if err != nil {
return nil, err
}
out = append(out, nres...)
}
return out, nil
}
func (r recurser) Find(ctx context.Context, s *spec, root list.Element, parts []string) ([]list.Element, error) {
var out []list.Element
if len(parts) > 0 {
pattern := parts[0]
matched, err := path.Match(pattern, path.Base(root.Path))
if err != nil {
return nil, err
}
if matched && s.wanted(root) {
out = append(out, root)
}
}
if !s.traversable(root.Object) {
return out, nil
}
k := list.Lister{
Collector: r.Collector,
Reference: root.Object.Reference(),
Prefix: root.Path,
}
in, err := k.List(ctx)
if err != nil {
return nil, err
}
for _, e := range in {
nres, err := r.Find(ctx, s, e, parts)
if err != nil {
return nil, err
}
out = append(out, nres...)
}
return out, nil
}

View File

@@ -1,91 +0,0 @@
/*
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.
*/
package history
import (
"context"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type Collector struct {
r types.ManagedObjectReference
c *vim25.Client
}
func NewCollector(c *vim25.Client, ref types.ManagedObjectReference) *Collector {
return &Collector{
r: ref,
c: c,
}
}
// Reference returns the managed object reference of this collector
func (c Collector) Reference() types.ManagedObjectReference {
return c.r
}
// Client returns the vim25 client used by this collector
func (c Collector) Client() *vim25.Client {
return c.c
}
// Properties wraps property.DefaultCollector().RetrieveOne() and returns
// properties for the specified managed object reference
func (c Collector) Properties(ctx context.Context, r types.ManagedObjectReference, ps []string, dst interface{}) error {
return property.DefaultCollector(c.c).RetrieveOne(ctx, r, ps, dst)
}
func (c Collector) Destroy(ctx context.Context) error {
req := types.DestroyCollector{
This: c.r,
}
_, err := methods.DestroyCollector(ctx, c.c, &req)
return err
}
func (c Collector) Reset(ctx context.Context) error {
req := types.ResetCollector{
This: c.r,
}
_, err := methods.ResetCollector(ctx, c.c, &req)
return err
}
func (c Collector) Rewind(ctx context.Context) error {
req := types.RewindCollector{
This: c.r,
}
_, err := methods.RewindCollector(ctx, c.c, &req)
return err
}
func (c Collector) SetPageSize(ctx context.Context, maxCount int32) error {
req := types.SetCollectorPageSize{
This: c.r,
MaxCount: maxCount,
}
_, err := methods.SetCollectorPageSize(ctx, c.c, &req)
return err
}

View File

@@ -1,63 +0,0 @@
/*
Copyright (c) 2020 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.
*/
package internal
import (
"net"
"path"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
// InventoryPath composed of entities by Name
func InventoryPath(entities []mo.ManagedEntity) string {
val := "/"
for _, entity := range entities {
// Skip root folder in building inventory path.
if entity.Parent == nil {
continue
}
val = path.Join(val, entity.Name)
}
return val
}
func HostSystemManagementIPs(config []types.VirtualNicManagerNetConfig) []net.IP {
var ips []net.IP
for _, nc := range config {
if nc.NicType != string(types.HostVirtualNicManagerNicTypeManagement) {
continue
}
for ix := range nc.CandidateVnic {
for _, selectedVnicKey := range nc.SelectedVnic {
if nc.CandidateVnic[ix].Key != selectedVnicKey {
continue
}
ip := net.ParseIP(nc.CandidateVnic[ix].Spec.Ip.IpAddress)
if ip != nil {
ips = append(ips, ip)
}
}
}
}
return ips
}

View File

@@ -1,123 +0,0 @@
/*
Copyright (c) 2014-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.
*/
package internal
import (
"context"
"github.com/vmware/govmomi/vim25/soap"
)
type RetrieveDynamicTypeManagerBody struct {
Req *RetrieveDynamicTypeManagerRequest `xml:"urn:vim25 RetrieveDynamicTypeManager"`
Res *RetrieveDynamicTypeManagerResponse `xml:"urn:vim25 RetrieveDynamicTypeManagerResponse"`
Fault_ *soap.Fault
}
func (b *RetrieveDynamicTypeManagerBody) Fault() *soap.Fault { return b.Fault_ }
func RetrieveDynamicTypeManager(ctx context.Context, r soap.RoundTripper, req *RetrieveDynamicTypeManagerRequest) (*RetrieveDynamicTypeManagerResponse, error) {
var reqBody, resBody RetrieveDynamicTypeManagerBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type RetrieveManagedMethodExecuterBody struct {
Req *RetrieveManagedMethodExecuterRequest `xml:"urn:vim25 RetrieveManagedMethodExecuter"`
Res *RetrieveManagedMethodExecuterResponse `xml:"urn:vim25 RetrieveManagedMethodExecuterResponse"`
Fault_ *soap.Fault
}
func (b *RetrieveManagedMethodExecuterBody) Fault() *soap.Fault { return b.Fault_ }
func RetrieveManagedMethodExecuter(ctx context.Context, r soap.RoundTripper, req *RetrieveManagedMethodExecuterRequest) (*RetrieveManagedMethodExecuterResponse, error) {
var reqBody, resBody RetrieveManagedMethodExecuterBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type DynamicTypeMgrQueryMoInstancesBody struct {
Req *DynamicTypeMgrQueryMoInstancesRequest `xml:"urn:vim25 DynamicTypeMgrQueryMoInstances"`
Res *DynamicTypeMgrQueryMoInstancesResponse `xml:"urn:vim25 DynamicTypeMgrQueryMoInstancesResponse"`
Fault_ *soap.Fault
}
func (b *DynamicTypeMgrQueryMoInstancesBody) Fault() *soap.Fault { return b.Fault_ }
func DynamicTypeMgrQueryMoInstances(ctx context.Context, r soap.RoundTripper, req *DynamicTypeMgrQueryMoInstancesRequest) (*DynamicTypeMgrQueryMoInstancesResponse, error) {
var reqBody, resBody DynamicTypeMgrQueryMoInstancesBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type DynamicTypeMgrQueryTypeInfoBody struct {
Req *DynamicTypeMgrQueryTypeInfoRequest `xml:"urn:vim25 DynamicTypeMgrQueryTypeInfo"`
Res *DynamicTypeMgrQueryTypeInfoResponse `xml:"urn:vim25 DynamicTypeMgrQueryTypeInfoResponse"`
Fault_ *soap.Fault
}
func (b *DynamicTypeMgrQueryTypeInfoBody) Fault() *soap.Fault { return b.Fault_ }
func DynamicTypeMgrQueryTypeInfo(ctx context.Context, r soap.RoundTripper, req *DynamicTypeMgrQueryTypeInfoRequest) (*DynamicTypeMgrQueryTypeInfoResponse, error) {
var reqBody, resBody DynamicTypeMgrQueryTypeInfoBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type ExecuteSoapBody struct {
Req *ExecuteSoapRequest `xml:"urn:vim25 ExecuteSoap"`
Res *ExecuteSoapResponse `xml:"urn:vim25 ExecuteSoapResponse"`
Fault_ *soap.Fault
}
func (b *ExecuteSoapBody) Fault() *soap.Fault { return b.Fault_ }
func ExecuteSoap(ctx context.Context, r soap.RoundTripper, req *ExecuteSoapRequest) (*ExecuteSoapResponse, error) {
var reqBody, resBody ExecuteSoapBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}

View File

@@ -1,270 +0,0 @@
/*
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.
*/
package internal
import (
"reflect"
"github.com/vmware/govmomi/vim25/types"
)
type DynamicTypeMgrQueryMoInstancesRequest struct {
This types.ManagedObjectReference `xml:"_this"`
FilterSpec BaseDynamicTypeMgrFilterSpec `xml:"filterSpec,omitempty,typeattr"`
}
type DynamicTypeMgrQueryMoInstancesResponse struct {
Returnval []DynamicTypeMgrMoInstance `xml:"urn:vim25 returnval"`
}
type DynamicTypeEnumTypeInfo struct {
types.DynamicData
Name string `xml:"name"`
WsdlName string `xml:"wsdlName"`
Version string `xml:"version"`
Value []string `xml:"value,omitempty"`
Annotation []DynamicTypeMgrAnnotation `xml:"annotation,omitempty"`
}
func init() {
types.Add("DynamicTypeEnumTypeInfo", reflect.TypeOf((*DynamicTypeEnumTypeInfo)(nil)).Elem())
}
type DynamicTypeMgrAllTypeInfoRequest struct {
types.DynamicData
ManagedTypeInfo []DynamicTypeMgrManagedTypeInfo `xml:"managedTypeInfo,omitempty"`
EnumTypeInfo []DynamicTypeEnumTypeInfo `xml:"enumTypeInfo,omitempty"`
DataTypeInfo []DynamicTypeMgrDataTypeInfo `xml:"dataTypeInfo,omitempty"`
}
func init() {
types.Add("DynamicTypeMgrAllTypeInfo", reflect.TypeOf((*DynamicTypeMgrAllTypeInfoRequest)(nil)).Elem())
}
type DynamicTypeMgrAnnotation struct {
types.DynamicData
Name string `xml:"name"`
Parameter []string `xml:"parameter,omitempty"`
}
func init() {
types.Add("DynamicTypeMgrAnnotation", reflect.TypeOf((*DynamicTypeMgrAnnotation)(nil)).Elem())
}
type DynamicTypeMgrDataTypeInfo struct {
types.DynamicData
Name string `xml:"name"`
WsdlName string `xml:"wsdlName"`
Version string `xml:"version"`
Base []string `xml:"base,omitempty"`
Property []DynamicTypeMgrPropertyTypeInfo `xml:"property,omitempty"`
Annotation []DynamicTypeMgrAnnotation `xml:"annotation,omitempty"`
}
func init() {
types.Add("DynamicTypeMgrDataTypeInfo", reflect.TypeOf((*DynamicTypeMgrDataTypeInfo)(nil)).Elem())
}
func (b *DynamicTypeMgrFilterSpec) GetDynamicTypeMgrFilterSpec() *DynamicTypeMgrFilterSpec { return b }
type BaseDynamicTypeMgrFilterSpec interface {
GetDynamicTypeMgrFilterSpec() *DynamicTypeMgrFilterSpec
}
type DynamicTypeMgrFilterSpec struct {
types.DynamicData
}
func init() {
types.Add("DynamicTypeMgrFilterSpec", reflect.TypeOf((*DynamicTypeMgrFilterSpec)(nil)).Elem())
}
type DynamicTypeMgrManagedTypeInfo struct {
types.DynamicData
Name string `xml:"name"`
WsdlName string `xml:"wsdlName"`
Version string `xml:"version"`
Base []string `xml:"base,omitempty"`
Property []DynamicTypeMgrPropertyTypeInfo `xml:"property,omitempty"`
Method []DynamicTypeMgrMethodTypeInfo `xml:"method,omitempty"`
Annotation []DynamicTypeMgrAnnotation `xml:"annotation,omitempty"`
}
func init() {
types.Add("DynamicTypeMgrManagedTypeInfo", reflect.TypeOf((*DynamicTypeMgrManagedTypeInfo)(nil)).Elem())
}
type DynamicTypeMgrMethodTypeInfo struct {
types.DynamicData
Name string `xml:"name"`
WsdlName string `xml:"wsdlName"`
Version string `xml:"version"`
ParamTypeInfo []DynamicTypeMgrParamTypeInfo `xml:"paramTypeInfo,omitempty"`
ReturnTypeInfo *DynamicTypeMgrParamTypeInfo `xml:"returnTypeInfo,omitempty"`
Fault []string `xml:"fault,omitempty"`
PrivId string `xml:"privId,omitempty"`
Annotation []DynamicTypeMgrAnnotation `xml:"annotation,omitempty"`
}
func init() {
types.Add("DynamicTypeMgrMethodTypeInfo", reflect.TypeOf((*DynamicTypeMgrMethodTypeInfo)(nil)).Elem())
}
type DynamicTypeMgrMoFilterSpec struct {
DynamicTypeMgrFilterSpec
Id string `xml:"id,omitempty"`
TypeSubstr string `xml:"typeSubstr,omitempty"`
}
func init() {
types.Add("DynamicTypeMgrMoFilterSpec", reflect.TypeOf((*DynamicTypeMgrMoFilterSpec)(nil)).Elem())
}
type DynamicTypeMgrMoInstance struct {
types.DynamicData
Id string `xml:"id"`
MoType string `xml:"moType"`
}
func init() {
types.Add("DynamicTypeMgrMoInstance", reflect.TypeOf((*DynamicTypeMgrMoInstance)(nil)).Elem())
}
type DynamicTypeMgrParamTypeInfo struct {
types.DynamicData
Name string `xml:"name"`
Version string `xml:"version"`
Type string `xml:"type"`
PrivId string `xml:"privId,omitempty"`
Annotation []DynamicTypeMgrAnnotation `xml:"annotation,omitempty"`
}
func init() {
types.Add("DynamicTypeMgrParamTypeInfo", reflect.TypeOf((*DynamicTypeMgrParamTypeInfo)(nil)).Elem())
}
type DynamicTypeMgrPropertyTypeInfo struct {
types.DynamicData
Name string `xml:"name"`
Version string `xml:"version"`
Type string `xml:"type"`
PrivId string `xml:"privId,omitempty"`
MsgIdFormat string `xml:"msgIdFormat,omitempty"`
Annotation []DynamicTypeMgrAnnotation `xml:"annotation,omitempty"`
}
type DynamicTypeMgrQueryTypeInfoRequest struct {
This types.ManagedObjectReference `xml:"_this"`
FilterSpec BaseDynamicTypeMgrFilterSpec `xml:"filterSpec,omitempty,typeattr"`
}
type DynamicTypeMgrQueryTypeInfoResponse struct {
Returnval DynamicTypeMgrAllTypeInfoRequest `xml:"urn:vim25 returnval"`
}
func init() {
types.Add("DynamicTypeMgrPropertyTypeInfo", reflect.TypeOf((*DynamicTypeMgrPropertyTypeInfo)(nil)).Elem())
}
type DynamicTypeMgrTypeFilterSpec struct {
DynamicTypeMgrFilterSpec
TypeSubstr string `xml:"typeSubstr,omitempty"`
}
func init() {
types.Add("DynamicTypeMgrTypeFilterSpec", reflect.TypeOf((*DynamicTypeMgrTypeFilterSpec)(nil)).Elem())
}
type ReflectManagedMethodExecuterSoapArgument struct {
types.DynamicData
Name string `xml:"name"`
Val string `xml:"val"`
}
func init() {
types.Add("ReflectManagedMethodExecuterSoapArgument", reflect.TypeOf((*ReflectManagedMethodExecuterSoapArgument)(nil)).Elem())
}
type ReflectManagedMethodExecuterSoapFault struct {
types.DynamicData
FaultMsg string `xml:"faultMsg"`
FaultDetail string `xml:"faultDetail,omitempty"`
}
func init() {
types.Add("ReflectManagedMethodExecuterSoapFault", reflect.TypeOf((*ReflectManagedMethodExecuterSoapFault)(nil)).Elem())
}
type ReflectManagedMethodExecuterSoapResult struct {
types.DynamicData
Response string `xml:"response,omitempty"`
Fault *ReflectManagedMethodExecuterSoapFault `xml:"fault,omitempty"`
}
type RetrieveDynamicTypeManagerRequest struct {
This types.ManagedObjectReference `xml:"_this"`
}
type RetrieveDynamicTypeManagerResponse struct {
Returnval *InternalDynamicTypeManager `xml:"urn:vim25 returnval"`
}
type RetrieveManagedMethodExecuterRequest struct {
This types.ManagedObjectReference `xml:"_this"`
}
func init() {
types.Add("RetrieveManagedMethodExecuter", reflect.TypeOf((*RetrieveManagedMethodExecuterRequest)(nil)).Elem())
}
type RetrieveManagedMethodExecuterResponse struct {
Returnval *ReflectManagedMethodExecuter `xml:"urn:vim25 returnval"`
}
type InternalDynamicTypeManager struct {
types.ManagedObjectReference
}
type ReflectManagedMethodExecuter struct {
types.ManagedObjectReference
}
type ExecuteSoapRequest struct {
This types.ManagedObjectReference `xml:"_this"`
Moid string `xml:"moid"`
Version string `xml:"version"`
Method string `xml:"method"`
Argument []ReflectManagedMethodExecuterSoapArgument `xml:"argument,omitempty"`
}
type ExecuteSoapResponse struct {
Returnval *ReflectManagedMethodExecuterSoapResult `xml:"urn:vim25 returnval"`
}

View File

@@ -1,25 +0,0 @@
/*
Copyright (c) 2014-2022 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.
*/
package version
const (
// ClientName is the name of this SDK
ClientName = "govmomi"
// ClientVersion is the version of this SDK
ClientVersion = "0.30.6"
)

View File

@@ -1,630 +0,0 @@
/*
Copyright (c) 2014-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.
*/
package list
import (
"context"
"fmt"
"path"
"reflect"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
type Element struct {
Path string
Object mo.Reference
}
func (e Element) String() string {
return fmt.Sprintf("%s @ %s", e.Object.Reference(), e.Path)
}
func ToElement(r mo.Reference, prefix string) Element {
var name string
// Comments about types to be expected in folders copied from the
// documentation of the Folder managed object:
// http://pubs.vmware.com/vsphere-55/topic/com.vmware.wssdk.apiref.doc/vim.Folder.html
switch m := r.(type) {
case mo.Folder:
name = m.Name
case mo.StoragePod:
name = m.Name
// { "vim.Datacenter" } - Identifies the root folder and its descendant
// folders. Data center folders can contain child data center folders and
// Datacenter managed objects. Datacenter objects contain virtual machine,
// compute resource, network entity, and datastore folders.
case mo.Datacenter:
name = m.Name
// { "vim.Virtualmachine", "vim.VirtualApp" } - Identifies a virtual machine
// folder. A virtual machine folder may contain child virtual machine
// folders. It also can contain VirtualMachine managed objects, templates,
// and VirtualApp managed objects.
case mo.VirtualMachine:
name = m.Name
case mo.VirtualApp:
name = m.Name
// { "vim.ComputeResource" } - Identifies a compute resource
// folder, which contains child compute resource folders and ComputeResource
// hierarchies.
case mo.ComputeResource:
name = m.Name
case mo.ClusterComputeResource:
name = m.Name
case mo.HostSystem:
name = m.Name
case mo.ResourcePool:
name = m.Name
// { "vim.Network" } - Identifies a network entity folder.
// Network entity folders on a vCenter Server can contain Network,
// DistributedVirtualSwitch, and DistributedVirtualPortgroup managed objects.
// Network entity folders on an ESXi host can contain only Network objects.
case mo.Network:
name = m.Name
case mo.OpaqueNetwork:
name = m.Name
case mo.DistributedVirtualSwitch:
name = m.Name
case mo.DistributedVirtualPortgroup:
name = m.Name
case mo.VmwareDistributedVirtualSwitch:
name = m.Name
// { "vim.Datastore" } - Identifies a datastore folder. Datastore folders can
// contain child datastore folders and Datastore managed objects.
case mo.Datastore:
name = m.Name
default:
panic("not implemented for type " + reflect.TypeOf(r).String())
}
e := Element{
Path: path.Join(prefix, name),
Object: r,
}
return e
}
type Lister struct {
Collector *property.Collector
Reference types.ManagedObjectReference
Prefix string
All bool
}
func (l Lister) retrieveProperties(ctx context.Context, req types.RetrieveProperties, dst *[]interface{}) error {
res, err := l.Collector.RetrieveProperties(ctx, req)
if err != nil {
return err
}
// Instead of using mo.LoadRetrievePropertiesResponse, use a custom loop to
// iterate over the results and ignore entries that have properties that
// could not be retrieved (a non-empty `missingSet` property). Since the
// returned objects are enumerated by vSphere in the first place, any object
// that has a non-empty `missingSet` property is indicative of a race
// condition in vSphere where the object was enumerated initially, but was
// removed before its properties could be collected.
for _, p := range res.Returnval {
v, err := mo.ObjectContentToType(p)
if err != nil {
// Ignore fault if it is ManagedObjectNotFound
if soap.IsVimFault(err) {
switch soap.ToVimFault(err).(type) {
case *types.ManagedObjectNotFound:
continue
}
}
return err
}
*dst = append(*dst, v)
}
return nil
}
func (l Lister) List(ctx context.Context) ([]Element, error) {
switch l.Reference.Type {
case "Folder", "StoragePod":
return l.ListFolder(ctx)
case "Datacenter":
return l.ListDatacenter(ctx)
case "ComputeResource", "ClusterComputeResource":
// Treat ComputeResource and ClusterComputeResource as one and the same.
// It doesn't matter from the perspective of the lister.
return l.ListComputeResource(ctx)
case "ResourcePool":
return l.ListResourcePool(ctx)
case "HostSystem":
return l.ListHostSystem(ctx)
case "VirtualApp":
return l.ListVirtualApp(ctx)
case "VmwareDistributedVirtualSwitch", "DistributedVirtualSwitch":
return l.ListDistributedVirtualSwitch(ctx)
default:
return nil, fmt.Errorf("cannot traverse type " + l.Reference.Type)
}
}
func (l Lister) ListFolder(ctx context.Context) ([]Element, error) {
spec := types.PropertyFilterSpec{
ObjectSet: []types.ObjectSpec{
{
Obj: l.Reference,
SelectSet: []types.BaseSelectionSpec{
&types.TraversalSpec{
Path: "childEntity",
Skip: types.NewBool(false),
Type: "Folder",
},
},
Skip: types.NewBool(true),
},
},
}
// Retrieve all objects that we can deal with
childTypes := []string{
"Folder",
"Datacenter",
"VirtualApp",
"VirtualMachine",
"Network",
"ComputeResource",
"ClusterComputeResource",
"Datastore",
"DistributedVirtualSwitch",
}
for _, t := range childTypes {
pspec := types.PropertySpec{
Type: t,
}
if l.All {
pspec.All = types.NewBool(true)
} else {
pspec.PathSet = []string{"name"}
// Additional basic properties.
switch t {
case "Folder":
pspec.PathSet = append(pspec.PathSet, "childType")
case "ComputeResource", "ClusterComputeResource":
// The ComputeResource and ClusterComputeResource are dereferenced in
// the ResourcePoolFlag. Make sure they always have their resourcePool
// field populated.
pspec.PathSet = append(pspec.PathSet, "resourcePool")
}
}
spec.PropSet = append(spec.PropSet, pspec)
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{spec},
}
var dst []interface{}
err := l.retrieveProperties(ctx, req, &dst)
if err != nil {
return nil, err
}
es := []Element{}
for _, v := range dst {
es = append(es, ToElement(v.(mo.Reference), l.Prefix))
}
return es, nil
}
func (l Lister) ListDatacenter(ctx context.Context) ([]Element, error) {
ospec := types.ObjectSpec{
Obj: l.Reference,
Skip: types.NewBool(true),
}
// Include every datastore folder in the select set
fields := []string{
"vmFolder",
"hostFolder",
"datastoreFolder",
"networkFolder",
}
for _, f := range fields {
tspec := types.TraversalSpec{
Path: f,
Skip: types.NewBool(false),
Type: "Datacenter",
}
ospec.SelectSet = append(ospec.SelectSet, &tspec)
}
pspec := types.PropertySpec{
Type: "Folder",
}
if l.All {
pspec.All = types.NewBool(true)
} else {
pspec.PathSet = []string{"name", "childType"}
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: []types.ObjectSpec{ospec},
PropSet: []types.PropertySpec{pspec},
},
},
}
var dst []interface{}
err := l.retrieveProperties(ctx, req, &dst)
if err != nil {
return nil, err
}
es := []Element{}
for _, v := range dst {
es = append(es, ToElement(v.(mo.Reference), l.Prefix))
}
return es, nil
}
func (l Lister) ListComputeResource(ctx context.Context) ([]Element, error) {
ospec := types.ObjectSpec{
Obj: l.Reference,
Skip: types.NewBool(true),
}
fields := []string{
"host",
"network",
"resourcePool",
}
for _, f := range fields {
tspec := types.TraversalSpec{
Path: f,
Skip: types.NewBool(false),
Type: "ComputeResource",
}
ospec.SelectSet = append(ospec.SelectSet, &tspec)
}
childTypes := []string{
"HostSystem",
"Network",
"ResourcePool",
}
var pspecs []types.PropertySpec
for _, t := range childTypes {
pspec := types.PropertySpec{
Type: t,
}
if l.All {
pspec.All = types.NewBool(true)
} else {
pspec.PathSet = []string{"name"}
}
pspecs = append(pspecs, pspec)
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: []types.ObjectSpec{ospec},
PropSet: pspecs,
},
},
}
var dst []interface{}
err := l.retrieveProperties(ctx, req, &dst)
if err != nil {
return nil, err
}
es := []Element{}
for _, v := range dst {
es = append(es, ToElement(v.(mo.Reference), l.Prefix))
}
return es, nil
}
func (l Lister) ListResourcePool(ctx context.Context) ([]Element, error) {
ospec := types.ObjectSpec{
Obj: l.Reference,
Skip: types.NewBool(true),
}
fields := []string{
"resourcePool",
}
for _, f := range fields {
tspec := types.TraversalSpec{
Path: f,
Skip: types.NewBool(false),
Type: "ResourcePool",
}
ospec.SelectSet = append(ospec.SelectSet, &tspec)
}
childTypes := []string{
"ResourcePool",
}
var pspecs []types.PropertySpec
for _, t := range childTypes {
pspec := types.PropertySpec{
Type: t,
}
if l.All {
pspec.All = types.NewBool(true)
} else {
pspec.PathSet = []string{"name"}
}
pspecs = append(pspecs, pspec)
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: []types.ObjectSpec{ospec},
PropSet: pspecs,
},
},
}
var dst []interface{}
err := l.retrieveProperties(ctx, req, &dst)
if err != nil {
return nil, err
}
es := []Element{}
for _, v := range dst {
es = append(es, ToElement(v.(mo.Reference), l.Prefix))
}
return es, nil
}
func (l Lister) ListHostSystem(ctx context.Context) ([]Element, error) {
ospec := types.ObjectSpec{
Obj: l.Reference,
Skip: types.NewBool(true),
}
fields := []string{
"datastore",
"network",
"vm",
}
for _, f := range fields {
tspec := types.TraversalSpec{
Path: f,
Skip: types.NewBool(false),
Type: "HostSystem",
}
ospec.SelectSet = append(ospec.SelectSet, &tspec)
}
childTypes := []string{
"Datastore",
"Network",
"VirtualMachine",
}
var pspecs []types.PropertySpec
for _, t := range childTypes {
pspec := types.PropertySpec{
Type: t,
}
if l.All {
pspec.All = types.NewBool(true)
} else {
pspec.PathSet = []string{"name"}
}
pspecs = append(pspecs, pspec)
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: []types.ObjectSpec{ospec},
PropSet: pspecs,
},
},
}
var dst []interface{}
err := l.retrieveProperties(ctx, req, &dst)
if err != nil {
return nil, err
}
es := []Element{}
for _, v := range dst {
es = append(es, ToElement(v.(mo.Reference), l.Prefix))
}
return es, nil
}
func (l Lister) ListDistributedVirtualSwitch(ctx context.Context) ([]Element, error) {
ospec := types.ObjectSpec{
Obj: l.Reference,
Skip: types.NewBool(true),
}
fields := []string{
"portgroup",
}
for _, f := range fields {
tspec := types.TraversalSpec{
Path: f,
Skip: types.NewBool(false),
Type: "DistributedVirtualSwitch",
}
ospec.SelectSet = append(ospec.SelectSet, &tspec)
}
childTypes := []string{
"DistributedVirtualPortgroup",
}
var pspecs []types.PropertySpec
for _, t := range childTypes {
pspec := types.PropertySpec{
Type: t,
}
if l.All {
pspec.All = types.NewBool(true)
} else {
pspec.PathSet = []string{"name"}
}
pspecs = append(pspecs, pspec)
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: []types.ObjectSpec{ospec},
PropSet: pspecs,
},
},
}
var dst []interface{}
err := l.retrieveProperties(ctx, req, &dst)
if err != nil {
return nil, err
}
es := []Element{}
for _, v := range dst {
es = append(es, ToElement(v.(mo.Reference), l.Prefix))
}
return es, nil
}
func (l Lister) ListVirtualApp(ctx context.Context) ([]Element, error) {
ospec := types.ObjectSpec{
Obj: l.Reference,
Skip: types.NewBool(true),
}
fields := []string{
"resourcePool",
"vm",
}
for _, f := range fields {
tspec := types.TraversalSpec{
Path: f,
Skip: types.NewBool(false),
Type: "VirtualApp",
}
ospec.SelectSet = append(ospec.SelectSet, &tspec)
}
childTypes := []string{
"ResourcePool",
"VirtualMachine",
}
var pspecs []types.PropertySpec
for _, t := range childTypes {
pspec := types.PropertySpec{
Type: t,
}
if l.All {
pspec.All = types.NewBool(true)
} else {
pspec.PathSet = []string{"name"}
}
pspecs = append(pspecs, pspec)
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: []types.ObjectSpec{ospec},
PropSet: pspecs,
},
},
}
var dst []interface{}
err := l.retrieveProperties(ctx, req, &dst)
if err != nil {
return nil, err
}
es := []Element{}
for _, v := range dst {
es = append(es, ToElement(v.(mo.Reference), l.Prefix))
}
return es, nil
}

View File

@@ -1,44 +0,0 @@
/*
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.
*/
package list
import (
"path"
"strings"
)
func ToParts(p string) []string {
p = path.Clean(p)
if p == "/" {
return []string{}
}
if len(p) > 0 {
// Prefix ./ if relative
if p[0] != '/' && p[0] != '.' {
p = "./" + p
}
}
ps := strings.Split(p, "/")
if ps[0] == "" {
// Start at root
ps = ps[1:]
}
return ps
}

View File

@@ -1,159 +0,0 @@
/*
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.
*/
package lookup
import (
"context"
"crypto/x509"
"encoding/base64"
"log"
"net/url"
"github.com/vmware/govmomi/lookup/methods"
"github.com/vmware/govmomi/lookup/types"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/soap"
vim "github.com/vmware/govmomi/vim25/types"
)
const (
Namespace = "lookup"
Version = "2.0"
Path = "/lookupservice" + vim25.Path
)
var (
ServiceInstance = vim.ManagedObjectReference{
Type: "LookupServiceInstance",
Value: "ServiceInstance",
}
)
// Client is a soap.Client targeting the SSO Lookup Service API endpoint.
type Client struct {
*soap.Client
RoundTripper soap.RoundTripper
ServiceContent types.LookupServiceContent
}
// NewClient returns a client targeting the SSO Lookup Service API endpoint.
func NewClient(ctx context.Context, c *vim25.Client) (*Client, error) {
// PSC may be external, attempt to derive from sts.uri
path := &url.URL{Path: Path}
if c.ServiceContent.Setting != nil {
m := object.NewOptionManager(c, *c.ServiceContent.Setting)
opts, err := m.Query(ctx, "config.vpxd.sso.sts.uri")
if err == nil && len(opts) == 1 {
u, err := url.Parse(opts[0].GetOptionValue().Value.(string))
if err == nil {
path.Scheme = u.Scheme
path.Host = u.Host
}
}
}
sc := c.Client.NewServiceClient(path.String(), Namespace)
sc.Version = Version
req := types.RetrieveServiceContent{
This: ServiceInstance,
}
res, err := methods.RetrieveServiceContent(ctx, sc, &req)
if err != nil {
return nil, err
}
return &Client{sc, sc, res.Returnval}, nil
}
// RoundTrip dispatches to the RoundTripper field.
func (c *Client) RoundTrip(ctx context.Context, req, res soap.HasFault) error {
return c.RoundTripper.RoundTrip(ctx, req, res)
}
func (c *Client) List(ctx context.Context, filter *types.LookupServiceRegistrationFilter) ([]types.LookupServiceRegistrationInfo, error) {
req := types.List{
This: *c.ServiceContent.ServiceRegistration,
FilterCriteria: filter,
}
res, err := methods.List(ctx, c, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (c *Client) SiteID(ctx context.Context) (string, error) {
req := types.GetSiteId{
This: *c.ServiceContent.ServiceRegistration,
}
res, err := methods.GetSiteId(ctx, c, &req)
if err != nil {
return "", err
}
return res.Returnval, nil
}
// EndpointURL uses the Lookup Service to find the endpoint URL and thumbprint for the given filter.
// If the endpoint is found, its TLS certificate is also added to the vim25.Client's trusted host thumbprints.
// If the Lookup Service is not available, the given path is returned as the default.
func EndpointURL(ctx context.Context, c *vim25.Client, path string, filter *types.LookupServiceRegistrationFilter) string {
if lu, err := NewClient(ctx, c); err == nil {
info, _ := lu.List(ctx, filter)
if len(info) != 0 && len(info[0].ServiceEndpoints) != 0 {
endpoint := &info[0].ServiceEndpoints[0]
path = endpoint.Url
if u, err := url.Parse(path); err == nil {
// Set thumbprint only for endpoints on hosts outside this vCenter.
// Platform Services may live on multiple hosts.
if c.URL().Host != u.Host && c.Thumbprint(u.Host) == "" {
c.SetThumbprint(u.Host, endpointThumbprint(endpoint))
}
}
}
}
return path
}
// endpointThumbprint converts the base64 encoded endpoint certificate to a SHA1 thumbprint.
func endpointThumbprint(endpoint *types.LookupServiceRegistrationEndpoint) string {
if len(endpoint.SslTrust) == 0 {
return ""
}
enc := endpoint.SslTrust[0]
b, err := base64.StdEncoding.DecodeString(enc)
if err != nil {
log.Printf("base64.Decode(%q): %s", enc, err)
return ""
}
cert, err := x509.ParseCertificate(b)
if err != nil {
log.Printf("x509.ParseCertificate(%q): %s", enc, err)
return ""
}
return soap.ThumbprintSHA1(cert)
}

View File

@@ -1,224 +0,0 @@
/*
Copyright (c) 2014-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.
*/
package methods
import (
"context"
"github.com/vmware/govmomi/lookup/types"
"github.com/vmware/govmomi/vim25/soap"
)
type CreateBody struct {
Req *types.Create `xml:"urn:lookup Create,omitempty"`
Res *types.CreateResponse `xml:"urn:lookup CreateResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *CreateBody) Fault() *soap.Fault { return b.Fault_ }
func Create(ctx context.Context, r soap.RoundTripper, req *types.Create) (*types.CreateResponse, error) {
var reqBody, resBody CreateBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type DeleteBody struct {
Req *types.Delete `xml:"urn:lookup Delete,omitempty"`
Res *types.DeleteResponse `xml:"urn:lookup DeleteResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *DeleteBody) Fault() *soap.Fault { return b.Fault_ }
func Delete(ctx context.Context, r soap.RoundTripper, req *types.Delete) (*types.DeleteResponse, error) {
var reqBody, resBody DeleteBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type GetBody struct {
Req *types.Get `xml:"urn:lookup Get,omitempty"`
Res *types.GetResponse `xml:"urn:lookup GetResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *GetBody) Fault() *soap.Fault { return b.Fault_ }
func Get(ctx context.Context, r soap.RoundTripper, req *types.Get) (*types.GetResponse, error) {
var reqBody, resBody GetBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type GetLocaleBody struct {
Req *types.GetLocale `xml:"urn:lookup GetLocale,omitempty"`
Res *types.GetLocaleResponse `xml:"urn:lookup GetLocaleResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *GetLocaleBody) Fault() *soap.Fault { return b.Fault_ }
func GetLocale(ctx context.Context, r soap.RoundTripper, req *types.GetLocale) (*types.GetLocaleResponse, error) {
var reqBody, resBody GetLocaleBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type GetSiteIdBody struct {
Req *types.GetSiteId `xml:"urn:lookup GetSiteId,omitempty"`
Res *types.GetSiteIdResponse `xml:"urn:lookup GetSiteIdResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *GetSiteIdBody) Fault() *soap.Fault { return b.Fault_ }
func GetSiteId(ctx context.Context, r soap.RoundTripper, req *types.GetSiteId) (*types.GetSiteIdResponse, error) {
var reqBody, resBody GetSiteIdBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type ListBody struct {
Req *types.List `xml:"urn:lookup List,omitempty"`
Res *types.ListResponse `xml:"urn:lookup ListResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *ListBody) Fault() *soap.Fault { return b.Fault_ }
func List(ctx context.Context, r soap.RoundTripper, req *types.List) (*types.ListResponse, error) {
var reqBody, resBody ListBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type RetrieveHaBackupConfigurationBody struct {
Req *types.RetrieveHaBackupConfiguration `xml:"urn:lookup RetrieveHaBackupConfiguration,omitempty"`
Res *types.RetrieveHaBackupConfigurationResponse `xml:"urn:lookup RetrieveHaBackupConfigurationResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *RetrieveHaBackupConfigurationBody) Fault() *soap.Fault { return b.Fault_ }
func RetrieveHaBackupConfiguration(ctx context.Context, r soap.RoundTripper, req *types.RetrieveHaBackupConfiguration) (*types.RetrieveHaBackupConfigurationResponse, error) {
var reqBody, resBody RetrieveHaBackupConfigurationBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type RetrieveServiceContentBody struct {
Req *types.RetrieveServiceContent `xml:"urn:lookup RetrieveServiceContent,omitempty"`
Res *types.RetrieveServiceContentResponse `xml:"urn:lookup RetrieveServiceContentResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *RetrieveServiceContentBody) Fault() *soap.Fault { return b.Fault_ }
func RetrieveServiceContent(ctx context.Context, r soap.RoundTripper, req *types.RetrieveServiceContent) (*types.RetrieveServiceContentResponse, error) {
var reqBody, resBody RetrieveServiceContentBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type SetBody struct {
Req *types.Set `xml:"urn:lookup Set,omitempty"`
Res *types.SetResponse `xml:"urn:lookup SetResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *SetBody) Fault() *soap.Fault { return b.Fault_ }
func Set(ctx context.Context, r soap.RoundTripper, req *types.Set) (*types.SetResponse, error) {
var reqBody, resBody SetBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type SetLocaleBody struct {
Req *types.SetLocale `xml:"urn:lookup SetLocale,omitempty"`
Res *types.SetLocaleResponse `xml:"urn:lookup SetLocaleResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *SetLocaleBody) Fault() *soap.Fault { return b.Fault_ }
func SetLocale(ctx context.Context, r soap.RoundTripper, req *types.SetLocale) (*types.SetLocaleResponse, error) {
var reqBody, resBody SetLocaleBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}

View File

@@ -1,139 +0,0 @@
/*
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.
*/
package simulator
import (
"github.com/google/uuid"
"github.com/vmware/govmomi/lookup"
"github.com/vmware/govmomi/lookup/types"
"github.com/vmware/govmomi/simulator"
"github.com/vmware/govmomi/vim25"
)
var (
siteID = "vcsim"
)
// registrationInfo returns a ServiceRegistration populated with vcsim's OptionManager settings.
// The complete list can be captured using: govc sso.service.ls -dump
func registrationInfo() []types.LookupServiceRegistrationInfo {
vc := simulator.Map.Get(vim25.ServiceInstance).(*simulator.ServiceInstance)
setting := simulator.Map.OptionManager().Setting
sm := simulator.Map.SessionManager()
opts := make(map[string]string, len(setting))
for _, o := range setting {
opt := o.GetOptionValue()
if val, ok := opt.Value.(string); ok {
opts[opt.Key] = val
}
}
trust := []string{""}
if sm.TLSCert != nil {
trust[0] = sm.TLSCert()
}
sdk := opts["vcsim.server.url"] + vim25.Path
admin := opts["config.vpxd.sso.default.admin"]
owner := opts["config.vpxd.sso.solutionUser.name"]
instance := opts["VirtualCenter.InstanceName"]
// Real PSC has 30+ services by default, we just provide a few that are useful for vmomi interaction..
info := []types.LookupServiceRegistrationInfo{
{
LookupServiceRegistrationCommonServiceInfo: types.LookupServiceRegistrationCommonServiceInfo{
LookupServiceRegistrationMutableServiceInfo: types.LookupServiceRegistrationMutableServiceInfo{
ServiceVersion: lookup.Version,
ServiceEndpoints: []types.LookupServiceRegistrationEndpoint{
{
Url: opts["config.vpxd.sso.sts.uri"],
EndpointType: types.LookupServiceRegistrationEndpointType{
Protocol: "wsTrust",
Type: "com.vmware.cis.cs.identity.sso",
},
SslTrust: trust,
},
},
},
OwnerId: admin,
ServiceType: types.LookupServiceRegistrationServiceType{
Product: "com.vmware.cis",
Type: "cs.identity",
},
},
ServiceId: siteID + ":" + uuid.New().String(),
SiteId: siteID,
},
{
LookupServiceRegistrationCommonServiceInfo: types.LookupServiceRegistrationCommonServiceInfo{
LookupServiceRegistrationMutableServiceInfo: types.LookupServiceRegistrationMutableServiceInfo{
ServiceVersion: vim25.Version,
ServiceEndpoints: []types.LookupServiceRegistrationEndpoint{
{
Url: sdk,
EndpointType: types.LookupServiceRegistrationEndpointType{
Protocol: "vmomi",
Type: "com.vmware.vim",
},
SslTrust: trust,
EndpointAttributes: []types.LookupServiceRegistrationAttribute{
{
Key: "cis.common.ep.localurl",
Value: sdk,
},
},
},
},
ServiceAttributes: []types.LookupServiceRegistrationAttribute{
{
Key: "com.vmware.cis.cm.GroupInternalId",
Value: "com.vmware.vim.vcenter",
},
{
Key: "com.vmware.vim.vcenter.instanceName",
Value: instance,
},
{
Key: "com.vmware.cis.cm.ControlScript",
Value: "service-control-default-vmon",
},
{
Key: "com.vmware.cis.cm.HostId",
Value: uuid.New().String(),
},
},
ServiceNameResourceKey: "AboutInfo.vpx.name",
ServiceDescriptionResourceKey: "AboutInfo.vpx.name",
},
OwnerId: owner,
ServiceType: types.LookupServiceRegistrationServiceType{
Product: "com.vmware.cis",
Type: "vcenterserver",
},
NodeId: uuid.New().String(),
},
ServiceId: vc.Content.About.InstanceUuid,
SiteId: siteID,
},
}
sts := info[0]
sts.ServiceType.Type = "sso:sts" // obsolete service type, but still used by PowerCLI
return append(info, sts)
}

View File

@@ -1,177 +0,0 @@
/*
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.
*/
package simulator
import (
"sync"
"github.com/vmware/govmomi/lookup"
"github.com/vmware/govmomi/lookup/methods"
"github.com/vmware/govmomi/lookup/types"
"github.com/vmware/govmomi/simulator"
"github.com/vmware/govmomi/vim25/soap"
vim "github.com/vmware/govmomi/vim25/types"
)
var content = types.LookupServiceContent{
LookupService: vim.ManagedObjectReference{Type: "LookupLookupService", Value: "lookupService"},
ServiceRegistration: &vim.ManagedObjectReference{Type: "LookupServiceRegistration", Value: "ServiceRegistration"},
DeploymentInformationService: vim.ManagedObjectReference{Type: "LookupDeploymentInformationService", Value: "deploymentInformationService"},
L10n: vim.ManagedObjectReference{Type: "LookupL10n", Value: "l10n"},
}
func init() {
simulator.RegisterEndpoint(func(s *simulator.Service, r *simulator.Registry) {
if r.IsVPX() {
s.RegisterSDK(New())
}
})
}
func New() *simulator.Registry {
r := simulator.NewRegistry()
r.Namespace = lookup.Namespace
r.Path = lookup.Path
r.Put(&ServiceInstance{
ManagedObjectReference: lookup.ServiceInstance,
Content: content,
register: func() {
r.Put(&ServiceRegistration{
ManagedObjectReference: *content.ServiceRegistration,
Info: registrationInfo(),
})
},
})
return r
}
type ServiceInstance struct {
vim.ManagedObjectReference
Content types.LookupServiceContent
instance sync.Once
register func()
}
func (s *ServiceInstance) RetrieveServiceContent(_ *types.RetrieveServiceContent) soap.HasFault {
// defer register to this point to ensure we can include vcsim's cert in ServiceEndpoints.SslTrust
// TODO: we should be able to register within New(), but this is the only place that currently depends on vcsim's cert.
s.instance.Do(s.register)
return &methods.RetrieveServiceContentBody{
Res: &types.RetrieveServiceContentResponse{
Returnval: s.Content,
},
}
}
type ServiceRegistration struct {
vim.ManagedObjectReference
Info []types.LookupServiceRegistrationInfo
}
func (s *ServiceRegistration) GetSiteId(_ *types.GetSiteId) soap.HasFault {
return &methods.GetSiteIdBody{
Res: &types.GetSiteIdResponse{
Returnval: siteID,
},
}
}
func matchServiceType(filter, info *types.LookupServiceRegistrationServiceType) bool {
if filter.Product != "" {
if filter.Product != info.Product {
return false
}
}
if filter.Type != "" {
if filter.Type != info.Type {
return false
}
}
return true
}
func matchEndpointType(filter, info *types.LookupServiceRegistrationEndpointType) bool {
if filter.Protocol != "" {
if filter.Protocol != info.Protocol {
return false
}
}
if filter.Type != "" {
if filter.Type != info.Type {
return false
}
}
return true
}
func (s *ServiceRegistration) List(req *types.List) soap.HasFault {
body := new(methods.ListBody)
filter := req.FilterCriteria
if filter == nil {
// This is what a real PSC returns if FilterCriteria is nil.
body.Fault_ = simulator.Fault("LookupFaultServiceFault", &vim.SystemError{
Reason: "Invalid fault",
})
return body
}
body.Res = new(types.ListResponse)
for _, info := range s.Info {
if filter.SiteId != "" {
if filter.SiteId != info.SiteId {
continue
}
}
if filter.NodeId != "" {
if filter.NodeId != info.NodeId {
continue
}
}
if filter.ServiceType != nil {
if !matchServiceType(filter.ServiceType, &info.ServiceType) {
continue
}
}
if filter.EndpointType != nil {
services := info.ServiceEndpoints
info.ServiceEndpoints = nil
for _, service := range services {
if !matchEndpointType(filter.EndpointType, &service.EndpointType) {
continue
}
info.ServiceEndpoints = append(info.ServiceEndpoints, service)
}
if len(info.ServiceEndpoints) == 0 {
continue
}
}
body.Res.Returnval = append(body.Res.Returnval, info)
}
return body
}

View File

@@ -1,412 +0,0 @@
/*
Copyright (c) 2014-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.
*/
package types
import (
"reflect"
"github.com/vmware/govmomi/vim25/types"
vim "github.com/vmware/govmomi/vim25/types"
)
type Create CreateRequestType
func init() {
types.Add("lookup:Create", reflect.TypeOf((*Create)(nil)).Elem())
}
type CreateRequestType struct {
This vim.ManagedObjectReference `xml:"_this"`
ServiceId string `xml:"serviceId"`
CreateSpec LookupServiceRegistrationCreateSpec `xml:"createSpec"`
}
func init() {
types.Add("lookup:CreateRequestType", reflect.TypeOf((*CreateRequestType)(nil)).Elem())
}
type CreateResponse struct {
}
type Delete DeleteRequestType
func init() {
types.Add("lookup:Delete", reflect.TypeOf((*Delete)(nil)).Elem())
}
type DeleteRequestType struct {
This vim.ManagedObjectReference `xml:"_this"`
ServiceId string `xml:"serviceId"`
}
func init() {
types.Add("lookup:DeleteRequestType", reflect.TypeOf((*DeleteRequestType)(nil)).Elem())
}
type DeleteResponse struct {
}
type Get GetRequestType
func init() {
types.Add("lookup:Get", reflect.TypeOf((*Get)(nil)).Elem())
}
type GetLocale GetLocaleRequestType
func init() {
types.Add("lookup:GetLocale", reflect.TypeOf((*GetLocale)(nil)).Elem())
}
type GetLocaleRequestType struct {
This vim.ManagedObjectReference `xml:"_this"`
}
func init() {
types.Add("lookup:GetLocaleRequestType", reflect.TypeOf((*GetLocaleRequestType)(nil)).Elem())
}
type GetLocaleResponse struct {
Returnval string `xml:"returnval"`
}
type GetRequestType struct {
This vim.ManagedObjectReference `xml:"_this"`
ServiceId string `xml:"serviceId"`
}
func init() {
types.Add("lookup:GetRequestType", reflect.TypeOf((*GetRequestType)(nil)).Elem())
}
type GetResponse struct {
Returnval LookupServiceRegistrationInfo `xml:"returnval"`
}
type GetSiteId GetSiteIdRequestType
func init() {
types.Add("lookup:GetSiteId", reflect.TypeOf((*GetSiteId)(nil)).Elem())
}
type GetSiteIdRequestType struct {
This vim.ManagedObjectReference `xml:"_this"`
}
func init() {
types.Add("lookup:GetSiteIdRequestType", reflect.TypeOf((*GetSiteIdRequestType)(nil)).Elem())
}
type GetSiteIdResponse struct {
Returnval string `xml:"returnval"`
}
type List ListRequestType
func init() {
types.Add("lookup:List", reflect.TypeOf((*List)(nil)).Elem())
}
type ListRequestType struct {
This vim.ManagedObjectReference `xml:"_this"`
FilterCriteria *LookupServiceRegistrationFilter `xml:"filterCriteria,omitempty"`
}
func init() {
types.Add("lookup:ListRequestType", reflect.TypeOf((*ListRequestType)(nil)).Elem())
}
type ListResponse struct {
Returnval []LookupServiceRegistrationInfo `xml:"returnval,omitempty"`
}
type LookupFaultEntryExistsFault struct {
LookupFaultServiceFault
Name string `xml:"name"`
}
func init() {
types.Add("lookup:LookupFaultEntryExistsFault", reflect.TypeOf((*LookupFaultEntryExistsFault)(nil)).Elem())
}
type LookupFaultEntryExistsFaultFault LookupFaultEntryExistsFault
func init() {
types.Add("lookup:LookupFaultEntryExistsFaultFault", reflect.TypeOf((*LookupFaultEntryExistsFaultFault)(nil)).Elem())
}
type LookupFaultEntryNotFoundFault struct {
LookupFaultServiceFault
Name string `xml:"name"`
}
func init() {
types.Add("lookup:LookupFaultEntryNotFoundFault", reflect.TypeOf((*LookupFaultEntryNotFoundFault)(nil)).Elem())
}
type LookupFaultEntryNotFoundFaultFault LookupFaultEntryNotFoundFault
func init() {
types.Add("lookup:LookupFaultEntryNotFoundFaultFault", reflect.TypeOf((*LookupFaultEntryNotFoundFaultFault)(nil)).Elem())
}
type LookupFaultServiceFault struct {
vim.MethodFault
ErrorMessage string `xml:"errorMessage,omitempty"`
}
func init() {
types.Add("lookup:LookupFaultServiceFault", reflect.TypeOf((*LookupFaultServiceFault)(nil)).Elem())
}
type LookupFaultUnsupportedSiteFault struct {
LookupFaultServiceFault
OperatingSite string `xml:"operatingSite"`
RequestedSite string `xml:"requestedSite"`
}
func init() {
types.Add("lookup:LookupFaultUnsupportedSiteFault", reflect.TypeOf((*LookupFaultUnsupportedSiteFault)(nil)).Elem())
}
type LookupFaultUnsupportedSiteFaultFault LookupFaultUnsupportedSiteFault
func init() {
types.Add("lookup:LookupFaultUnsupportedSiteFaultFault", reflect.TypeOf((*LookupFaultUnsupportedSiteFaultFault)(nil)).Elem())
}
type LookupHaBackupNodeConfiguration struct {
vim.DynamicData
DbType string `xml:"dbType"`
DbJdbcUrl string `xml:"dbJdbcUrl"`
DbUser string `xml:"dbUser"`
DbPass string `xml:"dbPass"`
}
func init() {
types.Add("lookup:LookupHaBackupNodeConfiguration", reflect.TypeOf((*LookupHaBackupNodeConfiguration)(nil)).Elem())
}
type LookupServiceContent struct {
vim.DynamicData
LookupService vim.ManagedObjectReference `xml:"lookupService"`
ServiceRegistration *vim.ManagedObjectReference `xml:"serviceRegistration,omitempty"`
DeploymentInformationService vim.ManagedObjectReference `xml:"deploymentInformationService"`
L10n vim.ManagedObjectReference `xml:"l10n"`
}
func init() {
types.Add("lookup:LookupServiceContent", reflect.TypeOf((*LookupServiceContent)(nil)).Elem())
}
type LookupServiceRegistrationAttribute struct {
vim.DynamicData
Key string `xml:"key"`
Value string `xml:"value"`
}
func init() {
types.Add("lookup:LookupServiceRegistrationAttribute", reflect.TypeOf((*LookupServiceRegistrationAttribute)(nil)).Elem())
}
type LookupServiceRegistrationCommonServiceInfo struct {
LookupServiceRegistrationMutableServiceInfo
OwnerId string `xml:"ownerId"`
ServiceType LookupServiceRegistrationServiceType `xml:"serviceType"`
NodeId string `xml:"nodeId,omitempty"`
}
func init() {
types.Add("lookup:LookupServiceRegistrationCommonServiceInfo", reflect.TypeOf((*LookupServiceRegistrationCommonServiceInfo)(nil)).Elem())
}
type LookupServiceRegistrationCreateSpec struct {
LookupServiceRegistrationCommonServiceInfo
}
func init() {
types.Add("lookup:LookupServiceRegistrationCreateSpec", reflect.TypeOf((*LookupServiceRegistrationCreateSpec)(nil)).Elem())
}
type LookupServiceRegistrationEndpoint struct {
vim.DynamicData
Url string `xml:"url"`
EndpointType LookupServiceRegistrationEndpointType `xml:"endpointType"`
SslTrust []string `xml:"sslTrust,omitempty"`
EndpointAttributes []LookupServiceRegistrationAttribute `xml:"endpointAttributes,omitempty"`
}
func init() {
types.Add("lookup:LookupServiceRegistrationEndpoint", reflect.TypeOf((*LookupServiceRegistrationEndpoint)(nil)).Elem())
}
type LookupServiceRegistrationEndpointType struct {
vim.DynamicData
Protocol string `xml:"protocol,omitempty"`
Type string `xml:"type,omitempty"`
}
func init() {
types.Add("lookup:LookupServiceRegistrationEndpointType", reflect.TypeOf((*LookupServiceRegistrationEndpointType)(nil)).Elem())
}
type LookupServiceRegistrationFilter struct {
vim.DynamicData
SiteId string `xml:"siteId,omitempty"`
NodeId string `xml:"nodeId,omitempty"`
ServiceType *LookupServiceRegistrationServiceType `xml:"serviceType,omitempty"`
EndpointType *LookupServiceRegistrationEndpointType `xml:"endpointType,omitempty"`
}
func init() {
types.Add("lookup:LookupServiceRegistrationFilter", reflect.TypeOf((*LookupServiceRegistrationFilter)(nil)).Elem())
}
type LookupServiceRegistrationInfo struct {
LookupServiceRegistrationCommonServiceInfo
ServiceId string `xml:"serviceId"`
SiteId string `xml:"siteId"`
}
func init() {
types.Add("lookup:LookupServiceRegistrationInfo", reflect.TypeOf((*LookupServiceRegistrationInfo)(nil)).Elem())
}
type LookupServiceRegistrationMutableServiceInfo struct {
vim.DynamicData
ServiceVersion string `xml:"serviceVersion"`
VendorNameResourceKey string `xml:"vendorNameResourceKey,omitempty"`
VendorNameDefault string `xml:"vendorNameDefault,omitempty"`
VendorProductInfoResourceKey string `xml:"vendorProductInfoResourceKey,omitempty"`
VendorProductInfoDefault string `xml:"vendorProductInfoDefault,omitempty"`
ServiceEndpoints []LookupServiceRegistrationEndpoint `xml:"serviceEndpoints,omitempty"`
ServiceAttributes []LookupServiceRegistrationAttribute `xml:"serviceAttributes,omitempty"`
ServiceNameResourceKey string `xml:"serviceNameResourceKey,omitempty"`
ServiceNameDefault string `xml:"serviceNameDefault,omitempty"`
ServiceDescriptionResourceKey string `xml:"serviceDescriptionResourceKey,omitempty"`
ServiceDescriptionDefault string `xml:"serviceDescriptionDefault,omitempty"`
}
func init() {
types.Add("lookup:LookupServiceRegistrationMutableServiceInfo", reflect.TypeOf((*LookupServiceRegistrationMutableServiceInfo)(nil)).Elem())
}
type LookupServiceRegistrationServiceType struct {
vim.DynamicData
Product string `xml:"product"`
Type string `xml:"type"`
}
func init() {
types.Add("lookup:LookupServiceRegistrationServiceType", reflect.TypeOf((*LookupServiceRegistrationServiceType)(nil)).Elem())
}
type LookupServiceRegistrationSetSpec struct {
LookupServiceRegistrationMutableServiceInfo
}
func init() {
types.Add("lookup:LookupServiceRegistrationSetSpec", reflect.TypeOf((*LookupServiceRegistrationSetSpec)(nil)).Elem())
}
type RetrieveHaBackupConfiguration RetrieveHaBackupConfigurationRequestType
func init() {
types.Add("lookup:RetrieveHaBackupConfiguration", reflect.TypeOf((*RetrieveHaBackupConfiguration)(nil)).Elem())
}
type RetrieveHaBackupConfigurationRequestType struct {
This vim.ManagedObjectReference `xml:"_this"`
}
func init() {
types.Add("lookup:RetrieveHaBackupConfigurationRequestType", reflect.TypeOf((*RetrieveHaBackupConfigurationRequestType)(nil)).Elem())
}
type RetrieveHaBackupConfigurationResponse struct {
Returnval LookupHaBackupNodeConfiguration `xml:"returnval"`
}
type RetrieveServiceContent RetrieveServiceContentRequestType
func init() {
types.Add("lookup:RetrieveServiceContent", reflect.TypeOf((*RetrieveServiceContent)(nil)).Elem())
}
type RetrieveServiceContentRequestType struct {
This vim.ManagedObjectReference `xml:"_this"`
}
func init() {
types.Add("lookup:RetrieveServiceContentRequestType", reflect.TypeOf((*RetrieveServiceContentRequestType)(nil)).Elem())
}
type RetrieveServiceContentResponse struct {
Returnval LookupServiceContent `xml:"returnval"`
}
type Set SetRequestType
func init() {
types.Add("lookup:Set", reflect.TypeOf((*Set)(nil)).Elem())
}
type SetLocale SetLocaleRequestType
func init() {
types.Add("lookup:SetLocale", reflect.TypeOf((*SetLocale)(nil)).Elem())
}
type SetLocaleRequestType struct {
This vim.ManagedObjectReference `xml:"_this"`
Locale string `xml:"locale"`
}
func init() {
types.Add("lookup:SetLocaleRequestType", reflect.TypeOf((*SetLocaleRequestType)(nil)).Elem())
}
type SetLocaleResponse struct {
Returnval string `xml:"returnval"`
}
type SetRequestType struct {
This vim.ManagedObjectReference `xml:"_this"`
ServiceId string `xml:"serviceId"`
ServiceSpec LookupServiceRegistrationSetSpec `xml:"serviceSpec"`
}
func init() {
types.Add("lookup:SetRequestType", reflect.TypeOf((*SetRequestType)(nil)).Elem())
}
type SetResponse struct {
}

View File

@@ -1,233 +0,0 @@
/*
Copyright (c) 2015-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.
*/
package nfc
import (
"context"
"fmt"
"io"
"path"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/task"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
type Lease struct {
types.ManagedObjectReference
c *vim25.Client
}
func NewLease(c *vim25.Client, ref types.ManagedObjectReference) *Lease {
return &Lease{ref, c}
}
// Abort wraps methods.Abort
func (l *Lease) Abort(ctx context.Context, fault *types.LocalizedMethodFault) error {
req := types.HttpNfcLeaseAbort{
This: l.Reference(),
Fault: fault,
}
_, err := methods.HttpNfcLeaseAbort(ctx, l.c, &req)
if err != nil {
return err
}
return nil
}
// Complete wraps methods.Complete
func (l *Lease) Complete(ctx context.Context) error {
req := types.HttpNfcLeaseComplete{
This: l.Reference(),
}
_, err := methods.HttpNfcLeaseComplete(ctx, l.c, &req)
if err != nil {
return err
}
return nil
}
// GetManifest wraps methods.GetManifest
func (l *Lease) GetManifest(ctx context.Context) error {
req := types.HttpNfcLeaseGetManifest{
This: l.Reference(),
}
_, err := methods.HttpNfcLeaseGetManifest(ctx, l.c, &req)
if err != nil {
return err
}
return nil
}
// Progress wraps methods.Progress
func (l *Lease) Progress(ctx context.Context, percent int32) error {
req := types.HttpNfcLeaseProgress{
This: l.Reference(),
Percent: percent,
}
_, err := methods.HttpNfcLeaseProgress(ctx, l.c, &req)
if err != nil {
return err
}
return nil
}
type LeaseInfo struct {
types.HttpNfcLeaseInfo
Items []FileItem
}
func (l *Lease) newLeaseInfo(li *types.HttpNfcLeaseInfo, items []types.OvfFileItem) (*LeaseInfo, error) {
info := &LeaseInfo{
HttpNfcLeaseInfo: *li,
}
for _, device := range li.DeviceUrl {
u, err := l.c.ParseURL(device.Url)
if err != nil {
return nil, err
}
if device.SslThumbprint != "" {
// TODO: prefer host management IP
l.c.SetThumbprint(u.Host, device.SslThumbprint)
}
if len(items) == 0 {
// this is an export
item := types.OvfFileItem{
DeviceId: device.Key,
Path: device.TargetId,
Size: device.FileSize,
}
if item.Size == 0 {
item.Size = li.TotalDiskCapacityInKB * 1024
}
if item.Path == "" {
item.Path = path.Base(device.Url)
}
info.Items = append(info.Items, NewFileItem(u, item))
continue
}
// this is an import
for _, item := range items {
if device.ImportKey == item.DeviceId {
info.Items = append(info.Items, NewFileItem(u, item))
break
}
}
}
return info, nil
}
func (l *Lease) Wait(ctx context.Context, items []types.OvfFileItem) (*LeaseInfo, error) {
var lease mo.HttpNfcLease
pc := property.DefaultCollector(l.c)
err := property.Wait(ctx, pc, l.Reference(), []string{"state", "info", "error"}, func(pc []types.PropertyChange) bool {
done := false
for _, c := range pc {
if c.Val == nil {
continue
}
switch c.Name {
case "error":
val := c.Val.(types.LocalizedMethodFault)
lease.Error = &val
done = true
case "info":
val := c.Val.(types.HttpNfcLeaseInfo)
lease.Info = &val
case "state":
lease.State = c.Val.(types.HttpNfcLeaseState)
if lease.State != types.HttpNfcLeaseStateInitializing {
done = true
}
}
}
return done
})
if err != nil {
return nil, err
}
if lease.State == types.HttpNfcLeaseStateReady {
return l.newLeaseInfo(lease.Info, items)
}
if lease.Error != nil {
return nil, &task.Error{LocalizedMethodFault: lease.Error}
}
return nil, fmt.Errorf("unexpected nfc lease state: %s", lease.State)
}
func (l *Lease) StartUpdater(ctx context.Context, info *LeaseInfo) *LeaseUpdater {
return newLeaseUpdater(ctx, l, info)
}
func (l *Lease) Upload(ctx context.Context, item FileItem, f io.Reader, opts soap.Upload) error {
if opts.Progress == nil {
opts.Progress = item
}
// Non-disk files (such as .iso) use the PUT method.
// Overwrite: t header is also required in this case (ovftool does the same)
if item.Create {
opts.Method = "PUT"
opts.Headers = map[string]string{
"Overwrite": "t",
}
} else {
opts.Method = "POST"
opts.Type = "application/x-vnd.vmware-streamVmdk"
}
return l.c.Upload(ctx, f, item.URL, &opts)
}
func (l *Lease) DownloadFile(ctx context.Context, file string, item FileItem, opts soap.Download) error {
if opts.Progress == nil {
opts.Progress = item
}
return l.c.DownloadFile(ctx, file, item.URL, &opts)
}

View File

@@ -1,146 +0,0 @@
/*
Copyright (c) 2014-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.
*/
package nfc
import (
"context"
"log"
"net/url"
"sync"
"sync/atomic"
"time"
"github.com/vmware/govmomi/vim25/progress"
"github.com/vmware/govmomi/vim25/types"
)
type FileItem struct {
types.OvfFileItem
URL *url.URL
ch chan progress.Report
}
func NewFileItem(u *url.URL, item types.OvfFileItem) FileItem {
return FileItem{
OvfFileItem: item,
URL: u,
ch: make(chan progress.Report),
}
}
func (o FileItem) Sink() chan<- progress.Report {
return o.ch
}
// File converts the FileItem.OvfFileItem to an OvfFile
func (o FileItem) File() types.OvfFile {
return types.OvfFile{
DeviceId: o.DeviceId,
Path: o.Path,
Size: o.Size,
}
}
type LeaseUpdater struct {
pos int64 // Number of bytes (keep first to ensure 64 bit alignment)
total int64 // Total number of bytes (keep first to ensure 64 bit alignment)
lease *Lease
done chan struct{} // When lease updater should stop
wg sync.WaitGroup // Track when update loop is done
}
func newLeaseUpdater(ctx context.Context, lease *Lease, info *LeaseInfo) *LeaseUpdater {
l := LeaseUpdater{
lease: lease,
done: make(chan struct{}),
}
for _, item := range info.Items {
l.total += item.Size
go l.waitForProgress(item)
}
// Kickstart update loop
l.wg.Add(1)
go l.run()
return &l
}
func (l *LeaseUpdater) waitForProgress(item FileItem) {
var pos, total int64
total = item.Size
for {
select {
case <-l.done:
return
case p, ok := <-item.ch:
// Return in case of error
if ok && p.Error() != nil {
return
}
if !ok {
// Last element on the channel, add to total
atomic.AddInt64(&l.pos, total-pos)
return
}
// Approximate progress in number of bytes
x := int64(float32(total) * (p.Percentage() / 100.0))
atomic.AddInt64(&l.pos, x-pos)
pos = x
}
}
}
func (l *LeaseUpdater) run() {
defer l.wg.Done()
tick := time.NewTicker(2 * time.Second)
defer tick.Stop()
for {
select {
case <-l.done:
return
case <-tick.C:
// From the vim api HttpNfcLeaseProgress(percent) doc, percent ==
// "Completion status represented as an integer in the 0-100 range."
// Always report the current value of percent, as it will renew the
// lease even if the value hasn't changed or is 0.
percent := int32(float32(100*atomic.LoadInt64(&l.pos)) / float32(l.total))
err := l.lease.Progress(context.TODO(), percent)
if err != nil {
log.Printf("NFC lease progress: %s", err)
return
}
}
}
}
func (l *LeaseUpdater) Done() {
close(l.done)
l.wg.Wait()
}

View File

@@ -1,221 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type AuthorizationManager struct {
Common
}
func NewAuthorizationManager(c *vim25.Client) *AuthorizationManager {
m := AuthorizationManager{
Common: NewCommon(c, *c.ServiceContent.AuthorizationManager),
}
return &m
}
type AuthorizationRoleList []types.AuthorizationRole
func (l AuthorizationRoleList) ById(id int32) *types.AuthorizationRole {
for _, role := range l {
if role.RoleId == id {
return &role
}
}
return nil
}
func (l AuthorizationRoleList) ByName(name string) *types.AuthorizationRole {
for _, role := range l {
if role.Name == name {
return &role
}
}
return nil
}
func (m AuthorizationManager) RoleList(ctx context.Context) (AuthorizationRoleList, error) {
var am mo.AuthorizationManager
err := m.Properties(ctx, m.Reference(), []string{"roleList"}, &am)
if err != nil {
return nil, err
}
return AuthorizationRoleList(am.RoleList), nil
}
func (m AuthorizationManager) RetrieveEntityPermissions(ctx context.Context, entity types.ManagedObjectReference, inherited bool) ([]types.Permission, error) {
req := types.RetrieveEntityPermissions{
This: m.Reference(),
Entity: entity,
Inherited: inherited,
}
res, err := methods.RetrieveEntityPermissions(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m AuthorizationManager) RemoveEntityPermission(ctx context.Context, entity types.ManagedObjectReference, user string, isGroup bool) error {
req := types.RemoveEntityPermission{
This: m.Reference(),
Entity: entity,
User: user,
IsGroup: isGroup,
}
_, err := methods.RemoveEntityPermission(ctx, m.Client(), &req)
return err
}
func (m AuthorizationManager) SetEntityPermissions(ctx context.Context, entity types.ManagedObjectReference, permission []types.Permission) error {
req := types.SetEntityPermissions{
This: m.Reference(),
Entity: entity,
Permission: permission,
}
_, err := methods.SetEntityPermissions(ctx, m.Client(), &req)
return err
}
func (m AuthorizationManager) RetrieveRolePermissions(ctx context.Context, id int32) ([]types.Permission, error) {
req := types.RetrieveRolePermissions{
This: m.Reference(),
RoleId: id,
}
res, err := methods.RetrieveRolePermissions(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m AuthorizationManager) RetrieveAllPermissions(ctx context.Context) ([]types.Permission, error) {
req := types.RetrieveAllPermissions{
This: m.Reference(),
}
res, err := methods.RetrieveAllPermissions(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m AuthorizationManager) AddRole(ctx context.Context, name string, ids []string) (int32, error) {
req := types.AddAuthorizationRole{
This: m.Reference(),
Name: name,
PrivIds: ids,
}
res, err := methods.AddAuthorizationRole(ctx, m.Client(), &req)
if err != nil {
return -1, err
}
return res.Returnval, nil
}
func (m AuthorizationManager) RemoveRole(ctx context.Context, id int32, failIfUsed bool) error {
req := types.RemoveAuthorizationRole{
This: m.Reference(),
RoleId: id,
FailIfUsed: failIfUsed,
}
_, err := methods.RemoveAuthorizationRole(ctx, m.Client(), &req)
return err
}
func (m AuthorizationManager) UpdateRole(ctx context.Context, id int32, name string, ids []string) error {
req := types.UpdateAuthorizationRole{
This: m.Reference(),
RoleId: id,
NewName: name,
PrivIds: ids,
}
_, err := methods.UpdateAuthorizationRole(ctx, m.Client(), &req)
return err
}
func (m AuthorizationManager) HasUserPrivilegeOnEntities(ctx context.Context, entities []types.ManagedObjectReference, userName string, privID []string) ([]types.EntityPrivilege, error) {
req := types.HasUserPrivilegeOnEntities{
This: m.Reference(),
Entities: entities,
UserName: userName,
PrivId: privID,
}
res, err := methods.HasUserPrivilegeOnEntities(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m AuthorizationManager) HasPrivilegeOnEntity(ctx context.Context, entity types.ManagedObjectReference, sessionID string, privID []string) ([]bool, error) {
req := types.HasPrivilegeOnEntity{
This: m.Reference(),
Entity: entity,
SessionId: sessionID,
PrivId: privID,
}
res, err := methods.HasPrivilegeOnEntity(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m AuthorizationManager) FetchUserPrivilegeOnEntities(ctx context.Context, entities []types.ManagedObjectReference, userName string) ([]types.UserPrivilegeResult, error) {
req := types.FetchUserPrivilegeOnEntities{
This: m.Reference(),
Entities: entities,
UserName: userName,
}
res, err := methods.FetchUserPrivilegeOnEntities(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}

View File

@@ -1,86 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
type DisabledMethodRequest struct {
Method string `xml:"method"`
Reason string `xml:"reasonId"`
}
type disableMethodsRequest struct {
This types.ManagedObjectReference `xml:"_this"`
Entity []types.ManagedObjectReference `xml:"entity"`
Method []DisabledMethodRequest `xml:"method"`
Source string `xml:"sourceId"`
Scope bool `xml:"sessionScope,omitempty"`
}
type disableMethodsBody struct {
Req *disableMethodsRequest `xml:"urn:internalvim25 DisableMethods,omitempty"`
Res interface{} `xml:"urn:vim25 DisableMethodsResponse,omitempty"`
Err *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *disableMethodsBody) Fault() *soap.Fault { return b.Err }
func (m AuthorizationManager) DisableMethods(ctx context.Context, entity []types.ManagedObjectReference, method []DisabledMethodRequest, source string) error {
var reqBody, resBody disableMethodsBody
reqBody.Req = &disableMethodsRequest{
This: m.Reference(),
Entity: entity,
Method: method,
Source: source,
}
return m.Client().RoundTrip(ctx, &reqBody, &resBody)
}
type enableMethodsRequest struct {
This types.ManagedObjectReference `xml:"_this"`
Entity []types.ManagedObjectReference `xml:"entity"`
Method []string `xml:"method"`
Source string `xml:"sourceId"`
}
type enableMethodsBody struct {
Req *enableMethodsRequest `xml:"urn:internalvim25 EnableMethods,omitempty"`
Res interface{} `xml:"urn:vim25 EnableMethodsResponse,omitempty"`
Err *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *enableMethodsBody) Fault() *soap.Fault { return b.Err }
func (m AuthorizationManager) EnableMethods(ctx context.Context, entity []types.ManagedObjectReference, method []string, source string) error {
var reqBody, resBody enableMethodsBody
reqBody.Req = &enableMethodsRequest{
This: m.Reference(),
Entity: entity,
Method: method,
Source: source,
}
return m.Client().RoundTrip(ctx, &reqBody, &resBody)
}

View File

@@ -1,103 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type ClusterComputeResource struct {
ComputeResource
}
func NewClusterComputeResource(c *vim25.Client, ref types.ManagedObjectReference) *ClusterComputeResource {
return &ClusterComputeResource{
ComputeResource: *NewComputeResource(c, ref),
}
}
func (c ClusterComputeResource) Configuration(ctx context.Context) (*types.ClusterConfigInfoEx, error) {
var obj mo.ClusterComputeResource
err := c.Properties(ctx, c.Reference(), []string{"configurationEx"}, &obj)
if err != nil {
return nil, err
}
return obj.ConfigurationEx.(*types.ClusterConfigInfoEx), nil
}
func (c ClusterComputeResource) AddHost(ctx context.Context, spec types.HostConnectSpec, asConnected bool, license *string, resourcePool *types.ManagedObjectReference) (*Task, error) {
req := types.AddHost_Task{
This: c.Reference(),
Spec: spec,
AsConnected: asConnected,
}
if license != nil {
req.License = *license
}
if resourcePool != nil {
req.ResourcePool = resourcePool
}
res, err := methods.AddHost_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
return NewTask(c.c, res.Returnval), nil
}
func (c ClusterComputeResource) MoveInto(ctx context.Context, hosts ...*HostSystem) (*Task, error) {
req := types.MoveInto_Task{
This: c.Reference(),
}
hostReferences := make([]types.ManagedObjectReference, len(hosts))
for i, host := range hosts {
hostReferences[i] = host.Reference()
}
req.Host = hostReferences
res, err := methods.MoveInto_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
return NewTask(c.c, res.Returnval), nil
}
func (c ClusterComputeResource) PlaceVm(ctx context.Context, spec types.PlacementSpec) (*types.PlacementResult, error) {
req := types.PlaceVm{
This: c.Reference(),
PlacementSpec: spec,
}
res, err := methods.PlaceVm(ctx, c.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}

View File

@@ -1,148 +0,0 @@
/*
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.
*/
package object
import (
"context"
"errors"
"fmt"
"path"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
var (
ErrNotSupported = errors.New("product/version specific feature not supported by target")
)
// Common contains the fields and functions common to all objects.
type Common struct {
InventoryPath string
c *vim25.Client
r types.ManagedObjectReference
}
func (c Common) String() string {
ref := fmt.Sprintf("%v", c.Reference())
if c.InventoryPath == "" {
return ref
}
return fmt.Sprintf("%s @ %s", ref, c.InventoryPath)
}
func NewCommon(c *vim25.Client, r types.ManagedObjectReference) Common {
return Common{c: c, r: r}
}
func (c Common) Reference() types.ManagedObjectReference {
return c.r
}
func (c Common) Client() *vim25.Client {
return c.c
}
// Name returns the base name of the InventoryPath field
func (c Common) Name() string {
if c.InventoryPath == "" {
return ""
}
return path.Base(c.InventoryPath)
}
func (c *Common) SetInventoryPath(p string) {
c.InventoryPath = p
}
// ObjectName fetches the mo.ManagedEntity.Name field via the property collector.
func (c Common) ObjectName(ctx context.Context) (string, error) {
var content []types.ObjectContent
err := c.Properties(ctx, c.Reference(), []string{"name"}, &content)
if err != nil {
return "", err
}
for i := range content {
for _, prop := range content[i].PropSet {
return prop.Val.(string), nil
}
}
return "", nil
}
// Properties is a wrapper for property.DefaultCollector().RetrieveOne()
func (c Common) Properties(ctx context.Context, r types.ManagedObjectReference, ps []string, dst interface{}) error {
return property.DefaultCollector(c.c).RetrieveOne(ctx, r, ps, dst)
}
func (c Common) Destroy(ctx context.Context) (*Task, error) {
req := types.Destroy_Task{
This: c.Reference(),
}
res, err := methods.Destroy_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
return NewTask(c.c, res.Returnval), nil
}
func (c Common) Rename(ctx context.Context, name string) (*Task, error) {
req := types.Rename_Task{
This: c.Reference(),
NewName: name,
}
res, err := methods.Rename_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
return NewTask(c.c, res.Returnval), nil
}
func (c Common) SetCustomValue(ctx context.Context, key string, value string) error {
req := types.SetCustomValue{
This: c.Reference(),
Key: key,
Value: value,
}
_, err := methods.SetCustomValue(ctx, c.c, &req)
return err
}
func ReferenceFromString(s string) *types.ManagedObjectReference {
var ref types.ManagedObjectReference
if !ref.FromString(s) {
return nil
}
if mo.IsManagedObjectType(ref.Type) {
return &ref
}
return nil
}

View File

@@ -1,111 +0,0 @@
/*
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.
*/
package object
import (
"context"
"path"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type ComputeResource struct {
Common
}
func NewComputeResource(c *vim25.Client, ref types.ManagedObjectReference) *ComputeResource {
return &ComputeResource{
Common: NewCommon(c, ref),
}
}
func (c ComputeResource) Hosts(ctx context.Context) ([]*HostSystem, error) {
var cr mo.ComputeResource
err := c.Properties(ctx, c.Reference(), []string{"host"}, &cr)
if err != nil {
return nil, err
}
if len(cr.Host) == 0 {
return nil, nil
}
var hs []mo.HostSystem
pc := property.DefaultCollector(c.Client())
err = pc.Retrieve(ctx, cr.Host, []string{"name"}, &hs)
if err != nil {
return nil, err
}
var hosts []*HostSystem
for _, h := range hs {
host := NewHostSystem(c.Client(), h.Reference())
host.InventoryPath = path.Join(c.InventoryPath, h.Name)
hosts = append(hosts, host)
}
return hosts, nil
}
func (c ComputeResource) Datastores(ctx context.Context) ([]*Datastore, error) {
var cr mo.ComputeResource
err := c.Properties(ctx, c.Reference(), []string{"datastore"}, &cr)
if err != nil {
return nil, err
}
var dss []*Datastore
for _, ref := range cr.Datastore {
ds := NewDatastore(c.c, ref)
dss = append(dss, ds)
}
return dss, nil
}
func (c ComputeResource) ResourcePool(ctx context.Context) (*ResourcePool, error) {
var cr mo.ComputeResource
err := c.Properties(ctx, c.Reference(), []string{"resourcePool"}, &cr)
if err != nil {
return nil, err
}
return NewResourcePool(c.c, *cr.ResourcePool), nil
}
func (c ComputeResource) Reconfigure(ctx context.Context, spec types.BaseComputeResourceConfigSpec, modify bool) (*Task, error) {
req := types.ReconfigureComputeResource_Task{
This: c.Reference(),
Spec: spec,
Modify: modify,
}
res, err := methods.ReconfigureComputeResource_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
return NewTask(c.c, res.Returnval), nil
}

View File

@@ -1,146 +0,0 @@
/*
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.
*/
package object
import (
"context"
"errors"
"strconv"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
var (
ErrKeyNameNotFound = errors.New("key name not found")
)
type CustomFieldsManager struct {
Common
}
// GetCustomFieldsManager wraps NewCustomFieldsManager, returning ErrNotSupported
// when the client is not connected to a vCenter instance.
func GetCustomFieldsManager(c *vim25.Client) (*CustomFieldsManager, error) {
if c.ServiceContent.CustomFieldsManager == nil {
return nil, ErrNotSupported
}
return NewCustomFieldsManager(c), nil
}
func NewCustomFieldsManager(c *vim25.Client) *CustomFieldsManager {
m := CustomFieldsManager{
Common: NewCommon(c, *c.ServiceContent.CustomFieldsManager),
}
return &m
}
func (m CustomFieldsManager) Add(ctx context.Context, name string, moType string, fieldDefPolicy *types.PrivilegePolicyDef, fieldPolicy *types.PrivilegePolicyDef) (*types.CustomFieldDef, error) {
req := types.AddCustomFieldDef{
This: m.Reference(),
Name: name,
MoType: moType,
FieldDefPolicy: fieldDefPolicy,
FieldPolicy: fieldPolicy,
}
res, err := methods.AddCustomFieldDef(ctx, m.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (m CustomFieldsManager) Remove(ctx context.Context, key int32) error {
req := types.RemoveCustomFieldDef{
This: m.Reference(),
Key: key,
}
_, err := methods.RemoveCustomFieldDef(ctx, m.c, &req)
return err
}
func (m CustomFieldsManager) Rename(ctx context.Context, key int32, name string) error {
req := types.RenameCustomFieldDef{
This: m.Reference(),
Key: key,
Name: name,
}
_, err := methods.RenameCustomFieldDef(ctx, m.c, &req)
return err
}
func (m CustomFieldsManager) Set(ctx context.Context, entity types.ManagedObjectReference, key int32, value string) error {
req := types.SetField{
This: m.Reference(),
Entity: entity,
Key: key,
Value: value,
}
_, err := methods.SetField(ctx, m.c, &req)
return err
}
type CustomFieldDefList []types.CustomFieldDef
func (m CustomFieldsManager) Field(ctx context.Context) (CustomFieldDefList, error) {
var fm mo.CustomFieldsManager
err := m.Properties(ctx, m.Reference(), []string{"field"}, &fm)
if err != nil {
return nil, err
}
return fm.Field, nil
}
func (m CustomFieldsManager) FindKey(ctx context.Context, name string) (int32, error) {
field, err := m.Field(ctx)
if err != nil {
return -1, err
}
for _, def := range field {
if def.Name == name {
return def.Key, nil
}
}
k, err := strconv.Atoi(name)
if err == nil {
// assume literal int key
return int32(k), nil
}
return -1, ErrKeyNameNotFound
}
func (l CustomFieldDefList) ByKey(key int32) *types.CustomFieldDef {
for _, def := range l {
if def.Key == key {
return &def
}
}
return nil
}

View File

@@ -1,173 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type CustomizationSpecManager struct {
Common
}
func NewCustomizationSpecManager(c *vim25.Client) *CustomizationSpecManager {
cs := CustomizationSpecManager{
Common: NewCommon(c, *c.ServiceContent.CustomizationSpecManager),
}
return &cs
}
func (cs CustomizationSpecManager) Info(ctx context.Context) ([]types.CustomizationSpecInfo, error) {
var m mo.CustomizationSpecManager
err := cs.Properties(ctx, cs.Reference(), []string{"info"}, &m)
return m.Info, err
}
func (cs CustomizationSpecManager) DoesCustomizationSpecExist(ctx context.Context, name string) (bool, error) {
req := types.DoesCustomizationSpecExist{
This: cs.Reference(),
Name: name,
}
res, err := methods.DoesCustomizationSpecExist(ctx, cs.c, &req)
if err != nil {
return false, err
}
return res.Returnval, nil
}
func (cs CustomizationSpecManager) GetCustomizationSpec(ctx context.Context, name string) (*types.CustomizationSpecItem, error) {
req := types.GetCustomizationSpec{
This: cs.Reference(),
Name: name,
}
res, err := methods.GetCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (cs CustomizationSpecManager) CreateCustomizationSpec(ctx context.Context, item types.CustomizationSpecItem) error {
req := types.CreateCustomizationSpec{
This: cs.Reference(),
Item: item,
}
_, err := methods.CreateCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return err
}
return nil
}
func (cs CustomizationSpecManager) OverwriteCustomizationSpec(ctx context.Context, item types.CustomizationSpecItem) error {
req := types.OverwriteCustomizationSpec{
This: cs.Reference(),
Item: item,
}
_, err := methods.OverwriteCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return err
}
return nil
}
func (cs CustomizationSpecManager) DeleteCustomizationSpec(ctx context.Context, name string) error {
req := types.DeleteCustomizationSpec{
This: cs.Reference(),
Name: name,
}
_, err := methods.DeleteCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return err
}
return nil
}
func (cs CustomizationSpecManager) DuplicateCustomizationSpec(ctx context.Context, name string, newName string) error {
req := types.DuplicateCustomizationSpec{
This: cs.Reference(),
Name: name,
NewName: newName,
}
_, err := methods.DuplicateCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return err
}
return nil
}
func (cs CustomizationSpecManager) RenameCustomizationSpec(ctx context.Context, name string, newName string) error {
req := types.RenameCustomizationSpec{
This: cs.Reference(),
Name: name,
NewName: newName,
}
_, err := methods.RenameCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return err
}
return nil
}
func (cs CustomizationSpecManager) CustomizationSpecItemToXml(ctx context.Context, item types.CustomizationSpecItem) (string, error) {
req := types.CustomizationSpecItemToXml{
This: cs.Reference(),
Item: item,
}
res, err := methods.CustomizationSpecItemToXml(ctx, cs.c, &req)
if err != nil {
return "", err
}
return res.Returnval, nil
}
func (cs CustomizationSpecManager) XmlToCustomizationSpecItem(ctx context.Context, xml string) (*types.CustomizationSpecItem, error) {
req := types.XmlToCustomizationSpecItem{
This: cs.Reference(),
SpecItemXml: xml,
}
res, err := methods.XmlToCustomizationSpecItem(ctx, cs.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}

View File

@@ -1,129 +0,0 @@
/*
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.
*/
package object
import (
"context"
"fmt"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type DatacenterFolders struct {
VmFolder *Folder
HostFolder *Folder
DatastoreFolder *Folder
NetworkFolder *Folder
}
type Datacenter struct {
Common
}
func NewDatacenter(c *vim25.Client, ref types.ManagedObjectReference) *Datacenter {
return &Datacenter{
Common: NewCommon(c, ref),
}
}
func (d *Datacenter) Folders(ctx context.Context) (*DatacenterFolders, error) {
var md mo.Datacenter
ps := []string{"name", "vmFolder", "hostFolder", "datastoreFolder", "networkFolder"}
err := d.Properties(ctx, d.Reference(), ps, &md)
if err != nil {
return nil, err
}
df := &DatacenterFolders{
VmFolder: NewFolder(d.c, md.VmFolder),
HostFolder: NewFolder(d.c, md.HostFolder),
DatastoreFolder: NewFolder(d.c, md.DatastoreFolder),
NetworkFolder: NewFolder(d.c, md.NetworkFolder),
}
paths := []struct {
name string
path *string
}{
{"vm", &df.VmFolder.InventoryPath},
{"host", &df.HostFolder.InventoryPath},
{"datastore", &df.DatastoreFolder.InventoryPath},
{"network", &df.NetworkFolder.InventoryPath},
}
for _, p := range paths {
*p.path = fmt.Sprintf("/%s/%s", md.Name, p.name)
}
return df, nil
}
func (d Datacenter) Destroy(ctx context.Context) (*Task, error) {
req := types.Destroy_Task{
This: d.Reference(),
}
res, err := methods.Destroy_Task(ctx, d.c, &req)
if err != nil {
return nil, err
}
return NewTask(d.c, res.Returnval), nil
}
// PowerOnVM powers on multiple virtual machines with a single vCenter call.
// If called against ESX, serially powers on the list of VMs and the returned *Task will always be nil.
func (d Datacenter) PowerOnVM(ctx context.Context, vm []types.ManagedObjectReference, option ...types.BaseOptionValue) (*Task, error) {
if d.Client().IsVC() {
req := types.PowerOnMultiVM_Task{
This: d.Reference(),
Vm: vm,
Option: option,
}
res, err := methods.PowerOnMultiVM_Task(ctx, d.c, &req)
if err != nil {
return nil, err
}
return NewTask(d.c, res.Returnval), nil
}
for _, ref := range vm {
obj := NewVirtualMachine(d.Client(), ref)
task, err := obj.PowerOn(ctx)
if err != nil {
return nil, err
}
err = task.Wait(ctx)
if err != nil {
// Ignore any InvalidPowerState fault, as it indicates the VM is already powered on
if f, ok := err.(types.HasFault); ok {
if _, ok = f.Fault().(*types.InvalidPowerState); !ok {
return nil, err
}
}
}
}
return nil, nil
}

View File

@@ -1,439 +0,0 @@
/*
Copyright (c) 2015-2016 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.
*/
package object
import (
"context"
"fmt"
"io"
"math/rand"
"net/http"
"net/url"
"os"
"path"
"strings"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/session"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
// DatastoreNoSuchDirectoryError is returned when a directory could not be found.
type DatastoreNoSuchDirectoryError struct {
verb string
subject string
}
func (e DatastoreNoSuchDirectoryError) Error() string {
return fmt.Sprintf("cannot %s '%s': No such directory", e.verb, e.subject)
}
// DatastoreNoSuchFileError is returned when a file could not be found.
type DatastoreNoSuchFileError struct {
verb string
subject string
}
func (e DatastoreNoSuchFileError) Error() string {
return fmt.Sprintf("cannot %s '%s': No such file", e.verb, e.subject)
}
type Datastore struct {
Common
DatacenterPath string
}
func NewDatastore(c *vim25.Client, ref types.ManagedObjectReference) *Datastore {
return &Datastore{
Common: NewCommon(c, ref),
}
}
func (d Datastore) Path(path string) string {
var p DatastorePath
if p.FromString(path) {
return p.String() // already in "[datastore] path" format
}
return (&DatastorePath{
Datastore: d.Name(),
Path: path,
}).String()
}
// NewURL constructs a url.URL with the given file path for datastore access over HTTP.
func (d Datastore) NewURL(path string) *url.URL {
u := d.c.URL()
return &url.URL{
Scheme: u.Scheme,
Host: u.Host,
Path: fmt.Sprintf("/folder/%s", path),
RawQuery: url.Values{
"dcPath": []string{d.DatacenterPath},
"dsName": []string{d.Name()},
}.Encode(),
}
}
// URL is deprecated, use NewURL instead.
func (d Datastore) URL(ctx context.Context, dc *Datacenter, path string) (*url.URL, error) {
return d.NewURL(path), nil
}
func (d Datastore) Browser(ctx context.Context) (*HostDatastoreBrowser, error) {
var do mo.Datastore
err := d.Properties(ctx, d.Reference(), []string{"browser"}, &do)
if err != nil {
return nil, err
}
return NewHostDatastoreBrowser(d.c, do.Browser), nil
}
func (d Datastore) useServiceTicket() bool {
// If connected to workstation, service ticketing not supported
// If connected to ESX, service ticketing not needed
if !d.c.IsVC() {
return false
}
key := "GOVMOMI_USE_SERVICE_TICKET"
val := d.c.URL().Query().Get(key)
if val == "" {
val = os.Getenv(key)
}
if val == "1" || val == "true" {
return true
}
return false
}
func (d Datastore) useServiceTicketHostName(name string) bool {
// No need if talking directly to ESX.
if !d.c.IsVC() {
return false
}
// If version happens to be < 5.1
if name == "" {
return false
}
// If the HostSystem is using DHCP on a network without dynamic DNS,
// HostSystem.Config.Network.DnsConfig.HostName is set to "localhost" by default.
// This resolves to "localhost.localdomain" by default via /etc/hosts on ESX.
// In that case, we will stick with the HostSystem.Name which is the IP address that
// was used to connect the host to VC.
if name == "localhost.localdomain" {
return false
}
// Still possible to have HostName that don't resolve via DNS,
// so we default to false.
key := "GOVMOMI_USE_SERVICE_TICKET_HOSTNAME"
val := d.c.URL().Query().Get(key)
if val == "" {
val = os.Getenv(key)
}
if val == "1" || val == "true" {
return true
}
return false
}
type datastoreServiceTicketHostKey struct{}
// HostContext returns a Context where the given host will be used for datastore HTTP access
// via the ServiceTicket method.
func (d Datastore) HostContext(ctx context.Context, host *HostSystem) context.Context {
return context.WithValue(ctx, datastoreServiceTicketHostKey{}, host)
}
// ServiceTicket obtains a ticket via AcquireGenericServiceTicket and returns it an http.Cookie with the url.URL
// that can be used along with the ticket cookie to access the given path. An host is chosen at random unless the
// the given Context was created with a specific host via the HostContext method.
func (d Datastore) ServiceTicket(ctx context.Context, path string, method string) (*url.URL, *http.Cookie, error) {
u := d.NewURL(path)
host, ok := ctx.Value(datastoreServiceTicketHostKey{}).(*HostSystem)
if !ok {
if !d.useServiceTicket() {
return u, nil, nil
}
hosts, err := d.AttachedHosts(ctx)
if err != nil {
return nil, nil, err
}
if len(hosts) == 0 {
// Fallback to letting vCenter choose a host
return u, nil, nil
}
// Pick a random attached host
host = hosts[rand.Intn(len(hosts))]
}
ips, err := host.ManagementIPs(ctx)
if err != nil {
return nil, nil, err
}
if len(ips) > 0 {
// prefer a ManagementIP
u.Host = ips[0].String()
} else {
// fallback to inventory name
u.Host, err = host.ObjectName(ctx)
if err != nil {
return nil, nil, err
}
}
// VC datacenter path will not be valid against ESX
q := u.Query()
delete(q, "dcPath")
u.RawQuery = q.Encode()
spec := types.SessionManagerHttpServiceRequestSpec{
Url: u.String(),
// See SessionManagerHttpServiceRequestSpecMethod enum
Method: fmt.Sprintf("http%s%s", method[0:1], strings.ToLower(method[1:])),
}
sm := session.NewManager(d.Client())
ticket, err := sm.AcquireGenericServiceTicket(ctx, &spec)
if err != nil {
return nil, nil, err
}
cookie := &http.Cookie{
Name: "vmware_cgi_ticket",
Value: ticket.Id,
}
if d.useServiceTicketHostName(ticket.HostName) {
u.Host = ticket.HostName
}
d.Client().SetThumbprint(u.Host, ticket.SslThumbprint)
return u, cookie, nil
}
func (d Datastore) uploadTicket(ctx context.Context, path string, param *soap.Upload) (*url.URL, *soap.Upload, error) {
p := soap.DefaultUpload
if param != nil {
p = *param // copy
}
u, ticket, err := d.ServiceTicket(ctx, path, p.Method)
if err != nil {
return nil, nil, err
}
p.Ticket = ticket
return u, &p, nil
}
func (d Datastore) downloadTicket(ctx context.Context, path string, param *soap.Download) (*url.URL, *soap.Download, error) {
p := soap.DefaultDownload
if param != nil {
p = *param // copy
}
u, ticket, err := d.ServiceTicket(ctx, path, p.Method)
if err != nil {
return nil, nil, err
}
p.Ticket = ticket
return u, &p, nil
}
// Upload via soap.Upload with an http service ticket
func (d Datastore) Upload(ctx context.Context, f io.Reader, path string, param *soap.Upload) error {
u, p, err := d.uploadTicket(ctx, path, param)
if err != nil {
return err
}
return d.Client().Upload(ctx, f, u, p)
}
// UploadFile via soap.Upload with an http service ticket
func (d Datastore) UploadFile(ctx context.Context, file string, path string, param *soap.Upload) error {
u, p, err := d.uploadTicket(ctx, path, param)
if err != nil {
return err
}
return d.Client().UploadFile(ctx, file, u, p)
}
// Download via soap.Download with an http service ticket
func (d Datastore) Download(ctx context.Context, path string, param *soap.Download) (io.ReadCloser, int64, error) {
u, p, err := d.downloadTicket(ctx, path, param)
if err != nil {
return nil, 0, err
}
return d.Client().Download(ctx, u, p)
}
// DownloadFile via soap.Download with an http service ticket
func (d Datastore) DownloadFile(ctx context.Context, path string, file string, param *soap.Download) error {
u, p, err := d.downloadTicket(ctx, path, param)
if err != nil {
return err
}
return d.Client().DownloadFile(ctx, file, u, p)
}
// AttachedHosts returns hosts that have this Datastore attached, accessible and writable.
func (d Datastore) AttachedHosts(ctx context.Context) ([]*HostSystem, error) {
var ds mo.Datastore
var hosts []*HostSystem
pc := property.DefaultCollector(d.Client())
err := pc.RetrieveOne(ctx, d.Reference(), []string{"host"}, &ds)
if err != nil {
return nil, err
}
mounts := make(map[types.ManagedObjectReference]types.DatastoreHostMount)
var refs []types.ManagedObjectReference
for _, host := range ds.Host {
refs = append(refs, host.Key)
mounts[host.Key] = host
}
var hs []mo.HostSystem
err = pc.Retrieve(ctx, refs, []string{"runtime.connectionState", "runtime.powerState"}, &hs)
if err != nil {
return nil, err
}
for _, host := range hs {
if host.Runtime.ConnectionState == types.HostSystemConnectionStateConnected &&
host.Runtime.PowerState == types.HostSystemPowerStatePoweredOn {
mount := mounts[host.Reference()]
info := mount.MountInfo
if *info.Mounted && *info.Accessible && info.AccessMode == string(types.HostMountModeReadWrite) {
hosts = append(hosts, NewHostSystem(d.Client(), mount.Key))
}
}
}
return hosts, nil
}
// AttachedClusterHosts returns hosts that have this Datastore attached, accessible and writable and are members of the given cluster.
func (d Datastore) AttachedClusterHosts(ctx context.Context, cluster *ComputeResource) ([]*HostSystem, error) {
var hosts []*HostSystem
clusterHosts, err := cluster.Hosts(ctx)
if err != nil {
return nil, err
}
attachedHosts, err := d.AttachedHosts(ctx)
if err != nil {
return nil, err
}
refs := make(map[types.ManagedObjectReference]bool)
for _, host := range attachedHosts {
refs[host.Reference()] = true
}
for _, host := range clusterHosts {
if refs[host.Reference()] {
hosts = append(hosts, host)
}
}
return hosts, nil
}
func (d Datastore) Stat(ctx context.Context, file string) (types.BaseFileInfo, error) {
b, err := d.Browser(ctx)
if err != nil {
return nil, err
}
spec := types.HostDatastoreBrowserSearchSpec{
Details: &types.FileQueryFlags{
FileType: true,
FileSize: true,
Modification: true,
FileOwner: types.NewBool(true),
},
MatchPattern: []string{path.Base(file)},
}
dsPath := d.Path(path.Dir(file))
task, err := b.SearchDatastore(ctx, dsPath, &spec)
if err != nil {
return nil, err
}
info, err := task.WaitForResult(ctx, nil)
if err != nil {
if types.IsFileNotFound(err) {
// FileNotFound means the base path doesn't exist.
return nil, DatastoreNoSuchDirectoryError{"stat", dsPath}
}
return nil, err
}
res := info.Result.(types.HostDatastoreBrowserSearchResults)
if len(res.File) == 0 {
// File doesn't exist
return nil, DatastoreNoSuchFileError{"stat", d.Path(file)}
}
return res.File[0], nil
}
// Type returns the type of file system volume.
func (d Datastore) Type(ctx context.Context) (types.HostFileSystemVolumeFileSystemType, error) {
var mds mo.Datastore
if err := d.Properties(ctx, d.Reference(), []string{"summary.type"}, &mds); err != nil {
return types.HostFileSystemVolumeFileSystemType(""), err
}
return types.HostFileSystemVolumeFileSystemType(mds.Summary.Type), nil
}

View File

@@ -1,412 +0,0 @@
/*
Copyright (c) 2016-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.
*/
package object
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"os"
"path"
"sync"
"time"
"github.com/vmware/govmomi/vim25/soap"
)
// DatastoreFile implements io.Reader, io.Seeker and io.Closer interfaces for datastore file access.
type DatastoreFile struct {
d Datastore
ctx context.Context
name string
buf io.Reader
body io.ReadCloser
length int64
offset struct {
read, seek int64
}
}
// Open opens the named file relative to the Datastore.
func (d Datastore) Open(ctx context.Context, name string) (*DatastoreFile, error) {
return &DatastoreFile{
d: d,
name: name,
length: -1,
ctx: ctx,
}, nil
}
// Read reads up to len(b) bytes from the DatastoreFile.
func (f *DatastoreFile) Read(b []byte) (int, error) {
if f.offset.read != f.offset.seek {
// A Seek() call changed the offset, we need to issue a new GET
_ = f.Close()
f.offset.read = f.offset.seek
} else if f.buf != nil {
// f.buf + f behaves like an io.MultiReader
n, err := f.buf.Read(b)
if err == io.EOF {
f.buf = nil // buffer has been drained
}
if n > 0 {
return n, nil
}
}
body, err := f.get()
if err != nil {
return 0, err
}
n, err := body.Read(b)
f.offset.read += int64(n)
f.offset.seek += int64(n)
return n, err
}
// Close closes the DatastoreFile.
func (f *DatastoreFile) Close() error {
var err error
if f.body != nil {
err = f.body.Close()
f.body = nil
}
f.buf = nil
return err
}
// Seek sets the offset for the next Read on the DatastoreFile.
func (f *DatastoreFile) Seek(offset int64, whence int) (int64, error) {
switch whence {
case io.SeekStart:
case io.SeekCurrent:
offset += f.offset.seek
case io.SeekEnd:
if f.length < 0 {
_, err := f.Stat()
if err != nil {
return 0, err
}
}
offset += f.length
default:
return 0, errors.New("Seek: invalid whence")
}
// allow negative SeekStart for initial Range request
if offset < 0 {
return 0, errors.New("Seek: invalid offset")
}
f.offset.seek = offset
return offset, nil
}
type fileStat struct {
file *DatastoreFile
header http.Header
}
func (s *fileStat) Name() string {
return path.Base(s.file.name)
}
func (s *fileStat) Size() int64 {
return s.file.length
}
func (s *fileStat) Mode() os.FileMode {
return 0
}
func (s *fileStat) ModTime() time.Time {
return time.Now() // no Last-Modified
}
func (s *fileStat) IsDir() bool {
return false
}
func (s *fileStat) Sys() interface{} {
return s.header
}
func statusError(res *http.Response) error {
if res.StatusCode == http.StatusNotFound {
return os.ErrNotExist
}
return errors.New(res.Status)
}
// Stat returns the os.FileInfo interface describing file.
func (f *DatastoreFile) Stat() (os.FileInfo, error) {
// TODO: consider using Datastore.Stat() instead
u, p, err := f.d.downloadTicket(f.ctx, f.name, &soap.Download{Method: "HEAD"})
if err != nil {
return nil, err
}
res, err := f.d.Client().DownloadRequest(f.ctx, u, p)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, statusError(res)
}
f.length = res.ContentLength
return &fileStat{f, res.Header}, nil
}
func (f *DatastoreFile) get() (io.Reader, error) {
if f.body != nil {
return f.body, nil
}
u, p, err := f.d.downloadTicket(f.ctx, f.name, nil)
if err != nil {
return nil, err
}
if f.offset.read != 0 {
p.Headers = map[string]string{
"Range": fmt.Sprintf("bytes=%d-", f.offset.read),
}
}
res, err := f.d.Client().DownloadRequest(f.ctx, u, p)
if err != nil {
return nil, err
}
switch res.StatusCode {
case http.StatusOK:
f.length = res.ContentLength
case http.StatusPartialContent:
var start, end int
cr := res.Header.Get("Content-Range")
_, err = fmt.Sscanf(cr, "bytes %d-%d/%d", &start, &end, &f.length)
if err != nil {
f.length = -1
}
case http.StatusRequestedRangeNotSatisfiable:
// ok: Read() will return io.EOF
default:
return nil, statusError(res)
}
if f.length < 0 {
_ = res.Body.Close()
return nil, errors.New("unable to determine file size")
}
f.body = res.Body
return f.body, nil
}
func lastIndexLines(s []byte, line *int, include func(l int, m string) bool) (int64, bool) {
i := len(s) - 1
done := false
for i > 0 {
o := bytes.LastIndexByte(s[:i], '\n')
if o < 0 {
break
}
msg := string(s[o+1 : i+1])
if !include(*line, msg) {
done = true
break
} else {
i = o
*line++
}
}
return int64(i), done
}
// Tail seeks to the position of the last N lines of the file.
func (f *DatastoreFile) Tail(n int) error {
return f.TailFunc(n, func(line int, _ string) bool { return n > line })
}
// TailFunc will seek backwards in the datastore file until it hits a line that does
// not satisfy the supplied `include` function.
func (f *DatastoreFile) TailFunc(lines int, include func(line int, message string) bool) error {
// Read the file in reverse using bsize chunks
const bsize = int64(1024 * 16)
fsize, err := f.Seek(0, io.SeekEnd)
if err != nil {
return err
}
if lines == 0 {
return nil
}
chunk := int64(-1)
buf := bytes.NewBuffer(make([]byte, 0, bsize))
line := 0
for {
var eof bool
var pos int64
nread := bsize
offset := chunk * bsize
remain := fsize + offset
if remain < 0 {
if pos, err = f.Seek(0, io.SeekStart); err != nil {
return err
}
nread = bsize + remain
eof = true
} else if pos, err = f.Seek(offset, io.SeekEnd); err != nil {
return err
}
if _, err = io.CopyN(buf, f, nread); err != nil {
if err != io.EOF {
return err
}
}
b := buf.Bytes()
idx, done := lastIndexLines(b, &line, include)
if done {
if chunk == -1 {
// We found all N lines in the last chunk of the file.
// The seek offset is also now at the current end of file.
// Save this buffer to avoid another GET request when Read() is called.
buf.Next(int(idx + 1))
f.buf = buf
return nil
}
if _, err = f.Seek(pos+idx+1, io.SeekStart); err != nil {
return err
}
break
}
if eof {
if remain < 0 {
// We found < N lines in the entire file, so seek to the start.
_, _ = f.Seek(0, io.SeekStart)
}
break
}
chunk--
buf.Reset()
}
return nil
}
type followDatastoreFile struct {
r *DatastoreFile
c chan struct{}
i time.Duration
o sync.Once
}
// Read reads up to len(b) bytes from the DatastoreFile being followed.
// This method will block until data is read, an error other than io.EOF is returned or Close() is called.
func (f *followDatastoreFile) Read(p []byte) (int, error) {
offset := f.r.offset.seek
stop := false
for {
n, err := f.r.Read(p)
if err != nil && err == io.EOF {
_ = f.r.Close() // GET request body has been drained.
if stop {
return n, err
}
err = nil
}
if n > 0 {
return n, err
}
select {
case <-f.c:
// Wake up and stop polling once the body has been drained
stop = true
case <-time.After(f.i):
}
info, serr := f.r.Stat()
if serr != nil {
// Return EOF rather than 404 if the file goes away
if serr == os.ErrNotExist {
_ = f.r.Close()
return 0, io.EOF
}
return 0, serr
}
if info.Size() < offset {
// assume file has be truncated
offset, err = f.r.Seek(0, io.SeekStart)
if err != nil {
return 0, err
}
}
}
}
// Close will stop Follow polling and close the underlying DatastoreFile.
func (f *followDatastoreFile) Close() error {
f.o.Do(func() { close(f.c) })
return nil
}
// Follow returns an io.ReadCloser to stream the file contents as data is appended.
func (f *DatastoreFile) Follow(interval time.Duration) io.ReadCloser {
return &followDatastoreFile{
r: f,
c: make(chan struct{}),
i: interval,
}
}

View File

@@ -1,228 +0,0 @@
/*
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.
*/
package object
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"log"
"path"
"strings"
"github.com/vmware/govmomi/vim25/progress"
"github.com/vmware/govmomi/vim25/soap"
)
// DatastoreFileManager combines FileManager and VirtualDiskManager to manage files on a Datastore
type DatastoreFileManager struct {
Datacenter *Datacenter
Datastore *Datastore
FileManager *FileManager
VirtualDiskManager *VirtualDiskManager
Force bool
DatacenterTarget *Datacenter
}
// NewFileManager creates a new instance of DatastoreFileManager
func (d Datastore) NewFileManager(dc *Datacenter, force bool) *DatastoreFileManager {
c := d.Client()
m := &DatastoreFileManager{
Datacenter: dc,
Datastore: &d,
FileManager: NewFileManager(c),
VirtualDiskManager: NewVirtualDiskManager(c),
Force: force,
DatacenterTarget: dc,
}
return m
}
func (m *DatastoreFileManager) WithProgress(ctx context.Context, s progress.Sinker) context.Context {
return context.WithValue(ctx, m, s)
}
func (m *DatastoreFileManager) wait(ctx context.Context, task *Task) error {
var logger progress.Sinker
if s, ok := ctx.Value(m).(progress.Sinker); ok {
logger = s
}
_, err := task.WaitForResult(ctx, logger)
return err
}
// Delete dispatches to the appropriate Delete method based on file name extension
func (m *DatastoreFileManager) Delete(ctx context.Context, name string) error {
switch path.Ext(name) {
case ".vmdk":
return m.DeleteVirtualDisk(ctx, name)
default:
return m.DeleteFile(ctx, name)
}
}
// DeleteFile calls FileManager.DeleteDatastoreFile
func (m *DatastoreFileManager) DeleteFile(ctx context.Context, name string) error {
p := m.Path(name)
task, err := m.FileManager.DeleteDatastoreFile(ctx, p.String(), m.Datacenter)
if err != nil {
return err
}
return m.wait(ctx, task)
}
// DeleteVirtualDisk calls VirtualDiskManager.DeleteVirtualDisk
// Regardless of the Datastore type, DeleteVirtualDisk will fail if 'ddb.deletable=false',
// so if Force=true this method attempts to set 'ddb.deletable=true' before starting the delete task.
func (m *DatastoreFileManager) DeleteVirtualDisk(ctx context.Context, name string) error {
p := m.Path(name)
var merr error
if m.Force {
merr = m.markDiskAsDeletable(ctx, p)
}
task, err := m.VirtualDiskManager.DeleteVirtualDisk(ctx, p.String(), m.Datacenter)
if err != nil {
log.Printf("markDiskAsDeletable(%s): %s", p, merr)
return err
}
return m.wait(ctx, task)
}
// CopyFile calls FileManager.CopyDatastoreFile
func (m *DatastoreFileManager) CopyFile(ctx context.Context, src string, dst string) error {
srcp := m.Path(src)
dstp := m.Path(dst)
task, err := m.FileManager.CopyDatastoreFile(ctx, srcp.String(), m.Datacenter, dstp.String(), m.DatacenterTarget, m.Force)
if err != nil {
return err
}
return m.wait(ctx, task)
}
// Copy dispatches to the appropriate FileManager or VirtualDiskManager Copy method based on file name extension
func (m *DatastoreFileManager) Copy(ctx context.Context, src string, dst string) error {
srcp := m.Path(src)
dstp := m.Path(dst)
f := m.FileManager.CopyDatastoreFile
if srcp.IsVMDK() {
// types.VirtualDiskSpec=nil as it is not implemented by vCenter
f = func(ctx context.Context, src string, srcDC *Datacenter, dst string, dstDC *Datacenter, force bool) (*Task, error) {
return m.VirtualDiskManager.CopyVirtualDisk(ctx, src, srcDC, dst, dstDC, nil, force)
}
}
task, err := f(ctx, srcp.String(), m.Datacenter, dstp.String(), m.DatacenterTarget, m.Force)
if err != nil {
return err
}
return m.wait(ctx, task)
}
// MoveFile calls FileManager.MoveDatastoreFile
func (m *DatastoreFileManager) MoveFile(ctx context.Context, src string, dst string) error {
srcp := m.Path(src)
dstp := m.Path(dst)
task, err := m.FileManager.MoveDatastoreFile(ctx, srcp.String(), m.Datacenter, dstp.String(), m.DatacenterTarget, m.Force)
if err != nil {
return err
}
return m.wait(ctx, task)
}
// Move dispatches to the appropriate FileManager or VirtualDiskManager Move method based on file name extension
func (m *DatastoreFileManager) Move(ctx context.Context, src string, dst string) error {
srcp := m.Path(src)
dstp := m.Path(dst)
f := m.FileManager.MoveDatastoreFile
if srcp.IsVMDK() {
f = m.VirtualDiskManager.MoveVirtualDisk
}
task, err := f(ctx, srcp.String(), m.Datacenter, dstp.String(), m.DatacenterTarget, m.Force)
if err != nil {
return err
}
return m.wait(ctx, task)
}
// Path converts path name to a DatastorePath
func (m *DatastoreFileManager) Path(name string) *DatastorePath {
var p DatastorePath
if !p.FromString(name) {
p.Path = name
p.Datastore = m.Datastore.Name()
}
return &p
}
func (m *DatastoreFileManager) markDiskAsDeletable(ctx context.Context, path *DatastorePath) error {
r, _, err := m.Datastore.Download(ctx, path.Path, &soap.DefaultDownload)
if err != nil {
return err
}
defer r.Close()
hasFlag := false
buf := new(bytes.Buffer)
s := bufio.NewScanner(&io.LimitedReader{R: r, N: 2048}) // should be only a few hundred bytes, limit to be sure
for s.Scan() {
line := s.Text()
if strings.HasPrefix(line, "ddb.deletable") {
hasFlag = true
continue
}
fmt.Fprintln(buf, line)
}
if err := s.Err(); err != nil {
return err // any error other than EOF
}
if !hasFlag {
return nil // already deletable, so leave as-is
}
// rewrite the .vmdk with ddb.deletable flag removed (the default is true)
return m.Datastore.Upload(ctx, buf, path.Path, &soap.DefaultUpload)
}

View File

@@ -1,71 +0,0 @@
/*
Copyright (c) 2016 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.
*/
package object
import (
"fmt"
"path"
"strings"
)
// DatastorePath contains the components of a datastore path.
type DatastorePath struct {
Datastore string
Path string
}
// FromString parses a datastore path.
// Returns true if the path could be parsed, false otherwise.
func (p *DatastorePath) FromString(s string) bool {
if s == "" {
return false
}
s = strings.TrimSpace(s)
if !strings.HasPrefix(s, "[") {
return false
}
s = s[1:]
ix := strings.Index(s, "]")
if ix < 0 {
return false
}
p.Datastore = s[:ix]
p.Path = strings.TrimSpace(s[ix+1:])
return true
}
// String formats a datastore path.
func (p *DatastorePath) String() string {
s := fmt.Sprintf("[%s]", p.Datastore)
if p.Path == "" {
return s
}
return strings.Join([]string{s, p.Path}, " ")
}
// IsVMDK returns true if Path has a ".vmdk" extension
func (p *DatastorePath) IsVMDK() bool {
return path.Ext(p.Path) == ".vmdk"
}

View File

@@ -1,76 +0,0 @@
/*
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.
*/
package object
import (
"context"
"fmt"
"io"
"math"
)
// DiagnosticLog wraps DiagnosticManager.BrowseLog
type DiagnosticLog struct {
m DiagnosticManager
Key string
Host *HostSystem
Start int32
}
// Seek to log position starting at the last nlines of the log
func (l *DiagnosticLog) Seek(ctx context.Context, nlines int32) error {
h, err := l.m.BrowseLog(ctx, l.Host, l.Key, math.MaxInt32, 0)
if err != nil {
return err
}
l.Start = h.LineEnd - nlines
return nil
}
// Copy log starting from l.Start to the given io.Writer
// Returns on error or when end of log is reached.
func (l *DiagnosticLog) Copy(ctx context.Context, w io.Writer) (int, error) {
const max = 500 // VC max == 500, ESX max == 1000
written := 0
for {
h, err := l.m.BrowseLog(ctx, l.Host, l.Key, l.Start, max)
if err != nil {
return 0, err
}
for _, line := range h.LineText {
n, err := fmt.Fprintln(w, line)
written += n
if err != nil {
return written, err
}
}
l.Start += int32(len(h.LineText))
if l.Start >= h.LineEnd {
break
}
}
return written, nil
}

View File

@@ -1,102 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type DiagnosticManager struct {
Common
}
func NewDiagnosticManager(c *vim25.Client) *DiagnosticManager {
m := DiagnosticManager{
Common: NewCommon(c, *c.ServiceContent.DiagnosticManager),
}
return &m
}
func (m DiagnosticManager) Log(ctx context.Context, host *HostSystem, key string) *DiagnosticLog {
return &DiagnosticLog{
m: m,
Key: key,
Host: host,
}
}
func (m DiagnosticManager) BrowseLog(ctx context.Context, host *HostSystem, key string, start, lines int32) (*types.DiagnosticManagerLogHeader, error) {
req := types.BrowseDiagnosticLog{
This: m.Reference(),
Key: key,
Start: start,
Lines: lines,
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.BrowseDiagnosticLog(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (m DiagnosticManager) GenerateLogBundles(ctx context.Context, includeDefault bool, host []*HostSystem) (*Task, error) {
req := types.GenerateLogBundles_Task{
This: m.Reference(),
IncludeDefault: includeDefault,
}
for _, h := range host {
req.Host = append(req.Host, h.Reference())
}
res, err := methods.GenerateLogBundles_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
func (m DiagnosticManager) QueryDescriptions(ctx context.Context, host *HostSystem) ([]types.DiagnosticManagerLogDescriptor, error) {
req := types.QueryDescriptions{
This: m.Reference(),
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.QueryDescriptions(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}

View File

@@ -1,90 +0,0 @@
/*
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.
*/
package object
import (
"context"
"fmt"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type DistributedVirtualPortgroup struct {
Common
}
func NewDistributedVirtualPortgroup(c *vim25.Client, ref types.ManagedObjectReference) *DistributedVirtualPortgroup {
return &DistributedVirtualPortgroup{
Common: NewCommon(c, ref),
}
}
func (p DistributedVirtualPortgroup) GetInventoryPath() string {
return p.InventoryPath
}
// EthernetCardBackingInfo returns the VirtualDeviceBackingInfo for this DistributedVirtualPortgroup
func (p DistributedVirtualPortgroup) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error) {
var dvp mo.DistributedVirtualPortgroup
var dvs mo.DistributedVirtualSwitch
prop := "config.distributedVirtualSwitch"
if err := p.Properties(ctx, p.Reference(), []string{"key", prop}, &dvp); err != nil {
return nil, err
}
// From the docs at https://code.vmware.com/apis/196/vsphere/doc/vim.dvs.DistributedVirtualPortgroup.ConfigInfo.html:
// "This property should always be set unless the user's setting does not have System.Read privilege on the object referred to by this property."
// Note that "the object" refers to the Switch, not the PortGroup.
if dvp.Config.DistributedVirtualSwitch == nil {
name := p.InventoryPath
if name == "" {
name = p.Reference().String()
}
return nil, fmt.Errorf("failed to create EthernetCardBackingInfo for %s: System.Read privilege required for %s", name, prop)
}
if err := p.Properties(ctx, *dvp.Config.DistributedVirtualSwitch, []string{"uuid"}, &dvs); err != nil {
return nil, err
}
backing := &types.VirtualEthernetCardDistributedVirtualPortBackingInfo{
Port: types.DistributedVirtualSwitchPortConnection{
PortgroupKey: dvp.Key,
SwitchUuid: dvs.Uuid,
},
}
return backing, nil
}
func (p DistributedVirtualPortgroup) Reconfigure(ctx context.Context, spec types.DVPortgroupConfigSpec) (*Task, error) {
req := types.ReconfigureDVPortgroup_Task{
This: p.Reference(),
Spec: spec,
}
res, err := methods.ReconfigureDVPortgroup_Task(ctx, p.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(p.Client(), res.Returnval), nil
}

View File

@@ -1,118 +0,0 @@
/*
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.
*/
package object
import (
"context"
"fmt"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type DistributedVirtualSwitch struct {
Common
}
func NewDistributedVirtualSwitch(c *vim25.Client, ref types.ManagedObjectReference) *DistributedVirtualSwitch {
return &DistributedVirtualSwitch{
Common: NewCommon(c, ref),
}
}
func (s DistributedVirtualSwitch) GetInventoryPath() string {
return s.InventoryPath
}
func (s DistributedVirtualSwitch) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error) {
ref := s.Reference()
name := s.InventoryPath
if name == "" {
name = ref.String()
}
return nil, fmt.Errorf("type %s (%s) cannot be used for EthernetCardBackingInfo", ref.Type, name)
}
func (s DistributedVirtualSwitch) Reconfigure(ctx context.Context, spec types.BaseDVSConfigSpec) (*Task, error) {
req := types.ReconfigureDvs_Task{
This: s.Reference(),
Spec: spec,
}
res, err := methods.ReconfigureDvs_Task(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(s.Client(), res.Returnval), nil
}
func (s DistributedVirtualSwitch) AddPortgroup(ctx context.Context, spec []types.DVPortgroupConfigSpec) (*Task, error) {
req := types.AddDVPortgroup_Task{
This: s.Reference(),
Spec: spec,
}
res, err := methods.AddDVPortgroup_Task(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(s.Client(), res.Returnval), nil
}
func (s DistributedVirtualSwitch) FetchDVPorts(ctx context.Context, criteria *types.DistributedVirtualSwitchPortCriteria) ([]types.DistributedVirtualPort, error) {
req := &types.FetchDVPorts{
This: s.Reference(),
Criteria: criteria,
}
res, err := methods.FetchDVPorts(ctx, s.Client(), req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (s DistributedVirtualSwitch) ReconfigureDVPort(ctx context.Context, spec []types.DVPortConfigSpec) (*Task, error) {
req := types.ReconfigureDVPort_Task{
This: s.Reference(),
Port: spec,
}
res, err := methods.ReconfigureDVPort_Task(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(s.Client(), res.Returnval), nil
}
func (s DistributedVirtualSwitch) ReconfigureLACP(ctx context.Context, spec []types.VMwareDvsLacpGroupSpec) (*Task, error) {
req := types.UpdateDVSLacpGroupConfig_Task{
This: s.Reference(),
LacpGroupSpec: spec,
}
res, err := methods.UpdateDVSLacpGroupConfig_Task(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(s.Client(), res.Returnval), nil
}

View File

@@ -1,113 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type ExtensionManager struct {
Common
}
// GetExtensionManager wraps NewExtensionManager, returning ErrNotSupported
// when the client is not connected to a vCenter instance.
func GetExtensionManager(c *vim25.Client) (*ExtensionManager, error) {
if c.ServiceContent.ExtensionManager == nil {
return nil, ErrNotSupported
}
return NewExtensionManager(c), nil
}
func NewExtensionManager(c *vim25.Client) *ExtensionManager {
o := ExtensionManager{
Common: NewCommon(c, *c.ServiceContent.ExtensionManager),
}
return &o
}
func (m ExtensionManager) List(ctx context.Context) ([]types.Extension, error) {
var em mo.ExtensionManager
err := m.Properties(ctx, m.Reference(), []string{"extensionList"}, &em)
if err != nil {
return nil, err
}
return em.ExtensionList, nil
}
func (m ExtensionManager) Find(ctx context.Context, key string) (*types.Extension, error) {
req := types.FindExtension{
This: m.Reference(),
ExtensionKey: key,
}
res, err := methods.FindExtension(ctx, m.c, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m ExtensionManager) Register(ctx context.Context, extension types.Extension) error {
req := types.RegisterExtension{
This: m.Reference(),
Extension: extension,
}
_, err := methods.RegisterExtension(ctx, m.c, &req)
return err
}
func (m ExtensionManager) SetCertificate(ctx context.Context, key string, certificatePem string) error {
req := types.SetExtensionCertificate{
This: m.Reference(),
ExtensionKey: key,
CertificatePem: certificatePem,
}
_, err := methods.SetExtensionCertificate(ctx, m.c, &req)
return err
}
func (m ExtensionManager) Unregister(ctx context.Context, key string) error {
req := types.UnregisterExtension{
This: m.Reference(),
ExtensionKey: key,
}
_, err := methods.UnregisterExtension(ctx, m.c, &req)
return err
}
func (m ExtensionManager) Update(ctx context.Context, extension types.Extension) error {
req := types.UpdateExtension{
This: m.Reference(),
Extension: extension,
}
_, err := methods.UpdateExtension(ctx, m.c, &req)
return err
}

View File

@@ -1,126 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type FileManager struct {
Common
}
func NewFileManager(c *vim25.Client) *FileManager {
f := FileManager{
Common: NewCommon(c, *c.ServiceContent.FileManager),
}
return &f
}
func (f FileManager) CopyDatastoreFile(ctx context.Context, sourceName string, sourceDatacenter *Datacenter, destinationName string, destinationDatacenter *Datacenter, force bool) (*Task, error) {
req := types.CopyDatastoreFile_Task{
This: f.Reference(),
SourceName: sourceName,
DestinationName: destinationName,
Force: types.NewBool(force),
}
if sourceDatacenter != nil {
ref := sourceDatacenter.Reference()
req.SourceDatacenter = &ref
}
if destinationDatacenter != nil {
ref := destinationDatacenter.Reference()
req.DestinationDatacenter = &ref
}
res, err := methods.CopyDatastoreFile_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
// DeleteDatastoreFile deletes the specified file or folder from the datastore.
func (f FileManager) DeleteDatastoreFile(ctx context.Context, name string, dc *Datacenter) (*Task, error) {
req := types.DeleteDatastoreFile_Task{
This: f.Reference(),
Name: name,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.DeleteDatastoreFile_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
// MakeDirectory creates a folder using the specified name.
func (f FileManager) MakeDirectory(ctx context.Context, name string, dc *Datacenter, createParentDirectories bool) error {
req := types.MakeDirectory{
This: f.Reference(),
Name: name,
CreateParentDirectories: types.NewBool(createParentDirectories),
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
_, err := methods.MakeDirectory(ctx, f.c, &req)
return err
}
func (f FileManager) MoveDatastoreFile(ctx context.Context, sourceName string, sourceDatacenter *Datacenter, destinationName string, destinationDatacenter *Datacenter, force bool) (*Task, error) {
req := types.MoveDatastoreFile_Task{
This: f.Reference(),
SourceName: sourceName,
DestinationName: destinationName,
Force: types.NewBool(force),
}
if sourceDatacenter != nil {
ref := sourceDatacenter.Reference()
req.SourceDatacenter = &ref
}
if destinationDatacenter != nil {
ref := destinationDatacenter.Reference()
req.DestinationDatacenter = &ref
}
res, err := methods.MoveDatastoreFile_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}

View File

@@ -1,241 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type Folder struct {
Common
}
func NewFolder(c *vim25.Client, ref types.ManagedObjectReference) *Folder {
return &Folder{
Common: NewCommon(c, ref),
}
}
func NewRootFolder(c *vim25.Client) *Folder {
f := NewFolder(c, c.ServiceContent.RootFolder)
f.InventoryPath = "/"
return f
}
func (f Folder) Children(ctx context.Context) ([]Reference, error) {
var mf mo.Folder
err := f.Properties(ctx, f.Reference(), []string{"childEntity"}, &mf)
if err != nil {
return nil, err
}
var rs []Reference
for _, e := range mf.ChildEntity {
if r := NewReference(f.c, e); r != nil {
rs = append(rs, r)
}
}
return rs, nil
}
func (f Folder) CreateDatacenter(ctx context.Context, datacenter string) (*Datacenter, error) {
req := types.CreateDatacenter{
This: f.Reference(),
Name: datacenter,
}
res, err := methods.CreateDatacenter(ctx, f.c, &req)
if err != nil {
return nil, err
}
// Response will be nil if this is an ESX host that does not belong to a vCenter
if res == nil {
return nil, nil
}
return NewDatacenter(f.c, res.Returnval), nil
}
func (f Folder) CreateCluster(ctx context.Context, cluster string, spec types.ClusterConfigSpecEx) (*ClusterComputeResource, error) {
req := types.CreateClusterEx{
This: f.Reference(),
Name: cluster,
Spec: spec,
}
res, err := methods.CreateClusterEx(ctx, f.c, &req)
if err != nil {
return nil, err
}
// Response will be nil if this is an ESX host that does not belong to a vCenter
if res == nil {
return nil, nil
}
return NewClusterComputeResource(f.c, res.Returnval), nil
}
func (f Folder) CreateFolder(ctx context.Context, name string) (*Folder, error) {
req := types.CreateFolder{
This: f.Reference(),
Name: name,
}
res, err := methods.CreateFolder(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewFolder(f.c, res.Returnval), err
}
func (f Folder) CreateStoragePod(ctx context.Context, name string) (*StoragePod, error) {
req := types.CreateStoragePod{
This: f.Reference(),
Name: name,
}
res, err := methods.CreateStoragePod(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewStoragePod(f.c, res.Returnval), err
}
func (f Folder) AddStandaloneHost(ctx context.Context, spec types.HostConnectSpec, addConnected bool, license *string, compResSpec *types.BaseComputeResourceConfigSpec) (*Task, error) {
req := types.AddStandaloneHost_Task{
This: f.Reference(),
Spec: spec,
AddConnected: addConnected,
}
if license != nil {
req.License = *license
}
if compResSpec != nil {
req.CompResSpec = *compResSpec
}
res, err := methods.AddStandaloneHost_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
func (f Folder) CreateVM(ctx context.Context, config types.VirtualMachineConfigSpec, pool *ResourcePool, host *HostSystem) (*Task, error) {
req := types.CreateVM_Task{
This: f.Reference(),
Config: config,
Pool: pool.Reference(),
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.CreateVM_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
func (f Folder) RegisterVM(ctx context.Context, path string, name string, asTemplate bool, pool *ResourcePool, host *HostSystem) (*Task, error) {
req := types.RegisterVM_Task{
This: f.Reference(),
Path: path,
AsTemplate: asTemplate,
}
if name != "" {
req.Name = name
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
if pool != nil {
ref := pool.Reference()
req.Pool = &ref
}
res, err := methods.RegisterVM_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
func (f Folder) CreateDVS(ctx context.Context, spec types.DVSCreateSpec) (*Task, error) {
req := types.CreateDVS_Task{
This: f.Reference(),
Spec: spec,
}
res, err := methods.CreateDVS_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
func (f Folder) MoveInto(ctx context.Context, list []types.ManagedObjectReference) (*Task, error) {
req := types.MoveIntoFolder_Task{
This: f.Reference(),
List: list,
}
res, err := methods.MoveIntoFolder_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
func (f Folder) PlaceVmsXCluster(ctx context.Context, spec types.PlaceVmsXClusterSpec) (*types.PlaceVmsXClusterResult, error) {
req := types.PlaceVmsXCluster{
This: f.Reference(),
PlacementSpec: spec,
}
res, err := methods.PlaceVmsXCluster(ctx, f.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}

View File

@@ -1,65 +0,0 @@
/*
Copyright (c) 2016 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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type HostAccountManager struct {
Common
}
func NewHostAccountManager(c *vim25.Client, ref types.ManagedObjectReference) *HostAccountManager {
return &HostAccountManager{
Common: NewCommon(c, ref),
}
}
func (m HostAccountManager) Create(ctx context.Context, user *types.HostAccountSpec) error {
req := types.CreateUser{
This: m.Reference(),
User: user,
}
_, err := methods.CreateUser(ctx, m.Client(), &req)
return err
}
func (m HostAccountManager) Update(ctx context.Context, user *types.HostAccountSpec) error {
req := types.UpdateUser{
This: m.Reference(),
User: user,
}
_, err := methods.UpdateUser(ctx, m.Client(), &req)
return err
}
func (m HostAccountManager) Remove(ctx context.Context, userName string) error {
req := types.RemoveUser{
This: m.Reference(),
UserName: userName,
}
_, err := methods.RemoveUser(ctx, m.Client(), &req)
return err
}

View File

@@ -1,247 +0,0 @@
/*
Copyright (c) 2016 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.
*/
package object
import (
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"fmt"
"io"
"net/url"
"strings"
"text/tabwriter"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
// HostCertificateInfo provides helpers for types.HostCertificateManagerCertificateInfo
type HostCertificateInfo struct {
types.HostCertificateManagerCertificateInfo
ThumbprintSHA1 string
ThumbprintSHA256 string
Err error
Certificate *x509.Certificate `json:"-"`
subjectName *pkix.Name
issuerName *pkix.Name
}
// FromCertificate converts x509.Certificate to HostCertificateInfo
func (info *HostCertificateInfo) FromCertificate(cert *x509.Certificate) *HostCertificateInfo {
info.Certificate = cert
info.subjectName = &cert.Subject
info.issuerName = &cert.Issuer
info.Issuer = info.fromName(info.issuerName)
info.NotBefore = &cert.NotBefore
info.NotAfter = &cert.NotAfter
info.Subject = info.fromName(info.subjectName)
info.ThumbprintSHA1 = soap.ThumbprintSHA1(cert)
// SHA-256 for info purposes only, API fields all use SHA-1
sum := sha256.Sum256(cert.Raw)
hex := make([]string, len(sum))
for i, b := range sum {
hex[i] = fmt.Sprintf("%02X", b)
}
info.ThumbprintSHA256 = strings.Join(hex, ":")
if info.Status == "" {
info.Status = string(types.HostCertificateManagerCertificateInfoCertificateStatusUnknown)
}
return info
}
// FromURL connects to the given URL.Host via tls.Dial with the given tls.Config and populates the HostCertificateInfo
// via tls.ConnectionState. If the certificate was verified with the given tls.Config, the Err field will be nil.
// Otherwise, Err will be set to the x509.UnknownAuthorityError or x509.HostnameError.
// If tls.Dial returns an error of any other type, that error is returned.
func (info *HostCertificateInfo) FromURL(u *url.URL, config *tls.Config) error {
addr := u.Host
if !(strings.LastIndex(addr, ":") > strings.LastIndex(addr, "]")) {
addr += ":443"
}
conn, err := tls.Dial("tcp", addr, config)
if err != nil {
if !soap.IsCertificateUntrusted(err) {
return err
}
info.Err = err
conn, err = tls.Dial("tcp", addr, &tls.Config{InsecureSkipVerify: true})
if err != nil {
return err
}
} else {
info.Status = string(types.HostCertificateManagerCertificateInfoCertificateStatusGood)
}
state := conn.ConnectionState()
_ = conn.Close()
info.FromCertificate(state.PeerCertificates[0])
return nil
}
var emailAddressOID = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1}
func (info *HostCertificateInfo) fromName(name *pkix.Name) string {
var attrs []string
oids := map[string]string{
emailAddressOID.String(): "emailAddress",
}
for _, attr := range name.Names {
if key, ok := oids[attr.Type.String()]; ok {
attrs = append(attrs, fmt.Sprintf("%s=%s", key, attr.Value))
}
}
attrs = append(attrs, fmt.Sprintf("CN=%s", name.CommonName))
add := func(key string, vals []string) {
for _, val := range vals {
attrs = append(attrs, fmt.Sprintf("%s=%s", key, val))
}
}
elts := []struct {
key string
val []string
}{
{"OU", name.OrganizationalUnit},
{"O", name.Organization},
{"L", name.Locality},
{"ST", name.Province},
{"C", name.Country},
}
for _, elt := range elts {
add(elt.key, elt.val)
}
return strings.Join(attrs, ",")
}
func (info *HostCertificateInfo) toName(s string) *pkix.Name {
var name pkix.Name
for _, pair := range strings.Split(s, ",") {
attr := strings.SplitN(pair, "=", 2)
if len(attr) != 2 {
continue
}
v := attr[1]
switch strings.ToLower(attr[0]) {
case "cn":
name.CommonName = v
case "ou":
name.OrganizationalUnit = append(name.OrganizationalUnit, v)
case "o":
name.Organization = append(name.Organization, v)
case "l":
name.Locality = append(name.Locality, v)
case "st":
name.Province = append(name.Province, v)
case "c":
name.Country = append(name.Country, v)
case "emailaddress":
name.Names = append(name.Names, pkix.AttributeTypeAndValue{Type: emailAddressOID, Value: v})
}
}
return &name
}
// SubjectName parses Subject into a pkix.Name
func (info *HostCertificateInfo) SubjectName() *pkix.Name {
if info.subjectName != nil {
return info.subjectName
}
return info.toName(info.Subject)
}
// IssuerName parses Issuer into a pkix.Name
func (info *HostCertificateInfo) IssuerName() *pkix.Name {
if info.issuerName != nil {
return info.issuerName
}
return info.toName(info.Issuer)
}
// Write outputs info similar to the Chrome Certificate Viewer.
func (info *HostCertificateInfo) Write(w io.Writer) error {
tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0)
s := func(val string) string {
if val != "" {
return val
}
return "<Not Part Of Certificate>"
}
ss := func(val []string) string {
return s(strings.Join(val, ","))
}
name := func(n *pkix.Name) {
fmt.Fprintf(tw, " Common Name (CN):\t%s\n", s(n.CommonName))
fmt.Fprintf(tw, " Organization (O):\t%s\n", ss(n.Organization))
fmt.Fprintf(tw, " Organizational Unit (OU):\t%s\n", ss(n.OrganizationalUnit))
}
status := info.Status
if info.Err != nil {
status = fmt.Sprintf("ERROR %s", info.Err)
}
fmt.Fprintf(tw, "Certificate Status:\t%s\n", status)
fmt.Fprintln(tw, "Issued To:\t")
name(info.SubjectName())
fmt.Fprintln(tw, "Issued By:\t")
name(info.IssuerName())
fmt.Fprintln(tw, "Validity Period:\t")
fmt.Fprintf(tw, " Issued On:\t%s\n", info.NotBefore)
fmt.Fprintf(tw, " Expires On:\t%s\n", info.NotAfter)
if info.ThumbprintSHA1 != "" {
fmt.Fprintln(tw, "Thumbprints:\t")
if info.ThumbprintSHA256 != "" {
fmt.Fprintf(tw, " SHA-256 Thumbprint:\t%s\n", info.ThumbprintSHA256)
}
fmt.Fprintf(tw, " SHA-1 Thumbprint:\t%s\n", info.ThumbprintSHA1)
}
return tw.Flush()
}

View File

@@ -1,162 +0,0 @@
/*
Copyright (c) 2016 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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
// HostCertificateManager provides helper methods around the HostSystem.ConfigManager.CertificateManager
type HostCertificateManager struct {
Common
Host *HostSystem
}
// NewHostCertificateManager creates a new HostCertificateManager helper
func NewHostCertificateManager(c *vim25.Client, ref types.ManagedObjectReference, host types.ManagedObjectReference) *HostCertificateManager {
return &HostCertificateManager{
Common: NewCommon(c, ref),
Host: NewHostSystem(c, host),
}
}
// CertificateInfo wraps the host CertificateManager certificateInfo property with the HostCertificateInfo helper.
// The ThumbprintSHA1 field is set to HostSystem.Summary.Config.SslThumbprint if the host system is managed by a vCenter.
func (m HostCertificateManager) CertificateInfo(ctx context.Context) (*HostCertificateInfo, error) {
var hs mo.HostSystem
var cm mo.HostCertificateManager
pc := property.DefaultCollector(m.Client())
err := pc.RetrieveOne(ctx, m.Reference(), []string{"certificateInfo"}, &cm)
if err != nil {
return nil, err
}
_ = pc.RetrieveOne(ctx, m.Host.Reference(), []string{"summary.config.sslThumbprint"}, &hs)
return &HostCertificateInfo{
HostCertificateManagerCertificateInfo: cm.CertificateInfo,
ThumbprintSHA1: hs.Summary.Config.SslThumbprint,
}, nil
}
// GenerateCertificateSigningRequest requests the host system to generate a certificate-signing request (CSR) for itself.
// The CSR is then typically provided to a Certificate Authority to sign and issue the SSL certificate for the host system.
// Use InstallServerCertificate to import this certificate.
func (m HostCertificateManager) GenerateCertificateSigningRequest(ctx context.Context, useIPAddressAsCommonName bool) (string, error) {
req := types.GenerateCertificateSigningRequest{
This: m.Reference(),
UseIpAddressAsCommonName: useIPAddressAsCommonName,
}
res, err := methods.GenerateCertificateSigningRequest(ctx, m.Client(), &req)
if err != nil {
return "", err
}
return res.Returnval, nil
}
// GenerateCertificateSigningRequestByDn requests the host system to generate a certificate-signing request (CSR) for itself.
// Alternative version similar to GenerateCertificateSigningRequest but takes a Distinguished Name (DN) as a parameter.
func (m HostCertificateManager) GenerateCertificateSigningRequestByDn(ctx context.Context, distinguishedName string) (string, error) {
req := types.GenerateCertificateSigningRequestByDn{
This: m.Reference(),
DistinguishedName: distinguishedName,
}
res, err := methods.GenerateCertificateSigningRequestByDn(ctx, m.Client(), &req)
if err != nil {
return "", err
}
return res.Returnval, nil
}
// InstallServerCertificate imports the given SSL certificate to the host system.
func (m HostCertificateManager) InstallServerCertificate(ctx context.Context, cert string) error {
req := types.InstallServerCertificate{
This: m.Reference(),
Cert: cert,
}
_, err := methods.InstallServerCertificate(ctx, m.Client(), &req)
if err != nil {
return err
}
// NotifyAffectedService is internal, not exposing as we don't have a use case other than with InstallServerCertificate
// Without this call, hostd needs to be restarted to use the updated certificate
// Note: using Refresh as it has the same struct/signature, we just need to use different xml name tags
body := struct {
Req *types.Refresh `xml:"urn:vim25 NotifyAffectedServices,omitempty"`
Res *types.RefreshResponse `xml:"urn:vim25 NotifyAffectedServicesResponse,omitempty"`
methods.RefreshBody
}{
Req: &types.Refresh{This: m.Reference()},
}
return m.Client().RoundTrip(ctx, &body, &body)
}
// ListCACertificateRevocationLists returns the SSL CRLs of Certificate Authorities that are trusted by the host system.
func (m HostCertificateManager) ListCACertificateRevocationLists(ctx context.Context) ([]string, error) {
req := types.ListCACertificateRevocationLists{
This: m.Reference(),
}
res, err := methods.ListCACertificateRevocationLists(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
// ListCACertificates returns the SSL certificates of Certificate Authorities that are trusted by the host system.
func (m HostCertificateManager) ListCACertificates(ctx context.Context) ([]string, error) {
req := types.ListCACertificates{
This: m.Reference(),
}
res, err := methods.ListCACertificates(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
// ReplaceCACertificatesAndCRLs replaces the trusted CA certificates and CRL used by the host system.
// These determine whether the server can verify the identity of an external entity.
func (m HostCertificateManager) ReplaceCACertificatesAndCRLs(ctx context.Context, caCert []string, caCrl []string) error {
req := types.ReplaceCACertificatesAndCRLs{
This: m.Reference(),
CaCert: caCert,
CaCrl: caCrl,
}
_, err := methods.ReplaceCACertificatesAndCRLs(ctx, m.Client(), &req)
return err
}

View File

@@ -1,171 +0,0 @@
/*
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.
*/
package object
import (
"context"
"fmt"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/types"
)
type HostConfigManager struct {
Common
}
func NewHostConfigManager(c *vim25.Client, ref types.ManagedObjectReference) *HostConfigManager {
return &HostConfigManager{
Common: NewCommon(c, ref),
}
}
// reference returns the ManagedObjectReference for the given HostConfigManager property name.
// An error is returned if the field is nil, of type ErrNotSupported if versioned is true.
func (m HostConfigManager) reference(ctx context.Context, name string, versioned ...bool) (types.ManagedObjectReference, error) {
prop := "configManager." + name
var content []types.ObjectContent
err := m.Properties(ctx, m.Reference(), []string{prop}, &content)
if err != nil {
return types.ManagedObjectReference{}, err
}
for _, c := range content {
for _, p := range c.PropSet {
if p.Name != prop {
continue
}
if ref, ok := p.Val.(types.ManagedObjectReference); ok {
return ref, nil
}
}
}
err = fmt.Errorf("%s %s is nil", m.Reference(), prop)
if len(versioned) == 1 && versioned[0] {
err = ErrNotSupported
}
return types.ManagedObjectReference{}, err
}
func (m HostConfigManager) DatastoreSystem(ctx context.Context) (*HostDatastoreSystem, error) {
ref, err := m.reference(ctx, "datastoreSystem")
if err != nil {
return nil, err
}
return NewHostDatastoreSystem(m.c, ref), nil
}
func (m HostConfigManager) NetworkSystem(ctx context.Context) (*HostNetworkSystem, error) {
ref, err := m.reference(ctx, "networkSystem")
if err != nil {
return nil, err
}
return NewHostNetworkSystem(m.c, ref), nil
}
func (m HostConfigManager) FirewallSystem(ctx context.Context) (*HostFirewallSystem, error) {
ref, err := m.reference(ctx, "firewallSystem")
if err != nil {
return nil, err
}
return NewHostFirewallSystem(m.c, ref), nil
}
func (m HostConfigManager) StorageSystem(ctx context.Context) (*HostStorageSystem, error) {
ref, err := m.reference(ctx, "storageSystem")
if err != nil {
return nil, err
}
return NewHostStorageSystem(m.c, ref), nil
}
func (m HostConfigManager) VirtualNicManager(ctx context.Context) (*HostVirtualNicManager, error) {
ref, err := m.reference(ctx, "virtualNicManager")
if err != nil {
return nil, err
}
return NewHostVirtualNicManager(m.c, ref, m.Reference()), nil
}
func (m HostConfigManager) VsanSystem(ctx context.Context) (*HostVsanSystem, error) {
ref, err := m.reference(ctx, "vsanSystem", true) // Added in 5.5
if err != nil {
return nil, err
}
return NewHostVsanSystem(m.c, ref), nil
}
func (m HostConfigManager) VsanInternalSystem(ctx context.Context) (*HostVsanInternalSystem, error) {
ref, err := m.reference(ctx, "vsanInternalSystem", true) // Added in 5.5
if err != nil {
return nil, err
}
return NewHostVsanInternalSystem(m.c, ref), nil
}
func (m HostConfigManager) AccountManager(ctx context.Context) (*HostAccountManager, error) {
ref, err := m.reference(ctx, "accountManager", true) // Added in 5.5
if err != nil {
if err == ErrNotSupported {
// Versions < 5.5 can use the ServiceContent ref,
// but only when connected directly to ESX.
if m.c.ServiceContent.AccountManager == nil {
return nil, err
}
ref = *m.c.ServiceContent.AccountManager
} else {
return nil, err
}
}
return NewHostAccountManager(m.c, ref), nil
}
func (m HostConfigManager) OptionManager(ctx context.Context) (*OptionManager, error) {
ref, err := m.reference(ctx, "advancedOption")
if err != nil {
return nil, err
}
return NewOptionManager(m.c, ref), nil
}
func (m HostConfigManager) ServiceSystem(ctx context.Context) (*HostServiceSystem, error) {
ref, err := m.reference(ctx, "serviceSystem")
if err != nil {
return nil, err
}
return NewHostServiceSystem(m.c, ref), nil
}
func (m HostConfigManager) CertificateManager(ctx context.Context) (*HostCertificateManager, error) {
ref, err := m.reference(ctx, "certificateManager", true) // Added in 6.0
if err != nil {
return nil, err
}
return NewHostCertificateManager(m.c, ref, m.Reference()), nil
}
func (m HostConfigManager) DateTimeSystem(ctx context.Context) (*HostDateTimeSystem, error) {
ref, err := m.reference(ctx, "dateTimeSystem")
if err != nil {
return nil, err
}
return NewHostDateTimeSystem(m.c, ref), nil
}

View File

@@ -1,65 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type HostDatastoreBrowser struct {
Common
}
func NewHostDatastoreBrowser(c *vim25.Client, ref types.ManagedObjectReference) *HostDatastoreBrowser {
return &HostDatastoreBrowser{
Common: NewCommon(c, ref),
}
}
func (b HostDatastoreBrowser) SearchDatastore(ctx context.Context, datastorePath string, searchSpec *types.HostDatastoreBrowserSearchSpec) (*Task, error) {
req := types.SearchDatastore_Task{
This: b.Reference(),
DatastorePath: datastorePath,
SearchSpec: searchSpec,
}
res, err := methods.SearchDatastore_Task(ctx, b.c, &req)
if err != nil {
return nil, err
}
return NewTask(b.c, res.Returnval), nil
}
func (b HostDatastoreBrowser) SearchDatastoreSubFolders(ctx context.Context, datastorePath string, searchSpec *types.HostDatastoreBrowserSearchSpec) (*Task, error) {
req := types.SearchDatastoreSubFolders_Task{
This: b.Reference(),
DatastorePath: datastorePath,
SearchSpec: searchSpec,
}
res, err := methods.SearchDatastoreSubFolders_Task(ctx, b.c, &req)
if err != nil {
return nil, err
}
return NewTask(b.c, res.Returnval), nil
}

View File

@@ -1,135 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type HostDatastoreSystem struct {
Common
}
func NewHostDatastoreSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostDatastoreSystem {
return &HostDatastoreSystem{
Common: NewCommon(c, ref),
}
}
func (s HostDatastoreSystem) CreateLocalDatastore(ctx context.Context, name string, path string) (*Datastore, error) {
req := types.CreateLocalDatastore{
This: s.Reference(),
Name: name,
Path: path,
}
res, err := methods.CreateLocalDatastore(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewDatastore(s.Client(), res.Returnval), nil
}
func (s HostDatastoreSystem) CreateNasDatastore(ctx context.Context, spec types.HostNasVolumeSpec) (*Datastore, error) {
req := types.CreateNasDatastore{
This: s.Reference(),
Spec: spec,
}
res, err := methods.CreateNasDatastore(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewDatastore(s.Client(), res.Returnval), nil
}
func (s HostDatastoreSystem) CreateVmfsDatastore(ctx context.Context, spec types.VmfsDatastoreCreateSpec) (*Datastore, error) {
req := types.CreateVmfsDatastore{
This: s.Reference(),
Spec: spec,
}
res, err := methods.CreateVmfsDatastore(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewDatastore(s.Client(), res.Returnval), nil
}
func (s HostDatastoreSystem) Remove(ctx context.Context, ds *Datastore) error {
req := types.RemoveDatastore{
This: s.Reference(),
Datastore: ds.Reference(),
}
_, err := methods.RemoveDatastore(ctx, s.Client(), &req)
if err != nil {
return err
}
return nil
}
func (s HostDatastoreSystem) QueryAvailableDisksForVmfs(ctx context.Context) ([]types.HostScsiDisk, error) {
req := types.QueryAvailableDisksForVmfs{
This: s.Reference(),
}
res, err := methods.QueryAvailableDisksForVmfs(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (s HostDatastoreSystem) QueryVmfsDatastoreCreateOptions(ctx context.Context, devicePath string) ([]types.VmfsDatastoreOption, error) {
req := types.QueryVmfsDatastoreCreateOptions{
This: s.Reference(),
DevicePath: devicePath,
}
res, err := methods.QueryVmfsDatastoreCreateOptions(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (s HostDatastoreSystem) ResignatureUnresolvedVmfsVolumes(ctx context.Context, devicePaths []string) (*Task, error) {
req := &types.ResignatureUnresolvedVmfsVolume_Task{
This: s.Reference(),
ResolutionSpec: types.HostUnresolvedVmfsResignatureSpec{
ExtentDevicePath: devicePaths,
},
}
res, err := methods.ResignatureUnresolvedVmfsVolume_Task(ctx, s.Client(), req)
if err != nil {
return nil, err
}
return NewTask(s.c, res.Returnval), nil
}

View File

@@ -1,69 +0,0 @@
/*
Copyright (c) 2016 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.
*/
package object
import (
"context"
"time"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type HostDateTimeSystem struct {
Common
}
func NewHostDateTimeSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostDateTimeSystem {
return &HostDateTimeSystem{
Common: NewCommon(c, ref),
}
}
func (s HostDateTimeSystem) UpdateConfig(ctx context.Context, config types.HostDateTimeConfig) error {
req := types.UpdateDateTimeConfig{
This: s.Reference(),
Config: config,
}
_, err := methods.UpdateDateTimeConfig(ctx, s.c, &req)
return err
}
func (s HostDateTimeSystem) Update(ctx context.Context, date time.Time) error {
req := types.UpdateDateTime{
This: s.Reference(),
DateTime: date,
}
_, err := methods.UpdateDateTime(ctx, s.c, &req)
return err
}
func (s HostDateTimeSystem) Query(ctx context.Context) (*time.Time, error) {
req := types.QueryDateTime{
This: s.Reference(),
}
res, err := methods.QueryDateTime(ctx, s.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}

View File

@@ -1,181 +0,0 @@
/*
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.
*/
package object
import (
"context"
"errors"
"fmt"
"strings"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type HostFirewallSystem struct {
Common
}
func NewHostFirewallSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostFirewallSystem {
return &HostFirewallSystem{
Common: NewCommon(c, ref),
}
}
func (s HostFirewallSystem) DisableRuleset(ctx context.Context, id string) error {
req := types.DisableRuleset{
This: s.Reference(),
Id: id,
}
_, err := methods.DisableRuleset(ctx, s.c, &req)
return err
}
func (s HostFirewallSystem) EnableRuleset(ctx context.Context, id string) error {
req := types.EnableRuleset{
This: s.Reference(),
Id: id,
}
_, err := methods.EnableRuleset(ctx, s.c, &req)
return err
}
func (s HostFirewallSystem) Refresh(ctx context.Context) error {
req := types.RefreshFirewall{
This: s.Reference(),
}
_, err := methods.RefreshFirewall(ctx, s.c, &req)
return err
}
func (s HostFirewallSystem) Info(ctx context.Context) (*types.HostFirewallInfo, error) {
var fs mo.HostFirewallSystem
err := s.Properties(ctx, s.Reference(), []string{"firewallInfo"}, &fs)
if err != nil {
return nil, err
}
return fs.FirewallInfo, nil
}
// HostFirewallRulesetList provides helpers for a slice of types.HostFirewallRuleset
type HostFirewallRulesetList []types.HostFirewallRuleset
// ByRule returns a HostFirewallRulesetList where Direction, PortType and Protocol are equal and Port is within range
func (l HostFirewallRulesetList) ByRule(rule types.HostFirewallRule) HostFirewallRulesetList {
var matches HostFirewallRulesetList
for _, rs := range l {
for _, r := range rs.Rule {
if r.PortType != rule.PortType ||
r.Protocol != rule.Protocol ||
r.Direction != rule.Direction {
continue
}
if r.EndPort == 0 && rule.Port == r.Port ||
rule.Port >= r.Port && rule.Port <= r.EndPort {
matches = append(matches, rs)
break
}
}
}
return matches
}
// EnabledByRule returns a HostFirewallRulesetList with Match(rule) applied and filtered via Enabled()
// if enabled param is true, otherwise filtered via Disabled().
// An error is returned if the resulting list is empty.
func (l HostFirewallRulesetList) EnabledByRule(rule types.HostFirewallRule, enabled bool) (HostFirewallRulesetList, error) {
var matched, skipped HostFirewallRulesetList
var matchedKind, skippedKind string
l = l.ByRule(rule)
if enabled {
matched = l.Enabled()
matchedKind = "enabled"
skipped = l.Disabled()
skippedKind = "disabled"
} else {
matched = l.Disabled()
matchedKind = "disabled"
skipped = l.Enabled()
skippedKind = "enabled"
}
if len(matched) == 0 {
msg := fmt.Sprintf("%d %s firewall rulesets match %s %s %s %d, %d %s rulesets match",
len(matched), matchedKind,
rule.Direction, rule.Protocol, rule.PortType, rule.Port,
len(skipped), skippedKind)
if len(skipped) != 0 {
msg += fmt.Sprintf(": %s", strings.Join(skipped.Keys(), ", "))
}
return nil, errors.New(msg)
}
return matched, nil
}
// Enabled returns a HostFirewallRulesetList with enabled rules
func (l HostFirewallRulesetList) Enabled() HostFirewallRulesetList {
var matches HostFirewallRulesetList
for _, rs := range l {
if rs.Enabled {
matches = append(matches, rs)
}
}
return matches
}
// Disabled returns a HostFirewallRulesetList with disabled rules
func (l HostFirewallRulesetList) Disabled() HostFirewallRulesetList {
var matches HostFirewallRulesetList
for _, rs := range l {
if !rs.Enabled {
matches = append(matches, rs)
}
}
return matches
}
// Keys returns the HostFirewallRuleset.Key for each ruleset in the list
func (l HostFirewallRulesetList) Keys() []string {
var keys []string
for _, rs := range l {
keys = append(keys, rs.Key)
}
return keys
}

View File

@@ -1,358 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type HostNetworkSystem struct {
Common
}
func NewHostNetworkSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostNetworkSystem {
return &HostNetworkSystem{
Common: NewCommon(c, ref),
}
}
// AddPortGroup wraps methods.AddPortGroup
func (o HostNetworkSystem) AddPortGroup(ctx context.Context, portgrp types.HostPortGroupSpec) error {
req := types.AddPortGroup{
This: o.Reference(),
Portgrp: portgrp,
}
_, err := methods.AddPortGroup(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// AddServiceConsoleVirtualNic wraps methods.AddServiceConsoleVirtualNic
func (o HostNetworkSystem) AddServiceConsoleVirtualNic(ctx context.Context, portgroup string, nic types.HostVirtualNicSpec) (string, error) {
req := types.AddServiceConsoleVirtualNic{
This: o.Reference(),
Portgroup: portgroup,
Nic: nic,
}
res, err := methods.AddServiceConsoleVirtualNic(ctx, o.c, &req)
if err != nil {
return "", err
}
return res.Returnval, nil
}
// AddVirtualNic wraps methods.AddVirtualNic
func (o HostNetworkSystem) AddVirtualNic(ctx context.Context, portgroup string, nic types.HostVirtualNicSpec) (string, error) {
req := types.AddVirtualNic{
This: o.Reference(),
Portgroup: portgroup,
Nic: nic,
}
res, err := methods.AddVirtualNic(ctx, o.c, &req)
if err != nil {
return "", err
}
return res.Returnval, nil
}
// AddVirtualSwitch wraps methods.AddVirtualSwitch
func (o HostNetworkSystem) AddVirtualSwitch(ctx context.Context, vswitchName string, spec *types.HostVirtualSwitchSpec) error {
req := types.AddVirtualSwitch{
This: o.Reference(),
VswitchName: vswitchName,
Spec: spec,
}
_, err := methods.AddVirtualSwitch(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// QueryNetworkHint wraps methods.QueryNetworkHint
func (o HostNetworkSystem) QueryNetworkHint(ctx context.Context, device []string) ([]types.PhysicalNicHintInfo, error) {
req := types.QueryNetworkHint{
This: o.Reference(),
Device: device,
}
res, err := methods.QueryNetworkHint(ctx, o.c, &req)
if err != nil {
return nil, err
}
return res.Returnval, err
}
// RefreshNetworkSystem wraps methods.RefreshNetworkSystem
func (o HostNetworkSystem) RefreshNetworkSystem(ctx context.Context) error {
req := types.RefreshNetworkSystem{
This: o.Reference(),
}
_, err := methods.RefreshNetworkSystem(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// RemovePortGroup wraps methods.RemovePortGroup
func (o HostNetworkSystem) RemovePortGroup(ctx context.Context, pgName string) error {
req := types.RemovePortGroup{
This: o.Reference(),
PgName: pgName,
}
_, err := methods.RemovePortGroup(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// RemoveServiceConsoleVirtualNic wraps methods.RemoveServiceConsoleVirtualNic
func (o HostNetworkSystem) RemoveServiceConsoleVirtualNic(ctx context.Context, device string) error {
req := types.RemoveServiceConsoleVirtualNic{
This: o.Reference(),
Device: device,
}
_, err := methods.RemoveServiceConsoleVirtualNic(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// RemoveVirtualNic wraps methods.RemoveVirtualNic
func (o HostNetworkSystem) RemoveVirtualNic(ctx context.Context, device string) error {
req := types.RemoveVirtualNic{
This: o.Reference(),
Device: device,
}
_, err := methods.RemoveVirtualNic(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// RemoveVirtualSwitch wraps methods.RemoveVirtualSwitch
func (o HostNetworkSystem) RemoveVirtualSwitch(ctx context.Context, vswitchName string) error {
req := types.RemoveVirtualSwitch{
This: o.Reference(),
VswitchName: vswitchName,
}
_, err := methods.RemoveVirtualSwitch(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// RestartServiceConsoleVirtualNic wraps methods.RestartServiceConsoleVirtualNic
func (o HostNetworkSystem) RestartServiceConsoleVirtualNic(ctx context.Context, device string) error {
req := types.RestartServiceConsoleVirtualNic{
This: o.Reference(),
Device: device,
}
_, err := methods.RestartServiceConsoleVirtualNic(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateConsoleIpRouteConfig wraps methods.UpdateConsoleIpRouteConfig
func (o HostNetworkSystem) UpdateConsoleIpRouteConfig(ctx context.Context, config types.BaseHostIpRouteConfig) error {
req := types.UpdateConsoleIpRouteConfig{
This: o.Reference(),
Config: config,
}
_, err := methods.UpdateConsoleIpRouteConfig(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateDnsConfig wraps methods.UpdateDnsConfig
func (o HostNetworkSystem) UpdateDnsConfig(ctx context.Context, config types.BaseHostDnsConfig) error {
req := types.UpdateDnsConfig{
This: o.Reference(),
Config: config,
}
_, err := methods.UpdateDnsConfig(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateIpRouteConfig wraps methods.UpdateIpRouteConfig
func (o HostNetworkSystem) UpdateIpRouteConfig(ctx context.Context, config types.BaseHostIpRouteConfig) error {
req := types.UpdateIpRouteConfig{
This: o.Reference(),
Config: config,
}
_, err := methods.UpdateIpRouteConfig(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateIpRouteTableConfig wraps methods.UpdateIpRouteTableConfig
func (o HostNetworkSystem) UpdateIpRouteTableConfig(ctx context.Context, config types.HostIpRouteTableConfig) error {
req := types.UpdateIpRouteTableConfig{
This: o.Reference(),
Config: config,
}
_, err := methods.UpdateIpRouteTableConfig(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateNetworkConfig wraps methods.UpdateNetworkConfig
func (o HostNetworkSystem) UpdateNetworkConfig(ctx context.Context, config types.HostNetworkConfig, changeMode string) (*types.HostNetworkConfigResult, error) {
req := types.UpdateNetworkConfig{
This: o.Reference(),
Config: config,
ChangeMode: changeMode,
}
res, err := methods.UpdateNetworkConfig(ctx, o.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
// UpdatePhysicalNicLinkSpeed wraps methods.UpdatePhysicalNicLinkSpeed
func (o HostNetworkSystem) UpdatePhysicalNicLinkSpeed(ctx context.Context, device string, linkSpeed *types.PhysicalNicLinkInfo) error {
req := types.UpdatePhysicalNicLinkSpeed{
This: o.Reference(),
Device: device,
LinkSpeed: linkSpeed,
}
_, err := methods.UpdatePhysicalNicLinkSpeed(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdatePortGroup wraps methods.UpdatePortGroup
func (o HostNetworkSystem) UpdatePortGroup(ctx context.Context, pgName string, portgrp types.HostPortGroupSpec) error {
req := types.UpdatePortGroup{
This: o.Reference(),
PgName: pgName,
Portgrp: portgrp,
}
_, err := methods.UpdatePortGroup(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateServiceConsoleVirtualNic wraps methods.UpdateServiceConsoleVirtualNic
func (o HostNetworkSystem) UpdateServiceConsoleVirtualNic(ctx context.Context, device string, nic types.HostVirtualNicSpec) error {
req := types.UpdateServiceConsoleVirtualNic{
This: o.Reference(),
Device: device,
Nic: nic,
}
_, err := methods.UpdateServiceConsoleVirtualNic(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateVirtualNic wraps methods.UpdateVirtualNic
func (o HostNetworkSystem) UpdateVirtualNic(ctx context.Context, device string, nic types.HostVirtualNicSpec) error {
req := types.UpdateVirtualNic{
This: o.Reference(),
Device: device,
Nic: nic,
}
_, err := methods.UpdateVirtualNic(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateVirtualSwitch wraps methods.UpdateVirtualSwitch
func (o HostNetworkSystem) UpdateVirtualSwitch(ctx context.Context, vswitchName string, spec types.HostVirtualSwitchSpec) error {
req := types.UpdateVirtualSwitch{
This: o.Reference(),
VswitchName: vswitchName,
Spec: spec,
}
_, err := methods.UpdateVirtualSwitch(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}

View File

@@ -1,88 +0,0 @@
/*
Copyright (c) 2016 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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type HostServiceSystem struct {
Common
}
func NewHostServiceSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostServiceSystem {
return &HostServiceSystem{
Common: NewCommon(c, ref),
}
}
func (s HostServiceSystem) Service(ctx context.Context) ([]types.HostService, error) {
var ss mo.HostServiceSystem
err := s.Properties(ctx, s.Reference(), []string{"serviceInfo.service"}, &ss)
if err != nil {
return nil, err
}
return ss.ServiceInfo.Service, nil
}
func (s HostServiceSystem) Start(ctx context.Context, id string) error {
req := types.StartService{
This: s.Reference(),
Id: id,
}
_, err := methods.StartService(ctx, s.Client(), &req)
return err
}
func (s HostServiceSystem) Stop(ctx context.Context, id string) error {
req := types.StopService{
This: s.Reference(),
Id: id,
}
_, err := methods.StopService(ctx, s.Client(), &req)
return err
}
func (s HostServiceSystem) Restart(ctx context.Context, id string) error {
req := types.RestartService{
This: s.Reference(),
Id: id,
}
_, err := methods.RestartService(ctx, s.Client(), &req)
return err
}
func (s HostServiceSystem) UpdatePolicy(ctx context.Context, id string, policy string) error {
req := types.UpdateServicePolicy{
This: s.Reference(),
Id: id,
Policy: policy,
}
_, err := methods.UpdateServicePolicy(ctx, s.Client(), &req)
return err
}

View File

@@ -1,200 +0,0 @@
/*
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.
*/
package object
import (
"context"
"errors"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type HostStorageSystem struct {
Common
}
func NewHostStorageSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostStorageSystem {
return &HostStorageSystem{
Common: NewCommon(c, ref),
}
}
func (s HostStorageSystem) RetrieveDiskPartitionInfo(ctx context.Context, devicePath string) (*types.HostDiskPartitionInfo, error) {
req := types.RetrieveDiskPartitionInfo{
This: s.Reference(),
DevicePath: []string{devicePath},
}
res, err := methods.RetrieveDiskPartitionInfo(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil || len(res.Returnval) == 0 {
return nil, errors.New("no partition info")
}
return &res.Returnval[0], nil
}
func (s HostStorageSystem) ComputeDiskPartitionInfo(ctx context.Context, devicePath string, layout types.HostDiskPartitionLayout) (*types.HostDiskPartitionInfo, error) {
req := types.ComputeDiskPartitionInfo{
This: s.Reference(),
DevicePath: devicePath,
Layout: layout,
}
res, err := methods.ComputeDiskPartitionInfo(ctx, s.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (s HostStorageSystem) UpdateDiskPartitionInfo(ctx context.Context, devicePath string, spec types.HostDiskPartitionSpec) error {
req := types.UpdateDiskPartitions{
This: s.Reference(),
DevicePath: devicePath,
Spec: spec,
}
_, err := methods.UpdateDiskPartitions(ctx, s.c, &req)
return err
}
func (s HostStorageSystem) RescanAllHba(ctx context.Context) error {
req := types.RescanAllHba{
This: s.Reference(),
}
_, err := methods.RescanAllHba(ctx, s.c, &req)
return err
}
func (s HostStorageSystem) Refresh(ctx context.Context) error {
req := types.RefreshStorageSystem{
This: s.Reference(),
}
_, err := methods.RefreshStorageSystem(ctx, s.c, &req)
return err
}
func (s HostStorageSystem) RescanVmfs(ctx context.Context) error {
req := types.RescanVmfs{
This: s.Reference(),
}
_, err := methods.RescanVmfs(ctx, s.c, &req)
return err
}
func (s HostStorageSystem) MarkAsSsd(ctx context.Context, uuid string) (*Task, error) {
req := types.MarkAsSsd_Task{
This: s.Reference(),
ScsiDiskUuid: uuid,
}
res, err := methods.MarkAsSsd_Task(ctx, s.c, &req)
if err != nil {
return nil, err
}
return NewTask(s.c, res.Returnval), nil
}
func (s HostStorageSystem) MarkAsNonSsd(ctx context.Context, uuid string) (*Task, error) {
req := types.MarkAsNonSsd_Task{
This: s.Reference(),
ScsiDiskUuid: uuid,
}
res, err := methods.MarkAsNonSsd_Task(ctx, s.c, &req)
if err != nil {
return nil, err
}
return NewTask(s.c, res.Returnval), nil
}
func (s HostStorageSystem) MarkAsLocal(ctx context.Context, uuid string) (*Task, error) {
req := types.MarkAsLocal_Task{
This: s.Reference(),
ScsiDiskUuid: uuid,
}
res, err := methods.MarkAsLocal_Task(ctx, s.c, &req)
if err != nil {
return nil, err
}
return NewTask(s.c, res.Returnval), nil
}
func (s HostStorageSystem) MarkAsNonLocal(ctx context.Context, uuid string) (*Task, error) {
req := types.MarkAsNonLocal_Task{
This: s.Reference(),
ScsiDiskUuid: uuid,
}
res, err := methods.MarkAsNonLocal_Task(ctx, s.c, &req)
if err != nil {
return nil, err
}
return NewTask(s.c, res.Returnval), nil
}
func (s HostStorageSystem) AttachScsiLun(ctx context.Context, uuid string) error {
req := types.AttachScsiLun{
This: s.Reference(),
LunUuid: uuid,
}
_, err := methods.AttachScsiLun(ctx, s.c, &req)
return err
}
func (s HostStorageSystem) QueryUnresolvedVmfsVolumes(ctx context.Context) ([]types.HostUnresolvedVmfsVolume, error) {
req := &types.QueryUnresolvedVmfsVolume{
This: s.Reference(),
}
res, err := methods.QueryUnresolvedVmfsVolume(ctx, s.Client(), req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (s HostStorageSystem) UnmountVmfsVolume(ctx context.Context, vmfsUuid string) error {
req := &types.UnmountVmfsVolume{
This: s.Reference(),
VmfsUuid: vmfsUuid,
}
_, err := methods.UnmountVmfsVolume(ctx, s.Client(), req)
if err != nil {
return err
}
return nil
}

View File

@@ -1,154 +0,0 @@
/*
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.
*/
package object
import (
"context"
"fmt"
"net"
"github.com/vmware/govmomi/internal"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type HostSystem struct {
Common
}
func NewHostSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostSystem {
return &HostSystem{
Common: NewCommon(c, ref),
}
}
func (h HostSystem) ConfigManager() *HostConfigManager {
return NewHostConfigManager(h.c, h.Reference())
}
func (h HostSystem) ResourcePool(ctx context.Context) (*ResourcePool, error) {
var mh mo.HostSystem
err := h.Properties(ctx, h.Reference(), []string{"parent"}, &mh)
if err != nil {
return nil, err
}
var mcr *mo.ComputeResource
var parent interface{}
switch mh.Parent.Type {
case "ComputeResource":
mcr = new(mo.ComputeResource)
parent = mcr
case "ClusterComputeResource":
mcc := new(mo.ClusterComputeResource)
mcr = &mcc.ComputeResource
parent = mcc
default:
return nil, fmt.Errorf("unknown host parent type: %s", mh.Parent.Type)
}
err = h.Properties(ctx, *mh.Parent, []string{"resourcePool"}, parent)
if err != nil {
return nil, err
}
pool := NewResourcePool(h.c, *mcr.ResourcePool)
return pool, nil
}
func (h HostSystem) ManagementIPs(ctx context.Context) ([]net.IP, error) {
var mh mo.HostSystem
err := h.Properties(ctx, h.Reference(), []string{"config.virtualNicManagerInfo.netConfig"}, &mh)
if err != nil {
return nil, err
}
config := mh.Config
if config == nil {
return nil, nil
}
info := config.VirtualNicManagerInfo
if info == nil {
return nil, nil
}
return internal.HostSystemManagementIPs(info.NetConfig), nil
}
func (h HostSystem) Disconnect(ctx context.Context) (*Task, error) {
req := types.DisconnectHost_Task{
This: h.Reference(),
}
res, err := methods.DisconnectHost_Task(ctx, h.c, &req)
if err != nil {
return nil, err
}
return NewTask(h.c, res.Returnval), nil
}
func (h HostSystem) Reconnect(ctx context.Context, cnxSpec *types.HostConnectSpec, reconnectSpec *types.HostSystemReconnectSpec) (*Task, error) {
req := types.ReconnectHost_Task{
This: h.Reference(),
CnxSpec: cnxSpec,
ReconnectSpec: reconnectSpec,
}
res, err := methods.ReconnectHost_Task(ctx, h.c, &req)
if err != nil {
return nil, err
}
return NewTask(h.c, res.Returnval), nil
}
func (h HostSystem) EnterMaintenanceMode(ctx context.Context, timeout int32, evacuate bool, spec *types.HostMaintenanceSpec) (*Task, error) {
req := types.EnterMaintenanceMode_Task{
This: h.Reference(),
Timeout: timeout,
EvacuatePoweredOffVms: types.NewBool(evacuate),
MaintenanceSpec: spec,
}
res, err := methods.EnterMaintenanceMode_Task(ctx, h.c, &req)
if err != nil {
return nil, err
}
return NewTask(h.c, res.Returnval), nil
}
func (h HostSystem) ExitMaintenanceMode(ctx context.Context, timeout int32) (*Task, error) {
req := types.ExitMaintenanceMode_Task{
This: h.Reference(),
Timeout: timeout,
}
res, err := methods.ExitMaintenanceMode_Task(ctx, h.c, &req)
if err != nil {
return nil, err
}
return NewTask(h.c, res.Returnval), nil
}

View File

@@ -1,93 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type HostVirtualNicManager struct {
Common
Host *HostSystem
}
func NewHostVirtualNicManager(c *vim25.Client, ref types.ManagedObjectReference, host types.ManagedObjectReference) *HostVirtualNicManager {
return &HostVirtualNicManager{
Common: NewCommon(c, ref),
Host: NewHostSystem(c, host),
}
}
func (m HostVirtualNicManager) Info(ctx context.Context) (*types.HostVirtualNicManagerInfo, error) {
var vnm mo.HostVirtualNicManager
err := m.Properties(ctx, m.Reference(), []string{"info"}, &vnm)
if err != nil {
return nil, err
}
return &vnm.Info, nil
}
func (m HostVirtualNicManager) DeselectVnic(ctx context.Context, nicType string, device string) error {
if nicType == string(types.HostVirtualNicManagerNicTypeVsan) {
// Avoid fault.NotSupported:
// "Error deselecting device '$device': VSAN interfaces must be deselected using vim.host.VsanSystem"
s, err := m.Host.ConfigManager().VsanSystem(ctx)
if err != nil {
return err
}
return s.updateVnic(ctx, device, false)
}
req := types.DeselectVnicForNicType{
This: m.Reference(),
NicType: nicType,
Device: device,
}
_, err := methods.DeselectVnicForNicType(ctx, m.Client(), &req)
return err
}
func (m HostVirtualNicManager) SelectVnic(ctx context.Context, nicType string, device string) error {
if nicType == string(types.HostVirtualNicManagerNicTypeVsan) {
// Avoid fault.NotSupported:
// "Error selecting device '$device': VSAN interfaces must be selected using vim.host.VsanSystem"
s, err := m.Host.ConfigManager().VsanSystem(ctx)
if err != nil {
return err
}
return s.updateVnic(ctx, device, true)
}
req := types.SelectVnicForNicType{
This: m.Reference(),
NicType: nicType,
Device: device,
}
_, err := methods.SelectVnicForNicType(ctx, m.Client(), &req)
return err
}

View File

@@ -1,117 +0,0 @@
/*
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.
*/
package object
import (
"context"
"encoding/json"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type HostVsanInternalSystem struct {
Common
}
func NewHostVsanInternalSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostVsanInternalSystem {
m := HostVsanInternalSystem{
Common: NewCommon(c, ref),
}
return &m
}
// QueryVsanObjectUuidsByFilter returns vSAN DOM object uuids by filter.
func (m HostVsanInternalSystem) QueryVsanObjectUuidsByFilter(ctx context.Context, uuids []string, limit int32, version int32) ([]string, error) {
req := types.QueryVsanObjectUuidsByFilter{
This: m.Reference(),
Uuids: uuids,
Limit: &limit,
Version: version,
}
res, err := methods.QueryVsanObjectUuidsByFilter(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
type VsanObjExtAttrs struct {
Type string `json:"Object type"`
Class string `json:"Object class"`
Size string `json:"Object size"`
Path string `json:"Object path"`
Name string `json:"User friendly name"`
}
func (a *VsanObjExtAttrs) DatastorePath(dir string) string {
l := len(dir)
path := a.Path
if len(path) >= l {
path = a.Path[l:]
}
if path != "" {
return path
}
return a.Name // vmnamespace
}
// GetVsanObjExtAttrs is internal and intended for troubleshooting/debugging situations in the field.
// WARNING: This API can be slow because we do IOs (reads) to all the objects.
func (m HostVsanInternalSystem) GetVsanObjExtAttrs(ctx context.Context, uuids []string) (map[string]VsanObjExtAttrs, error) {
req := types.GetVsanObjExtAttrs{
This: m.Reference(),
Uuids: uuids,
}
res, err := methods.GetVsanObjExtAttrs(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
var attrs map[string]VsanObjExtAttrs
err = json.Unmarshal([]byte(res.Returnval), &attrs)
return attrs, err
}
// DeleteVsanObjects is internal and intended for troubleshooting/debugging only.
// WARNING: This API can be slow because we do IOs to all the objects.
// DOM won't allow access to objects which have lost quorum. Such objects can be deleted with the optional "force" flag.
// These objects may however re-appear with quorum if the absent components come back (network partition gets resolved, etc.)
func (m HostVsanInternalSystem) DeleteVsanObjects(ctx context.Context, uuids []string, force *bool) ([]types.HostVsanInternalSystemDeleteVsanObjectsResult, error) {
req := types.DeleteVsanObjects{
This: m.Reference(),
Uuids: uuids,
Force: force,
}
res, err := methods.DeleteVsanObjects(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}

View File

@@ -1,88 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type HostVsanSystem struct {
Common
}
func NewHostVsanSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostVsanSystem {
return &HostVsanSystem{
Common: NewCommon(c, ref),
}
}
func (s HostVsanSystem) Update(ctx context.Context, config types.VsanHostConfigInfo) (*Task, error) {
req := types.UpdateVsan_Task{
This: s.Reference(),
Config: config,
}
res, err := methods.UpdateVsan_Task(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(s.Client(), res.Returnval), nil
}
// updateVnic in support of the HostVirtualNicManager.{SelectVnic,DeselectVnic} methods
func (s HostVsanSystem) updateVnic(ctx context.Context, device string, enable bool) error {
var vsan mo.HostVsanSystem
err := s.Properties(ctx, s.Reference(), []string{"config.networkInfo.port"}, &vsan)
if err != nil {
return err
}
info := vsan.Config
var port []types.VsanHostConfigInfoNetworkInfoPortConfig
for _, p := range info.NetworkInfo.Port {
if p.Device == device {
continue
}
port = append(port, p)
}
if enable {
port = append(port, types.VsanHostConfigInfoNetworkInfoPortConfig{
Device: device,
})
}
info.NetworkInfo.Port = port
task, err := s.Update(ctx, info)
if err != nil {
return err
}
_, err = task.WaitForResult(ctx, nil)
return err
}

View File

@@ -1,76 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type DatastoreNamespaceManager struct {
Common
}
func NewDatastoreNamespaceManager(c *vim25.Client) *DatastoreNamespaceManager {
n := DatastoreNamespaceManager{
Common: NewCommon(c, *c.ServiceContent.DatastoreNamespaceManager),
}
return &n
}
// CreateDirectory creates a top-level directory on the given vsan datastore, using
// the given user display name hint and opaque storage policy.
func (nm DatastoreNamespaceManager) CreateDirectory(ctx context.Context, ds *Datastore, displayName string, policy string) (string, error) {
req := &types.CreateDirectory{
This: nm.Reference(),
Datastore: ds.Reference(),
DisplayName: displayName,
Policy: policy,
}
resp, err := methods.CreateDirectory(ctx, nm.c, req)
if err != nil {
return "", err
}
return resp.Returnval, nil
}
// DeleteDirectory deletes the given top-level directory from a vsan datastore.
func (nm DatastoreNamespaceManager) DeleteDirectory(ctx context.Context, dc *Datacenter, datastorePath string) error {
req := &types.DeleteDirectory{
This: nm.Reference(),
DatastorePath: datastorePath,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
if _, err := methods.DeleteDirectory(ctx, nm.c, req); err != nil {
return err
}
return nil
}

View File

@@ -1,54 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/types"
)
type Network struct {
Common
}
func NewNetwork(c *vim25.Client, ref types.ManagedObjectReference) *Network {
return &Network{
Common: NewCommon(c, ref),
}
}
func (n Network) GetInventoryPath() string {
return n.InventoryPath
}
// EthernetCardBackingInfo returns the VirtualDeviceBackingInfo for this Network
func (n Network) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error) {
name, err := n.ObjectName(ctx)
if err != nil {
return nil, err
}
backing := &types.VirtualEthernetCardNetworkBackingInfo{
VirtualDeviceDeviceBackingInfo: types.VirtualDeviceDeviceBackingInfo{
DeviceName: name,
},
}
return backing, nil
}

View File

@@ -1,31 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25/types"
)
// The NetworkReference interface is implemented by managed objects
// which can be used as the backing for a VirtualEthernetCard.
type NetworkReference interface {
Reference
GetInventoryPath() string
EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error)
}

View File

@@ -1,72 +0,0 @@
/*
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.
*/
package object
import (
"context"
"fmt"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type OpaqueNetwork struct {
Common
}
func NewOpaqueNetwork(c *vim25.Client, ref types.ManagedObjectReference) *OpaqueNetwork {
return &OpaqueNetwork{
Common: NewCommon(c, ref),
}
}
func (n OpaqueNetwork) GetInventoryPath() string {
return n.InventoryPath
}
// EthernetCardBackingInfo returns the VirtualDeviceBackingInfo for this Network
func (n OpaqueNetwork) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error) {
summary, err := n.Summary(ctx)
if err != nil {
return nil, err
}
backing := &types.VirtualEthernetCardOpaqueNetworkBackingInfo{
OpaqueNetworkId: summary.OpaqueNetworkId,
OpaqueNetworkType: summary.OpaqueNetworkType,
}
return backing, nil
}
// Summary returns the mo.OpaqueNetwork.Summary property
func (n OpaqueNetwork) Summary(ctx context.Context) (*types.OpaqueNetworkSummary, error) {
var props mo.OpaqueNetwork
err := n.Properties(ctx, n.Reference(), []string{"summary"}, &props)
if err != nil {
return nil, err
}
summary, ok := props.Summary.(*types.OpaqueNetworkSummary)
if !ok {
return nil, fmt.Errorf("%s unsupported network summary type: %T", n, props.Summary)
}
return summary, nil
}

View File

@@ -1,59 +0,0 @@
/*
Copyright (c) 2016 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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type OptionManager struct {
Common
}
func NewOptionManager(c *vim25.Client, ref types.ManagedObjectReference) *OptionManager {
return &OptionManager{
Common: NewCommon(c, ref),
}
}
func (m OptionManager) Query(ctx context.Context, name string) ([]types.BaseOptionValue, error) {
req := types.QueryOptions{
This: m.Reference(),
Name: name,
}
res, err := methods.QueryOptions(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m OptionManager) Update(ctx context.Context, value []types.BaseOptionValue) error {
req := types.UpdateOptions{
This: m.Reference(),
ChangedValue: value,
}
_, err := methods.UpdateOptions(ctx, m.Client(), &req)
return err
}

View File

@@ -1,151 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/nfc"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type ResourcePool struct {
Common
}
func NewResourcePool(c *vim25.Client, ref types.ManagedObjectReference) *ResourcePool {
return &ResourcePool{
Common: NewCommon(c, ref),
}
}
// Owner returns the ResourcePool owner as a ClusterComputeResource or ComputeResource.
func (p ResourcePool) Owner(ctx context.Context) (Reference, error) {
var pool mo.ResourcePool
err := p.Properties(ctx, p.Reference(), []string{"owner"}, &pool)
if err != nil {
return nil, err
}
return NewReference(p.Client(), pool.Owner), nil
}
func (p ResourcePool) ImportVApp(ctx context.Context, spec types.BaseImportSpec, folder *Folder, host *HostSystem) (*nfc.Lease, error) {
req := types.ImportVApp{
This: p.Reference(),
Spec: spec,
}
if folder != nil {
ref := folder.Reference()
req.Folder = &ref
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.ImportVApp(ctx, p.c, &req)
if err != nil {
return nil, err
}
return nfc.NewLease(p.c, res.Returnval), nil
}
func (p ResourcePool) Create(ctx context.Context, name string, spec types.ResourceConfigSpec) (*ResourcePool, error) {
req := types.CreateResourcePool{
This: p.Reference(),
Name: name,
Spec: spec,
}
res, err := methods.CreateResourcePool(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewResourcePool(p.c, res.Returnval), nil
}
func (p ResourcePool) CreateVApp(ctx context.Context, name string, resSpec types.ResourceConfigSpec, configSpec types.VAppConfigSpec, folder *Folder) (*VirtualApp, error) {
req := types.CreateVApp{
This: p.Reference(),
Name: name,
ResSpec: resSpec,
ConfigSpec: configSpec,
}
if folder != nil {
ref := folder.Reference()
req.VmFolder = &ref
}
res, err := methods.CreateVApp(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewVirtualApp(p.c, res.Returnval), nil
}
func (p ResourcePool) UpdateConfig(ctx context.Context, name string, config *types.ResourceConfigSpec) error {
req := types.UpdateConfig{
This: p.Reference(),
Name: name,
Config: config,
}
if config != nil && config.Entity == nil {
ref := p.Reference()
// Create copy of config so changes won't leak back to the caller
newConfig := *config
newConfig.Entity = &ref
req.Config = &newConfig
}
_, err := methods.UpdateConfig(ctx, p.c, &req)
return err
}
func (p ResourcePool) DestroyChildren(ctx context.Context) error {
req := types.DestroyChildren{
This: p.Reference(),
}
_, err := methods.DestroyChildren(ctx, p.c, &req)
return err
}
func (p ResourcePool) Destroy(ctx context.Context) (*Task, error) {
req := types.Destroy_Task{
This: p.Reference(),
}
res, err := methods.Destroy_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}

View File

@@ -1,259 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type SearchIndex struct {
Common
}
func NewSearchIndex(c *vim25.Client) *SearchIndex {
s := SearchIndex{
Common: NewCommon(c, *c.ServiceContent.SearchIndex),
}
return &s
}
// FindByDatastorePath finds a virtual machine by its location on a datastore.
func (s SearchIndex) FindByDatastorePath(ctx context.Context, dc *Datacenter, path string) (Reference, error) {
req := types.FindByDatastorePath{
This: s.Reference(),
Datacenter: dc.Reference(),
Path: path,
}
res, err := methods.FindByDatastorePath(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
return NewReference(s.c, *res.Returnval), nil
}
// FindByDnsName finds a virtual machine or host by DNS name.
func (s SearchIndex) FindByDnsName(ctx context.Context, dc *Datacenter, dnsName string, vmSearch bool) (Reference, error) {
req := types.FindByDnsName{
This: s.Reference(),
DnsName: dnsName,
VmSearch: vmSearch,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.FindByDnsName(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
return NewReference(s.c, *res.Returnval), nil
}
// FindByInventoryPath finds a managed entity based on its location in the inventory.
func (s SearchIndex) FindByInventoryPath(ctx context.Context, path string) (Reference, error) {
req := types.FindByInventoryPath{
This: s.Reference(),
InventoryPath: path,
}
res, err := methods.FindByInventoryPath(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
r := NewReference(s.c, *res.Returnval)
type common interface {
SetInventoryPath(string)
}
if c, ok := r.(common); ok {
c.SetInventoryPath(path)
}
return r, nil
}
// FindByIp finds a virtual machine or host by IP address.
func (s SearchIndex) FindByIp(ctx context.Context, dc *Datacenter, ip string, vmSearch bool) (Reference, error) {
req := types.FindByIp{
This: s.Reference(),
Ip: ip,
VmSearch: vmSearch,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.FindByIp(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
return NewReference(s.c, *res.Returnval), nil
}
// FindByUuid finds a virtual machine or host by UUID.
func (s SearchIndex) FindByUuid(ctx context.Context, dc *Datacenter, uuid string, vmSearch bool, instanceUuid *bool) (Reference, error) {
req := types.FindByUuid{
This: s.Reference(),
Uuid: uuid,
VmSearch: vmSearch,
InstanceUuid: instanceUuid,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.FindByUuid(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
return NewReference(s.c, *res.Returnval), nil
}
// FindChild finds a particular child based on a managed entity name.
func (s SearchIndex) FindChild(ctx context.Context, entity Reference, name string) (Reference, error) {
req := types.FindChild{
This: s.Reference(),
Entity: entity.Reference(),
Name: name,
}
res, err := methods.FindChild(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
return NewReference(s.c, *res.Returnval), nil
}
// FindAllByDnsName finds all virtual machines or hosts by DNS name.
func (s SearchIndex) FindAllByDnsName(ctx context.Context, dc *Datacenter, dnsName string, vmSearch bool) ([]Reference, error) {
req := types.FindAllByDnsName{
This: s.Reference(),
DnsName: dnsName,
VmSearch: vmSearch,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.FindAllByDnsName(ctx, s.c, &req)
if err != nil {
return nil, err
}
if len(res.Returnval) == 0 {
return nil, nil
}
var references []Reference
for _, returnval := range res.Returnval {
references = append(references, NewReference(s.c, returnval))
}
return references, nil
}
// FindAllByIp finds all virtual machines or hosts by IP address.
func (s SearchIndex) FindAllByIp(ctx context.Context, dc *Datacenter, ip string, vmSearch bool) ([]Reference, error) {
req := types.FindAllByIp{
This: s.Reference(),
Ip: ip,
VmSearch: vmSearch,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.FindAllByIp(ctx, s.c, &req)
if err != nil {
return nil, err
}
if len(res.Returnval) == 0 {
return nil, nil
}
var references []Reference
for _, returnval := range res.Returnval {
references = append(references, NewReference(s.c, returnval))
}
return references, nil
}
// FindAllByUuid finds all virtual machines or hosts by UUID.
func (s SearchIndex) FindAllByUuid(ctx context.Context, dc *Datacenter, uuid string, vmSearch bool, instanceUuid *bool) ([]Reference, error) {
req := types.FindAllByUuid{
This: s.Reference(),
Uuid: uuid,
VmSearch: vmSearch,
InstanceUuid: instanceUuid,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.FindAllByUuid(ctx, s.c, &req)
if err != nil {
return nil, err
}
if len(res.Returnval) == 0 {
return nil, nil
}
var references []Reference
for _, returnval := range res.Returnval {
references = append(references, NewReference(s.c, returnval))
}
return references, nil
}

View File

@@ -1,34 +0,0 @@
/*
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.
*/
package object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/types"
)
type StoragePod struct {
*Folder
}
func NewStoragePod(c *vim25.Client, ref types.ManagedObjectReference) *StoragePod {
return &StoragePod{
Folder: &Folder{
Common: NewCommon(c, ref),
},
}
}

View File

@@ -1,179 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type StorageResourceManager struct {
Common
}
func NewStorageResourceManager(c *vim25.Client) *StorageResourceManager {
sr := StorageResourceManager{
Common: NewCommon(c, *c.ServiceContent.StorageResourceManager),
}
return &sr
}
func (sr StorageResourceManager) ApplyStorageDrsRecommendation(ctx context.Context, key []string) (*Task, error) {
req := types.ApplyStorageDrsRecommendation_Task{
This: sr.Reference(),
Key: key,
}
res, err := methods.ApplyStorageDrsRecommendation_Task(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return NewTask(sr.c, res.Returnval), nil
}
func (sr StorageResourceManager) ApplyStorageDrsRecommendationToPod(ctx context.Context, pod *StoragePod, key string) (*Task, error) {
req := types.ApplyStorageDrsRecommendationToPod_Task{
This: sr.Reference(),
Key: key,
}
if pod != nil {
req.Pod = pod.Reference()
}
res, err := methods.ApplyStorageDrsRecommendationToPod_Task(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return NewTask(sr.c, res.Returnval), nil
}
func (sr StorageResourceManager) CancelStorageDrsRecommendation(ctx context.Context, key []string) error {
req := types.CancelStorageDrsRecommendation{
This: sr.Reference(),
Key: key,
}
_, err := methods.CancelStorageDrsRecommendation(ctx, sr.c, &req)
return err
}
func (sr StorageResourceManager) ConfigureDatastoreIORM(ctx context.Context, datastore *Datastore, spec types.StorageIORMConfigSpec, key string) (*Task, error) {
req := types.ConfigureDatastoreIORM_Task{
This: sr.Reference(),
Spec: spec,
}
if datastore != nil {
req.Datastore = datastore.Reference()
}
res, err := methods.ConfigureDatastoreIORM_Task(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return NewTask(sr.c, res.Returnval), nil
}
func (sr StorageResourceManager) ConfigureStorageDrsForPod(ctx context.Context, pod *StoragePod, spec types.StorageDrsConfigSpec, modify bool) (*Task, error) {
req := types.ConfigureStorageDrsForPod_Task{
This: sr.Reference(),
Spec: spec,
Modify: modify,
}
if pod != nil {
req.Pod = pod.Reference()
}
res, err := methods.ConfigureStorageDrsForPod_Task(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return NewTask(sr.c, res.Returnval), nil
}
func (sr StorageResourceManager) QueryDatastorePerformanceSummary(ctx context.Context, datastore *Datastore) ([]types.StoragePerformanceSummary, error) {
req := types.QueryDatastorePerformanceSummary{
This: sr.Reference(),
}
if datastore != nil {
req.Datastore = datastore.Reference()
}
res, err := methods.QueryDatastorePerformanceSummary(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (sr StorageResourceManager) QueryIORMConfigOption(ctx context.Context, host *HostSystem) (*types.StorageIORMConfigOption, error) {
req := types.QueryIORMConfigOption{
This: sr.Reference(),
}
if host != nil {
req.Host = host.Reference()
}
res, err := methods.QueryIORMConfigOption(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (sr StorageResourceManager) RecommendDatastores(ctx context.Context, storageSpec types.StoragePlacementSpec) (*types.StoragePlacementResult, error) {
req := types.RecommendDatastores{
This: sr.Reference(),
StorageSpec: storageSpec,
}
res, err := methods.RecommendDatastores(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (sr StorageResourceManager) RefreshStorageDrsRecommendation(ctx context.Context, pod *StoragePod) error {
req := types.RefreshStorageDrsRecommendation{
This: sr.Reference(),
}
if pod != nil {
req.Pod = pod.Reference()
}
_, err := methods.RefreshStorageDrsRecommendation(ctx, sr.c, &req)
return err
}

View File

@@ -1,100 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/task"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/progress"
"github.com/vmware/govmomi/vim25/types"
)
// Task is a convenience wrapper around task.Task that keeps a reference to
// the client that was used to create it. This allows users to call the Wait()
// function with only a context parameter, instead of a context parameter, a
// soap.RoundTripper, and reference to the root property collector.
type Task struct {
Common
}
func NewTask(c *vim25.Client, ref types.ManagedObjectReference) *Task {
t := Task{
Common: NewCommon(c, ref),
}
return &t
}
func (t *Task) Wait(ctx context.Context) error {
_, err := t.WaitForResult(ctx, nil)
return err
}
func (t *Task) WaitForResult(ctx context.Context, s ...progress.Sinker) (*types.TaskInfo, error) {
var pr progress.Sinker
if len(s) == 1 {
pr = s[0]
}
p := property.DefaultCollector(t.c)
return task.Wait(ctx, t.Reference(), p, pr)
}
func (t *Task) Cancel(ctx context.Context) error {
_, err := methods.CancelTask(ctx, t.Client(), &types.CancelTask{
This: t.Reference(),
})
return err
}
// SetState sets task state and optionally sets results or fault, as appropriate for state.
func (t *Task) SetState(ctx context.Context, state types.TaskInfoState, result types.AnyType, fault *types.LocalizedMethodFault) error {
req := types.SetTaskState{
This: t.Reference(),
State: state,
Result: result,
Fault: fault,
}
_, err := methods.SetTaskState(ctx, t.Common.Client(), &req)
return err
}
// SetDescription updates task description to describe the current phase of the task.
func (t *Task) SetDescription(ctx context.Context, description types.LocalizableMessage) error {
req := types.SetTaskDescription{
This: t.Reference(),
Description: description,
}
_, err := methods.SetTaskDescription(ctx, t.Common.Client(), &req)
return err
}
// UpdateProgress Sets percentage done for this task and recalculates overall percentage done.
// If a percentDone value of less than zero or greater than 100 is specified,
// a value of zero or 100 respectively is used.
func (t *Task) UpdateProgress(ctx context.Context, percentDone int) error {
req := types.UpdateProgress{
This: t.Reference(),
PercentDone: int32(percentDone),
}
_, err := methods.UpdateProgress(ctx, t.Common.Client(), &req)
return err
}

View File

@@ -1,78 +0,0 @@
/*
Copyright (c) 2021 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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type TenantManager struct {
Common
}
func NewTenantManager(c *vim25.Client) *TenantManager {
t := TenantManager{
Common: NewCommon(c, *c.ServiceContent.TenantManager),
}
return &t
}
func (t TenantManager) MarkServiceProviderEntities(ctx context.Context, entities []types.ManagedObjectReference) error {
req := types.MarkServiceProviderEntities{
This: t.Reference(),
Entity: entities,
}
_, err := methods.MarkServiceProviderEntities(ctx, t.Client(), &req)
if err != nil {
return err
}
return nil
}
func (t TenantManager) UnmarkServiceProviderEntities(ctx context.Context, entities []types.ManagedObjectReference) error {
req := types.UnmarkServiceProviderEntities{
This: t.Reference(),
Entity: entities,
}
_, err := methods.UnmarkServiceProviderEntities(ctx, t.Client(), &req)
if err != nil {
return err
}
return nil
}
func (t TenantManager) RetrieveServiceProviderEntities(ctx context.Context) ([]types.ManagedObjectReference, error) {
req := types.RetrieveServiceProviderEntities{
This: t.Reference(),
}
res, err := methods.RetrieveServiceProviderEntities(ctx, t.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}

View File

@@ -1,67 +0,0 @@
/*
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.
*/
package object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/types"
)
type Reference interface {
Reference() types.ManagedObjectReference
}
func NewReference(c *vim25.Client, e types.ManagedObjectReference) Reference {
switch e.Type {
case "Folder":
return NewFolder(c, e)
case "StoragePod":
return &StoragePod{
NewFolder(c, e),
}
case "Datacenter":
return NewDatacenter(c, e)
case "VirtualMachine":
return NewVirtualMachine(c, e)
case "VirtualApp":
return &VirtualApp{
NewResourcePool(c, e),
}
case "ComputeResource":
return NewComputeResource(c, e)
case "ClusterComputeResource":
return NewClusterComputeResource(c, e)
case "HostSystem":
return NewHostSystem(c, e)
case "Network":
return NewNetwork(c, e)
case "OpaqueNetwork":
return NewOpaqueNetwork(c, e)
case "ResourcePool":
return NewResourcePool(c, e)
case "DistributedVirtualSwitch":
return NewDistributedVirtualSwitch(c, e)
case "VmwareDistributedVirtualSwitch":
return &VmwareDistributedVirtualSwitch{*NewDistributedVirtualSwitch(c, e)}
case "DistributedVirtualPortgroup":
return NewDistributedVirtualPortgroup(c, e)
case "Datastore":
return NewDatastore(c, e)
default:
panic("Unknown managed entity: " + e.Type)
}
}

View File

@@ -1,121 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type VirtualApp struct {
*ResourcePool
}
func NewVirtualApp(c *vim25.Client, ref types.ManagedObjectReference) *VirtualApp {
return &VirtualApp{
ResourcePool: NewResourcePool(c, ref),
}
}
func (p VirtualApp) CreateChildVM(ctx context.Context, config types.VirtualMachineConfigSpec, host *HostSystem) (*Task, error) {
req := types.CreateChildVM_Task{
This: p.Reference(),
Config: config,
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.CreateChildVM_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}
func (p VirtualApp) UpdateConfig(ctx context.Context, spec types.VAppConfigSpec) error {
req := types.UpdateVAppConfig{
This: p.Reference(),
Spec: spec,
}
_, err := methods.UpdateVAppConfig(ctx, p.c, &req)
return err
}
func (p VirtualApp) PowerOn(ctx context.Context) (*Task, error) {
req := types.PowerOnVApp_Task{
This: p.Reference(),
}
res, err := methods.PowerOnVApp_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}
func (p VirtualApp) PowerOff(ctx context.Context, force bool) (*Task, error) {
req := types.PowerOffVApp_Task{
This: p.Reference(),
Force: force,
}
res, err := methods.PowerOffVApp_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}
func (p VirtualApp) Suspend(ctx context.Context) (*Task, error) {
req := types.SuspendVApp_Task{
This: p.Reference(),
}
res, err := methods.SuspendVApp_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}
func (p VirtualApp) Clone(ctx context.Context, name string, target types.ManagedObjectReference, spec types.VAppCloneSpec) (*Task, error) {
req := types.CloneVApp_Task{
This: p.Reference(),
Name: name,
Target: target,
Spec: spec,
}
res, err := methods.CloneVApp_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}

View File

@@ -1,965 +0,0 @@
/*
Copyright (c) 2015-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.
*/
package object
import (
"errors"
"fmt"
"math/rand"
"path/filepath"
"reflect"
"regexp"
"sort"
"strings"
"github.com/vmware/govmomi/vim25/types"
)
// Type values for use in BootOrder
const (
DeviceTypeNone = "-"
DeviceTypeCdrom = "cdrom"
DeviceTypeDisk = "disk"
DeviceTypeEthernet = "ethernet"
DeviceTypeFloppy = "floppy"
)
// VirtualDeviceList provides helper methods for working with a list of virtual devices.
type VirtualDeviceList []types.BaseVirtualDevice
// SCSIControllerTypes are used for adding a new SCSI controller to a VM.
func SCSIControllerTypes() VirtualDeviceList {
// Return a mutable list of SCSI controller types, initialized with defaults.
return VirtualDeviceList([]types.BaseVirtualDevice{
&types.VirtualLsiLogicController{},
&types.VirtualBusLogicController{},
&types.ParaVirtualSCSIController{},
&types.VirtualLsiLogicSASController{},
}).Select(func(device types.BaseVirtualDevice) bool {
c := device.(types.BaseVirtualSCSIController).GetVirtualSCSIController()
c.SharedBus = types.VirtualSCSISharingNoSharing
c.BusNumber = -1
return true
})
}
// EthernetCardTypes are used for adding a new ethernet card to a VM.
func EthernetCardTypes() VirtualDeviceList {
return VirtualDeviceList([]types.BaseVirtualDevice{
&types.VirtualE1000{},
&types.VirtualE1000e{},
&types.VirtualVmxnet2{},
&types.VirtualVmxnet3{},
&types.VirtualVmxnet3Vrdma{},
&types.VirtualPCNet32{},
&types.VirtualSriovEthernetCard{},
}).Select(func(device types.BaseVirtualDevice) bool {
c := device.(types.BaseVirtualEthernetCard).GetVirtualEthernetCard()
c.GetVirtualDevice().Key = VirtualDeviceList{}.newRandomKey()
return true
})
}
// Select returns a new list containing all elements of the list for which the given func returns true.
func (l VirtualDeviceList) Select(f func(device types.BaseVirtualDevice) bool) VirtualDeviceList {
var found VirtualDeviceList
for _, device := range l {
if f(device) {
found = append(found, device)
}
}
return found
}
// SelectByType returns a new list with devices that are equal to or extend the given type.
func (l VirtualDeviceList) SelectByType(deviceType types.BaseVirtualDevice) VirtualDeviceList {
dtype := reflect.TypeOf(deviceType)
if dtype == nil {
return nil
}
dname := dtype.Elem().Name()
return l.Select(func(device types.BaseVirtualDevice) bool {
t := reflect.TypeOf(device)
if t == dtype {
return true
}
_, ok := t.Elem().FieldByName(dname)
return ok
})
}
// SelectByBackingInfo returns a new list with devices matching the given backing info.
// If the value of backing is nil, any device with a backing of the same type will be returned.
func (l VirtualDeviceList) SelectByBackingInfo(backing types.BaseVirtualDeviceBackingInfo) VirtualDeviceList {
t := reflect.TypeOf(backing)
return l.Select(func(device types.BaseVirtualDevice) bool {
db := device.GetVirtualDevice().Backing
if db == nil {
return false
}
if reflect.TypeOf(db) != t {
return false
}
if reflect.ValueOf(backing).IsNil() {
// selecting by backing type
return true
}
switch a := db.(type) {
case *types.VirtualEthernetCardNetworkBackingInfo:
b := backing.(*types.VirtualEthernetCardNetworkBackingInfo)
return a.DeviceName == b.DeviceName
case *types.VirtualEthernetCardDistributedVirtualPortBackingInfo:
b := backing.(*types.VirtualEthernetCardDistributedVirtualPortBackingInfo)
return a.Port.SwitchUuid == b.Port.SwitchUuid &&
a.Port.PortgroupKey == b.Port.PortgroupKey
case *types.VirtualEthernetCardOpaqueNetworkBackingInfo:
b := backing.(*types.VirtualEthernetCardOpaqueNetworkBackingInfo)
return a.OpaqueNetworkId == b.OpaqueNetworkId
case *types.VirtualDiskFlatVer2BackingInfo:
b := backing.(*types.VirtualDiskFlatVer2BackingInfo)
if a.Parent != nil && b.Parent != nil {
return a.Parent.FileName == b.Parent.FileName
}
return a.FileName == b.FileName
case *types.VirtualSerialPortURIBackingInfo:
b := backing.(*types.VirtualSerialPortURIBackingInfo)
return a.ServiceURI == b.ServiceURI
case types.BaseVirtualDeviceFileBackingInfo:
b := backing.(types.BaseVirtualDeviceFileBackingInfo)
return a.GetVirtualDeviceFileBackingInfo().FileName == b.GetVirtualDeviceFileBackingInfo().FileName
case *types.VirtualPCIPassthroughVmiopBackingInfo:
b := backing.(*types.VirtualPCIPassthroughVmiopBackingInfo)
return a.Vgpu == b.Vgpu
case *types.VirtualPCIPassthroughDynamicBackingInfo:
b := backing.(*types.VirtualPCIPassthroughDynamicBackingInfo)
if b.CustomLabel != "" && b.CustomLabel != a.CustomLabel {
return false
}
if len(b.AllowedDevice) == 0 {
return true
}
for _, x := range a.AllowedDevice {
for _, y := range b.AllowedDevice {
if x.DeviceId == y.DeviceId && x.VendorId == y.VendorId {
return true
}
}
}
return false
default:
return false
}
})
}
// Find returns the device matching the given name.
func (l VirtualDeviceList) Find(name string) types.BaseVirtualDevice {
for _, device := range l {
if l.Name(device) == name {
return device
}
}
return nil
}
// FindByKey returns the device matching the given key.
func (l VirtualDeviceList) FindByKey(key int32) types.BaseVirtualDevice {
for _, device := range l {
if device.GetVirtualDevice().Key == key {
return device
}
}
return nil
}
// FindIDEController will find the named IDE controller if given, otherwise will pick an available controller.
// An error is returned if the named controller is not found or not an IDE controller. Or, if name is not
// given and no available controller can be found.
func (l VirtualDeviceList) FindIDEController(name string) (*types.VirtualIDEController, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(*types.VirtualIDEController); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not an IDE controller", name)
}
c := l.PickController((*types.VirtualIDEController)(nil))
if c == nil {
return nil, errors.New("no available IDE controller")
}
return c.(*types.VirtualIDEController), nil
}
// CreateIDEController creates a new IDE controller.
func (l VirtualDeviceList) CreateIDEController() (types.BaseVirtualDevice, error) {
ide := &types.VirtualIDEController{}
ide.Key = l.NewKey()
return ide, nil
}
// FindSCSIController will find the named SCSI controller if given, otherwise will pick an available controller.
// An error is returned if the named controller is not found or not an SCSI controller. Or, if name is not
// given and no available controller can be found.
func (l VirtualDeviceList) FindSCSIController(name string) (*types.VirtualSCSIController, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(types.BaseVirtualSCSIController); ok {
return c.GetVirtualSCSIController(), nil
}
return nil, fmt.Errorf("%s is not an SCSI controller", name)
}
c := l.PickController((*types.VirtualSCSIController)(nil))
if c == nil {
return nil, errors.New("no available SCSI controller")
}
return c.(types.BaseVirtualSCSIController).GetVirtualSCSIController(), nil
}
// CreateSCSIController creates a new SCSI controller of type name if given, otherwise defaults to lsilogic.
func (l VirtualDeviceList) CreateSCSIController(name string) (types.BaseVirtualDevice, error) {
ctypes := SCSIControllerTypes()
if name == "" || name == "scsi" {
name = ctypes.Type(ctypes[0])
} else if name == "virtualscsi" {
name = "pvscsi" // ovf VirtualSCSI mapping
}
found := ctypes.Select(func(device types.BaseVirtualDevice) bool {
return l.Type(device) == name
})
if len(found) == 0 {
return nil, fmt.Errorf("unknown SCSI controller type '%s'", name)
}
c, ok := found[0].(types.BaseVirtualSCSIController)
if !ok {
return nil, fmt.Errorf("invalid SCSI controller type '%s'", name)
}
scsi := c.GetVirtualSCSIController()
scsi.BusNumber = l.newSCSIBusNumber()
scsi.Key = l.NewKey()
scsi.ScsiCtlrUnitNumber = 7
return c.(types.BaseVirtualDevice), nil
}
var scsiBusNumbers = []int{0, 1, 2, 3}
// newSCSIBusNumber returns the bus number to use for adding a new SCSI bus device.
// -1 is returned if there are no bus numbers available.
func (l VirtualDeviceList) newSCSIBusNumber() int32 {
var used []int
for _, d := range l.SelectByType((*types.VirtualSCSIController)(nil)) {
num := d.(types.BaseVirtualSCSIController).GetVirtualSCSIController().BusNumber
if num >= 0 {
used = append(used, int(num))
} // else caller is creating a new vm using SCSIControllerTypes
}
sort.Ints(used)
for i, n := range scsiBusNumbers {
if i == len(used) || n != used[i] {
return int32(n)
}
}
return -1
}
// FindNVMEController will find the named NVME controller if given, otherwise will pick an available controller.
// An error is returned if the named controller is not found or not an NVME controller. Or, if name is not
// given and no available controller can be found.
func (l VirtualDeviceList) FindNVMEController(name string) (*types.VirtualNVMEController, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(*types.VirtualNVMEController); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not an NVME controller", name)
}
c := l.PickController((*types.VirtualNVMEController)(nil))
if c == nil {
return nil, errors.New("no available NVME controller")
}
return c.(*types.VirtualNVMEController), nil
}
// CreateNVMEController creates a new NVMWE controller.
func (l VirtualDeviceList) CreateNVMEController() (types.BaseVirtualDevice, error) {
nvme := &types.VirtualNVMEController{}
nvme.BusNumber = l.newNVMEBusNumber()
nvme.Key = l.NewKey()
return nvme, nil
}
var nvmeBusNumbers = []int{0, 1, 2, 3}
// newNVMEBusNumber returns the bus number to use for adding a new NVME bus device.
// -1 is returned if there are no bus numbers available.
func (l VirtualDeviceList) newNVMEBusNumber() int32 {
var used []int
for _, d := range l.SelectByType((*types.VirtualNVMEController)(nil)) {
num := d.(types.BaseVirtualController).GetVirtualController().BusNumber
if num >= 0 {
used = append(used, int(num))
} // else caller is creating a new vm using NVMEControllerTypes
}
sort.Ints(used)
for i, n := range nvmeBusNumbers {
if i == len(used) || n != used[i] {
return int32(n)
}
}
return -1
}
// FindDiskController will find an existing ide or scsi disk controller.
func (l VirtualDeviceList) FindDiskController(name string) (types.BaseVirtualController, error) {
switch {
case name == "ide":
return l.FindIDEController("")
case name == "scsi" || name == "":
return l.FindSCSIController("")
case name == "nvme":
return l.FindNVMEController("")
default:
if c, ok := l.Find(name).(types.BaseVirtualController); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not a valid controller", name)
}
}
// PickController returns a controller of the given type(s).
// If no controllers are found or have no available slots, then nil is returned.
func (l VirtualDeviceList) PickController(kind types.BaseVirtualController) types.BaseVirtualController {
l = l.SelectByType(kind.(types.BaseVirtualDevice)).Select(func(device types.BaseVirtualDevice) bool {
num := len(device.(types.BaseVirtualController).GetVirtualController().Device)
switch device.(type) {
case types.BaseVirtualSCSIController:
return num < 15
case *types.VirtualIDEController:
return num < 2
case *types.VirtualNVMEController:
return num < 8
default:
return true
}
})
if len(l) == 0 {
return nil
}
return l[0].(types.BaseVirtualController)
}
// newUnitNumber returns the unit number to use for attaching a new device to the given controller.
func (l VirtualDeviceList) newUnitNumber(c types.BaseVirtualController) int32 {
units := make([]bool, 30)
switch sc := c.(type) {
case types.BaseVirtualSCSIController:
// The SCSI controller sits on its own bus
units[sc.GetVirtualSCSIController().ScsiCtlrUnitNumber] = true
}
key := c.GetVirtualController().Key
for _, device := range l {
d := device.GetVirtualDevice()
if d.ControllerKey == key && d.UnitNumber != nil {
units[int(*d.UnitNumber)] = true
}
}
for unit, used := range units {
if !used {
return int32(unit)
}
}
return -1
}
// NewKey returns the key to use for adding a new device to the device list.
// The device list we're working with here may not be complete (e.g. when
// we're only adding new devices), so any positive keys could conflict with device keys
// that are already in use. To avoid this type of conflict, we can use negative keys
// here, which will be resolved to positive keys by vSphere as the reconfiguration is done.
func (l VirtualDeviceList) NewKey() int32 {
var key int32 = -200
for _, device := range l {
d := device.GetVirtualDevice()
if d.Key < key {
key = d.Key
}
}
return key - 1
}
// AssignController assigns a device to a controller.
func (l VirtualDeviceList) AssignController(device types.BaseVirtualDevice, c types.BaseVirtualController) {
d := device.GetVirtualDevice()
d.ControllerKey = c.GetVirtualController().Key
d.UnitNumber = new(int32)
*d.UnitNumber = l.newUnitNumber(c)
if d.Key == 0 {
d.Key = l.newRandomKey()
}
}
// newRandomKey returns a random negative device key.
// The generated key can be used for devices you want to add so that it does not collide with existing ones.
func (l VirtualDeviceList) newRandomKey() int32 {
// NOTE: rand.Uint32 cannot be used here because conversion from uint32 to int32 may change the sign
key := rand.Int31() * -1
if key == 0 {
return -1
}
return key
}
// CreateDisk creates a new VirtualDisk device which can be added to a VM.
func (l VirtualDeviceList) CreateDisk(c types.BaseVirtualController, ds types.ManagedObjectReference, name string) *types.VirtualDisk {
// If name is not specified, one will be chosen for you.
// But if when given, make sure it ends in .vmdk, otherwise it will be treated as a directory.
if len(name) > 0 && filepath.Ext(name) != ".vmdk" {
name += ".vmdk"
}
device := &types.VirtualDisk{
VirtualDevice: types.VirtualDevice{
Backing: &types.VirtualDiskFlatVer2BackingInfo{
DiskMode: string(types.VirtualDiskModePersistent),
ThinProvisioned: types.NewBool(true),
VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
FileName: name,
Datastore: &ds,
},
},
},
}
l.AssignController(device, c)
return device
}
// ChildDisk creates a new VirtualDisk device, linked to the given parent disk, which can be added to a VM.
func (l VirtualDeviceList) ChildDisk(parent *types.VirtualDisk) *types.VirtualDisk {
disk := *parent
backing := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo)
p := new(DatastorePath)
p.FromString(backing.FileName)
p.Path = ""
// Use specified disk as parent backing to a new disk.
disk.Backing = &types.VirtualDiskFlatVer2BackingInfo{
VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
FileName: p.String(),
Datastore: backing.Datastore,
},
Parent: backing,
DiskMode: backing.DiskMode,
ThinProvisioned: backing.ThinProvisioned,
}
return &disk
}
func (l VirtualDeviceList) connectivity(device types.BaseVirtualDevice, v bool) error {
c := device.GetVirtualDevice().Connectable
if c == nil {
return fmt.Errorf("%s is not connectable", l.Name(device))
}
c.Connected = v
c.StartConnected = v
return nil
}
// Connect changes the device to connected, returns an error if the device is not connectable.
func (l VirtualDeviceList) Connect(device types.BaseVirtualDevice) error {
return l.connectivity(device, true)
}
// Disconnect changes the device to disconnected, returns an error if the device is not connectable.
func (l VirtualDeviceList) Disconnect(device types.BaseVirtualDevice) error {
return l.connectivity(device, false)
}
// FindCdrom finds a cdrom device with the given name, defaulting to the first cdrom device if any.
func (l VirtualDeviceList) FindCdrom(name string) (*types.VirtualCdrom, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(*types.VirtualCdrom); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not a cdrom device", name)
}
c := l.SelectByType((*types.VirtualCdrom)(nil))
if len(c) == 0 {
return nil, errors.New("no cdrom device found")
}
return c[0].(*types.VirtualCdrom), nil
}
// CreateCdrom creates a new VirtualCdrom device which can be added to a VM.
func (l VirtualDeviceList) CreateCdrom(c *types.VirtualIDEController) (*types.VirtualCdrom, error) {
device := &types.VirtualCdrom{}
l.AssignController(device, c)
l.setDefaultCdromBacking(device)
device.Connectable = &types.VirtualDeviceConnectInfo{
AllowGuestControl: true,
Connected: true,
StartConnected: true,
}
return device, nil
}
// InsertIso changes the cdrom device backing to use the given iso file.
func (l VirtualDeviceList) InsertIso(device *types.VirtualCdrom, iso string) *types.VirtualCdrom {
device.Backing = &types.VirtualCdromIsoBackingInfo{
VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
FileName: iso,
},
}
return device
}
// EjectIso removes the iso file based backing and replaces with the default cdrom backing.
func (l VirtualDeviceList) EjectIso(device *types.VirtualCdrom) *types.VirtualCdrom {
l.setDefaultCdromBacking(device)
return device
}
func (l VirtualDeviceList) setDefaultCdromBacking(device *types.VirtualCdrom) {
device.Backing = &types.VirtualCdromAtapiBackingInfo{
VirtualDeviceDeviceBackingInfo: types.VirtualDeviceDeviceBackingInfo{
DeviceName: fmt.Sprintf("%s-%d-%d", DeviceTypeCdrom, device.ControllerKey, device.UnitNumber),
UseAutoDetect: types.NewBool(false),
},
}
}
// FindFloppy finds a floppy device with the given name, defaulting to the first floppy device if any.
func (l VirtualDeviceList) FindFloppy(name string) (*types.VirtualFloppy, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(*types.VirtualFloppy); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not a floppy device", name)
}
c := l.SelectByType((*types.VirtualFloppy)(nil))
if len(c) == 0 {
return nil, errors.New("no floppy device found")
}
return c[0].(*types.VirtualFloppy), nil
}
// CreateFloppy creates a new VirtualFloppy device which can be added to a VM.
func (l VirtualDeviceList) CreateFloppy() (*types.VirtualFloppy, error) {
device := &types.VirtualFloppy{}
c := l.PickController((*types.VirtualSIOController)(nil))
if c == nil {
return nil, errors.New("no available SIO controller")
}
l.AssignController(device, c)
l.setDefaultFloppyBacking(device)
device.Connectable = &types.VirtualDeviceConnectInfo{
AllowGuestControl: true,
Connected: true,
StartConnected: true,
}
return device, nil
}
// InsertImg changes the floppy device backing to use the given img file.
func (l VirtualDeviceList) InsertImg(device *types.VirtualFloppy, img string) *types.VirtualFloppy {
device.Backing = &types.VirtualFloppyImageBackingInfo{
VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
FileName: img,
},
}
return device
}
// EjectImg removes the img file based backing and replaces with the default floppy backing.
func (l VirtualDeviceList) EjectImg(device *types.VirtualFloppy) *types.VirtualFloppy {
l.setDefaultFloppyBacking(device)
return device
}
func (l VirtualDeviceList) setDefaultFloppyBacking(device *types.VirtualFloppy) {
device.Backing = &types.VirtualFloppyDeviceBackingInfo{
VirtualDeviceDeviceBackingInfo: types.VirtualDeviceDeviceBackingInfo{
DeviceName: fmt.Sprintf("%s-%d", DeviceTypeFloppy, device.UnitNumber),
UseAutoDetect: types.NewBool(false),
},
}
}
// FindSerialPort finds a serial port device with the given name, defaulting to the first serial port device if any.
func (l VirtualDeviceList) FindSerialPort(name string) (*types.VirtualSerialPort, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(*types.VirtualSerialPort); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not a serial port device", name)
}
c := l.SelectByType((*types.VirtualSerialPort)(nil))
if len(c) == 0 {
return nil, errors.New("no serial port device found")
}
return c[0].(*types.VirtualSerialPort), nil
}
// CreateSerialPort creates a new VirtualSerialPort device which can be added to a VM.
func (l VirtualDeviceList) CreateSerialPort() (*types.VirtualSerialPort, error) {
device := &types.VirtualSerialPort{
YieldOnPoll: true,
}
c := l.PickController((*types.VirtualSIOController)(nil))
if c == nil {
return nil, errors.New("no available SIO controller")
}
l.AssignController(device, c)
l.setDefaultSerialPortBacking(device)
return device, nil
}
// ConnectSerialPort connects a serial port to a server or client uri.
func (l VirtualDeviceList) ConnectSerialPort(device *types.VirtualSerialPort, uri string, client bool, proxyuri string) *types.VirtualSerialPort {
if strings.HasPrefix(uri, "[") {
device.Backing = &types.VirtualSerialPortFileBackingInfo{
VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
FileName: uri,
},
}
return device
}
direction := types.VirtualDeviceURIBackingOptionDirectionServer
if client {
direction = types.VirtualDeviceURIBackingOptionDirectionClient
}
device.Backing = &types.VirtualSerialPortURIBackingInfo{
VirtualDeviceURIBackingInfo: types.VirtualDeviceURIBackingInfo{
Direction: string(direction),
ServiceURI: uri,
ProxyURI: proxyuri,
},
}
return device
}
// DisconnectSerialPort disconnects the serial port backing.
func (l VirtualDeviceList) DisconnectSerialPort(device *types.VirtualSerialPort) *types.VirtualSerialPort {
l.setDefaultSerialPortBacking(device)
return device
}
func (l VirtualDeviceList) setDefaultSerialPortBacking(device *types.VirtualSerialPort) {
device.Backing = &types.VirtualSerialPortURIBackingInfo{
VirtualDeviceURIBackingInfo: types.VirtualDeviceURIBackingInfo{
Direction: "client",
ServiceURI: "localhost:0",
},
}
}
// CreateEthernetCard creates a new VirtualEthernetCard of the given name name and initialized with the given backing.
func (l VirtualDeviceList) CreateEthernetCard(name string, backing types.BaseVirtualDeviceBackingInfo) (types.BaseVirtualDevice, error) {
ctypes := EthernetCardTypes()
if name == "" {
name = ctypes.deviceName(ctypes[0])
}
found := ctypes.Select(func(device types.BaseVirtualDevice) bool {
return l.deviceName(device) == name
})
if len(found) == 0 {
return nil, fmt.Errorf("unknown ethernet card type '%s'", name)
}
c, ok := found[0].(types.BaseVirtualEthernetCard)
if !ok {
return nil, fmt.Errorf("invalid ethernet card type '%s'", name)
}
c.GetVirtualEthernetCard().Backing = backing
return c.(types.BaseVirtualDevice), nil
}
// PrimaryMacAddress returns the MacAddress field of the primary VirtualEthernetCard
func (l VirtualDeviceList) PrimaryMacAddress() string {
eth0 := l.Find("ethernet-0")
if eth0 == nil {
return ""
}
return eth0.(types.BaseVirtualEthernetCard).GetVirtualEthernetCard().MacAddress
}
// convert a BaseVirtualDevice to a BaseVirtualMachineBootOptionsBootableDevice
var bootableDevices = map[string]func(device types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice{
DeviceTypeNone: func(types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice {
return &types.VirtualMachineBootOptionsBootableDevice{}
},
DeviceTypeCdrom: func(types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice {
return &types.VirtualMachineBootOptionsBootableCdromDevice{}
},
DeviceTypeDisk: func(d types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice {
return &types.VirtualMachineBootOptionsBootableDiskDevice{
DeviceKey: d.GetVirtualDevice().Key,
}
},
DeviceTypeEthernet: func(d types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice {
return &types.VirtualMachineBootOptionsBootableEthernetDevice{
DeviceKey: d.GetVirtualDevice().Key,
}
},
DeviceTypeFloppy: func(types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice {
return &types.VirtualMachineBootOptionsBootableFloppyDevice{}
},
}
// BootOrder returns a list of devices which can be used to set boot order via VirtualMachine.SetBootOptions.
// The order can be any of "ethernet", "cdrom", "floppy" or "disk" or by specific device name.
// A value of "-" will clear the existing boot order on the VC/ESX side.
func (l VirtualDeviceList) BootOrder(order []string) []types.BaseVirtualMachineBootOptionsBootableDevice {
var devices []types.BaseVirtualMachineBootOptionsBootableDevice
for _, name := range order {
if kind, ok := bootableDevices[name]; ok {
if name == DeviceTypeNone {
// Not covered in the API docs, nor obvious, but this clears the boot order on the VC/ESX side.
devices = append(devices, new(types.VirtualMachineBootOptionsBootableDevice))
continue
}
for _, device := range l {
if l.Type(device) == name {
devices = append(devices, kind(device))
}
}
continue
}
if d := l.Find(name); d != nil {
if kind, ok := bootableDevices[l.Type(d)]; ok {
devices = append(devices, kind(d))
}
}
}
return devices
}
// SelectBootOrder returns an ordered list of devices matching the given bootable device order
func (l VirtualDeviceList) SelectBootOrder(order []types.BaseVirtualMachineBootOptionsBootableDevice) VirtualDeviceList {
var devices VirtualDeviceList
for _, bd := range order {
for _, device := range l {
if kind, ok := bootableDevices[l.Type(device)]; ok {
if reflect.DeepEqual(kind(device), bd) {
devices = append(devices, device)
}
}
}
}
return devices
}
// TypeName returns the vmodl type name of the device
func (l VirtualDeviceList) TypeName(device types.BaseVirtualDevice) string {
dtype := reflect.TypeOf(device)
if dtype == nil {
return ""
}
return dtype.Elem().Name()
}
var deviceNameRegexp = regexp.MustCompile(`(?:Virtual)?(?:Machine)?(\w+?)(?:Card|EthernetCard|Device|Controller)?$`)
func (l VirtualDeviceList) deviceName(device types.BaseVirtualDevice) string {
name := "device"
typeName := l.TypeName(device)
m := deviceNameRegexp.FindStringSubmatch(typeName)
if len(m) == 2 {
name = strings.ToLower(m[1])
}
return name
}
// Type returns a human-readable name for the given device
func (l VirtualDeviceList) Type(device types.BaseVirtualDevice) string {
switch device.(type) {
case types.BaseVirtualEthernetCard:
return DeviceTypeEthernet
case *types.ParaVirtualSCSIController:
return "pvscsi"
case *types.VirtualLsiLogicSASController:
return "lsilogic-sas"
case *types.VirtualNVMEController:
return "nvme"
case *types.VirtualPrecisionClock:
return "clock"
default:
return l.deviceName(device)
}
}
// Name returns a stable, human-readable name for the given device
func (l VirtualDeviceList) Name(device types.BaseVirtualDevice) string {
var key string
var UnitNumber int32
d := device.GetVirtualDevice()
if d.UnitNumber != nil {
UnitNumber = *d.UnitNumber
}
dtype := l.Type(device)
switch dtype {
case DeviceTypeEthernet:
// Ethernet devices of UnitNumber 7-19 are non-SRIOV. Ethernet devices of
// UnitNumber 45-36 descending are SRIOV
if UnitNumber <= 45 && UnitNumber >= 36 {
key = fmt.Sprintf("sriov-%d", 45-UnitNumber)
} else {
key = fmt.Sprintf("%d", UnitNumber-7)
}
case DeviceTypeDisk:
key = fmt.Sprintf("%d-%d", d.ControllerKey, UnitNumber)
default:
key = fmt.Sprintf("%d", d.Key)
}
return fmt.Sprintf("%s-%s", dtype, key)
}
// ConfigSpec creates a virtual machine configuration spec for
// the specified operation, for the list of devices in the device list.
func (l VirtualDeviceList) ConfigSpec(op types.VirtualDeviceConfigSpecOperation) ([]types.BaseVirtualDeviceConfigSpec, error) {
var fop types.VirtualDeviceConfigSpecFileOperation
switch op {
case types.VirtualDeviceConfigSpecOperationAdd:
fop = types.VirtualDeviceConfigSpecFileOperationCreate
case types.VirtualDeviceConfigSpecOperationEdit:
fop = types.VirtualDeviceConfigSpecFileOperationReplace
case types.VirtualDeviceConfigSpecOperationRemove:
fop = types.VirtualDeviceConfigSpecFileOperationDestroy
default:
panic("unknown op")
}
var res []types.BaseVirtualDeviceConfigSpec
for _, device := range l {
config := &types.VirtualDeviceConfigSpec{
Device: device,
Operation: op,
FileOperation: diskFileOperation(op, fop, device),
}
res = append(res, config)
}
return res, nil
}

View File

@@ -1,227 +0,0 @@
/*
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.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type VirtualDiskManager struct {
Common
}
func NewVirtualDiskManager(c *vim25.Client) *VirtualDiskManager {
m := VirtualDiskManager{
Common: NewCommon(c, *c.ServiceContent.VirtualDiskManager),
}
return &m
}
// CopyVirtualDisk copies a virtual disk, performing conversions as specified in the spec.
func (m VirtualDiskManager) CopyVirtualDisk(
ctx context.Context,
sourceName string, sourceDatacenter *Datacenter,
destName string, destDatacenter *Datacenter,
destSpec *types.VirtualDiskSpec, force bool) (*Task, error) {
req := types.CopyVirtualDisk_Task{
This: m.Reference(),
SourceName: sourceName,
DestName: destName,
DestSpec: destSpec,
Force: types.NewBool(force),
}
if sourceDatacenter != nil {
ref := sourceDatacenter.Reference()
req.SourceDatacenter = &ref
}
if destDatacenter != nil {
ref := destDatacenter.Reference()
req.DestDatacenter = &ref
}
res, err := methods.CopyVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
// CreateVirtualDisk creates a new virtual disk.
func (m VirtualDiskManager) CreateVirtualDisk(
ctx context.Context,
name string, datacenter *Datacenter,
spec types.BaseVirtualDiskSpec) (*Task, error) {
req := types.CreateVirtualDisk_Task{
This: m.Reference(),
Name: name,
Spec: spec,
}
if datacenter != nil {
ref := datacenter.Reference()
req.Datacenter = &ref
}
res, err := methods.CreateVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
// MoveVirtualDisk moves a virtual disk.
func (m VirtualDiskManager) MoveVirtualDisk(
ctx context.Context,
sourceName string, sourceDatacenter *Datacenter,
destName string, destDatacenter *Datacenter,
force bool) (*Task, error) {
req := types.MoveVirtualDisk_Task{
This: m.Reference(),
SourceName: sourceName,
DestName: destName,
Force: types.NewBool(force),
}
if sourceDatacenter != nil {
ref := sourceDatacenter.Reference()
req.SourceDatacenter = &ref
}
if destDatacenter != nil {
ref := destDatacenter.Reference()
req.DestDatacenter = &ref
}
res, err := methods.MoveVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
// DeleteVirtualDisk deletes a virtual disk.
func (m VirtualDiskManager) DeleteVirtualDisk(ctx context.Context, name string, dc *Datacenter) (*Task, error) {
req := types.DeleteVirtualDisk_Task{
This: m.Reference(),
Name: name,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.DeleteVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
// InflateVirtualDisk inflates a virtual disk.
func (m VirtualDiskManager) InflateVirtualDisk(ctx context.Context, name string, dc *Datacenter) (*Task, error) {
req := types.InflateVirtualDisk_Task{
This: m.Reference(),
Name: name,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.InflateVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
// ShrinkVirtualDisk shrinks a virtual disk.
func (m VirtualDiskManager) ShrinkVirtualDisk(ctx context.Context, name string, dc *Datacenter, copy *bool) (*Task, error) {
req := types.ShrinkVirtualDisk_Task{
This: m.Reference(),
Name: name,
Copy: copy,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.ShrinkVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
// Queries virtual disk uuid
func (m VirtualDiskManager) QueryVirtualDiskUuid(ctx context.Context, name string, dc *Datacenter) (string, error) {
req := types.QueryVirtualDiskUuid{
This: m.Reference(),
Name: name,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.QueryVirtualDiskUuid(ctx, m.c, &req)
if err != nil {
return "", err
}
if res == nil {
return "", nil
}
return res.Returnval, nil
}
func (m VirtualDiskManager) SetVirtualDiskUuid(ctx context.Context, name string, dc *Datacenter, uuid string) error {
req := types.SetVirtualDiskUuid{
This: m.Reference(),
Name: name,
Uuid: uuid,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
_, err := methods.SetVirtualDiskUuid(ctx, m.c, &req)
return err
}

View File

@@ -1,166 +0,0 @@
/*
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.
*/
package object
import (
"context"
"reflect"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
func init() {
types.Add("ArrayOfVirtualDiskInfo", reflect.TypeOf((*arrayOfVirtualDiskInfo)(nil)).Elem())
types.Add("VirtualDiskInfo", reflect.TypeOf((*VirtualDiskInfo)(nil)).Elem())
}
type arrayOfVirtualDiskInfo struct {
VirtualDiskInfo []VirtualDiskInfo `xml:"VirtualDiskInfo,omitempty"`
}
type queryVirtualDiskInfoTaskRequest struct {
This types.ManagedObjectReference `xml:"_this"`
Name string `xml:"name"`
Datacenter *types.ManagedObjectReference `xml:"datacenter,omitempty"`
IncludeParents bool `xml:"includeParents"`
}
type queryVirtualDiskInfoTaskResponse struct {
Returnval types.ManagedObjectReference `xml:"returnval"`
}
type queryVirtualDiskInfoTaskBody struct {
Req *queryVirtualDiskInfoTaskRequest `xml:"urn:internalvim25 QueryVirtualDiskInfo_Task,omitempty"`
Res *queryVirtualDiskInfoTaskResponse `xml:"urn:vim25 QueryVirtualDiskInfo_TaskResponse,omitempty"`
InternalRes *queryVirtualDiskInfoTaskResponse `xml:"urn:internalvim25 QueryVirtualDiskInfo_TaskResponse,omitempty"`
Err *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *queryVirtualDiskInfoTaskBody) Fault() *soap.Fault { return b.Err }
func queryVirtualDiskInfoTask(ctx context.Context, r soap.RoundTripper, req *queryVirtualDiskInfoTaskRequest) (*queryVirtualDiskInfoTaskResponse, error) {
var reqBody, resBody queryVirtualDiskInfoTaskBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
if resBody.Res != nil {
return resBody.Res, nil
}
return resBody.InternalRes, nil
}
type VirtualDiskInfo struct {
Name string `xml:"unit>name"`
DiskType string `xml:"diskType"`
Parent string `xml:"parent,omitempty"`
}
func (m VirtualDiskManager) QueryVirtualDiskInfo(ctx context.Context, name string, dc *Datacenter, includeParents bool) ([]VirtualDiskInfo, error) {
req := queryVirtualDiskInfoTaskRequest{
This: m.Reference(),
Name: name,
IncludeParents: includeParents,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := queryVirtualDiskInfoTask(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
info, err := NewTask(m.Client(), res.Returnval).WaitForResult(ctx, nil)
if err != nil {
return nil, err
}
return info.Result.(arrayOfVirtualDiskInfo).VirtualDiskInfo, nil
}
type createChildDiskTaskRequest struct {
This types.ManagedObjectReference `xml:"_this"`
ChildName string `xml:"childName"`
ChildDatacenter *types.ManagedObjectReference `xml:"childDatacenter,omitempty"`
ParentName string `xml:"parentName"`
ParentDatacenter *types.ManagedObjectReference `xml:"parentDatacenter,omitempty"`
IsLinkedClone bool `xml:"isLinkedClone"`
}
type createChildDiskTaskResponse struct {
Returnval types.ManagedObjectReference `xml:"returnval"`
}
type createChildDiskTaskBody struct {
Req *createChildDiskTaskRequest `xml:"urn:internalvim25 CreateChildDisk_Task,omitempty"`
Res *createChildDiskTaskResponse `xml:"urn:vim25 CreateChildDisk_TaskResponse,omitempty"`
InternalRes *createChildDiskTaskResponse `xml:"urn:internalvim25 CreateChildDisk_TaskResponse,omitempty"`
Err *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *createChildDiskTaskBody) Fault() *soap.Fault { return b.Err }
func createChildDiskTask(ctx context.Context, r soap.RoundTripper, req *createChildDiskTaskRequest) (*createChildDiskTaskResponse, error) {
var reqBody, resBody createChildDiskTaskBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
if resBody.Res != nil {
return resBody.Res, nil // vim-version <= 6.5
}
return resBody.InternalRes, nil // vim-version >= 6.7
}
func (m VirtualDiskManager) CreateChildDisk(ctx context.Context, parent string, pdc *Datacenter, name string, dc *Datacenter, linked bool) (*Task, error) {
req := createChildDiskTaskRequest{
This: m.Reference(),
ChildName: name,
ParentName: parent,
IsLinkedClone: linked,
}
if dc != nil {
ref := dc.Reference()
req.ChildDatacenter = &ref
}
if pdc != nil {
ref := pdc.Reference()
req.ParentDatacenter = &ref
}
res, err := createChildDiskTask(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(m.Client(), res.Returnval), nil
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,25 +0,0 @@
/*
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.
*/
package object
type VmwareDistributedVirtualSwitch struct {
DistributedVirtualSwitch
}
func (s VmwareDistributedVirtualSwitch) GetInventoryPath() string {
return s.InventoryPath
}

View File

@@ -1,128 +0,0 @@
/*
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.
*/
package ovf
import (
"github.com/vmware/govmomi/vim25/types"
)
/*
Source: http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2.24.0/CIM_VirtualSystemSettingData.xsd
*/
type CIMVirtualSystemSettingData struct {
ElementName string `xml:"ElementName"`
InstanceID string `xml:"InstanceID"`
AutomaticRecoveryAction *uint8 `xml:"AutomaticRecoveryAction"`
AutomaticShutdownAction *uint8 `xml:"AutomaticShutdownAction"`
AutomaticStartupAction *uint8 `xml:"AutomaticStartupAction"`
AutomaticStartupActionDelay *string `xml:"AutomaticStartupActionDelay>Interval"`
AutomaticStartupActionSequenceNumber *uint16 `xml:"AutomaticStartupActionSequenceNumber"`
Caption *string `xml:"Caption"`
ConfigurationDataRoot *string `xml:"ConfigurationDataRoot"`
ConfigurationFile *string `xml:"ConfigurationFile"`
ConfigurationID *string `xml:"ConfigurationID"`
CreationTime *string `xml:"CreationTime"`
Description *string `xml:"Description"`
LogDataRoot *string `xml:"LogDataRoot"`
Notes []string `xml:"Notes"`
RecoveryFile *string `xml:"RecoveryFile"`
SnapshotDataRoot *string `xml:"SnapshotDataRoot"`
SuspendDataRoot *string `xml:"SuspendDataRoot"`
SwapFileDataRoot *string `xml:"SwapFileDataRoot"`
VirtualSystemIdentifier *string `xml:"VirtualSystemIdentifier"`
VirtualSystemType *string `xml:"VirtualSystemType"`
}
/*
Source: http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2.24.0/CIM_ResourceAllocationSettingData.xsd
*/
type CIMResourceAllocationSettingData struct {
ElementName string `xml:"ElementName"`
InstanceID string `xml:"InstanceID"`
ResourceType *uint16 `xml:"ResourceType"`
OtherResourceType *string `xml:"OtherResourceType"`
ResourceSubType *string `xml:"ResourceSubType"`
AddressOnParent *string `xml:"AddressOnParent"`
Address *string `xml:"Address"`
AllocationUnits *string `xml:"AllocationUnits"`
AutomaticAllocation *bool `xml:"AutomaticAllocation"`
AutomaticDeallocation *bool `xml:"AutomaticDeallocation"`
Caption *string `xml:"Caption"`
Connection []string `xml:"Connection"`
ConsumerVisibility *uint16 `xml:"ConsumerVisibility"`
Description *string `xml:"Description"`
HostResource []string `xml:"HostResource"`
Limit *uint64 `xml:"Limit"`
MappingBehavior *uint `xml:"MappingBehavior"`
Parent *string `xml:"Parent"`
PoolID *string `xml:"PoolID"`
Reservation *uint64 `xml:"Reservation"`
VirtualQuantity *uint `xml:"VirtualQuantity"`
VirtualQuantityUnits *string `xml:"VirtualQuantityUnits"`
Weight *uint `xml:"Weight"`
}
/*
Source: http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2.24.0/CIM_StorageAllocationSettingData.xsd
*/
type CIMStorageAllocationSettingData struct {
ElementName string `xml:"ElementName"`
InstanceID string `xml:"InstanceID"`
ResourceType *uint16 `xml:"ResourceType"`
OtherResourceType *string `xml:"OtherResourceType"`
ResourceSubType *string `xml:"ResourceSubType"`
Access *uint16 `xml:"Access"`
Address *string `xml:"Address"`
AddressOnParent *string `xml:"AddressOnParent"`
AllocationUnits *string `xml:"AllocationUnits"`
AutomaticAllocation *bool `xml:"AutomaticAllocation"`
AutomaticDeallocation *bool `xml:"AutomaticDeallocation"`
Caption *string `xml:"Caption"`
ChangeableType *uint16 `xml:"ChangeableType"`
ComponentSetting []types.AnyType `xml:"ComponentSetting"`
ConfigurationName *string `xml:"ConfigurationName"`
Connection []string `xml:"Connection"`
ConsumerVisibility *uint16 `xml:"ConsumerVisibility"`
Description *string `xml:"Description"`
Generation *uint64 `xml:"Generation"`
HostExtentName *string `xml:"HostExtentName"`
HostExtentNameFormat *uint16 `xml:"HostExtentNameFormat"`
HostExtentNameNamespace *uint16 `xml:"HostExtentNameNamespace"`
HostExtentStartingAddress *uint64 `xml:"HostExtentStartingAddress"`
HostResource []string `xml:"HostResource"`
HostResourceBlockSize *uint64 `xml:"HostResourceBlockSize"`
Limit *uint64 `xml:"Limit"`
MappingBehavior *uint `xml:"MappingBehavior"`
OtherHostExtentNameFormat *string `xml:"OtherHostExtentNameFormat"`
OtherHostExtentNameNamespace *string `xml:"OtherHostExtentNameNamespace"`
Parent *string `xml:"Parent"`
PoolID *string `xml:"PoolID"`
Reservation *uint64 `xml:"Reservation"`
SoID *string `xml:"SoID"`
SoOrgID *string `xml:"SoOrgID"`
VirtualQuantity *uint `xml:"VirtualQuantity"`
VirtualQuantityUnits *string `xml:"VirtualQuantityUnits"`
VirtualResourceBlockSize *uint64 `xml:"VirtualResourceBlockSize"`
Weight *uint `xml:"Weight"`
}

View File

@@ -1,25 +0,0 @@
/*
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.
*/
/*
Package ovf provides functionality to unmarshal and inspect the structure
of an OVF file. It is not a complete implementation of the specification and
is intended to be used to import virtual infrastructure into vSphere.
For a complete specification of the OVF standard, refer to:
https://www.dmtf.org/sites/default/files/standards/documents/DSP0243_2.1.0.pdf
*/
package ovf

View File

@@ -1,99 +0,0 @@
/*
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.
*/
package ovf
import (
"bytes"
"fmt"
"github.com/vmware/govmomi/vim25/xml"
)
const (
ovfEnvHeader = `<Environment
xmlns="http://schemas.dmtf.org/ovf/environment/1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:oe="http://schemas.dmtf.org/ovf/environment/1"
xmlns:ve="http://www.vmware.com/schema/ovfenv"
oe:id=""
ve:esxId="%s">`
ovfEnvPlatformSection = `<PlatformSection>
<Kind>%s</Kind>
<Version>%s</Version>
<Vendor>%s</Vendor>
<Locale>%s</Locale>
</PlatformSection>`
ovfEnvPropertyHeader = `<PropertySection>`
ovfEnvPropertyEntry = `<Property oe:key="%s" oe:value="%s"/>`
ovfEnvPropertyFooter = `</PropertySection>`
ovfEnvFooter = `</Environment>`
)
type Env struct {
XMLName xml.Name `xml:"http://schemas.dmtf.org/ovf/environment/1 Environment"`
ID string `xml:"id,attr"`
EsxID string `xml:"http://www.vmware.com/schema/ovfenv esxId,attr"`
Platform *PlatformSection `xml:"PlatformSection"`
Property *PropertySection `xml:"PropertySection"`
}
type PlatformSection struct {
Kind string `xml:"Kind"`
Version string `xml:"Version"`
Vendor string `xml:"Vendor"`
Locale string `xml:"Locale"`
}
type PropertySection struct {
Properties []EnvProperty `xml:"Property"`
}
type EnvProperty struct {
Key string `xml:"key,attr"`
Value string `xml:"value,attr"`
}
// Marshal marshals Env to xml by using xml.Marshal.
func (e Env) Marshal() (string, error) {
x, err := xml.Marshal(e)
if err != nil {
return "", err
}
return fmt.Sprintf("%s%s", xml.Header, x), nil
}
// MarshalManual manually marshals Env to xml suitable for a vApp guest.
// It exists to overcome the lack of expressiveness in Go's XML namespaces.
func (e Env) MarshalManual() string {
var buffer bytes.Buffer
buffer.WriteString(xml.Header)
buffer.WriteString(fmt.Sprintf(ovfEnvHeader, e.EsxID))
buffer.WriteString(fmt.Sprintf(ovfEnvPlatformSection, e.Platform.Kind, e.Platform.Version, e.Platform.Vendor, e.Platform.Locale))
buffer.WriteString(fmt.Sprint(ovfEnvPropertyHeader))
for _, p := range e.Property.Properties {
buffer.WriteString(fmt.Sprintf(ovfEnvPropertyEntry, p.Key, p.Value))
}
buffer.WriteString(fmt.Sprint(ovfEnvPropertyFooter))
buffer.WriteString(fmt.Sprint(ovfEnvFooter))
return buffer.String()
}

View File

@@ -1,208 +0,0 @@
/*
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.
*/
package ovf
type Envelope struct {
References []File `xml:"References>File"`
// Package level meta-data
Annotation *AnnotationSection `xml:"AnnotationSection"`
Product *ProductSection `xml:"ProductSection"`
Network *NetworkSection `xml:"NetworkSection"`
Disk *DiskSection `xml:"DiskSection"`
OperatingSystem *OperatingSystemSection `xml:"OperatingSystemSection"`
Eula *EulaSection `xml:"EulaSection"`
VirtualHardware *VirtualHardwareSection `xml:"VirtualHardwareSection"`
ResourceAllocation *ResourceAllocationSection `xml:"ResourceAllocationSection"`
DeploymentOption *DeploymentOptionSection `xml:"DeploymentOptionSection"`
// Content: A VirtualSystem or a VirtualSystemCollection
VirtualSystem *VirtualSystem `xml:"VirtualSystem"`
}
type VirtualSystem struct {
Content
Annotation []AnnotationSection `xml:"AnnotationSection"`
Product []ProductSection `xml:"ProductSection"`
OperatingSystem []OperatingSystemSection `xml:"OperatingSystemSection"`
Eula []EulaSection `xml:"EulaSection"`
VirtualHardware []VirtualHardwareSection `xml:"VirtualHardwareSection"`
}
type File struct {
ID string `xml:"id,attr"`
Href string `xml:"href,attr"`
Size uint `xml:"size,attr"`
Compression *string `xml:"compression,attr"`
ChunkSize *int `xml:"chunkSize,attr"`
}
type Content struct {
ID string `xml:"id,attr"`
Info string `xml:"Info"`
Name *string `xml:"Name"`
}
type Section struct {
Required *bool `xml:"required,attr"`
Info string `xml:"Info"`
}
type AnnotationSection struct {
Section
Annotation string `xml:"Annotation"`
}
type ProductSection struct {
Section
Class *string `xml:"class,attr"`
Instance *string `xml:"instance,attr"`
Product string `xml:"Product"`
Vendor string `xml:"Vendor"`
Version string `xml:"Version"`
FullVersion string `xml:"FullVersion"`
ProductURL string `xml:"ProductUrl"`
VendorURL string `xml:"VendorUrl"`
AppURL string `xml:"AppUrl"`
Property []Property `xml:"Property"`
}
type Property struct {
Key string `xml:"key,attr"`
Type string `xml:"type,attr"`
Qualifiers *string `xml:"qualifiers,attr"`
UserConfigurable *bool `xml:"userConfigurable,attr"`
Default *string `xml:"value,attr"`
Password *bool `xml:"password,attr"`
Label *string `xml:"Label"`
Description *string `xml:"Description"`
Values []PropertyConfigurationValue `xml:"Value"`
}
type PropertyConfigurationValue struct {
Value string `xml:"value,attr"`
Configuration *string `xml:"configuration,attr"`
}
type NetworkSection struct {
Section
Networks []Network `xml:"Network"`
}
type Network struct {
Name string `xml:"name,attr"`
Description string `xml:"Description"`
}
type DiskSection struct {
Section
Disks []VirtualDiskDesc `xml:"Disk"`
}
type VirtualDiskDesc struct {
DiskID string `xml:"diskId,attr"`
FileRef *string `xml:"fileRef,attr"`
Capacity string `xml:"capacity,attr"`
CapacityAllocationUnits *string `xml:"capacityAllocationUnits,attr"`
Format *string `xml:"format,attr"`
PopulatedSize *int `xml:"populatedSize,attr"`
ParentRef *string `xml:"parentRef,attr"`
}
type OperatingSystemSection struct {
Section
ID int16 `xml:"id,attr"`
Version *string `xml:"version,attr"`
OSType *string `xml:"osType,attr"`
Description *string `xml:"Description"`
}
type EulaSection struct {
Section
License string `xml:"License"`
}
type Config struct {
Required *bool `xml:"required,attr"`
Key string `xml:"key,attr"`
Value string `xml:"value,attr"`
}
type VirtualHardwareSection struct {
Section
ID *string `xml:"id,attr"`
Transport *string `xml:"transport,attr"`
System *VirtualSystemSettingData `xml:"System"`
Item []ResourceAllocationSettingData `xml:"Item"`
StorageItem []StorageAllocationSettingData `xml:"StorageItem"`
Config []Config `xml:"Config"`
ExtraConfig []Config `xml:"ExtraConfig"`
}
type VirtualSystemSettingData struct {
CIMVirtualSystemSettingData
}
type ResourceAllocationSettingData struct {
CIMResourceAllocationSettingData
Required *bool `xml:"required,attr"`
Configuration *string `xml:"configuration,attr"`
Bound *string `xml:"bound,attr"`
}
type StorageAllocationSettingData struct {
CIMStorageAllocationSettingData
Required *bool `xml:"required,attr"`
Configuration *string `xml:"configuration,attr"`
Bound *string `xml:"bound,attr"`
}
type ResourceAllocationSection struct {
Section
Item []ResourceAllocationSettingData `xml:"Item"`
}
type DeploymentOptionSection struct {
Section
Configuration []DeploymentOptionConfiguration `xml:"Configuration"`
}
type DeploymentOptionConfiguration struct {
ID string `xml:"id,attr"`
Default *bool `xml:"default,attr"`
Label string `xml:"Label"`
Description string `xml:"Description"`
}

View File

@@ -1,103 +0,0 @@
/*
Copyright (c) 2015-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.
*/
package ovf
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type Manager struct {
types.ManagedObjectReference
c *vim25.Client
}
func NewManager(c *vim25.Client) *Manager {
return &Manager{*c.ServiceContent.OvfManager, c}
}
// CreateDescriptor wraps methods.CreateDescriptor
func (m *Manager) CreateDescriptor(ctx context.Context, obj mo.Reference, cdp types.OvfCreateDescriptorParams) (*types.OvfCreateDescriptorResult, error) {
req := types.CreateDescriptor{
This: m.Reference(),
Obj: obj.Reference(),
Cdp: cdp,
}
res, err := methods.CreateDescriptor(ctx, m.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
// CreateImportSpec wraps methods.CreateImportSpec
func (m *Manager) CreateImportSpec(ctx context.Context, ovfDescriptor string, resourcePool mo.Reference, datastore mo.Reference, cisp types.OvfCreateImportSpecParams) (*types.OvfCreateImportSpecResult, error) {
req := types.CreateImportSpec{
This: m.Reference(),
OvfDescriptor: ovfDescriptor,
ResourcePool: resourcePool.Reference(),
Datastore: datastore.Reference(),
Cisp: cisp,
}
res, err := methods.CreateImportSpec(ctx, m.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
// ParseDescriptor wraps methods.ParseDescriptor
func (m *Manager) ParseDescriptor(ctx context.Context, ovfDescriptor string, pdp types.OvfParseDescriptorParams) (*types.OvfParseDescriptorResult, error) {
req := types.ParseDescriptor{
This: m.Reference(),
OvfDescriptor: ovfDescriptor,
Pdp: pdp,
}
res, err := methods.ParseDescriptor(ctx, m.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
// ValidateHost wraps methods.ValidateHost
func (m *Manager) ValidateHost(ctx context.Context, ovfDescriptor string, host mo.Reference, vhp types.OvfValidateHostParams) (*types.OvfValidateHostResult, error) {
req := types.ValidateHost{
This: m.Reference(),
OvfDescriptor: ovfDescriptor,
Host: host.Reference(),
Vhp: vhp,
}
res, err := methods.ValidateHost(ctx, m.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}

View File

@@ -1,35 +0,0 @@
/*
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.
*/
package ovf
import (
"io"
"github.com/vmware/govmomi/vim25/xml"
)
func Unmarshal(r io.Reader) (*Envelope, error) {
var e Envelope
dec := xml.NewDecoder(r)
err := dec.Decode(&e)
if err != nil {
return nil, err
}
return &e, nil
}

View File

@@ -1,287 +0,0 @@
/*
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.
*/
package pbm
import (
"context"
"fmt"
"github.com/vmware/govmomi/pbm/methods"
"github.com/vmware/govmomi/pbm/types"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/soap"
vim "github.com/vmware/govmomi/vim25/types"
)
const (
Namespace = "pbm"
Path = "/pbm"
)
var (
ServiceInstance = vim.ManagedObjectReference{
Type: "PbmServiceInstance",
Value: "ServiceInstance",
}
)
type Client struct {
*soap.Client
ServiceContent types.PbmServiceInstanceContent
RoundTripper soap.RoundTripper
}
func NewClient(ctx context.Context, c *vim25.Client) (*Client, error) {
sc := c.Client.NewServiceClient(Path, Namespace)
req := types.PbmRetrieveServiceContent{
This: ServiceInstance,
}
res, err := methods.PbmRetrieveServiceContent(ctx, sc, &req)
if err != nil {
return nil, err
}
return &Client{sc, res.Returnval, sc}, nil
}
// RoundTrip dispatches to the RoundTripper field.
func (c *Client) RoundTrip(ctx context.Context, req, res soap.HasFault) error {
return c.RoundTripper.RoundTrip(ctx, req, res)
}
func (c *Client) QueryProfile(ctx context.Context, rtype types.PbmProfileResourceType, category string) ([]types.PbmProfileId, error) {
req := types.PbmQueryProfile{
This: c.ServiceContent.ProfileManager,
ResourceType: rtype,
ProfileCategory: category,
}
res, err := methods.PbmQueryProfile(ctx, c, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (c *Client) RetrieveContent(ctx context.Context, ids []types.PbmProfileId) ([]types.BasePbmProfile, error) {
req := types.PbmRetrieveContent{
This: c.ServiceContent.ProfileManager,
ProfileIds: ids,
}
res, err := methods.PbmRetrieveContent(ctx, c, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
type PlacementCompatibilityResult []types.PbmPlacementCompatibilityResult
func (c *Client) CheckRequirements(ctx context.Context, hubs []types.PbmPlacementHub, ref *types.PbmServerObjectRef, preq []types.BasePbmPlacementRequirement) (PlacementCompatibilityResult, error) {
req := types.PbmCheckRequirements{
This: c.ServiceContent.PlacementSolver,
HubsToSearch: hubs,
PlacementSubjectRef: ref,
PlacementSubjectRequirement: preq,
}
res, err := methods.PbmCheckRequirements(ctx, c, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (l PlacementCompatibilityResult) CompatibleDatastores() []types.PbmPlacementHub {
var compatibleDatastores []types.PbmPlacementHub
for _, res := range l {
if len(res.Error) == 0 {
compatibleDatastores = append(compatibleDatastores, res.Hub)
}
}
return compatibleDatastores
}
func (l PlacementCompatibilityResult) NonCompatibleDatastores() []types.PbmPlacementHub {
var nonCompatibleDatastores []types.PbmPlacementHub
for _, res := range l {
if len(res.Error) > 0 {
nonCompatibleDatastores = append(nonCompatibleDatastores, res.Hub)
}
}
return nonCompatibleDatastores
}
func (c *Client) CreateProfile(ctx context.Context, capabilityProfileCreateSpec types.PbmCapabilityProfileCreateSpec) (*types.PbmProfileId, error) {
req := types.PbmCreate{
This: c.ServiceContent.ProfileManager,
CreateSpec: capabilityProfileCreateSpec,
}
res, err := methods.PbmCreate(ctx, c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (c *Client) UpdateProfile(ctx context.Context, id types.PbmProfileId, updateSpec types.PbmCapabilityProfileUpdateSpec) error {
req := types.PbmUpdate{
This: c.ServiceContent.ProfileManager,
ProfileId: id,
UpdateSpec: updateSpec,
}
_, err := methods.PbmUpdate(ctx, c, &req)
if err != nil {
return err
}
return nil
}
func (c *Client) DeleteProfile(ctx context.Context, ids []types.PbmProfileId) ([]types.PbmProfileOperationOutcome, error) {
req := types.PbmDelete{
This: c.ServiceContent.ProfileManager,
ProfileId: ids,
}
res, err := methods.PbmDelete(ctx, c, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (c *Client) QueryAssociatedEntity(ctx context.Context, id types.PbmProfileId, entityType string) ([]types.PbmServerObjectRef, error) {
req := types.PbmQueryAssociatedEntity{
This: c.ServiceContent.ProfileManager,
Profile: id,
EntityType: entityType,
}
res, err := methods.PbmQueryAssociatedEntity(ctx, c, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (c *Client) QueryAssociatedEntities(ctx context.Context, ids []types.PbmProfileId) ([]types.PbmQueryProfileResult, error) {
req := types.PbmQueryAssociatedEntities{
This: c.ServiceContent.ProfileManager,
Profiles: ids,
}
res, err := methods.PbmQueryAssociatedEntities(ctx, c, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (c *Client) ProfileIDByName(ctx context.Context, profileName string) (string, error) {
resourceType := types.PbmProfileResourceType{
ResourceType: string(types.PbmProfileResourceTypeEnumSTORAGE),
}
category := types.PbmProfileCategoryEnumREQUIREMENT
ids, err := c.QueryProfile(ctx, resourceType, string(category))
if err != nil {
return "", err
}
profiles, err := c.RetrieveContent(ctx, ids)
if err != nil {
return "", err
}
for i := range profiles {
profile := profiles[i].GetPbmProfile()
if profile.Name == profileName {
return profile.ProfileId.UniqueId, nil
}
}
return "", fmt.Errorf("no pbm profile found with name: %q", profileName)
}
func (c *Client) FetchCapabilityMetadata(ctx context.Context, rtype *types.PbmProfileResourceType, vendorUuid string) ([]types.PbmCapabilityMetadataPerCategory, error) {
req := types.PbmFetchCapabilityMetadata{
This: c.ServiceContent.ProfileManager,
ResourceType: rtype,
VendorUuid: vendorUuid,
}
res, err := methods.PbmFetchCapabilityMetadata(ctx, c, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (c *Client) FetchComplianceResult(ctx context.Context, entities []types.PbmServerObjectRef) ([]types.PbmComplianceResult, error) {
req := types.PbmFetchComplianceResult{
This: c.ServiceContent.ComplianceManager,
Entities: entities,
}
res, err := methods.PbmFetchComplianceResult(ctx, c, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
// GetProfileNameByID gets storage profile name by ID
func (c *Client) GetProfileNameByID(ctx context.Context, profileID string) (string, error) {
resourceType := types.PbmProfileResourceType{
ResourceType: string(types.PbmProfileResourceTypeEnumSTORAGE),
}
category := types.PbmProfileCategoryEnumREQUIREMENT
ids, err := c.QueryProfile(ctx, resourceType, string(category))
if err != nil {
return "", err
}
profiles, err := c.RetrieveContent(ctx, ids)
if err != nil {
return "", err
}
for i := range profiles {
profile := profiles[i].GetPbmProfile()
if profile.ProfileId.UniqueId == profileID {
return profile.Name, nil
}
}
return "", fmt.Errorf("no pbm profile found with id: %q", profileID)
}

View File

@@ -1,664 +0,0 @@
/*
Copyright (c) 2014-2022 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.
*/
package methods
import (
"context"
"github.com/vmware/govmomi/pbm/types"
"github.com/vmware/govmomi/vim25/soap"
)
type PbmAssignDefaultRequirementProfileBody struct {
Req *types.PbmAssignDefaultRequirementProfile `xml:"urn:pbm PbmAssignDefaultRequirementProfile,omitempty"`
Res *types.PbmAssignDefaultRequirementProfileResponse `xml:"urn:pbm PbmAssignDefaultRequirementProfileResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmAssignDefaultRequirementProfileBody) Fault() *soap.Fault { return b.Fault_ }
func PbmAssignDefaultRequirementProfile(ctx context.Context, r soap.RoundTripper, req *types.PbmAssignDefaultRequirementProfile) (*types.PbmAssignDefaultRequirementProfileResponse, error) {
var reqBody, resBody PbmAssignDefaultRequirementProfileBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmCheckCompatibilityBody struct {
Req *types.PbmCheckCompatibility `xml:"urn:pbm PbmCheckCompatibility,omitempty"`
Res *types.PbmCheckCompatibilityResponse `xml:"urn:pbm PbmCheckCompatibilityResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmCheckCompatibilityBody) Fault() *soap.Fault { return b.Fault_ }
func PbmCheckCompatibility(ctx context.Context, r soap.RoundTripper, req *types.PbmCheckCompatibility) (*types.PbmCheckCompatibilityResponse, error) {
var reqBody, resBody PbmCheckCompatibilityBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmCheckCompatibilityWithSpecBody struct {
Req *types.PbmCheckCompatibilityWithSpec `xml:"urn:pbm PbmCheckCompatibilityWithSpec,omitempty"`
Res *types.PbmCheckCompatibilityWithSpecResponse `xml:"urn:pbm PbmCheckCompatibilityWithSpecResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmCheckCompatibilityWithSpecBody) Fault() *soap.Fault { return b.Fault_ }
func PbmCheckCompatibilityWithSpec(ctx context.Context, r soap.RoundTripper, req *types.PbmCheckCompatibilityWithSpec) (*types.PbmCheckCompatibilityWithSpecResponse, error) {
var reqBody, resBody PbmCheckCompatibilityWithSpecBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmCheckComplianceBody struct {
Req *types.PbmCheckCompliance `xml:"urn:pbm PbmCheckCompliance,omitempty"`
Res *types.PbmCheckComplianceResponse `xml:"urn:pbm PbmCheckComplianceResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmCheckComplianceBody) Fault() *soap.Fault { return b.Fault_ }
func PbmCheckCompliance(ctx context.Context, r soap.RoundTripper, req *types.PbmCheckCompliance) (*types.PbmCheckComplianceResponse, error) {
var reqBody, resBody PbmCheckComplianceBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmCheckRequirementsBody struct {
Req *types.PbmCheckRequirements `xml:"urn:pbm PbmCheckRequirements,omitempty"`
Res *types.PbmCheckRequirementsResponse `xml:"urn:pbm PbmCheckRequirementsResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmCheckRequirementsBody) Fault() *soap.Fault { return b.Fault_ }
func PbmCheckRequirements(ctx context.Context, r soap.RoundTripper, req *types.PbmCheckRequirements) (*types.PbmCheckRequirementsResponse, error) {
var reqBody, resBody PbmCheckRequirementsBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmCheckRollupComplianceBody struct {
Req *types.PbmCheckRollupCompliance `xml:"urn:pbm PbmCheckRollupCompliance,omitempty"`
Res *types.PbmCheckRollupComplianceResponse `xml:"urn:pbm PbmCheckRollupComplianceResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmCheckRollupComplianceBody) Fault() *soap.Fault { return b.Fault_ }
func PbmCheckRollupCompliance(ctx context.Context, r soap.RoundTripper, req *types.PbmCheckRollupCompliance) (*types.PbmCheckRollupComplianceResponse, error) {
var reqBody, resBody PbmCheckRollupComplianceBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmCreateBody struct {
Req *types.PbmCreate `xml:"urn:pbm PbmCreate,omitempty"`
Res *types.PbmCreateResponse `xml:"urn:pbm PbmCreateResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmCreateBody) Fault() *soap.Fault { return b.Fault_ }
func PbmCreate(ctx context.Context, r soap.RoundTripper, req *types.PbmCreate) (*types.PbmCreateResponse, error) {
var reqBody, resBody PbmCreateBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmDeleteBody struct {
Req *types.PbmDelete `xml:"urn:pbm PbmDelete,omitempty"`
Res *types.PbmDeleteResponse `xml:"urn:pbm PbmDeleteResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmDeleteBody) Fault() *soap.Fault { return b.Fault_ }
func PbmDelete(ctx context.Context, r soap.RoundTripper, req *types.PbmDelete) (*types.PbmDeleteResponse, error) {
var reqBody, resBody PbmDeleteBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmFetchCapabilityMetadataBody struct {
Req *types.PbmFetchCapabilityMetadata `xml:"urn:pbm PbmFetchCapabilityMetadata,omitempty"`
Res *types.PbmFetchCapabilityMetadataResponse `xml:"urn:pbm PbmFetchCapabilityMetadataResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmFetchCapabilityMetadataBody) Fault() *soap.Fault { return b.Fault_ }
func PbmFetchCapabilityMetadata(ctx context.Context, r soap.RoundTripper, req *types.PbmFetchCapabilityMetadata) (*types.PbmFetchCapabilityMetadataResponse, error) {
var reqBody, resBody PbmFetchCapabilityMetadataBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmFetchCapabilitySchemaBody struct {
Req *types.PbmFetchCapabilitySchema `xml:"urn:pbm PbmFetchCapabilitySchema,omitempty"`
Res *types.PbmFetchCapabilitySchemaResponse `xml:"urn:pbm PbmFetchCapabilitySchemaResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmFetchCapabilitySchemaBody) Fault() *soap.Fault { return b.Fault_ }
func PbmFetchCapabilitySchema(ctx context.Context, r soap.RoundTripper, req *types.PbmFetchCapabilitySchema) (*types.PbmFetchCapabilitySchemaResponse, error) {
var reqBody, resBody PbmFetchCapabilitySchemaBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmFetchComplianceResultBody struct {
Req *types.PbmFetchComplianceResult `xml:"urn:pbm PbmFetchComplianceResult,omitempty"`
Res *types.PbmFetchComplianceResultResponse `xml:"urn:pbm PbmFetchComplianceResultResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmFetchComplianceResultBody) Fault() *soap.Fault { return b.Fault_ }
func PbmFetchComplianceResult(ctx context.Context, r soap.RoundTripper, req *types.PbmFetchComplianceResult) (*types.PbmFetchComplianceResultResponse, error) {
var reqBody, resBody PbmFetchComplianceResultBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmFetchResourceTypeBody struct {
Req *types.PbmFetchResourceType `xml:"urn:pbm PbmFetchResourceType,omitempty"`
Res *types.PbmFetchResourceTypeResponse `xml:"urn:pbm PbmFetchResourceTypeResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmFetchResourceTypeBody) Fault() *soap.Fault { return b.Fault_ }
func PbmFetchResourceType(ctx context.Context, r soap.RoundTripper, req *types.PbmFetchResourceType) (*types.PbmFetchResourceTypeResponse, error) {
var reqBody, resBody PbmFetchResourceTypeBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmFetchRollupComplianceResultBody struct {
Req *types.PbmFetchRollupComplianceResult `xml:"urn:pbm PbmFetchRollupComplianceResult,omitempty"`
Res *types.PbmFetchRollupComplianceResultResponse `xml:"urn:pbm PbmFetchRollupComplianceResultResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmFetchRollupComplianceResultBody) Fault() *soap.Fault { return b.Fault_ }
func PbmFetchRollupComplianceResult(ctx context.Context, r soap.RoundTripper, req *types.PbmFetchRollupComplianceResult) (*types.PbmFetchRollupComplianceResultResponse, error) {
var reqBody, resBody PbmFetchRollupComplianceResultBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmFetchVendorInfoBody struct {
Req *types.PbmFetchVendorInfo `xml:"urn:pbm PbmFetchVendorInfo,omitempty"`
Res *types.PbmFetchVendorInfoResponse `xml:"urn:pbm PbmFetchVendorInfoResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmFetchVendorInfoBody) Fault() *soap.Fault { return b.Fault_ }
func PbmFetchVendorInfo(ctx context.Context, r soap.RoundTripper, req *types.PbmFetchVendorInfo) (*types.PbmFetchVendorInfoResponse, error) {
var reqBody, resBody PbmFetchVendorInfoBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmFindApplicableDefaultProfileBody struct {
Req *types.PbmFindApplicableDefaultProfile `xml:"urn:pbm PbmFindApplicableDefaultProfile,omitempty"`
Res *types.PbmFindApplicableDefaultProfileResponse `xml:"urn:pbm PbmFindApplicableDefaultProfileResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmFindApplicableDefaultProfileBody) Fault() *soap.Fault { return b.Fault_ }
func PbmFindApplicableDefaultProfile(ctx context.Context, r soap.RoundTripper, req *types.PbmFindApplicableDefaultProfile) (*types.PbmFindApplicableDefaultProfileResponse, error) {
var reqBody, resBody PbmFindApplicableDefaultProfileBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmQueryAssociatedEntitiesBody struct {
Req *types.PbmQueryAssociatedEntities `xml:"urn:pbm PbmQueryAssociatedEntities,omitempty"`
Res *types.PbmQueryAssociatedEntitiesResponse `xml:"urn:pbm PbmQueryAssociatedEntitiesResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmQueryAssociatedEntitiesBody) Fault() *soap.Fault { return b.Fault_ }
func PbmQueryAssociatedEntities(ctx context.Context, r soap.RoundTripper, req *types.PbmQueryAssociatedEntities) (*types.PbmQueryAssociatedEntitiesResponse, error) {
var reqBody, resBody PbmQueryAssociatedEntitiesBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmQueryAssociatedEntityBody struct {
Req *types.PbmQueryAssociatedEntity `xml:"urn:pbm PbmQueryAssociatedEntity,omitempty"`
Res *types.PbmQueryAssociatedEntityResponse `xml:"urn:pbm PbmQueryAssociatedEntityResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmQueryAssociatedEntityBody) Fault() *soap.Fault { return b.Fault_ }
func PbmQueryAssociatedEntity(ctx context.Context, r soap.RoundTripper, req *types.PbmQueryAssociatedEntity) (*types.PbmQueryAssociatedEntityResponse, error) {
var reqBody, resBody PbmQueryAssociatedEntityBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmQueryAssociatedProfileBody struct {
Req *types.PbmQueryAssociatedProfile `xml:"urn:pbm PbmQueryAssociatedProfile,omitempty"`
Res *types.PbmQueryAssociatedProfileResponse `xml:"urn:pbm PbmQueryAssociatedProfileResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmQueryAssociatedProfileBody) Fault() *soap.Fault { return b.Fault_ }
func PbmQueryAssociatedProfile(ctx context.Context, r soap.RoundTripper, req *types.PbmQueryAssociatedProfile) (*types.PbmQueryAssociatedProfileResponse, error) {
var reqBody, resBody PbmQueryAssociatedProfileBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmQueryAssociatedProfilesBody struct {
Req *types.PbmQueryAssociatedProfiles `xml:"urn:pbm PbmQueryAssociatedProfiles,omitempty"`
Res *types.PbmQueryAssociatedProfilesResponse `xml:"urn:pbm PbmQueryAssociatedProfilesResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmQueryAssociatedProfilesBody) Fault() *soap.Fault { return b.Fault_ }
func PbmQueryAssociatedProfiles(ctx context.Context, r soap.RoundTripper, req *types.PbmQueryAssociatedProfiles) (*types.PbmQueryAssociatedProfilesResponse, error) {
var reqBody, resBody PbmQueryAssociatedProfilesBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmQueryByRollupComplianceStatusBody struct {
Req *types.PbmQueryByRollupComplianceStatus `xml:"urn:pbm PbmQueryByRollupComplianceStatus,omitempty"`
Res *types.PbmQueryByRollupComplianceStatusResponse `xml:"urn:pbm PbmQueryByRollupComplianceStatusResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmQueryByRollupComplianceStatusBody) Fault() *soap.Fault { return b.Fault_ }
func PbmQueryByRollupComplianceStatus(ctx context.Context, r soap.RoundTripper, req *types.PbmQueryByRollupComplianceStatus) (*types.PbmQueryByRollupComplianceStatusResponse, error) {
var reqBody, resBody PbmQueryByRollupComplianceStatusBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmQueryDefaultRequirementProfileBody struct {
Req *types.PbmQueryDefaultRequirementProfile `xml:"urn:pbm PbmQueryDefaultRequirementProfile,omitempty"`
Res *types.PbmQueryDefaultRequirementProfileResponse `xml:"urn:pbm PbmQueryDefaultRequirementProfileResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmQueryDefaultRequirementProfileBody) Fault() *soap.Fault { return b.Fault_ }
func PbmQueryDefaultRequirementProfile(ctx context.Context, r soap.RoundTripper, req *types.PbmQueryDefaultRequirementProfile) (*types.PbmQueryDefaultRequirementProfileResponse, error) {
var reqBody, resBody PbmQueryDefaultRequirementProfileBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmQueryDefaultRequirementProfilesBody struct {
Req *types.PbmQueryDefaultRequirementProfiles `xml:"urn:pbm PbmQueryDefaultRequirementProfiles,omitempty"`
Res *types.PbmQueryDefaultRequirementProfilesResponse `xml:"urn:pbm PbmQueryDefaultRequirementProfilesResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmQueryDefaultRequirementProfilesBody) Fault() *soap.Fault { return b.Fault_ }
func PbmQueryDefaultRequirementProfiles(ctx context.Context, r soap.RoundTripper, req *types.PbmQueryDefaultRequirementProfiles) (*types.PbmQueryDefaultRequirementProfilesResponse, error) {
var reqBody, resBody PbmQueryDefaultRequirementProfilesBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmQueryMatchingHubBody struct {
Req *types.PbmQueryMatchingHub `xml:"urn:pbm PbmQueryMatchingHub,omitempty"`
Res *types.PbmQueryMatchingHubResponse `xml:"urn:pbm PbmQueryMatchingHubResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmQueryMatchingHubBody) Fault() *soap.Fault { return b.Fault_ }
func PbmQueryMatchingHub(ctx context.Context, r soap.RoundTripper, req *types.PbmQueryMatchingHub) (*types.PbmQueryMatchingHubResponse, error) {
var reqBody, resBody PbmQueryMatchingHubBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmQueryMatchingHubWithSpecBody struct {
Req *types.PbmQueryMatchingHubWithSpec `xml:"urn:pbm PbmQueryMatchingHubWithSpec,omitempty"`
Res *types.PbmQueryMatchingHubWithSpecResponse `xml:"urn:pbm PbmQueryMatchingHubWithSpecResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmQueryMatchingHubWithSpecBody) Fault() *soap.Fault { return b.Fault_ }
func PbmQueryMatchingHubWithSpec(ctx context.Context, r soap.RoundTripper, req *types.PbmQueryMatchingHubWithSpec) (*types.PbmQueryMatchingHubWithSpecResponse, error) {
var reqBody, resBody PbmQueryMatchingHubWithSpecBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmQueryProfileBody struct {
Req *types.PbmQueryProfile `xml:"urn:pbm PbmQueryProfile,omitempty"`
Res *types.PbmQueryProfileResponse `xml:"urn:pbm PbmQueryProfileResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmQueryProfileBody) Fault() *soap.Fault { return b.Fault_ }
func PbmQueryProfile(ctx context.Context, r soap.RoundTripper, req *types.PbmQueryProfile) (*types.PbmQueryProfileResponse, error) {
var reqBody, resBody PbmQueryProfileBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmQueryReplicationGroupsBody struct {
Req *types.PbmQueryReplicationGroups `xml:"urn:pbm PbmQueryReplicationGroups,omitempty"`
Res *types.PbmQueryReplicationGroupsResponse `xml:"urn:pbm PbmQueryReplicationGroupsResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmQueryReplicationGroupsBody) Fault() *soap.Fault { return b.Fault_ }
func PbmQueryReplicationGroups(ctx context.Context, r soap.RoundTripper, req *types.PbmQueryReplicationGroups) (*types.PbmQueryReplicationGroupsResponse, error) {
var reqBody, resBody PbmQueryReplicationGroupsBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmQuerySpaceStatsForStorageContainerBody struct {
Req *types.PbmQuerySpaceStatsForStorageContainer `xml:"urn:pbm PbmQuerySpaceStatsForStorageContainer,omitempty"`
Res *types.PbmQuerySpaceStatsForStorageContainerResponse `xml:"urn:pbm PbmQuerySpaceStatsForStorageContainerResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmQuerySpaceStatsForStorageContainerBody) Fault() *soap.Fault { return b.Fault_ }
func PbmQuerySpaceStatsForStorageContainer(ctx context.Context, r soap.RoundTripper, req *types.PbmQuerySpaceStatsForStorageContainer) (*types.PbmQuerySpaceStatsForStorageContainerResponse, error) {
var reqBody, resBody PbmQuerySpaceStatsForStorageContainerBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmResetDefaultRequirementProfileBody struct {
Req *types.PbmResetDefaultRequirementProfile `xml:"urn:pbm PbmResetDefaultRequirementProfile,omitempty"`
Res *types.PbmResetDefaultRequirementProfileResponse `xml:"urn:pbm PbmResetDefaultRequirementProfileResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmResetDefaultRequirementProfileBody) Fault() *soap.Fault { return b.Fault_ }
func PbmResetDefaultRequirementProfile(ctx context.Context, r soap.RoundTripper, req *types.PbmResetDefaultRequirementProfile) (*types.PbmResetDefaultRequirementProfileResponse, error) {
var reqBody, resBody PbmResetDefaultRequirementProfileBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmResetVSanDefaultProfileBody struct {
Req *types.PbmResetVSanDefaultProfile `xml:"urn:pbm PbmResetVSanDefaultProfile,omitempty"`
Res *types.PbmResetVSanDefaultProfileResponse `xml:"urn:pbm PbmResetVSanDefaultProfileResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmResetVSanDefaultProfileBody) Fault() *soap.Fault { return b.Fault_ }
func PbmResetVSanDefaultProfile(ctx context.Context, r soap.RoundTripper, req *types.PbmResetVSanDefaultProfile) (*types.PbmResetVSanDefaultProfileResponse, error) {
var reqBody, resBody PbmResetVSanDefaultProfileBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmRetrieveContentBody struct {
Req *types.PbmRetrieveContent `xml:"urn:pbm PbmRetrieveContent,omitempty"`
Res *types.PbmRetrieveContentResponse `xml:"urn:pbm PbmRetrieveContentResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmRetrieveContentBody) Fault() *soap.Fault { return b.Fault_ }
func PbmRetrieveContent(ctx context.Context, r soap.RoundTripper, req *types.PbmRetrieveContent) (*types.PbmRetrieveContentResponse, error) {
var reqBody, resBody PbmRetrieveContentBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmRetrieveServiceContentBody struct {
Req *types.PbmRetrieveServiceContent `xml:"urn:pbm PbmRetrieveServiceContent,omitempty"`
Res *types.PbmRetrieveServiceContentResponse `xml:"urn:pbm PbmRetrieveServiceContentResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmRetrieveServiceContentBody) Fault() *soap.Fault { return b.Fault_ }
func PbmRetrieveServiceContent(ctx context.Context, r soap.RoundTripper, req *types.PbmRetrieveServiceContent) (*types.PbmRetrieveServiceContentResponse, error) {
var reqBody, resBody PbmRetrieveServiceContentBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type PbmUpdateBody struct {
Req *types.PbmUpdate `xml:"urn:pbm PbmUpdate,omitempty"`
Res *types.PbmUpdateResponse `xml:"urn:pbm PbmUpdateResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *PbmUpdateBody) Fault() *soap.Fault { return b.Fault_ }
func PbmUpdate(ctx context.Context, r soap.RoundTripper, req *types.PbmUpdate) (*types.PbmUpdateResponse, error) {
var reqBody, resBody PbmUpdateBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}

View File

@@ -1,148 +0,0 @@
/*
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.
*/
package pbm
import (
"fmt"
"strconv"
"strings"
"github.com/vmware/govmomi/pbm/types"
)
// A struct to capture pbm create spec details.
type CapabilityProfileCreateSpec struct {
Name string
SubProfileName string
Description string
Category string
CapabilityList []Capability
}
// A struct to capture pbm capability instance details.
type Capability struct {
ID string
Namespace string
PropertyList []Property
}
// A struct to capture pbm property instance details.
type Property struct {
ID string
Operator string
Value string
DataType string
}
func CreateCapabilityProfileSpec(pbmCreateSpec CapabilityProfileCreateSpec) (*types.PbmCapabilityProfileCreateSpec, error) {
capabilities, err := createCapabilityInstances(pbmCreateSpec.CapabilityList)
if err != nil {
return nil, err
}
pbmCapabilityProfileSpec := types.PbmCapabilityProfileCreateSpec{
Name: pbmCreateSpec.Name,
Description: pbmCreateSpec.Description,
Category: pbmCreateSpec.Category,
ResourceType: types.PbmProfileResourceType{
ResourceType: string(types.PbmProfileResourceTypeEnumSTORAGE),
},
Constraints: &types.PbmCapabilitySubProfileConstraints{
SubProfiles: []types.PbmCapabilitySubProfile{
types.PbmCapabilitySubProfile{
Capability: capabilities,
Name: pbmCreateSpec.SubProfileName,
},
},
},
}
return &pbmCapabilityProfileSpec, nil
}
func createCapabilityInstances(rules []Capability) ([]types.PbmCapabilityInstance, error) {
var capabilityInstances []types.PbmCapabilityInstance
for _, capabilityRule := range rules {
capability := types.PbmCapabilityInstance{
Id: types.PbmCapabilityMetadataUniqueId{
Namespace: capabilityRule.Namespace,
Id: capabilityRule.ID,
},
}
var propertyInstances []types.PbmCapabilityPropertyInstance
for _, propertyRule := range capabilityRule.PropertyList {
property := types.PbmCapabilityPropertyInstance{
Id: propertyRule.ID,
}
if propertyRule.Operator != "" {
property.Operator = propertyRule.Operator
}
var err error
switch strings.ToLower(propertyRule.DataType) {
case "int":
// Go int32 is marshalled to xsi:int whereas Go int is marshalled to xsi:long when sending down the wire.
var val int32
val, err = verifyPropertyValueIsInt(propertyRule.Value, propertyRule.DataType)
property.Value = val
case "bool":
var val bool
val, err = verifyPropertyValueIsBoolean(propertyRule.Value, propertyRule.DataType)
property.Value = val
case "string":
property.Value = propertyRule.Value
case "set":
set := types.PbmCapabilityDiscreteSet{}
for _, val := range strings.Split(propertyRule.Value, ",") {
set.Values = append(set.Values, val)
}
property.Value = set
default:
return nil, fmt.Errorf("invalid value: %q with datatype: %q", propertyRule.Value, propertyRule.Value)
}
if err != nil {
return nil, fmt.Errorf("invalid value: %q with datatype: %q", propertyRule.Value, propertyRule.Value)
}
propertyInstances = append(propertyInstances, property)
}
constraintInstances := []types.PbmCapabilityConstraintInstance{
types.PbmCapabilityConstraintInstance{
PropertyInstance: propertyInstances,
},
}
capability.Constraint = constraintInstances
capabilityInstances = append(capabilityInstances, capability)
}
return capabilityInstances, nil
}
// Verify if the capability value is of type integer.
func verifyPropertyValueIsInt(propertyValue string, dataType string) (int32, error) {
val, err := strconv.ParseInt(propertyValue, 10, 32)
if err != nil {
return -1, err
}
return int32(val), nil
}
// Verify if the capability value is of type integer.
func verifyPropertyValueIsBoolean(propertyValue string, dataType string) (bool, error) {
val, err := strconv.ParseBool(propertyValue)
if err != nil {
return false, err
}
return val, nil
}

View File

@@ -1,307 +0,0 @@
/*
Copyright (c) 2014-2022 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.
*/
package types
import (
"reflect"
"github.com/vmware/govmomi/vim25/types"
)
type PbmAssociateAndApplyPolicyStatusPolicyStatus string
const (
PbmAssociateAndApplyPolicyStatusPolicyStatusSuccess = PbmAssociateAndApplyPolicyStatusPolicyStatus("success")
PbmAssociateAndApplyPolicyStatusPolicyStatusFailed = PbmAssociateAndApplyPolicyStatusPolicyStatus("failed")
PbmAssociateAndApplyPolicyStatusPolicyStatusInvalid = PbmAssociateAndApplyPolicyStatusPolicyStatus("invalid")
)
func init() {
types.Add("pbm:PbmAssociateAndApplyPolicyStatusPolicyStatus", reflect.TypeOf((*PbmAssociateAndApplyPolicyStatusPolicyStatus)(nil)).Elem())
}
type PbmBuiltinGenericType string
const (
PbmBuiltinGenericTypeVMW_RANGE = PbmBuiltinGenericType("VMW_RANGE")
PbmBuiltinGenericTypeVMW_SET = PbmBuiltinGenericType("VMW_SET")
)
func init() {
types.Add("pbm:PbmBuiltinGenericType", reflect.TypeOf((*PbmBuiltinGenericType)(nil)).Elem())
}
type PbmBuiltinType string
const (
PbmBuiltinTypeXSD_LONG = PbmBuiltinType("XSD_LONG")
PbmBuiltinTypeXSD_SHORT = PbmBuiltinType("XSD_SHORT")
PbmBuiltinTypeXSD_INTEGER = PbmBuiltinType("XSD_INTEGER")
PbmBuiltinTypeXSD_INT = PbmBuiltinType("XSD_INT")
PbmBuiltinTypeXSD_STRING = PbmBuiltinType("XSD_STRING")
PbmBuiltinTypeXSD_BOOLEAN = PbmBuiltinType("XSD_BOOLEAN")
PbmBuiltinTypeXSD_DOUBLE = PbmBuiltinType("XSD_DOUBLE")
PbmBuiltinTypeXSD_DATETIME = PbmBuiltinType("XSD_DATETIME")
PbmBuiltinTypeVMW_TIMESPAN = PbmBuiltinType("VMW_TIMESPAN")
PbmBuiltinTypeVMW_POLICY = PbmBuiltinType("VMW_POLICY")
)
func init() {
types.Add("pbm:PbmBuiltinType", reflect.TypeOf((*PbmBuiltinType)(nil)).Elem())
}
type PbmCapabilityOperator string
const (
PbmCapabilityOperatorNOT = PbmCapabilityOperator("NOT")
)
func init() {
types.Add("pbm:PbmCapabilityOperator", reflect.TypeOf((*PbmCapabilityOperator)(nil)).Elem())
}
type PbmCapabilityTimeUnitType string
const (
PbmCapabilityTimeUnitTypeSECONDS = PbmCapabilityTimeUnitType("SECONDS")
PbmCapabilityTimeUnitTypeMINUTES = PbmCapabilityTimeUnitType("MINUTES")
PbmCapabilityTimeUnitTypeHOURS = PbmCapabilityTimeUnitType("HOURS")
PbmCapabilityTimeUnitTypeDAYS = PbmCapabilityTimeUnitType("DAYS")
PbmCapabilityTimeUnitTypeWEEKS = PbmCapabilityTimeUnitType("WEEKS")
PbmCapabilityTimeUnitTypeMONTHS = PbmCapabilityTimeUnitType("MONTHS")
PbmCapabilityTimeUnitTypeYEARS = PbmCapabilityTimeUnitType("YEARS")
)
func init() {
types.Add("pbm:PbmCapabilityTimeUnitType", reflect.TypeOf((*PbmCapabilityTimeUnitType)(nil)).Elem())
}
type PbmComplianceResultComplianceTaskStatus string
const (
PbmComplianceResultComplianceTaskStatusInProgress = PbmComplianceResultComplianceTaskStatus("inProgress")
PbmComplianceResultComplianceTaskStatusSuccess = PbmComplianceResultComplianceTaskStatus("success")
PbmComplianceResultComplianceTaskStatusFailed = PbmComplianceResultComplianceTaskStatus("failed")
)
func init() {
types.Add("pbm:PbmComplianceResultComplianceTaskStatus", reflect.TypeOf((*PbmComplianceResultComplianceTaskStatus)(nil)).Elem())
}
type PbmComplianceStatus string
const (
PbmComplianceStatusCompliant = PbmComplianceStatus("compliant")
PbmComplianceStatusNonCompliant = PbmComplianceStatus("nonCompliant")
PbmComplianceStatusUnknown = PbmComplianceStatus("unknown")
PbmComplianceStatusNotApplicable = PbmComplianceStatus("notApplicable")
PbmComplianceStatusOutOfDate = PbmComplianceStatus("outOfDate")
)
func init() {
types.Add("pbm:PbmComplianceStatus", reflect.TypeOf((*PbmComplianceStatus)(nil)).Elem())
}
type PbmDebugManagerKeystoreName string
const (
PbmDebugManagerKeystoreNameSMS = PbmDebugManagerKeystoreName("SMS")
PbmDebugManagerKeystoreNameTRUSTED_ROOTS = PbmDebugManagerKeystoreName("TRUSTED_ROOTS")
)
func init() {
types.Add("pbm:PbmDebugManagerKeystoreName", reflect.TypeOf((*PbmDebugManagerKeystoreName)(nil)).Elem())
}
type PbmHealthStatusForEntity string
const (
PbmHealthStatusForEntityRed = PbmHealthStatusForEntity("red")
PbmHealthStatusForEntityYellow = PbmHealthStatusForEntity("yellow")
PbmHealthStatusForEntityGreen = PbmHealthStatusForEntity("green")
PbmHealthStatusForEntityUnknown = PbmHealthStatusForEntity("unknown")
)
func init() {
types.Add("pbm:PbmHealthStatusForEntity", reflect.TypeOf((*PbmHealthStatusForEntity)(nil)).Elem())
}
type PbmIofilterInfoFilterType string
const (
PbmIofilterInfoFilterTypeINSPECTION = PbmIofilterInfoFilterType("INSPECTION")
PbmIofilterInfoFilterTypeCOMPRESSION = PbmIofilterInfoFilterType("COMPRESSION")
PbmIofilterInfoFilterTypeENCRYPTION = PbmIofilterInfoFilterType("ENCRYPTION")
PbmIofilterInfoFilterTypeREPLICATION = PbmIofilterInfoFilterType("REPLICATION")
PbmIofilterInfoFilterTypeCACHE = PbmIofilterInfoFilterType("CACHE")
PbmIofilterInfoFilterTypeDATAPROVIDER = PbmIofilterInfoFilterType("DATAPROVIDER")
PbmIofilterInfoFilterTypeDATASTOREIOCONTROL = PbmIofilterInfoFilterType("DATASTOREIOCONTROL")
)
func init() {
types.Add("pbm:PbmIofilterInfoFilterType", reflect.TypeOf((*PbmIofilterInfoFilterType)(nil)).Elem())
}
type PbmLineOfServiceInfoLineOfServiceEnum string
const (
PbmLineOfServiceInfoLineOfServiceEnumINSPECTION = PbmLineOfServiceInfoLineOfServiceEnum("INSPECTION")
PbmLineOfServiceInfoLineOfServiceEnumCOMPRESSION = PbmLineOfServiceInfoLineOfServiceEnum("COMPRESSION")
PbmLineOfServiceInfoLineOfServiceEnumENCRYPTION = PbmLineOfServiceInfoLineOfServiceEnum("ENCRYPTION")
PbmLineOfServiceInfoLineOfServiceEnumREPLICATION = PbmLineOfServiceInfoLineOfServiceEnum("REPLICATION")
PbmLineOfServiceInfoLineOfServiceEnumCACHING = PbmLineOfServiceInfoLineOfServiceEnum("CACHING")
PbmLineOfServiceInfoLineOfServiceEnumPERSISTENCE = PbmLineOfServiceInfoLineOfServiceEnum("PERSISTENCE")
PbmLineOfServiceInfoLineOfServiceEnumDATA_PROVIDER = PbmLineOfServiceInfoLineOfServiceEnum("DATA_PROVIDER")
PbmLineOfServiceInfoLineOfServiceEnumDATASTORE_IO_CONTROL = PbmLineOfServiceInfoLineOfServiceEnum("DATASTORE_IO_CONTROL")
PbmLineOfServiceInfoLineOfServiceEnumDATA_PROTECTION = PbmLineOfServiceInfoLineOfServiceEnum("DATA_PROTECTION")
)
func init() {
types.Add("pbm:PbmLineOfServiceInfoLineOfServiceEnum", reflect.TypeOf((*PbmLineOfServiceInfoLineOfServiceEnum)(nil)).Elem())
}
type PbmLoggingConfigurationComponent string
const (
PbmLoggingConfigurationComponentPbm = PbmLoggingConfigurationComponent("pbm")
PbmLoggingConfigurationComponentVslm = PbmLoggingConfigurationComponent("vslm")
PbmLoggingConfigurationComponentSms = PbmLoggingConfigurationComponent("sms")
PbmLoggingConfigurationComponentSpbm = PbmLoggingConfigurationComponent("spbm")
PbmLoggingConfigurationComponentSps = PbmLoggingConfigurationComponent("sps")
PbmLoggingConfigurationComponentHttpclient_header = PbmLoggingConfigurationComponent("httpclient_header")
PbmLoggingConfigurationComponentHttpclient_content = PbmLoggingConfigurationComponent("httpclient_content")
PbmLoggingConfigurationComponentVmomi = PbmLoggingConfigurationComponent("vmomi")
)
func init() {
types.Add("pbm:PbmLoggingConfigurationComponent", reflect.TypeOf((*PbmLoggingConfigurationComponent)(nil)).Elem())
}
type PbmLoggingConfigurationLogLevel string
const (
PbmLoggingConfigurationLogLevelINFO = PbmLoggingConfigurationLogLevel("INFO")
PbmLoggingConfigurationLogLevelDEBUG = PbmLoggingConfigurationLogLevel("DEBUG")
PbmLoggingConfigurationLogLevelTRACE = PbmLoggingConfigurationLogLevel("TRACE")
)
func init() {
types.Add("pbm:PbmLoggingConfigurationLogLevel", reflect.TypeOf((*PbmLoggingConfigurationLogLevel)(nil)).Elem())
}
type PbmObjectType string
const (
PbmObjectTypeVirtualMachine = PbmObjectType("virtualMachine")
PbmObjectTypeVirtualMachineAndDisks = PbmObjectType("virtualMachineAndDisks")
PbmObjectTypeVirtualDiskId = PbmObjectType("virtualDiskId")
PbmObjectTypeVirtualDiskUUID = PbmObjectType("virtualDiskUUID")
PbmObjectTypeDatastore = PbmObjectType("datastore")
PbmObjectTypeVsanObjectId = PbmObjectType("vsanObjectId")
PbmObjectTypeFileShareId = PbmObjectType("fileShareId")
PbmObjectTypeUnknown = PbmObjectType("unknown")
)
func init() {
types.Add("pbm:PbmObjectType", reflect.TypeOf((*PbmObjectType)(nil)).Elem())
}
type PbmOperation string
const (
PbmOperationCREATE = PbmOperation("CREATE")
PbmOperationREGISTER = PbmOperation("REGISTER")
PbmOperationRECONFIGURE = PbmOperation("RECONFIGURE")
PbmOperationMIGRATE = PbmOperation("MIGRATE")
PbmOperationCLONE = PbmOperation("CLONE")
)
func init() {
types.Add("pbm:PbmOperation", reflect.TypeOf((*PbmOperation)(nil)).Elem())
}
type PbmPolicyAssociationVolumeAllocationType string
const (
PbmPolicyAssociationVolumeAllocationTypeFullyInitialized = PbmPolicyAssociationVolumeAllocationType("FullyInitialized")
PbmPolicyAssociationVolumeAllocationTypeReserveSpace = PbmPolicyAssociationVolumeAllocationType("ReserveSpace")
PbmPolicyAssociationVolumeAllocationTypeConserveSpaceWhenPossible = PbmPolicyAssociationVolumeAllocationType("ConserveSpaceWhenPossible")
)
func init() {
types.Add("pbm:PbmPolicyAssociationVolumeAllocationType", reflect.TypeOf((*PbmPolicyAssociationVolumeAllocationType)(nil)).Elem())
}
type PbmProfileCategoryEnum string
const (
PbmProfileCategoryEnumREQUIREMENT = PbmProfileCategoryEnum("REQUIREMENT")
PbmProfileCategoryEnumRESOURCE = PbmProfileCategoryEnum("RESOURCE")
PbmProfileCategoryEnumDATA_SERVICE_POLICY = PbmProfileCategoryEnum("DATA_SERVICE_POLICY")
)
func init() {
types.Add("pbm:PbmProfileCategoryEnum", reflect.TypeOf((*PbmProfileCategoryEnum)(nil)).Elem())
}
type PbmProfileResourceTypeEnum string
const (
PbmProfileResourceTypeEnumSTORAGE = PbmProfileResourceTypeEnum("STORAGE")
)
func init() {
types.Add("pbm:PbmProfileResourceTypeEnum", reflect.TypeOf((*PbmProfileResourceTypeEnum)(nil)).Elem())
}
type PbmSystemCreatedProfileType string
const (
PbmSystemCreatedProfileTypeVsanDefaultProfile = PbmSystemCreatedProfileType("VsanDefaultProfile")
PbmSystemCreatedProfileTypeVVolDefaultProfile = PbmSystemCreatedProfileType("VVolDefaultProfile")
PbmSystemCreatedProfileTypePmemDefaultProfile = PbmSystemCreatedProfileType("PmemDefaultProfile")
PbmSystemCreatedProfileTypeVsanMaxDefaultProfile = PbmSystemCreatedProfileType("VsanMaxDefaultProfile")
)
func init() {
types.Add("pbm:PbmSystemCreatedProfileType", reflect.TypeOf((*PbmSystemCreatedProfileType)(nil)).Elem())
}
type PbmVmOperation string
const (
PbmVmOperationCREATE = PbmVmOperation("CREATE")
PbmVmOperationRECONFIGURE = PbmVmOperation("RECONFIGURE")
PbmVmOperationMIGRATE = PbmVmOperation("MIGRATE")
PbmVmOperationCLONE = PbmVmOperation("CLONE")
)
func init() {
types.Add("pbm:PbmVmOperation", reflect.TypeOf((*PbmVmOperation)(nil)).Elem())
}
type PbmVvolType string
const (
PbmVvolTypeConfig = PbmVvolType("Config")
PbmVvolTypeData = PbmVvolType("Data")
PbmVvolTypeSwap = PbmVvolType("Swap")
)
func init() {
types.Add("pbm:PbmVvolType", reflect.TypeOf((*PbmVvolType)(nil)).Elem())
}

View File

@@ -1,139 +0,0 @@
/*
Copyright (c) 2014-2022 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.
*/
package types
import (
"reflect"
"github.com/vmware/govmomi/vim25/types"
)
func (b *PbmCapabilityConstraints) GetPbmCapabilityConstraints() *PbmCapabilityConstraints { return b }
type BasePbmCapabilityConstraints interface {
GetPbmCapabilityConstraints() *PbmCapabilityConstraints
}
func init() {
types.Add("BasePbmCapabilityConstraints", reflect.TypeOf((*PbmCapabilityConstraints)(nil)).Elem())
}
func (b *PbmCapabilityProfile) GetPbmCapabilityProfile() *PbmCapabilityProfile { return b }
type BasePbmCapabilityProfile interface {
GetPbmCapabilityProfile() *PbmCapabilityProfile
}
func init() {
types.Add("BasePbmCapabilityProfile", reflect.TypeOf((*PbmCapabilityProfile)(nil)).Elem())
}
func (b *PbmCapabilityProfilePropertyMismatchFault) GetPbmCapabilityProfilePropertyMismatchFault() *PbmCapabilityProfilePropertyMismatchFault {
return b
}
type BasePbmCapabilityProfilePropertyMismatchFault interface {
GetPbmCapabilityProfilePropertyMismatchFault() *PbmCapabilityProfilePropertyMismatchFault
}
func init() {
types.Add("BasePbmCapabilityProfilePropertyMismatchFault", reflect.TypeOf((*PbmCapabilityProfilePropertyMismatchFault)(nil)).Elem())
}
func (b *PbmCapabilityTypeInfo) GetPbmCapabilityTypeInfo() *PbmCapabilityTypeInfo { return b }
type BasePbmCapabilityTypeInfo interface {
GetPbmCapabilityTypeInfo() *PbmCapabilityTypeInfo
}
func init() {
types.Add("BasePbmCapabilityTypeInfo", reflect.TypeOf((*PbmCapabilityTypeInfo)(nil)).Elem())
}
func (b *PbmCompatibilityCheckFault) GetPbmCompatibilityCheckFault() *PbmCompatibilityCheckFault {
return b
}
type BasePbmCompatibilityCheckFault interface {
GetPbmCompatibilityCheckFault() *PbmCompatibilityCheckFault
}
func init() {
types.Add("BasePbmCompatibilityCheckFault", reflect.TypeOf((*PbmCompatibilityCheckFault)(nil)).Elem())
}
func (b *PbmFault) GetPbmFault() *PbmFault { return b }
type BasePbmFault interface {
GetPbmFault() *PbmFault
}
func init() {
types.Add("BasePbmFault", reflect.TypeOf((*PbmFault)(nil)).Elem())
}
func (b *PbmLineOfServiceInfo) GetPbmLineOfServiceInfo() *PbmLineOfServiceInfo { return b }
type BasePbmLineOfServiceInfo interface {
GetPbmLineOfServiceInfo() *PbmLineOfServiceInfo
}
func init() {
types.Add("BasePbmLineOfServiceInfo", reflect.TypeOf((*PbmLineOfServiceInfo)(nil)).Elem())
}
func (b *PbmPlacementMatchingResources) GetPbmPlacementMatchingResources() *PbmPlacementMatchingResources {
return b
}
type BasePbmPlacementMatchingResources interface {
GetPbmPlacementMatchingResources() *PbmPlacementMatchingResources
}
func init() {
types.Add("BasePbmPlacementMatchingResources", reflect.TypeOf((*PbmPlacementMatchingResources)(nil)).Elem())
}
func (b *PbmPlacementRequirement) GetPbmPlacementRequirement() *PbmPlacementRequirement { return b }
type BasePbmPlacementRequirement interface {
GetPbmPlacementRequirement() *PbmPlacementRequirement
}
func init() {
types.Add("BasePbmPlacementRequirement", reflect.TypeOf((*PbmPlacementRequirement)(nil)).Elem())
}
func (b *PbmProfile) GetPbmProfile() *PbmProfile { return b }
type BasePbmProfile interface {
GetPbmProfile() *PbmProfile
}
func init() {
types.Add("BasePbmProfile", reflect.TypeOf((*PbmProfile)(nil)).Elem())
}
func (b *PbmPropertyMismatchFault) GetPbmPropertyMismatchFault() *PbmPropertyMismatchFault { return b }
type BasePbmPropertyMismatchFault interface {
GetPbmPropertyMismatchFault() *PbmPropertyMismatchFault
}
func init() {
types.Add("BasePbmPropertyMismatchFault", reflect.TypeOf((*PbmPropertyMismatchFault)(nil)).Elem())
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,51 +0,0 @@
# Copyright (c) 2021 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
ifneq (,$(strip $(GOOS)))
ifeq (,$(strip $(GOARCH)))
GOARCH := $(shell go env | grep GOARCH | awk -F= '{print $$2}' | tr -d '"')
endif
endif
ifneq (,$(strip $(GOARCH)))
ifeq (,$(strip $(GOOS)))
GOOS := $(shell go env | grep GOOS | awk -F= '{print $$2}' | tr -d '"')
endif
endif
ifeq (2,$(words $(GOOS) $(GOARCH)))
PROGRAM := $(PROGRAM)_$(GOOS)_$(GOARCH)
endif
ifeq (windows,$(GOOS))
PROGRAM := $(PROGRAM).exe
endif
all: $(PROGRAM)
TAGS += netgo
ifeq (,$(strip $(findstring -w,$(LDFLAGS))))
LDFLAGS += -w
endif
BUILD_ARGS := -tags '$(TAGS)' -ldflags '$(LDFLAGS)' -v
$(PROGRAM):
CGO_ENABLED=0 go build -a $(BUILD_ARGS) -o $@
install:
CGO_ENABLED=0 go install -v $(BUILD_ARGS)
ifneq (,$(strip $(BUILD_OS)))
ifneq (,$(strip $(BUILD_ARCH)))
GOOS_GOARCH_TARGETS := $(foreach a,$(BUILD_ARCH),$(patsubst %,%_$a,$(BUILD_OS)))
XBUILD := $(addprefix $(PROGRAM)_,$(GOOS_GOARCH_TARGETS))
$(XBUILD):
GOOS=$(word 2,$(subst _, ,$@)) GOARCH=$(word 3,$(subst _, ,$@)) $(MAKE) --output-sync=target
build-all: $(XBUILD)
endif
endif
clean:
@rm -f $(PROGRAM) $(XBUILD)
.PHONY: build-all install clean

View File

@@ -1,217 +0,0 @@
/*
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.
*/
package property
import (
"context"
"errors"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
// Collector models the PropertyCollector managed object.
//
// For more information, see:
// http://pubs.vmware.com/vsphere-60/index.jsp?topic=%2Fcom.vmware.wssdk.apiref.doc%2Fvmodl.query.PropertyCollector.html
//
type Collector struct {
roundTripper soap.RoundTripper
reference types.ManagedObjectReference
}
// DefaultCollector returns the session's default property collector.
func DefaultCollector(c *vim25.Client) *Collector {
p := Collector{
roundTripper: c,
reference: c.ServiceContent.PropertyCollector,
}
return &p
}
func (p Collector) Reference() types.ManagedObjectReference {
return p.reference
}
// Create creates a new session-specific Collector that can be used to
// retrieve property updates independent of any other Collector.
func (p *Collector) Create(ctx context.Context) (*Collector, error) {
req := types.CreatePropertyCollector{
This: p.Reference(),
}
res, err := methods.CreatePropertyCollector(ctx, p.roundTripper, &req)
if err != nil {
return nil, err
}
newp := Collector{
roundTripper: p.roundTripper,
reference: res.Returnval,
}
return &newp, nil
}
// Destroy destroys this Collector.
func (p *Collector) Destroy(ctx context.Context) error {
req := types.DestroyPropertyCollector{
This: p.Reference(),
}
_, err := methods.DestroyPropertyCollector(ctx, p.roundTripper, &req)
if err != nil {
return err
}
p.reference = types.ManagedObjectReference{}
return nil
}
func (p *Collector) CreateFilter(ctx context.Context, req types.CreateFilter) error {
req.This = p.Reference()
_, err := methods.CreateFilter(ctx, p.roundTripper, &req)
if err != nil {
return err
}
return nil
}
func (p *Collector) WaitForUpdates(ctx context.Context, version string, opts ...*types.WaitOptions) (*types.UpdateSet, error) {
req := types.WaitForUpdatesEx{
This: p.Reference(),
Version: version,
}
if len(opts) == 1 {
req.Options = opts[0]
} else if len(opts) > 1 {
panic("only one option may be specified")
}
res, err := methods.WaitForUpdatesEx(ctx, p.roundTripper, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (p *Collector) CancelWaitForUpdates(ctx context.Context) error {
req := &types.CancelWaitForUpdates{This: p.Reference()}
_, err := methods.CancelWaitForUpdates(ctx, p.roundTripper, req)
return err
}
func (p *Collector) RetrieveProperties(ctx context.Context, req types.RetrieveProperties) (*types.RetrievePropertiesResponse, error) {
req.This = p.Reference()
return methods.RetrieveProperties(ctx, p.roundTripper, &req)
}
// Retrieve loads properties for a slice of managed objects. The dst argument
// must be a pointer to a []interface{}, which is populated with the instances
// of the specified managed objects, with the relevant properties filled in. If
// the properties slice is nil, all properties are loaded.
// Note that pointer types are optional fields that may be left as a nil value.
// The caller should check such fields for a nil value before dereferencing.
func (p *Collector) Retrieve(ctx context.Context, objs []types.ManagedObjectReference, ps []string, dst interface{}) error {
if len(objs) == 0 {
return errors.New("object references is empty")
}
kinds := make(map[string]bool)
var propSet []types.PropertySpec
var objectSet []types.ObjectSpec
for _, obj := range objs {
if _, ok := kinds[obj.Type]; !ok {
spec := types.PropertySpec{
Type: obj.Type,
}
if len(ps) == 0 {
spec.All = types.NewBool(true)
} else {
spec.PathSet = ps
}
propSet = append(propSet, spec)
kinds[obj.Type] = true
}
objectSpec := types.ObjectSpec{
Obj: obj,
Skip: types.NewBool(false),
}
objectSet = append(objectSet, objectSpec)
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: objectSet,
PropSet: propSet,
},
},
}
res, err := p.RetrieveProperties(ctx, req)
if err != nil {
return err
}
if d, ok := dst.(*[]types.ObjectContent); ok {
*d = res.Returnval
return nil
}
return mo.LoadObjectContent(res.Returnval, dst)
}
// RetrieveWithFilter populates dst as Retrieve does, but only for entities matching the given filter.
func (p *Collector) RetrieveWithFilter(ctx context.Context, objs []types.ManagedObjectReference, ps []string, dst interface{}, filter Filter) error {
if len(filter) == 0 {
return p.Retrieve(ctx, objs, ps, dst)
}
var content []types.ObjectContent
err := p.Retrieve(ctx, objs, filter.Keys(), &content)
if err != nil {
return err
}
objs = filter.MatchObjectContent(content)
if len(objs) == 0 {
return nil
}
return p.Retrieve(ctx, objs, ps, dst)
}
// RetrieveOne calls Retrieve with a single managed object reference via Collector.Retrieve().
func (p *Collector) RetrieveOne(ctx context.Context, obj types.ManagedObjectReference, ps []string, dst interface{}) error {
var objs = []types.ManagedObjectReference{obj}
return p.Retrieve(ctx, objs, ps, dst)
}

View File

@@ -1,168 +0,0 @@
/*
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.
*/
package property
import (
"fmt"
"path"
"reflect"
"strconv"
"strings"
"github.com/vmware/govmomi/vim25/types"
)
// Filter provides methods for matching against types.DynamicProperty
type Filter map[string]types.AnyType
// Keys returns the Filter map keys as a []string
func (f Filter) Keys() []string {
keys := make([]string, 0, len(f))
for key := range f {
keys = append(keys, key)
}
return keys
}
// MatchProperty returns true if a Filter entry matches the given prop.
func (f Filter) MatchProperty(prop types.DynamicProperty) bool {
if prop.Val == nil {
return false
}
match, ok := f[prop.Name]
if !ok {
return false
}
if match == prop.Val {
return true
}
ptype := reflect.TypeOf(prop.Val)
if strings.HasPrefix(ptype.Name(), "ArrayOf") {
pval := reflect.ValueOf(prop.Val).Field(0)
for i := 0; i < pval.Len(); i++ {
prop.Val = pval.Index(i).Interface()
if f.MatchProperty(prop) {
return true
}
}
return false
}
if reflect.TypeOf(match) != ptype {
s, ok := match.(string)
if !ok {
return false
}
// convert if we can
switch val := prop.Val.(type) {
case bool:
match, _ = strconv.ParseBool(s)
case int16:
x, _ := strconv.ParseInt(s, 10, 16)
match = int16(x)
case int32:
x, _ := strconv.ParseInt(s, 10, 32)
match = int32(x)
case int64:
match, _ = strconv.ParseInt(s, 10, 64)
case float32:
x, _ := strconv.ParseFloat(s, 32)
match = float32(x)
case float64:
match, _ = strconv.ParseFloat(s, 64)
case fmt.Stringer:
prop.Val = val.String()
case *types.CustomFieldStringValue:
prop.Val = fmt.Sprintf("%d:%s", val.Key, val.Value)
default:
if ptype.Kind() != reflect.String {
return false
}
// An enum type we can convert to a string type
prop.Val = reflect.ValueOf(prop.Val).String()
}
}
switch pval := prop.Val.(type) {
case string:
s := match.(string)
if s == "*" {
return true // TODO: path.Match fails if s contains a '/'
}
m, _ := path.Match(s, pval)
return m
default:
return reflect.DeepEqual(match, pval)
}
}
// MatchPropertyList returns true if all given props match the Filter.
func (f Filter) MatchPropertyList(props []types.DynamicProperty) bool {
for _, p := range props {
if !f.MatchProperty(p) {
return false
}
}
return len(f) == len(props) // false if a property such as VM "guest" is unset
}
// MatchObjectContent returns a list of ObjectContent.Obj where the ObjectContent.PropSet matches all properties the Filter.
func (f Filter) MatchObjectContent(objects []types.ObjectContent) []types.ManagedObjectReference {
var refs []types.ManagedObjectReference
for _, o := range objects {
if f.MatchPropertyList(o.PropSet) {
refs = append(refs, o.Obj)
}
}
return refs
}
// MatchAnyPropertyList returns true if any given props match the Filter.
func (f Filter) MatchAnyPropertyList(props []types.DynamicProperty) bool {
for _, p := range props {
if f.MatchProperty(p) {
return true
}
}
return false
}
// MatchAnyObjectContent returns a list of ObjectContent.Obj where the ObjectContent.PropSet matches any property in the Filter.
func (f Filter) MatchAnyObjectContent(objects []types.ObjectContent) []types.ManagedObjectReference {
var refs []types.ManagedObjectReference
for _, o := range objects {
if f.MatchAnyPropertyList(o.PropSet) {
refs = append(refs, o.Obj)
}
}
return refs
}

Some files were not shown because too many files have changed in this diff Show More